diff --git a/src/cli/commands/logs/index.ts b/src/cli/commands/logs/index.ts new file mode 100644 index 00000000..15951019 --- /dev/null +++ b/src/cli/commands/logs/index.ts @@ -0,0 +1,296 @@ +import { Command } from "commander"; +import type { CLIContext } from "@/cli/types.js"; +import { runCommand } from "@/cli/utils/index.js"; +import type { RunCommandResult } from "@/cli/utils/runCommand.js"; +import { InvalidInputError } from "@/core/errors.js"; +import { readProjectConfig } from "@/core/index.js"; +import type { + FunctionLogFilters, + FunctionLogsResponse, + LogLevel, +} from "@/core/resources/function/index.js"; +import { + FunctionNotFoundError, + fetchFunctionLogs, +} from "@/core/resources/function/index.js"; + +// ─── TYPES ────────────────────────────────────────────────── + +interface LogsOptions { + function?: string; + since?: string; + until?: string; + level?: string; + limit?: string; + order?: string; + json?: boolean; +} + +/** + * Unified log entry for display. + */ +interface LogEntry { + time: string; + level: string; + message: string; + source: string; // function name +} + +// ─── CONSTANTS ────────────────────────────────────────────── + +const VALID_LEVELS = ["log", "info", "warn", "error", "debug"]; + +// ─── OPTION PARSING ───────────────────────────────────────── + +/** + * Parse CLI options into FunctionLogFilters. + */ +function parseFunctionFilters(options: LogsOptions): FunctionLogFilters { + const filters: FunctionLogFilters = {}; + + if (options.since) { + filters.since = options.since; + } + + if (options.until) { + filters.until = options.until; + } + + if (options.level) { + filters.level = options.level as LogLevel; + } + + if (options.limit) { + filters.limit = Number.parseInt(options.limit, 10); + } + + if (options.order) { + filters.order = options.order.toLowerCase() as "asc" | "desc"; + } + + return filters; +} + +/** + * Parse --function option into array of function names. + */ +function parseFunctionNames(option: string | undefined): string[] { + if (!option) return []; + return option + .split(",") + .map((s) => s.trim()) + .filter((s) => s.length > 0); +} + +/** + * Ensure datetime has a timezone (append Z if missing) for APIs that require it. + */ +function normalizeDatetime(value: string): string { + if (/Z$|[+-]\d{2}:\d{2}$/.test(value)) return value; + return `${value}Z`; +} + +/** + * Validate CLI options upfront before any API calls. + */ +function validateOptions(options: LogsOptions): void { + if (options.level && !VALID_LEVELS.includes(options.level)) { + throw new InvalidInputError( + `Invalid level: "${options.level}". Must be one of: ${VALID_LEVELS.join(", ")}.` + ); + } + if (options.limit) { + const limit = Number.parseInt(options.limit, 10); + if (Number.isNaN(limit) || limit < 1 || limit > 1000) { + throw new InvalidInputError( + `Invalid limit: "${options.limit}". Must be a number between 1 and 1000.` + ); + } + } + if (options.order) { + const order = options.order.toUpperCase(); + if (order !== "ASC" && order !== "DESC") { + throw new InvalidInputError( + `Invalid order: "${options.order}". Must be "ASC" or "DESC".` + ); + } + } +} + +// ─── DISPLAY ──────────────────────────────────────────────── + +/** + * Format a single log entry as a plain log-file line. + */ +function formatEntry(entry: LogEntry): string { + const time = entry.time.substring(0, 19).replace("T", " "); + const level = entry.level.toUpperCase().padEnd(5); + const message = entry.message.trim(); + return `${time} ${level} ${message}\n`; +} + +/** + * Display function logs (log-file style, plain stdout). + */ +function displayLogs(entries: LogEntry[]): void { + if (entries.length === 0) { + process.stdout.write("No logs found matching the filters.\n"); + return; + } + + process.stdout.write(`Showing ${entries.length} function log entries\n\n`); + + for (const entry of entries) { + process.stdout.write(formatEntry(entry)); + } +} + +// ─── ACTIONS ──────────────────────────────────────────────── + +/** + * Normalize a function log entry to display format. + */ +function normalizeLogEntry( + entry: { time: string; level: string; message: string }, + functionName: string +): LogEntry { + return { + time: entry.time, + level: entry.level, + message: `[${functionName}] ${entry.message}`, + source: functionName, + }; +} + +/** + * Fetch logs for specified functions. + * If a function is not found, re-throws with a hint listing available functions. + */ +async function fetchLogsForFunctions( + functionNames: string[], + options: LogsOptions, + availableFunctionNames: string[] +): Promise { + const filters = parseFunctionFilters(options); + const allEntries: LogEntry[] = []; + + for (const functionName of functionNames) { + let logs: FunctionLogsResponse; + try { + logs = await fetchFunctionLogs(functionName, filters); + } catch (error) { + if ( + error instanceof FunctionNotFoundError && + availableFunctionNames.length > 0 + ) { + const available = availableFunctionNames.join(", "); + throw new InvalidInputError( + `Function "${functionName}" was not found in this app`, + { + hints: [ + { + message: `Available functions in this project: ${available}`, + }, + { + message: + "Make sure the function has been deployed before fetching logs", + command: "base44 functions deploy", + }, + ], + } + ); + } + throw error; + } + + const entries = logs.map((entry) => normalizeLogEntry(entry, functionName)); + allEntries.push(...entries); + } + + // When fetching multiple functions, merge-sort the combined results + // (each function's logs are already sorted by the backend) + if (functionNames.length > 1) { + const order = options.order?.toUpperCase() === "ASC" ? 1 : -1; + allEntries.sort((a, b) => order * a.time.localeCompare(b.time)); + } + + return allEntries; +} + +/** + * Get all function names from project config. + */ +async function getAllFunctionNames(): Promise { + const { functions } = await readProjectConfig(); + return functions.map((fn) => fn.name); +} + +/** + * Main logs action. + */ +async function logsAction(options: LogsOptions): Promise { + if (options.since) options.since = normalizeDatetime(options.since); + if (options.until) options.until = normalizeDatetime(options.until); + validateOptions(options); + + const specifiedFunctions = parseFunctionNames(options.function); + + // Always read project functions so we can list them in error messages + const allProjectFunctions = await getAllFunctionNames(); + + // Determine which functions to fetch logs for + const functionNames = + specifiedFunctions.length > 0 ? specifiedFunctions : allProjectFunctions; + + if (functionNames.length === 0) { + process.stdout.write("No functions found in this project.\n"); + return {}; + } + + let entries = await fetchLogsForFunctions( + functionNames, + options, + allProjectFunctions + ); + + // Apply limit after merging logs from all functions + const limit = options.limit ? Number.parseInt(options.limit, 10) : undefined; + if (limit !== undefined && entries.length > limit) { + entries = entries.slice(0, limit); + } + + if (options.json) { + process.stdout.write(`${JSON.stringify(entries, null, 2)}\n`); + } else { + displayLogs(entries); + } + + return {}; +} + +// ─── COMMAND ──────────────────────────────────────────────── + +export function getLogsCommand(context: CLIContext): Command { + return new Command("logs") + .description("Fetch function logs for this app") + .option( + "--function ", + "Filter by function name(s), comma-separated. If omitted, fetches logs for all project functions" + ) + .option("--since ", "Show logs from this time (ISO format)") + .option("--until ", "Show logs until this time (ISO format)") + .option( + "--level ", + "Filter by log level: log, info, warn, error, debug" + ) + .option("-n, --limit ", "Results per page (1-1000, default: 50)") + .option("--order ", "Sort order: ASC|DESC (default: DESC)") + .option("--json", "Output raw JSON") + .action(async (options: LogsOptions) => { + await runCommand( + () => logsAction(options), + { requireAuth: true, skipIntro: true, skipOutro: true }, + context + ); + }); +} diff --git a/src/cli/program.ts b/src/cli/program.ts index 15e4f1d7..024b71e1 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -6,6 +6,7 @@ import { getWhoamiCommand } from "@/cli/commands/auth/whoami.js"; import { getDashboardCommand } from "@/cli/commands/dashboard/index.js"; import { getEntitiesPushCommand } from "@/cli/commands/entities/push.js"; import { getFunctionsDeployCommand } from "@/cli/commands/functions/deploy.js"; +import { getLogsCommand } from "@/cli/commands/logs/index.js"; import { getCreateCommand } from "@/cli/commands/project/create.js"; import { getDeployCommand } from "@/cli/commands/project/deploy.js"; import { getLinkCommand } from "@/cli/commands/project/link.js"; @@ -54,5 +55,8 @@ export function createProgram(context: CLIContext): Command { // Register types command program.addCommand(getTypesCommand(context), { hidden: true }); + // Register logs command + program.addCommand(getLogsCommand(context)); + return program; } diff --git a/src/cli/utils/runCommand.ts b/src/cli/utils/runCommand.ts index 0dcd35a2..5abd980a 100644 --- a/src/cli/utils/runCommand.ts +++ b/src/cli/utils/runCommand.ts @@ -27,6 +27,18 @@ export interface RunCommandOptions { * @default true */ requireAppConfig?: boolean; + /** + * Skip intro and upgrade notification for pipe-friendly or log-file-style output. + * Use for commands that write raw content to stdout (e.g. logs). + * @default false + */ + skipIntro?: boolean; + /** + * Skip outro for pipe-friendly or log-file-style output. + * Use for commands that write raw content to stdout (e.g. logs). + * @default false + */ + skipOutro?: boolean; } export interface RunCommandResult { @@ -65,17 +77,20 @@ export async function runCommand( options: RunCommandOptions | undefined, context: CLIContext ): Promise { - console.log(); + const skipIntro = options?.skipIntro === true; + const skipOutro = options?.skipOutro === true; - if (options?.fullBanner) { - await printBanner(); - intro(""); - } else { - intro(theme.colors.base44OrangeBackground(" Base 44 ")); + if (!skipIntro) { + console.log(); + if (options?.fullBanner) { + await printBanner(); + intro(""); + } else { + intro(theme.colors.base44OrangeBackground(" Base 44 ")); + } + await printUpgradeNotificationIfAvailable(); } - await printUpgradeNotificationIfAvailable(); - try { // Check authentication if required if (options?.requireAuth) { @@ -103,7 +118,9 @@ export async function runCommand( } const { outroMessage } = await commandFn(); - outro(outroMessage || ""); + if (!skipOutro) { + outro(outroMessage || ""); + } } catch (error) { // Display error message const errorMessage = error instanceof Error ? error.message : String(error); @@ -124,7 +141,11 @@ export async function runCommand( // Get error context and display in outro const errorContext = context.errorReporter.getErrorContext(); - outro(theme.format.errorContext(errorContext)); + if (!skipOutro) { + outro(theme.format.errorContext(errorContext)); + } else { + process.stderr.write(`${theme.format.errorContext(errorContext)}\n`); + } // Re-throw for runCLI to handle (error reporting, exit code) throw error; diff --git a/src/core/errors.ts b/src/core/errors.ts index 32c1e1a8..4f74fb66 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -424,6 +424,29 @@ export class FileReadError extends SystemError { } } +/** + * Thrown when a specific function is not found in the app. + */ +export class FunctionNotFoundError extends ApiError { + constructor(functionName: string, cause: Error) { + super(`Function "${functionName}" was not found in this app`, { + statusCode: 404, + cause, + hints: [ + { + message: + "Make sure the function name is correct and has been deployed", + command: "base44 functions deploy", + }, + { + message: + "List project functions by checking the base44/functions/ directory", + }, + ], + }); + } +} + /** * Thrown for unexpected internal errors. */ diff --git a/src/core/resources/function/api.ts b/src/core/resources/function/api.ts index 03974785..31e61b48 100644 --- a/src/core/resources/function/api.ts +++ b/src/core/resources/function/api.ts @@ -1,11 +1,23 @@ import type { KyResponse } from "ky"; +import { HTTPError } from "ky"; import { getAppClient } from "@/core/clients/index.js"; -import { ApiError, SchemaValidationError } from "@/core/errors.js"; +import { + ApiError, + FunctionNotFoundError, + SchemaValidationError, +} from "@/core/errors.js"; import type { DeployFunctionsResponse, + FunctionLogFilters, + FunctionLogsResponse, FunctionWithCode, } from "@/core/resources/function/schema.js"; -import { DeployFunctionsResponseSchema } from "@/core/resources/function/schema.js"; +import { + DeployFunctionsResponseSchema, + FunctionLogsResponseSchema, +} from "@/core/resources/function/schema.js"; + +export { FunctionNotFoundError }; function toDeployPayloadItem(fn: FunctionWithCode) { return { @@ -45,3 +57,86 @@ export async function deployFunctions( return result.data; } + +// ─── FUNCTION LOGS API ────────────────────────────────────── + +/** + * Build query string from filter options. + */ +function buildLogsQueryString(filters: FunctionLogFilters): string { + const params = new URLSearchParams(); + + if (filters.since) { + params.set("since", filters.since); + } + if (filters.until) { + params.set("until", filters.until); + } + if (filters.level) { + params.set("level", filters.level); + } + if (filters.limit !== undefined) { + params.set("limit", String(filters.limit)); + } + if (filters.order) { + params.set("order", filters.order); + } + + const queryString = params.toString(); + return queryString ? `?${queryString}` : ""; +} + +/** + * Fetch runtime logs for a specific function from Deno Deploy. + */ +export async function fetchFunctionLogs( + functionName: string, + filters: FunctionLogFilters = {} +): Promise { + const appClient = getAppClient(); + const queryString = buildLogsQueryString(filters); + + let response: KyResponse; + try { + response = await appClient.get( + `functions-mgmt/${functionName}/logs${queryString}` + ); + } catch (error) { + if (error instanceof HTTPError) { + if (error.response.status === 404) { + throw new FunctionNotFoundError(functionName, error); + } + + // The server returns a 500 with a KeyError when the function doesn't + // exist: {"error_type":"KeyError","message":"'fn-name'", ...} + // Detect this and throw a clear "not found" error instead. + try { + const body = (await error.response.clone().json()) as Record< + string, + unknown + >; + if (body.error_type === "KeyError") { + throw new FunctionNotFoundError(functionName, error); + } + } catch (parseError) { + if (parseError instanceof ApiError) throw parseError; + // JSON parse failed — fall through to generic handler + } + } + throw await ApiError.fromHttpError( + error, + `fetching function logs: '${functionName}'` + ); + } + + const result = FunctionLogsResponseSchema.safeParse(await response.json()); + + if (!result.success) { + throw new SchemaValidationError( + "Invalid function logs response from server", + result.error + ); + } + + return result.data; +} diff --git a/src/core/resources/function/schema.ts b/src/core/resources/function/schema.ts index 6da71f15..80109d69 100644 --- a/src/core/resources/function/schema.ts +++ b/src/core/resources/function/schema.ts @@ -103,3 +103,41 @@ export type DeployFunctionsResponse = z.infer< export type FunctionWithCode = Omit & { files: FunctionFile[]; }; + +// ─── FUNCTION LOGS SCHEMAS ────────────────────────────────── + +/** + * Log level from Deno Deploy runtime. + */ +export const LogLevelSchema = z.enum(["log", "info", "warn", "error", "debug"]); + +export type LogLevel = z.infer; + +/** + * Single log entry from the function runtime (Deno Deploy). + */ +export const FunctionLogEntrySchema = z.object({ + time: z.string(), + level: LogLevelSchema, + message: z.string(), +}); + +export type FunctionLogEntry = z.infer; + +/** + * Response from the function logs API - array of log entries. + */ +export const FunctionLogsResponseSchema = z.array(FunctionLogEntrySchema); + +export type FunctionLogsResponse = z.infer; + +/** + * CLI filter options for function logs. + */ +export interface FunctionLogFilters { + since?: string; + until?: string; + level?: LogLevel; + limit?: number; + order?: "asc" | "desc"; +} diff --git a/tests/cli/logs.spec.ts b/tests/cli/logs.spec.ts new file mode 100644 index 00000000..62296e94 --- /dev/null +++ b/tests/cli/logs.spec.ts @@ -0,0 +1,190 @@ +import { describe, it } from "vitest"; +import { fixture, setupCLITests } from "./testkit/index.js"; + +describe("logs command", () => { + const t = setupCLITests(); + + it("fetches and displays function logs when --function is specified", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", [ + { + time: "2024-01-15T10:30:00.000Z", + level: "info", + message: "Processing request", + }, + { + time: "2024-01-15T10:30:00.050Z", + level: "error", + message: "Something went wrong", + }, + ]); + + const result = await t.run("logs", "--function", "my-function"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("Showing 2 function log entries"); + t.expectResult(result).toContain("Processing request"); + t.expectResult(result).toContain("Something went wrong"); + }); + + it("fetches logs for multiple functions with --function comma-separated", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("fn1", [ + { time: "2024-01-15T10:30:00Z", level: "info", message: "From fn1" }, + ]); + t.api.mockFunctionLogs("fn2", [ + { time: "2024-01-15T10:29:00Z", level: "info", message: "From fn2" }, + ]); + + const result = await t.run("logs", "--function", "fn1,fn2"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("From fn1"); + t.expectResult(result).toContain("From fn2"); + }); + + it("fetches logs for all project functions when no --function specified", async () => { + await t.givenLoggedInWithProject(fixture("full-project")); + t.api.mockFunctionLogs("hello", [ + { time: "2024-01-15T10:29:00Z", level: "log", message: "Hello world" }, + ]); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("Hello world"); + }); + + it("shows no functions message when project has no functions", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("No functions found in this project"); + }); + + it("shows no logs message when empty", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", []); + + const result = await t.run("logs", "--function", "my-function"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("No logs found matching the filters."); + }); + + it("filters function logs by --level", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + // Backend filters by level, so mock returns only matching entries + t.api.mockFunctionLogs("my-function", [ + { + time: "2024-01-15T10:30:00.050Z", + level: "error", + message: "Error message", + }, + ]); + + const result = await t.run( + "logs", + "--function", + "my-function", + "--level", + "error" + ); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("Error message"); + t.expectResult(result).toNotContain("Info message"); + }); + + it("outputs JSON with --json flag", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", [ + { + time: "2024-01-15T10:30:00.000Z", + level: "info", + message: "Test log", + }, + ]); + + const result = await t.run("logs", "--function", "my-function", "--json"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain('"time"'); + t.expectResult(result).toContain('"level"'); + t.expectResult(result).toContain('"message"'); + t.expectResult(result).toContain('"source"'); + }); + + it("fails when not in a project directory", async () => { + await t.givenLoggedIn({ email: "test@example.com", name: "Test User" }); + + const result = await t.run("logs"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("No Base44 project found"); + }); + + it("fails when API returns error for function logs", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogsError("my-function", { + status: 500, + body: { error: "Server error" }, + }); + + const result = await t.run("logs", "--function", "my-function"); + + t.expectResult(result).toFail(); + }); + + it("fails with invalid level option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run( + "logs", + "--function", + "dummy", + "--level", + "invalid" + ); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid level"); + }); + + it("fails with invalid limit option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("logs", "--limit", "9999"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid limit"); + }); + + it("fails with invalid order option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + + const result = await t.run("logs", "--order", "RANDOM"); + + t.expectResult(result).toFail(); + t.expectResult(result).toContain("Invalid order"); + }); + + it("passes filter options to API", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", []); + + const result = await t.run( + "logs", + "--function", + "my-function", + "--limit", + "10", + "--order", + "ASC" + ); + + t.expectResult(result).toSucceed(); + }); +}); diff --git a/tests/cli/testkit/Base44APIMock.ts b/tests/cli/testkit/Base44APIMock.ts index c1e1d4ec..ada3be22 100644 --- a/tests/cli/testkit/Base44APIMock.ts +++ b/tests/cli/testkit/Base44APIMock.ts @@ -57,6 +57,14 @@ export interface AgentsFetchResponse { total: number; } +export interface FunctionLogEntry { + time: string; + level: "log" | "info" | "warn" | "error" | "debug"; + message: string; +} + +export type FunctionLogsResponse = FunctionLogEntry[]; + export interface CreateAppResponse { id: string; name: string; @@ -182,6 +190,17 @@ export class Base44APIMock { return this; } + /** Mock GET /api/apps/{appId}/functions-mgmt/{functionName}/logs - Fetch function logs */ + mockFunctionLogs(functionName: string, response: FunctionLogsResponse): this { + this.handlers.push( + http.get( + `${BASE_URL}/api/apps/${this.appId}/functions-mgmt/${functionName}/logs`, + () => HttpResponse.json(response) + ) + ); + return this; + } + // ─── GENERAL ENDPOINTS ───────────────────────────────────── /** Mock POST /api/apps - Create new app */ @@ -263,6 +282,15 @@ export class Base44APIMock { ); } + /** Mock function logs to return an error */ + mockFunctionLogsError(functionName: string, error: ErrorResponse): this { + return this.mockError( + "get", + `/api/apps/${this.appId}/functions-mgmt/${functionName}/logs`, + error + ); + } + /** Mock token endpoint to return an error (for auth failure testing) */ mockTokenError(error: ErrorResponse): this { return this.mockError("post", "/oauth/token", error);