mirror of
https://github.com/LukeHagar/vercel.git
synced 2025-12-11 04:22:13 +00:00
Compare commits
18 Commits
@now/node-
...
@now/optip
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8a5da6a3e | ||
|
|
48f7b72bb2 | ||
|
|
8e2d5de446 | ||
|
|
2b3efb06be | ||
|
|
13e57bf68f | ||
|
|
dc3f112d4f | ||
|
|
da1c423033 | ||
|
|
5e1d58f0e8 | ||
|
|
8940f7fa33 | ||
|
|
0aeecd81d3 | ||
|
|
bd4cb3d2a0 | ||
|
|
b3d14f536d | ||
|
|
445d4d84cb | ||
|
|
30d4ec8cbd | ||
|
|
51355c263c | ||
|
|
ec6d695f24 | ||
|
|
da910dc097 | ||
|
|
00cb55f953 |
@@ -1,3 +1,4 @@
|
||||
{
|
||||
"singleQuote": true
|
||||
"singleQuote": true,
|
||||
"trailingComma": "es5"
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@
|
||||
"prettier --write",
|
||||
"eslint --fix",
|
||||
"git add"
|
||||
],
|
||||
"*.ts": [
|
||||
"prettier --write",
|
||||
"git add"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/bash",
|
||||
"version": "0.1.5-canary.1",
|
||||
"version": "0.2.0",
|
||||
"description": "Now 2.0 builder for HTTP endpoints written in Bash",
|
||||
"main": "index.js",
|
||||
"author": "Nathan Rajlich <nate@zeit.co>",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/build-utils",
|
||||
"version": "0.4.41-canary.7",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.js",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import path from 'path';
|
||||
import FileFsRef from '../file-fs-ref';
|
||||
import { File, Files } from '../types';
|
||||
import { mkdirp, readlink, symlink } from 'fs-extra';
|
||||
import { File, Files, Meta } from '../types';
|
||||
import { remove, mkdirp, readlink, symlink } from 'fs-extra';
|
||||
|
||||
export interface DownloadedFiles {
|
||||
[filePath: string]: FileFsRef
|
||||
@@ -29,13 +29,31 @@ async function downloadFile(file: File, fsPath: string): Promise<FileFsRef> {
|
||||
}
|
||||
}
|
||||
|
||||
export default async function download(files: Files, basePath: string): Promise<DownloadedFiles> {
|
||||
async function removeFile(basePath: string, fileMatched: string) {
|
||||
const file = path.join(basePath, fileMatched);
|
||||
await remove(file);
|
||||
}
|
||||
|
||||
export default async function download(files: Files, basePath: string, meta?: Meta): Promise<DownloadedFiles> {
|
||||
const files2: DownloadedFiles = {};
|
||||
const { filesChanged = null, filesRemoved = null } = meta || {};
|
||||
|
||||
await Promise.all(
|
||||
Object.keys(files).map(async (name) => {
|
||||
// If the file does not exist anymore, remove it.
|
||||
if (Array.isArray(filesRemoved) && filesRemoved.includes(name)) {
|
||||
await removeFile(basePath, name);
|
||||
return;
|
||||
}
|
||||
|
||||
// If a file didn't change, do not re-download it.
|
||||
if (Array.isArray(filesChanged) && !filesChanged.includes(name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const file = files[name];
|
||||
const fsPath = path.join(basePath, name);
|
||||
|
||||
files2[name] = await downloadFile(file, fsPath);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -112,7 +112,11 @@ export async function installDependencies(destPath: string, args: string[] = [])
|
||||
}
|
||||
}
|
||||
|
||||
export async function runPackageJsonScript(destPath: string, scriptName: string) {
|
||||
export async function runPackageJsonScript(
|
||||
destPath: string,
|
||||
scriptName: string,
|
||||
opts?: SpawnOptions
|
||||
) {
|
||||
assert(path.isAbsolute(destPath));
|
||||
const { hasScript, hasPackageLockJson } = await scanParentDirs(
|
||||
destPath,
|
||||
@@ -122,10 +126,10 @@ export async function runPackageJsonScript(destPath: string, scriptName: string)
|
||||
|
||||
if (hasPackageLockJson) {
|
||||
console.log(`running "npm run ${scriptName}"`);
|
||||
await spawnAsync('npm', ['run', scriptName], destPath);
|
||||
await spawnAsync('npm', ['run', scriptName], destPath, opts);
|
||||
} else {
|
||||
console.log(`running "yarn run ${scriptName}"`);
|
||||
await spawnAsync('yarn', ['--cwd', destPath, 'run', scriptName], destPath);
|
||||
await spawnAsync('yarn', ['--cwd', destPath, 'run', scriptName], destPath, opts);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import FileRef from "./file-ref";
|
||||
import FileRef from './file-ref';
|
||||
import FileFsRef from './file-fs-ref';
|
||||
|
||||
export interface File {
|
||||
@@ -9,11 +9,11 @@ export interface File {
|
||||
}
|
||||
|
||||
export interface Files {
|
||||
[filePath: string]: File
|
||||
[filePath: string]: File;
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
[key: string]: string
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
export interface Meta {
|
||||
@@ -29,7 +29,7 @@ export interface AnalyzeOptions {
|
||||
*/
|
||||
files: {
|
||||
[filePath: string]: FileRef;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Name of entrypoint file for this particular build job. Value
|
||||
@@ -52,7 +52,6 @@ export interface AnalyzeOptions {
|
||||
config: Config;
|
||||
}
|
||||
|
||||
|
||||
export interface BuildOptions {
|
||||
/**
|
||||
* All source files of the project
|
||||
@@ -138,9 +137,15 @@ export interface ShouldServeOptions {
|
||||
* All source files of the project
|
||||
*/
|
||||
files: {
|
||||
[path: string]: FileFsRef
|
||||
[path: string]: FileFsRef;
|
||||
};
|
||||
|
||||
/**
|
||||
* A writable temporary directory where you are encouraged to perform your
|
||||
* build process. This directory will be populated with the restored cache.
|
||||
*/
|
||||
workPath: string;
|
||||
|
||||
/**
|
||||
* An arbitrary object passed by the user in the build definition defined
|
||||
* in `now.json`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/cgi",
|
||||
"version": "0.0.16-canary.0",
|
||||
"version": "0.1.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/go",
|
||||
"version": "0.3.1-canary.3",
|
||||
"version": "0.4.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/html-minifier",
|
||||
"version": "1.0.8-canary.1",
|
||||
"version": "1.1.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/lambda",
|
||||
"version": "0.4.10-canary.1",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/md",
|
||||
"version": "0.4.10-canary.2",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/mdx-deck",
|
||||
"version": "0.4.19-canary.2",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/next",
|
||||
"version": "0.2.0-canary.40",
|
||||
"version": "0.2.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index",
|
||||
"scripts": {
|
||||
@@ -14,10 +14,10 @@
|
||||
"directory": "packages/now-next"
|
||||
},
|
||||
"dependencies": {
|
||||
"@now/node-bridge": "^1.0.2-canary.2",
|
||||
"@now/node-bridge": "^1.1.0",
|
||||
"fs-extra": "^7.0.0",
|
||||
"get-port": "^5.0.0",
|
||||
"resolve-from": "^4.0.0",
|
||||
"resolve-from": "^5.0.0",
|
||||
"semver": "^5.6.0"
|
||||
},
|
||||
"files": [
|
||||
@@ -25,7 +25,7 @@
|
||||
],
|
||||
"devDependencies": {
|
||||
"@types/next-server": "^8.0.0",
|
||||
"@types/resolve-from": "^4.0.0",
|
||||
"@types/resolve-from": "^5.0.1",
|
||||
"@types/semver": "^6.0.0",
|
||||
"jest": "^24.7.1",
|
||||
"typescript": "^3.4.3"
|
||||
|
||||
@@ -7,18 +7,9 @@ export interface ProcessEnv {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
async function main(env: ProcessEnv) {
|
||||
const { ENTRY_PATH } = env;
|
||||
|
||||
if (!ENTRY_PATH) {
|
||||
console.error('No ENTRY_PATH defined');
|
||||
process.exit(1);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const next = require(resolveFrom(ENTRY_PATH, 'next'));
|
||||
const app = next({ dev: true, dir: ENTRY_PATH });
|
||||
async function main(env: ProcessEnv, cwd: string) {
|
||||
const next = require(resolveFrom(cwd, 'next'));
|
||||
const app = next({ dev: true, dir: cwd });
|
||||
const handler = app.getRequestHandler();
|
||||
|
||||
const openPort = await getPort({
|
||||
@@ -47,4 +38,4 @@ async function main(env: ProcessEnv) {
|
||||
});
|
||||
}
|
||||
|
||||
main(process.env as ProcessEnv);
|
||||
main(process.env as ProcessEnv, process.cwd());
|
||||
|
||||
@@ -1,51 +1,51 @@
|
||||
import { ChildProcess, fork, SpawnOptions } from 'child_process';
|
||||
import {
|
||||
pathExists,
|
||||
readFile,
|
||||
unlink as unlinkFile,
|
||||
writeFile,
|
||||
} from 'fs-extra';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import semver from 'semver';
|
||||
|
||||
import {
|
||||
BuildOptions,
|
||||
createLambda,
|
||||
download,
|
||||
FileFsRef,
|
||||
FileBlob,
|
||||
FileFsRef,
|
||||
Files,
|
||||
glob,
|
||||
Lambda,
|
||||
PrepareCacheOptions,
|
||||
runNpmInstall,
|
||||
runPackageJsonScript,
|
||||
Lambda,
|
||||
Files,
|
||||
BuildOptions,
|
||||
PrepareCacheOptions,
|
||||
} from '@now/build-utils';
|
||||
import resolveFrom from 'resolve-from';
|
||||
import path from 'path';
|
||||
import { fork } from 'child_process';
|
||||
import {
|
||||
readFile,
|
||||
writeFile,
|
||||
unlink as unlinkFile,
|
||||
remove as removePath,
|
||||
pathExists,
|
||||
} from 'fs-extra';
|
||||
import semver from 'semver';
|
||||
|
||||
import nextLegacyVersions from './legacy-versions';
|
||||
import {
|
||||
excludeFiles,
|
||||
validateEntrypoint,
|
||||
includeOnlyEntryDirectory,
|
||||
normalizePackageJson,
|
||||
onlyStaticDirectory,
|
||||
getNextConfig,
|
||||
getPathsInside,
|
||||
getRoutes,
|
||||
includeOnlyEntryDirectory,
|
||||
normalizePackageJson,
|
||||
onlyStaticDirectory,
|
||||
stringMap,
|
||||
validateEntrypoint,
|
||||
} from './utils';
|
||||
|
||||
interface BuildParamsMeta {
|
||||
isDev: boolean | undefined,
|
||||
requestPath: string | undefined,
|
||||
};
|
||||
isDev: boolean | undefined;
|
||||
}
|
||||
|
||||
interface BuildParamsType extends BuildOptions {
|
||||
files: Files,
|
||||
entrypoint: string,
|
||||
workPath: string,
|
||||
meta: BuildParamsMeta,
|
||||
};
|
||||
files: Files;
|
||||
entrypoint: string;
|
||||
workPath: string;
|
||||
meta: BuildParamsMeta;
|
||||
}
|
||||
|
||||
export const version = 2;
|
||||
|
||||
@@ -69,7 +69,7 @@ async function readPackageJson(entryPath: string) {
|
||||
async function writePackageJson(workPath: string, packageJson: Object) {
|
||||
await writeFile(
|
||||
path.join(workPath, 'package.json'),
|
||||
JSON.stringify(packageJson, null, 2),
|
||||
JSON.stringify(packageJson, null, 2)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -79,11 +79,14 @@ async function writePackageJson(workPath: string, packageJson: Object) {
|
||||
async function writeNpmRc(workPath: string, token: string) {
|
||||
await writeFile(
|
||||
path.join(workPath, '.npmrc'),
|
||||
`//registry.npmjs.org/:_authToken=${token}`,
|
||||
`//registry.npmjs.org/:_authToken=${token}`
|
||||
);
|
||||
}
|
||||
|
||||
function getNextVersion(packageJson: {dependencies?: {[key: string]: string},devDependencies?: {[key:string]:string}}) {
|
||||
function getNextVersion(packageJson: {
|
||||
dependencies?: { [key: string]: string };
|
||||
devDependencies?: { [key: string]: string };
|
||||
}) {
|
||||
let nextVersion;
|
||||
if (packageJson.dependencies && packageJson.dependencies.next) {
|
||||
nextVersion = packageJson.dependencies.next;
|
||||
@@ -116,19 +119,22 @@ function isLegacyNext(nextVersion: string) {
|
||||
const name = '[@now/next]';
|
||||
const urls: stringMap = {};
|
||||
|
||||
async function startDevServer(entryPath: string): Promise<string> {
|
||||
function startDevServer(entryPath: string) {
|
||||
const forked = fork(path.join(__dirname, 'dev-server.js'), [], {
|
||||
cwd: entryPath,
|
||||
execArgv: [],
|
||||
env: {
|
||||
ENTRY_PATH: entryPath,
|
||||
NOW_REGION: 'dev1'
|
||||
NOW_REGION: 'dev1',
|
||||
},
|
||||
silent: true
|
||||
});
|
||||
|
||||
return new Promise(resolve => {
|
||||
forked.on('message', resolve);
|
||||
});
|
||||
const getUrl = () =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
forked.on('message', resolve);
|
||||
forked.on('error', reject);
|
||||
});
|
||||
|
||||
return { forked, getUrl };
|
||||
}
|
||||
|
||||
export const config = {
|
||||
@@ -136,57 +142,69 @@ export const config = {
|
||||
};
|
||||
|
||||
export const build = async ({
|
||||
files, workPath, entrypoint, meta = {} as BuildParamsMeta,
|
||||
}: BuildParamsType): Promise<{routes?: any[], output: Files, watch?: string[]}> => {
|
||||
files,
|
||||
workPath,
|
||||
entrypoint,
|
||||
meta = {} as BuildParamsMeta,
|
||||
}: BuildParamsType): Promise<{
|
||||
routes?: any[];
|
||||
output: Files;
|
||||
watch?: string[];
|
||||
childProcesses: ChildProcess[];
|
||||
}> => {
|
||||
validateEntrypoint(entrypoint);
|
||||
|
||||
const routes: any[] = [];
|
||||
const entryDirectory = path.dirname(entrypoint);
|
||||
const entryPath = path.join(workPath, entryDirectory);
|
||||
const dotNext = path.join(entryPath, '.next');
|
||||
const uponRequest = typeof meta.requestPath === 'string';
|
||||
|
||||
if ((meta.isDev && !uponRequest) || !meta.isDev) {
|
||||
console.log(`${name} Downloading user files...`);
|
||||
await download(files, workPath);
|
||||
}
|
||||
console.log(`${name} Downloading user files...`);
|
||||
await download(files, workPath, meta);
|
||||
|
||||
const pkg = await readPackageJson(entryPath);
|
||||
const nextVersion = getNextVersion(pkg);
|
||||
|
||||
if (!nextVersion) {
|
||||
throw new Error(
|
||||
'No Next.js version could be detected in "package.json". Make sure `"next"` is installed in "dependencies" or "devDependencies"',
|
||||
'No Next.js version could be detected in "package.json". Make sure `"next"` is installed in "dependencies" or "devDependencies"'
|
||||
);
|
||||
}
|
||||
|
||||
process.env.__NEXT_BUILDER_EXPERIMENTAL_TARGET = 'serverless';
|
||||
|
||||
if (meta.isDev) {
|
||||
// eslint-disable-next-line no-underscore-dangle
|
||||
process.env.__NEXT_BUILDER_EXPERIMENTAL_DEBUG = 'true';
|
||||
|
||||
console.log(`${name} Requested ${meta.requestPath || '/'}`);
|
||||
let childProcess: ChildProcess | undefined;
|
||||
|
||||
// If this is the initial build, we want to start the server
|
||||
if (!urls[entrypoint]) {
|
||||
console.log(`${name} Installing dependencies...`);
|
||||
await runNpmInstall(entryPath, ['--prefer-offline']);
|
||||
|
||||
urls[entrypoint] = await startDevServer(entryPath);
|
||||
console.log(`${name} Development server for ${entrypoint} running at ${urls[entrypoint]}`);
|
||||
const { forked, getUrl } = startDevServer(entryPath);
|
||||
urls[entrypoint] = await getUrl();
|
||||
childProcess = forked;
|
||||
console.log(
|
||||
`${name} Development server for ${entrypoint} running at ${
|
||||
urls[entrypoint]
|
||||
}`
|
||||
);
|
||||
}
|
||||
|
||||
const pathsInside = getPathsInside(entryDirectory, files)
|
||||
const pathsInside = getPathsInside(entryDirectory, files);
|
||||
|
||||
return {
|
||||
output: {},
|
||||
routes: getRoutes(entryDirectory, pathsInside, files, urls[entrypoint]),
|
||||
watch: pathsInside
|
||||
watch: pathsInside,
|
||||
childProcesses: childProcess ? [childProcess] : [],
|
||||
};
|
||||
}
|
||||
|
||||
if (await pathExists(dotNext)) {
|
||||
console.warn(
|
||||
'WARNING: You should not upload the `.next` directory. See https://zeit.co/docs/v2/deployments/official-builders/next-js-now-next/ for more details.',
|
||||
'WARNING: You should not upload the `.next` directory. See https://zeit.co/docs/v2/deployments/official-builders/next-js-now-next/ for more details.'
|
||||
);
|
||||
}
|
||||
|
||||
@@ -208,7 +226,7 @@ export const build = async ({
|
||||
}
|
||||
|
||||
console.warn(
|
||||
"WARNING: your application is being deployed in @now/next's legacy mode. http://err.sh/zeit/now-builders/now-next-legacy-mode",
|
||||
"WARNING: your application is being deployed in @now/next's legacy mode. http://err.sh/zeit/now-builders/now-next-legacy-mode"
|
||||
);
|
||||
|
||||
console.log('normalizing package.json');
|
||||
@@ -217,7 +235,7 @@ export const build = async ({
|
||||
await writePackageJson(entryPath, packageJson);
|
||||
} else if (!pkg.scripts || !pkg.scripts['now-build']) {
|
||||
console.warn(
|
||||
'WARNING: "now-build" script not found. Adding \'"now-build": "next build"\' to "package.json" automatically',
|
||||
'WARNING: "now-build" script not found. Adding \'"now-build": "next build"\' to "package.json" automatically'
|
||||
);
|
||||
pkg.scripts = {
|
||||
'now-build': 'next build',
|
||||
@@ -236,7 +254,13 @@ export const build = async ({
|
||||
await runNpmInstall(entryPath, ['--prefer-offline']);
|
||||
|
||||
console.log('running user script...');
|
||||
await runPackageJsonScript(entryPath, 'now-build');
|
||||
const memoryToConsume = Math.floor(os.totalmem() / 1024 ** 2) - 128;
|
||||
await runPackageJsonScript(entryPath, 'now-build', {
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_OPTIONS: `--max_old_space_size=${memoryToConsume}`,
|
||||
},
|
||||
} as SpawnOptions);
|
||||
|
||||
if (isLegacy) {
|
||||
console.log('running npm install --production...');
|
||||
@@ -247,7 +271,7 @@ export const build = async ({
|
||||
await unlinkFile(path.join(entryPath, '.npmrc'));
|
||||
}
|
||||
|
||||
const lambdas: {[key: string]: Lambda} = {};
|
||||
const lambdas: { [key: string]: Lambda } = {};
|
||||
|
||||
if (isLegacy) {
|
||||
const filesAfterBuild = await glob('**', entryPath);
|
||||
@@ -257,11 +281,11 @@ export const build = async ({
|
||||
try {
|
||||
buildId = await readFile(
|
||||
path.join(entryPath, '.next', 'BUILD_ID'),
|
||||
'utf8',
|
||||
'utf8'
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
'BUILD_ID not found in ".next". The "package.json" "build" script did not run "next build"',
|
||||
'BUILD_ID not found in ".next". The "package.json" "build" script did not run "next build"'
|
||||
);
|
||||
throw new Error('Missing BUILD_ID');
|
||||
}
|
||||
@@ -269,12 +293,12 @@ export const build = async ({
|
||||
const dotNextServerRootFiles = await glob('.next/server/*', entryPath);
|
||||
const nodeModules = excludeFiles(
|
||||
await glob('node_modules/**', entryPath),
|
||||
file => file.startsWith('node_modules/.cache'),
|
||||
file => file.startsWith('node_modules/.cache')
|
||||
);
|
||||
const launcherFiles = {
|
||||
'now__bridge.js': new FileFsRef({ fsPath: require('@now/node-bridge') }),
|
||||
};
|
||||
const nextFiles: {[key: string]: FileFsRef} = {
|
||||
const nextFiles: { [key: string]: FileFsRef } = {
|
||||
...nodeModules,
|
||||
...dotNextRootFiles,
|
||||
...dotNextServerRootFiles,
|
||||
@@ -285,13 +309,13 @@ export const build = async ({
|
||||
}
|
||||
const pages = await glob(
|
||||
'**/*.js',
|
||||
path.join(entryPath, '.next', 'server', 'static', buildId, 'pages'),
|
||||
path.join(entryPath, '.next', 'server', 'static', buildId, 'pages')
|
||||
);
|
||||
const launcherPath = path.join(__dirname, 'legacy-launcher.js');
|
||||
const launcherData = await readFile(launcherPath, 'utf8');
|
||||
|
||||
await Promise.all(
|
||||
Object.keys(pages).map(async (page) => {
|
||||
Object.keys(pages).map(async page => {
|
||||
// These default pages don't have to be handled as they'd always 404
|
||||
if (['_app.js', '_error.js', '_document.js'].includes(page)) {
|
||||
return;
|
||||
@@ -300,7 +324,7 @@ export const build = async ({
|
||||
const pathname = page.replace(/\.js$/, '');
|
||||
const launcher = launcherData.replace(
|
||||
'PATHNAME_PLACEHOLDER',
|
||||
`/${pathname.replace(/(^|\/)index$/, '')}`,
|
||||
`/${pathname.replace(/(^|\/)index$/, '')}`
|
||||
);
|
||||
|
||||
const pageFiles = {
|
||||
@@ -329,7 +353,7 @@ export const build = async ({
|
||||
runtime: 'nodejs8.10',
|
||||
});
|
||||
console.log(`Created lambda for page: "${page}"`);
|
||||
}),
|
||||
})
|
||||
);
|
||||
} else {
|
||||
console.log('preparing lambda files...');
|
||||
@@ -341,7 +365,7 @@ export const build = async ({
|
||||
};
|
||||
const pages = await glob(
|
||||
'**/*.js',
|
||||
path.join(entryPath, '.next', 'serverless', 'pages'),
|
||||
path.join(entryPath, '.next', 'serverless', 'pages')
|
||||
);
|
||||
|
||||
const pageKeys = Object.keys(pages);
|
||||
@@ -356,14 +380,14 @@ export const build = async ({
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
'No serverless pages were built. https://err.sh/zeit/now-builders/now-next-no-serverless-pages-built',
|
||||
'No serverless pages were built. https://err.sh/zeit/now-builders/now-next-no-serverless-pages-built'
|
||||
);
|
||||
}
|
||||
|
||||
// An optional assets folder that is placed alongside every page entrypoint
|
||||
const assets = await glob(
|
||||
'assets/**',
|
||||
path.join(entryPath, '.next', 'serverless'),
|
||||
path.join(entryPath, '.next', 'serverless')
|
||||
);
|
||||
|
||||
const assetKeys = Object.keys(assets);
|
||||
@@ -373,7 +397,7 @@ export const build = async ({
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
pageKeys.map(async (page) => {
|
||||
pageKeys.map(async page => {
|
||||
// These default pages don't have to be handled as they'd always 404
|
||||
if (['_app.js', '_error.js', '_document.js'].includes(page)) {
|
||||
return;
|
||||
@@ -392,42 +416,48 @@ export const build = async ({
|
||||
runtime: 'nodejs8.10',
|
||||
});
|
||||
console.log(`Created lambda for page: "${page}"`);
|
||||
}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const nextStaticFiles = await glob(
|
||||
'**',
|
||||
path.join(entryPath, '.next', 'static'),
|
||||
path.join(entryPath, '.next', 'static')
|
||||
);
|
||||
const staticFiles = Object.keys(nextStaticFiles).reduce(
|
||||
(mappedFiles, file) => ({
|
||||
...mappedFiles,
|
||||
[path.join(entryDirectory, `_next/static/${file}`)]: nextStaticFiles[file],
|
||||
[path.join(entryDirectory, `_next/static/${file}`)]: nextStaticFiles[
|
||||
file
|
||||
],
|
||||
}),
|
||||
{},
|
||||
{}
|
||||
);
|
||||
|
||||
const staticDirectoryFiles = onlyStaticDirectory(
|
||||
includeOnlyEntryDirectory(files, entryDirectory),
|
||||
entryDirectory,
|
||||
entryDirectory
|
||||
);
|
||||
|
||||
return {
|
||||
output: { ...lambdas, ...staticFiles, ...staticDirectoryFiles },
|
||||
routes: [],
|
||||
watch: []
|
||||
watch: [],
|
||||
childProcesses: [],
|
||||
};
|
||||
};
|
||||
|
||||
export const prepareCache = async ({ workPath, entrypoint }: PrepareCacheOptions) => {
|
||||
export const prepareCache = async ({
|
||||
workPath,
|
||||
entrypoint,
|
||||
}: PrepareCacheOptions) => {
|
||||
console.log('preparing cache ...');
|
||||
const entryDirectory = path.dirname(entrypoint);
|
||||
const entryPath = path.join(workPath, entryDirectory);
|
||||
|
||||
const pkg = await readPackageJson(entryPath);
|
||||
const nextVersion = getNextVersion(pkg);
|
||||
if (!nextVersion) throw new Error('Could not parse Next.js version')
|
||||
if (!nextVersion) throw new Error('Could not parse Next.js version');
|
||||
const isLegacy = isLegacyNext(nextVersion);
|
||||
|
||||
if (isLegacy) {
|
||||
|
||||
90
packages/now-next/test/unit/build.test.js
Normal file
90
packages/now-next/test/unit/build.test.js
Normal file
@@ -0,0 +1,90 @@
|
||||
/* global expect, it, jest */
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { build } = require('@now/next');
|
||||
const { FileBlob } = require('@now/build-utils');
|
||||
|
||||
jest.setTimeout(45000);
|
||||
|
||||
describe('build meta dev', () => {
|
||||
const files = {
|
||||
'next.config.js': new FileBlob({
|
||||
mode: 0o777,
|
||||
data: `
|
||||
module.exports = {
|
||||
target: 'serverless'
|
||||
}
|
||||
`,
|
||||
}),
|
||||
'pages/index.js': new FileBlob({
|
||||
mode: 0o777,
|
||||
data: `
|
||||
export default () => 'Index page'
|
||||
`,
|
||||
}),
|
||||
'package.json': new FileBlob({
|
||||
mode: 0o777,
|
||||
data: `
|
||||
{
|
||||
"scripts": {
|
||||
"now-build": "next build"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "8",
|
||||
"react": "16",
|
||||
"react-dom": "16"
|
||||
}
|
||||
}
|
||||
`,
|
||||
}),
|
||||
};
|
||||
const entrypoint = 'next.config.js';
|
||||
const workPath = path.join(
|
||||
os.tmpdir(),
|
||||
Math.random()
|
||||
.toString()
|
||||
.slice(3),
|
||||
);
|
||||
console.log('workPath directory: ', workPath);
|
||||
/*
|
||||
it('should have builder v2 response isDev=false', async () => {
|
||||
const meta = { isDev: false, requestPath: null };
|
||||
const { output, routes, watch } = await build({
|
||||
files,
|
||||
workPath,
|
||||
entrypoint,
|
||||
meta,
|
||||
});
|
||||
//console.log('output: ', Object.keys(output));
|
||||
expect(Object.keys(output).length).toBe(7);
|
||||
expect(output.index.type).toBe('Lambda');
|
||||
expect(routes.length).toBe(0);
|
||||
expect(watch.length).toBe(0);
|
||||
});
|
||||
*/
|
||||
|
||||
it('should have builder v2 response isDev=true', async () => {
|
||||
const meta = { isDev: true, requestPath: null };
|
||||
const {
|
||||
output, routes, watch, childProcesses,
|
||||
} = await build({
|
||||
files,
|
||||
workPath,
|
||||
entrypoint,
|
||||
meta,
|
||||
});
|
||||
routes.forEach((route) => {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
route.dest = route.dest.replace(':4000', ':5000');
|
||||
});
|
||||
expect(output).toEqual({});
|
||||
expect(routes).toEqual([
|
||||
{ src: '/_next/(.*)', dest: 'http://localhost:5000/_next/$1' },
|
||||
{ src: '/static/(.*)', dest: 'http://localhost:5000/static/$1' },
|
||||
{ src: '/index', dest: 'http://localhost:5000/index' },
|
||||
{ src: '/', dest: 'http://localhost:5000/' },
|
||||
]);
|
||||
expect(watch).toEqual(['next.config.js', 'pages/index.js', 'package.json']);
|
||||
childProcesses.forEach(cp => cp.kill());
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/node-bridge",
|
||||
"version": "1.0.2-canary.2",
|
||||
"version": "1.1.0",
|
||||
"license": "MIT",
|
||||
"main": "./index.js",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/node-server",
|
||||
"version": "0.5.4-canary.5",
|
||||
"version": "0.6.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -8,7 +8,7 @@
|
||||
"directory": "packages/now-node-server"
|
||||
},
|
||||
"dependencies": {
|
||||
"@now/node-bridge": "^1.0.2-canary.2",
|
||||
"@now/node-bridge": "^1.1.0",
|
||||
"@zeit/ncc": "0.18.1",
|
||||
"fs-extra": "7.0.1"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/node",
|
||||
"version": "0.5.4-canary.6",
|
||||
"version": "0.6.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index",
|
||||
"repository": {
|
||||
@@ -9,7 +9,7 @@
|
||||
"directory": "packages/now-node"
|
||||
},
|
||||
"dependencies": {
|
||||
"@now/node-bridge": "^1.0.2-canary.2",
|
||||
"@now/node-bridge": "^1.1.0",
|
||||
"@zeit/ncc": "0.18.1",
|
||||
"fs-extra": "7.0.1"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/optipng",
|
||||
"version": "0.4.9-canary.1",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/php-bridge",
|
||||
"version": "0.4.16-canary.0",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/php",
|
||||
"version": "0.4.17-canary.1",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -8,7 +8,7 @@
|
||||
"directory": "packages/now-php"
|
||||
},
|
||||
"dependencies": {
|
||||
"@now/php-bridge": "^0.4.16-canary.0"
|
||||
"@now/php-bridge": "^0.5.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "jest"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/python",
|
||||
"version": "0.1.0-canary.2",
|
||||
"version": "0.1.0",
|
||||
"main": "index.js",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/rust",
|
||||
"version": "0.1.2-canary.2",
|
||||
"version": "0.2.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
const path = require('path');
|
||||
const { existsSync } = require('fs');
|
||||
const getPort = require('get-port');
|
||||
const { promisify } = require('util');
|
||||
const { timeout } = require('promise-timeout');
|
||||
const { existsSync, readFileSync } = require('fs');
|
||||
const waitForPort = promisify(require('wait-for-port'));
|
||||
const {
|
||||
glob,
|
||||
download,
|
||||
@@ -17,12 +21,16 @@ function validateDistDir(distDir) {
|
||||
}
|
||||
}
|
||||
|
||||
exports.version = 2;
|
||||
|
||||
const nowDevScriptPorts = new Map();
|
||||
|
||||
exports.build = async ({
|
||||
files, entrypoint, workPath, config,
|
||||
files, entrypoint, workPath, config, meta = {},
|
||||
}) => {
|
||||
console.log('downloading user files...');
|
||||
await download(files, workPath);
|
||||
console.log('running user scripts...');
|
||||
await download(files, workPath, meta);
|
||||
|
||||
const mountpoint = path.dirname(entrypoint);
|
||||
const entrypointFsDirname = path.join(workPath, mountpoint);
|
||||
const distPath = path.join(
|
||||
@@ -31,13 +39,79 @@ exports.build = async ({
|
||||
(config && config.distDir) || 'dist',
|
||||
);
|
||||
|
||||
if (path.basename(entrypoint) === 'package.json') {
|
||||
const entrypointName = path.basename(entrypoint);
|
||||
if (entrypointName === 'package.json') {
|
||||
await runNpmInstall(entrypointFsDirname, ['--prefer-offline']);
|
||||
if (await runPackageJsonScript(entrypointFsDirname, 'now-build')) {
|
||||
|
||||
const pkgPath = path.join(workPath, entrypoint);
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
|
||||
|
||||
let output = {};
|
||||
const routes = [];
|
||||
|
||||
if (meta.isDev && pkg.scripts && pkg.scripts['now-dev']) {
|
||||
let devPort = nowDevScriptPorts.get(entrypoint);
|
||||
if (typeof devPort === 'number') {
|
||||
console.log('`now-dev` server already running for %j', entrypoint);
|
||||
} else {
|
||||
// Run the `now-dev` script out-of-bounds, since it is assumed that
|
||||
// it will launch a dev server that never "completes"
|
||||
devPort = await getPort();
|
||||
nowDevScriptPorts.set(entrypoint, devPort);
|
||||
const opts = {
|
||||
env: { ...process.env, PORT: String(devPort) },
|
||||
};
|
||||
const promise = runPackageJsonScript(
|
||||
entrypointFsDirname,
|
||||
'now-dev',
|
||||
opts,
|
||||
);
|
||||
promise.then(
|
||||
() => {
|
||||
nowDevScriptPorts.delete(entrypoint);
|
||||
},
|
||||
(err) => {
|
||||
console.log('`now-dev` script error:', err);
|
||||
nowDevScriptPorts.delete(entrypoint);
|
||||
},
|
||||
);
|
||||
|
||||
// Now wait for the server to have listened on `$PORT`, after which we
|
||||
// will ProxyPass any requests to that development server that come in
|
||||
// for this builder.
|
||||
try {
|
||||
await timeout(waitForPort('localhost', devPort), 60 * 1000);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Failed to detect a server running on port ${devPort}`,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('Detected dev server for %j', entrypoint);
|
||||
}
|
||||
|
||||
let srcBase = mountpoint.replace(/^\.\/?/, '');
|
||||
if (srcBase.length > 0) {
|
||||
srcBase = `/${srcBase}`;
|
||||
}
|
||||
routes.push({
|
||||
src: `${srcBase}/(.*)`,
|
||||
dest: `http://localhost:${devPort}${srcBase}/$1`,
|
||||
});
|
||||
} else {
|
||||
// Run the `now-build` script and wait for completion to collect the build
|
||||
// outputs
|
||||
console.log('running user "now-build" script from `package.json`...');
|
||||
if (!(await runPackageJsonScript(entrypointFsDirname, 'now-build'))) {
|
||||
throw new Error(
|
||||
`An error running "now-build" script in "${entrypoint}"`,
|
||||
);
|
||||
}
|
||||
validateDistDir(distPath);
|
||||
return glob('**', distPath, mountpoint);
|
||||
output = await glob('**', distPath, mountpoint);
|
||||
}
|
||||
throw new Error(`An error running "now-build" script in "${entrypoint}"`);
|
||||
const watch = [path.join(mountpoint.replace(/^\.\/?/, ''), '**/*')];
|
||||
return { routes, watch, output };
|
||||
}
|
||||
|
||||
if (path.extname(entrypoint) === '.sh') {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/static-build",
|
||||
"version": "0.4.19-canary.2",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -9,5 +9,10 @@
|
||||
},
|
||||
"scripts": {
|
||||
"test": "jest"
|
||||
},
|
||||
"dependencies": {
|
||||
"get-port": "5.0.0",
|
||||
"promise-timeout": "1.3.0",
|
||||
"wait-for-port": "0.0.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@now/wordpress",
|
||||
"version": "0.4.16-canary.0",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -8,7 +8,7 @@
|
||||
"directory": "packages/now-wordpress"
|
||||
},
|
||||
"dependencies": {
|
||||
"@now/php-bridge": "^0.4.16-canary.0",
|
||||
"@now/php-bridge": "^0.5.0",
|
||||
"node-fetch": "2.3.0",
|
||||
"yauzl": "2.10.0"
|
||||
},
|
||||
|
||||
37
yarn.lock
37
yarn.lock
@@ -1046,10 +1046,12 @@
|
||||
"@types/prop-types" "*"
|
||||
csstype "^2.2.0"
|
||||
|
||||
"@types/resolve-from@^4.0.0":
|
||||
version "4.0.0"
|
||||
resolved "https://registry.yarnpkg.com/@types/resolve-from/-/resolve-from-4.0.0.tgz#55538ffe8e35c3116a4cebf814ce1a1f1d663fcc"
|
||||
integrity sha512-LjkxahYnTBr75YRCEI/FQnQVfP4fP69koNW+3bmSkZuiSCkXkTJpfl7SPcZ4biXfmZHduoVLElP4VWBhex+0zQ==
|
||||
"@types/resolve-from@^5.0.1":
|
||||
version "5.0.1"
|
||||
resolved "https://registry.yarnpkg.com/@types/resolve-from/-/resolve-from-5.0.1.tgz#2714eaa840c0472dcfa96ec3fb9d170dbf0b677d"
|
||||
integrity sha512-1G7n5Jtr5inoS1Ez2Y9Efedk9/wH6uGQslbfhGTOw9J42PCAwuyaDgQHW7fIq02+shwB02kM/w31W8gMxI8ORg==
|
||||
dependencies:
|
||||
resolve-from "*"
|
||||
|
||||
"@types/semver@^6.0.0":
|
||||
version "6.0.0"
|
||||
@@ -3787,18 +3789,18 @@ get-pkg-repo@^1.0.0:
|
||||
parse-github-repo-url "^1.3.0"
|
||||
through2 "^2.0.0"
|
||||
|
||||
get-port@^3.2.0:
|
||||
version "3.2.0"
|
||||
resolved "https://registry.yarnpkg.com/get-port/-/get-port-3.2.0.tgz#dd7ce7de187c06c8bf353796ac71e099f0980ebc"
|
||||
integrity sha1-3Xzn3hh8Bsi/NTeWrHHgmfCYDrw=
|
||||
|
||||
get-port@^5.0.0:
|
||||
get-port@5.0.0, get-port@^5.0.0:
|
||||
version "5.0.0"
|
||||
resolved "https://registry.yarnpkg.com/get-port/-/get-port-5.0.0.tgz#aa22b6b86fd926dd7884de3e23332c9f70c031a6"
|
||||
integrity sha512-imzMU0FjsZqNa6BqOjbbW6w5BivHIuQKopjpPqcnx0AVHJQKCxK1O+Ab3OrVXhrekqfVMjwA9ZYu062R+KcIsQ==
|
||||
dependencies:
|
||||
type-fest "^0.3.0"
|
||||
|
||||
get-port@^3.2.0:
|
||||
version "3.2.0"
|
||||
resolved "https://registry.yarnpkg.com/get-port/-/get-port-3.2.0.tgz#dd7ce7de187c06c8bf353796ac71e099f0980ebc"
|
||||
integrity sha1-3Xzn3hh8Bsi/NTeWrHHgmfCYDrw=
|
||||
|
||||
get-proxy@^1.0.1:
|
||||
version "1.1.0"
|
||||
resolved "https://registry.yarnpkg.com/get-proxy/-/get-proxy-1.1.0.tgz#894854491bc591b0f147d7ae570f5c678b7256eb"
|
||||
@@ -7965,6 +7967,11 @@ promise-retry@^1.1.1:
|
||||
err-code "^1.0.0"
|
||||
retry "^0.10.0"
|
||||
|
||||
promise-timeout@1.3.0:
|
||||
version "1.3.0"
|
||||
resolved "https://registry.yarnpkg.com/promise-timeout/-/promise-timeout-1.3.0.tgz#d1c78dd50a607d5f0a5207410252a3a0914e1014"
|
||||
integrity sha512-5yANTE0tmi5++POym6OgtFmwfDvOXABD9oj/jLQr5GPEyuNEb7jH4wbbANJceJid49jwhi1RddxnhnEAb/doqg==
|
||||
|
||||
prompts@^0.1.9:
|
||||
version "0.1.14"
|
||||
resolved "https://registry.yarnpkg.com/prompts/-/prompts-0.1.14.tgz#a8e15c612c5c9ec8f8111847df3337c9cbd443b2"
|
||||
@@ -8473,6 +8480,11 @@ resolve-cwd@^2.0.0:
|
||||
dependencies:
|
||||
resolve-from "^3.0.0"
|
||||
|
||||
resolve-from@*, resolve-from@^5.0.0:
|
||||
version "5.0.0"
|
||||
resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69"
|
||||
integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==
|
||||
|
||||
resolve-from@^1.0.0:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-1.0.1.tgz#26cbfe935d1aeeeabb29bc3fe5aeb01e93d44226"
|
||||
@@ -9937,6 +9949,11 @@ w3c-hr-time@^1.0.1:
|
||||
dependencies:
|
||||
browser-process-hrtime "^0.1.2"
|
||||
|
||||
wait-for-port@0.0.2:
|
||||
version "0.0.2"
|
||||
resolved "https://registry.yarnpkg.com/wait-for-port/-/wait-for-port-0.0.2.tgz#bb5ff253436b9933ab9d65c00d584dc68c4d531a"
|
||||
integrity sha1-u1/yU0NrmTOrnWXADVhNxoxNUxo=
|
||||
|
||||
walker@^1.0.7, walker@~1.0.5:
|
||||
version "1.0.7"
|
||||
resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.7.tgz#2f7f9b8fd10d677262b18a884e28d19618e028fb"
|
||||
|
||||
Reference in New Issue
Block a user