Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42,850 changes: 24,095 additions & 18,755 deletions package-lock.json

Large diffs are not rendered by default.

19 changes: 12 additions & 7 deletions packages/@apphosting/adapter-nextjs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@apphosting/adapter-nextjs",
"version": "14.0.21",
"name": "wei-nextjs-adapter-test",
"version": "15.0.13",
"main": "dist/index.js",
"description": "Experimental addon to the Firebase CLI to add web framework support",
"repository": {
Expand All @@ -9,6 +9,7 @@
},
"bin": {
"apphosting-adapter-nextjs-build": "dist/bin/build.js",
"apphosting-adapter-nextjs-serve": "dist/bin/serve.js",
"apphosting-adapter-nextjs-create": "dist/bin/create.js"
},
"author": {
Expand All @@ -21,7 +22,8 @@
"type": "module",
"sideEffects": false,
"scripts": {
"build": "rm -rf dist && tsc && chmod +x ./dist/bin/*",
"build": "rm -rf dist && tsc && npm run bundle",
"bundle": "esbuild src/bin/build.ts --bundle --platform=node --format=esm --banner:js='#!/usr/bin/env node' --outfile=dist/bin/build.js --external:esbuild --external:fs-extra && esbuild src/bin/serve.ts --bundle --platform=node --format=esm --banner:js='#!/usr/bin/env node' --outfile=dist/bin/serve.js --external:next --external:react --external:react-dom && esbuild src/index.ts --bundle --platform=node --format=cjs --outfile=dist/index.js",
"test": "npm run test:unit && npm run test:functional",
"test:unit": "ts-mocha -p tsconfig.json 'src/**/*.spec.ts' 'src/*.spec.ts'",
"test:functional": "node --loader ts-node/esm ./e2e/run-local.ts",
Expand All @@ -44,9 +46,10 @@
"license": "Apache-2.0",
"dependencies": {
"@apphosting/common": "*",
"esbuild": "^0.25.0",
"fastify": "^5.6.1",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The fastify dependency was added, but it doesn't appear to be used anywhere in the codebase. The new serve.ts uses Node's built-in http module. To keep dependencies clean, this unused package should be removed.

"fs-extra": "^11.1.1",
"yaml": "^2.3.4",
"semver": "^7.7.3"
"yaml": "^2.3.4"
},
"peerDependencies": {
"next": "*"
Expand All @@ -61,12 +64,14 @@
"@types/mocha": "*",
"@types/tmp": "*",
"mocha": "*",
"next": "~14.0.0",
"next": "15.6.0-canary.54",
"protoc": "^32.1.0",
"semver": "*",
"tmp": "*",
"ts-mocha": "*",
"ts-node": "*",
"ts-proto": "^2.7.7",
"typescript": "*",
"verdaccio": "^5.30.3"
}
}
}
189 changes: 123 additions & 66 deletions packages/@apphosting/adapter-nextjs/src/bin/build.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,137 @@
#! /usr/bin/env node
// import { build } from "esbuild";
// import { stringify } from "yaml";
// import { spawn } from "child_process";
// import { join, dirname } from "path";
// import fs from "fs-extra";
// import { fileURLToPath } from "url";
import {
generateBuildOutput,
loadConfig,
populateOutputBundleOptions,
generateBuildOutput,
validateOutputDirectory,
getAdapterMetadata,
exists,
checkNextJSVersion,
} from "../utils.js";
import { join } from "path";
import { getBuildOptions, runBuild } from "@apphosting/common";
import {
addRouteOverrides,
overrideNextConfig,
restoreNextConfig,
validateNextConfigOverride,
} from "../overrides.js";

const root = process.cwd();
const opts = getBuildOptions();
// const __filename = fileURLToPath(import.meta.url);
// const __dirname = dirname(__filename);
// export async function main() {
// const root = process.cwd();
// console.log(`🏗️ Starting Adapter Build in ${root}...`);

// // 1. Run Next.js Build
// const nextBuild = spawn("npx", ["next", "build"], {
// stdio: "inherit",
// cwd: root,
// shell: true,
// env: { ...process.env, NODE_ENV: "production" },
// });

// await new Promise<void>((resolve, reject) => {
// nextBuild.on("close", (code) => {
// if (code === 0) resolve();
// else reject(new Error(`Next.js build failed with code ${code}`));
// });
// });

// // 2. Move Standalone Output to .apphosting
// const standaloneDir = join(root, ".next", "standalone");
// const outputDir = join(root, ".apphosting");

