Skip to content

fix(functions): make functions:serve match deployed cloud functions - #299

Merged
Harshi-Shah-CS merged 27 commits into
v2-devfrom
CL-8791
Nov 19, 2026
Merged

Harshi-Shah-CS merged 27 commits into
v2-devfrom
CL-8791

Conversation

@Harshi-Shah-CS

Copy link
Copy Markdown
Contributor

Fixes CL-8791 (V2 bug bash, scenario 9.1): launch:functions:serve behaved differently from deployed cloud functions, and its errors were hard to act on.

What

Requests now match AWS deployed functions (lambda-node-bridge/cf-sv-with-helpers.ts in contentfly-deployment-agent), as agreed with the ticket's reporter:

  • The project .env is loaded before functions are bundled, so code that reads a variable at the top of a file gets its value.
  • request.cookies is the parsed Cookie header, or {} when there is none. cookie is now a direct dependency, at the version express already pulls in.
  • text/plain bodies arrive as the raw string and application/octet-stream bodies as a Buffer. JSON, urlencoded, text and binary bodies are all accepted up to Lambda's 6mb cap (body-parser's default was 100kb).
  • Body parsers and the cache-control: no-store default are registered once, not once per function. Parser error responses (malformed JSON, oversize) now carry cache-control: no-store too.

Imports from outside functions/ are warned about. They work locally but fail when deployed. serve prints warn: functions/a.js imports shared/util.js, which is outside functions/ and will not be available when deployed. and keeps serving. The warning names the function file that crosses the boundary: it follows static, dynamic and CommonJS imports, and chains through other outside files. Each warning prints once across all functions. node_modules packages are exempt.

Errors and ports:

  • --port 0 prints the port the server actually listens on.
  • A port must be decimal digits. 0x10, 1e3, +3000 and 3000 are rejected.
  • An invalid port, a missing --data-dir and a --data-dir that is a file now print one error: line on stderr (coloured only on a TTY) through the shared failure path, and exit 1. The invalid-port record is still written to logs/error.log and is flushed to disk before the process exits.
  • logs/ is created only when something is written to it, so a normal or failed run no longer leaves an empty folder.

Please check: V1 parity in AGENTS.md

AGENTS.md said serve was V1 byte for byte, on the product owner's instruction: port errors on stdout, nothing on stderr, "do not add this.error". This PR changes that section on purpose. It keeps what the ticket calls deliberate V1 parity (PORT beats --port, exit 1 on a bad port) and lists the rest as approved differences. If the stderr and port changes should not ship, say so here.

Known gaps (not fixed here)

  • Azure and GCP: they run the vendored CLI 1.6.0 server, which leaves text and octet-stream bodies unparsed and never sets request.cookies. Locally, a handler that reads the raw request stream for those two types now gets an empty stream. Updating the vendored copy is a separate deployment-agent change.
  • Symlinked packages: an npm/yarn workspace or file: package resolves outside node_modules, so it can get the outside-functions/ warning.
  • Other body types: XML, CSV and similar still arrive as {}, as before. AWS gives undefined for them.
  • Error naming: load and runtime errors still don't name the user's file (ticket item 3). That is a follow-up.

Tests

  • New unit tests cover each behaviour above in src/functions/cloud-functions.test.ts and src/functions/function.logger.test.ts. src/commands/launch/functions/serve.test.ts covers the port and --data-dir cases. test/integration/functions-serve-port.test.ts checks the stderr line, the exit code and error.log end to end.
  • Tests that pinned the old stdout output and the up-front logs/ folder are updated to the new behaviour.
  • Full suite green: npm test, 197 suites, 3,900 tests.
  • Checked against the built CLI (node bin/run.js launch:functions:serve --port 70000): exit 1, nothing on stdout, one line on stderr, and the record in logs/error.log.

#claude_code#
🤖 Generated with Claude Code

Harshi-Shah-CS and others added 26 commits November 19, 2026 19:51
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…eader

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…as a buffer

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 <noreply@anthropic.com>
…parsed

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 <noreply@anthropic.com>
…unction

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…uested

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 <noreply@anthropic.com>
…b cap

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 <noreply@anthropic.com>
…ding dots

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
… on a tty

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 <noreply@anthropic.com>
…e shared path

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 <noreply@anthropic.com>
A --data-dir pointing at a file reached the Logger, whose file transport
failed with an internal "ENOTDIR: not a directory, mkdir '<file>/logs'".
Check that the path is a directory before building the Logger and fail
with "--data-dir <path> is not a directory", exit 1.

#claude_code#
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…file

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@Harshi-Shah-CS
Harshi-Shah-CS requested review from a team as code owners November 19, 2026 16:35
@snyk-io

snyk-io Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues
✅ Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@github-actions

Copy link
Copy Markdown

🔒 Security Scan Results

ℹ️ Note: Only vulnerabilities with available fixes (upgrades or patches) are counted toward thresholds.

Check Type Count (with fixes) Without fixes Threshold Result
🔴 Critical Severity 0 0 10 ✅ Passed
🟠 High Severity 0 2 25 ✅ Passed
🟡 Medium Severity 0 1 500 ✅ Passed
🔵 Low Severity 0 0 1000 ✅ Passed

⏱️ SLA Breach Summary

✅ No SLA breaches detected. All vulnerabilities are within acceptable time thresholds.

Severity Breaches (with fixes) Breaches (no fixes) SLA Threshold (with/no fixes) Status
🔴 Critical 0 0 15 / 30 days ✅ Passed
🟠 High 0 0 30 / 120 days ✅ Passed
🟡 Medium 0 0 90 / 365 days ✅ Passed
🔵 Low 0 0 180 / 365 days ✅ Passed

ℹ️ Vulnerabilities Without Available Fixes (Informational Only)

The following vulnerabilities were detected but do not have fixes available (no upgrade or patch). These are excluded from failure thresholds:

  • Critical without fixes: 0
  • High without fixes: 2
  • Medium without fixes: 1
  • Low without fixes: 0

✅ BUILD PASSED - All security checks passed

@github-actions

Copy link
Copy Markdown

🔒 Security Scan Results

ℹ️ Note: Only vulnerabilities with available fixes (upgrades or patches) are counted toward thresholds.

Check Type Count (with fixes) Without fixes Threshold Result
🔴 Critical Severity 0 0 10 ✅ Passed
🟠 High Severity 0 2 25 ✅ Passed
🟡 Medium Severity 0 1 500 ✅ Passed
🔵 Low Severity 0 0 1000 ✅ Passed

⏱️ SLA Breach Summary

✅ No SLA breaches detected. All vulnerabilities are within acceptable time thresholds.

Severity Breaches (with fixes) Breaches (no fixes) SLA Threshold (with/no fixes) Status
🔴 Critical 0 0 15 / 30 days ✅ Passed
🟠 High 0 0 30 / 120 days ✅ Passed
🟡 Medium 0 0 90 / 365 days ✅ Passed
🔵 Low 0 0 180 / 365 days ✅ Passed

ℹ️ Vulnerabilities Without Available Fixes (Informational Only)

The following vulnerabilities were detected but do not have fixes available (no upgrade or patch). These are excluded from failure thresholds:

  • Critical without fixes: 0
  • High without fixes: 2
  • Medium without fixes: 1
  • Low without fixes: 0

✅ BUILD PASSED - All security checks passed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants