diff --git a/.talismanrc b/.talismanrc index 7e003f9..6dd8717 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 70d8c0a..eca5465 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 diff --git a/package-lock.json b/package-lock.json index c0038e7..48ca4cf 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 c708d50..9a3d0cc 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/commands/launch/functions/serve.test.ts b/src/commands/launch/functions/serve.test.ts index 2738818..c4350e0 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, 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,46 +150,55 @@ 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([]); }); - it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' '])( - 'rejects the invalid port %p once through the project logger and exits 1 as v1 did', + it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' ', '0x10', '1e3', '+3000', ' 3000'])( + '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 }); 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`]); - await eventually(() => readLog(dataDir, 'error.log') !== ''); + expect(stdout).toEqual([]); expect(readLog(dataDir, 'error.log')).toBe(`{"level":"error","message":"${INVALID_PORT_MESSAGE}"}\n`); expect(readLog(dataDir, 'info.log')).toBe(''); }, ); - 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(); }); + 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); @@ -308,10 +308,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 2eaf834..a9891b3 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, statSync } from 'node:fs'; import { EXIT_RUNTIME, EXIT_USAGE } from '../../../core/constants'; import { failureOutputOf, reportFailure } from '../../../core/failure'; @@ -24,14 +25,23 @@ 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 }); + } + + 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); 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'); + await logger.flush(); + this.error(message, { exit: EXIT_RUNTIME }); } this.sharedConfig = { diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 02110f3..b80447a 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, functionFilesImporting, isOutsideDirectory, listenFailure } from './cloud-functions'; import { PortInUseError } from './function.errors'; import { loadDataURL } from './load-data-url'; @@ -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(); @@ -43,9 +47,15 @@ function freePort(): Promise { }); } -function sendRequest(port: number, path: string, method = 'GET'): 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 }, (response) => { + const clientRequest = httpRequest({ host: '127.0.0.1', port, path, method, headers }, (response) => { let body = ''; response.setEncoding('utf8'); response.on('data', (chunk) => { @@ -60,7 +70,7 @@ function sendRequest(port: number, path: string, method = 'GET'): Promise { ]); }); + 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(); @@ -267,11 +287,246 @@ 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' }); }); + 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', { headers: { cookie: 'sid=abc; theme=dark%20mode' } }); + + 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.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.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.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(); + + await new CloudFunctions(workspace).serve(port); + 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' }); + }); + + 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('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('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( + '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" };'); + 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(); @@ -295,6 +550,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(); @@ -307,23 +577,48 @@ 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; }); }); +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); + }); +}); + 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 baa4944..8f8a7e9 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -1,12 +1,17 @@ +import { parse as parseCookieHeader } from 'cookie'; import dotenv from 'dotenv'; import type { + NextFunction, Request, Response, } from 'express'; 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 type { Plugin } from 'rollup'; import { styled } from '../core/style'; import { isRecord } from '../core/values'; @@ -23,10 +28,110 @@ 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'; } +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); + }); +} + +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); +} + +function attachCookies(request: Request, _response: Response, next: NextFunction): void { + request.cookies = request.headers.cookie ? parseCookieHeader(request.headers.cookie) : {}; + 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(defaultToNoStore); + app.use(attachCookies); + 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 })); +} + import { loadDataURL } from './load-data-url'; export function listenFailure(error: NodeJS.ErrnoException, servingPort: number): Error { @@ -52,6 +157,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; @@ -72,11 +179,9 @@ export class CloudFunctions { const app = express(); app.disable('x-powered-by'); - - await this.applyAppRouter(exactRouteResources, app); - await this.applyAppRouter(dynamicRouteResources, app); - - dotenv.config({ path: path.join(this.pathToSourceCode, ENV_FILE_NAME) }); + applyRequestMiddleware(app); + this.applyAppRouter(exactRouteResources, app); + this.applyAppRouter(dynamicRouteResources, app); return this.startServer(app, servingPort, [ ...exactRouteResources, @@ -109,7 +214,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); }); @@ -117,36 +222,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 { @@ -158,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) { @@ -169,7 +259,7 @@ export class CloudFunctions { continue; } - const handler = await this.buildHandlerForFilepath(filePath); + const handler = await this.buildHandlerForFilepath(filePath, outsideImports); if (!handler) { continue; } @@ -226,17 +316,22 @@ export class CloudFunctions { return { exactRouteResources, dynamicRouteResources }; } - 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'), 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)], }); + outsideImports.report(importersById); const { output } = await bundle.generate({ format: 'esm', diff --git a/src/functions/function.inputs.ts b/src/functions/function.inputs.ts index 7d80888..e1ee734 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; } diff --git a/src/functions/function.logger.test.ts b/src/functions/function.logger.test.ts index 20dc0a1..fba7d19 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,17 +66,16 @@ 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 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 +83,16 @@ 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('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 () => { @@ -131,7 +135,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 c6b4075..b15676d 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,49 +51,59 @@ 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); + } + } + + private get consoleFormat(): winston.Logform.Format { + return winston.format.combine(winston.format.simple(), winston.format.colorize({ all: true })); + } + + private get infoLogger(): winston.Logger { + this.loggers.info ??= this.getLoggerInstance('info'); + return this.loggers.info; + } + + private get errorLogger(): winston.Logger { + this.loggers.error ??= this.getLoggerInstance('error'); + return this.loggers.error; } getLoggerInstance(logType: LoggerType): winston.Logger { - const consoleOptions: winston.transports.ConsoleTransportOptions = { - format: winston.format.combine(winston.format.simple(), winston.format.colorize({ all: true })), - }; + 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') { - consoleOptions.level = logType; + return winston.createLogger({ transports: [fileTransport], levels: { error: 0 } }); } - if (existsSync(this.config.projectBasePath)) { - const filename = normalize(resolve(this.config.projectBasePath, 'logs', `${logType}.log`)).replace( - /^(\.\.(\/|\\|$))+/, - '', - ); - const loggerOptions: winston.LoggerOptions = { - transports: [ - new winston.transports.File({ - ...this.loggerOptions, - level: logType, - filename, - }), - new winston.transports.Console(consoleOptions), - ], - levels: customLevels.levels, - }; - - if (logType === 'error') { - loggerOptions.levels = { error: 0 }; - } + return winston.createLogger({ + transports: [fileTransport, new winston.transports.Console({ format: this.consoleFormat })], + levels: customLevels.levels, + }); + } - return winston.createLogger(loggerOptions); - } + 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; + }); - winston - .createLogger({ - transports: [new winston.transports.Console(consoleOptions)], - }) - .error('Provided base path is not valid'); - process.exit(1); + await Promise.all( + fileTransports.map((transport) => new Promise((resolve) => transport.once('finish', () => resolve()))), + ); } 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 09ecd55..ffe6f41 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; @@ -38,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)); } @@ -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 9cbe9f4..e916f79 100644 --- a/test/integration/retired-commands.test.ts +++ b/test/integration/retired-commands.test.ts @@ -122,15 +122,15 @@ 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; - 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 }); });