// // Clean previous build
// await fs.remove(outputDir);
// await fs.ensureDir(outputDir);

// console.log("📦 Copying standalone server to .apphosting...");

// // Copy the standalone directory content to .apphosting
// // Note: This includes a 'server.js' and 'node_modules'
// await fs.copy(standaloneDir, outputDir);

// // Copy the 'public' folder and '.next/static' (Standalone doesn't include these by default!)
// await fs
// .copy(join(root, "public"), join(outputDir, "public"), { dereference: true })
// .catch(() => {});
// await fs.copy(join(root, ".next", "static"), join(outputDir, ".next", "static"), {
// dereference: true,
// });
// const configSource = join(root, ".next", "firebase-next-config.json");
// const configDest = join(outputDir, "firebase-next-config.json");

// if (await fs.pathExists(configSource)) {
// console.log("📦 Copying serialized config...");
// await fs.copy(configSource, configDest);
// } else {
// console.warn("⚠️ Could not find firebase-next-config.json. Server may fail to start.");
// }
// // 3. Bundle OUR Runtime Server
// // We put our serve.js *next to* the Next.js server.js
// console.log("📦 Bundling runtime server...");
// await build({
// entryPoints: [join(__dirname, "serve.js")],
// bundle: true,
// platform: "node",
// format: "cjs",
// outfile: join(outputDir, "adapter-server.js"),
// external: ["next", "react", "react-dom"],
// });

// Set standalone mode
process.env.NEXT_PRIVATE_STANDALONE = "true";
// console.log("📦 Generating bundle.yaml...");

// const bundle = {
// version: "v1",
// runConfig: {
// // This runs the file we just bundled in step 3
// runCommand: "node .apphosting/adapter-server.js",

// concurrency: 80,
// cpu: 1,
// memoryMiB: 512,
// minInstances: 0,
// maxInstances: 100,
// },
// metadata: {
// adapterPackageName: "wei-nextjs-adapter-test",
// adapterVersion: "15.0.3",
// frameworkVersion: "16.0.1",
// framework: "nextjs",
// },
// outputFiles: {
// serverApp: {
// include: [".apphosting"],
// },
// },
// };

// await fs.writeFile(join(outputDir, "bundle.yaml"), stringify(bundle));

// console.log("✅ Build complete. Artifacts in .apphosting/");
// }

// main().catch((err) => {
// console.error(err);
// process.exit(1);
// });

import { join } from "node:path";
// Opt-out sending telemetry to Vercel
process.env.NEXT_TELEMETRY_DISABLED = "1";

checkNextJSVersion(process.env.FRAMEWORK_VERSION);
process.env.NEXT_ADAPTER_PATH = join(import.meta.dirname, "..", "index.cjs");

await runBuild();

const opts = getBuildOptions();
const root = process.cwd();

const nextConfig = await loadConfig(root, opts.projectDirectory);

/**
* Override user's Next Config to optimize the app for Firebase App Hosting
* and validate that the override resulted in a valid config that Next.js can
* load.
*
* We restore the user's Next Config at the end of the build, after the config file has been
* copied over to the output directory, so that the user's original code is not modified.
*
* If the app does not have a next.config.[js|mjs|ts] file in the first place,
* then can skip config override.
*
* Note: loadConfig always returns a fileName (default: next.config.js) even if
* one does not exist in the app's root: https://github.com/vercel/next.js/blob/23681508ca34b66a6ef55965c5eac57de20eb67f/packages/next/src/server/config.ts#L1115
*/
const nextConfigPath = join(root, nextConfig.configFileName);
if (await exists(nextConfigPath)) {
await overrideNextConfig(root, nextConfig.configFileName);
await validateNextConfigOverride(root, opts.projectDirectory, nextConfig.configFileName);
}

try {
await runBuild();

const adapterMetadata = getAdapterMetadata();
const nextBuildDirectory = join(opts.projectDirectory, nextConfig.distDir);
const outputBundleOptions = populateOutputBundleOptions(
root,
opts.projectDirectory,
nextBuildDirectory,
);

await addRouteOverrides(
outputBundleOptions.outputDirectoryAppPath,
nextConfig.distDir,
adapterMetadata,
);

const nextjsVersion = process.env.FRAMEWORK_VERSION || "unspecified";
await generateBuildOutput(
root,
opts.projectDirectory,
outputBundleOptions,
nextBuildDirectory,
nextjsVersion,
adapterMetadata,
);
await validateOutputDirectory(outputBundleOptions, nextBuildDirectory);
} finally {
await restoreNextConfig(root, nextConfig.configFileName);
}
const nextBuildDirectory = join(opts.projectDirectory, nextConfig.distDir);
const outputBundleOptions = populateOutputBundleOptions(
root,
opts.projectDirectory,
nextBuildDirectory,
);
await generateBuildOutput(root, opts.projectDirectory, outputBundleOptions, nextBuildDirectory);

