diff --git a/src/cli/commands/logs/index.ts b/src/cli/commands/logs/index.ts new file mode 100644 index 00000000..c84c3128 --- /dev/null +++ b/src/cli/commands/logs/index.ts @@ -0,0 +1,628 @@ +import { log } from "@clack/prompts"; +import { Command } from "commander"; +import type { CLIContext } from "@/cli/types.js"; +import { runCommand, runTask, theme } 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 { + AuditLogEvent, + AuditLogFilters, + AuditLogsResponse, +} from "@/core/logs/index.js"; +import { fetchAuditLogs } from "@/core/logs/index.js"; +import type { + FunctionLogFilters, + LogLevel, +} from "@/core/resources/function/index.js"; +import { 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 (normalized from both sources). + */ +interface UnifiedLogEntry { + time: string; + level: string; + message: string; + source: string; // "App" for audit logs, function name for function logs +} + +/** + * Counts for display header (audit vs function breakdown and pagination). + */ +interface LogCounts { + auditCount: number; + functionCount: number; + auditTotal?: number; + hasMore?: boolean; +} + +// ─── CONSTANTS ────────────────────────────────────────────── + +const VALID_LEVELS = ["log", "info", "warn", "error", "debug"]; + +// ─── AUDIT LOG MESSAGE FORMATTING ─────────────────────────── + +/** + * Format an audit log event into a human-readable message. + */ +function formatAuditMessage(event: AuditLogEvent): string { + const m = (event.metadata ?? {}) as Record; + const isFailure = event.status === "failure"; + + switch (event.event_type) { + // Function calls + case "api.function.call": { + const fnName = m.function_name ?? "unknown"; + const statusCode = m.status_code ?? ""; + return isFailure + ? `function ${fnName} failed (status ${statusCode})` + : `function ${fnName} called (status ${statusCode})`; + } + + // Entity operations + case "app.entity.created": { + const entity = m.entity_name ?? "unknown"; + const id = m.entity_id ?? ""; + return isFailure + ? `failed to create entity ${entity}` + : `entity ${entity} created (id: ${id})`; + } + case "app.entity.updated": { + const entity = m.entity_name ?? "unknown"; + const id = m.entity_id ?? ""; + return isFailure + ? `failed to update entity ${entity}` + : `entity ${entity} updated (id: ${id})`; + } + case "app.entity.deleted": { + const entity = m.entity_name ?? "unknown"; + const id = m.entity_id ?? ""; + return isFailure + ? `failed to delete entity ${entity}` + : `entity ${entity} deleted (id: ${id})`; + } + case "app.entity.bulk_created": { + const entity = m.entity_name ?? "unknown"; + const count = m.count ?? 0; + const method = m.method ?? ""; + return isFailure + ? `bulk create failed for ${entity}` + : `${count} ${entity} entities created via ${method}`; + } + case "app.entity.bulk_deleted": { + const entity = m.entity_name ?? "unknown"; + const count = m.count ?? 0; + const method = m.method ?? ""; + return isFailure + ? `bulk delete failed for ${entity}` + : `${count} ${entity} entities deleted via ${method}`; + } + case "app.entity.query": { + const entity = m.entity_name ?? "unknown"; + return isFailure ? `query failed for ${entity}` : `queried ${entity}`; + } + + // User operations (always success) + case "app.user.registered": { + const email = m.target_email ?? "unknown"; + const role = m.role ?? ""; + return `user ${email} registered as ${role}`; + } + case "app.user.updated": { + const email = m.target_email ?? "unknown"; + return `user ${email} updated`; + } + case "app.user.deleted": { + const email = m.target_email ?? "unknown"; + return `user ${email} deleted`; + } + case "app.user.role_changed": { + const email = m.target_email ?? "unknown"; + const oldRole = m.old_role ?? ""; + const newRole = m.new_role ?? ""; + return `user ${email} role changed: ${oldRole} → ${newRole}`; + } + case "app.user.invited": { + const email = m.invitee_email ?? "unknown"; + const role = m.role ?? ""; + return `invited ${email} as ${role}`; + } + case "app.user.page_visit": { + const page = m.page_name ?? "unknown"; + return `page visit: ${page}`; + } + + // Auth operations (always success) + case "app.auth.login": { + const method = m.auth_method ?? "unknown"; + return `login via ${method}`; + } + + // Access operations (always success) + case "app.access.requested": { + const email = m.requester_email ?? "unknown"; + return `access requested by ${email}`; + } + case "app.access.approved": { + const email = m.target_email ?? "unknown"; + return `access approved for ${email}`; + } + case "app.access.denied": { + const email = m.target_email ?? "unknown"; + return `access denied for ${email}`; + } + + // Automation & Integration (can fail) + case "app.automation.executed": { + const name = m.automation_name ?? "unknown"; + return isFailure + ? `automation ${name} failed` + : `automation ${name} executed`; + } + case "app.integration.executed": { + const name = m.integration_name ?? "unknown"; + const action = m.action ?? ""; + const duration = m.duration_ms ?? ""; + return isFailure + ? `integration ${name} failed: ${action}` + : `integration ${name}: ${action} (${duration}ms)`; + } + + // Agent conversation (always success) + case "app.agent.conversation": { + const name = m.agent_name ?? "unknown"; + const model = m.model ?? ""; + return `agent ${name} conversation (${model})`; + } + + // Fallback for unknown event types + default: + return isFailure ? `${event.event_type} failed` : event.event_type; + } +} + +/** + * Normalize an audit log event to unified format. + */ +function normalizeAuditLog(event: AuditLogEvent): UnifiedLogEntry { + const level = event.status === "failure" ? "error" : "info"; + const message = formatAuditMessage(event); + return { time: event.timestamp, level, message, source: "App" }; +} + +/** + * Normalize a function log entry to unified format. + */ +function normalizeFunctionLog( + entry: { time: string; level: string; message: string }, + functionName: string +): UnifiedLogEntry { + return { + time: entry.time, + level: entry.level, + message: `[${functionName}] ${entry.message}`, + source: functionName, + }; +} + +// ─── OPTION PARSING ───────────────────────────────────────── + +/** + * Map --level to audit log status filter. + * - log/info → success + * - error → failure + * - debug/warn → skip audit logs (returns null; audit has no warn level) + */ +function mapLevelToStatus( + level: string | undefined +): "success" | "failure" | null | undefined { + if (!level) return undefined; // No filter + if (level === "debug" || level === "warn") return null; // Skip audit logs + if (level === "log" || level === "info") return "success"; + if (level === "error") return "failure"; + return undefined; +} + +/** + * Parse CLI options into AuditLogFilters. + */ +function parseAuditFilters(options: LogsOptions): AuditLogFilters { + const filters: AuditLogFilters = {}; + + // Map level to status + const status = mapLevelToStatus(options.level); + if (status) { + filters.status = status; + } + + if (options.since) { + filters.since = options.since; + } + + if (options.until) { + filters.until = options.until; + } + + if (options.limit) { + filters.limit = Number.parseInt(options.limit, 10); + } + + if (options.order) { + filters.order = options.order.toUpperCase() as "ASC" | "DESC"; + } + + return filters; +} + +/** + * Check if audit logs should be fetched based on level filter. + */ +function shouldFetchAuditLogs(level: string | undefined): boolean { + return mapLevelToStatus(level) !== null; +} + +/** + * 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); + } + + 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 ──────────────────────────────────────────────── + +/** + * Get color/style for a log level. + */ +function formatLevel(level: string): string { + switch (level) { + case "error": + return theme.colors.base44Orange(level.padEnd(5)); + case "warn": + return theme.colors.shinyOrange(level.padEnd(5)); + case "info": + return theme.colors.links(level.padEnd(5)); + case "debug": + return theme.styles.dim(level.padEnd(5)); + default: + return level.padEnd(5); + } +} + +/** + * Wrap a single line at specified width, returning array of lines. + */ +function wrapLine(text: string, width: number): string[] { + if (text.length <= width) return [text]; + + const lines: string[] = []; + let remaining = text; + + while (remaining.length > width) { + // Find last space within width, or break at width if no space + let breakPoint = remaining.lastIndexOf(" ", width); + if (breakPoint <= 0) breakPoint = width; + + lines.push(remaining.substring(0, breakPoint)); + remaining = remaining.substring(breakPoint).trimStart(); + } + + if (remaining.length > 0) { + lines.push(remaining); + } + + return lines; +} + +// Column widths: TIME(19) + 2 spaces + LEVEL(5) + 2 spaces = 28 chars before message +const MESSAGE_INDENT = " ".repeat(28); +const MESSAGE_WIDTH = 80; + +/** + * Format a unified log entry for display. + * Preserves original newlines in the message and wraps long lines. + */ +function formatEntry(entry: UnifiedLogEntry): string { + const time = entry.time.substring(0, 19).replace("T", " "); + const level = formatLevel(entry.level); + + // Split by original newlines first, then wrap each line + const originalLines = entry.message.split("\n"); + const allLines: string[] = []; + + for (const line of originalLines) { + const wrappedLines = wrapLine(line, MESSAGE_WIDTH); + allLines.push(...wrappedLines); + } + + const firstLine = `${theme.styles.dim(time)} ${level} ${allLines[0] ?? ""}`; + + if (allLines.length <= 1) { + return firstLine; + } + + // Join continuation lines with proper indentation + const continuationLines = allLines + .slice(1) + .map((line) => `${MESSAGE_INDENT}${line}`) + .join("\n"); + + return `${firstLine}\n${continuationLines}`; +} + +/** + * Display unified logs with count breakdown. + */ +function displayLogs(entries: UnifiedLogEntry[], counts: LogCounts): void { + if (entries.length === 0) { + log.info("No logs found matching the filters."); + return; + } + + const { auditCount, functionCount, auditTotal, hasMore } = counts; + let countInfo: string; + if (auditCount > 0 && functionCount > 0) { + countInfo = `Showing ${entries.length} log entries (${auditCount} app events, ${functionCount} function logs)`; + } else if (auditCount > 0 && auditTotal !== undefined) { + countInfo = `Showing ${entries.length} of ${auditTotal} app events`; + } else if (functionCount > 0) { + countInfo = `Showing ${entries.length} function log entries`; + } else { + countInfo = `Showing ${entries.length} log entries`; + } + log.info(theme.styles.dim(`${countInfo}\n`)); + + const header = `${"TIME".padEnd(19)} ${"LEVEL".padEnd(5)} MESSAGE`; + log.message(theme.styles.header(header)); + + // Entries + for (const entry of entries) { + log.message(formatEntry(entry)); + } + + if (hasMore) { + log.info( + theme.styles.dim("\nMore results available. Use --limit to fetch more.") + ); + } +} + +// ─── ACTIONS ──────────────────────────────────────────────── + +/** + * Fetch and display audit logs. + */ +async function fetchAuditLogsAction(options: LogsOptions): Promise<{ + entries: UnifiedLogEntry[]; + pagination: AuditLogsResponse["pagination"]; +}> { + const filters = parseAuditFilters(options); + + const response = await runTask( + "Fetching app logs...", + async () => { + return await fetchAuditLogs(filters); + }, + { + successMessage: "Logs fetched successfully", + errorMessage: "Failed to fetch app logs", + } + ); + + const entries = response.events.map(normalizeAuditLog); + return { entries, pagination: response.pagination }; +} + +/** + * Fetch and display function logs. + */ +async function fetchFunctionLogsAction( + functionNames: string[], + options: LogsOptions +): Promise { + const filters = parseFunctionFilters(options); + const allEntries: UnifiedLogEntry[] = []; + + for (const functionName of functionNames) { + const logs = await runTask( + `Fetching logs for "${functionName}"...`, + async () => { + return await fetchFunctionLogs(functionName, filters); + }, + { + successMessage: `Logs for "${functionName}" fetched`, + errorMessage: `Failed to fetch logs for "${functionName}"`, + } + ); + + // Filter by level if specified (API doesn't support level filtering) + const filteredLogs = filters.level + ? logs.filter((entry) => entry.level === filters.level) + : logs; + + const entries = filteredLogs.map((entry) => + normalizeFunctionLog(entry, functionName) + ); + allEntries.push(...entries); + } + + // Sort by time (respecting order option) + 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); + const allEntries: UnifiedLogEntry[] = []; + let pagination: AuditLogsResponse["pagination"] | undefined; + + if (specifiedFunctions.length > 0) { + // --function specified: fetch only those function logs (no audit logs) + const entries = await fetchFunctionLogsAction(specifiedFunctions, options); + allEntries.push(...entries); + } else { + // No --function: fetch both audit logs and all project function logs + + // Fetch audit logs (unless --level=debug) + if (shouldFetchAuditLogs(options.level)) { + const result = await fetchAuditLogsAction(options); + allEntries.push(...result.entries); + pagination = result.pagination; + } + + // Fetch all project function logs + const functionNames = await getAllFunctionNames(); + if (functionNames.length > 0) { + const functionEntries = await fetchFunctionLogsAction( + functionNames, + options + ); + allEntries.push(...functionEntries); + } + + // Sort combined entries by time + const order = options.order?.toUpperCase() === "ASC" ? 1 : -1; + allEntries.sort((a, b) => order * a.time.localeCompare(b.time)); + } + + const limit = options.limit ? Number.parseInt(options.limit, 10) : undefined; + if (limit !== undefined && allEntries.length > limit) { + allEntries.length = limit; + } + + if (options.json) { + process.stdout.write(`${JSON.stringify(allEntries, null, 2)}\n`); + } else { + const auditCount = allEntries.filter((e) => e.source === "App").length; + const functionCount = allEntries.length - auditCount; + const counts: LogCounts = { + auditCount, + functionCount, + auditTotal: functionCount === 0 ? pagination?.total : undefined, + hasMore: functionCount === 0 ? pagination?.has_more : undefined, + }; + displayLogs(allEntries, counts); + } + + return {}; +} + +// ─── COMMAND ──────────────────────────────────────────────── + +export function getLogsCommand(context: CLIContext): Command { + return new Command("logs") + .description("Fetch logs for this app (app logs + all function logs)") + .option( + "--function ", + "Filter by function name(s), comma-separated. If provided, fetches only those function logs" + ) + .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 }, + 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/core/index.ts b/src/core/index.ts index 723c3e77..78381b29 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -3,6 +3,7 @@ export * from "./clients/index.js"; export * from "./config.js"; export * from "./consts.js"; export * from "./errors.js"; +export * from "./logs/index.js"; export * from "./project/index.js"; export * from "./resources/index.js"; export * from "./site/index.js"; diff --git a/src/core/logs/api.ts b/src/core/logs/api.ts new file mode 100644 index 00000000..b81f25ee --- /dev/null +++ b/src/core/logs/api.ts @@ -0,0 +1,109 @@ +/** + * Audit logs API functions. + */ + +import type { KyResponse } from "ky"; +import { base44Client } from "@/core/clients/index.js"; +import { ApiError, SchemaValidationError } from "@/core/errors.js"; +import { getAppConfig } from "@/core/project/index.js"; +import type { AuditLogFilters, AuditLogsResponse } from "./schema.js"; +import { AppInfoResponseSchema, AuditLogsResponseSchema } from "./schema.js"; + +/** + * Fetch the workspace (organization) ID for the current app. + * Required because audit logs are fetched at the workspace level. + */ +export async function getWorkspaceId(): Promise { + const { id: appId } = getAppConfig(); + + let response: KyResponse; + try { + // GET /api/apps/{app_id} returns app info including organization_id + response = await base44Client.get(`api/apps/${appId}`); + } catch (error) { + throw await ApiError.fromHttpError(error, "fetching app info"); + } + + const result = AppInfoResponseSchema.safeParse(await response.json()); + + if (!result.success) { + throw new SchemaValidationError( + "Invalid app info response from server", + result.error + ); + } + + return result.data.organization_id; +} + +/** + * Build the API request body from CLI filter options. + * Transforms camelCase options to snake_case for the API. + */ +function buildRequestBody( + appId: string, + filters: AuditLogFilters +): Record { + const body: Record = { + app_id: appId, + order: filters.order ?? "DESC", + limit: filters.limit ?? 50, + }; + + if (filters.status) { + body.status = filters.status; + } + if (filters.eventTypes && filters.eventTypes.length > 0) { + body.event_types = filters.eventTypes; + } + if (filters.userEmail) { + body.user_email = filters.userEmail; + } + if (filters.since) { + body.start_date = filters.since; + } + if (filters.until) { + body.end_date = filters.until; + } + if (filters.cursorTimestamp) { + body.cursor_timestamp = filters.cursorTimestamp; + } + if (filters.cursorUserEmail) { + body.cursor_user_email = filters.cursorUserEmail; + } + + return body; +} + +/** + * Fetch audit logs for the current app. + */ +export async function fetchAuditLogs( + filters: AuditLogFilters = {} +): Promise { + const { id: appId } = getAppConfig(); + const workspaceId = await getWorkspaceId(); + + let response: KyResponse; + try { + response = await base44Client.post( + `api/workspace/audit-logs/list?workspaceId=${workspaceId}`, + { + json: buildRequestBody(appId, filters), + } + ); + } catch (error) { + throw await ApiError.fromHttpError(error, "fetching audit logs"); + } + + const result = AuditLogsResponseSchema.safeParse(await response.json()); + + if (!result.success) { + throw new SchemaValidationError( + "Invalid audit logs response from server", + result.error + ); + } + + return result.data; +} diff --git a/src/core/logs/index.ts b/src/core/logs/index.ts new file mode 100644 index 00000000..94ea5aa4 --- /dev/null +++ b/src/core/logs/index.ts @@ -0,0 +1,7 @@ +export { fetchAuditLogs, getWorkspaceId } from "./api.js"; +export type { + AuditLogEvent, + AuditLogFilters, + AuditLogsResponse, + Pagination, +} from "./schema.js"; diff --git a/src/core/logs/schema.ts b/src/core/logs/schema.ts new file mode 100644 index 00000000..2a929b2c --- /dev/null +++ b/src/core/logs/schema.ts @@ -0,0 +1,74 @@ +import { z } from "zod"; + +/** + * Single audit log event from the API response. + */ +export const AuditLogEventSchema = z.looseObject({ + timestamp: z.string(), + user_email: z.string().nullable(), + workspace_id: z.string(), + app_id: z.string(), + ip: z.string().nullable(), + user_agent: z.string().nullable(), + event_type: z.string(), + status: z.enum(["success", "failure"]), + error_code: z.string().nullable(), + metadata: z.record(z.string(), z.unknown()).nullable(), +}); + +export type AuditLogEvent = z.infer; + +/** + * Pagination cursor for fetching the next page. + */ +export const PaginationCursorSchema = z.object({ + timestamp: z.string(), + user_email: z.string(), +}); + +/** + * Pagination info from the API response. + */ +export const PaginationSchema = z.object({ + total: z.number(), + limit: z.number(), + has_more: z.boolean(), + next_cursor: PaginationCursorSchema.nullable(), +}); + +export type Pagination = z.infer; + +/** + * Full audit logs API response. + */ +export const AuditLogsResponseSchema = z.object({ + events: z.array(AuditLogEventSchema), + pagination: PaginationSchema, +}); + +export type AuditLogsResponse = z.infer; + +/** + * App info response schema (for extracting workspace/organization ID). + */ +export const AppInfoResponseSchema = z.looseObject({ + organization_id: z.string(), +}); + +export type AppInfoResponse = z.infer; + +/** + * CLI filter options (camelCase for TypeScript). + * These are transformed to snake_case when building the API request. + */ +export interface AuditLogFilters { + status?: "success" | "failure"; + eventTypes?: string[]; + userEmail?: string; + since?: string; + until?: string; + limit?: number; + order?: "ASC" | "DESC"; + cursorTimestamp?: string; + cursorUserEmail?: string; +} diff --git a/src/core/resources/function/api.ts b/src/core/resources/function/api.ts index bf4edca0..495861cf 100644 --- a/src/core/resources/function/api.ts +++ b/src/core/resources/function/api.ts @@ -1,11 +1,17 @@ import type { KyResponse } from "ky"; +import { HTTPError } from "ky"; import { getAppClient } from "@/core/clients/index.js"; import { ApiError, 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"; function toDeployPayloadItem(fn: FunctionWithCode) { return { @@ -44,3 +50,63 @@ 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.limit !== undefined) { + params.set("limit", String(filters.limit)); + } + + 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 && error.response.status === 404) { + throw new ApiError(`Function "${functionName}" not found`, { + statusCode: 404, + cause: error, + hints: [{ message: "Check the function name and try again" }], + }); + } + throw await ApiError.fromHttpError(error, "fetching function logs"); + } + + 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 c12adb45..5501c9c0 100644 --- a/src/core/resources/function/schema.ts +++ b/src/core/resources/function/schema.ts @@ -48,3 +48,40 @@ 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; +} diff --git a/tests/cli/logs.spec.ts b/tests/cli/logs.spec.ts new file mode 100644 index 00000000..6248bd2b --- /dev/null +++ b/tests/cli/logs.spec.ts @@ -0,0 +1,325 @@ +import { describe, it } from "vitest"; +import { fixture, setupCLITests } from "./testkit/index.js"; + +const TEST_WORKSPACE_ID = "test-workspace-id"; + +describe("logs command", () => { + const t = setupCLITests(); + + it("fetches and displays audit logs successfully", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [ + { + timestamp: "2024-01-15T10:30:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "api.function.call", + status: "success", + ip: null, + user_agent: null, + error_code: null, + metadata: null, + }, + { + timestamp: "2024-01-15T10:29:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "app.entity.created", + status: "failure", + ip: null, + user_agent: null, + error_code: "VALIDATION_ERROR", + metadata: { entity_name: "Task" }, + }, + ], + pagination: { + total: 2, + limit: 50, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("Logs fetched successfully"); + t.expectResult(result).toContain("Showing 2 of 2 app events"); + t.expectResult(result).toContain("function unknown called"); + t.expectResult(result).toContain("failed to create entity Task"); + }); + + it("shows no logs message when empty", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [], + pagination: { + total: 0, + limit: 50, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("No logs found matching the filters."); + }); + + it("outputs unified JSON with --json flag", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [ + { + timestamp: "2024-01-15T10:30:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "api.function.call", + status: "success", + ip: null, + user_agent: null, + error_code: null, + metadata: null, + }, + ], + pagination: { + total: 1, + limit: 50, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run("logs", "--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("shows pagination hint when more results available", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [ + { + timestamp: "2024-01-15T10:30:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "api.function.call", + status: "success", + ip: null, + user_agent: null, + error_code: null, + metadata: null, + }, + ], + pagination: { + total: 100, + limit: 50, + has_more: true, + next_cursor: { + timestamp: "2024-01-15T10:29:00Z", + user_email: "user@example.com", + }, + }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toSucceed(); + t.expectResult(result).toContain("More results available"); + t.expectResult(result).toContain("--limit"); + }); + + it("fetches only 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('Logs for "my-function" fetched'); + 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("filters function logs by --level", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockFunctionLogs("my-function", [ + { + time: "2024-01-15T10:30:00.000Z", + level: "info", + message: "Info message", + }, + { + 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("fetches both audit and function logs when no --function specified", async () => { + await t.givenLoggedInWithProject(fixture("full-project")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [ + { + timestamp: "2024-01-15T10:30:00Z", + user_email: "user@example.com", + workspace_id: TEST_WORKSPACE_ID, + app_id: "test-app-id", + event_type: "app.entity.created", + status: "success", + ip: null, + user_agent: null, + error_code: null, + metadata: { entity_name: "Task", entity_id: "1" }, + }, + ], + pagination: { + total: 1, + limit: 50, + has_more: false, + next_cursor: null, + }, + }); + 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("Logs fetched successfully"); + t.expectResult(result).toContain("entity Task created"); + t.expectResult(result).toContain("Hello world"); + }); + + 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", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + t.api.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogsError({ + status: 500, + body: { error: "Server error" }, + }); + + const result = await t.run("logs"); + + t.expectResult(result).toFail(); + }); + + it("fails with invalid level option", async () => { + await t.givenLoggedInWithProject(fixture("basic")); + // --level is validated when fetching function logs; use --function so level is parsed + t.api.mockFunctionLogs("dummy", []); + + 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.mockAppInfo({ organization_id: TEST_WORKSPACE_ID }); + t.api.mockAuditLogs(TEST_WORKSPACE_ID, { + events: [], + pagination: { + total: 0, + limit: 10, + has_more: false, + next_cursor: null, + }, + }); + + const result = await t.run("logs", "--limit", "10", "--order", "ASC"); + + t.expectResult(result).toSucceed(); + }); +}); diff --git a/tests/cli/testkit/Base44APIMock.ts b/tests/cli/testkit/Base44APIMock.ts index c1e1d4ec..edefb0c7 100644 --- a/tests/cli/testkit/Base44APIMock.ts +++ b/tests/cli/testkit/Base44APIMock.ts @@ -57,6 +57,37 @@ export interface AgentsFetchResponse { total: number; } +export interface AppInfoResponse { + organization_id: string; + [key: string]: unknown; +} + +export interface AuditLogsResponse { + events: Array<{ + timestamp: string; + user_email: string | null; + workspace_id: string; + app_id: string; + event_type: string; + status: "success" | "failure"; + [key: string]: unknown; + }>; + pagination: { + total: number; + limit: number; + has_more: boolean; + next_cursor: { timestamp: string; user_email: string } | null; + }; +} + +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 +213,44 @@ export class Base44APIMock { return this; } + /** Mock GET /api/apps/{appId} - Get app info (for workspace ID) */ + mockAppInfo(response: AppInfoResponse): this { + this.handlers.push( + http.get(`${BASE_URL}/api/apps/${this.appId}`, () => + HttpResponse.json(response) + ) + ); + return this; + } + + /** Mock POST /api/workspace/audit-logs/list - Fetch audit logs */ + mockAuditLogs(workspaceId: string, response: AuditLogsResponse): this { + this.handlers.push( + http.post(`${BASE_URL}/api/workspace/audit-logs/list`, ({ request }) => { + const url = new URL(request.url); + if (url.searchParams.get("workspaceId") === workspaceId) { + return HttpResponse.json(response); + } + return HttpResponse.json( + { error: "Workspace not found" }, + { status: 404 } + ); + }) + ); + 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 +332,25 @@ export class Base44APIMock { ); } + /** Mock app info to return an error */ + mockAppInfoError(error: ErrorResponse): this { + return this.mockError("get", `/api/apps/${this.appId}`, error); + } + + /** Mock audit logs to return an error */ + mockAuditLogsError(error: ErrorResponse): this { + return this.mockError("post", "/api/workspace/audit-logs/list", error); + } + + /** 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);