Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
4602ad6
progress
mathu97 Feb 24, 2025
50297f5
add an overrides file to explicitely override nextjs defaults for app…
mathu97 Feb 24, 2025
5df4372
move adapterMetadata to common func
mathu97 Feb 24, 2025
2c7a1ca
check for middleware usage and add header
mathu97 Feb 24, 2025
62a71db
look at middleware manifest to check if middleware exists
mathu97 Feb 25, 2025
3662682
fix path
mathu97 Feb 25, 2025
b77e40c
fix test
mathu97 Feb 25, 2025
8dbf472
fix lint error
mathu97 Feb 25, 2025
8ac3016
bump nextjs adapter
mathu97 Feb 25, 2025
2e6d383
fix next app version test
mathu97 Feb 25, 2025
8b5b018
update package-lock
mathu97 Feb 25, 2025
005b780
update patch version instead of minor
mathu97 Feb 25, 2025
e2d7cc5
replace .eslintrc.json with eslint.config.mjs (preferred for next 15)
mathu97 Feb 25, 2025
e16ed40
move from using .eslintrc.json to eslint.config.mjs (preferred for ne…
mathu97 Feb 25, 2025
b14ccb4
fix e2e test
mathu97 Feb 25, 2025
01bf2b7
attempt2
mathu97 Feb 25, 2025
1387bc9
fix local test
mathu97 Feb 25, 2025
f0d7595
Merge branch 'bug/fix-nextjs-adapter-functional-tests' into feat/cust…
mathu97 Feb 25, 2025
23a5efc
add unit tests and e2e tests to test route overrides
mathu97 Feb 25, 2025
461b27a
add jsdocs
mathu97 Feb 25, 2025
f88c546
Merge remote-tracking branch 'origin/main' into feat/custom-apphostin…
mathu97 Feb 25, 2025
f4b045d
add jsdoc for interfaces
mathu97 Feb 25, 2025
c658e2c
address comments
mathu97 Feb 26, 2025
852da0d
refactor e2e scaffolding to be able to setup nextjs apps to test diff…
mathu97 Feb 26, 2025
564fc58
fix e2e tests failing for older node versions
mathu97 Feb 26, 2025
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 34 additions & 1 deletion packages/@apphosting/adapter-nextjs/e2e/app.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import * as assert from "assert";
import { posix } from "path";
import fsExtra from "fs-extra";

export const host = process.env.HOST;

if (!host) {
throw new Error("HOST environment variable expected");
}

let adapterVersion: string;
before(() => {
const packageJson = fsExtra.readJSONSync("package.json");
adapterVersion = packageJson.version;
if (!adapterVersion) throw new Error("couldn't parse package.json version");
});

describe("app", () => {
it("/", async () => {
const response = await fetch(host);
Expand Down Expand Up @@ -114,4 +121,30 @@ describe("app", () => {
"private, no-cache, no-store, max-age=0, must-revalidate",
);
});

it("should have x-fah-adapter header and no x-fah-middleware header on all routes", async () => {
const routes = [
"/",
"/ssg",
"/ssr",
"/ssr/streaming",
"/isr/time",
"/isr/demand",
"/nonexistent-route",
];

for (const route of routes) {
const response = await fetch(posix.join(host, route));
assert.equal(
response.headers.get("x-fah-adapter"),
`nextjs-${adapterVersion}`,
`Route ${route} missing x-fah-adapter header`,
);
assert.equal(
response.headers.get("x-fah-middleware"),
null,
`Route ${route} should not have x-fah-middleware header`,
);
}
});
});
43 changes: 43 additions & 0 deletions packages/@apphosting/adapter-nextjs/e2e/middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import * as assert from "assert";
import { posix } from "path";
import fsExtra from "fs-extra";

export const host = process.env.HOST;
if (!host) {
throw new Error("HOST environment variable expected");
}

let adapterVersion: string;
before(() => {
const packageJson = fsExtra.readJSONSync("package.json");
adapterVersion = packageJson.version;
if (!adapterVersion) throw new Error("couldn't parse package.json version");
});

describe("middleware", () => {
it("should have x-fah-adapter header and x-fah-middleware header on all routes", async () => {
const routes = [
"/",
"/ssg",
"/ssr",
"/ssr/streaming",
"/isr/time",
"/isr/demand",
"/nonexistent-route",
];

for (const route of routes) {
const response = await fetch(posix.join(host, route));
assert.equal(
response.headers.get("x-fah-adapter"),
`nextjs-${adapterVersion}`,
`Route ${route} missing x-fah-adapter header`,
);
assert.equal(
response.headers.get("x-fah-middleware"),
"true",
`Route ${route} missing x-fah-middleware header`,
);
}
});
});
242 changes: 159 additions & 83 deletions packages/@apphosting/adapter-nextjs/e2e/run-local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,100 +12,176 @@ const __dirname = dirname(fileURLToPath(import.meta.url));

const starterTemplateDir = "../../../starters/nextjs/basic";

// Define scenarios to test
interface Scenario {
name: string; // Name of the scenario
setup?: (cwd: string) => Promise<void>; // Optional setup function before building the app
tests?: string[]; // List of test files to run
}

const scenarios: Scenario[] = [
{
name: "basic",
// No setup needed for basic scenario
tests: ["app.spec.ts"],
},
{
name: "with-middleware",
setup: async (cwd: string) => {
// Create a middleware.ts file
const middlewareContent = `
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
// This is a simple middleware that doesn't modify the request
console.log('Middleware executed', request.nextUrl.pathname);
}

export const config = {
matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)',
};
`;

await fsExtra.writeFile(join(cwd, "src", "middleware.ts"), middlewareContent);
console.log(`Created middleware.ts file`);
},
tests: ["middleware.spec.ts"], // Only run middleware-specific tests
},
];

const errors: any[] = [];

await rmdir(join(__dirname, "runs"), { recursive: true }).catch(() => undefined);

console.log("\nBuilding and starting test project...");

const runId = Math.random().toString().split(".")[1];
const cwd = join(__dirname, "runs", runId);
await mkdirp(cwd);

console.log(`[${runId}] Copying ${starterTemplateDir} to working directory`);
await cp(starterTemplateDir, cwd, { recursive: true });

console.log(`[${runId}] > npm ci --silent --no-progress`);
await promiseSpawn("npm", ["ci", "--silent", "--no-progress"], {
cwd,
stdio: "inherit",
shell: true,
});

const buildScript = relative(cwd, join(__dirname, "../dist/bin/build.js"));
console.log(`[${runId}] > node ${buildScript}`);

const packageJson = JSON.parse(readFileSync(join(cwd, "package.json"), "utf-8"));
const frameworkVersion = packageJson.dependencies.next.replace("^", "");
await promiseSpawn("node", [buildScript], {
cwd,
stdio: "inherit",
shell: true,
env: {
...process.env,
FRAMEWORK_VERSION: frameworkVersion,
},
});

const bundleYaml = parseYaml(readFileSync(join(cwd, ".apphosting/bundle.yaml")).toString());
// Run each scenario
for (const scenario of scenarios) {
console.log(`\n\nRunning scenario: ${scenario.name}`);

const runCommand = bundleYaml.runConfig.runCommand;
const runId = `${scenario.name}-${Math.random().toString().split(".")[1]}`;
const cwd = join(__dirname, "runs", runId);
await mkdirp(cwd);

if (typeof runCommand !== "string") {
throw new Error("runCommand must be a string");
}
console.log(`[${runId}] Copying ${starterTemplateDir} to working directory`);
await cp(starterTemplateDir, cwd, { recursive: true });

const [runScript, ...runArgs] = runCommand.split(" ");
let resolveHostname: (it: string) => void;
let rejectHostname: () => void;
const hostnamePromise = new Promise<string>((resolve, reject) => {
resolveHostname = resolve;
rejectHostname = reject;
});
const port = 8080 + Math.floor(Math.random() * 1000);
console.log(`[${runId}] > PORT=${port} ${runCommand}`);
const run = spawn(runScript, runArgs, {
cwd,
shell: true,
env: {
NODE_ENV: "production",
PORT: port.toString(),
PATH: process.env.PATH,
},
});
run.stderr.on("data", (data) => console.error(data.toString()));
run.stdout.on("data", (data) => {
console.log(data.toString());
// Check for the "Ready in" message to determine when the server is fully started
if (data.toString().includes(`Ready in`)) {
// We use 0.0.0.0 instead of localhost to avoid issues when ipv6 is not available (Node 18)
resolveHostname(`http://0.0.0.0:${port}`);
}
});
run.on("close", (code) => {
if (code) {
rejectHostname();
// Run scenario-specific setup if provided
if (scenario.setup) {
console.log(`[${runId}] Running setup for ${scenario.name}`);
await scenario.setup(cwd);
}
});
const host = await hostnamePromise;

console.log("\n\n");

try {
console.log(`> HOST=${host} ts-mocha -p tsconfig.json e2e/*.spec.ts`);
await promiseSpawn("ts-mocha", ["-p", "tsconfig.json", "e2e/*.spec.ts"], {
shell: true,
console.log(`[${runId}] > npm ci --silent --no-progress`);
await promiseSpawn("npm", ["ci", "--silent", "--no-progress"], {
cwd,
stdio: "inherit",
env: {
...process.env,
HOST: host,
},
}).finally(() => {
run.stdin.end();
run.kill("SIGKILL");
shell: true,
});
} catch (e) {
errors.push(e);

const buildScript = relative(cwd, join(__dirname, "../dist/bin/build.js"));
const buildLogPath = join(cwd, "build.log");
console.log(`[${runId}] > node ${buildScript} (output written to ${buildLogPath})`);

const packageJson = JSON.parse(readFileSync(join(cwd, "package.json"), "utf-8"));
const frameworkVersion = packageJson.dependencies.next.replace("^", "");

try {
await promiseSpawn("node", [buildScript], {
cwd,
stdioString: true,
stdio: "pipe",
shell: true,
env: {
...process.env,
FRAMEWORK_VERSION: frameworkVersion,
},
}).then((result) => {
// Write stdout and stderr to the log file
fsExtra.writeFileSync(buildLogPath, result.stdout + result.stderr);
});

const bundleYaml = parseYaml(readFileSync(join(cwd, ".apphosting/bundle.yaml")).toString());

const runCommand = bundleYaml.runConfig.runCommand;

if (typeof runCommand !== "string") {
throw new Error("runCommand must be a string");
}

const [runScript, ...runArgs] = runCommand.split(" ");
let resolveHostname: (it: string) => void;
let rejectHostname: () => void;
const hostnamePromise = new Promise<string>((resolve, reject) => {
resolveHostname = resolve;
rejectHostname = reject;
});
const port = 8080 + Math.floor(Math.random() * 1000);
const runLogPath = join(cwd, "run.log");
console.log(`[${runId}] > PORT=${port} ${runCommand} (output written to ${runLogPath})`);
const runLogStream = fsExtra.createWriteStream(runLogPath);

const run = spawn(runScript, runArgs, {
cwd,
shell: true,
env: {
NODE_ENV: "production",
PORT: port.toString(),
PATH: process.env.PATH,
},
});

run.stderr.on("data", (data) => {
const output = data.toString();
runLogStream.write(output);
});

run.stdout.on("data", (data) => {
const output = data.toString();
runLogStream.write(output);
// Check for the "Ready in" message to determine when the server is fully started
if (output.includes(`Ready in`)) {
// We use 0.0.0.0 instead of localhost to avoid issues when ipv6 is not available (Node 18)
resolveHostname(`http://0.0.0.0:${port}`);
}
});

run.on("close", (code) => {
runLogStream.end();
if (code) {
rejectHostname();
}
});
const host = await hostnamePromise;

console.log("\n\n");

try {
// Determine which test files to run
const testPattern = scenario.tests
? scenario.tests.map((test) => `e2e/${test}`).join(" ")
: "e2e/*.spec.ts";

console.log(
`> HOST=${host} SCENARIO=${scenario.name} ts-mocha -p tsconfig.json ${testPattern}`,
);
await promiseSpawn("ts-mocha", ["-p", "tsconfig.json", ...testPattern.split(" ")], {
shell: true,
stdio: "inherit",
env: {
...process.env,
HOST: host,
SCENARIO: scenario.name,
},
}).finally(() => {
run.stdin.end();
run.kill("SIGKILL");
});
} catch (e) {
errors.push(e);
}
} catch (e) {
console.error(`Error in scenario ${scenario.name}:`, e);
errors.push(e);
}
}

if (errors.length) {
Expand Down
4 changes: 2 additions & 2 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.9",
"version": "14.0.10",
"main": "dist/index.js",
"description": "Experimental addon to the Firebase CLI to add web framework support",
"repository": {
Expand All @@ -23,7 +23,7 @@
"scripts": {
"build": "rm -rf dist && tsc && chmod +x ./dist/bin/*",
"test": "npm run test:unit && npm run test:functional",
"test:unit": "ts-mocha -p tsconfig.json src/**/*.spec.ts",
"test:unit": "ts-mocha -p tsconfig.json 'src/**/*.spec.ts' 'src/*.spec.ts'",
"test:functional": "node --loader ts-node/esm ./e2e/run-local.ts",
"localregistry:start": "npx verdaccio --config ../publish-dev/verdaccio-config.yaml",
"localregistry:publish": "(npm view --registry=http://localhost:4873 @apphosting/adapter-nextjs && npm unpublish --@apphosting:registry=http://localhost:4873 --force); npm publish --@apphosting:registry=http://localhost:4873"
Expand Down
Loading