await validateOutputDirectory(outputBundleOptions, nextBuildDirectory);
96 changes: 96 additions & 0 deletions packages/@apphosting/adapter-nextjs/src/bin/serve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { createServer } from "http";
import { parse } from "url";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import { createRequire } from "module";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const require = createRequire(import.meta.url);
const __dirname = dirname(__filename);

Check failure on line 10 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

'__dirname' is assigned a value but never used

// 1. SET ENV VARS
// @ts-ignore

Check failure on line 13 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free
process.env['NODE_ENV'] = "production";

Check failure on line 14 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Replace `'NODE_ENV'` with `"NODE_ENV"`
process.env['NEXT_PRIVATE_MINIMAL_MODE'] = "1";

Check failure on line 15 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Replace `'NEXT_PRIVATE_MINIMAL_MODE'` with `"NEXT_PRIVATE_MINIMAL_MODE"`

async function start() {
// 1. GET THE APP ROOT
// The CLI passes the app directory as the first argument (process.argv[2])
// If missing, fallback to the current directory (but that usually fails in this setup)
const serverDir = process.argv[2] || process.cwd();

console.log(`> Starting server from: ${serverDir}`);

// 2. IMPORT NEXT.JS INTERNALS
const nextMetaPath = require.resolve("next/dist/server/request-meta", { paths: [serverDir] });
const { NEXT_REQUEST_META } = require(nextMetaPath);

let configPath = path.join(serverDir, "output.json");

if (!fs.existsSync(configPath)) {
configPath = path.join(process.cwd(), ".apphosting", "output.json");

Check failure on line 32 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Delete `·`
}
if (!fs.existsSync(configPath)) {
console.error(`❌ Config not found at: ${configPath}`);
process.exit(1);
}

const rawConfig = fs.readFileSync(configPath, 'utf-8');

Check failure on line 39 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Replace `'utf-8'` with `"utf-8"`
const buildContext = JSON.parse(rawConfig);

// Helper to find the postponed state for a path
const getPostponedState = (path: string) => {
let prerender = buildContext.outputs.prerenders.find((it: any) => it.pathname === path);
if (!prerender) {
const dynamicMatch = buildContext.routes.dynamicRoutes.find((it: any) =>

Check failure on line 46 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Delete `·`
path.match(new RegExp(it.sourceRegex))

Check failure on line 47 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Insert `,`
)?.source;
prerender = buildContext.outputs.prerenders.find((it: any) => it.pathname === dynamicMatch);
}
return prerender?.fallback?.postponedState;
};

// 4. SETUP SERVER
const nextPath = require.resolve("next/dist/server/next-server", { paths: [serverDir] });
const NextServer = require(nextPath).default;

Check failure on line 57 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Delete `··`
const server = new NextServer({
dir: serverDir,
hostname: '0.0.0.0',

Check failure on line 60 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts

View workflow job for this annotation

GitHub Actions / Lint

Replace `'0.0.0.0'` with `"0.0.0.0"`
port: parseInt(process.env.PORT || "8080"),
conf: buildContext.config,
});

await server.prepare();
const requestHandler = server.getRequestHandler();

createServer(async (req: any, res: any) => {
try {
const parsedUrl = parse(req.url, true);
const { pathname } = parsedUrl;

if (req.headers['next-resume'] === '1' && pathname) {
const postponed = getPostponedState(pathname);
if (postponed) {
console.log(`⚡️ Injecting Postponed State for ${pathname}`);
req[NEXT_REQUEST_META] = { postponed };
}
}

if (!req.headers['x-matched-path']) {
req.headers['x-matched-path'] = pathname;
}

await requestHandler(req, res, parsedUrl);
} catch (err) {
console.error(err);
res.statusCode = 500;
res.end("Internal Error");
}
}).listen(parseInt(process.env.PORT || "8080"), () => {
console.log(`> Ready on http://localhost:${process.env.PORT || 8080}`);
});
}

start();
Loading
Loading