Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export const prepareCache = async ({
workPath,
entrypoint,
}: PrepareCacheOptions): Promise => {
debug('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');
const isLegacy = isLegacyNext(nextVersion);
if (isLegacy) {
// skip caching legacy mode (swapping deps between all and production can get bug-prone)
return {};
}
debug('Producing cache file manifest...');
const cacheEntrypoint = path.relative(workPath, entryPath);
const cache = {
}: PrepareCacheOptions): Promise => {
debug('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');
const isLegacy = isLegacyNext(nextVersion);
if (isLegacy) {
// skip caching legacy mode (swapping deps between all and production can get bug-prone)
return {};
}
debug('Producing cache file manifest...');
const cacheEntrypoint = path.relative(workPath, entryPath);
const cache = {
...(await glob(path.join(cacheEntrypoint, 'node_modules/**'), workPath)),
...(await glob(path.join(cacheEntrypoint, '.next/cache/**'), workPath)),
};
debug('Cache file manifest produced');
return cache;
};
const nextVersion = getNextVersion(pkg);
if (!nextVersion) throw new Error('Could not parse Next.js version');
const isLegacy = isLegacyNext(nextVersion);
if (isLegacy) {
// skip caching legacy mode (swapping deps between all and production can get bug-prone)
return {};
}
debug('Producing cache file manifest...');
const cacheEntrypoint = path.relative(workPath, entryPath);
const cache = {
...(await glob(path.join(cacheEntrypoint, 'node_modules/**'), workPath)),
...(await glob(path.join(cacheEntrypoint, '.next/cache/**'), workPath)),
};
debug('Cache file manifest produced');
return cache;
};
const hasRelativeVendorDir = await pathExists(relativeVendorDir);
const hasVendorDir = hasRootVendorDir || hasRelativeVendorDir;
if (hasRelativeVendorDir) {
if (hasRootVendorDir) {
debug(
'found two vendor directories, choosing the vendor directory relative to entrypoint'
);
} else {
debug('found vendor directory relative to entrypoint');
}
// vendor dir must be at the root for lambda to find it
await move(relativeVendorDir, vendorDir);
} else if (hasRootVendorDir) {
debug('found vendor directory in project root');
}
await ensureDir(vendorDir);
// no vendor directory, check for Gemfile to install
if (!hasVendorDir) {
const gemFile = join(entryDirectory, 'Gemfile');
if (fsFiles[gemFile]) {
debug(
'did not find a vendor directory but found a Gemfile, bundling gems...'
);
const gemfilePath = fsFiles[gemFile].fsPath;
// try installing. this won't work if native extesions are required.
// if that's the case, gems should be vendored locally before deploying.
await unlinkFile(path.join(entryPath, 'yarn.lock'));
} catch (err) {
debug('no yarn.lock removed');
}
try {
await unlinkFile(path.join(entryPath, 'package-lock.json'));
} catch (err) {
debug('no package-lock.json removed');
}
console.warn(
"WARNING: your application is being deployed in @now/next's legacy mode. http://err.sh/zeit/now/now-next-legacy-mode"
);
debug('Normalizing package.json');
const packageJson = normalizePackageJson(pkg);
debug('Normalized package.json result: ', packageJson);
await writePackageJson(entryPath, packageJson);
} else if (pkg.scripts && pkg.scripts['now-build']) {
debug('Found user `now-build` script');
shouldRunScript = 'now-build';
} else if (pkg.scripts && pkg.scripts['build']) {
debug('Found user `build` script');
shouldRunScript = 'build';
} else if (!pkg.scripts || !pkg.scripts['now-build']) {
debug(
'Your application is being built using `next build`. ' +
'If you need to define a different build step, please create a `now-build` script in your `package.json` ' +
'(e.g. `{ "scripts": { "now-build": "npm run prepare && next build" } }`).'
);
pkg.scripts = {
debug('no yarn.lock removed');
}
try {
await unlinkFile(path.join(entryPath, 'package-lock.json'));
} catch (err) {
debug('no package-lock.json removed');
}
console.warn(
"WARNING: your application is being deployed in @now/next's legacy mode. http://err.sh/zeit/now/now-next-legacy-mode"
);
debug('Normalizing package.json');
const packageJson = normalizePackageJson(pkg);
debug('Normalized package.json result: ', packageJson);
await writePackageJson(entryPath, packageJson);
} else if (pkg.scripts && pkg.scripts['now-build']) {
debug('Found user `now-build` script');
shouldRunScript = 'now-build';
} else if (pkg.scripts && pkg.scripts['build']) {
debug('Found user `build` script');
shouldRunScript = 'build';
} else if (!pkg.scripts || !pkg.scripts['now-build']) {
debug(
'Your application is being built using `next build`. ' +
'If you need to define a different build step, please create a `now-build` script in your `package.json` ' +
'(e.g. `{ "scripts": { "now-build": "npm run prepare && next build" } }`).'
);
pkg.scripts = {
'now-build': 'next build',
...(pkg.scripts || {}),
function createGoPathTree(goPath: string, platform: string, arch: string) {
const tuple = `${getPlatform(platform)}_${getArch(arch)}`;
debug('Creating GOPATH directory structure for %o (%s)', goPath, tuple);
return Promise.all([
mkdirp(join(goPath, 'bin')),
mkdirp(join(goPath, 'pkg', tuple))
]);
}
let realNextVersion: string | undefined;
try {
realNextVersion = require(resolveFrom(entryPath, 'next/package.json'))
.version;
debug(`Detected Next.js version: ${realNextVersion}`);
} catch (_ignored) {
debug(`Could not identify real Next.js version, that's OK!`);
}
if (!isLegacy) {
await createServerlessConfig(workPath, entryPath, realNextVersion);
}
debug('Running user script...');
const memoryToConsume = Math.floor(os.totalmem() / 1024 ** 2) - 128;
const env: { [key: string]: string | undefined } = { ...spawnOpts.env };
env.NODE_OPTIONS = `--max_old_space_size=${memoryToConsume}`;
await runPackageJsonScript(entryPath, shouldRunScript, { ...spawnOpts, env });
const routesManifest = await getRoutesManifest(entryPath, realNextVersion);
const rewrites: Route[] = [];
const redirects: Route[] = [];
if (routesManifest) {
switch (routesManifest.version) {
case 1:
case 2: {
redirects.push(...convertRedirects(routesManifest.redirects));
rewrites.push(...convertRewrites(routesManifest.rewrites));
break;
export async function getAnalyzedEntrypoint(filePath: string, modulePath = '') {
debug('Analyzing entrypoint %o', filePath);
const bin = join(__dirname, 'analyze');
const isAnalyzeExist = await pathExists(bin);
if (!isAnalyzeExist) {
const src = join(__dirname, 'util', 'analyze.go');
const dest = join(__dirname, 'analyze');
const go = await downloadGo();
await go.build(src, dest);
}
const args = [`-modpath=${modulePath}`, filePath];
const analyzed = await execa.stdout(bin, args);
debug('Analyzed entrypoint %o', analyzed);
return analyzed;
}
private execute(...args: string[]) {
const { opts, env } = this;
debug('Exec %o', `go ${args.join(' ')}`);
return execa('go', args, { stdio: 'pipe', ...opts, env });
}