mirror of
https://github.com/LukeHagar/vercel.git
synced 2025-12-11 04:22:13 +00:00
Compare commits
27 Commits
@vercel/bu
...
@vercel/py
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf827a8b91 | ||
|
|
bed83e829c | ||
|
|
0f0ee4e845 | ||
|
|
2d70c6c811 | ||
|
|
887309f0a5 | ||
|
|
8a7657c80b | ||
|
|
279d0bf988 | ||
|
|
d2b31d03da | ||
|
|
16acf906fc | ||
|
|
0127d17703 | ||
|
|
0bfc2a3693 | ||
|
|
b9809b140c | ||
|
|
faaccc1f9f | ||
|
|
4b61f1dd61 | ||
|
|
cdd417455f | ||
|
|
fe671f56c5 | ||
|
|
ddf9e6cf3f | ||
|
|
13b03c6abd | ||
|
|
7dd4c629ad | ||
|
|
81b3d7f5f1 | ||
|
|
3566c32209 | ||
|
|
267ca7b379 | ||
|
|
7b9d9954b8 | ||
|
|
79675db241 | ||
|
|
3ac8a3f67f | ||
|
|
2f19949133 | ||
|
|
85fd2aed7e |
@@ -1,14 +1,7 @@
|
||||
node_modules
|
||||
dist
|
||||
examples
|
||||
|
||||
# gatsby-plugin-now
|
||||
packages/gatsby-plugin-now/test/fixtures
|
||||
|
||||
# build-utils
|
||||
packages/build-utils/test/fixtures
|
||||
|
||||
# cli
|
||||
packages/cli/@types
|
||||
packages/cli/download
|
||||
packages/cli/dist
|
||||
@@ -17,24 +10,9 @@ packages/cli/test/dev/fixtures
|
||||
packages/cli/bin
|
||||
packages/cli/link
|
||||
packages/cli/src/util/dev/templates/*.ts
|
||||
|
||||
# client
|
||||
packages/client/tests/fixtures
|
||||
packages/client/lib
|
||||
|
||||
# next
|
||||
packages/next/test/fixtures
|
||||
|
||||
# node
|
||||
packages/node/src/bridge.ts
|
||||
packages/node/test/fixtures
|
||||
|
||||
# node-bridge
|
||||
packages/node-bridge/bridge.*
|
||||
|
||||
# static-build
|
||||
packages/static-build/test/fixtures
|
||||
packages/static-build/test/build-fixtures
|
||||
|
||||
# redwood
|
||||
packages/redwood/test/fixtures
|
||||
packages/node-bridge/bridge.js
|
||||
packages/node-bridge/launcher.js
|
||||
|
||||
@@ -14,7 +14,6 @@ const frameworks = (_frameworks as Framework[])
|
||||
sort: undefined,
|
||||
dependency: undefined,
|
||||
defaultRoutes: undefined,
|
||||
cachePattern: undefined,
|
||||
devCommand: undefined,
|
||||
buildCommand: undefined,
|
||||
};
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 25 KiB |
8
examples/nuxtjs/.gitignore
vendored
8
examples/nuxtjs/.gitignore
vendored
@@ -80,11 +80,15 @@ dist
|
||||
|
||||
# IDE / Editor
|
||||
.idea
|
||||
.editorconfig
|
||||
|
||||
# Service worker
|
||||
sw.*
|
||||
|
||||
# Mac OSX
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
||||
# Vim swap files
|
||||
*.swp
|
||||
|
||||
# Vercel
|
||||
.vercel
|
||||
|
||||
@@ -1 +1,4 @@
|
||||
README.md
|
||||
.nuxt
|
||||
node_modules
|
||||
*.log
|
||||
|
||||
@@ -8,7 +8,7 @@ Deploy your own Nuxt.js project with Vercel.
|
||||
|
||||
[](https://vercel.com/import/project?template=https://github.com/vercel/vercel/tree/main/examples/nuxtjs)
|
||||
|
||||
_Live Example: https://nuxtjs.now-examples.now.sh_
|
||||
_Live Example: https://nuxtjs.now-examples.vercel.app/_
|
||||
|
||||
### How We Created This Example
|
||||
|
||||
@@ -17,5 +17,3 @@ To get started with Nuxt.js deployed with Vercel, you can use the [Create-Nuxt-A
|
||||
```shell
|
||||
$ npx create-nuxt-app my-app
|
||||
```
|
||||
|
||||
> The only change made is to amend the output directory in `nuxt.config.js` to `"/public"`.
|
||||
|
||||
@@ -1,44 +1,37 @@
|
||||
export default {
|
||||
mode: 'spa',
|
||||
/*
|
||||
** Headers of the page
|
||||
*/
|
||||
// Target: https://go.nuxtjs.dev/config-target
|
||||
target: 'static',
|
||||
|
||||
// Global page headers: https://go.nuxtjs.dev/config-head
|
||||
head: {
|
||||
title: process.env.npm_package_name || '',
|
||||
title: 'nuxtjs',
|
||||
meta: [
|
||||
{ charset: 'utf-8' },
|
||||
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
|
||||
{
|
||||
hid: 'description',
|
||||
name: 'description',
|
||||
content: process.env.npm_package_description || '',
|
||||
content: 'My astonishing Nuxt.js project',
|
||||
},
|
||||
],
|
||||
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
|
||||
},
|
||||
/*
|
||||
** Customize the progress-bar color
|
||||
*/
|
||||
loading: { color: '#fff' },
|
||||
/*
|
||||
** Global CSS
|
||||
*/
|
||||
|
||||
// Global CSS: https://go.nuxtjs.dev/config-css
|
||||
css: [],
|
||||
/*
|
||||
** Plugins to load before mounting the App
|
||||
*/
|
||||
|
||||
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
|
||||
plugins: [],
|
||||
/*
|
||||
** Nuxt.js modules
|
||||
*/
|
||||
|
||||
// Auto import components: https://go.nuxtjs.dev/config-components
|
||||
components: true,
|
||||
|
||||
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
|
||||
buildModules: [],
|
||||
|
||||
// Modules: https://go.nuxtjs.dev/config-modules
|
||||
modules: [],
|
||||
/*
|
||||
** Build configuration
|
||||
*/
|
||||
build: {
|
||||
/*
|
||||
** You can extend webpack config here
|
||||
*/
|
||||
extend(config, ctx) {},
|
||||
},
|
||||
|
||||
// Build Configuration: https://go.nuxtjs.dev/config-build
|
||||
build: {}
|
||||
};
|
||||
|
||||
@@ -10,9 +10,8 @@
|
||||
"start": "nuxt start"
|
||||
},
|
||||
"dependencies": {
|
||||
"nuxt": "^2.0.0"
|
||||
"core-js": "^3.15.0",
|
||||
"nuxt": "^2.15.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^2.0.7"
|
||||
}
|
||||
"devDependencies": {}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<a
|
||||
href="https://nuxtjs.org/"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="button--green"
|
||||
>
|
||||
Documentation
|
||||
@@ -19,6 +20,7 @@
|
||||
<a
|
||||
href="https://github.com/nuxt/nuxt.js"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="button--grey"
|
||||
>
|
||||
GitHub
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.4 KiB |
File diff suppressed because it is too large
Load Diff
33
package.json
33
package.json
@@ -15,27 +15,27 @@
|
||||
"lerna": "3.16.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "2.0.0",
|
||||
"@typescript-eslint/parser": "2.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "4.28.0",
|
||||
"@typescript-eslint/parser": "4.28.0",
|
||||
"@vercel/ncc": "0.24.0",
|
||||
"async-retry": "1.2.3",
|
||||
"buffer-replace": "1.0.0",
|
||||
"cheerio": "1.0.0-rc.3",
|
||||
"eslint": "6.2.2",
|
||||
"eslint-config-prettier": "6.1.0",
|
||||
"eslint-plugin-jest": "23.8.2",
|
||||
"eslint": "7.29.0",
|
||||
"eslint-config-prettier": "8.3.0",
|
||||
"eslint-plugin-jest": "24.3.6",
|
||||
"husky": "6.0.0",
|
||||
"json5": "2.1.1",
|
||||
"lint-staged": "9.2.5",
|
||||
"node-fetch": "2.6.1",
|
||||
"npm-package-arg": "6.1.0",
|
||||
"prettier": "2.0.5"
|
||||
"prettier": "2.3.1"
|
||||
},
|
||||
"scripts": {
|
||||
"lerna": "lerna",
|
||||
"bootstrap": "lerna bootstrap",
|
||||
"publish-stable": "echo 'Run `yarn changelog` for instructions'",
|
||||
"publish-canary": "git pull && lerna version prerelease --preid canary --message 'Publish Canary' --exact",
|
||||
"publish-canary": "git checkout main && git pull && lerna version prerelease --preid canary --message 'Publish Canary' --exact",
|
||||
"publish-from-github": "./utils/publish.sh",
|
||||
"changelog": "node utils/changelog.js",
|
||||
"build": "node utils/run.js build all",
|
||||
@@ -79,8 +79,7 @@
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/eslint-recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"prettier",
|
||||
"prettier/@typescript-eslint"
|
||||
"prettier"
|
||||
],
|
||||
"env": {
|
||||
"node": true,
|
||||
@@ -89,26 +88,19 @@
|
||||
},
|
||||
"rules": {
|
||||
"require-atomic-updates": 0,
|
||||
"@typescript-eslint/ban-ts-ignore": 0,
|
||||
"@typescript-eslint/ban-ts-comment": 0,
|
||||
"@typescript-eslint/camelcase": 0,
|
||||
"@typescript-eslint/explicit-function-return-type": 0,
|
||||
"@typescript-eslint/explicit-module-boundary-types": 0,
|
||||
"@typescript-eslint/no-empty-function": 0,
|
||||
"@typescript-eslint/no-explicit-any": 0,
|
||||
"@typescript-eslint/no-non-null-assertion": 0,
|
||||
"@typescript-eslint/no-unused-vars": 2,
|
||||
"@typescript-eslint/no-use-before-define": 0,
|
||||
"@typescript-eslint/no-var-requires": 0,
|
||||
"jest/no-disabled-tests": 2,
|
||||
"jest/no-focused-tests": 2
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"**/*.js"
|
||||
],
|
||||
"rules": {
|
||||
"@typescript-eslint/no-var-requires": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"packages/cli/**/*"
|
||||
@@ -125,8 +117,7 @@
|
||||
"@typescript-eslint/member-delimiter-style": 0,
|
||||
"@typescript-eslint/no-empty-function": 0,
|
||||
"@typescript-eslint/no-explicit-any": 0,
|
||||
"@typescript-eslint/no-inferrable-types": 0,
|
||||
"@typescript-eslint/no-var-requires": 0
|
||||
"@typescript-eslint/no-inferrable-types": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/build-utils",
|
||||
"version": "2.11.1",
|
||||
"version": "2.11.2-canary.2",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.js",
|
||||
@@ -29,7 +29,7 @@
|
||||
"@types/node-fetch": "^2.1.6",
|
||||
"@types/semver": "6.0.0",
|
||||
"@types/yazl": "^2.4.1",
|
||||
"@vercel/frameworks": "0.4.1",
|
||||
"@vercel/frameworks": "0.4.2-canary.1",
|
||||
"@vercel/ncc": "0.24.0",
|
||||
"aggregate-error": "3.0.1",
|
||||
"async-retry": "1.2.3",
|
||||
@@ -47,7 +47,7 @@
|
||||
"node-fetch": "2.6.1",
|
||||
"semver": "6.1.1",
|
||||
"ts-jest": "24.1.0",
|
||||
"typescript": "3.9.3",
|
||||
"typescript": "4.3.4",
|
||||
"yazl": "2.4.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,6 +424,7 @@ function getApiMatches() {
|
||||
|
||||
return [
|
||||
{ src: 'api/**/*.js', use: `@vercel/node`, config },
|
||||
{ src: 'api/**/*.mjs', use: `@vercel/node`, config },
|
||||
{ src: 'api/**/*.ts', use: `@vercel/node`, config },
|
||||
{ src: 'api/**/!(*_test).go', use: `@vercel/go`, config },
|
||||
{ src: 'api/**/*.py', use: `@vercel/python`, config },
|
||||
|
||||
@@ -1346,6 +1346,25 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
|
||||
expect((errorRoutes![0] as Source).status).toBe(404);
|
||||
});
|
||||
|
||||
it('api detect node mjs files', async () => {
|
||||
const files = [
|
||||
'api/index.mjs',
|
||||
'api/users.mjs',
|
||||
'api/config/staging.mjs',
|
||||
'api/config/production.mjs',
|
||||
'api/src/controllers/health.mjs',
|
||||
'api/src/controllers/user.module.mjs',
|
||||
];
|
||||
|
||||
const { builders, errorRoutes } = await detectBuilders(files, undefined, {
|
||||
featHandleMiss,
|
||||
});
|
||||
expect(builders!.length).toBe(6);
|
||||
expect(builders!.every(b => b.src!.endsWith('.mjs'))).toBe(true);
|
||||
expect(errorRoutes!.length).toBe(1);
|
||||
expect((errorRoutes![0] as Source).status).toBe(404);
|
||||
});
|
||||
|
||||
it('just public', async () => {
|
||||
const files = ['public/index.html', 'public/favicon.ico', 'README.md'];
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vercel",
|
||||
"version": "23.0.1",
|
||||
"version": "23.0.2-canary.3",
|
||||
"preferGlobal": true,
|
||||
"license": "Apache-2.0",
|
||||
"description": "The command-line interface for Vercel",
|
||||
@@ -61,11 +61,11 @@
|
||||
"node": ">= 12"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vercel/build-utils": "2.11.1",
|
||||
"@vercel/go": "1.2.2",
|
||||
"@vercel/node": "1.11.1",
|
||||
"@vercel/python": "2.0.4",
|
||||
"@vercel/ruby": "1.2.6",
|
||||
"@vercel/build-utils": "2.11.2-canary.2",
|
||||
"@vercel/go": "1.2.3-canary.0",
|
||||
"@vercel/node": "1.11.2-canary.3",
|
||||
"@vercel/python": "2.0.5-canary.0",
|
||||
"@vercel/ruby": "1.2.7-canary.0",
|
||||
"update-notifier": "4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -100,7 +100,7 @@
|
||||
"@types/universal-analytics": "0.4.2",
|
||||
"@types/which": "1.3.2",
|
||||
"@types/write-json-file": "2.2.1",
|
||||
"@vercel/frameworks": "0.4.1",
|
||||
"@vercel/frameworks": "0.4.2-canary.1",
|
||||
"@vercel/ncc": "0.24.0",
|
||||
"@zeit/fun": "0.11.2",
|
||||
"@zeit/source-map-support": "0.6.2",
|
||||
@@ -171,7 +171,7 @@
|
||||
"tree-kill": "1.2.2",
|
||||
"ts-eager": "2.0.2",
|
||||
"ts-node": "8.3.0",
|
||||
"typescript": "3.9.3",
|
||||
"typescript": "4.3.4",
|
||||
"universal-analytics": "0.4.20",
|
||||
"utility-types": "2.1.0",
|
||||
"which": "2.0.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import chalk from 'chalk';
|
||||
import logo from '../../util/output/logo';
|
||||
import { getPkgName } from '../../util/pkg-name.ts';
|
||||
import { getPkgName } from '../../util/pkg-name';
|
||||
|
||||
export const help = () => `
|
||||
${chalk.bold(`${logo} ${getPkgName()}`)} [options] <command | path>
|
||||
@@ -92,30 +92,3 @@ export const help = () => `
|
||||
${chalk.cyan(`$ ${getPkgName()} help list`)}
|
||||
|
||||
`;
|
||||
|
||||
export const args = {
|
||||
'--force': Boolean,
|
||||
'--with-cache': Boolean,
|
||||
'--public': Boolean,
|
||||
'--no-clipboard': Boolean,
|
||||
'--env': [String],
|
||||
'--build-env': [String],
|
||||
'--meta': [String],
|
||||
// This is not an array in favor of matching
|
||||
// the config property name.
|
||||
'--regions': String,
|
||||
'--prod': Boolean,
|
||||
'--confirm': Boolean,
|
||||
'-f': '--force',
|
||||
'-p': '--public',
|
||||
'-e': '--env',
|
||||
'-b': '--build-env',
|
||||
'-C': '--no-clipboard',
|
||||
'-m': '--meta',
|
||||
'-c': '--confirm',
|
||||
|
||||
// deprecated
|
||||
'--name': String,
|
||||
'-n': '--name',
|
||||
'--target': String,
|
||||
};
|
||||
@@ -1,37 +1,62 @@
|
||||
import fs from 'fs-extra';
|
||||
import { resolve, basename } from 'path';
|
||||
import { fileNameSymbol } from '@vercel/client';
|
||||
import getScope from '../../util/get-scope.ts';
|
||||
import { VercelConfig, fileNameSymbol } from '@vercel/client';
|
||||
import code from '../../util/output/code';
|
||||
import highlight from '../../util/output/highlight';
|
||||
import { readLocalConfig } from '../../util/config/files';
|
||||
import getArgs from '../../util/get-args';
|
||||
import { handleError } from '../../util/error';
|
||||
import { help, args } from './args';
|
||||
import { help } from './args';
|
||||
import deploy from './latest';
|
||||
import Client from '../../util/client';
|
||||
|
||||
export default async client => {
|
||||
const {
|
||||
output,
|
||||
config: { currentTeam },
|
||||
} = client;
|
||||
export default async (client: Client) => {
|
||||
const { output } = client;
|
||||
|
||||
let contextName = currentTeam || 'current user';
|
||||
let argv = null;
|
||||
|
||||
try {
|
||||
argv = getArgs(client.argv.slice(2), args);
|
||||
argv = getArgs(client.argv.slice(2), {
|
||||
'--force': Boolean,
|
||||
'--with-cache': Boolean,
|
||||
'--public': Boolean,
|
||||
'--no-clipboard': Boolean,
|
||||
'--env': [String],
|
||||
'--build-env': [String],
|
||||
'--meta': [String],
|
||||
// This is not an array in favor of matching
|
||||
// the config property name.
|
||||
'--regions': String,
|
||||
'--prod': Boolean,
|
||||
'--confirm': Boolean,
|
||||
'-f': '--force',
|
||||
'-p': '--public',
|
||||
'-e': '--env',
|
||||
'-b': '--build-env',
|
||||
'-C': '--no-clipboard',
|
||||
'-m': '--meta',
|
||||
'-c': '--confirm',
|
||||
|
||||
// deprecated
|
||||
'--name': String,
|
||||
'-n': '--name',
|
||||
'--target': String,
|
||||
});
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (argv['--help']) {
|
||||
output.print(help());
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (argv._[0] === 'deploy') {
|
||||
argv._.shift();
|
||||
}
|
||||
|
||||
let paths = [];
|
||||
|
||||
let paths;
|
||||
if (argv._.length > 0) {
|
||||
// If path is relative: resolve
|
||||
// if path is absolute: clear up strange `/` etc
|
||||
@@ -40,20 +65,14 @@ export default async client => {
|
||||
paths = [process.cwd()];
|
||||
}
|
||||
|
||||
let { localConfig } = client;
|
||||
let localConfig: VercelConfig | null = client.localConfig;
|
||||
if (!localConfig || localConfig instanceof Error) {
|
||||
localConfig = readLocalConfig(paths[0]);
|
||||
}
|
||||
const stats = {};
|
||||
|
||||
if (argv['--help']) {
|
||||
output.print(help());
|
||||
return 2;
|
||||
}
|
||||
|
||||
for (const path of paths) {
|
||||
try {
|
||||
stats[path] = await fs.lstat(path);
|
||||
await fs.stat(path);
|
||||
} catch (err) {
|
||||
output.error(
|
||||
`The specified file or directory "${basename(path)}" does not exist.`
|
||||
@@ -62,26 +81,15 @@ export default async client => {
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
({ contextName } = await getScope(client));
|
||||
} catch (err) {
|
||||
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
|
||||
output.error(err.message);
|
||||
return 1;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (localConfig) {
|
||||
const { version } = localConfig;
|
||||
const file = highlight(localConfig[fileNameSymbol]);
|
||||
const file = highlight(localConfig[fileNameSymbol]!);
|
||||
const prop = code('version');
|
||||
|
||||
if (version) {
|
||||
if (typeof version === 'number') {
|
||||
if (version !== 2) {
|
||||
const two = code(2);
|
||||
const two = code(String(2));
|
||||
|
||||
output.error(
|
||||
`The value of the ${prop} property within ${file} can only be ${two}.`
|
||||
@@ -97,5 +105,5 @@ export default async client => {
|
||||
}
|
||||
}
|
||||
|
||||
return deploy(client, contextName, output, stats, localConfig, args);
|
||||
return deploy(client, paths, localConfig, argv);
|
||||
};
|
||||
@@ -3,13 +3,12 @@ import bytes from 'bytes';
|
||||
import { join } from 'path';
|
||||
import { write as copy } from 'clipboardy';
|
||||
import chalk from 'chalk';
|
||||
import { fileNameSymbol } from '@vercel/client';
|
||||
import { Dictionary, fileNameSymbol, VercelConfig } from '@vercel/client';
|
||||
import { getPrettyError } from '@vercel/build-utils';
|
||||
import { handleError } from '../../util/error';
|
||||
import getArgs from '../../util/get-args';
|
||||
import toHumanPath from '../../util/humanize-path';
|
||||
import Now from '../../util';
|
||||
import stamp from '../../util/output/stamp.ts';
|
||||
import stamp from '../../util/output/stamp';
|
||||
import createDeploy from '../../util/deploy/create-deploy';
|
||||
import getDeploymentByIdOrHost from '../../util/deploy/get-deployment-by-id-or-host';
|
||||
import parseMeta from '../../util/parse-meta';
|
||||
@@ -53,10 +52,15 @@ import validatePaths, {
|
||||
validateRootDirectory,
|
||||
} from '../../util/validate-paths';
|
||||
import { readLocalConfig } from '../../util/config/files';
|
||||
import { getCommandName } from '../../util/pkg-name.ts';
|
||||
import { getPreferredPreviewURL } from '../../util/deploy/get-preferred-preview-url.ts';
|
||||
import { getCommandName } from '../../util/pkg-name';
|
||||
import { getPreferredPreviewURL } from '../../util/deploy/get-preferred-preview-url';
|
||||
import { Output } from '../../util/output';
|
||||
import Client from '../../util/client';
|
||||
|
||||
const addProcessEnv = async (log, env) => {
|
||||
const addProcessEnv = async (
|
||||
log: (str: string) => void,
|
||||
env: typeof process.env
|
||||
) => {
|
||||
let val;
|
||||
|
||||
for (const key of Object.keys(env)) {
|
||||
@@ -85,8 +89,8 @@ const addProcessEnv = async (log, env) => {
|
||||
};
|
||||
|
||||
const printDeploymentStatus = async (
|
||||
output,
|
||||
client,
|
||||
output: Output,
|
||||
client: Client,
|
||||
{
|
||||
readyState,
|
||||
alias: aliasList,
|
||||
@@ -94,10 +98,17 @@ const printDeploymentStatus = async (
|
||||
target,
|
||||
indications,
|
||||
url: deploymentUrl,
|
||||
}: {
|
||||
readyState: string;
|
||||
alias: string[];
|
||||
aliasError: Error;
|
||||
target: string;
|
||||
indications: any;
|
||||
url: string;
|
||||
},
|
||||
deployStamp,
|
||||
isClipboardEnabled,
|
||||
isFile
|
||||
deployStamp: () => string,
|
||||
isClipboardEnabled: boolean,
|
||||
isFile: boolean
|
||||
) => {
|
||||
const isProdDeployment = target === 'production';
|
||||
|
||||
@@ -116,8 +127,8 @@ const printDeploymentStatus = async (
|
||||
);
|
||||
} else {
|
||||
// print preview/production url
|
||||
let previewUrl;
|
||||
let isWildcard;
|
||||
let previewUrl: string;
|
||||
let isWildcard: boolean;
|
||||
if (!isFile && Array.isArray(aliasList) && aliasList.length > 0) {
|
||||
const previewUrlInfo = await getPreferredPreviewURL(client, aliasList);
|
||||
if (previewUrlInfo) {
|
||||
@@ -136,11 +147,12 @@ const printDeploymentStatus = async (
|
||||
// copy to clipboard
|
||||
let isCopiedToClipboard = false;
|
||||
if (isClipboardEnabled && !isWildcard) {
|
||||
await copy(previewUrl)
|
||||
.then(() => {
|
||||
isCopiedToClipboard = true;
|
||||
})
|
||||
.catch(error => output.debug(`Error copying to clipboard: ${error}`));
|
||||
try {
|
||||
await copy(previewUrl);
|
||||
isCopiedToClipboard = true;
|
||||
} catch (err) {
|
||||
output.debug(`Error copyind to clipboard: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
output.print(
|
||||
@@ -176,7 +188,7 @@ const printDeploymentStatus = async (
|
||||
};
|
||||
|
||||
// Converts `env` Arrays, Strings and Objects into env Objects.
|
||||
const parseEnv = env => {
|
||||
const parseEnv = (env?: string[] | Dictionary<string>) => {
|
||||
if (!env) {
|
||||
return {};
|
||||
}
|
||||
@@ -201,35 +213,25 @@ const parseEnv = env => {
|
||||
|
||||
o[key] = value;
|
||||
return o;
|
||||
}, {});
|
||||
}, {} as Dictionary<string | undefined>);
|
||||
}
|
||||
|
||||
// assume it's already an Object
|
||||
return env;
|
||||
};
|
||||
|
||||
export default async function main(
|
||||
client,
|
||||
contextName,
|
||||
output,
|
||||
stats,
|
||||
localConfig,
|
||||
args
|
||||
client: Client,
|
||||
paths: string[],
|
||||
localConfig: VercelConfig | null,
|
||||
argv: any
|
||||
) {
|
||||
let argv = null;
|
||||
|
||||
try {
|
||||
argv = getArgs(client.argv.slice(2), args);
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const {
|
||||
apiUrl,
|
||||
output,
|
||||
authConfig: { token },
|
||||
} = client;
|
||||
const { log, debug, error, warn } = output;
|
||||
const paths = Object.keys(stats);
|
||||
const debugEnabled = argv['--debug'];
|
||||
|
||||
const { isTTY } = process.stdout;
|
||||
@@ -265,6 +267,7 @@ export default async function main(
|
||||
}
|
||||
|
||||
let { org, project, status } = link;
|
||||
|
||||
let newProjectName = null;
|
||||
let rootDirectory = project ? project.rootDirectory : null;
|
||||
let sourceFilesOutsideRootDirectory = true;
|
||||
@@ -340,6 +343,16 @@ export default async function main(
|
||||
}
|
||||
}
|
||||
|
||||
// At this point `org` should be populated
|
||||
if (!org) {
|
||||
throw new Error(`"org" is not defined`);
|
||||
}
|
||||
|
||||
// Set the `contextName` and `currentTeam` as specified by the
|
||||
// Project Settings, so that API calls happen with the proper scope
|
||||
const contextName = org.slug;
|
||||
client.config.currentTeam = org.type === 'team' ? org.id : undefined;
|
||||
|
||||
// if we have `sourceFilesOutsideRootDirectory` set to `true`, we use the current path
|
||||
// and upload the entire directory.
|
||||
const sourcePath =
|
||||
@@ -354,7 +367,7 @@ export default async function main(
|
||||
path,
|
||||
sourcePath,
|
||||
project
|
||||
? `To change your Project Settings, go to https://vercel.com/${org.slug}/${project.name}/settings`
|
||||
? `To change your Project Settings, go to https://vercel.com/${org?.slug}/${project.name}/settings`
|
||||
: ''
|
||||
)) === false
|
||||
) {
|
||||
@@ -373,7 +386,7 @@ export default async function main(
|
||||
output.print(
|
||||
`${prependEmoji(
|
||||
`The ${highlight(
|
||||
localConfig[fileNameSymbol]
|
||||
localConfig[fileNameSymbol]!
|
||||
)} file should be inside of the provided root directory.`,
|
||||
emoji('warning')
|
||||
)}\n`
|
||||
@@ -387,7 +400,7 @@ export default async function main(
|
||||
output.print(
|
||||
`${prependEmoji(
|
||||
`The ${code('name')} property in ${highlight(
|
||||
localConfig[fileNameSymbol]
|
||||
localConfig[fileNameSymbol]!
|
||||
)} is deprecated (https://vercel.link/name-prop)`,
|
||||
emoji('warning')
|
||||
)}\n`
|
||||
@@ -395,7 +408,7 @@ export default async function main(
|
||||
}
|
||||
|
||||
// build `env`
|
||||
const isObject = item =>
|
||||
const isObject = (item: any) =>
|
||||
Object.prototype.toString.call(item) === '[object Object]';
|
||||
|
||||
// This validation needs to happen on the client side because
|
||||
@@ -404,7 +417,7 @@ export default async function main(
|
||||
if (typeof localConfig.env !== 'undefined' && !isObject(localConfig.env)) {
|
||||
error(
|
||||
`The ${code('env')} property in ${highlight(
|
||||
localConfig[fileNameSymbol]
|
||||
localConfig[fileNameSymbol]!
|
||||
)} needs to be an object`
|
||||
);
|
||||
return 1;
|
||||
@@ -414,7 +427,7 @@ export default async function main(
|
||||
if (!isObject(localConfig.build)) {
|
||||
error(
|
||||
`The ${code('build')} property in ${highlight(
|
||||
localConfig[fileNameSymbol]
|
||||
localConfig[fileNameSymbol]!
|
||||
)} needs to be an object`
|
||||
);
|
||||
return 1;
|
||||
@@ -426,7 +439,7 @@ export default async function main(
|
||||
) {
|
||||
error(
|
||||
`The ${code('build.env')} property in ${highlight(
|
||||
localConfig[fileNameSymbol]
|
||||
localConfig[fileNameSymbol]!
|
||||
)} needs to be an object`
|
||||
);
|
||||
return 1;
|
||||
@@ -466,7 +479,7 @@ export default async function main(
|
||||
// build `regions`
|
||||
const regionFlag = (argv['--regions'] || '')
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
.map((s: string) => s.trim())
|
||||
.filter(Boolean);
|
||||
const regions = regionFlag.length > 0 ? regionFlag : localConfig.regions;
|
||||
|
||||
@@ -497,13 +510,13 @@ export default async function main(
|
||||
target = 'production';
|
||||
}
|
||||
|
||||
const currentTeam = org.type === 'team' ? org.id : undefined;
|
||||
const currentTeam = org?.type === 'team' ? org.id : undefined;
|
||||
const now = new Now({ apiUrl, token, debug: debugEnabled, currentTeam });
|
||||
let deployStamp = stamp();
|
||||
let deployment = null;
|
||||
|
||||
try {
|
||||
const createArgs = {
|
||||
const createArgs: any = {
|
||||
name: project ? project.name : newProjectName,
|
||||
env: deploymentEnv,
|
||||
build: { env: deploymentBuildEnv },
|
||||
@@ -527,7 +540,7 @@ export default async function main(
|
||||
}
|
||||
|
||||
deployment = await createDeploy(
|
||||
output,
|
||||
client,
|
||||
now,
|
||||
contextName,
|
||||
[sourcePath],
|
||||
@@ -537,18 +550,15 @@ export default async function main(
|
||||
path
|
||||
);
|
||||
|
||||
if (
|
||||
deployment instanceof Error &&
|
||||
deployment.code === 'missing_project_settings'
|
||||
) {
|
||||
if (deployment.code === 'missing_project_settings') {
|
||||
let { projectSettings, framework } = deployment;
|
||||
|
||||
if (rootDirectory) {
|
||||
projectSettings.rootDirectory = rootDirectory;
|
||||
}
|
||||
|
||||
if (typeof sourceFilesOutsideRootDirectory !== 'undefined') {
|
||||
projectSettings.sourceFilesOutsideRootDirectory = sourceFilesOutsideRootDirectory;
|
||||
projectSettings.sourceFilesOutsideRootDirectory =
|
||||
sourceFilesOutsideRootDirectory;
|
||||
}
|
||||
|
||||
const settings = await editProjectSettings(
|
||||
@@ -563,7 +573,7 @@ export default async function main(
|
||||
deployStamp = stamp();
|
||||
createArgs.deployStamp = deployStamp;
|
||||
deployment = await createDeploy(
|
||||
output,
|
||||
client,
|
||||
now,
|
||||
contextName,
|
||||
[sourcePath],
|
||||
@@ -575,7 +585,7 @@ export default async function main(
|
||||
}
|
||||
|
||||
if (deployment instanceof NotDomainOwner) {
|
||||
output.error(deployment);
|
||||
output.error(deployment.message);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -583,7 +593,7 @@ export default async function main(
|
||||
output.error(
|
||||
deployment.message ||
|
||||
'An unexpected error occurred while deploying your project',
|
||||
null,
|
||||
undefined,
|
||||
'https://vercel.link/help',
|
||||
'Contact Support'
|
||||
);
|
||||
@@ -596,7 +606,7 @@ export default async function main(
|
||||
}
|
||||
|
||||
const deploymentResponse = await getDeploymentByIdOrHost(
|
||||
now,
|
||||
client,
|
||||
contextName,
|
||||
deployment.id,
|
||||
'v10'
|
||||
@@ -676,12 +686,7 @@ export default async function main(
|
||||
output.error(err.message || 'Build failed');
|
||||
output.error(
|
||||
`Check your logs at https://${now.url}/_logs or run ${getCommandName(
|
||||
`logs ${now.url}`,
|
||||
{
|
||||
// Backticks are interpreted as part of the URL, causing CMD+Click
|
||||
// behavior to fail in editors like VSCode.
|
||||
backticks: false,
|
||||
}
|
||||
`logs ${now.url}`
|
||||
)}`
|
||||
);
|
||||
|
||||
@@ -715,7 +720,11 @@ export default async function main(
|
||||
);
|
||||
}
|
||||
|
||||
function handleCreateDeployError(output, error, localConfig) {
|
||||
function handleCreateDeployError(
|
||||
output: Output,
|
||||
error: Error,
|
||||
localConfig: VercelConfig
|
||||
) {
|
||||
if (error instanceof InvalidDomain) {
|
||||
output.error(`The domain ${error.meta.domain} is not valid`);
|
||||
return 1;
|
||||
@@ -108,8 +108,5 @@ export default async function dev(
|
||||
systemEnvValues,
|
||||
});
|
||||
|
||||
process.once('SIGINT', () => devServer.stop());
|
||||
process.once('SIGTERM', () => devServer.stop());
|
||||
|
||||
await devServer.start(...listen);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ import getDomainPrice from '../../util/domains/get-domain-price';
|
||||
import { getCommandName } from '../../util/pkg-name';
|
||||
import { getDomainConfig } from '../../util/domains/get-domain-config';
|
||||
import code from '../../util/output/code';
|
||||
import wait from '../../util/output/wait';
|
||||
import { getDomainRegistrar } from '../../util/domains/get-domain-registrar';
|
||||
|
||||
type Options = {};
|
||||
@@ -59,7 +58,7 @@ export default async function inspect(
|
||||
|
||||
output.debug(`Fetching domain info`);
|
||||
|
||||
const cancelWait = wait(
|
||||
output.spinner(
|
||||
`Fetching Domain ${domainName} under ${chalk.bold(contextName)}`
|
||||
);
|
||||
|
||||
@@ -68,9 +67,6 @@ export default async function inspect(
|
||||
client,
|
||||
contextName,
|
||||
domainName,
|
||||
cancelWait,
|
||||
}).finally(() => {
|
||||
cancelWait();
|
||||
});
|
||||
|
||||
if (typeof information === 'number') {
|
||||
@@ -207,13 +203,11 @@ async function fetchInformation({
|
||||
client,
|
||||
contextName,
|
||||
domainName,
|
||||
cancelWait,
|
||||
}: {
|
||||
output: Output;
|
||||
client: Client;
|
||||
contextName: string;
|
||||
domainName: string;
|
||||
cancelWait: () => void;
|
||||
}) {
|
||||
const [domain, renewalPrice] = await Promise.all([
|
||||
getDomainByName(client, contextName, domainName, { ignoreWait: true }),
|
||||
@@ -223,13 +217,11 @@ async function fetchInformation({
|
||||
]);
|
||||
|
||||
if (domain instanceof DomainNotFound) {
|
||||
cancelWait();
|
||||
output.prettyError(domain);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (domain instanceof DomainPermissionDenied) {
|
||||
cancelWait();
|
||||
output.prettyError(domain);
|
||||
output.log(`Run ${getCommandName(`domains ls`)} to see your domains.`);
|
||||
return 1;
|
||||
@@ -238,7 +230,6 @@ async function fetchInformation({
|
||||
const projects = await findProjectsForDomain(client, domainName);
|
||||
|
||||
if (projects instanceof Error) {
|
||||
cancelWait();
|
||||
output.prettyError(projects);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import ms from 'ms';
|
||||
import chalk from 'chalk';
|
||||
import plural from 'pluralize';
|
||||
|
||||
import wait from '../../util/output/wait';
|
||||
import Client from '../../util/client';
|
||||
import getDomains from '../../util/domains/get-domains';
|
||||
import getScope from '../../util/get-scope';
|
||||
@@ -55,14 +54,9 @@ export default async function ls(
|
||||
return 1;
|
||||
}
|
||||
|
||||
const cancelWait = wait(`Fetching Domains under ${chalk.bold(contextName)}`);
|
||||
output.spinner(`Fetching Domains under ${chalk.bold(contextName)}`);
|
||||
|
||||
const { domains, pagination } = await getDomains(
|
||||
client,
|
||||
nextTimestamp
|
||||
).finally(() => {
|
||||
cancelWait();
|
||||
});
|
||||
const { domains, pagination } = await getDomains(client, nextTimestamp);
|
||||
|
||||
output.log(
|
||||
`${plural('Domain', domains.length, true)} found under ${chalk.bold(
|
||||
|
||||
@@ -12,6 +12,7 @@ import { getCommandName, getPkgName } from '../util/pkg-name';
|
||||
import getGlobalPathConfig from '../util/config/global-path';
|
||||
import { writeToAuthConfigFile, writeToConfigFile } from '../util/config/files';
|
||||
import Client from '../util/client';
|
||||
import { LoginResult } from '../util/login/types';
|
||||
|
||||
const help = () => {
|
||||
console.log(`
|
||||
@@ -66,7 +67,7 @@ export default async function login(client: Client): Promise<number> {
|
||||
|
||||
const input = argv._[1];
|
||||
|
||||
let result: number | string = 1;
|
||||
let result: LoginResult = 1;
|
||||
|
||||
if (input) {
|
||||
// Email or Team slug was provided via command line
|
||||
@@ -85,12 +86,20 @@ export default async function login(client: Client): Promise<number> {
|
||||
return result;
|
||||
}
|
||||
|
||||
// If the token was upgraded (not a new login), then don't modify
|
||||
// the current scope.
|
||||
if (!client.authConfig.token) {
|
||||
if (result.teamId) {
|
||||
// SSO login, so set the current scope to the appropriate Team
|
||||
client.config.currentTeam = result.teamId;
|
||||
} else {
|
||||
delete client.config.currentTeam;
|
||||
}
|
||||
}
|
||||
|
||||
// When `result` is a string it's the user's authentication token.
|
||||
// It needs to be saved to the configuration file.
|
||||
client.authConfig.token = result;
|
||||
|
||||
// New user, so we can't keep the team
|
||||
delete client.config.currentTeam;
|
||||
client.authConfig.token = result.token;
|
||||
|
||||
writeToAuthConfigFile(client.authConfig);
|
||||
writeToConfigFile(client.config);
|
||||
|
||||
@@ -243,7 +243,7 @@ function printLogShort(log: any) {
|
||||
|
||||
const date = new Date(log.created).toISOString();
|
||||
|
||||
data.split('\n').forEach((line, i) => {
|
||||
data.split('\n').forEach(line => {
|
||||
if (
|
||||
line.includes('START RequestId:') ||
|
||||
line.includes('END RequestId:') ||
|
||||
@@ -260,18 +260,9 @@ function printLogShort(log: any) {
|
||||
}
|
||||
}
|
||||
|
||||
if (i === 0) {
|
||||
console.log(
|
||||
`${chalk.dim(date)} ${line.replace('[now-builder-debug] ', '')}`
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
`${' '.repeat(date.length)} ${line.replace(
|
||||
'[now-builder-debug] ',
|
||||
''
|
||||
)}`
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`${chalk.dim(date)} ${line.replace('[now-builder-debug] ', '')}`
|
||||
);
|
||||
});
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -8,7 +8,6 @@ import exit from '../util/exit';
|
||||
import logo from '../util/output/logo';
|
||||
import getScope from '../util/get-scope';
|
||||
import getCommandFlags from '../util/get-command-flags';
|
||||
import wait from '../util/output/wait';
|
||||
import { getPkgName, getCommandName } from '../util/pkg-name.ts';
|
||||
|
||||
const e = encodeURIComponent;
|
||||
@@ -103,6 +102,7 @@ export default async client => {
|
||||
};
|
||||
|
||||
async function run({ client, contextName }) {
|
||||
const { output } = client;
|
||||
const args = argv._.slice(1);
|
||||
const start = Date.now();
|
||||
|
||||
@@ -118,7 +118,7 @@ async function run({ client, contextName }) {
|
||||
return exit(2);
|
||||
}
|
||||
|
||||
const stopSpinner = wait(`Fetching projects in ${chalk.bold(contextName)}`);
|
||||
output.spinner(`Fetching projects in ${chalk.bold(contextName)}`);
|
||||
|
||||
let projectsUrl = '/v4/projects/?limit=20';
|
||||
|
||||
@@ -131,7 +131,7 @@ async function run({ client, contextName }) {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
stopSpinner();
|
||||
output.stopSpinner();
|
||||
|
||||
const elapsed = ms(new Date() - start);
|
||||
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import chalk from 'chalk';
|
||||
import stamp from '../../util/output/stamp.ts';
|
||||
import info from '../../util/output/info';
|
||||
import error from '../../util/output/error';
|
||||
import wait from '../../util/output/wait';
|
||||
import rightPad from '../../util/output/right-pad';
|
||||
import eraseLines from '../../util/output/erase-lines';
|
||||
import chars from '../../util/output/chars';
|
||||
import success from '../../util/output/success';
|
||||
import note from '../../util/output/note';
|
||||
import textInput from '../../util/input/text';
|
||||
import invite from './invite';
|
||||
@@ -40,14 +37,12 @@ export default async function add(client, teams) {
|
||||
let slug;
|
||||
let team;
|
||||
let elapsed;
|
||||
let stopSpinner;
|
||||
const { output } = client;
|
||||
|
||||
console.log(
|
||||
info(
|
||||
`Pick a team identifier for its url (e.g.: ${chalk.cyan(
|
||||
'`vercel.com/acme`'
|
||||
)})`
|
||||
)
|
||||
output.log(
|
||||
`Pick a team identifier for its url (e.g.: ${chalk.cyan(
|
||||
'`vercel.com/acme`'
|
||||
)})`
|
||||
);
|
||||
do {
|
||||
try {
|
||||
@@ -61,7 +56,7 @@ export default async function add(client, teams) {
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.message === 'USER_ABORT') {
|
||||
console.log(info('Aborted'));
|
||||
output.log('Aborted');
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -69,26 +64,26 @@ export default async function add(client, teams) {
|
||||
}
|
||||
|
||||
elapsed = stamp();
|
||||
stopSpinner = wait(teamUrlPrefix + slug);
|
||||
output.spinner(teamUrlPrefix + slug);
|
||||
|
||||
let res;
|
||||
try {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
res = await teams.create({ slug });
|
||||
stopSpinner();
|
||||
team = res;
|
||||
} catch (err) {
|
||||
stopSpinner();
|
||||
output.stopSpinner();
|
||||
process.stdout.write(eraseLines(2));
|
||||
console.error(error(err.message));
|
||||
output.error(err.message);
|
||||
}
|
||||
} while (!team);
|
||||
|
||||
output.stopSpinner();
|
||||
process.stdout.write(eraseLines(2));
|
||||
|
||||
console.log(success(`Team created ${elapsed()}`));
|
||||
console.log(`${chalk.cyan(`${chars.tick} `) + teamUrlPrefix + slug}\n`);
|
||||
console.log(info('Pick a display name for your team'));
|
||||
output.success(`Team created ${elapsed()}`);
|
||||
output.log(`${chalk.cyan(`${chars.tick} `) + teamUrlPrefix + slug}\n`);
|
||||
output.log('Pick a display name for your team');
|
||||
|
||||
let name;
|
||||
|
||||
@@ -107,17 +102,16 @@ export default async function add(client, teams) {
|
||||
}
|
||||
|
||||
elapsed = stamp();
|
||||
stopSpinner = wait(teamNamePrefix + name);
|
||||
output.spinner(teamNamePrefix + name);
|
||||
|
||||
const res = await teams.edit({ id: team.id, name });
|
||||
|
||||
stopSpinner();
|
||||
|
||||
output.stopSpinner();
|
||||
process.stdout.write(eraseLines(2));
|
||||
|
||||
if (res.error) {
|
||||
console.error(error(res.error.message));
|
||||
console.log(`${chalk.red(`✖ ${teamNamePrefix}`)}${name}`);
|
||||
output.error(res.error.message);
|
||||
output.log(`${chalk.red(`✖ ${teamNamePrefix}`)}${name}`);
|
||||
|
||||
return 1;
|
||||
// TODO: maybe we want to ask the user to retry? not sure if
|
||||
@@ -126,10 +120,10 @@ export default async function add(client, teams) {
|
||||
|
||||
team = Object.assign(team, res);
|
||||
|
||||
console.log(success(`Team name saved ${elapsed()}`));
|
||||
console.log(`${chalk.cyan(`${chars.tick} `) + teamNamePrefix + team.name}\n`);
|
||||
output.success(`Team name saved ${elapsed()}`);
|
||||
output.log(`${chalk.cyan(`${chars.tick} `) + teamNamePrefix + team.name}\n`);
|
||||
|
||||
stopSpinner = wait('Saving');
|
||||
output.spinner('Saving');
|
||||
|
||||
// Update config file
|
||||
const configCopy = Object.assign({}, client.config);
|
||||
@@ -142,7 +136,7 @@ export default async function add(client, teams) {
|
||||
|
||||
writeToConfigFile(configCopy);
|
||||
|
||||
stopSpinner();
|
||||
output.stopSpinner();
|
||||
|
||||
await invite(client, { _: [] }, teams, {
|
||||
introMsg: 'Invite your teammates! When done, press enter on an empty field',
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
// Packages
|
||||
import chalk from 'chalk';
|
||||
|
||||
// Utilities
|
||||
import wait from '../../util/output/wait';
|
||||
|
||||
import info from '../../util/output/info';
|
||||
import error from '../../util/output/error';
|
||||
import chars from '../../util/output/chars';
|
||||
import table from '../../util/output/table';
|
||||
import getUser from '../../util/get-user.ts';
|
||||
@@ -23,7 +15,7 @@ export default async function list(client, argv, teams) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
const stopSpinner = wait('Fetching teams');
|
||||
output.spinner('Fetching teams');
|
||||
const { teams: list, pagination } = await teams.ls({
|
||||
next,
|
||||
apiVersion: 2,
|
||||
@@ -31,23 +23,19 @@ export default async function list(client, argv, teams) {
|
||||
let { currentTeam } = config;
|
||||
const accountIsCurrent = !currentTeam;
|
||||
|
||||
stopSpinner();
|
||||
|
||||
const stopUserSpinner = wait('Fetching user information');
|
||||
output.spinner('Fetching user information');
|
||||
let user;
|
||||
try {
|
||||
user = await getUser(client);
|
||||
} catch (err) {
|
||||
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
|
||||
console.error(error(err.message));
|
||||
output.error(err.message);
|
||||
return 1;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
stopUserSpinner();
|
||||
|
||||
if (accountIsCurrent) {
|
||||
currentTeam = {
|
||||
slug: user.username || user.email,
|
||||
@@ -79,12 +67,12 @@ export default async function list(client, argv, teams) {
|
||||
const count = teamList.length;
|
||||
if (!count) {
|
||||
// Maybe should not happen
|
||||
console.error(error(`No team found`));
|
||||
output.error(`No teams found`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
info(`${chalk.bold(count)} team${count > 1 ? 's' : ''} found`);
|
||||
console.log();
|
||||
output.stopSpinner();
|
||||
console.log(); // empty line
|
||||
|
||||
table(
|
||||
['', 'id', 'email / name'],
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import chalk from 'chalk';
|
||||
import logo from '../util/output/logo';
|
||||
import getScope from '../util/get-scope.ts';
|
||||
import { getPkgName } from '../util/pkg-name.ts';
|
||||
import getArgs from '../util/get-args.ts';
|
||||
import handleError from '../util/handle-error.ts';
|
||||
import getScope from '../util/get-scope';
|
||||
import { getPkgName } from '../util/pkg-name';
|
||||
import getArgs from '../util/get-args';
|
||||
import handleError from '../util/handle-error';
|
||||
import Client from '../util/client';
|
||||
|
||||
const help = () => {
|
||||
console.log(`
|
||||
@@ -31,7 +32,7 @@ const help = () => {
|
||||
`);
|
||||
};
|
||||
|
||||
export default async client => {
|
||||
export default async (client: Client) => {
|
||||
const { output } = client;
|
||||
let argv;
|
||||
try {
|
||||
@@ -50,6 +50,7 @@ import { SENTRY_DSN } from './util/constants.ts';
|
||||
import getUpdateCommand from './util/get-update-command';
|
||||
import { metrics, shouldCollectMetrics } from './util/metrics.ts';
|
||||
import { getCommandName, getTitleName } from './util/pkg-name.ts';
|
||||
import doLoginPrompt from './util/login/prompt.ts';
|
||||
|
||||
const isCanary = pkg.version.includes('canary');
|
||||
|
||||
@@ -422,13 +423,24 @@ const main = async () => {
|
||||
) {
|
||||
if (isTTY) {
|
||||
output.log(info(`No existing credentials found. Please log in:`));
|
||||
const result = await doLoginPrompt(client);
|
||||
|
||||
subcommand = 'login';
|
||||
client.argv[2] = 'login';
|
||||
// The login function failed, so it returned an exit code
|
||||
if (typeof result === 'number') {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Ensure that subcommands lead to login as well, if
|
||||
// no credentials are defined
|
||||
client.argv = client.argv.splice(0, 3);
|
||||
// When `result` is a string it's the user's authentication token.
|
||||
// It needs to be saved to the configuration file.
|
||||
client.authConfig.token = result;
|
||||
|
||||
// New user, so we can't keep the team
|
||||
delete client.config.currentTeam;
|
||||
|
||||
configFiles.writeToAuthConfigFile(client.authConfig);
|
||||
configFiles.writeToConfigFile(client.config);
|
||||
|
||||
output.debug(`Saved credentials in "${hp(VERCEL_DIR)}"`);
|
||||
} else {
|
||||
output.prettyError({
|
||||
message:
|
||||
|
||||
@@ -270,6 +270,7 @@ export interface Project extends ProjectSettings {
|
||||
rootDirectory?: string | null;
|
||||
latestDeployments?: Partial<Deployment>[];
|
||||
autoExposeSystemEnvs?: boolean;
|
||||
sourceFilesOutsideRootDirectory: boolean;
|
||||
}
|
||||
|
||||
export interface Org {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { resolve } from 'path';
|
||||
import wait from '../output/wait';
|
||||
import Client from '../client';
|
||||
import { Cert } from '../../types';
|
||||
|
||||
@@ -10,7 +9,7 @@ export default async function createCertFromFile(
|
||||
certPath: string,
|
||||
caPath: string
|
||||
) {
|
||||
const cancelWait = wait('Adding your custom certificate');
|
||||
client.output.spinner('Adding your custom certificate');
|
||||
|
||||
try {
|
||||
const cert = readFileSync(resolve(certPath), 'utf8');
|
||||
@@ -36,7 +35,5 @@ export default async function createCertFromFile(
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
cancelWait();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import chalk from 'chalk';
|
||||
import { Cert } from '../../types';
|
||||
import * as ERRORS from '../errors-ts';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
import mapCertError from './map-cert-error';
|
||||
|
||||
export default async function startCertOrder(
|
||||
@@ -11,7 +10,7 @@ export default async function startCertOrder(
|
||||
cns: string[],
|
||||
context: string // eslint-disable-line
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Issuing a certificate for ${chalk.bold(cns.join(', '))}`
|
||||
);
|
||||
try {
|
||||
@@ -22,10 +21,8 @@ export default async function startCertOrder(
|
||||
domains: cns,
|
||||
},
|
||||
});
|
||||
cancelWait();
|
||||
return cert;
|
||||
} catch (error) {
|
||||
cancelWait();
|
||||
if (error.code === 'cert_order_not_found') {
|
||||
return new ERRORS.CertOrderNotFound(cns);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import chalk from 'chalk';
|
||||
import wait from '../output/wait';
|
||||
import Client from '../client';
|
||||
|
||||
export type CertificateChallenge = {
|
||||
@@ -24,23 +23,17 @@ export default async function startCertOrder(
|
||||
cns: string[],
|
||||
contextName: string
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Starting certificate issuance for ${chalk.bold(
|
||||
cns.join(', ')
|
||||
)} under ${chalk.bold(contextName)}`
|
||||
);
|
||||
try {
|
||||
const order = await client.fetch<CertificateOrder>('/v3/now/certs', {
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
op: 'startOrder',
|
||||
domains: cns
|
||||
}
|
||||
});
|
||||
cancelWait();
|
||||
return order;
|
||||
} catch (error) {
|
||||
cancelWait();
|
||||
throw error;
|
||||
}
|
||||
const order = await client.fetch<CertificateOrder>('/v3/now/certs', {
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
op: 'startOrder',
|
||||
domains: cns,
|
||||
},
|
||||
});
|
||||
return order;
|
||||
}
|
||||
|
||||
@@ -90,8 +90,10 @@ export default class Client extends EventEmitter {
|
||||
}
|
||||
|
||||
const headers = new Headers(opts.headers);
|
||||
headers.set('authorization', `Bearer ${this.authConfig.token}`);
|
||||
headers.set('user-agent', ua);
|
||||
if (this.authConfig.token) {
|
||||
headers.set('authorization', `Bearer ${this.authConfig.token}`);
|
||||
}
|
||||
|
||||
let body;
|
||||
if (isJSONObject(opts.body)) {
|
||||
@@ -163,7 +165,7 @@ export default class Client extends EventEmitter {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
this.authConfig.token = result;
|
||||
this.authConfig.token = result.token;
|
||||
writeToAuthConfigFile(this.authConfig);
|
||||
});
|
||||
|
||||
|
||||
@@ -3,17 +3,21 @@ import * as ERRORS_TS from '../errors-ts';
|
||||
import * as ERRORS from '../errors';
|
||||
import { NowError } from '../now-error';
|
||||
import mapCertError from '../certs/map-cert-error';
|
||||
import { Org } from '../../types';
|
||||
import Now from '..';
|
||||
import Client from '../client';
|
||||
import { DeploymentError } from '../../../../client/dist';
|
||||
|
||||
export default async function createDeploy(
|
||||
output,
|
||||
now,
|
||||
contextName,
|
||||
paths,
|
||||
createArgs,
|
||||
org,
|
||||
isSettingUpProject,
|
||||
cwd
|
||||
) {
|
||||
client: Client,
|
||||
now: Now,
|
||||
contextName: string,
|
||||
paths: string[],
|
||||
createArgs: any,
|
||||
org: Org | null,
|
||||
isSettingUpProject: boolean,
|
||||
cwd?: string
|
||||
): Promise<any | DeploymentError> {
|
||||
try {
|
||||
return await now.create(paths, createArgs, org, isSettingUpProject, cwd);
|
||||
} catch (error) {
|
||||
@@ -83,16 +87,17 @@ export default async function createDeploy(
|
||||
// If the cert is missing we try to generate a new one and the retry
|
||||
if (error.code === 'cert_missing') {
|
||||
const result = await generateCertForDeploy(
|
||||
output,
|
||||
now,
|
||||
client,
|
||||
contextName,
|
||||
error.value
|
||||
);
|
||||
|
||||
if (result instanceof NowError) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return createDeploy(
|
||||
output,
|
||||
client,
|
||||
now,
|
||||
contextName,
|
||||
paths,
|
||||
@@ -1,17 +1,16 @@
|
||||
import psl from 'psl';
|
||||
import { NowError } from '../now-error';
|
||||
import { Output } from '../output';
|
||||
import Client from '../client';
|
||||
import createCertForCns from '../certs/create-cert-for-cns';
|
||||
import setupDomain from '../domains/setup-domain';
|
||||
import { InvalidDomain } from '../errors-ts';
|
||||
|
||||
export default async function generateCertForDeploy(
|
||||
output: Output,
|
||||
client: Client,
|
||||
contextName: string,
|
||||
deployURL: string
|
||||
) {
|
||||
const { output } = client;
|
||||
const parsedDomain = psl.parse(deployURL);
|
||||
if (parsedDomain.error) {
|
||||
return new InvalidDomain(deployURL, parsedDomain.error.message);
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Output } from '../output';
|
||||
import Client from '../client';
|
||||
import getDomainDNSRecords from './get-domain-dns-records';
|
||||
import getDomains from '../domains/get-domains';
|
||||
import wait from '../output/wait';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export type DomainRecordsItem = {
|
||||
@@ -60,11 +59,7 @@ async function getDomainNames(
|
||||
contextName: string,
|
||||
next?: number
|
||||
) {
|
||||
const cancelWait = wait(`Fetching domains under ${chalk.bold(contextName)}`);
|
||||
try {
|
||||
const { domains, pagination } = await getDomains(client, next);
|
||||
return { domainNames: domains.map(domain => domain.name), pagination };
|
||||
} finally {
|
||||
cancelWait();
|
||||
}
|
||||
client.output.spinner(`Fetching domains under ${chalk.bold(contextName)}`);
|
||||
const { domains, pagination } = await getDomains(client, next);
|
||||
return { domainNames: domains.map(domain => domain.name), pagination };
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { resolve } from 'path';
|
||||
import { Response } from 'node-fetch';
|
||||
import { DomainNotFound, InvalidDomain } from '../errors-ts';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
|
||||
type JSONResponse = {
|
||||
recordIds: string[];
|
||||
@@ -16,7 +15,7 @@ export default async function importZonefile(
|
||||
domain: string,
|
||||
zonefilePath: string
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Importing Zone file for domain ${domain} under ${chalk.bold(contextName)}`
|
||||
);
|
||||
const zonefile = readFileSync(resolve(zonefilePath), 'utf8');
|
||||
@@ -33,10 +32,8 @@ export default async function importZonefile(
|
||||
);
|
||||
|
||||
const { recordIds } = (await res.json()) as JSONResponse;
|
||||
cancelWait();
|
||||
return recordIds;
|
||||
} catch (error) {
|
||||
cancelWait();
|
||||
if (error.code === 'not_found') {
|
||||
return new DomainNotFound(domain, contextName);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import retry from 'async-retry';
|
||||
import { DomainAlreadyExists, InvalidDomain } from '../errors-ts';
|
||||
import { Domain } from '../../types';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
|
||||
type Response = {
|
||||
domain: Domain;
|
||||
@@ -14,17 +13,11 @@ export default async function addDomain(
|
||||
domain: string,
|
||||
contextName: string
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Adding domain ${domain} under ${chalk.bold(contextName)}`
|
||||
);
|
||||
try {
|
||||
const addedDomain = await performAddRequest(client, domain);
|
||||
cancelWait();
|
||||
return addedDomain;
|
||||
} catch (error) {
|
||||
cancelWait();
|
||||
throw error;
|
||||
}
|
||||
const addedDomain = await performAddRequest(client, domain);
|
||||
return addedDomain;
|
||||
}
|
||||
|
||||
async function performAddRequest(client: Client, domainName: string) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import chalk from 'chalk';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
import { Domain } from '../../types';
|
||||
import { DomainPermissionDenied, DomainNotFound } from '../errors-ts';
|
||||
|
||||
@@ -16,14 +15,15 @@ export default async function getDomainByName(
|
||||
ignoreWait?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
const cancelWait = options.ignoreWait
|
||||
? null
|
||||
: wait(`Fetching domain ${domainName} under ${chalk.bold(contextName)}`);
|
||||
if (!options.ignoreWait) {
|
||||
client.output.spinner(
|
||||
`Fetching domain ${domainName} under ${chalk.bold(contextName)}`
|
||||
);
|
||||
}
|
||||
try {
|
||||
const { domain } = await client.fetch<Response>(
|
||||
`/v4/domains/${encodeURIComponent(domainName)}`
|
||||
);
|
||||
|
||||
return domain;
|
||||
} catch (error) {
|
||||
if (error.status === 404) {
|
||||
@@ -35,7 +35,5 @@ export default async function getDomainByName(
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
cancelWait?.();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import chalk from 'chalk';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
import { Domain } from '../../types';
|
||||
|
||||
type Response = {
|
||||
@@ -12,7 +11,7 @@ export async function getDomain(
|
||||
contextName: string,
|
||||
domainName: string
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Fetching domain ${domainName} under ${chalk.bold(contextName)}`
|
||||
);
|
||||
try {
|
||||
@@ -27,7 +26,5 @@ export async function getDomain(
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
cancelWait();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,22 +3,19 @@ import retry from 'async-retry';
|
||||
import { Domain } from '../../types';
|
||||
import * as ERRORS from '../errors-ts';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
|
||||
export default async function verifyDomain(
|
||||
client: Client,
|
||||
domainName: string,
|
||||
contextName: string
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Verifying domain ${domainName} under ${chalk.bold(contextName)}`
|
||||
);
|
||||
try {
|
||||
const { domain } = await performVerifyDomain(client, domainName);
|
||||
cancelWait();
|
||||
return domain;
|
||||
} catch (error) {
|
||||
cancelWait();
|
||||
if (error.code === 'verification_failed') {
|
||||
return new ERRORS.DomainVerificationFailed({
|
||||
purchased: false,
|
||||
|
||||
@@ -588,7 +588,7 @@ export class DeploymentNotFound extends NowError<
|
||||
'DEPLOYMENT_NOT_FOUND',
|
||||
{ id: string; context: string }
|
||||
> {
|
||||
constructor({ context, id = '' }: { context: string; id: string }) {
|
||||
constructor({ context, id = '' }: { context: string; id?: string }) {
|
||||
super({
|
||||
code: 'DEPLOYMENT_NOT_FOUND',
|
||||
meta: { id, context },
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
async function* eventListenerToGenerator(event: string, emitter: EventEmitter) {
|
||||
while (true) {
|
||||
yield new Promise(resolve => {
|
||||
const handler = (...args: any[]) => {
|
||||
emitter.removeListener(event, handler);
|
||||
resolve(...args);
|
||||
};
|
||||
emitter.on(event, handler);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default eventListenerToGenerator;
|
||||
@@ -20,6 +20,7 @@ export default class Now extends EventEmitter {
|
||||
constructor({
|
||||
apiUrl,
|
||||
token,
|
||||
url = null,
|
||||
currentTeam = null,
|
||||
forceNew = false,
|
||||
withCache = false,
|
||||
@@ -28,6 +29,7 @@ export default class Now extends EventEmitter {
|
||||
}) {
|
||||
super();
|
||||
|
||||
this.url = url;
|
||||
this._token = token;
|
||||
this._debug = debug;
|
||||
this._forceNew = forceNew;
|
||||
|
||||
@@ -22,7 +22,7 @@ export default async function editProjectSettings(
|
||||
output: Output,
|
||||
projectSettings: PartialProjectSettings | null,
|
||||
framework: Framework | null,
|
||||
autoConfirm: boolean
|
||||
autoConfirm?: boolean
|
||||
): Promise<ProjectSettings> {
|
||||
// create new settings object, missing values will be filled with `null`
|
||||
const settings: ProjectSettings = Object.assign(
|
||||
|
||||
@@ -177,7 +177,7 @@ export default async function setupAndLink(
|
||||
}
|
||||
|
||||
const deployment = await createDeploy(
|
||||
output,
|
||||
client,
|
||||
now,
|
||||
config.currentTeam || 'current user',
|
||||
[sourcePath],
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { URL } from 'url';
|
||||
import { LoginParams } from './types';
|
||||
import Client from '../client';
|
||||
import doOauthLogin from './oauth';
|
||||
|
||||
export default function doBitbucketLogin(params: LoginParams) {
|
||||
export default function doBitbucketLogin(client: Client, ssoUserId?: string) {
|
||||
const url = new URL(
|
||||
'/api/registration/bitbucket/connect',
|
||||
// Can't use `apiUrl` here because this URL sets a
|
||||
// cookie that the OAuth callback URL depends on
|
||||
'https://vercel.com'
|
||||
);
|
||||
return doOauthLogin(params, url, 'Bitbucket');
|
||||
return doOauthLogin(client, url, 'Bitbucket', ssoUserId);
|
||||
}
|
||||
|
||||
@@ -4,20 +4,22 @@ import highlight from '../output/highlight';
|
||||
import eraseLines from '../output/erase-lines';
|
||||
import verify from './verify';
|
||||
import executeLogin from './login';
|
||||
import { LoginParams } from './types';
|
||||
import Client from '../client';
|
||||
import { LoginResult } from './types';
|
||||
|
||||
export default async function doEmailLogin(
|
||||
params: LoginParams,
|
||||
email: string
|
||||
): Promise<number | string> {
|
||||
client: Client,
|
||||
email: string,
|
||||
ssoUserId?: string
|
||||
): Promise<LoginResult> {
|
||||
let securityCode;
|
||||
let verificationToken;
|
||||
const { apiUrl, output } = params;
|
||||
const { output } = client;
|
||||
|
||||
output.spinner('Sending you an email');
|
||||
|
||||
try {
|
||||
const data = await executeLogin(apiUrl, email);
|
||||
const data = await executeLogin(client, email);
|
||||
verificationToken = data.token;
|
||||
securityCode = data.securityCode;
|
||||
} catch (err) {
|
||||
@@ -42,9 +44,15 @@ export default async function doEmailLogin(
|
||||
while (!token) {
|
||||
try {
|
||||
await sleep(ms('1s'));
|
||||
token = await verify(email, verificationToken, 'Email', params);
|
||||
token = await verify(
|
||||
client,
|
||||
email,
|
||||
verificationToken,
|
||||
'Email',
|
||||
ssoUserId
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.message !== 'Confirmation incomplete') {
|
||||
if (err.serverMessage !== 'Confirmation incomplete') {
|
||||
output.error(err.message);
|
||||
return 1;
|
||||
}
|
||||
@@ -52,5 +60,5 @@ export default async function doEmailLogin(
|
||||
}
|
||||
|
||||
output.success(`Email authentication complete for ${email}`);
|
||||
return token;
|
||||
return { token };
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { URL } from 'url';
|
||||
import { LoginParams } from './types';
|
||||
import Client from '../client';
|
||||
import doOauthLogin from './oauth';
|
||||
|
||||
export default function doGithubLogin(params: LoginParams) {
|
||||
export default function doGithubLogin(client: Client, ssoUserId?: string) {
|
||||
const url = new URL(
|
||||
'/api/registration/login-with-github',
|
||||
// Can't use `apiUrl` here because this URL sets a
|
||||
// cookie that the OAuth callback URL depends on
|
||||
'https://vercel.com'
|
||||
);
|
||||
return doOauthLogin(params, url, 'GitHub');
|
||||
return doOauthLogin(client, url, 'GitHub', ssoUserId);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { URL } from 'url';
|
||||
import { LoginParams } from './types';
|
||||
import Client from '../client';
|
||||
import doOauthLogin from './oauth';
|
||||
|
||||
export default function doGitlabLogin(params: LoginParams) {
|
||||
export default function doGitlabLogin(client: Client, ssoUserId?: string) {
|
||||
// Can't use `apiUrl` here because this URL sets a
|
||||
// cookie that the OAuth callback URL depends on
|
||||
const url = new URL('/api/registration/gitlab/connect', 'https://vercel.com');
|
||||
return doOauthLogin(params, url, 'GitLab');
|
||||
return doOauthLogin(client, url, 'GitLab', ssoUserId);
|
||||
}
|
||||
|
||||
@@ -1,38 +1,28 @@
|
||||
import fetch from 'node-fetch';
|
||||
import Client from '../client';
|
||||
import { InvalidEmail, AccountNotFound } from '../errors-ts';
|
||||
import ua from '../ua';
|
||||
import { LoginData } from './types';
|
||||
|
||||
export default async function login(
|
||||
apiUrl: string,
|
||||
email: string,
|
||||
mode: 'login' | 'signup' = 'login'
|
||||
client: Client,
|
||||
email: string
|
||||
): Promise<LoginData> {
|
||||
const response = await fetch(`${apiUrl}/now/registration?mode=${mode}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': ua,
|
||||
},
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
const { error = {} } = body;
|
||||
if (error.code === 'not_exists') {
|
||||
try {
|
||||
return await client.fetch<LoginData>(`/registration?mode=login`, {
|
||||
method: 'POST',
|
||||
body: { email },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === 'not_exists') {
|
||||
throw new AccountNotFound(
|
||||
email,
|
||||
`Please sign up: https://vercel.com/signup`
|
||||
);
|
||||
}
|
||||
|
||||
if (error.code === 'invalid_email') {
|
||||
throw new InvalidEmail(email, error.message);
|
||||
if (err.code === 'invalid_email') {
|
||||
throw new InvalidEmail(email, err.message);
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected error: ${error.message}`);
|
||||
throw new Error(`Unexpected error: ${err.message}`);
|
||||
}
|
||||
|
||||
return body as LoginData;
|
||||
}
|
||||
|
||||
@@ -2,19 +2,21 @@ import http from 'http';
|
||||
import open from 'open';
|
||||
import { URL } from 'url';
|
||||
import listen from 'async-listen';
|
||||
import { LoginParams } from './types';
|
||||
import Client from '../client';
|
||||
import prompt from './prompt';
|
||||
import verify from './verify';
|
||||
import highlight from '../output/highlight';
|
||||
import link from '../output/link';
|
||||
import eraseLines from '../output/erase-lines';
|
||||
import { LoginResult } from './types';
|
||||
|
||||
export default async function doOauthLogin(
|
||||
params: LoginParams,
|
||||
client: Client,
|
||||
url: URL,
|
||||
provider: string
|
||||
): Promise<number | string> {
|
||||
const { output } = params;
|
||||
provider: string,
|
||||
ssoUserId?: string
|
||||
): Promise<LoginResult> {
|
||||
const { output } = client;
|
||||
|
||||
const server = http.createServer();
|
||||
const address = await listen(server, 0, '127.0.0.1');
|
||||
@@ -30,6 +32,10 @@ export default async function doOauthLogin(
|
||||
const [query] = await Promise.all([
|
||||
new Promise<URL['searchParams']>((resolve, reject) => {
|
||||
server.once('request', (req, res) => {
|
||||
// Close the HTTP connection to prevent
|
||||
// `server.close()` from hanging
|
||||
res.setHeader('connection', 'close');
|
||||
|
||||
const query = new URL(req.url || '/', 'http://localhost')
|
||||
.searchParams;
|
||||
resolve(query);
|
||||
@@ -85,16 +91,17 @@ export default async function doOauthLogin(
|
||||
// If an `ssoUserId` was returned, then the SAML Profile is not yet connected
|
||||
// to a Team member. Prompt the user to log in to a Vercel account now, which
|
||||
// will complete the connection to the SAML Profile.
|
||||
const ssoUserId = query.get('ssoUserId');
|
||||
if (ssoUserId) {
|
||||
const ssoUserIdParam = query.get('ssoUserId');
|
||||
if (ssoUserIdParam) {
|
||||
output.log(
|
||||
'Please log in to your Vercel account to complete SAML connection.'
|
||||
);
|
||||
return prompt({ ...params, ssoUserId });
|
||||
return prompt(client, undefined, ssoUserIdParam);
|
||||
}
|
||||
|
||||
const email = query.get('email');
|
||||
const verificationToken = query.get('token');
|
||||
const teamId = query.get('teamId');
|
||||
if (!email || !verificationToken) {
|
||||
output.error(
|
||||
'Verification token was not provided. Please contact support.'
|
||||
@@ -103,11 +110,17 @@ export default async function doOauthLogin(
|
||||
}
|
||||
|
||||
output.spinner('Verifying authentication token');
|
||||
const token = await verify(email, verificationToken, provider, params);
|
||||
const token = await verify(
|
||||
client,
|
||||
email,
|
||||
verificationToken,
|
||||
provider,
|
||||
ssoUserId
|
||||
);
|
||||
output.success(
|
||||
`${provider} authentication complete for ${highlight(email)}`
|
||||
);
|
||||
return token;
|
||||
return { token, teamId };
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import inquirer from 'inquirer';
|
||||
import Client from '../client';
|
||||
import error from '../output/error';
|
||||
import listInput from '../input/list';
|
||||
import { getCommandName } from '../pkg-name';
|
||||
import { LoginParams, SAMLError } from './types';
|
||||
import { LoginResult, SAMLError } from './types';
|
||||
import doSsoLogin from './sso';
|
||||
import doEmailLogin from './email';
|
||||
import doGithubLogin from './github';
|
||||
@@ -10,10 +11,11 @@ import doGitlabLogin from './gitlab';
|
||||
import doBitbucketLogin from './bitbucket';
|
||||
|
||||
export default async function prompt(
|
||||
params: LoginParams,
|
||||
error?: Pick<SAMLError, 'teamId'>
|
||||
client: Client,
|
||||
error?: Pick<SAMLError, 'teamId'>,
|
||||
ssoUserId?: string
|
||||
) {
|
||||
let result: number | string = 1;
|
||||
let result: LoginResult = 1;
|
||||
|
||||
const choices = [
|
||||
{ name: 'Continue with GitHub', value: 'github', short: 'github' },
|
||||
@@ -23,7 +25,7 @@ export default async function prompt(
|
||||
{ name: 'Continue with SAML Single Sign-On', value: 'sso', short: 'sso' },
|
||||
];
|
||||
|
||||
if (params.ssoUserId || (error && !error.teamId)) {
|
||||
if (ssoUserId || (error && !error.teamId)) {
|
||||
// Remove SAML login option if we're connecting SAML Profile,
|
||||
// or if this is a SAML error for a user / team without SAML
|
||||
choices.pop();
|
||||
@@ -35,17 +37,17 @@ export default async function prompt(
|
||||
});
|
||||
|
||||
if (choice === 'github') {
|
||||
result = await doGithubLogin(params);
|
||||
result = await doGithubLogin(client, ssoUserId);
|
||||
} else if (choice === 'gitlab') {
|
||||
result = await doGitlabLogin(params);
|
||||
result = await doGitlabLogin(client, ssoUserId);
|
||||
} else if (choice === 'bitbucket') {
|
||||
result = await doBitbucketLogin(params);
|
||||
result = await doBitbucketLogin(client, ssoUserId);
|
||||
} else if (choice === 'email') {
|
||||
const email = await readInput('Enter your email address');
|
||||
result = await doEmailLogin(params, email);
|
||||
result = await doEmailLogin(client, email, ssoUserId);
|
||||
} else if (choice === 'sso') {
|
||||
const slug = error?.teamId || (await readInput('Enter your Team slug'));
|
||||
result = await doSsoLogin(params, slug);
|
||||
result = await doSsoLogin(client, slug, ssoUserId);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
import { bold } from 'chalk';
|
||||
import doSsoLogin from './sso';
|
||||
import showLoginPrompt from './prompt';
|
||||
import { LoginParams, SAMLError } from './types';
|
||||
import { LoginResult, SAMLError } from './types';
|
||||
import confirm from '../input/confirm';
|
||||
import Client from '../client';
|
||||
|
||||
export default async function reauthenticate(
|
||||
params: LoginParams,
|
||||
client: Client,
|
||||
error: Pick<SAMLError, 'enforced' | 'scope' | 'teamId'>
|
||||
): Promise<string | number> {
|
||||
let result: string | number = 1;
|
||||
): Promise<LoginResult> {
|
||||
if (error.teamId && error.enforced) {
|
||||
// If team has SAML enforced then trigger the SSO login directly
|
||||
params.output.log(
|
||||
client.output.log(
|
||||
`You must re-authenticate with SAML to use ${bold(error.scope)} scope.`
|
||||
);
|
||||
if (await confirm(`Log in with SAML?`, true)) {
|
||||
result = await doSsoLogin(params, error.teamId);
|
||||
return doSsoLogin(client, error.teamId);
|
||||
}
|
||||
} else {
|
||||
// Personal account, or team that does not have SAML enforced
|
||||
params.output.log(
|
||||
client.output.log(
|
||||
`You must re-authenticate to use ${bold(error.scope)} scope.`
|
||||
);
|
||||
result = await showLoginPrompt(params, error);
|
||||
return showLoginPrompt(client, error);
|
||||
}
|
||||
return result;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { URL } from 'url';
|
||||
import { LoginParams } from './types';
|
||||
import Client from '../client';
|
||||
import doOauthLogin from './oauth';
|
||||
|
||||
export default function doSsoLogin(params: LoginParams, teamIdOrSlug: string) {
|
||||
const url = new URL('/auth/sso', params.apiUrl);
|
||||
export default function doSsoLogin(
|
||||
client: Client,
|
||||
teamIdOrSlug: string,
|
||||
ssoUserId?: string
|
||||
) {
|
||||
const url = new URL('/auth/sso', client.apiUrl);
|
||||
url.searchParams.set('teamId', teamIdOrSlug);
|
||||
return doOauthLogin(params, url, 'SAML Single Sign-On');
|
||||
return doOauthLogin(client, url, 'SAML Single Sign-On', ssoUserId);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { AuthConfig } from '../../types';
|
||||
import { Output } from '../output';
|
||||
|
||||
export interface LoginParams {
|
||||
authConfig: AuthConfig;
|
||||
apiUrl: string;
|
||||
output: Output;
|
||||
ssoUserId?: string;
|
||||
}
|
||||
|
||||
export interface LoginData {
|
||||
token: string;
|
||||
securityCode: string;
|
||||
}
|
||||
|
||||
export type LoginResult = number | LoginResultSuccess;
|
||||
|
||||
export interface LoginResultSuccess {
|
||||
token: string;
|
||||
teamId?: string | null;
|
||||
}
|
||||
|
||||
export interface VerifyData {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface SAMLError {
|
||||
saml?: true;
|
||||
teamId: string | null;
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
import { URL } from 'url';
|
||||
import fetch, { Headers } from 'node-fetch';
|
||||
import ua from '../ua';
|
||||
import { LoginParams } from './types';
|
||||
import Client from '../client';
|
||||
import { hostname } from 'os';
|
||||
import { getTitleName } from '../pkg-name';
|
||||
import { VerifyData } from './types';
|
||||
|
||||
export default async function verify(
|
||||
client: Client,
|
||||
email: string,
|
||||
verificationToken: string,
|
||||
provider: string,
|
||||
{ authConfig, apiUrl, ssoUserId }: LoginParams
|
||||
ssoUserId?: string
|
||||
): Promise<string> {
|
||||
const url = new URL('/registration/verify', apiUrl);
|
||||
const url = new URL('/registration/verify', client.apiUrl);
|
||||
url.searchParams.set('email', email);
|
||||
url.searchParams.set('token', verificationToken);
|
||||
|
||||
const headers = new Headers({ 'User-Agent': ua });
|
||||
|
||||
if (authConfig.token) {
|
||||
// If there is already an auth token then it will be
|
||||
// upgraded, rather than a new token being created
|
||||
headers.set('Authorization', `Bearer ${authConfig.token}`);
|
||||
} else {
|
||||
if (!client.authConfig.token) {
|
||||
// Set the "name" of the Token that will be created
|
||||
const hyphens = new RegExp('-', 'g');
|
||||
const host = hostname().replace(hyphens, ' ').replace('.local', '');
|
||||
@@ -35,16 +29,6 @@ export default async function verify(
|
||||
url.searchParams.set('ssoUserId', ssoUserId);
|
||||
}
|
||||
|
||||
const res = await fetch(url.href, { headers });
|
||||
const body = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
const err = new Error(
|
||||
`Unexpected ${res.status} status code from verify API`
|
||||
);
|
||||
Object.assign(err, body.error);
|
||||
throw err;
|
||||
}
|
||||
|
||||
return body.token;
|
||||
const { token } = await client.fetch<VerifyData>(url.href);
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import chalk from 'chalk';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
import { ProjectAliasTarget } from '../../types';
|
||||
|
||||
export async function addDomainToProject(
|
||||
@@ -8,7 +7,7 @@ export async function addDomainToProject(
|
||||
projectNameOrId: string,
|
||||
domain: string
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Adding domain ${domain} to project ${chalk.bold(projectNameOrId)}`
|
||||
);
|
||||
try {
|
||||
@@ -40,7 +39,5 @@ export async function addDomainToProject(
|
||||
}
|
||||
|
||||
throw err;
|
||||
} finally {
|
||||
cancelWait();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import chalk from 'chalk';
|
||||
import Client from '../client';
|
||||
import wait from '../output/wait';
|
||||
import { ProjectAliasTarget } from '../../types';
|
||||
|
||||
export async function removeDomainFromProject(
|
||||
@@ -8,7 +7,7 @@ export async function removeDomainFromProject(
|
||||
projectNameOrId: string,
|
||||
domain: string
|
||||
) {
|
||||
const cancelWait = wait(
|
||||
client.output.spinner(
|
||||
`Removing domain ${domain} from project ${chalk.bold(projectNameOrId)}`
|
||||
);
|
||||
try {
|
||||
@@ -28,7 +27,5 @@ export async function removeDomainFromProject(
|
||||
}
|
||||
|
||||
throw err;
|
||||
} finally {
|
||||
cancelWait();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { dep1 } from './js/ecmascript-module';
|
||||
|
||||
const { dep2 } = require('./js/commonjs-module');
|
||||
|
||||
module.exports = (req, res) => {
|
||||
if (req && typeof dep1 === 'string' && typeof dep2 === 'string') {
|
||||
res.end('mixed-modules:js');
|
||||
} else {
|
||||
res.end('import failed');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { dep1 } from './js/em-jay-ess.mjs';
|
||||
|
||||
async function handler(_req, res) {
|
||||
const cjs = await import('./js/commonjs-module.js');
|
||||
if (dep1 === 'dep1' && cjs.default && cjs.default.dep2 === 'dep2') {
|
||||
res.end('mixed-modules:mjs');
|
||||
} else {
|
||||
res.end('import failed');
|
||||
}
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -0,0 +1,11 @@
|
||||
import { IncomingMessage, ServerResponse } from 'http';
|
||||
import { dep1 } from './ts/ecmascript-module';
|
||||
const { dep2 } = require('./ts/commonjs-module');
|
||||
|
||||
module.exports = (req: IncomingMessage, res: ServerResponse) => {
|
||||
if (req && typeof dep1 === 'string' && typeof dep2 === 'string') {
|
||||
res.end('mixed-modules:ts');
|
||||
} else {
|
||||
res.end('import failed');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { dep2: 'dep2' };
|
||||
@@ -0,0 +1,2 @@
|
||||
export const dep1 = 'dep1';
|
||||
export const another = 'another';
|
||||
@@ -0,0 +1,2 @@
|
||||
export const dep1 = 'dep1';
|
||||
export const another = 'another';
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"private": true
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { dep2: 'dep2' };
|
||||
@@ -0,0 +1 @@
|
||||
export const dep1 = 'dep1';
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"private": true
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { dep1 } from '../js/em-jay-ess.mjs';
|
||||
|
||||
async function handler(_req, res) {
|
||||
const cjs = await import('../js/commonjs-module.js');
|
||||
if (dep1 === 'dep1' && cjs.default && cjs.default.dep2 === 'dep2') {
|
||||
res.end('mixed-modules:auto');
|
||||
} else {
|
||||
res.end('import failed');
|
||||
}
|
||||
}
|
||||
|
||||
export default handler;
|
||||
@@ -0,0 +1,12 @@
|
||||
import { dep1 } from '../../js/em-jay-ess.mjs';
|
||||
|
||||
async function handler(_req, res) {
|
||||
const cjs = await import('../../js/commonjs-module.js');
|
||||
if (dep1 === 'dep1' && cjs.default && cjs.default.dep2 === 'dep2') {
|
||||
res.end('mixed-modules:also');
|
||||
} else {
|
||||
res.end('import failed');
|
||||
}
|
||||
}
|
||||
|
||||
export default handler;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"private": true,
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 2,
|
||||
"builds": [
|
||||
{ "src": "entrypoint**", "use": "@vercel/node@canary" },
|
||||
{ "src": "type-module-package-json/**/*.js", "use": "@vercel/node@canary" }
|
||||
]
|
||||
}
|
||||
@@ -1732,6 +1732,25 @@ test(
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 40-mixed-modules',
|
||||
testFixtureStdio('40-mixed-modules', async testPath => {
|
||||
await testPath(200, '/entrypoint.js', 'mixed-modules:js');
|
||||
await testPath(200, '/entrypoint.mjs', 'mixed-modules:mjs');
|
||||
await testPath(200, '/entrypoint.ts', 'mixed-modules:ts');
|
||||
await testPath(
|
||||
200,
|
||||
'/type-module-package-json/auto.js',
|
||||
'mixed-modules:auto'
|
||||
);
|
||||
await testPath(
|
||||
200,
|
||||
'/type-module-package-json/nested/also.js',
|
||||
'mixed-modules:also'
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Use `@vercel/python` with Flask requirements.txt',
|
||||
testFixtureStdio('python-flask', async testPath => {
|
||||
|
||||
3
packages/cli/test/integration.js
vendored
3
packages/cli/test/integration.js
vendored
@@ -157,9 +157,10 @@ function mockLoginApi(req, res) {
|
||||
let { pathname = '/', query = {} } = parseUrl(url, true);
|
||||
console.log(`[mock-login-server] ${method} ${pathname}`);
|
||||
const securityCode = 'Bears Beets Battlestar Galactica';
|
||||
res.setHeader('content-type', 'application/json');
|
||||
if (
|
||||
method === 'POST' &&
|
||||
pathname === '/now/registration' &&
|
||||
pathname === '/registration' &&
|
||||
query.mode === 'login'
|
||||
) {
|
||||
res.end(JSON.stringify({ token, securityCode }));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/client",
|
||||
"version": "10.1.1",
|
||||
"version": "10.1.2-canary.2",
|
||||
"main": "dist/index.js",
|
||||
"typings": "dist/index.d.ts",
|
||||
"homepage": "https://vercel.com",
|
||||
@@ -29,7 +29,7 @@
|
||||
"@types/node": "12.0.4",
|
||||
"@types/node-fetch": "2.5.4",
|
||||
"@types/recursive-readdir": "2.2.0",
|
||||
"typescript": "3.9.3"
|
||||
"typescript": "4.3.4"
|
||||
},
|
||||
"jest": {
|
||||
"preset": "ts-jest",
|
||||
@@ -40,7 +40,7 @@
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"@vercel/build-utils": "2.11.1",
|
||||
"@vercel/build-utils": "2.11.2-canary.2",
|
||||
"@zeit/fetch": "5.2.0",
|
||||
"async-retry": "1.2.3",
|
||||
"async-sema": "3.0.0",
|
||||
|
||||
@@ -102,6 +102,7 @@ export const fileNameSymbol = Symbol('fileName');
|
||||
export interface VercelConfig {
|
||||
[fileNameSymbol]?: string;
|
||||
name?: string;
|
||||
meta?: string[];
|
||||
version?: number;
|
||||
public?: boolean;
|
||||
env?: Dictionary<string>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/frameworks",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.2-canary.1",
|
||||
"main": "./dist/frameworks.js",
|
||||
"types": "./dist/frameworks.d.ts",
|
||||
"files": [
|
||||
@@ -20,10 +20,10 @@
|
||||
"@types/js-yaml": "3.12.1",
|
||||
"@types/node": "12.0.4",
|
||||
"@types/node-fetch": "2.5.8",
|
||||
"@vercel/routing-utils": "1.11.2",
|
||||
"@vercel/routing-utils": "1.11.3-canary.0",
|
||||
"ajv": "6.12.2",
|
||||
"jest": "24.9.0",
|
||||
"ts-jest": "24.1.0",
|
||||
"typescript": "3.9.3"
|
||||
"typescript": "4.3.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,7 @@ export const frameworks = [
|
||||
devCommand: 'next dev --port $PORT',
|
||||
buildCommand: 'next build',
|
||||
getOutputDirName: async () => 'public',
|
||||
cachePattern: '.next/cache/**',
|
||||
},
|
||||
{
|
||||
name: 'Gatsby.js',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/go",
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.3-canary.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index",
|
||||
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/go",
|
||||
@@ -31,6 +31,6 @@
|
||||
"node-fetch": "^2.2.1",
|
||||
"string-argv": "0.3.1",
|
||||
"tar": "4.4.6",
|
||||
"typescript": "3.9.3"
|
||||
"typescript": "4.3.4"
|
||||
}
|
||||
}
|
||||
|
||||
2
packages/node-bridge/.gitignore
vendored
2
packages/node-bridge/.gitignore
vendored
@@ -1,2 +0,0 @@
|
||||
/bridge.*
|
||||
/launcher.*
|
||||
18
packages/node-bridge/bridge.d.ts
vendored
Normal file
18
packages/node-bridge/bridge.d.ts
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
/// <reference types="node" />
|
||||
import { Server } from 'http';
|
||||
import {
|
||||
VercelProxyRequest,
|
||||
VercelProxyResponse,
|
||||
VercelProxyEvent,
|
||||
ServerLike,
|
||||
} from './types';
|
||||
|
||||
export declare class Bridge {
|
||||
constructor(server?: ServerLike, shouldStoreEvents?: boolean);
|
||||
setServer(server: ServerLike): void;
|
||||
setStoreEvents(shouldStoreEvents: boolean): void;
|
||||
listen(): void | Server;
|
||||
launcher(event: VercelProxyEvent, context: any): Promise<VercelProxyResponse>;
|
||||
consumeEvent(reqId: string): VercelProxyRequest;
|
||||
}
|
||||
export {};
|
||||
@@ -1,43 +1,4 @@
|
||||
/// <reference types="node" />
|
||||
import { AddressInfo } from 'net';
|
||||
import { APIGatewayProxyEvent, Context } from 'aws-lambda';
|
||||
import {
|
||||
Server,
|
||||
IncomingHttpHeaders,
|
||||
OutgoingHttpHeaders,
|
||||
request,
|
||||
} from 'http';
|
||||
|
||||
interface NowProxyEvent {
|
||||
Action: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface NowProxyRequest {
|
||||
isApiGateway?: boolean;
|
||||
method: string;
|
||||
path: string;
|
||||
headers: IncomingHttpHeaders;
|
||||
body: Buffer;
|
||||
}
|
||||
|
||||
export interface NowProxyResponse {
|
||||
statusCode: number;
|
||||
headers: OutgoingHttpHeaders;
|
||||
body: string;
|
||||
encoding: BufferEncoding;
|
||||
}
|
||||
|
||||
interface ServerLike {
|
||||
timeout?: number;
|
||||
listen: (
|
||||
opts: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
},
|
||||
callback: (this: Server | null) => void
|
||||
) => Server | void;
|
||||
}
|
||||
const { request } = require('http');
|
||||
|
||||
/**
|
||||
* If the `http.Server` handler function throws an error asynchronously,
|
||||
@@ -51,8 +12,11 @@ process.on('unhandledRejection', err => {
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
function normalizeNowProxyEvent(event: NowProxyEvent): NowProxyRequest {
|
||||
let bodyBuffer: Buffer | null;
|
||||
/**
|
||||
* @param {import('./types').VercelProxyEvent} event
|
||||
*/
|
||||
function normalizeProxyEvent(event) {
|
||||
let bodyBuffer;
|
||||
const { method, path, headers, encoding, body } = JSON.parse(event.body);
|
||||
|
||||
if (body) {
|
||||
@@ -70,10 +34,11 @@ function normalizeNowProxyEvent(event: NowProxyEvent): NowProxyRequest {
|
||||
return { isApiGateway: false, method, path, headers, body: bodyBuffer };
|
||||
}
|
||||
|
||||
function normalizeAPIGatewayProxyEvent(
|
||||
event: APIGatewayProxyEvent
|
||||
): NowProxyRequest {
|
||||
let bodyBuffer: Buffer | null;
|
||||
/**
|
||||
* @param {import('aws-lambda').APIGatewayProxyEvent} event
|
||||
*/
|
||||
function normalizeAPIGatewayProxyEvent(event) {
|
||||
let bodyBuffer;
|
||||
const { httpMethod: method, path, headers, body } = event;
|
||||
|
||||
if (body) {
|
||||
@@ -89,12 +54,13 @@ function normalizeAPIGatewayProxyEvent(
|
||||
return { isApiGateway: true, method, path, headers, body: bodyBuffer };
|
||||
}
|
||||
|
||||
function normalizeEvent(
|
||||
event: NowProxyEvent | APIGatewayProxyEvent
|
||||
): NowProxyRequest {
|
||||
/**
|
||||
* @param {import('./types').VercelProxyEvent | import('aws-lambda').APIGatewayProxyEvent} event
|
||||
*/
|
||||
function normalizeEvent(event) {
|
||||
if ('Action' in event) {
|
||||
if (event.Action === 'Invoke') {
|
||||
return normalizeNowProxyEvent(event);
|
||||
return normalizeProxyEvent(event);
|
||||
} else {
|
||||
throw new Error(`Unexpected event.Action: ${event.Action}`);
|
||||
}
|
||||
@@ -103,35 +69,40 @@ function normalizeEvent(
|
||||
}
|
||||
}
|
||||
|
||||
export class Bridge {
|
||||
private server: ServerLike | null;
|
||||
private listening: Promise<AddressInfo>;
|
||||
private resolveListening: (info: AddressInfo) => void;
|
||||
private events: { [key: string]: NowProxyRequest } = {};
|
||||
private reqIdSeed = 1;
|
||||
private shouldStoreEvents = false;
|
||||
|
||||
constructor(server?: ServerLike, shouldStoreEvents = false) {
|
||||
this.server = null;
|
||||
class Bridge {
|
||||
/**
|
||||
* @param {import('./types').ServerLike | null} server
|
||||
* @param {boolean} shouldStoreEvents
|
||||
*/
|
||||
constructor(server = null, shouldStoreEvents = false) {
|
||||
this.server = server;
|
||||
this.shouldStoreEvents = shouldStoreEvents;
|
||||
if (server) {
|
||||
this.setServer(server);
|
||||
}
|
||||
this.launcher = this.launcher.bind(this);
|
||||
|
||||
// This is just to appease TypeScript strict mode, since it doesn't
|
||||
// understand that the Promise constructor is synchronous
|
||||
this.resolveListening = (_info: AddressInfo) => {}; // eslint-disable-line @typescript-eslint/no-unused-vars
|
||||
this.reqIdSeed = 1;
|
||||
/**
|
||||
* @type {{ [key: string]: import('./types').VercelProxyRequest }}
|
||||
*/
|
||||
this.events = {};
|
||||
|
||||
this.listening = new Promise(resolve => {
|
||||
this.resolveListening = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
setServer(server: ServerLike) {
|
||||
/**
|
||||
* @param {import('./types').ServerLike} server
|
||||
*/
|
||||
setServer(server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {boolean} shouldStoreEvents
|
||||
*/
|
||||
setStoreEvents(shouldStoreEvents) {
|
||||
this.shouldStoreEvents = shouldStoreEvents;
|
||||
}
|
||||
|
||||
listen() {
|
||||
const { server, resolveListening } = this;
|
||||
if (!server) {
|
||||
@@ -173,10 +144,13 @@ export class Bridge {
|
||||
);
|
||||
}
|
||||
|
||||
async launcher(
|
||||
event: NowProxyEvent | APIGatewayProxyEvent,
|
||||
context: Pick<Context, 'callbackWaitsForEmptyEventLoop'>
|
||||
): Promise<NowProxyResponse> {
|
||||
/**
|
||||
*
|
||||
* @param {import('./types').VercelProxyEvent | import('aws-lambda').APIGatewayProxyEvent} event
|
||||
* @param {import('aws-lambda').Context} context
|
||||
* @return {Promise<{statusCode: number, headers: import('http').IncomingHttpHeaders, body: string, encoding: 'base64'}>}
|
||||
*/
|
||||
async launcher(event, context) {
|
||||
context.callbackWaitsForEmptyEventLoop = false;
|
||||
const { port } = await this.listening;
|
||||
|
||||
@@ -194,7 +168,10 @@ export class Bridge {
|
||||
const opts = { hostname: '127.0.0.1', port, path, method };
|
||||
const req = request(opts, res => {
|
||||
const response = res;
|
||||
const respBodyChunks: Buffer[] = [];
|
||||
/**
|
||||
* @type {Buffer[]}
|
||||
*/
|
||||
const respBodyChunks = [];
|
||||
response.on('data', chunk => respBodyChunks.push(Buffer.from(chunk)));
|
||||
response.on('error', reject);
|
||||
response.on('end', () => {
|
||||
@@ -227,18 +204,14 @@ export class Bridge {
|
||||
for (const [name, value] of Object.entries(headers)) {
|
||||
if (value === undefined) {
|
||||
console.error(
|
||||
'Skipping HTTP request header %j because value is undefined',
|
||||
name
|
||||
`Skipping HTTP request header "${name}" because value is undefined`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
req.setHeader(name, value);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
'Skipping HTTP request header: %j',
|
||||
`${name}: ${value}`
|
||||
);
|
||||
console.error(`Skipping HTTP request header: "${name}: ${value}"`);
|
||||
console.error(err.message);
|
||||
}
|
||||
}
|
||||
@@ -248,9 +221,15 @@ export class Bridge {
|
||||
});
|
||||
}
|
||||
|
||||
consumeEvent(reqId: string) {
|
||||
/**
|
||||
* @param {string} reqId
|
||||
* @return {import('./types').VercelProxyRequest}
|
||||
*/
|
||||
consumeEvent(reqId) {
|
||||
const event = this.events[reqId];
|
||||
delete this.events[reqId];
|
||||
return event;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Bridge };
|
||||
16
packages/node-bridge/launcher.d.ts
vendored
Normal file
16
packages/node-bridge/launcher.d.ts
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Bridge } from './bridge';
|
||||
import { LauncherConfiguration } from './types';
|
||||
export declare function makeVercelLauncher(
|
||||
config: LauncherConfiguration
|
||||
): string;
|
||||
export declare function getVercelLauncher({
|
||||
entrypointPath,
|
||||
helpersPath,
|
||||
shouldAddHelpers,
|
||||
}: LauncherConfiguration): () => Bridge;
|
||||
export declare function makeAwsLauncher(config: LauncherConfiguration): string;
|
||||
export declare function getAwsLauncher({
|
||||
entrypointPath,
|
||||
awsLambdaHandler,
|
||||
}: LauncherConfiguration): (e: any, context: any, callback: any) => any;
|
||||
export {};
|
||||
181
packages/node-bridge/launcher.js
Normal file
181
packages/node-bridge/launcher.js
Normal file
@@ -0,0 +1,181 @@
|
||||
const { parse } = require('url');
|
||||
const { createServer, Server } = require('http');
|
||||
const { Bridge } = require('./bridge.js');
|
||||
|
||||
/**
|
||||
* @param {import('./types').LauncherConfiguration} config
|
||||
*/
|
||||
function makeVercelLauncher(config) {
|
||||
const {
|
||||
entrypointPath,
|
||||
bridgePath,
|
||||
helpersPath,
|
||||
sourcemapSupportPath,
|
||||
shouldAddHelpers = false,
|
||||
shouldAddSourcemapSupport = false,
|
||||
} = config;
|
||||
return `
|
||||
const { parse } = require('url');
|
||||
const { createServer, Server } = require('http');
|
||||
const { Bridge } = require(${JSON.stringify(bridgePath)});
|
||||
${
|
||||
shouldAddSourcemapSupport
|
||||
? `require(${JSON.stringify(sourcemapSupportPath)});`
|
||||
: ''
|
||||
}
|
||||
const entrypointPath = ${JSON.stringify(entrypointPath)};
|
||||
const shouldAddHelpers = ${JSON.stringify(shouldAddHelpers)};
|
||||
const helpersPath = ${JSON.stringify(helpersPath)};
|
||||
|
||||
const func = (${getVercelLauncher(config).toString()})();
|
||||
exports.launcher = func.launcher;`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('./types').LauncherConfiguration} config
|
||||
*/
|
||||
function getVercelLauncher({
|
||||
entrypointPath,
|
||||
helpersPath,
|
||||
shouldAddHelpers = false,
|
||||
}) {
|
||||
return function () {
|
||||
const bridge = new Bridge();
|
||||
let isServerListening = false;
|
||||
|
||||
const originalListen = Server.prototype.listen;
|
||||
Server.prototype.listen = function listen() {
|
||||
isServerListening = true;
|
||||
console.log('Legacy server listening...');
|
||||
bridge.setServer(this);
|
||||
Server.prototype.listen = originalListen;
|
||||
bridge.listen();
|
||||
return this;
|
||||
};
|
||||
|
||||
if (!process.env.NODE_ENV) {
|
||||
const region = process.env.VERCEL_REGION || process.env.NOW_REGION;
|
||||
process.env.NODE_ENV = region === 'dev1' ? 'development' : 'production';
|
||||
}
|
||||
|
||||
import(entrypointPath)
|
||||
.then(listener => {
|
||||
// In some cases we might have nested default props
|
||||
// due to TS => JS
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (listener.default) listener = listener.default;
|
||||
}
|
||||
|
||||
if (typeof listener.listen === 'function') {
|
||||
Server.prototype.listen = originalListen;
|
||||
const server = listener;
|
||||
bridge.setServer(server);
|
||||
bridge.listen();
|
||||
} else if (typeof listener === 'function') {
|
||||
Server.prototype.listen = originalListen;
|
||||
if (shouldAddHelpers) {
|
||||
bridge.setStoreEvents(true);
|
||||
import(helpersPath).then(helper => {
|
||||
const server = helper.createServerWithHelpers(listener, bridge);
|
||||
bridge.setServer(server);
|
||||
bridge.listen();
|
||||
});
|
||||
} else {
|
||||
const server = createServer(listener);
|
||||
bridge.setServer(server);
|
||||
bridge.listen();
|
||||
}
|
||||
} else if (
|
||||
typeof listener === 'object' &&
|
||||
Object.keys(listener).length === 0
|
||||
) {
|
||||
setTimeout(() => {
|
||||
if (!isServerListening) {
|
||||
console.error('No exports found in module %j.', entrypointPath);
|
||||
console.error('Did you forget to export a function or a server?');
|
||||
process.exit(1);
|
||||
}
|
||||
}, 5000);
|
||||
} else {
|
||||
console.error('Invalid export found in module %j.', entrypointPath);
|
||||
console.error('The default export must be a function or server.');
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
if (err.code === 'MODULE_NOT_FOUND') {
|
||||
console.error(err.message);
|
||||
console.error(
|
||||
'Did you forget to add it to "dependencies" in `package.json`?'
|
||||
);
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
return bridge;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('./types').LauncherConfiguration} config
|
||||
*/
|
||||
function makeAwsLauncher(config) {
|
||||
const { entrypointPath, awsLambdaHandler = '' } = config;
|
||||
return `const { parse } = require("url");
|
||||
const funcName = ${JSON.stringify(awsLambdaHandler.split('.').pop())};
|
||||
const entrypointPath = ${JSON.stringify(entrypointPath)};
|
||||
exports.launcher = ${getAwsLauncher(config).toString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('./types').LauncherConfiguration} config
|
||||
*/
|
||||
function getAwsLauncher({ entrypointPath, awsLambdaHandler = '' }) {
|
||||
const funcName = awsLambdaHandler.split('.').pop() || '';
|
||||
if (typeof funcName !== 'string') {
|
||||
throw new TypeError('Expected "string"');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('aws-lambda').APIGatewayProxyEvent} e
|
||||
* @param {import('aws-lambda').Context} context
|
||||
* @param {() => void} callback
|
||||
*/
|
||||
function internal(e, context, callback) {
|
||||
const { path, method: httpMethod, body, headers } = JSON.parse(
|
||||
e.body || '{}'
|
||||
);
|
||||
const { query } = parse(path, true);
|
||||
/**
|
||||
* @type {{[key: string]: string}}
|
||||
*/
|
||||
const queryStringParameters = {};
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
if (typeof value === 'string') {
|
||||
queryStringParameters[key] = value;
|
||||
}
|
||||
}
|
||||
const awsGatewayEvent = {
|
||||
resource: '/{proxy+}',
|
||||
path: path,
|
||||
httpMethod: httpMethod,
|
||||
body: body,
|
||||
isBase64Encoded: true,
|
||||
queryStringParameters: queryStringParameters,
|
||||
multiValueQueryStringParameters: query,
|
||||
headers: headers,
|
||||
};
|
||||
|
||||
const mod = require(entrypointPath);
|
||||
return mod[funcName](awsGatewayEvent, context, callback);
|
||||
}
|
||||
return internal;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
makeVercelLauncher,
|
||||
getVercelLauncher,
|
||||
makeAwsLauncher,
|
||||
getAwsLauncher,
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/node-bridge",
|
||||
"version": "1.3.3",
|
||||
"version": "2.0.1-canary.1",
|
||||
"license": "MIT",
|
||||
"main": "./index.js",
|
||||
"repository": {
|
||||
@@ -15,12 +15,11 @@
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test-integration-once": "jest --env node --verbose --runInBand --bail",
|
||||
"prepublish": "npm run build"
|
||||
"test-unit": "jest --env node --verbose --runInBand --bail"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/aws-lambda": "8.10.19",
|
||||
"@types/node": "10.x",
|
||||
"typescript": "3.9.3"
|
||||
"@types/node": "*",
|
||||
"typescript": "4.3.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
import { parse } from 'url';
|
||||
import { createServer, Server } from 'http';
|
||||
import { Bridge } from './bridge';
|
||||
|
||||
type LauncherConfiguration = {
|
||||
entrypointPath: string;
|
||||
bridgePath: string;
|
||||
helpersPath: string;
|
||||
sourcemapSupportPath: string;
|
||||
shouldAddHelpers?: boolean;
|
||||
shouldAddSourcemapSupport?: boolean;
|
||||
awsLambdaHandler?: string;
|
||||
};
|
||||
|
||||
export function makeVercelLauncher(config: LauncherConfiguration): string {
|
||||
const {
|
||||
entrypointPath,
|
||||
bridgePath,
|
||||
helpersPath,
|
||||
sourcemapSupportPath,
|
||||
shouldAddHelpers = false,
|
||||
shouldAddSourcemapSupport = false,
|
||||
} = config;
|
||||
return `const bridge_1 = require(${JSON.stringify(bridgePath)});
|
||||
const http_1 = require("http");
|
||||
${
|
||||
shouldAddSourcemapSupport
|
||||
? `require(${JSON.stringify(sourcemapSupportPath)});`
|
||||
: ''
|
||||
}
|
||||
const entrypointPath = ${JSON.stringify(entrypointPath)};
|
||||
const shouldAddHelpers = ${JSON.stringify(shouldAddHelpers)};
|
||||
const helpersPath = ${JSON.stringify(helpersPath)};
|
||||
|
||||
const bridge = (${getNowLauncher(config)})();
|
||||
exports.launcher = bridge.launcher;`;
|
||||
}
|
||||
|
||||
export function getNowLauncher({
|
||||
entrypointPath,
|
||||
helpersPath,
|
||||
shouldAddHelpers = false,
|
||||
}: LauncherConfiguration) {
|
||||
return function (): Bridge {
|
||||
let bridge = new Bridge();
|
||||
let isServerListening = false;
|
||||
|
||||
const originalListen = Server.prototype.listen;
|
||||
Server.prototype.listen = function listen() {
|
||||
isServerListening = true;
|
||||
console.log('Legacy server listening...');
|
||||
bridge.setServer(this);
|
||||
Server.prototype.listen = originalListen;
|
||||
bridge.listen();
|
||||
return this;
|
||||
};
|
||||
|
||||
if (!process.env.NODE_ENV) {
|
||||
const region = process.env.VERCEL_REGION || process.env.NOW_REGION;
|
||||
process.env.NODE_ENV = region === 'dev1' ? 'development' : 'production';
|
||||
}
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
let listener = require(entrypointPath);
|
||||
if (listener.default) listener = listener.default;
|
||||
|
||||
if (typeof listener.listen === 'function') {
|
||||
Server.prototype.listen = originalListen;
|
||||
const server = listener;
|
||||
bridge.setServer(server);
|
||||
bridge.listen();
|
||||
} else if (typeof listener === 'function') {
|
||||
Server.prototype.listen = originalListen;
|
||||
let server: Server;
|
||||
if (shouldAddHelpers) {
|
||||
bridge = new Bridge(undefined, true);
|
||||
server = require(helpersPath).createServerWithHelpers(
|
||||
listener,
|
||||
bridge
|
||||
);
|
||||
} else {
|
||||
server = createServer(listener);
|
||||
}
|
||||
bridge.setServer(server);
|
||||
bridge.listen();
|
||||
} else if (
|
||||
typeof listener === 'object' &&
|
||||
Object.keys(listener).length === 0
|
||||
) {
|
||||
setTimeout(() => {
|
||||
if (!isServerListening) {
|
||||
console.error('No exports found in module %j.', entrypointPath);
|
||||
console.error('Did you forget to export a function or a server?');
|
||||
process.exit(1);
|
||||
}
|
||||
}, 5000);
|
||||
} else {
|
||||
console.error('Invalid export found in module %j.', entrypointPath);
|
||||
console.error('The default export must be a function or server.');
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code === 'MODULE_NOT_FOUND') {
|
||||
console.error(err.message);
|
||||
console.error(
|
||||
'Did you forget to add it to "dependencies" in `package.json`?'
|
||||
);
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return bridge;
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAwsLauncher(config: LauncherConfiguration): string {
|
||||
const { entrypointPath, awsLambdaHandler = '' } = config;
|
||||
return `const url_1 = require("url");
|
||||
const funcName = ${JSON.stringify(awsLambdaHandler.split('.').pop())};
|
||||
const entrypointPath = ${JSON.stringify(entrypointPath)};
|
||||
exports.launcher = ${getAwsLauncher(config)}`;
|
||||
}
|
||||
|
||||
export function getAwsLauncher({
|
||||
entrypointPath,
|
||||
awsLambdaHandler = '',
|
||||
}: LauncherConfiguration) {
|
||||
const funcName = awsLambdaHandler.split('.').pop();
|
||||
if (typeof funcName !== 'string') {
|
||||
throw new TypeError('Expected "string"');
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
return function (e, context, callback) {
|
||||
const { path, method: httpMethod, body, headers } = JSON.parse(e.body);
|
||||
const { query } = parse(path, true);
|
||||
const queryStringParameters: { [i: string]: string } = {};
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
if (typeof value === 'string') {
|
||||
queryStringParameters[key] = value;
|
||||
}
|
||||
}
|
||||
const awsGatewayEvent = {
|
||||
resource: '/{proxy+}',
|
||||
path: path,
|
||||
httpMethod: httpMethod,
|
||||
body: body,
|
||||
isBase64Encoded: true,
|
||||
queryStringParameters: queryStringParameters,
|
||||
multiValueQueryStringParameters: query,
|
||||
headers: headers,
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const mod = require(entrypointPath);
|
||||
return mod[funcName](awsGatewayEvent, context, callback);
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"esModuleInterop": true,
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"lib": ["esnext"],
|
||||
"target": "esnext",
|
||||
"module": "commonjs",
|
||||
"outDir": ".",
|
||||
"noEmit": true,
|
||||
"noImplicitReturns": true,
|
||||
"strict": true,
|
||||
"sourceMap": true,
|
||||
"declaration": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"include": ["bridge.js", "launcher.js"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
||||
38
packages/node-bridge/types.ts
Normal file
38
packages/node-bridge/types.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/// <reference types="node" />
|
||||
import { Server, IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
|
||||
export interface VercelProxyEvent {
|
||||
Action: string;
|
||||
body: string;
|
||||
}
|
||||
export interface VercelProxyRequest {
|
||||
isApiGateway?: boolean;
|
||||
method: string;
|
||||
path: string;
|
||||
headers: IncomingHttpHeaders;
|
||||
body: Buffer;
|
||||
}
|
||||
export interface VercelProxyResponse {
|
||||
statusCode: number;
|
||||
headers: OutgoingHttpHeaders;
|
||||
body: string;
|
||||
encoding: BufferEncoding;
|
||||
}
|
||||
export interface ServerLike {
|
||||
timeout?: number;
|
||||
listen: (
|
||||
opts: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
},
|
||||
callback: (this: Server | null) => void
|
||||
) => Server | void;
|
||||
}
|
||||
export type LauncherConfiguration = {
|
||||
entrypointPath: string;
|
||||
bridgePath: string;
|
||||
helpersPath: string;
|
||||
sourcemapSupportPath: string;
|
||||
shouldAddHelpers?: boolean;
|
||||
shouldAddSourcemapSupport?: boolean;
|
||||
awsLambdaHandler?: string;
|
||||
};
|
||||
2
packages/node/.gitignore
vendored
2
packages/node/.gitignore
vendored
@@ -1,5 +1,3 @@
|
||||
/dist
|
||||
/src/bridge.ts
|
||||
/src/launcher.ts
|
||||
/test/fixtures/**/types.d.ts
|
||||
/test/fixtures/11-symlinks/symlink
|
||||
|
||||
@@ -8,15 +8,6 @@ async function main() {
|
||||
const outDir = join(__dirname, 'dist');
|
||||
const bridgeDir = join(__dirname, '../node-bridge');
|
||||
|
||||
// Copy shared dependencies
|
||||
await Promise.all([
|
||||
fs.copyFile(join(bridgeDir, 'src/bridge.ts'), join(srcDir, 'bridge.ts')),
|
||||
fs.copyFile(
|
||||
join(bridgeDir, 'src/launcher.ts'),
|
||||
join(srcDir, 'launcher.ts')
|
||||
),
|
||||
]);
|
||||
|
||||
// Start fresh
|
||||
await fs.remove(outDir);
|
||||
|
||||
@@ -25,6 +16,12 @@ async function main() {
|
||||
stdio: 'inherit',
|
||||
});
|
||||
|
||||
// Copy bridge and launcher as-is
|
||||
await Promise.all([
|
||||
fs.copyFile(join(bridgeDir, 'bridge.js'), join(outDir, 'bridge.js')),
|
||||
fs.copyFile(join(bridgeDir, 'launcher.js'), join(outDir, 'launcher.js')),
|
||||
]);
|
||||
|
||||
// Copy type file for ts test
|
||||
await fs.copyFile(
|
||||
join(outDir, 'types.d.ts'),
|
||||
@@ -53,6 +50,8 @@ async function main() {
|
||||
'build',
|
||||
join(srcDir, 'helpers.ts'),
|
||||
'-e',
|
||||
'@vercel/node-bridge',
|
||||
'-e',
|
||||
'@vercel/build-utils',
|
||||
'-e',
|
||||
'@now/build-utils',
|
||||
@@ -72,6 +71,8 @@ async function main() {
|
||||
'build',
|
||||
join(__dirname, '../../node_modules/source-map-support/register'),
|
||||
'-e',
|
||||
'@vercel/node-bridge',
|
||||
'-e',
|
||||
'@vercel/build-utils',
|
||||
'-e',
|
||||
'@now/build-utils',
|
||||
@@ -93,6 +94,8 @@ async function main() {
|
||||
'build',
|
||||
join(srcDir, 'index.ts'),
|
||||
'-e',
|
||||
'@vercel/node-bridge',
|
||||
'-e',
|
||||
'@vercel/build-utils',
|
||||
'-e',
|
||||
'@now/build-utils',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/node",
|
||||
"version": "1.11.1",
|
||||
"version": "1.11.2-canary.3",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index",
|
||||
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/node-js",
|
||||
@@ -21,7 +21,7 @@
|
||||
"dependencies": {
|
||||
"@types/node": "*",
|
||||
"ts-node": "8.9.1",
|
||||
"typescript": "3.9.3"
|
||||
"typescript": "4.3.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "7.5.0",
|
||||
@@ -34,6 +34,7 @@
|
||||
"@types/test-listen": "1.1.0",
|
||||
"@vercel/ncc": "0.24.0",
|
||||
"@vercel/nft": "0.13.1",
|
||||
"@vercel/node-bridge": "2.0.1-canary.1",
|
||||
"content-type": "1.0.4",
|
||||
"cookie": "0.4.0",
|
||||
"etag": "1.8.1",
|
||||
|
||||
@@ -13,76 +13,79 @@ import { register } from 'ts-node';
|
||||
|
||||
type TypescriptModule = typeof import('typescript');
|
||||
|
||||
const resolveTypescript = (p: string): string => {
|
||||
try {
|
||||
return require.resolve('typescript', {
|
||||
paths: [p],
|
||||
});
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const requireTypescript = (p: string): TypescriptModule => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return require(p) as TypescriptModule;
|
||||
};
|
||||
|
||||
let ts: TypescriptModule | null = null;
|
||||
|
||||
// Assume Node.js 12 as the lowest common denominator
|
||||
let target = 'ES2019';
|
||||
const nodeMajor = Number(process.versions.node.split('.')[0]);
|
||||
if (nodeMajor >= 14) {
|
||||
target = 'ES2020';
|
||||
}
|
||||
|
||||
// Use the project's version of Typescript if available and supports `target`
|
||||
let compiler = resolveTypescript(process.cwd());
|
||||
if (compiler) {
|
||||
ts = requireTypescript(compiler);
|
||||
if (!(target in ts.ScriptTarget)) {
|
||||
ts = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise fall back to using the copy that `@vercel/node` uses
|
||||
if (!ts) {
|
||||
compiler = resolveTypescript(join(__dirname, '..'));
|
||||
ts = requireTypescript(compiler);
|
||||
}
|
||||
|
||||
if (tsconfig) {
|
||||
try {
|
||||
const { config } = ts.readConfigFile(tsconfig, ts.sys.readFile);
|
||||
if (config?.compilerOptions?.target) {
|
||||
target = config.compilerOptions.target;
|
||||
if (!process.env.VERCEL_DEV_IS_ESM) {
|
||||
const resolveTypescript = (p: string): string => {
|
||||
try {
|
||||
return require.resolve('typescript', {
|
||||
paths: [p],
|
||||
});
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
console.error(`Error while parsing "${tsconfig}"`);
|
||||
throw err;
|
||||
};
|
||||
|
||||
const requireTypescript = (p: string): TypescriptModule => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return require(p) as TypescriptModule;
|
||||
};
|
||||
|
||||
let ts: TypescriptModule | null = null;
|
||||
|
||||
// Assume Node.js 12 as the lowest common denominator
|
||||
let target = 'ES2019';
|
||||
const nodeMajor = Number(process.versions.node.split('.')[0]);
|
||||
if (nodeMajor >= 14) {
|
||||
target = 'ES2020';
|
||||
}
|
||||
|
||||
// Use the project's version of Typescript if available and supports `target`
|
||||
let compiler = resolveTypescript(process.cwd());
|
||||
if (compiler) {
|
||||
ts = requireTypescript(compiler);
|
||||
if (!(target in ts.ScriptTarget)) {
|
||||
ts = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
register({
|
||||
compiler,
|
||||
compilerOptions: {
|
||||
allowJs: true,
|
||||
esModuleInterop: true,
|
||||
jsx: 'react',
|
||||
module: 'commonjs',
|
||||
target,
|
||||
},
|
||||
project: tsconfig || undefined, // Resolve `tsconfig.json` from entrypoint dir
|
||||
transpileOnly: true,
|
||||
});
|
||||
// Otherwise fall back to using the copy that `@vercel/node` uses
|
||||
if (!ts) {
|
||||
compiler = resolveTypescript(join(__dirname, '..'));
|
||||
ts = requireTypescript(compiler);
|
||||
}
|
||||
|
||||
if (tsconfig) {
|
||||
try {
|
||||
const { config } = ts.readConfigFile(tsconfig, ts.sys.readFile);
|
||||
if (config?.compilerOptions?.target) {
|
||||
target = config.compilerOptions.target;
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
console.error(`Error while parsing "${tsconfig}"`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
register({
|
||||
compiler,
|
||||
compilerOptions: {
|
||||
allowJs: true,
|
||||
esModuleInterop: true,
|
||||
jsx: 'react',
|
||||
module: 'commonjs',
|
||||
target,
|
||||
},
|
||||
project: tsconfig || undefined, // Resolve `tsconfig.json` from entrypoint dir
|
||||
transpileOnly: true,
|
||||
});
|
||||
}
|
||||
|
||||
import { createServer, Server, IncomingMessage, ServerResponse } from 'http';
|
||||
import { Readable } from 'stream';
|
||||
import { Bridge } from './bridge';
|
||||
import { getNowLauncher } from './launcher';
|
||||
import type { Bridge } from '@vercel/node-bridge/bridge';
|
||||
// @ts-ignore - copied to the `dist` output as-is
|
||||
import { getVercelLauncher } from './launcher.js';
|
||||
|
||||
function listen(server: Server, port: number, host: string): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
@@ -105,17 +108,16 @@ async function main() {
|
||||
config.helpers === false || buildEnv.NODEJS_HELPERS === '0'
|
||||
);
|
||||
|
||||
bridge = getNowLauncher({
|
||||
entrypointPath: join(process.cwd(), entrypoint!),
|
||||
helpersPath: './helpers',
|
||||
shouldAddHelpers,
|
||||
bridgePath: 'not used',
|
||||
sourcemapSupportPath: 'not used',
|
||||
})();
|
||||
|
||||
const proxyServer = createServer(onDevRequest);
|
||||
await listen(proxyServer, 0, '127.0.0.1');
|
||||
|
||||
const launcher = getVercelLauncher({
|
||||
entrypointPath: join(process.cwd(), entrypoint!),
|
||||
helpersPath: './helpers.js',
|
||||
shouldAddHelpers,
|
||||
});
|
||||
bridge = launcher();
|
||||
|
||||
const address = proxyServer.address();
|
||||
if (typeof process.send === 'function') {
|
||||
process.send(address);
|
||||
@@ -156,7 +158,7 @@ export async function onDevRequest(
|
||||
};
|
||||
if (!bridge) {
|
||||
res.statusCode = 500;
|
||||
res.end('Bridge is not defined');
|
||||
res.end('Bridge is not ready, please try again');
|
||||
return;
|
||||
}
|
||||
const result = await bridge.launcher(event, {
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
VercelRequestBody,
|
||||
} from './types';
|
||||
import { Server } from 'http';
|
||||
import { Bridge } from './bridge';
|
||||
import type { Bridge } from '@vercel/node-bridge/bridge';
|
||||
|
||||
function getBodyParser(req: VercelRequest, body: Buffer) {
|
||||
return function parseBody(): VercelRequestBody {
|
||||
|
||||
@@ -46,7 +46,10 @@ const {
|
||||
isSymbolicLink,
|
||||
walkParentDirs,
|
||||
} = buildUtils;
|
||||
import { makeVercelLauncher, makeAwsLauncher } from './launcher';
|
||||
|
||||
// @ts-ignore - copied to the `dist` output as-is
|
||||
import { makeVercelLauncher, makeAwsLauncher } from './launcher.js';
|
||||
|
||||
import { Register, register } from './typescript';
|
||||
|
||||
export { shouldServe };
|
||||
@@ -81,10 +84,10 @@ const tscPath = resolve(
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
const libPathRegEx = /^node_modules|[\/\\]node_modules[\/\\]/;
|
||||
|
||||
const LAUNCHER_FILENAME = '___vc_launcher';
|
||||
const BRIDGE_FILENAME = '___vc_bridge';
|
||||
const HELPERS_FILENAME = '___vc_helpers';
|
||||
const SOURCEMAP_SUPPORT_FILENAME = '___vc_sourcemap_support';
|
||||
const LAUNCHER_FILENAME = '__launcher.js';
|
||||
const BRIDGE_FILENAME = '__bridge.js';
|
||||
const HELPERS_FILENAME = '__helpers.js';
|
||||
const SOURCEMAP_SUPPORT_FILENAME = '__sourcemap_support.js';
|
||||
|
||||
async function downloadInstallAndBundle({
|
||||
files,
|
||||
@@ -117,6 +120,16 @@ async function downloadInstallAndBundle({
|
||||
return { entrypointPath, entrypointFsDirname, nodeVersion, spawnOpts };
|
||||
}
|
||||
|
||||
function renameTStoJS(path: string) {
|
||||
if (path.endsWith('.ts')) {
|
||||
return path.slice(0, -3) + '.js';
|
||||
}
|
||||
if (path.endsWith('.tsx')) {
|
||||
return path.slice(0, -4) + '.js';
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
async function compile(
|
||||
workPath: string,
|
||||
baseDir: string,
|
||||
@@ -133,6 +146,7 @@ async function compile(
|
||||
const sourceCache = new Map<string, string | Buffer | null>();
|
||||
const fsCache = new Map<string, File>();
|
||||
const tsCompiled = new Set<string>();
|
||||
const pkgCache = new Map<string, { type?: string }>();
|
||||
|
||||
let shouldAddSourcemapSupport = false;
|
||||
|
||||
@@ -172,9 +186,7 @@ async function compile(
|
||||
}
|
||||
const { code, map } = tsCompile(source, path);
|
||||
tsCompiled.add(relPath);
|
||||
preparedFiles[
|
||||
relPath.slice(0, -3 - Number(path.endsWith('x'))) + '.js.map'
|
||||
] = new FileBlob({
|
||||
preparedFiles[renameTStoJS(relPath) + '.map'] = new FileBlob({
|
||||
data: JSON.stringify(map),
|
||||
});
|
||||
source = code;
|
||||
@@ -256,17 +268,12 @@ async function compile(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Rename .ts -> .js (except for entry)
|
||||
// There is a bug on Windows where entrypoint uses forward slashes
|
||||
// and workPath uses backslashes so we use resolve before comparing.
|
||||
if (
|
||||
resolve(baseDir, path) !== resolve(workPath, entrypoint) &&
|
||||
tsCompiled.has(path)
|
||||
) {
|
||||
preparedFiles[
|
||||
path.slice(0, -3 - Number(path.endsWith('x'))) + '.js'
|
||||
] = entry;
|
||||
} else preparedFiles[path] = entry;
|
||||
|
||||
if (tsCompiled.has(path)) {
|
||||
preparedFiles[renameTStoJS(path)] = entry;
|
||||
} else {
|
||||
preparedFiles[path] = entry;
|
||||
}
|
||||
}
|
||||
|
||||
// Compile ES Modules into CommonJS
|
||||
@@ -274,11 +281,29 @@ async function compile(
|
||||
file =>
|
||||
!file.endsWith('.ts') &&
|
||||
!file.endsWith('.tsx') &&
|
||||
!file.endsWith('.mjs') &&
|
||||
!file.match(libPathRegEx)
|
||||
);
|
||||
if (esmPaths.length) {
|
||||
const babelCompile = require('./babel').compile;
|
||||
for (const path of esmPaths) {
|
||||
const pathDir = join(workPath, dirname(path));
|
||||
if (!pkgCache.has(pathDir)) {
|
||||
const pathToPkg = await walkParentDirs({
|
||||
base: workPath,
|
||||
start: pathDir,
|
||||
filename: 'package.json',
|
||||
});
|
||||
const pkg = pathToPkg ? require(pathToPkg) : {};
|
||||
pkgCache.set(pathDir, pkg);
|
||||
}
|
||||
const pkg = pkgCache.get(pathDir) || {};
|
||||
if (pkg.type === 'module' && path.endsWith('.js')) {
|
||||
// Found parent package.json indicating this file is already ESM
|
||||
// so we should not transpile to CJS.
|
||||
// https://nodejs.org/api/packages.html#packages_type
|
||||
continue;
|
||||
}
|
||||
const filename = basename(path);
|
||||
const { data: source } = await FileBlob.fromStream({
|
||||
stream: preparedFiles[path].toStream(),
|
||||
@@ -366,33 +391,40 @@ export async function build({
|
||||
);
|
||||
debug(`Trace complete [${Date.now() - traceTime}ms]`);
|
||||
|
||||
const getFileName = (str: string) => `___vc/${str}`;
|
||||
|
||||
const launcher = awsLambdaHandler ? makeAwsLauncher : makeVercelLauncher;
|
||||
|
||||
const launcherSource = launcher({
|
||||
entrypointPath: `../${renameTStoJS(relative(baseDir, entrypointPath))}`,
|
||||
bridgePath: `./${BRIDGE_FILENAME}`,
|
||||
helpersPath: `./${HELPERS_FILENAME}`,
|
||||
sourcemapSupportPath: `./${SOURCEMAP_SUPPORT_FILENAME}`,
|
||||
shouldAddHelpers,
|
||||
shouldAddSourcemapSupport,
|
||||
awsLambdaHandler,
|
||||
});
|
||||
|
||||
const launcherFiles: Files = {
|
||||
[`${LAUNCHER_FILENAME}.js`]: new FileBlob({
|
||||
data: launcher({
|
||||
entrypointPath: `./${relative(baseDir, entrypointPath)}`,
|
||||
bridgePath: `./${BRIDGE_FILENAME}`,
|
||||
helpersPath: `./${HELPERS_FILENAME}`,
|
||||
sourcemapSupportPath: `./${SOURCEMAP_SUPPORT_FILENAME}`,
|
||||
shouldAddHelpers,
|
||||
shouldAddSourcemapSupport,
|
||||
awsLambdaHandler,
|
||||
}),
|
||||
[getFileName('package.json')]: new FileBlob({
|
||||
data: JSON.stringify({ type: 'commonjs' }),
|
||||
}),
|
||||
[`${BRIDGE_FILENAME}.js`]: new FileFsRef({
|
||||
[getFileName(LAUNCHER_FILENAME)]: new FileBlob({
|
||||
data: launcherSource,
|
||||
}),
|
||||
[getFileName(BRIDGE_FILENAME)]: new FileFsRef({
|
||||
fsPath: join(__dirname, 'bridge.js'),
|
||||
}),
|
||||
};
|
||||
|
||||
if (shouldAddSourcemapSupport) {
|
||||
launcherFiles[`${SOURCEMAP_SUPPORT_FILENAME}.js`] = new FileFsRef({
|
||||
launcherFiles[getFileName(SOURCEMAP_SUPPORT_FILENAME)] = new FileFsRef({
|
||||
fsPath: join(__dirname, 'source-map-support.js'),
|
||||
});
|
||||
}
|
||||
|
||||
if (shouldAddHelpers) {
|
||||
launcherFiles[`${HELPERS_FILENAME}.js`] = new FileFsRef({
|
||||
launcherFiles[getFileName(HELPERS_FILENAME)] = new FileFsRef({
|
||||
fsPath: join(__dirname, 'helpers.js'),
|
||||
});
|
||||
}
|
||||
@@ -402,7 +434,7 @@ export async function build({
|
||||
...preparedFiles,
|
||||
...launcherFiles,
|
||||
},
|
||||
handler: `${LAUNCHER_FILENAME}.launcher`,
|
||||
handler: `${getFileName(LAUNCHER_FILENAME).slice(0, -3)}.launcher`,
|
||||
runtime: nodeVersion.runtime,
|
||||
});
|
||||
|
||||
@@ -420,13 +452,21 @@ export async function startDevServer(
|
||||
opts: StartDevServerOptions
|
||||
): Promise<StartDevServerResult> {
|
||||
const { entrypoint, workPath, config, meta = {} } = opts;
|
||||
|
||||
// Find the `tsconfig.json` file closest to the entrypoint file
|
||||
const entryDir = join(workPath, dirname(entrypoint));
|
||||
const projectTsConfig = await walkParentDirs({
|
||||
base: workPath,
|
||||
start: join(workPath, dirname(entrypoint)),
|
||||
start: entryDir,
|
||||
filename: 'tsconfig.json',
|
||||
});
|
||||
const pathToPkg = await walkParentDirs({
|
||||
base: workPath,
|
||||
start: entryDir,
|
||||
filename: 'package.json',
|
||||
});
|
||||
const pkg = pathToPkg ? require(pathToPkg) : {};
|
||||
const isEsm =
|
||||
entrypoint.endsWith('.mjs') ||
|
||||
(pkg.type === 'module' && entrypoint.endsWith('.js'));
|
||||
|
||||
const devServerPath = join(__dirname, 'dev-server.js');
|
||||
const child = fork(devServerPath, [], {
|
||||
@@ -437,6 +477,7 @@ export async function startDevServer(
|
||||
...meta.env,
|
||||
VERCEL_DEV_ENTRYPOINT: entrypoint,
|
||||
VERCEL_DEV_TSCONFIG: projectTsConfig || '',
|
||||
VERCEL_DEV_IS_ESM: isEsm ? '1' : undefined,
|
||||
VERCEL_DEV_CONFIG: JSON.stringify(config),
|
||||
VERCEL_DEV_BUILD_ENV: JSON.stringify(meta.buildEnv || {}),
|
||||
},
|
||||
|
||||
@@ -59,7 +59,7 @@ interface Options {
|
||||
compiler?: string;
|
||||
ignore?: string[];
|
||||
project?: string;
|
||||
compilerOptions?: object;
|
||||
compilerOptions?: any;
|
||||
ignoreDiagnostics?: Array<number | string>;
|
||||
readFile?: (path: string) => string | undefined;
|
||||
fileExists?: (path: string) => boolean;
|
||||
@@ -214,7 +214,7 @@ export function register(opts: Options = {}): Register {
|
||||
/**
|
||||
* Create the basic required function using transpile mode.
|
||||
*/
|
||||
const getOutput = function(code: string, fileName: string): SourceOutput {
|
||||
const getOutput = function (code: string, fileName: string): SourceOutput {
|
||||
const result = ts.transpileModule(code, {
|
||||
fileName,
|
||||
transformers,
|
||||
@@ -284,7 +284,7 @@ export function register(opts: Options = {}): Register {
|
||||
const service = ts.createLanguageService(serviceHost, registry);
|
||||
|
||||
// Set the file contents into cache manually.
|
||||
const updateMemoryCache = function(contents: string, fileName: string) {
|
||||
const updateMemoryCache = function (contents: string, fileName: string) {
|
||||
const fileVersion = memoryCache.fileVersions.get(fileName) || 0;
|
||||
|
||||
// Avoid incrementing cache when nothing has changed.
|
||||
@@ -294,7 +294,7 @@ export function register(opts: Options = {}): Register {
|
||||
memoryCache.fileContents.set(fileName, contents);
|
||||
};
|
||||
|
||||
getOutputTypeCheck = function(code: string, fileName: string) {
|
||||
getOutputTypeCheck = function (code: string, fileName: string) {
|
||||
updateMemoryCache(code, fileName);
|
||||
|
||||
const output = service.getEmitOutput(fileName);
|
||||
@@ -430,9 +430,9 @@ export function register(opts: Options = {}): Register {
|
||||
): SourceOutput {
|
||||
const configFileName = detectConfig();
|
||||
const build = getBuild(configFileName);
|
||||
const { code: value, map: sourceMap } = (skipTypeCheck
|
||||
? build.getOutput
|
||||
: build.getOutputTypeCheck)(code, fileName);
|
||||
const { code: value, map: sourceMap } = (
|
||||
skipTypeCheck ? build.getOutput : build.getOutputTypeCheck
|
||||
)(code, fileName);
|
||||
const output = {
|
||||
code: value,
|
||||
map: Object.assign(JSON.parse(sourceMap), {
|
||||
|
||||
12
packages/node/test/fixtures/20-mixed-modules/entrypoint.mjs
vendored
Normal file
12
packages/node/test/fixtures/20-mixed-modules/entrypoint.mjs
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import { dep1 } from './js/em-jay-ess.mjs';
|
||||
|
||||
async function handler(_req, res) {
|
||||
const cjs = await import('./js/commonjs-module.js');
|
||||
if (dep1 === 'dep1' && cjs?.default?.dep2 === 'dep2') {
|
||||
res.end('mixed-modules:mjs:RANDOMNESS_PLACEHOLDER');
|
||||
} else {
|
||||
res.end('import failed');
|
||||
}
|
||||
};
|
||||
|
||||
export default handler;
|
||||
2
packages/node/test/fixtures/20-mixed-modules/js/em-jay-ess.mjs
vendored
Normal file
2
packages/node/test/fixtures/20-mixed-modules/js/em-jay-ess.mjs
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export const dep1 = 'dep1';
|
||||
export const another = 'another';
|
||||
12
packages/node/test/fixtures/20-mixed-modules/type-module-package-json/auto.js
vendored
Normal file
12
packages/node/test/fixtures/20-mixed-modules/type-module-package-json/auto.js
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import { dep1 } from '../js/em-jay-ess.mjs';
|
||||
|
||||
async function handler(_req, res) {
|
||||
const cjs = await import('../js/commonjs-module.js');
|
||||
if (dep1 === 'dep1' && cjs?.default?.dep2 === 'dep2') {
|
||||
res.end('mixed-modules:auto:RANDOMNESS_PLACEHOLDER');
|
||||
} else {
|
||||
res.end('import failed');
|
||||
}
|
||||
}
|
||||
|
||||
export default handler;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user