Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"AiGatewayConnection",
"ActorConnectOptions",
"AppPublicSettingsResponse",
"BrowserSession",
"BrowserSessionOptions",
"DeleteManyResult",
"DeleteResult",
"EntityAggregateResult",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
"AppPublicSettings",
"AppPublicSettingsResponse",
"AuthModule",
"BrowserModule",
"BrowserSession",
"BrowserSessionOptions",
"ConnectorApiRequest",
"ConnectorApiResponse",
"ConnectorApiResponsePhase",
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createEntitiesModule } from "./modules/entities.js";
import { createIntegrationsModule } from "./modules/integrations.js";
import { createAuthModule } from "./modules/auth.js";
import { createSsoModule } from "./modules/sso.js";
import { createBrowserModule } from "./modules/browser.js";
import {
createConnectorsModule,
createUserConnectorsModule,
Expand Down Expand Up @@ -293,6 +294,7 @@ export function createClient(config: CreateClientConfig): Base44Client {
}),
integrations: createIntegrationsModule(serviceRoleAxiosClient, appId),
sso: createSsoModule(serviceRoleAxiosClient, appId),
browser: createBrowserModule(serviceRoleAxiosClient),
connectors: createConnectorsModule(serviceRoleAxiosClient, appId),
functions: createFunctionsModule(serviceRoleFunctionsAxiosClient, appId, {
getAuthHeaders: () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/client.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { EntitiesModule } from "./modules/entities.types.js";
import type { IntegrationsModule } from "./modules/integrations.types.js";
import type { AuthModule } from "./modules/auth.types.js";
import type { SsoModule } from "./modules/sso.types.js";
import type { BrowserModule } from "./modules/browser.types.js";
import type {
PaymentsModule,
ServiceRolePaymentsModule,
Expand Down Expand Up @@ -239,6 +240,8 @@ export interface Base44Client {
aiGateway: AiGatewayModule;
/** {@link AppLogsModule | App logs module} with elevated permissions. */
appLogs: AppLogsModule;
/** {@link BrowserModule | Browser module} for remote browser sessions. */
browser: BrowserModule;
/** {@link ConnectorsModule | Connectors module} for OAuth token retrieval. */
connectors: ConnectorsModule;
/** {@link EntitiesModule | Entities module} with elevated permissions. */
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,12 @@ export type {
SubscriptionResult,
} from "./modules/payments.types.js";

export type {
BrowserModule,
BrowserSession,
BrowserSessionOptions,
} from "./modules/browser.types.js";

export { Actor, type Conn } from "./actor.js";

export type {
Expand Down
59 changes: 59 additions & 0 deletions packages/sdk/src/modules/browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { AxiosInstance } from "axios";
import {
BrowserModule,
BrowserSession,
BrowserSessionOptions,
} from "./browser.types.js";

interface BrowserSessionResponse {
session_id: string;
connection_url: string;
connection_scope: BrowserSession["connectionScope"];
connection_expires_at?: string;
session_expires_at?: string;
}

/**
* Creates the Browser module for the Base44 SDK.
*
* @param axios - Axios instance (should be service role client)
* @returns Browser module with methods to create and end remote browser sessions
* @internal
*/
export function createBrowserModule(axios: AxiosInstance): BrowserModule {
const endSession = async (sessionId: string): Promise<void> => {
if (!sessionId || typeof sessionId !== "string") {
throw new Error("Session ID is required and must be a string");
}

await axios.delete(`/v1/browser-sessions/${encodeURIComponent(sessionId)}`);
};

return {
async getSession(
options: BrowserSessionOptions = {}
): Promise<BrowserSession> {
// The app is derived from the service token, so the route isn't app-scoped.
const response = await axios.post<BrowserSessionResponse>(
"/v1/browser-sessions",
{ capture_debug_artifacts: options.captureDebugArtifacts ?? true }
);

const data = response as unknown as BrowserSessionResponse;
return {
sessionId: data.session_id,
connectionUrl: data.connection_url,
connectionScope: data.connection_scope,
...(data.connection_expires_at && {
connectionExpiresAt: data.connection_expires_at,
}),
...(data.session_expires_at && {
sessionExpiresAt: data.session_expires_at,
}),
end: () => endSession(data.session_id),
};
},

endSession,
};
}
119 changes: 119 additions & 0 deletions packages/sdk/src/modules/browser.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/**
* Options for {@linkcode BrowserModule.getSession | getSession()}.
*/
export interface BrowserSessionOptions {
/**
* Whether to capture browser recordings and diagnostic logs for the session.
*
* Captured artifacts stay with the remote browser provider and can't be retrieved through the SDK. Defaults to `true`.
*/
captureDebugArtifacts?: boolean;
}

/**
* A remote browser session returned by {@linkcode BrowserModule.getSession | getSession()}.
*/
export interface BrowserSession {
/**
* Opaque session identifier issued to your app.
*
* Pass it unchanged to {@linkcode BrowserModule.endSession | endSession()} to end the session from a different request.
*/
sessionId: string;
/**
* Signed WebSocket URL for connecting to the browser over the Chrome DevTools Protocol (CDP).
*
* Treat the complete URL as a credential. Don't log it or send it to the frontend.
*/
connectionUrl: string;
/**
* Scope of the CDP connection.
*
* - `'browser'`: The socket controls the whole browser.
* - `'page'`: The socket controls a single page.
*/
connectionScope: "browser" | "page";
/** ISO 8601 timestamp when the connection URL expires. Omitted when the provider doesn't expose it. */
connectionExpiresAt?: string;
/** ISO 8601 timestamp when the browser session expires. Omitted when the provider doesn't expose it. */
sessionExpiresAt?: string;
/**
* Ends the session. Equivalent to calling {@linkcode BrowserModule.endSession | endSession()} with this session's ID.
*/
end: () => Promise<void>;
}

/**
* Browser module for running browser automation from your backend.
*
* This module creates remote browser sessions that you can control with a CDP client library such as Playwright or Puppeteer. Base44 doesn't store browser state, so each session is independent. End each session when you're done with it. Otherwise it keeps running until the remote browser provider times it out.
*
* This module is only available to use with a client in service role authentication mode, which means it can only be used in backend environments.
*/
export interface BrowserModule {
/**
* Creates a new remote browser session and returns its connection details.
*
* Each call creates a fresh session. Calls aren't retried automatically, and repeating a failed call doesn't resume a previous session. Session creation is rate limited per app.
*
* @param options - Optional session settings.
* @returns Promise resolving to the new browser session.
*
* @example
* ```typescript
* // Open a page in a remote browser with Playwright
* import { createClientFromRequest } from 'npm:@base44/sdk';
* import { chromium } from 'npm:playwright-core';
*
* Deno.serve(async (req) => {
* const base44 = createClientFromRequest(req);
* const session = await base44.asServiceRole.browser.getSession();
*
* try {
* const browser = await chromium.connectOverCDP(session.connectionUrl);
* const page = browser.contexts()[0].pages()[0] ?? (await browser.newPage());
* await page.goto('https://example.com');
* const title = await page.title();
* await browser.close();
*
* return Response.json({ title });
* } finally {
* await session.end();
* }
* });
* ```
*
* @example
* ```typescript
* // Turn off recordings and diagnostic logs
* const session = await base44.asServiceRole.browser.getSession({
* captureDebugArtifacts: false,
* });
* ```
*/
getSession(options?: BrowserSessionOptions): Promise<BrowserSession>;

/**
* Ends a browser session created by your app.
*
* Use this when the session was created in a different request. Otherwise call `end()` on the session returned by {@linkcode getSession | getSession()}. Ending a session that has already ended succeeds, so it's safe to call more than once. The call fails with the `browser_session_not_found` error code if the ID wasn't issued to your app.
*
* @param sessionId - The `sessionId` returned by {@linkcode getSession | getSession()}, unchanged.
* @returns Promise that resolves when the session has ended.
*
* @example
* ```typescript
* // End a session whose ID was saved by an earlier request
* import { createClientFromRequest } from 'npm:@base44/sdk';
*
* Deno.serve(async (req) => {
* const base44 = createClientFromRequest(req);
* const { sessionId } = await req.json();
* await base44.asServiceRole.browser.endSession(sessionId);
*
* return new Response(null, { status: 204 });
* });
* ```
*/
endSession(sessionId: string): Promise<void>;
}
Loading
Loading