From 0bca8b6b00e206cbdf3246d8d2ac7d333ed33642 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 17:11:19 +0530 Subject: [PATCH 01/26] fix(functions): load .env before bundling and importing functions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit functions:serve loaded the project's .env only after every function had been bundled and imported, so code that reads a variable at the top of a function file (an SDK or DB client built at load time) saw undefined. Deployed functions have their environment set before they load. Load .env right after the functions/ directory check, before the functions are parsed. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 11 ++++++++--- src/functions/cloud-functions.ts | 4 ++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 02110f38..52250b27 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -307,19 +307,24 @@ describe('CloudFunctions serve routing', () => { expect((loggedErrors[0] as Error).message).toBe('handler blew up'); }); - it('loads the env file that sits beside the functions directory', async () => { + it('loads the env file beside the functions directory before the functions load', async () => { const envValue = randomUUID(); writeFileSync(join(workspace, '.env'), `LAUNCH_TEST_VALUE=${envValue}\n`); writeFunctionFile( 'env.js', - 'export default function env(request, response) { response.json({ value: process.env.LAUNCH_TEST_VALUE }); }', + [ + 'const atLoad = process.env.LAUNCH_TEST_VALUE;', + 'export default function env(request, response) {', + ' response.json({ atRequest: process.env.LAUNCH_TEST_VALUE, atLoad });', + '}', + ].join('\n'), ); const port = await freePort(); await new CloudFunctions(workspace).serve(port); const response = await sendRequest(port, '/env'); - expect(JSON.parse(response.body)).toEqual({ value: envValue }); + expect(JSON.parse(response.body)).toEqual({ atRequest: envValue, atLoad: envValue }); delete process.env.LAUNCH_TEST_VALUE; }); }); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index baa49449..34b28af2 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -52,6 +52,8 @@ export class CloudFunctions { if (!directoryExists) { throw new FunctionsDirectoryNotFoundError(this.pathToSourceCode); } + dotenv.config({ path: path.join(this.pathToSourceCode, ENV_FILE_NAME) }); + const cloudFunctionResources = await this.parseCloudFunctionResources(); const hasCloudFunctionResources = cloudFunctionResources.length; @@ -76,8 +78,6 @@ export class CloudFunctions { await this.applyAppRouter(exactRouteResources, app); await this.applyAppRouter(dynamicRouteResources, app); - dotenv.config({ path: path.join(this.pathToSourceCode, ENV_FILE_NAME) }); - return this.startServer(app, servingPort, [ ...exactRouteResources, ...dynamicRouteResources, From 0ce7259a6864c4d2d62464151b23c354fde5beaa Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 17:21:29 +0530 Subject: [PATCH 02/26] fix(functions): parse the Cookie header into request.cookies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The local server never set request.cookies, so it was always undefined, while a deployed function gets the parsed cookies (the AWS Lambda bridge parses them with the cookie package). The docs' debugging example reads request.cookies too. Parse the header with cookie, now a direct dependency at the version express already pulls in, before any function route runs. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- package-lock.json | 11 +++++++++++ package.json | 2 ++ src/functions/cloud-functions.test.ts | 19 +++++++++++++++++-- src/functions/cloud-functions.ts | 8 ++++++++ 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index c0038e7b..48ca4cf6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-node-resolve": "^16.0.3", "adm-zip": "^0.6.1", + "cookie": "^0.7.2", "dotenv": "^16.4.7", "express": "^4.22.3", "https-proxy-agent": "^5.0.1", @@ -31,6 +32,7 @@ "devDependencies": { "@eslint/js": "^9.39.5", "@oclif/test": "^4.2.0", + "@types/cookie": "^0.6.0", "@types/express": "^4.17.25", "@types/express-serve-static-core": "^4.19.9", "@types/jest": "^29.5.14", @@ -3718,6 +3720,13 @@ "@types/node": "*" } }, + "node_modules/@types/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "license": "MIT" @@ -5774,6 +5783,8 @@ }, "node_modules/cookie": { "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", "license": "MIT", "engines": { "node": ">= 0.6" diff --git a/package.json b/package.json index c708d50b..9a3d0cc4 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-node-resolve": "^16.0.3", "adm-zip": "^0.6.1", + "cookie": "^0.7.2", "dotenv": "^16.4.7", "express": "^4.22.3", "https-proxy-agent": "^5.0.1", @@ -39,6 +40,7 @@ "devDependencies": { "@eslint/js": "^9.39.5", "@oclif/test": "^4.2.0", + "@types/cookie": "^0.6.0", "@types/express": "^4.17.25", "@types/express-serve-static-core": "^4.19.9", "@types/jest": "^29.5.14", diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 52250b27..3c3ad959 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -43,9 +43,14 @@ function freePort(): Promise { }); } -function sendRequest(port: number, path: string, method = 'GET'): Promise { +function sendRequest( + port: number, + path: string, + method = 'GET', + headers: Record = {}, +): Promise { return new Promise((resolve, reject) => { - const clientRequest = httpRequest({ host: '127.0.0.1', port, path, method }, (response) => { + const clientRequest = httpRequest({ host: '127.0.0.1', port, path, method, headers }, (response) => { let body = ''; response.setEncoding('utf8'); response.on('data', (chunk) => { @@ -272,6 +277,16 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ method: 'POST' }); }); + it('parses the cookie header into request.cookies', async () => { + writeFunctionFile('cookies.js', 'export default function cookies(request, response) { response.json(request.cookies); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/cookies', 'GET', { cookie: 'sid=abc; theme=dark%20mode' }); + + expect(JSON.parse(response.body)).toEqual({ sid: 'abc', theme: 'dark mode' }); + }); + it('answers 404 for a path no function claims', async () => { writeFunctionFile('hello.js', 'export default function hello(request, response) { response.send("hi"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 34b28af2..de4a638b 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -1,5 +1,7 @@ +import { parse as parseCookieHeader } from 'cookie'; import dotenv from 'dotenv'; import type { + NextFunction, Request, Response, } from 'express'; @@ -74,6 +76,12 @@ export class CloudFunctions { const app = express(); app.disable('x-powered-by'); + app.use((request: Request, _response: Response, next: NextFunction) => { + if (request.headers.cookie) { + request.cookies = parseCookieHeader(request.headers.cookie); + } + next(); + }); await this.applyAppRouter(exactRouteResources, app); await this.applyAppRouter(dynamicRouteResources, app); From a36c659cced8a132516ad8415ea4250249f8f1d8 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 17:24:55 +0530 Subject: [PATCH 03/26] refactor(functions): name the cookie middleware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the inline cookie-parsing middleware out of serve() into a named attachCookies function, so serve() reads as a list of steps. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index de4a638b..bb5f5d71 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -29,6 +29,13 @@ function isHandler(value: unknown): value is CloudFunctionHandler { return typeof value === 'function'; } +function attachCookies(request: Request, _response: Response, next: NextFunction): void { + if (request.headers.cookie) { + request.cookies = parseCookieHeader(request.headers.cookie); + } + next(); +} + import { loadDataURL } from './load-data-url'; export function listenFailure(error: NodeJS.ErrnoException, servingPort: number): Error { @@ -76,12 +83,7 @@ export class CloudFunctions { const app = express(); app.disable('x-powered-by'); - app.use((request: Request, _response: Response, next: NextFunction) => { - if (request.headers.cookie) { - request.cookies = parseCookieHeader(request.headers.cookie); - } - next(); - }); + app.use(attachCookies); await this.applyAppRouter(exactRouteResources, app); await this.applyAppRouter(dynamicRouteResources, app); From cd978d78ac250293e320210d497bd9768e6fb12d Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 17:28:33 +0530 Subject: [PATCH 04/26] fix(functions): give request.cookies an empty object with no Cookie header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request without a Cookie header left request.cookies undefined, so a handler that reads request.cookies.sid threw. Deployed functions get {} in that case (the AWS Lambda bridge's cookie parser returns {} for a missing header). Match it. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 10 ++++++++++ src/functions/cloud-functions.ts | 4 +--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 3c3ad959..ea0d980c 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -287,6 +287,16 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ sid: 'abc', theme: 'dark mode' }); }); + it('gives request.cookies an empty object when no cookie header is sent', async () => { + writeFunctionFile('cookies.js', 'export default function cookies(request, response) { response.json(request.cookies); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/cookies'); + + expect(JSON.parse(response.body)).toEqual({}); + }); + it('answers 404 for a path no function claims', async () => { writeFunctionFile('hello.js', 'export default function hello(request, response) { response.send("hi"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index bb5f5d71..e9794f59 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -30,9 +30,7 @@ function isHandler(value: unknown): value is CloudFunctionHandler { } function attachCookies(request: Request, _response: Response, next: NextFunction): void { - if (request.headers.cookie) { - request.cookies = parseCookieHeader(request.headers.cookie); - } + request.cookies = request.headers.cookie ? parseCookieHeader(request.headers.cookie) : {}; next(); } From 9b8a08fa4f6bd2abef1ed9ae61b817a976dbc2a2 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 17:35:14 +0530 Subject: [PATCH 05/26] fix(functions): hand a text/plain body to the handler as the raw string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only the JSON and urlencoded parsers were registered, so a text/plain POST reached the handler as {} and the raw text was lost. Deployed functions get the raw string (the AWS Lambda bridge returns the body as-is for text/plain). Register express.text() before the function routes. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 13 ++++++++++++- src/functions/cloud-functions.ts | 1 + 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index ea0d980c..38dc3c7a 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -48,6 +48,7 @@ function sendRequest( path: string, method = 'GET', headers: Record = {}, + body?: string, ): Promise { return new Promise((resolve, reject) => { const clientRequest = httpRequest({ host: '127.0.0.1', port, path, method, headers }, (response) => { @@ -65,7 +66,7 @@ function sendRequest( }); }); clientRequest.on('error', reject); - clientRequest.end(); + clientRequest.end(body); }); } @@ -297,6 +298,16 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({}); }); + it('hands a text/plain body to the handler as the raw string', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/body', 'POST', { 'content-type': 'text/plain' }, 'raw text'); + + expect(JSON.parse(response.body)).toEqual({ body: 'raw text' }); + }); + it('answers 404 for a path no function claims', async () => { writeFunctionFile('hello.js', 'export default function hello(request, response) { response.send("hi"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index e9794f59..19860f71 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -82,6 +82,7 @@ export class CloudFunctions { const app = express(); app.disable('x-powered-by'); app.use(attachCookies); + app.use(express.text()); await this.applyAppRouter(exactRouteResources, app); await this.applyAppRouter(dynamicRouteResources, app); From 6ae81f037cb9534671f6ef69c9fd171ddac23f9a Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 17:35:57 +0530 Subject: [PATCH 06/26] refactor(test): take sendRequest's method, headers and body as options MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sendRequest had grown five positional arguments. Pass method, headers and body as one options object so each call says what it sends. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 38dc3c7a..494c75a2 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -43,13 +43,13 @@ function freePort(): Promise { }); } -function sendRequest( - port: number, - path: string, - method = 'GET', - headers: Record = {}, - body?: string, -): Promise { +interface RequestOptions { + method?: string; + headers?: Record; + body?: string; +} + +function sendRequest(port: number, path: string, { method = 'GET', headers = {}, body }: RequestOptions = {}): Promise { return new Promise((resolve, reject) => { const clientRequest = httpRequest({ host: '127.0.0.1', port, path, method, headers }, (response) => { let body = ''; @@ -273,7 +273,7 @@ describe('CloudFunctions serve routing', () => { const port = await freePort(); await new CloudFunctions(workspace).serve(port); - const response = await sendRequest(port, '/echo', 'POST'); + const response = await sendRequest(port, '/echo', { method: 'POST' }); expect(JSON.parse(response.body)).toEqual({ method: 'POST' }); }); @@ -283,7 +283,7 @@ describe('CloudFunctions serve routing', () => { const port = await freePort(); await new CloudFunctions(workspace).serve(port); - const response = await sendRequest(port, '/cookies', 'GET', { cookie: 'sid=abc; theme=dark%20mode' }); + const response = await sendRequest(port, '/cookies', { headers: { cookie: 'sid=abc; theme=dark%20mode' } }); expect(JSON.parse(response.body)).toEqual({ sid: 'abc', theme: 'dark mode' }); }); @@ -303,7 +303,11 @@ describe('CloudFunctions serve routing', () => { const port = await freePort(); await new CloudFunctions(workspace).serve(port); - const response = await sendRequest(port, '/body', 'POST', { 'content-type': 'text/plain' }, 'raw text'); + const response = await sendRequest(port, '/body', { + method: 'POST', + headers: { 'content-type': 'text/plain' }, + body: 'raw text', + }); expect(JSON.parse(response.body)).toEqual({ body: 'raw text' }); }); From fe55a281bfb6988ed5265411c40e68f0104182e7 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 17:40:10 +0530 Subject: [PATCH 07/26] fix(functions): hand an application/octet-stream body to the handler as a buffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An application/octet-stream POST reached the handler as {}, so binary uploads were lost. Deployed functions get a Buffer (the AWS Lambda bridge decodes octet-stream bodies into one). Register express.raw() before the function routes. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 21 +++++++++++++++++++++ src/functions/cloud-functions.ts | 1 + 2 files changed, 22 insertions(+) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 494c75a2..c93a7357 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -312,6 +312,27 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ body: 'raw text' }); }); + it('hands an application/octet-stream body to the handler as a buffer', async () => { + writeFunctionFile( + 'binary.js', + [ + 'export default function binary(request, response) {', + ' response.json({ isBuffer: Buffer.isBuffer(request.body), text: String(request.body) });', + '}', + ].join('\n'), + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/binary', { + method: 'POST', + headers: { 'content-type': 'application/octet-stream' }, + body: 'binary data', + }); + + expect(JSON.parse(response.body)).toEqual({ isBuffer: true, text: 'binary data' }); + }); + it('answers 404 for a path no function claims', async () => { writeFunctionFile('hello.js', 'export default function hello(request, response) { response.send("hi"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 19860f71..fc2a16d0 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -83,6 +83,7 @@ export class CloudFunctions { app.disable('x-powered-by'); app.use(attachCookies); app.use(express.text()); + app.use(express.raw()); await this.applyAppRouter(exactRouteResources, app); await this.applyAppRouter(dynamicRouteResources, app); From 1bd68c03cd63275285cb9e7765baabbeb70f27ca Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 18:06:13 +0530 Subject: [PATCH 08/26] test(functions): pin JSON and urlencoded bodies reaching the handler parsed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No test sent a JSON or urlencoded body, so nothing would notice if those parsers stopped running. Pin both before moving where they are registered. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index c93a7357..4ba04a47 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -298,6 +298,19 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({}); }); + it.each([ + ['application/json', '{"name":"launch","tags":["a","b"]}'], + ['application/x-www-form-urlencoded', 'name=launch&tags[]=a&tags[]=b'], + ])('hands a %s body to the handler as a parsed object', async (contentType, body) => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/body', { method: 'POST', headers: { 'content-type': contentType }, body }); + + expect(JSON.parse(response.body)).toEqual({ body: { name: 'launch', tags: ['a', 'b'] } }); + }); + it('hands a text/plain body to the handler as the raw string', async () => { writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); const port = await freePort(); From dd8f06346acef8bd8df08f47967a09cf007937a3 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 18:10:13 +0530 Subject: [PATCH 09/26] refactor(functions): register request middleware once, not once per function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit applyAppRouter added express.json(), express.urlencoded() and the cache-control default inside its per-function loop, so N functions stacked N copies of each. Only the first copy did anything. Register every request middleware once, in applyRequestMiddleware, and leave applyAppRouter to register the routes. With nothing async left in its loop, it no longer needs Promise.all. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.ts | 66 +++++++++++++++----------------- 1 file changed, 30 insertions(+), 36 deletions(-) diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index fc2a16d0..ab375ac5 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -34,6 +34,22 @@ function attachCookies(request: Request, _response: Response, next: NextFunction next(); } +function defaultToNoStore(_request: Request, response: Response, next: NextFunction): void { + if (!response.getHeader('cache-control')) { + response.setHeader('cache-control', 'no-store'); + } + next(); +} + +function applyRequestMiddleware(app: Express): void { + app.use(attachCookies); + app.use(express.json()); + app.use(express.urlencoded({ extended: true })); + app.use(express.text()); + app.use(express.raw()); + app.use(defaultToNoStore); +} + import { loadDataURL } from './load-data-url'; export function listenFailure(error: NodeJS.ErrnoException, servingPort: number): Error { @@ -81,12 +97,9 @@ export class CloudFunctions { const app = express(); app.disable('x-powered-by'); - app.use(attachCookies); - app.use(express.text()); - app.use(express.raw()); - - await this.applyAppRouter(exactRouteResources, app); - await this.applyAppRouter(dynamicRouteResources, app); + applyRequestMiddleware(app); + this.applyAppRouter(exactRouteResources, app); + this.applyAppRouter(dynamicRouteResources, app); return this.startServer(app, servingPort, [ ...exactRouteResources, @@ -127,36 +140,17 @@ export class CloudFunctions { }); } - private async applyAppRouter( - cloudFunctionResources: CloudFunctionResource[], - app: Express - ): Promise { - await Promise.all( - cloudFunctionResources.map(async (cloudFunctionResource) => { - - app.use(express.json()); - app.use(express.urlencoded({ extended: true })); - - app.use((_request: Request, response: Response, next) => { - if (!response.getHeader('cache-control')) { - response.setHeader('cache-control', 'no-store'); - } - next(); - }); - - app.all( - cloudFunctionResource.apiResourceURI, - async (request: Request, response: Response) => { - try { - await cloudFunctionResource.handler(request, response); - } catch (error) { - console.error(error); - response.status(500).send(); - } - } - ); - }) - ); + private applyAppRouter(cloudFunctionResources: CloudFunctionResource[], app: Express): void { + cloudFunctionResources.forEach((cloudFunctionResource) => { + app.all(cloudFunctionResource.apiResourceURI, async (request: Request, response: Response) => { + try { + await cloudFunctionResource.handler(request, response); + } catch (error) { + console.error(error); + response.status(500).send(); + } + }); + }); } private isProxyEdgeFile(filename: string): boolean { From 05b072362ad5495929b2c5eb33d4a831759a1711 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 18:22:47 +0530 Subject: [PATCH 10/26] feat(functions): warn when a function imports a file outside functions/ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rollup bundles anything it can resolve, so a function that imports ../../shared/util.js works under functions:serve but fails once deployed, where only functions/ is available. The local server hid a problem that only showed up in production. After bundling each function, print a warn: line for every bundled file outside functions/, naming the function file and the outside file relative to the project. It stays a warning so existing local setups keep running. Paths are compared after resolving symlinks, so a project under a symlinked directory is not misreported. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 25 +++++++++++++++++++++++-- src/functions/cloud-functions.ts | 19 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 4ba04a47..7facb68b 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -27,12 +27,16 @@ let loggedLines: string[]; let loggedErrors: unknown[]; let exitCodes: (number | undefined)[]; -function writeFunctionFile(relativePath: string, source: string): void { - const absolutePath = join(workspace, 'functions', relativePath); +function writeProjectFile(relativePath: string, source: string): void { + const absolutePath = join(workspace, relativePath); mkdirSync(dirname(absolutePath), { recursive: true }); writeFileSync(absolutePath, source); } +function writeFunctionFile(relativePath: string, source: string): void { + writeProjectFile(join('functions', relativePath), source); +} + function freePort(): Promise { return new Promise((resolve) => { const probe = createServer(); @@ -346,6 +350,23 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ isBuffer: true, text: 'binary data' }); }); + it('warns about an import from outside the functions directory and still serves the function', async () => { + writeProjectFile(join('shared', 'util.js'), 'export const greeting = "shared";'); + writeFunctionFile( + join('api', 'x.js'), + 'import { greeting } from "../../shared/util.js"; export default function x(request, response) { response.send(greeting); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/api/x'); + + expect(response.body).toBe('shared'); + expect(loggedLines).toContain( + 'warn: functions/api/x.js imports shared/util.js, which is outside functions/ and will not be available when deployed.', + ); + }); + it('answers 404 for a path no function claims', async () => { writeFunctionFile('hello.js', 'export default function hello(request, response) { response.send("hi"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index ab375ac5..e8b2a5b9 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -7,6 +7,7 @@ import type { } from 'express'; import express from 'express'; import type { Express } from 'express-serve-static-core'; +import { realpathSync } from 'fs'; import type { Server } from 'http'; import path from 'path'; @@ -230,6 +231,23 @@ export class CloudFunctions { return { exactRouteResources, dynamicRouteResources }; } + private warnAboutImportsOutsideFunctions(cloudFunctionFilePath: string, bundledFiles: string[]): void { + const projectDirectory = realpathSync(this.pathToSourceCode); + const functionsDirectory = realpathSync(this.cloudFunctionsDirectoryPath); + const importer = path.relative(projectDirectory, realpathSync(cloudFunctionFilePath)); + + bundledFiles + .map((bundledFile) => realpathSync(bundledFile)) + .filter((bundledFile) => path.relative(functionsDirectory, bundledFile).startsWith('..')) + .forEach((outsideFile) => { + const imported = path.relative(projectDirectory, outsideFile); + const warning = + `warn: ${importer} imports ${imported}, ` + + `which is outside ${CLOUD_FUNCTIONS_DIRECTORY}/ and will not be available when deployed.`; + console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); + }); + } + private async buildHandlerForFilepath(cloudFunctionFilePath: string): Promise { const [{ rollup }, { nodeResolve }, { default: commonjs }, { default: json }] = await Promise.all([ import('rollup'), @@ -241,6 +259,7 @@ export class CloudFunctions { input: cloudFunctionFilePath, plugins: [nodeResolve({ preferBuiltins: true }), commonjs(), json()], }); + this.warnAboutImportsOutsideFunctions(cloudFunctionFilePath, bundle.watchFiles); const { output } = await bundle.generate({ format: 'esm', From d76f8747409ccc97a16ac727658d9b2e727e8b1b Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 18:27:36 +0530 Subject: [PATCH 11/26] fix(functions): do not warn about packages imported from node_modules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The outside-functions/ warning fired for every npm package a function imported, because node_modules sits outside functions/. Packages are installed for the deployed function, so they are not a problem. Skip any bundled file under a node_modules directory. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 21 +++++++++++++++++++++ src/functions/cloud-functions.ts | 1 + 2 files changed, 22 insertions(+) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 7facb68b..522ef80f 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -367,6 +367,27 @@ describe('CloudFunctions serve routing', () => { ); }); + it('does not warn about a package imported from node_modules', async () => { + writeProjectFile(join('node_modules', 'fake-pkg', 'package.json'), '{"name":"fake-pkg","main":"index.js"}'); + writeProjectFile(join('node_modules', 'fake-pkg', 'index.js'), 'module.exports = { greeting: "from package" };'); + writeFunctionFile( + 'pkg.js', + 'import pkg from "fake-pkg"; export default function usesPkg(request, response) { response.send(pkg.greeting); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/pkg'); + + expect(response.body).toBe('from package'); + expect(loggedLines).toEqual([ + 'Detected Serverless Functions:', + ' 位 /pkg', + '', + `Serving Cloud Functions at http://localhost:${port}`, + ]); + }); + it('answers 404 for a path no function claims', async () => { writeFunctionFile('hello.js', 'export default function hello(request, response) { response.send("hi"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index e8b2a5b9..55c20514 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -239,6 +239,7 @@ export class CloudFunctions { bundledFiles .map((bundledFile) => realpathSync(bundledFile)) .filter((bundledFile) => path.relative(functionsDirectory, bundledFile).startsWith('..')) + .filter((bundledFile) => !bundledFile.split(path.sep).includes('node_modules')) .forEach((outsideFile) => { const imported = path.relative(projectDirectory, outsideFile); const warning = From 165c29adb96d7de2bed0530c3d13e6ff988f267a Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Wed, 18 Nov 2026 19:21:45 +0530 Subject: [PATCH 12/26] fix(functions): print the port the server listens on, not the one requested MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With --port 0 the server listens on a random free port, but the CLI printed "Serving Cloud Functions at http://localhost:0", so there was no way to know where to send requests. Print the port from server.address() once the server is listening. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 10 ++++++++++ src/functions/cloud-functions.ts | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 522ef80f..17d001d5 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -216,6 +216,16 @@ describe('CloudFunctions serve routing', () => { ]); }); + it('prints the port the server actually listens on when asked for port zero', async () => { + writeFunctionFile('hello.js', 'export default function hello(request, response) { response.send("hi"); }'); + + const server = (await new CloudFunctions(workspace).serve(0)) as Server; + const { port } = server.address() as AddressInfo; + + expect(port).not.toBe(0); + expect(loggedLines).toContain(`Serving Cloud Functions at http://localhost:${port}`); + }); + it('colours the serving url cyan when stdout is a terminal', async () => { writeFunctionFile('hello.js', 'export default function hello(request, response) { response.end(); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 55c20514..521678aa 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -9,6 +9,7 @@ import express from 'express'; import type { Express } from 'express-serve-static-core'; import { realpathSync } from 'fs'; import type { Server } from 'http'; +import type { AddressInfo } from 'net'; import path from 'path'; import { styled } from '../core/style'; @@ -133,7 +134,7 @@ export class CloudFunctions { const server = app.listen(servingPort, () => { server.off('error', refuse); - this.printServing(servingPort, cloudFunctionResources); + this.printServing((server.address() as AddressInfo).port, cloudFunctionResources); resolve(server); }); From 61d6434c13b194eda6ec1341196ef48c2d3a748f Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 13:12:37 +0530 Subject: [PATCH 13/26] fix(functions): accept text and octet-stream bodies up to Lambda's 6mb cap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit express.text() and express.raw() default to a 100kb limit, so a 150kb text/plain or 300kb binary upload got an Express 413 before the handler ran. Before those parsers were added such bodies reached the handler unread, and deployed AWS functions accept payloads up to 6mb. Give both parsers a 6mb limit, matching the AWS Lambda payload cap, as agreed with the ticket's reporter (match AWS). #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 15 +++++++++++++++ src/functions/cloud-functions.ts | 6 ++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 17d001d5..250a9a6f 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -325,6 +325,21 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ body: { name: 'launch', tags: ['a', 'b'] } }); }); + it.each(['text/plain', 'application/octet-stream'])( + 'hands a %s body over the 100kb parser default to the handler, as Lambda allows', + async (contentType) => { + writeFunctionFile('size.js', 'export default function size(request, response) { response.json({ length: request.body.length }); }'); + const body = 'a'.repeat(200 * 1024); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/size', { method: 'POST', headers: { 'content-type': contentType }, body }); + + expect(response.status).toBe(200); + expect(JSON.parse(response.body)).toEqual({ length: body.length }); + }, + ); + it('hands a text/plain body to the handler as the raw string', async () => { writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 521678aa..8ed367f1 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -27,6 +27,8 @@ import type { CloudFunctionResource } from './types'; type CloudFunctionHandler = CloudFunctionResource['handler']; +const DEPLOYED_PAYLOAD_LIMIT = '6mb'; + function isHandler(value: unknown): value is CloudFunctionHandler { return typeof value === 'function'; } @@ -47,8 +49,8 @@ function applyRequestMiddleware(app: Express): void { app.use(attachCookies); app.use(express.json()); app.use(express.urlencoded({ extended: true })); - app.use(express.text()); - app.use(express.raw()); + app.use(express.text({ limit: DEPLOYED_PAYLOAD_LIMIT })); + app.use(express.raw({ limit: DEPLOYED_PAYLOAD_LIMIT })); app.use(defaultToNoStore); } From 857f93cf1119734742cdb7f4b622884e39daf705 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 14:50:35 +0530 Subject: [PATCH 14/26] fix(functions): stop flagging functions subfolders named with two leading dots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The outside-functions/ check treated any relative path starting with ".." as outside, so a file in functions/..shared/ got a false "outside functions/" warning. Treat a file as outside only when its relative path is ".." or starts with "../". #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 20 ++++++++++++++++++++ src/functions/cloud-functions.ts | 7 ++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 250a9a6f..a207ad77 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -392,6 +392,26 @@ describe('CloudFunctions serve routing', () => { ); }); + it('does not warn about a file in a functions subfolder whose name starts with two dots', async () => { + writeFunctionFile(join('..shared', 'util.js'), 'export const greeting = "inside";'); + writeFunctionFile( + 'dots.js', + 'import { greeting } from "./..shared/util.js"; export default function dots(request, response) { response.send(greeting); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/dots'); + + expect(response.body).toBe('inside'); + expect(loggedLines).toEqual([ + 'Detected Serverless Functions:', + ' 位 /dots', + '', + `Serving Cloud Functions at http://localhost:${port}`, + ]); + }); + it('does not warn about a package imported from node_modules', async () => { writeProjectFile(join('node_modules', 'fake-pkg', 'package.json'), '{"name":"fake-pkg","main":"index.js"}'); writeProjectFile(join('node_modules', 'fake-pkg', 'index.js'), 'module.exports = { greeting: "from package" };'); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 8ed367f1..12754e85 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -33,6 +33,11 @@ function isHandler(value: unknown): value is CloudFunctionHandler { return typeof value === 'function'; } +function isOutsideDirectory(directory: string, file: string): boolean { + const relativePath = path.relative(directory, file); + return relativePath === '..' || relativePath.startsWith(`..${path.sep}`); +} + function attachCookies(request: Request, _response: Response, next: NextFunction): void { request.cookies = request.headers.cookie ? parseCookieHeader(request.headers.cookie) : {}; next(); @@ -241,7 +246,7 @@ export class CloudFunctions { bundledFiles .map((bundledFile) => realpathSync(bundledFile)) - .filter((bundledFile) => path.relative(functionsDirectory, bundledFile).startsWith('..')) + .filter((bundledFile) => isOutsideDirectory(functionsDirectory, bundledFile)) .filter((bundledFile) => !bundledFile.split(path.sep).includes('node_modules')) .forEach((outsideFile) => { const imported = path.relative(projectDirectory, outsideFile); From e70b8a3a9d83268fe60136406ff23549ca9e1605 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 15:00:13 +0530 Subject: [PATCH 15/26] fix(functions): warn about imports from another Windows drive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Windows, path.relative returns an absolute path when the file is on a different drive from functions/ (D:\lib\a.js against C:\app\functions), so the outside-functions/ check saw no leading ".." and stayed silent about a file that will not be deployed. Treat an absolute relative path as outside too. isOutsideDirectory is exported and takes an optional path module, so the Windows behaviour is tested with path.win32. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 10 ++++++++-- src/functions/cloud-functions.ts | 6 +++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index a207ad77..364eccfe 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -5,9 +5,9 @@ import { createServer } from 'http'; import { request as httpRequest } from 'http'; import type { AddressInfo } from 'net'; import { tmpdir } from 'os'; -import { dirname, join } from 'path'; +import { dirname, join, win32 } from 'path'; -import { CloudFunctions, listenFailure } from './cloud-functions'; +import { CloudFunctions, isOutsideDirectory, listenFailure } from './cloud-functions'; import { PortInUseError } from './function.errors'; import { loadDataURL } from './load-data-url'; @@ -490,6 +490,12 @@ describe('CloudFunctions serve routing', () => { }); }); +describe('isOutsideDirectory', () => { + it('treats a file on another Windows drive as outside the directory', () => { + expect(isOutsideDirectory('C:\\app\\functions', 'D:\\lib\\a.js', win32)).toBe(true); + }); +}); + describe('CloudFunctions serve failures', () => { it('rejects with the validation error the validator raised', async () => { writeFunctionFile('[id].js', 'export default function top(request, response) { response.send("top"); }'); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 12754e85..f2410377 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -33,9 +33,9 @@ function isHandler(value: unknown): value is CloudFunctionHandler { return typeof value === 'function'; } -function isOutsideDirectory(directory: string, file: string): boolean { - const relativePath = path.relative(directory, file); - return relativePath === '..' || relativePath.startsWith(`..${path.sep}`); +export function isOutsideDirectory(directory: string, file: string, pathApi: path.PlatformPath = path): boolean { + const relativePath = pathApi.relative(directory, file); + return relativePath === '..' || relativePath.startsWith(`..${pathApi.sep}`) || pathApi.isAbsolute(relativePath); } function attachCookies(request: Request, _response: Response, next: NextFunction): void { From a79b5cae4ef7e7bd419a90e5812bc496e7144ad3 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 17:23:14 +0530 Subject: [PATCH 16/26] fix(functions): name the function that reaches an outside file, once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The outside-functions/ warning always named the function being bundled. When ten functions shared functions/lib/db.js, which imports ../../config.js, it printed eleven warnings, ten of them blaming functions that never mention config.js. A small rollup plugin now records each module's static and dynamic importers at buildEnd. Each warning names the function file that reaches the outside file, walking past outside files and the commonjs plugin's virtual proxy modules (with a guard against cycles between them), so a chain like functions/a.js -> ../other.js -> ./config.js still names functions/a.js, and a require() of an outside ES module names the CommonJS function rather than "\0...?commonjs-proxy". Identical warnings print once across all functions. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 91 ++++++++++++++++++++++++++- src/functions/cloud-functions.ts | 68 ++++++++++++++++---- 2 files changed, 146 insertions(+), 13 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 364eccfe..3fea3007 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -7,7 +7,7 @@ import type { AddressInfo } from 'net'; import { tmpdir } from 'os'; import { dirname, join, win32 } from 'path'; -import { CloudFunctions, isOutsideDirectory, listenFailure } from './cloud-functions'; +import { CloudFunctions, functionFilesImporting, isOutsideDirectory, listenFailure } from './cloud-functions'; import { PortInUseError } from './function.errors'; import { loadDataURL } from './load-data-url'; @@ -392,6 +392,81 @@ describe('CloudFunctions serve routing', () => { ); }); + it('warns once, naming the shared helper that imports the outside file rather than each function using it', async () => { + writeProjectFile('config.js', 'export const region = "na";'); + writeFunctionFile(join('lib', 'db.js'), 'import { region } from "../../config.js"; export const db = `db-${region}`;'); + writeFunctionFile('a.js', 'import { db } from "./lib/db.js"; export default function a(request, response) { response.send(db); }'); + writeFunctionFile('b.js', 'import { db } from "./lib/db.js"; export default function b(request, response) { response.send(db); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + + expect(loggedLines).toEqual([ + 'warn: functions/lib/db.js imports config.js, which is outside functions/ and will not be available when deployed.', + 'Detected Serverless Functions:', + ' 位 /a', + ' 位 /b', + '', + `Serving Cloud Functions at http://localhost:${port}`, + ]); + }); + + it('names the function, not an outside file, for an outside file reached through another outside file', async () => { + writeProjectFile('config.js', 'export const region = "na";'); + writeProjectFile('other.js', 'import { region } from "./config.js"; export const label = `other-${region}`;'); + writeFunctionFile('a.js', 'import { label } from "../other.js"; export default function a(request, response) { response.send(label); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + + expect(loggedLines).toEqual([ + 'warn: functions/a.js imports other.js, which is outside functions/ and will not be available when deployed.', + 'warn: functions/a.js imports config.js, which is outside functions/ and will not be available when deployed.', + 'Detected Serverless Functions:', + ' 位 /a', + '', + `Serving Cloud Functions at http://localhost:${port}`, + ]); + }); + + it('warns about an outside file reached through a dynamic import', async () => { + writeProjectFile('config.js', 'export const region = "na";'); + writeFunctionFile( + 'dyn.js', + 'export default async function dyn(request, response) { const { region } = await import("../config.js"); response.send(region); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + + expect(loggedLines).toEqual([ + 'warn: functions/dyn.js imports config.js, which is outside functions/ and will not be available when deployed.', + 'Detected Serverless Functions:', + ' 位 /dyn', + '', + `Serving Cloud Functions at http://localhost:${port}`, + ]); + }); + + it('names the commonjs function, not the bundler proxy, when it requires an outside es module', async () => { + writeProjectFile('config.js', 'export const region = "na";'); + writeFunctionFile( + 'cjs.js', + 'const { region } = require("../config.js"); module.exports = function cjs(request, response) { response.send(region); };', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + + expect(loggedLines).toEqual([ + 'warn: functions/cjs.js imports config.js, which is outside functions/ and will not be available when deployed.', + 'Detected Serverless Functions:', + ' 位 /cjs', + '', + `Serving Cloud Functions at http://localhost:${port}`, + ]); + }); + it('does not warn about a file in a functions subfolder whose name starts with two dots', async () => { writeFunctionFile(join('..shared', 'util.js'), 'export const greeting = "inside";'); writeFunctionFile( @@ -490,6 +565,20 @@ describe('CloudFunctions serve routing', () => { }); }); +describe('functionFilesImporting', () => { + it('follows virtual importers to function files and stops on a cycle between virtual modules', () => { + const importersById = new Map([ + ['/project/config.js', ['\0config.js?proxy-a']], + ['\0config.js?proxy-a', ['\0config.js?proxy-b', '/project/functions/a.js']], + ['\0config.js?proxy-b', ['\0config.js?proxy-a']], + ]); + + expect(functionFilesImporting('/project/config.js', importersById, '/project/functions')).toEqual([ + '/project/functions/a.js', + ]); + }); +}); + describe('isOutsideDirectory', () => { it('treats a file on another Windows drive as outside the directory', () => { expect(isOutsideDirectory('C:\\app\\functions', 'D:\\lib\\a.js', win32)).toBe(true); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index f2410377..4e04f815 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -11,6 +11,7 @@ import { realpathSync } from 'fs'; import type { Server } from 'http'; import type { AddressInfo } from 'net'; import path from 'path'; +import type { Plugin } from 'rollup'; import { styled } from '../core/style'; import { isRecord } from '../core/values'; @@ -33,6 +34,42 @@ function isHandler(value: unknown): value is CloudFunctionHandler { return typeof value === 'function'; } +export type ImportersById = Map; + +function recordImporters(importersById: ImportersById): Plugin { + return { + name: 'launch-record-importers', + buildEnd() { + for (const moduleId of this.getModuleIds()) { + const moduleInfo = this.getModuleInfo(moduleId); + if (moduleInfo) { + importersById.set(moduleId, [...moduleInfo.importers, ...moduleInfo.dynamicImporters]); + } + } + }, + }; +} + +export function functionFilesImporting( + moduleId: string, + importersById: ImportersById, + functionsDirectory: string, + visited = new Set(), +): string[] { + return (importersById.get(moduleId) ?? []).flatMap((importer) => { + if (path.isAbsolute(importer) && !isOutsideDirectory(functionsDirectory, importer)) { + return [importer]; + } + + if (visited.has(importer)) { + return []; + } + + visited.add(importer); + return functionFilesImporting(importer, importersById, functionsDirectory, visited); + }); +} + export function isOutsideDirectory(directory: string, file: string, pathApi: path.PlatformPath = path): boolean { const relativePath = pathApi.relative(directory, file); return relativePath === '..' || relativePath.startsWith(`..${pathApi.sep}`) || pathApi.isAbsolute(relativePath); @@ -68,6 +105,7 @@ export function listenFailure(error: NodeJS.ErrnoException, servingPort: number) export class CloudFunctions { private cloudFunctionsDirectoryPath: string; private pathToSourceCode: string; + private readonly reportedOutsideImports = new Set(); constructor(pathToSourceCode: string) { this.cloudFunctionsDirectoryPath = path.join( @@ -239,21 +277,26 @@ export class CloudFunctions { return { exactRouteResources, dynamicRouteResources }; } - private warnAboutImportsOutsideFunctions(cloudFunctionFilePath: string, bundledFiles: string[]): void { + private warnAboutImportsOutsideFunctions(importersById: ImportersById): void { const projectDirectory = realpathSync(this.pathToSourceCode); const functionsDirectory = realpathSync(this.cloudFunctionsDirectoryPath); - const importer = path.relative(projectDirectory, realpathSync(cloudFunctionFilePath)); - bundledFiles - .map((bundledFile) => realpathSync(bundledFile)) - .filter((bundledFile) => isOutsideDirectory(functionsDirectory, bundledFile)) - .filter((bundledFile) => !bundledFile.split(path.sep).includes('node_modules')) + [...importersById.keys()] + .filter((moduleId) => path.isAbsolute(moduleId)) + .filter((moduleId) => isOutsideDirectory(functionsDirectory, moduleId)) + .filter((moduleId) => !moduleId.split(path.sep).includes('node_modules')) .forEach((outsideFile) => { const imported = path.relative(projectDirectory, outsideFile); - const warning = - `warn: ${importer} imports ${imported}, ` + - `which is outside ${CLOUD_FUNCTIONS_DIRECTORY}/ and will not be available when deployed.`; - console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); + functionFilesImporting(outsideFile, importersById, functionsDirectory) + .forEach((id) => { + const warning = + `warn: ${path.relative(projectDirectory, id)} imports ${imported}, ` + + `which is outside ${CLOUD_FUNCTIONS_DIRECTORY}/ and will not be available when deployed.`; + if (!this.reportedOutsideImports.has(warning)) { + this.reportedOutsideImports.add(warning); + console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); + } + }); }); } @@ -264,11 +307,12 @@ export class CloudFunctions { import('@rollup/plugin-commonjs'), import('@rollup/plugin-json'), ]); + const importersById: ImportersById = new Map(); const bundle = await rollup({ input: cloudFunctionFilePath, - plugins: [nodeResolve({ preferBuiltins: true }), commonjs(), json()], + plugins: [nodeResolve({ preferBuiltins: true }), commonjs(), json(), recordImporters(importersById)], }); - this.warnAboutImportsOutsideFunctions(cloudFunctionFilePath, bundle.watchFiles); + this.warnAboutImportsOutsideFunctions(importersById); const { output } = await bundle.generate({ format: 'esm', From 3bfaba9f0f77fc410834ac39ab298a0f7de67914 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 17:28:24 +0530 Subject: [PATCH 17/26] refactor(functions): report outside imports from one reporter per parse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The outside-functions/ warning lived on CloudFunctions: it resolved the project and functions directories with realpathSync on every function build, and deduped on a Set kept for the life of the instance, keyed on the formatted warning text. Move it into OutsideImportReporter, created once per parse of the functions directory. It resolves both directories once, and dedupes on the (importer, outside file) pair, so rewording the warning cannot change what counts as a duplicate. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.ts | 73 ++++++++++++++++++++------------ 1 file changed, 46 insertions(+), 27 deletions(-) diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 4e04f815..6210d43c 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -70,6 +70,42 @@ export function functionFilesImporting( }); } +class OutsideImportReporter { + private readonly reported = new Set(); + + constructor( + private readonly projectDirectory: string, + private readonly functionsDirectory: string, + ) {} + + report(importersById: ImportersById): void { + [...importersById.keys()] + .filter((moduleId) => path.isAbsolute(moduleId)) + .filter((moduleId) => isOutsideDirectory(this.functionsDirectory, moduleId)) + .filter((moduleId) => !moduleId.split(path.sep).includes('node_modules')) + .forEach((outsideFile) => { + functionFilesImporting(outsideFile, importersById, this.functionsDirectory).forEach((importer) => { + this.warnOnce(importer, outsideFile); + }); + }); + } + + private warnOnce(importer: string, outsideFile: string): void { + const pair = `${importer}\0${outsideFile}`; + if (this.reported.has(pair)) { + return; + } + + this.reported.add(pair); + const importerPath = path.relative(this.projectDirectory, importer); + const outsidePath = path.relative(this.projectDirectory, outsideFile); + const warning = + `warn: ${importerPath} imports ${outsidePath}, ` + + `which is outside ${CLOUD_FUNCTIONS_DIRECTORY}/ and will not be available when deployed.`; + console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); + } +} + export function isOutsideDirectory(directory: string, file: string, pathApi: path.PlatformPath = path): boolean { const relativePath = pathApi.relative(directory, file); return relativePath === '..' || relativePath.startsWith(`..${pathApi.sep}`) || pathApi.isAbsolute(relativePath); @@ -105,7 +141,6 @@ export function listenFailure(error: NodeJS.ErrnoException, servingPort: number) export class CloudFunctions { private cloudFunctionsDirectoryPath: string; private pathToSourceCode: string; - private readonly reportedOutsideImports = new Set(); constructor(pathToSourceCode: string) { this.cloudFunctionsDirectoryPath = path.join( @@ -209,6 +244,10 @@ export class CloudFunctions { CloudFunctionResource[] > { const filePaths = await walkFileSystem(this.cloudFunctionsDirectoryPath); + const outsideImports = new OutsideImportReporter( + realpathSync(this.pathToSourceCode), + realpathSync(this.cloudFunctionsDirectoryPath), + ); const cloudFunctionResources: CloudFunctionResource[] = []; for await (const filePath of filePaths) { @@ -220,7 +259,7 @@ export class CloudFunctions { continue; } - const handler = await this.buildHandlerForFilepath(filePath); + const handler = await this.buildHandlerForFilepath(filePath, outsideImports); if (!handler) { continue; } @@ -277,30 +316,10 @@ export class CloudFunctions { return { exactRouteResources, dynamicRouteResources }; } - private warnAboutImportsOutsideFunctions(importersById: ImportersById): void { - const projectDirectory = realpathSync(this.pathToSourceCode); - const functionsDirectory = realpathSync(this.cloudFunctionsDirectoryPath); - - [...importersById.keys()] - .filter((moduleId) => path.isAbsolute(moduleId)) - .filter((moduleId) => isOutsideDirectory(functionsDirectory, moduleId)) - .filter((moduleId) => !moduleId.split(path.sep).includes('node_modules')) - .forEach((outsideFile) => { - const imported = path.relative(projectDirectory, outsideFile); - functionFilesImporting(outsideFile, importersById, functionsDirectory) - .forEach((id) => { - const warning = - `warn: ${path.relative(projectDirectory, id)} imports ${imported}, ` + - `which is outside ${CLOUD_FUNCTIONS_DIRECTORY}/ and will not be available when deployed.`; - if (!this.reportedOutsideImports.has(warning)) { - this.reportedOutsideImports.add(warning); - console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); - } - }); - }); - } - - private async buildHandlerForFilepath(cloudFunctionFilePath: string): Promise { + private async buildHandlerForFilepath( + cloudFunctionFilePath: string, + outsideImports: OutsideImportReporter, + ): Promise { const [{ rollup }, { nodeResolve }, { default: commonjs }, { default: json }] = await Promise.all([ import('rollup'), import('@rollup/plugin-node-resolve'), @@ -312,7 +331,7 @@ export class CloudFunctions { input: cloudFunctionFilePath, plugins: [nodeResolve({ preferBuiltins: true }), commonjs(), json(), recordImporters(importersById)], }); - this.warnAboutImportsOutsideFunctions(importersById); + outsideImports.report(importersById); const { output } = await bundle.generate({ format: 'esm', From d2fa5df956b49d063ea0e27d0df3be871a556ce4 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 17:32:54 +0530 Subject: [PATCH 18/26] fix(functions): send cache-control no-store on body parser errors too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit defaultToNoStore was registered after the body parsers, so a malformed JSON body or an oversize payload got Express's 400/413 without the cache-control: no-store every other function response carries. Register it first. A handler that sets its own cache-control still wins, since it sets the header later. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 15 +++++++++++++++ src/functions/cloud-functions.ts | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 3fea3007..d2e94963 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -531,6 +531,21 @@ describe('CloudFunctions serve routing', () => { expect((await sendRequest(port, '/cached')).cacheControl).toBe('max-age=60'); }); + it('defaults cache-control to no-store on the 400 for a malformed json body', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/body', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{bad json', + }); + + expect(response.status).toBe(400); + expect(response.cacheControl).toBe('no-store'); + }); + it('answers 500 and logs when a handler throws', async () => { writeFunctionFile('broken.js', 'export default function broken() { throw new Error("handler blew up"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 6210d43c..3502a40b 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -124,12 +124,12 @@ function defaultToNoStore(_request: Request, response: Response, next: NextFunct } function applyRequestMiddleware(app: Express): void { + app.use(defaultToNoStore); app.use(attachCookies); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(express.text({ limit: DEPLOYED_PAYLOAD_LIMIT })); app.use(express.raw({ limit: DEPLOYED_PAYLOAD_LIMIT })); - app.use(defaultToNoStore); } import { loadDataURL } from './load-data-url'; From df1dae2669fbd9c132782e6859becc34eae2304b Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 17:37:52 +0530 Subject: [PATCH 19/26] fix(functions): accept JSON and urlencoded bodies up to Lambda's 6mb cap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit express.json() and express.urlencoded() kept body-parser's 100kb default, so a 200kb JSON or form POST got a 413 locally while a deployed AWS function accepts it. Give them the same 6mb limit as the text and octet-stream parsers, so all four body types match Lambda's payload cap. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/functions/cloud-functions.test.ts | 19 +++++++++++++++++++ src/functions/cloud-functions.ts | 4 ++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index d2e94963..b80447a9 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -340,6 +340,25 @@ describe('CloudFunctions serve routing', () => { }, ); + it.each([ + ['application/json', (data: string) => JSON.stringify({ data })], + ['application/x-www-form-urlencoded', (data: string) => `data=${data}`], + ])('hands a %s body over the 100kb parser default to the handler parsed, as Lambda allows', async (contentType, encode) => { + writeFunctionFile('size.js', 'export default function size(request, response) { response.json({ length: request.body.data.length }); }'); + const data = 'a'.repeat(200 * 1024); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/size', { + method: 'POST', + headers: { 'content-type': contentType }, + body: encode(data), + }); + + expect(response.status).toBe(200); + expect(JSON.parse(response.body)).toEqual({ length: data.length }); + }); + it('hands a text/plain body to the handler as the raw string', async () => { writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 3502a40b..8f8a7e90 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -126,8 +126,8 @@ function defaultToNoStore(_request: Request, response: Response, next: NextFunct function applyRequestMiddleware(app: Express): void { app.use(defaultToNoStore); app.use(attachCookies); - app.use(express.json()); - app.use(express.urlencoded({ extended: true })); + app.use(express.json({ limit: DEPLOYED_PAYLOAD_LIMIT })); + app.use(express.urlencoded({ extended: true, limit: DEPLOYED_PAYLOAD_LIMIT })); app.use(express.text({ limit: DEPLOYED_PAYLOAD_LIMIT })); app.use(express.raw({ limit: DEPLOYED_PAYLOAD_LIMIT })); } From 842bd0dc6e1ee067c29380806fd313bdf9e9ff7b Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 17:52:32 +0530 Subject: [PATCH 20/26] fix(functions): accept only decimal digits as a port MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit isValidPort converted the input with Number(), which also reads hex, exponent, signed and space-padded strings, so --port 0x10 served on port 16 and --port 1e3 on port 1000 (PORT the same). Require the value to be decimal digits only before converting it; the range check stays. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/commands/launch/functions/serve.test.ts | 2 +- src/functions/function.inputs.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/commands/launch/functions/serve.test.ts b/src/commands/launch/functions/serve.test.ts index 2738818f..799791a8 100644 --- a/src/commands/launch/functions/serve.test.ts +++ b/src/commands/launch/functions/serve.test.ts @@ -164,7 +164,7 @@ describe('launch:functions:serve init', () => { expect(stdout).toEqual([]); }); - it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' '])( + it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' ', '0x10', '1e3', '+3000', ' 3000'])( 'rejects the invalid port %p once through the project logger and exits 1 as v1 did', async (port) => { const dataDir = temporaryDirectory(); diff --git a/src/functions/function.inputs.ts b/src/functions/function.inputs.ts index 7d808882..e1ee7345 100644 --- a/src/functions/function.inputs.ts +++ b/src/functions/function.inputs.ts @@ -13,10 +13,10 @@ export const serveFlags = { }; export function isValidPort(input: string): boolean { - if (typeof input !== 'string' || input.trim() === '') { + if (typeof input !== 'string' || !/^\d+$/.test(input)) { return false; } const port = Number(input); - return Number.isInteger(port) && port >= 0 && port <= 65535; + return port <= 65535; } From 9cccb42006001eaeea01394e4e65fc20fdcd31e2 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 17:59:49 +0530 Subject: [PATCH 21/26] fix(functions): print the invalid port error to stderr, coloured only on a tty MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An invalid --port or PORT went through the winston Console transport, so "error: Invalid port number..." landed on stdout with raw colour codes even when piped, while every other V2 error goes to stderr through the shared failure path, coloured only on a TTY. The project error logger now writes only to logs/error.log (V1 parity for the log file), and serve fails with this.error so the shared path prints the message to stderr. The exit code stays 1, as chosen for V1 parity in bf9a139. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/commands/launch/functions/serve.test.ts | 15 ++++++----- src/commands/launch/functions/serve.ts | 5 ++-- src/functions/function.logger.test.ts | 6 ++--- src/functions/function.logger.ts | 15 ++++++----- test/integration/functions-serve-port.test.ts | 25 +++++++++---------- test/integration/retired-commands.test.ts | 2 +- 6 files changed, 33 insertions(+), 35 deletions(-) diff --git a/src/commands/launch/functions/serve.test.ts b/src/commands/launch/functions/serve.test.ts index 799791a8..f016614c 100644 --- a/src/commands/launch/functions/serve.test.ts +++ b/src/commands/launch/functions/serve.test.ts @@ -165,18 +165,17 @@ describe('launch:functions:serve init', () => { }); it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' ', '0x10', '1e3', '+3000', ' 3000'])( - 'rejects the invalid port %p once through the project logger and exits 1 as v1 did', + 'rejects the invalid port %p, logging it to error.log and failing with it so it reaches stderr, exiting 1', async (port) => { const dataDir = temporaryDirectory(); const command = commandWithFlags({ 'data-dir': dataDir, port }); const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error); - expect(failure).toBeInstanceOf(Errors.ExitError); - expect(failure).toMatchObject({ oclif: { exit: EXIT_RUNTIME } }); - expect((failure as Error).message).not.toContain(INVALID_PORT_MESSAGE); + expect(failure).toBeInstanceOf(Errors.CLIError); + expect(failure).toMatchObject({ message: INVALID_PORT_MESSAGE, oclif: { exit: EXIT_RUNTIME } }); expect(command['sharedConfig']).toBeUndefined(); - expect(stdout).toEqual([`\u001b[31merror: ${INVALID_PORT_MESSAGE}\u001b[39m\n`]); + expect(stdout).toEqual([]); await eventually(() => readLog(dataDir, 'error.log') !== ''); expect(readLog(dataDir, 'error.log')).toBe(`{"level":"error","message":"${INVALID_PORT_MESSAGE}"}\n`); expect(readLog(dataDir, 'info.log')).toBe(''); @@ -308,10 +307,10 @@ describe('launch:functions:serve port precedence', () => { const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error); - expect(failure).toBeInstanceOf(Errors.ExitError); - expect(failure).toMatchObject({ oclif: { exit: EXIT_RUNTIME } }); + expect(failure).toBeInstanceOf(Errors.CLIError); + expect(failure).toMatchObject({ message: INVALID_PORT_MESSAGE, oclif: { exit: EXIT_RUNTIME } }); expect(command['sharedConfig']).toBeUndefined(); - expect(stdout).toEqual([`\u001b[31merror: ${INVALID_PORT_MESSAGE}\u001b[39m\n`]); + expect(stdout).toEqual([]); }, ); diff --git a/src/commands/launch/functions/serve.ts b/src/commands/launch/functions/serve.ts index 2eaf8343..24f1c6e3 100755 --- a/src/commands/launch/functions/serve.ts +++ b/src/commands/launch/functions/serve.ts @@ -30,8 +30,9 @@ export default class Functions extends Command { const port = process.env.PORT || flags.port; if (!isValidPort(port)) { - this.log('Invalid port number. Please provide a valid port number between 0 and 65535.', 'error'); - this.exit(EXIT_RUNTIME); + const message = 'Invalid port number. Please provide a valid port number between 0 and 65535.'; + this.log(message, 'error'); + this.error(message, { exit: EXIT_RUNTIME }); } this.sharedConfig = { diff --git a/src/functions/function.logger.test.ts b/src/functions/function.logger.test.ts index 20dc0a16..47c72fc0 100644 --- a/src/functions/function.logger.test.ts +++ b/src/functions/function.logger.test.ts @@ -80,7 +80,7 @@ describe('function logger', () => { expect(read('info.log')).toBe(''); }); - it('writes an error to logs/error.log as a json line and prints it coloured on stdout', async () => { + it('writes an error to logs/error.log as a json line without printing it, leaving that to the command', async () => { const logger = loggerAt(projectBasePath); logger.log('Invalid port number.', 'error'); @@ -88,7 +88,7 @@ describe('function logger', () => { await eventually(() => read('error.log') !== ''); expect(read('error.log')).toBe('{"level":"error","message":"Invalid port number."}\n'); expect(read('info.log')).toBe(''); - expect(stdout).toEqual(['\u001b[31merror: Invalid port number.\u001b[39m\n']); + expect(stdout).toEqual([]); }); it('writes info and warn to logs/info.log, never to error.log, and drops debug everywhere', async () => { @@ -131,7 +131,7 @@ describe('function logger', () => { expect(info.levels).toEqual({ warn: 1, info: 2, debug: 3 }); expect(error.levels).toEqual({ error: 0 }); expect(consoleTransport(info).level).toBeUndefined(); - expect(consoleTransport(error).level).toBe('error'); + expect(consoleTransport(error)).toBeUndefined(); }); it('normalises a base path containing parent segments', () => { diff --git a/src/functions/function.logger.ts b/src/functions/function.logger.ts index c6b40757..35e304a2 100644 --- a/src/functions/function.logger.ts +++ b/src/functions/function.logger.ts @@ -70,19 +70,18 @@ export class Logger { /^(\.\.(\/|\\|$))+/, '', ); + const fileTransport = new winston.transports.File({ + ...this.loggerOptions, + level: logType, + filename, + }); const loggerOptions: winston.LoggerOptions = { - transports: [ - new winston.transports.File({ - ...this.loggerOptions, - level: logType, - filename, - }), - new winston.transports.Console(consoleOptions), - ], + transports: [fileTransport, new winston.transports.Console(consoleOptions)], levels: customLevels.levels, }; if (logType === 'error') { + loggerOptions.transports = [fileTransport]; loggerOptions.levels = { error: 0 }; } diff --git a/test/integration/functions-serve-port.test.ts b/test/integration/functions-serve-port.test.ts index 09ecd557..364a7fe6 100644 --- a/test/integration/functions-serve-port.test.ts +++ b/test/integration/functions-serve-port.test.ts @@ -3,12 +3,11 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { Interfaces } from '@oclif/core'; -import { Errors } from '@oclif/core'; import { runCommand } from '@oclif/test'; import { loadCliConfig } from '../support/oclif'; -const INVALID_PORT_RECORD = - '{"level":"error","message":"Invalid port number. Please provide a valid port number between 0 and 65535."}\n'; +const INVALID_PORT_MESSAGE = 'Invalid port number. Please provide a valid port number between 0 and 65535.'; +const INVALID_PORT_RECORD = `{"level":"error","message":"${INVALID_PORT_MESSAGE}"}\n`; const originalPort = process.env.PORT; let config: Interfaces.Config; @@ -52,41 +51,41 @@ describe('integration: launch:functions:serve port handling', () => { process.exitCode = 0; }); - it('logs the invalid port once, prints nothing to stderr and exits 1 without a second error message', async () => { - const { error, stderr } = await runCommand( + it('logs the invalid port to error.log, prints it once to stderr uncoloured and exits 1', async () => { + const { error, stdout, stderr } = await runCommand( ['launch:functions:serve', '--port', '70000', '--data-dir', projectDir], config, ); - expect(error).toBeInstanceOf(Errors.ExitError); expect(error?.oclif?.exit).toBe(1); - expect(stderr).toBe(''); + expect(stdout).toBe(''); + expect(stderr).toBe(`error: ${INVALID_PORT_MESSAGE}\n`); await expect(errorLog()).resolves.toBe(INVALID_PORT_RECORD); }); it('lets an invalid PORT beat a valid --port, so the flag never reaches the server', async () => { process.env.PORT = '70000'; - const { error, stderr } = await runCommand( + const { error, stdout, stderr } = await runCommand( ['launch:functions:serve', '--port', '4000', '--data-dir', projectDir], config, ); - expect(error).toBeInstanceOf(Errors.ExitError); expect(error?.oclif?.exit).toBe(1); - expect(stderr).toBe(''); + expect(stdout).toBe(''); + expect(stderr).toBe(`error: ${INVALID_PORT_MESSAGE}\n`); await expect(errorLog()).resolves.toBe(INVALID_PORT_RECORD); }); it('rejects an empty --port through the same invalid port path', async () => { - const { error, stderr } = await runCommand( + const { error, stdout, stderr } = await runCommand( ['launch:functions:serve', '--port', '""', '--data-dir', projectDir], config, ); - expect(error).toBeInstanceOf(Errors.ExitError); expect(error?.oclif?.exit).toBe(1); - expect(stderr).toBe(''); + expect(stdout).toBe(''); + expect(stderr).toBe(`error: ${INVALID_PORT_MESSAGE}\n`); await expect(errorLog()).resolves.toBe(INVALID_PORT_RECORD); }); diff --git a/test/integration/retired-commands.test.ts b/test/integration/retired-commands.test.ts index 9cbe9f43..e364133a 100644 --- a/test/integration/retired-commands.test.ts +++ b/test/integration/retired-commands.test.ts @@ -122,7 +122,7 @@ describe('integration: retired V1 command names', () => { const { error } = await runCommand(['launch:functions:serve', '--port', '70000', '--data-dir', projectDir], config); expect(error?.oclif?.exit).toBe(1); - expect(error?.message).toBe('EEXIT: 1'); + expect(error?.message).toBe('Invalid port number. Please provide a valid port number between 0 and 65535.'); expect(error?.message).not.toContain('was removed in Launch CLI v2'); const logs = join(projectDir, 'logs'); const deadline = Date.now() + 5000; From 66e78f7ea1cede94e4e2582f5306e90bfe657c76 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 18:18:48 +0530 Subject: [PATCH 22/26] fix(functions): print a missing --data-dir error to stderr through the shared path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A --data-dir that does not exist was caught inside the Logger constructor, which printed "error: Provided base path is not valid" to stdout with raw colour codes and called process.exit(1). Check the directory in serve before the Logger is built and fail with this.error, so the message reaches stderr, coloured only on a TTY. The exit code stays 1. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/commands/launch/functions/serve.test.ts | 15 +++++++-------- src/commands/launch/functions/serve.ts | 4 ++++ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/commands/launch/functions/serve.test.ts b/src/commands/launch/functions/serve.test.ts index f016614c..ebb42662 100644 --- a/src/commands/launch/functions/serve.test.ts +++ b/src/commands/launch/functions/serve.test.ts @@ -182,18 +182,17 @@ describe('launch:functions:serve init', () => { }, ); - it('exits 1 with the invalid base path error before validating the port when the data directory does not exist', async () => { - const exit = jest.spyOn(process, 'exit').mockImplementation(((code: number) => { - throw new Error(`exit ${code}`); - }) as never); + it('fails with the invalid base path error, exiting 1, before validating the port when the data directory does not exist', async () => { + const exit = jest.spyOn(process, 'exit').mockImplementation((() => undefined) as never); const missing = join(temporaryDirectory(), 'no-such-dir'); const command = commandWithFlags({ 'data-dir': missing, port: '99999' }); - await expect(command.init()).rejects.toThrow('exit 1'); + const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error); - expect(exit).toHaveBeenCalledTimes(1); - expect(exit).toHaveBeenCalledWith(1); - expect(stdout).toEqual(['\u001b[31merror: Provided base path is not valid\u001b[39m\n']); + expect(failure).toBeInstanceOf(Errors.CLIError); + expect(failure).toMatchObject({ message: 'Provided base path is not valid', oclif: { exit: EXIT_RUNTIME } }); + expect(exit).not.toHaveBeenCalled(); + expect(stdout).toEqual([]); expect(existsSync(missing)).toBe(false); expect(command['sharedConfig']).toBeUndefined(); }); diff --git a/src/commands/launch/functions/serve.ts b/src/commands/launch/functions/serve.ts index 24f1c6e3..92637999 100755 --- a/src/commands/launch/functions/serve.ts +++ b/src/commands/launch/functions/serve.ts @@ -1,4 +1,5 @@ import { Command } from '@oclif/core'; +import { existsSync } from 'node:fs'; import { EXIT_RUNTIME, EXIT_USAGE } from '../../../core/constants'; import { failureOutputOf, reportFailure } from '../../../core/failure'; @@ -24,6 +25,9 @@ export default class Functions extends Command { const { flags } = await this.parse(Functions); const currentWorkingDirectory = process.cwd(); const projectBasePath = flags['data-dir'] || currentWorkingDirectory; + if (!existsSync(projectBasePath)) { + this.error('Provided base path is not valid', { exit: EXIT_RUNTIME }); + } const logger = new Logger({ projectBasePath }); this.log = logger.log.bind(logger); From af8551f5972abb4f6e2d7655623341433d15f023 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 19:20:44 +0530 Subject: [PATCH 23/26] fix(functions): refuse a --data-dir that is a file, naming the path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A --data-dir pointing at a file reached the Logger, whose file transport failed with an internal "ENOTDIR: not a directory, mkdir '/logs'". Check that the path is a directory before building the Logger and fail with "--data-dir is not a directory", exit 1. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/commands/launch/functions/serve.test.ts | 15 ++++++++++++++- src/commands/launch/functions/serve.ts | 6 +++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/commands/launch/functions/serve.test.ts b/src/commands/launch/functions/serve.test.ts index ebb42662..1448b397 100644 --- a/src/commands/launch/functions/serve.test.ts +++ b/src/commands/launch/functions/serve.test.ts @@ -1,6 +1,6 @@ import { cliux } from '@contentstack/cli-utilities'; import { Errors, Parser } from '@oclif/core'; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -197,6 +197,19 @@ describe('launch:functions:serve init', () => { expect(command['sharedConfig']).toBeUndefined(); }); + it('fails naming the path, exiting 1, when the data directory is a file', async () => { + const file = join(temporaryDirectory(), 'not-a-dir.txt'); + writeFileSync(file, 'x'); + const command = commandWithFlags({ 'data-dir': file, port: '3000' }); + + const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error); + + expect(failure).toBeInstanceOf(Errors.CLIError); + expect(failure).toMatchObject({ message: `--data-dir ${file} is not a directory`, oclif: { exit: EXIT_RUNTIME } }); + expect(stdout).toEqual([]); + expect(command['sharedConfig']).toBeUndefined(); + }); + it('routes the command log through the project logger', async () => { const dataDir = temporaryDirectory(); const print = jest.spyOn(cliux, 'print').mockImplementation(() => undefined); diff --git a/src/commands/launch/functions/serve.ts b/src/commands/launch/functions/serve.ts index 92637999..4839bbd0 100755 --- a/src/commands/launch/functions/serve.ts +++ b/src/commands/launch/functions/serve.ts @@ -1,5 +1,5 @@ import { Command } from '@oclif/core'; -import { existsSync } from 'node:fs'; +import { existsSync, statSync } from 'node:fs'; import { EXIT_RUNTIME, EXIT_USAGE } from '../../../core/constants'; import { failureOutputOf, reportFailure } from '../../../core/failure'; @@ -29,6 +29,10 @@ export default class Functions extends Command { this.error('Provided base path is not valid', { exit: EXIT_RUNTIME }); } + if (!statSync(projectBasePath).isDirectory()) { + this.error(`--data-dir ${projectBasePath} is not a directory`, { exit: EXIT_RUNTIME }); + } + const logger = new Logger({ projectBasePath }); this.log = logger.log.bind(logger); From c5d299c7f37ff903ca26bbd5d44513d75aff1842 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 19:51:05 +0530 Subject: [PATCH 24/26] fix(functions): create logs/ only when something is written to a log file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Building the Logger created winston file transports at once, and those create logs/ in their constructor, so every functions:serve run left an empty logs/ folder in the project, even one that failed before serving (no functions/ folder, say). Build each winston logger the first time it is written to. winston's own lazy option does not help: the File transport still creates the directory in its constructor. The missing base path check stays in the Logger constructor. A run that logs an invalid port now leaves only logs/error.log. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/commands/launch/functions/serve.test.ts | 20 ++---- src/functions/function.logger.test.ts | 19 ++--- src/functions/function.logger.ts | 72 +++++++++---------- test/integration/functions-serve-port.test.ts | 2 +- test/integration/retired-commands.test.ts | 4 +- 5 files changed, 50 insertions(+), 67 deletions(-) diff --git a/src/commands/launch/functions/serve.test.ts b/src/commands/launch/functions/serve.test.ts index 1448b397..a5b02cf0 100644 --- a/src/commands/launch/functions/serve.test.ts +++ b/src/commands/launch/functions/serve.test.ts @@ -1,6 +1,6 @@ import { cliux } from '@contentstack/cli-utilities'; import { Errors, Parser } from '@oclif/core'; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -28,11 +28,6 @@ function temporaryDirectory(): string { return dir; } -function logFiles(dir: string): string[] { - const logs = join(dir, 'logs'); - return existsSync(logs) ? readdirSync(logs).sort() : []; -} - function readLog(dir: string, name: string): string { const path = join(dir, 'logs', name); return existsSync(path) ? readFileSync(path, 'utf8') : ''; @@ -85,7 +80,7 @@ beforeEach(() => { afterEach(async () => { for (const dir of temporaryDirectories.splice(0)) { if (existsSync(join(dir, 'logs'))) { - await eventually(() => logFiles(dir).length === 2); + await eventually(() => readLog(dir, 'error.log') !== ''); } rmSync(dir, { recursive: true, force: true }); @@ -122,7 +117,7 @@ describe('launch:functions:serve flag definitions', () => { }); describe('launch:functions:serve init', () => { - it('stores the supplied data directory and port and creates the project log files there', async () => { + it('stores the supplied data directory and port without creating a logs folder there', async () => { const dataDir = temporaryDirectory(); const command = commandWithFlags({ 'data-dir': dataDir, port: '4000' }); @@ -130,10 +125,7 @@ describe('launch:functions:serve init', () => { expect(Functions.prototype['parse']).toHaveBeenCalledWith(Functions); expect(command['sharedConfig']).toEqual({ projectBasePath: dataDir, port: 4000 }); - expect(existsSync(join(dataDir, 'logs'))).toBe(true); - await eventually(() => logFiles(dataDir).length === 2); - expect(logFiles(dataDir)).toEqual(['error.log', 'info.log']); - expect(readLog(dataDir, 'error.log')).toBe(''); + expect(existsSync(join(dataDir, 'logs'))).toBe(false); expect(stdout).toEqual([]); }); @@ -149,7 +141,6 @@ describe('launch:functions:serve init', () => { await command.init(); expect(command['sharedConfig']).toEqual({ projectBasePath: workingDirectory, port: 3000 }); - expect(existsSync(join(workingDirectory, 'logs'))).toBe(true); }); it.each(['0', '1', '3000', '65535'])('accepts the boundary port %s', async (port) => { @@ -159,8 +150,7 @@ describe('launch:functions:serve init', () => { await command.init(); expect(command['sharedConfig']).toEqual({ projectBasePath: dataDir, port: Number(port) }); - await eventually(() => logFiles(dataDir).length === 2); - expect(readLog(dataDir, 'error.log')).toBe(''); + expect(existsSync(join(dataDir, 'logs'))).toBe(false); expect(stdout).toEqual([]); }); diff --git a/src/functions/function.logger.test.ts b/src/functions/function.logger.test.ts index 47c72fc0..835084a1 100644 --- a/src/functions/function.logger.test.ts +++ b/src/functions/function.logger.test.ts @@ -1,6 +1,6 @@ import { cliux } from '@contentstack/cli-utilities'; import { randomBytes } from 'node:crypto'; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import winston from 'winston'; @@ -45,10 +45,6 @@ function read(name: string): string { return existsSync(path) ? readFileSync(path, 'utf8') : ''; } -function fileNames(): string[] { - return readdirSync(join(projectBasePath, 'logs')).sort(); -} - beforeEach(() => { projectBasePath = mkdtempSync(join(tmpdir(), 'launch-serve-log-')); stdout = []; @@ -70,14 +66,13 @@ afterEach(async () => { }); describe('function logger', () => { - it('creates the logs folder at construction and both empty log files without any message being written', async () => { - loggerAt(projectBasePath); + it('creates no logs folder until a message is written to a log file', () => { + jest.spyOn(cliux, 'print').mockImplementation(() => undefined); + const logger = loggerAt(projectBasePath); - expect(existsSync(join(projectBasePath, 'logs'))).toBe(true); - await eventually(() => fileNames().length === 2); - expect(fileNames()).toEqual(['error.log', 'info.log']); - expect(read('error.log')).toBe(''); - expect(read('info.log')).toBe(''); + logger.log('printed, not logged'); + + expect(existsSync(join(projectBasePath, 'logs'))).toBe(false); }); it('writes an error to logs/error.log as a json line without printing it, leaving that to the command', async () => { diff --git a/src/functions/function.logger.ts b/src/functions/function.logger.ts index 35e304a2..cca0ad77 100644 --- a/src/functions/function.logger.ts +++ b/src/functions/function.logger.ts @@ -37,8 +37,7 @@ function toText(value: unknown): string { } export class Logger { - private infoLogger!: winston.Logger; - private errorLogger!: winston.Logger; + private loggers: Partial> = {}; private config!: LoggerConfig; get loggerOptions(): winston.transports.FileTransportOptions { @@ -52,48 +51,47 @@ export class Logger { constructor(config: LoggerConfig) { this.config = config; - this.infoLogger = this.getLoggerInstance('info'); - this.errorLogger = this.getLoggerInstance('error'); + if (!existsSync(config.projectBasePath)) { + winston + .createLogger({ transports: [new winston.transports.Console({ format: this.consoleFormat, level: 'error' })] }) + .error('Provided base path is not valid'); + process.exit(1); + } } - getLoggerInstance(logType: LoggerType): winston.Logger { - const consoleOptions: winston.transports.ConsoleTransportOptions = { - format: winston.format.combine(winston.format.simple(), winston.format.colorize({ all: true })), - }; + private get consoleFormat(): winston.Logform.Format { + return winston.format.combine(winston.format.simple(), winston.format.colorize({ all: true })); + } - if (logType === 'error') { - consoleOptions.level = logType; - } + private get infoLogger(): winston.Logger { + this.loggers.info ??= this.getLoggerInstance('info'); + return this.loggers.info; + } - if (existsSync(this.config.projectBasePath)) { - const filename = normalize(resolve(this.config.projectBasePath, 'logs', `${logType}.log`)).replace( - /^(\.\.(\/|\\|$))+/, - '', - ); - const fileTransport = new winston.transports.File({ - ...this.loggerOptions, - level: logType, - filename, - }); - const loggerOptions: winston.LoggerOptions = { - transports: [fileTransport, new winston.transports.Console(consoleOptions)], - levels: customLevels.levels, - }; - - if (logType === 'error') { - loggerOptions.transports = [fileTransport]; - loggerOptions.levels = { error: 0 }; - } + private get errorLogger(): winston.Logger { + this.loggers.error ??= this.getLoggerInstance('error'); + return this.loggers.error; + } - return winston.createLogger(loggerOptions); + getLoggerInstance(logType: LoggerType): winston.Logger { + const filename = normalize(resolve(this.config.projectBasePath, 'logs', `${logType}.log`)).replace( + /^(\.\.(\/|\\|$))+/, + '', + ); + const fileTransport = new winston.transports.File({ + ...this.loggerOptions, + level: logType, + filename, + }); + + if (logType === 'error') { + return winston.createLogger({ transports: [fileTransport], levels: { error: 0 } }); } - winston - .createLogger({ - transports: [new winston.transports.Console(consoleOptions)], - }) - .error('Provided base path is not valid'); - process.exit(1); + return winston.createLogger({ + transports: [fileTransport, new winston.transports.Console({ format: this.consoleFormat })], + levels: customLevels.levels, + }); } log(message: unknown, logType?: LoggerType | PrintOptions | undefined): void { diff --git a/test/integration/functions-serve-port.test.ts b/test/integration/functions-serve-port.test.ts index 364a7fe6..ffe6f41a 100644 --- a/test/integration/functions-serve-port.test.ts +++ b/test/integration/functions-serve-port.test.ts @@ -37,7 +37,7 @@ describe('integration: launch:functions:serve port handling', () => { afterEach(async () => { const logs = join(projectDir, 'logs'); const deadline = Date.now() + 4000; - while ((!existsSync(logs) || readdirSync(logs).length < 2) && Date.now() < deadline) { + while ((!existsSync(logs) || readdirSync(logs).length < 1) && Date.now() < deadline) { await new Promise((resolve) => setTimeout(resolve, 10)); } diff --git a/test/integration/retired-commands.test.ts b/test/integration/retired-commands.test.ts index e364133a..e916f796 100644 --- a/test/integration/retired-commands.test.ts +++ b/test/integration/retired-commands.test.ts @@ -126,11 +126,11 @@ describe('integration: retired V1 command names', () => { expect(error?.message).not.toContain('was removed in Launch CLI v2'); const logs = join(projectDir, 'logs'); const deadline = Date.now() + 5000; - while ((!existsSync(logs) || readdirSync(logs).length < 2) && Date.now() < deadline) { + while ((!existsSync(logs) || readdirSync(logs).length < 1) && Date.now() < deadline) { await new Promise((resolve) => setTimeout(resolve, 10)); } - expect(readdirSync(logs).sort()).toEqual(['error.log', 'info.log']); + expect(readdirSync(logs).sort()).toEqual(['error.log']); rmSync(projectDir, { recursive: true, force: true }); }); From 53add7eeb88d323e7d52b26a4cb17b73e985fb54 Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 21:17:16 +0530 Subject: [PATCH 25/26] fix(functions): flush the invalid port record to disk before exiting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the error logger now built on first write, its file stream opens asynchronously after the record is logged, and the this.error thrown straight after reached process.exit first. A real run left an empty logs/ folder and no error.log; the tests missed it because runCommand never exits the process. Logger.flush() ends the loggers created so far and waits for their file transports to finish. serve awaits it before failing, so the record is on disk when the process exits. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/commands/launch/functions/serve.test.ts | 3 +-- src/commands/launch/functions/serve.ts | 1 + src/functions/function.logger.test.ts | 9 +++++++++ src/functions/function.logger.ts | 12 ++++++++++++ 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/commands/launch/functions/serve.test.ts b/src/commands/launch/functions/serve.test.ts index a5b02cf0..c4350e0e 100644 --- a/src/commands/launch/functions/serve.test.ts +++ b/src/commands/launch/functions/serve.test.ts @@ -155,7 +155,7 @@ describe('launch:functions:serve init', () => { }); it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' ', '0x10', '1e3', '+3000', ' 3000'])( - 'rejects the invalid port %p, logging it to error.log and failing with it so it reaches stderr, exiting 1', + 'rejects the invalid port %p, with it on disk in error.log before failing with it to stderr, exiting 1', async (port) => { const dataDir = temporaryDirectory(); const command = commandWithFlags({ 'data-dir': dataDir, port }); @@ -166,7 +166,6 @@ describe('launch:functions:serve init', () => { expect(failure).toMatchObject({ message: INVALID_PORT_MESSAGE, oclif: { exit: EXIT_RUNTIME } }); expect(command['sharedConfig']).toBeUndefined(); expect(stdout).toEqual([]); - await eventually(() => readLog(dataDir, 'error.log') !== ''); expect(readLog(dataDir, 'error.log')).toBe(`{"level":"error","message":"${INVALID_PORT_MESSAGE}"}\n`); expect(readLog(dataDir, 'info.log')).toBe(''); }, diff --git a/src/commands/launch/functions/serve.ts b/src/commands/launch/functions/serve.ts index 4839bbd0..a9891b31 100755 --- a/src/commands/launch/functions/serve.ts +++ b/src/commands/launch/functions/serve.ts @@ -40,6 +40,7 @@ export default class Functions extends Command { if (!isValidPort(port)) { const message = 'Invalid port number. Please provide a valid port number between 0 and 65535.'; this.log(message, 'error'); + await logger.flush(); this.error(message, { exit: EXIT_RUNTIME }); } diff --git a/src/functions/function.logger.test.ts b/src/functions/function.logger.test.ts index 835084a1..fba7d190 100644 --- a/src/functions/function.logger.test.ts +++ b/src/functions/function.logger.test.ts @@ -86,6 +86,15 @@ describe('function logger', () => { expect(stdout).toEqual([]); }); + it('has the error on disk by the time flush resolves, so a process exiting straight after keeps it', async () => { + const logger = new Logger({ projectBasePath }); + + logger.log('Invalid port number.', 'error'); + await logger.flush(); + + expect(read('error.log')).toBe('{"level":"error","message":"Invalid port number."}\n'); + }); + it('writes info and warn to logs/info.log, never to error.log, and drops debug everywhere', async () => { const logger = loggerAt(projectBasePath); diff --git a/src/functions/function.logger.ts b/src/functions/function.logger.ts index cca0ad77..b15676dd 100644 --- a/src/functions/function.logger.ts +++ b/src/functions/function.logger.ts @@ -94,6 +94,18 @@ export class Logger { }); } + async flush(): Promise { + const fileTransports = Object.values(this.loggers).flatMap((logger) => { + const transports = logger.transports.filter((transport) => transport instanceof winston.transports.File); + logger.end(); + return transports; + }); + + await Promise.all( + fileTransports.map((transport) => new Promise((resolve) => transport.once('finish', () => resolve()))), + ); + } + log(message: unknown, logType?: LoggerType | PrintOptions | undefined): void { const logString = this.returnString(message); From ce9dad83b3044f4c5cacbf4cda6d9415992c644b Mon Sep 17 00:00:00 2001 From: Harshi-Shah-CS Date: Thu, 19 Nov 2026 21:17:43 +0530 Subject: [PATCH 26/26] docs(agents): record functions:serve's approved differences from V1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AGENTS.md said serve was V1 byte for byte: port errors on stdout, nothing on stderr, "do not add this.error". CL-8791 changed that on purpose. Keep the parts that stay V1 (PORT beats --port, exit 1) and list the approved differences: errors on stderr with error.log flushed first, digits-only ports, logs/ only when written, requests matching AWS deployed functions, and the outside-functions/ warning. Refresh the .talismanrc checksums for the files this branch changed (AGENTS.md, package.json, src/functions/cloud-functions.test.ts, src/functions/function.logger.test.ts, test/integration/retired-commands.test.ts). The lines Talisman flags in them are prose, oclif command ids and test names, not secrets. #claude_code# 馃 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .talismanrc | 10 +++++----- AGENTS.md | 50 ++++++++++++++++++++++++++++++++++---------------- 2 files changed, 39 insertions(+), 21 deletions(-) diff --git a/.talismanrc b/.talismanrc index ce2a0e53..00b6747f 100644 --- a/.talismanrc +++ b/.talismanrc @@ -8,7 +8,7 @@ fileignoreconfig: - filename: src/core/failure.test.ts checksum: 3f5c731861dc816d141f6314c32bec55bc5197241447a4375bc76fa9f85339f0 - filename: test/integration/retired-commands.test.ts - checksum: c38d6e8dae6bd4d2034ff48bff488e89cc00d950a7417c6df890168ac743ae37 + checksum: 84d9c9ddae05faf49e6bd29e2835051714ed53ac35c8a0283c87679f06902b0a - filename: test/integration/manage-base-path.test.ts checksum: 79eb9ad420ea47d5bee8045d812c45b010bbeeafcaf5f85d11653140b0cd0db1 - filename: src/transport/rest-client.ts @@ -236,7 +236,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: c20a023e033c6222c645e94bf9fba4bdf884aa75d6c52f5c74ab185b8c335b01 + checksum: 06abd3d96ec675c81fdeb86bbe571bf027d9426da2c8bf10519dc8bd045dbc9d allowed_patterns: - "Do not add an exemption to a guard to make a new file pass" - "passes its own error wording to `client.request\\(req, MESSAGES\\)`" @@ -283,7 +283,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 5f49dc7f384fb9e33c8fb91f1c67b17ffc2fd3bbde3663f90f820056407e98a0 - filename: src/functions/cloud-functions.test.ts - checksum: 5faf7b0497efc9f620983220019736a0ec2e8c43f22316f888201912bbcb5d62 + checksum: 2b7d29ca3a8b87bc27e464d00517eb390d70b901ad892c0680bf613cb466920c - filename: src/transport/proxy.test.ts checksum: 06db291bb40ec55774179b02e3e1a9644bbaa116ec511c163e8d6012aebb3868 - filename: test/integration/project-upload-proxy.test.ts @@ -301,7 +301,7 @@ fileignoreconfig: - filename: src/transport/auth-strategy.ts checksum: 6fe87def1b508cb67203d4445d9bd889570e512ed4194dfc4fdd3182bc8b87b2 - filename: src/functions/function.logger.test.ts - checksum: 840b2b2b7f938e0862881871e8d568112631c58e12cf6c8a5be32e7552b8cf9e + checksum: e088ab5844cf4214d03f9c0f0a903b21ec7167e6879fc484d647e46b96f7a100 - filename: src/transport/cma-client.test.ts checksum: 85d62ef350b450cb09f1a840db79bdfb212d4f5fd650789d60d722915a892a59 - filename: src/core/search-list.test.ts @@ -487,7 +487,7 @@ fileignoreconfig: - filename: src/commands/launch/secrets/list.test.ts checksum: 109d1165d7ce16943b50955f60fd8a753a870115fdf5501fb2a5e4a1cf436eaa - filename: package.json - checksum: ae6f7fdb23fd9476dd4fca5b84d0f3999b578a73b8187af2f94edbb0a2172b16 + checksum: aa850fff4d587e974f73c1fd734c6798feed147f0dce449b33930ef7190b370c - filename: test/integration/secrets-set.test.ts checksum: 2527d5d35198cc08e1859ab79941338392b6d4fcbc87506adef6d7b096089963 - filename: src/secrets/secret.rules.test.ts diff --git a/AGENTS.md b/AGENTS.md index 70d8c0a2..eca5465f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -500,27 +500,45 @@ promoting these to `src/core/catalog.ts` now. `launch:functions:serve` is deliberately a plain oclif `Command` rather than a `LaunchCommand`, because it talks to no API and needs no auth gate, and it is **outside** -this contract on purpose: the product owner's instruction is no functional difference from -V1 in `serve`. Its port handling is V1's, byte for byte: +this contract on purpose. It started as V1 byte for byte, on the product owner's instruction; +CL-8791 (V2 bug bash) then made it match deployed cloud functions and V2's error output. These +parts are still V1's and must stay so: - The port is `process.env.PORT || flags.port`, applied by the command after parsing. A set `PORT` beats an explicit `--port`, and an empty `PORT` falls through to the flag. The `--port` flag therefore does **not** declare `env: 'PORT'` - oclif's precedence (argv first) is the opposite of V1's, and restoring it would be a behaviour change. -- An invalid port prints `Invalid port number. Please provide a valid port number between 0 - and 65535.` **once**, through the restored V1 logger (`src/functions/function.logger.ts`), - which writes every level - `error` included - to **stdout**, as winston's `Console` - transport does without `stderrLevels`, and records it in `logs/error.log`. The command - then calls `this.exit(EXIT_RUNTIME)`: exit **1**, and nothing on stderr. Do not add a - `this.error(...)` after the log line - that was a second print and an exit 2. - -Three V1 defects stay fixed and are the only approved differences: an empty or whitespace -port, from either `--port` or `PORT`, is rejected through that same one-message exit-1 path -(V1 accepted it because `Number('') === 0` and served on a random port); a busy port raises -`PortInUseError` and exits 2 with a clean message (V1 crashed on an unhandled `error` -event); and filepath validation is linear-time (V1's regex took 41 seconds on a plausible -40-character filename). `test/integration/functions-serve-port.test.ts` pins the port -precedence and the single message end to end. +- An invalid port exits **1** (`bf9a139`), not the usage code 2. + +The approved differences from V1 are these, and only these: + +- **Errors go to stderr.** An invalid port is recorded in `logs/error.log`, and the command + awaits `logger.flush()` so the record is on disk before the process exits. It then calls + `this.error(message, { exit: EXIT_RUNTIME })`, so `Invalid port number. Please provide a + valid port number between 0 and 65535.` prints **once** on stderr through the shared failure + path, coloured only on a TTY. The project error logger (`src/functions/function.logger.ts`) + writes only to the file and has no `Console` transport. A `--data-dir` that does not exist, + or that is a file, fails the same way before the logger is built. +- **A port is decimal digits only**, 0-65535. Hex, exponent, signed, space-padded, empty and + whitespace values are rejected through that same exit-1 path. V1 read `0x10` as 16 and + accepted `''` as 0, a random port. +- **`logs/` appears only when something is written to it.** V1 created it, empty, on every + run. +- **Requests match AWS deployed functions** (`lambda-node-bridge/cf-sv-with-helpers.ts` in + `contentfly-deployment-agent`), as agreed with CL-8791's reporter. JSON and urlencoded + bodies are parsed, `text/plain` arrives as the raw string, `application/octet-stream` as a + Buffer, all up to Lambda's 6mb cap. `request.cookies` is the parsed `Cookie` header, or `{}`. + The project `.env` is loaded before the functions are bundled. Azure and GCP still run the + vendored V1 server, which leaves text and octet-stream bodies unparsed; locally a handler + that reads the raw request stream for those two types gets an empty stream. +- **A function that reaches a file outside `functions/` is warned about, not refused**, naming + the function file that crosses the boundary. +- **A busy port** raises `PortInUseError` and exits 2 with a clean message (V1 crashed on an + unhandled `error` event), and **filepath validation is linear-time** (V1's regex took 41 + seconds on a plausible 40-character filename). + +`test/integration/functions-serve-port.test.ts` pins the port precedence and the single stderr +message end to end. A declined confirmation is a deliberate "no", not a failure, so it does not share code 1 with an API 500 - a CI log has to be able to tell those apart. 130 would claim the process was killed by