Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions packages/cli/src/cli/commands/project/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,15 @@ export async function deployAction(
};
}

const { project, entities, functions, agents, connectors, authConfig } =
projectData;
const {
project,
entities,
functions,
realtimeHandlers,
agents,
connectors,
authConfig,
} = projectData;

// Build summary of what will be deployed
const summaryLines: string[] = [];
Expand All @@ -60,6 +67,11 @@ export async function deployAction(
` - ${functions.length} ${functions.length === 1 ? "function" : "functions"}`,
);
}
if (realtimeHandlers.length > 0) {
summaryLines.push(
` - ${realtimeHandlers.length} ${realtimeHandlers.length === 1 ? "realtime handler" : "realtime handlers"}`,
);
}
if (agents.length > 0) {
summaryLines.push(
` - ${agents.length} ${agents.length === 1 ? "agent" : "agents"}`,
Expand Down
121 changes: 121 additions & 0 deletions packages/cli/src/cli/commands/realtime/deploy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import type { Logger } from "@base44-cli/logger";
import type { Command } from "commander";
import { CLIExitError } from "@/cli/errors.js";
import type { CLIContext, RunCommandResult } from "@/cli/types.js";
import { Base44Command, theme } from "@/cli/utils/index.js";
import { InvalidInputError } from "@/core/errors.js";
import { readProjectConfig } from "@/core/index.js";
import {
deployRealtimeHandlersSequentially,
type SingleRealtimeHandlerDeployResult,
} from "@/core/resources/realtime-handler/deploy.js";
import type { RealtimeHandler } from "@/core/resources/realtime-handler/schema.js";

function parseNames(args: string[]): string[] {
return args
.flatMap((arg) => arg.split(","))
.map((n) => n.trim())
.filter(Boolean);
}

function resolveHandlersToDeploy(
names: string[],
allHandlers: RealtimeHandler[],
): RealtimeHandler[] {
if (names.length === 0) return allHandlers;

const notFound = names.filter((n) => !allHandlers.some((h) => h.name === n));
if (notFound.length > 0) {
throw new InvalidInputError(
`Realtime handler${notFound.length > 1 ? "s" : ""} not found in project: ${notFound.join(", ")}`,
);
}
return allHandlers.filter((h) => names.includes(h.name));
}

function formatDeployResult(
result: SingleRealtimeHandlerDeployResult,
log: Logger,
): void {
const label = result.name.padEnd(25);
if (result.status === "deployed") {
const timing = result.durationMs
? theme.styles.dim(` (${(result.durationMs / 1000).toFixed(1)}s)`)
: "";
log.success(`${label} deployed${timing}`);
} else if (result.status === "unchanged") {
log.success(`${label} unchanged`);
} else {
log.error(`${label} error: ${result.error}`);
}
}

function buildDeploySummary(
results: SingleRealtimeHandlerDeployResult[],
): string {
const deployed = results.filter((r) => r.status === "deployed").length;
const unchanged = results.filter((r) => r.status === "unchanged").length;
const failed = results.filter((r) => r.status === "error").length;

const parts: string[] = [];
if (deployed > 0) parts.push(`${deployed} deployed`);
if (unchanged > 0) parts.push(`${unchanged} unchanged`);
if (failed > 0) parts.push(`${failed} error${failed !== 1 ? "s" : ""}`);
return parts.join(", ") || "No realtime handlers deployed";
}

async function deployRealtimeAction(
{ log }: CLIContext,
names: string[],
): Promise<RunCommandResult> {
const { realtimeHandlers } = await readProjectConfig();
const toDeploy = resolveHandlersToDeploy(names, realtimeHandlers);

if (toDeploy.length === 0) {
return {
outroMessage:
"No realtime handlers found. Create handlers in the 'realtime' directory.",
};
}

log.info(
`Found ${toDeploy.length} ${toDeploy.length === 1 ? "realtime handler" : "realtime handlers"} to deploy`,
);

let completed = 0;
const total = toDeploy.length;

const results = await deployRealtimeHandlersSequentially(toDeploy, {
onStart: (startNames) => {
const label =
startNames.length === 1
? startNames[0]
: `${startNames.length} realtime handlers`;
log.step(
theme.styles.dim(`[${completed + 1}/${total}] Deploying ${label}...`),
);
},
onResult: (result) => {
completed++;
formatDeployResult(result, log);
},
});

const hasFailures = results.some((r) => r.status === "error");
if (hasFailures) {
log.message(buildDeploySummary(results));
throw new CLIExitError(1);
}

return { outroMessage: buildDeploySummary(results) };
}

export function getDeployCommand(): Command {
return new Base44Command("deploy")
.description("Deploy realtime handlers to Base44")
.argument("[names...]", "Handler names to deploy (deploys all if omitted)")
.action(async (ctx: CLIContext, rawNames: string[]) => {
const names = parseNames(rawNames);
return deployRealtimeAction(ctx, names);
});
}
10 changes: 10 additions & 0 deletions packages/cli/src/cli/commands/realtime/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Command } from "commander";
import { getDeployCommand } from "./deploy.js";
import { getNewCommand } from "./new.js";

export function getRealtimeCommand(): Command {
return new Command("realtime")
.description("Manage realtime handlers")
.addCommand(getNewCommand())
.addCommand(getDeployCommand());
}
62 changes: 62 additions & 0 deletions packages/cli/src/cli/commands/realtime/new.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { dirname, join } from "node:path";
import type { Command } from "commander";
import type { CLIContext, RunCommandResult } from "@/cli/types.js";
import { Base44Command } from "@/cli/utils/index.js";
import { InvalidInputError } from "@/core/errors.js";
import { readProjectConfig } from "@/core/index.js";
import { pathExists, writeFile } from "@/core/utils/fs.js";

function buildHandlerScaffold(handlerName: string): string {
return `import { RealtimeHandler, type Conn } from "@base44/sdk";

interface State {
// shared state broadcast to all clients
}

interface Message {
// messages sent from clients
}

export class ${handlerName} extends RealtimeHandler<State, Message> {
handleConnect(conn: Conn) {
console.log("Connected:", conn.userId);
}
handleMessage(conn: Conn, msg: Message) {
console.log("Message:", msg);
}
handleTick() {}
handleClose(conn: Conn) {}
}
`;
}

async function newRealtimeHandlerAction(
_ctx: CLIContext,
handlerName: string,
): Promise<RunCommandResult> {
const { project } = await readProjectConfig();
const realtimeDir = join(dirname(project.configPath), project.realtimeDir);
const handlerDir = join(realtimeDir, handlerName);

if (await pathExists(handlerDir)) {
throw new InvalidInputError(
`Realtime handler "${handlerName}" already exists at ${handlerDir}`,
);
}

const entryPath = join(handlerDir, "entry.ts");
await writeFile(entryPath, buildHandlerScaffold(handlerName));

return {
outroMessage: `Created realtime handler "${handlerName}" at ${entryPath}`,
};
}

export function getNewCommand(): Command {
return new Base44Command("new")
.description("Create a new realtime handler scaffold")
.argument("<HandlerName>", "Name of the realtime handler class")
.action(async (ctx: CLIContext, handlerName: string) => {
return newRealtimeHandlerAction(ctx, handlerName);
});
}
3 changes: 2 additions & 1 deletion packages/cli/src/cli/commands/types/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const TYPES_FILE_PATH = "base44/.types/types.d.ts";
async function generateTypesAction({
runTask,
}: CLIContext): Promise<RunCommandResult> {
const { entities, functions, agents, connectors, project } =
const { entities, functions, agents, connectors, realtimeHandlers, project } =
await readProjectConfig();

await runTask("Generating types", async () => {
Expand All @@ -19,6 +19,7 @@ async function generateTypesAction({
functions,
agents,
connectors,
realtimeHandlers,
});
});

Expand Down
4 changes: 4 additions & 0 deletions packages/cli/src/cli/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { getDeployCommand } from "@/cli/commands/project/deploy.js";
import { getLinkCommand } from "@/cli/commands/project/link.js";
import { getLogsCommand } from "@/cli/commands/project/logs.js";
import { getScaffoldCommand } from "@/cli/commands/project/scaffold.js";
import { getRealtimeCommand } from "@/cli/commands/realtime/index.js";
import { getSandboxCommand } from "@/cli/commands/sandbox/index.js";
import { getSecretsCommand } from "@/cli/commands/secrets/index.js";
import { getSiteCommand } from "@/cli/commands/site/index.js";
Expand Down Expand Up @@ -82,6 +83,9 @@ export function createProgram(context: CLIContext): Command {
// Register functions commands
program.addCommand(getFunctionsCommand());

// Register realtime commands
program.addCommand(getRealtimeCommand());

// Register secrets commands
program.addCommand(getSecretsCommand());

Expand Down
38 changes: 28 additions & 10 deletions packages/cli/src/core/project/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
type BackendFunction,
functionResource,
} from "@/core/resources/function/index.js";
import { realtimeHandlerResource } from "@/core/resources/realtime-handler/index.js";
import { readJsonFile } from "@/core/utils/fs.js";

type ProjectResources = Omit<ProjectData, "project">;
Expand Down Expand Up @@ -60,6 +61,7 @@ class ProjectConfigReader {
project: { ...project, root, configPath },
entities,
functions,
realtimeHandlers: localResources.realtimeHandlers,
agents: localResources.agents,
connectors: localResources.connectors,
authConfig: localResources.authConfig,
Expand Down Expand Up @@ -105,16 +107,30 @@ class ProjectConfigReader {
project: ProjectConfig,
): Promise<ProjectResources> {
const configDir = dirname(configPath);
const [entities, functions, agents, connectors, authConfig] =
await Promise.all([
entityResource.readAll(join(configDir, project.entitiesDir)),
functionResource.readAll(join(configDir, project.functionsDir)),
agentResource.readAll(join(configDir, project.agentsDir)),
connectorResource.readAll(join(configDir, project.connectorsDir)),
authConfigResource.readAll(join(configDir, project.authDir)),
]);

return { entities, functions, agents, connectors, authConfig };
const [
entities,
functions,
realtimeHandlers,
agents,
connectors,
authConfig,
] = await Promise.all([
entityResource.readAll(join(configDir, project.entitiesDir)),
functionResource.readAll(join(configDir, project.functionsDir)),
realtimeHandlerResource.readAll(join(configDir, project.realtimeDir)),
agentResource.readAll(join(configDir, project.agentsDir)),
connectorResource.readAll(join(configDir, project.connectorsDir)),
authConfigResource.readAll(join(configDir, project.authDir)),
]);

return {
entities,
functions,
realtimeHandlers,
agents,
connectors,
authConfig,
};
}

private assertPluginProjectDoesNotLoadPlugins(
Expand Down Expand Up @@ -184,6 +200,7 @@ class ProjectConfigReader {
return {
entities: markPluginEntities(resources.entities, namespace),
functions: namespacePluginFunctions(resources.functions, namespace),
realtimeHandlers: [],
agents: [],
connectors: [],
authConfig: [],
Expand Down Expand Up @@ -240,6 +257,7 @@ class ProjectConfigReader {
return {
entities,
functions,
realtimeHandlers: [],
agents: [],
connectors: [],
authConfig: [],
Expand Down
26 changes: 22 additions & 4 deletions packages/cli/src/core/project/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
deployFunctionsSequentially,
type SingleFunctionDeployResult,
} from "@/core/resources/function/deploy.js";
import { deployRealtimeHandlersSequentially } from "@/core/resources/realtime-handler/deploy.js";
import { deploySite } from "@/core/site/index.js";

/**
Expand All @@ -20,18 +21,27 @@ import { deploySite } from "@/core/site/index.js";
* @returns true if there are entities, functions, agents, connectors, or a configured site to deploy
*/
export function hasResourcesToDeploy(projectData: ProjectData): boolean {
const { project, entities, functions, agents, connectors, authConfig } =
projectData;
const {
project,
entities,
functions,
realtimeHandlers,
agents,
connectors,
authConfig,
} = projectData;
const hasSite = Boolean(project.site?.outputDirectory);
const hasEntities = entities.length > 0;
const hasFunctions = functions.length > 0;
const hasRealtimeHandlers = realtimeHandlers.length > 0;
const hasAgents = agents.length > 0;
const hasConnectors = connectors.length > 0;
const hasAuthConfig = authConfig.length > 0;

return (
hasEntities ||
hasFunctions ||
hasRealtimeHandlers ||
hasAgents ||
hasConnectors ||
hasAuthConfig ||
Expand Down Expand Up @@ -69,14 +79,22 @@ export async function deployAll(
projectData: ProjectData,
options?: DeployAllOptions,
): Promise<DeployAllResult> {
const { project, entities, functions, agents, connectors, authConfig } =
projectData;
const {
project,
entities,
functions,
realtimeHandlers,
agents,
connectors,
authConfig,
} = projectData;

await entityResource.push(entities);
await deployFunctionsSequentially(functions, {
onStart: options?.onFunctionStart,
onResult: options?.onFunctionResult,
});
await deployRealtimeHandlersSequentially(realtimeHandlers);
await agentResource.push(agents);
await authConfigResource.push(authConfig);
const { results: connectorResults } = await pushConnectors(connectors);
Expand Down
Loading
Loading