@base44/sdk 0.8.18 → 0.8.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,22 +1,42 @@
1
1
  # Base44 JavaScript SDK
2
2
 
3
- The Base44 SDK provides a JavaScript interface for building apps on the Base44 platform. When Base44 generates your app, the generated code uses the SDK to authenticate users, manage your app's data, interact with AI agents, and more. You can then use the same SDK to modify and extend your app.
3
+ The Base44 SDK provides a JavaScript interface for building apps on the Base44 platform.
4
+
5
+ You can use it in two ways:
6
+
7
+ - **Inside Base44 apps**: When Base44 generates your app, the SDK is already set up and ready to use.
8
+ - **External apps**: Use the SDK to build your own frontend or backend that uses Base44 as a backend service.
9
+
10
+ ## Installation
11
+
12
+ **Inside Base44 apps**: The SDK is already available. No installation needed.
13
+
14
+ **External apps**: Install the SDK via npm:
15
+
16
+ ```bash
17
+ npm install @base44/sdk
18
+ ```
4
19
 
5
20
  ## Modules
6
21
 
7
22
  The SDK provides access to Base44's functionality through the following modules:
8
23
 
9
- - **[`agents`](https://docs.base44.com/sdk-docs/interfaces/agents)**: Interact with AI agents and manage conversations.
10
- - **[`app-logs`](https://docs.base44.com/sdk-docs/interfaces/app-logs)**: Access and query app logs.
11
- - **[`auth`](https://docs.base44.com/sdk-docs/interfaces/auth)**: Manage user authentication, registration, and session handling.
12
- - **[`connectors`](https://docs.base44.com/sdk-docs/interfaces/connectors)**: Manage OAuth connections and access tokens for third-party services.
13
- - **[`entities`](https://docs.base44.com/sdk-docs/interfaces/entities)**: Work with your app's data entities using CRUD operations.
14
- - **[`functions`](https://docs.base44.com/sdk-docs/interfaces/functions)**: Execute backend functions.
15
- - **[`integrations`](https://docs.base44.com/sdk-docs/type-aliases/integrations)**: Pre-built server-side functions for external services.
24
+ - **[`agents`](https://docs.base44.com/developers/references/sdk/docs/interfaces/agents)**: Interact with AI agents and manage conversations.
25
+ - **[`analytics`](https://docs.base44.com/developers/references/sdk/docs/interfaces/analytics)**: Track custom events in your app.
26
+ - **[`app-logs`](https://docs.base44.com/developers/references/sdk/docs/interfaces/app-logs)**: Access and query app logs.
27
+ - **[`auth`](https://docs.base44.com/developers/references/sdk/docs/interfaces/auth)**: Manage user authentication, registration, and session handling.
28
+ - **[`connectors`](https://docs.base44.com/developers/references/sdk/docs/interfaces/connectors)**: Manage OAuth connections and access tokens for third-party services.
29
+ - **[`entities`](https://docs.base44.com/developers/references/sdk/docs/interfaces/entities)**: Work with your app's data entities using CRUD operations.
30
+ - **[`functions`](https://docs.base44.com/developers/references/sdk/docs/interfaces/functions)**: Execute backend functions.
31
+ - **[`integrations`](https://docs.base44.com/developers/references/sdk/docs/type-aliases/integrations)**: Access pre-built and third-party integrations.
32
+
33
+ ## Quickstarts
16
34
 
17
- ## Example
35
+ How you get started depends on whether you're working inside a Base44-generated app or building your own.
18
36
 
19
- Here's a quick look at working with data in the SDK, using the `entities` module to create, update, and list records. In this example, we're working with a custom `Task` entity:
37
+ ### Inside Base44 apps
38
+
39
+ In Base44-generated apps, the client is pre-configured. Just import and use it:
20
40
 
21
41
  ```typescript
22
42
  import { base44 } from "@/api/base44Client";
@@ -37,14 +57,63 @@ await base44.entities.Task.update(newTask.id, {
37
57
  const tasks = await base44.entities.Task.list();
38
58
  ```
39
59
 
60
+ ### External apps
61
+
62
+ When using Base44 as a backend for your own app, install the SDK and create the client yourself:
63
+
64
+ ```typescript
65
+ import { createClient } from "@base44/sdk";
66
+
67
+ // Create a client for your Base44 app
68
+ const base44 = createClient({
69
+ appId: "your-app-id", // Find this in the Base44 editor URL
70
+ });
71
+
72
+ // Read public data
73
+ const products = await base44.entities.Products.list();
74
+
75
+ // Authenticate a user (token is automatically set)
76
+ await base44.auth.loginViaEmailPassword("user@example.com", "password");
77
+
78
+ // Access user's data
79
+ const userOrders = await base44.entities.Orders.list();
80
+ ```
81
+
82
+ ### Service role
83
+
84
+ By default, the client operates with user-level permissions, limiting access to what the current user can see and do. The service role provides elevated permissions for backend operations and is only available in Base44-hosted backend functions. External backends can't use service role permissions.
85
+
86
+ ```typescript
87
+ import { createClientFromRequest } from "npm:@base44/sdk";
88
+
89
+ Deno.serve(async (req) => {
90
+ const base44 = createClientFromRequest(req);
91
+
92
+ // Access all data with admin-level permissions
93
+ const allOrders = await base44.asServiceRole.entities.Orders.list();
94
+
95
+ return Response.json({ orders: allOrders });
96
+ });
97
+ ```
98
+
40
99
  ## Learn more
41
100
 
42
- For complete documentation, guides, and API reference, visit the **[Base44 SDK Documentation](https://docs.base44.com/sdk-getting-started/overview)**.
101
+ The best way to get started with the JavaScript SDK is to have Base44 build an app for you. Once you have an app, you can explore the generated code and experiment with the SDK to see how it works in practice. You can also ask Base44 to demonstrate specific features of the SDK.
102
+
103
+ For a deeper understanding, check out these guides:
104
+
105
+ 1. [Base44 client](https://docs.base44.com/developers/references/sdk/getting-started/client) - Work with the client in frontend, backend, and external app contexts.
106
+ 2. [Work with data](https://docs.base44.com/developers/references/sdk/getting-started/work-with-data) - Create, read, update, and delete data.
107
+ 3. [Common SDK patterns](https://docs.base44.com/developers/references/sdk/getting-started/work-with-sdk) - Authentication, integrations, functions, and error handling.
108
+
109
+ For the complete documentation and API reference, visit the **[Base44 Developer Docs](https://docs.base44.com/developers/home)**.
43
110
 
44
111
  ## Development
45
112
 
46
113
  ### Build the SDK
47
114
 
115
+ Build the SDK from source:
116
+
48
117
  ```bash
49
118
  npm install
50
119
  npm run build
@@ -52,6 +121,8 @@ npm run build
52
121
 
53
122
  ### Run tests
54
123
 
124
+ Run the test suite:
125
+
55
126
  ```bash
56
127
  # Run all tests
57
128
  npm test
@@ -64,6 +135,7 @@ npm run test:coverage
64
135
  ```
65
136
 
66
137
  For E2E tests, create a `tests/.env` file with:
138
+
67
139
  ```
68
140
  BASE44_APP_ID=your_app_id
69
141
  BASE44_AUTH_TOKEN=your_auth_token
package/dist/client.d.ts CHANGED
@@ -5,12 +5,14 @@ export type { Base44Client, CreateClientConfig, CreateClientOptions };
5
5
  *
6
6
  * This is the main entry point for the Base44 SDK. It creates a client that provides access to the SDK's modules, such as {@linkcode EntitiesModule | entities}, {@linkcode AuthModule | auth}, and {@linkcode FunctionsModule | functions}.
7
7
  *
8
- * Typically, you don't need to call this function because Base44 creates the client for you. You can then import and use the client to make API calls. The client takes care of managing authentication for you.
8
+ * How you get a client depends on your context:
9
+ * - **Inside a Base44 app:** The client is automatically created and configured for you. Import it from `@/api/base44Client`.
10
+ * - **External app using Base44 as a backend:** Call `createClient()` directly in your code to create and configure the client.
9
11
  *
10
12
  * The client supports three authentication modes:
11
- * - **Anonymous**: Access modules anonymously without authentication using `base44.moduleName`. Operations are scoped to public data and permissions.
12
- * - **User authentication**: Access modules with user-level permissions using `base44.moduleName`. Operations are scoped to the authenticated user's data and permissions.
13
- * - **Service role authentication**: Access modules with elevated permissions using `base44.asServiceRole.moduleName`. Operations can access any data available to the app's admin. Can only be used in the backend. Typically, you create a client with service role authentication using the {@linkcode createClientFromRequest | createClientFromRequest()} function in your backend functions.
13
+ * - **Anonymous**: Access modules without authentication using `base44.moduleName`. Operations are scoped to public data and permissions.
14
+ * - **User authentication**: Access modules with user-level permissions using `base44.moduleName`. Operations are scoped to the authenticated user's data and permissions. Use `base44.auth.loginViaEmailPassword()` or other auth methods to get a token.
15
+ * - **Service role authentication**: Access modules with elevated permissions using `base44.asServiceRole.moduleName`. Operations can access any data available to the app's admin. Only available in Base44-hosted backend functions. Create a client with service role authentication using {@linkcode createClientFromRequest | createClientFromRequest()}.
14
16
  *
15
17
  * For example, when using the {@linkcode EntitiesModule | entities} module:
16
18
  * - **Anonymous**: Can only read public data.
@@ -39,7 +41,9 @@ export declare function createClient(config: CreateClientConfig): Base44Client;
39
41
  /**
40
42
  * Creates a Base44 client from an HTTP request.
41
43
  *
42
- * The client is created by automatically extracting authentication tokens from a request to a backend function. Base44 inserts the necessary headers when forwarding requests to backend functions.
44
+ * This function is designed for use in Base44-hosted backend functions. For frontends and external backends, use {@linkcode createClient | createClient()} instead.
45
+ *
46
+ * When used in a Base44-hosted backend function, `createClientFromRequest()` automatically extracts authentication tokens from the request headers that Base44 injects when forwarding requests. The returned client includes service role access using `base44.asServiceRole`, which provides admin-level permissions.
43
47
  *
44
48
  * To learn more about the Base44 client, see {@linkcode createClient | createClient()}.
45
49
  *
package/dist/client.js CHANGED
@@ -16,12 +16,14 @@ import { createAnalyticsModule } from "./modules/analytics.js";
16
16
  *
17
17
  * This is the main entry point for the Base44 SDK. It creates a client that provides access to the SDK's modules, such as {@linkcode EntitiesModule | entities}, {@linkcode AuthModule | auth}, and {@linkcode FunctionsModule | functions}.
18
18
  *
19
- * Typically, you don't need to call this function because Base44 creates the client for you. You can then import and use the client to make API calls. The client takes care of managing authentication for you.
19
+ * How you get a client depends on your context:
20
+ * - **Inside a Base44 app:** The client is automatically created and configured for you. Import it from `@/api/base44Client`.
21
+ * - **External app using Base44 as a backend:** Call `createClient()` directly in your code to create and configure the client.
20
22
  *
21
23
  * The client supports three authentication modes:
22
- * - **Anonymous**: Access modules anonymously without authentication using `base44.moduleName`. Operations are scoped to public data and permissions.
23
- * - **User authentication**: Access modules with user-level permissions using `base44.moduleName`. Operations are scoped to the authenticated user's data and permissions.
24
- * - **Service role authentication**: Access modules with elevated permissions using `base44.asServiceRole.moduleName`. Operations can access any data available to the app's admin. Can only be used in the backend. Typically, you create a client with service role authentication using the {@linkcode createClientFromRequest | createClientFromRequest()} function in your backend functions.
24
+ * - **Anonymous**: Access modules without authentication using `base44.moduleName`. Operations are scoped to public data and permissions.
25
+ * - **User authentication**: Access modules with user-level permissions using `base44.moduleName`. Operations are scoped to the authenticated user's data and permissions. Use `base44.auth.loginViaEmailPassword()` or other auth methods to get a token.
26
+ * - **Service role authentication**: Access modules with elevated permissions using `base44.asServiceRole.moduleName`. Operations can access any data available to the app's admin. Only available in Base44-hosted backend functions. Create a client with service role authentication using {@linkcode createClientFromRequest | createClientFromRequest()}.
25
27
  *
26
28
  * For example, when using the {@linkcode EntitiesModule | entities} module:
27
29
  * - **Anonymous**: Can only read public data.
@@ -48,6 +50,8 @@ import { createAnalyticsModule } from "./modules/analytics.js";
48
50
  */
49
51
  export function createClient(config) {
50
52
  const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, } = config;
53
+ // Normalize appBaseUrl to always be a string (empty if not provided or invalid)
54
+ const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";
51
55
  const socketConfig = {
52
56
  serverUrl,
53
57
  mountPath: "/ws-user-apps/socket.io/",
@@ -100,7 +104,7 @@ export function createClient(config) {
100
104
  interceptResponses: false,
101
105
  });
102
106
  const userAuthModule = createAuthModule(axiosClient, functionsAxiosClient, appId, {
103
- appBaseUrl,
107
+ appBaseUrl: normalizedAppBaseUrl,
104
108
  serverUrl,
105
109
  });
106
110
  const userModules = {
@@ -224,7 +228,7 @@ export function createClient(config) {
224
228
  /**
225
229
  * Provides access to service role modules.
226
230
  *
227
- * Service role authentication provides elevated permissions for server-side operations. Unlike user authentication, which is scoped to a specific user's permissions, service role authentication has access to the data and operations available to the app's admin.
231
+ * Service role authentication provides elevated permissions for backend operations. Unlike user authentication, which is scoped to a specific user's permissions, service role authentication has access to the data and operations available to the app's admin.
228
232
  *
229
233
  * @throws {Error} When accessed without providing a serviceToken during client creation.
230
234
  *
@@ -251,7 +255,9 @@ export function createClient(config) {
251
255
  /**
252
256
  * Creates a Base44 client from an HTTP request.
253
257
  *
254
- * The client is created by automatically extracting authentication tokens from a request to a backend function. Base44 inserts the necessary headers when forwarding requests to backend functions.
258
+ * This function is designed for use in Base44-hosted backend functions. For frontends and external backends, use {@linkcode createClient | createClient()} instead.
259
+ *
260
+ * When used in a Base44-hosted backend function, `createClientFromRequest()` automatically extracts authentication tokens from the request headers that Base44 injects when forwarding requests. The returned client includes service role access using `base44.asServiceRole`, which provides admin-level permissions.
255
261
  *
256
262
  * To learn more about the Base44 client, see {@linkcode createClient | createClient()}.
257
263
  *
@@ -39,10 +39,13 @@ export interface CreateClientConfig {
39
39
  appId: string;
40
40
  /**
41
41
  * User authentication token. Used to authenticate as a specific user.
42
+ *
43
+ * Inside Base44 apps, the token is managed automatically. For external apps, use auth methods like {@linkcode AuthModule.loginViaEmailPassword | loginViaEmailPassword()} which set the token automatically.
42
44
  */
43
45
  token?: string;
44
46
  /**
45
- * Service role authentication token. Use this in the backend when you need elevated permissions to access data available to the app's admin or perform admin operations. This token should be kept secret and never exposed in the app's frontend. Typically, you get this token from a request to a backend function using {@linkcode createClientFromRequest | createClientFromRequest()}.
47
+ * Service role authentication token. Provides elevated permissions to access data available to the app's admin. Only available in Base44-hosted backend functions. Automatically added to client's created using {@linkcode createClientFromRequest | createClientFromRequest()}.
48
+ * @internal
46
49
  */
47
50
  serviceToken?: string;
48
51
  /**
@@ -71,20 +74,20 @@ export interface CreateClientConfig {
71
74
  * Provides access to all SDK modules for interacting with the app.
72
75
  */
73
76
  export interface Base44Client {
74
- /** {@link EntitiesModule | Entities module} for CRUD operations on your data models. */
75
- entities: EntitiesModule;
76
- /** {@link IntegrationsModule | Integrations module} for calling pre-built integration endpoints. */
77
- integrations: IntegrationsModule;
78
- /** {@link AuthModule | Auth module} for user authentication and management. */
79
- auth: AuthModule;
80
- /** {@link FunctionsModule | Functions module} for invoking custom backend functions. */
81
- functions: FunctionsModule;
82
77
  /** {@link AgentsModule | Agents module} for managing AI agent conversations. */
83
78
  agents: AgentsModule;
79
+ /** {@link AnalyticsModule | Analytics module} for tracking custom events in your app. */
80
+ analytics: AnalyticsModule;
84
81
  /** {@link AppLogsModule | App logs module} for tracking app usage. */
85
82
  appLogs: AppLogsModule;
86
- /** {@link AnalyticsModule | Analytics module} for tracking app usage. */
87
- analytics: AnalyticsModule;
83
+ /** {@link AuthModule | Auth module} for user authentication and management. */
84
+ auth: AuthModule;
85
+ /** {@link EntitiesModule | Entities module} for CRUD operations on your data models. */
86
+ entities: EntitiesModule;
87
+ /** {@link FunctionsModule | Functions module} for invoking custom backend functions. */
88
+ functions: FunctionsModule;
89
+ /** {@link IntegrationsModule | Integrations module} for calling pre-built integration endpoints. */
90
+ integrations: IntegrationsModule;
88
91
  /** Cleanup function to disconnect WebSocket connections. Call when you're done with the client. */
89
92
  cleanup: () => void;
90
93
  /**
@@ -112,22 +115,22 @@ export interface Base44Client {
112
115
  * @throws {Error} When accessed without providing a serviceToken during client creation
113
116
  */
114
117
  readonly asServiceRole: {
118
+ /** {@link AgentsModule | Agents module} with elevated permissions. */
119
+ agents: AgentsModule;
120
+ /** {@link AppLogsModule | App logs module} with elevated permissions. */
121
+ appLogs: AppLogsModule;
122
+ /** {@link ConnectorsModule | Connectors module} for OAuth token retrieval. */
123
+ connectors: ConnectorsModule;
115
124
  /** {@link EntitiesModule | Entities module} with elevated permissions. */
116
125
  entities: EntitiesModule;
126
+ /** {@link FunctionsModule | Functions module} with elevated permissions. */
127
+ functions: FunctionsModule;
117
128
  /** {@link IntegrationsModule | Integrations module} with elevated permissions. */
118
129
  integrations: IntegrationsModule;
119
130
  /** {@link SsoModule | SSO module} for generating SSO tokens.
120
131
  * @internal
121
132
  */
122
133
  sso: SsoModule;
123
- /** {@link ConnectorsModule | Connectors module} for OAuth token retrieval. */
124
- connectors: ConnectorsModule;
125
- /** {@link FunctionsModule | Functions module} with elevated permissions. */
126
- functions: FunctionsModule;
127
- /** {@link AgentsModule | Agents module} with elevated permissions. */
128
- agents: AgentsModule;
129
- /** {@link AppLogsModule | App logs module} with elevated permissions. */
130
- appLogs: AppLogsModule;
131
134
  /** Cleanup function to disconnect WebSocket connections. */
132
135
  cleanup: () => void;
133
136
  };
package/dist/index.d.ts CHANGED
@@ -4,11 +4,11 @@ import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl } from
4
4
  export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
5
5
  export type { Base44Client, CreateClientConfig, CreateClientOptions, Base44ErrorJSON, };
6
6
  export * from "./types.js";
7
- export type { EntitiesModule, EntityHandler, RealtimeEventType, RealtimeEvent, RealtimeCallback, Subscription, } from "./modules/entities.types.js";
7
+ export type { EntitiesModule, EntityHandler, EntityRecord, EntityTypeRegistry, RealtimeEventType, RealtimeEvent, RealtimeCallback, } from "./modules/entities.types.js";
8
8
  export type { AuthModule, LoginResponse, RegisterParams, VerifyOtpParams, ChangePasswordParams, ResetPasswordParams, User, } from "./modules/auth.types.js";
9
9
  export type { IntegrationsModule, IntegrationPackage, IntegrationEndpointFunction, CoreIntegrations, InvokeLLMParams, GenerateImageParams, GenerateImageResult, UploadFileParams, UploadFileResult, SendEmailParams, SendEmailResult, ExtractDataFromUploadedFileParams, ExtractDataFromUploadedFileResult, UploadPrivateFileParams, UploadPrivateFileResult, CreateFileSignedUrlParams, CreateFileSignedUrlResult, } from "./modules/integrations.types.js";
10
- export type { FunctionsModule } from "./modules/functions.types.js";
11
- export type { AgentsModule, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
10
+ export type { FunctionsModule, FunctionNameRegistry, } from "./modules/functions.types.js";
11
+ export type { AgentsModule, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
12
12
  export type { AppLogsModule } from "./modules/app-logs.types.js";
13
13
  export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
14
14
  export type { ConnectorsModule } from "./modules/connectors.types.js";
@@ -1,6 +1,16 @@
1
1
  import { AxiosInstance } from "axios";
2
2
  import { RoomsSocket } from "../utils/socket-utils.js";
3
3
  import { ModelFilterParams } from "../types.js";
4
+ /**
5
+ * Registry of agent names.
6
+ * Augment this interface to enable autocomplete for agent names.
7
+ */
8
+ export interface AgentNameRegistry {
9
+ }
10
+ /**
11
+ * Agent name type - uses registry keys if augmented, otherwise string.
12
+ */
13
+ export type AgentName = keyof AgentNameRegistry extends never ? string : keyof AgentNameRegistry;
4
14
  /**
5
15
  * Reasoning information for an agent message.
6
16
  *
@@ -72,7 +82,7 @@ export interface AgentMessageMetadata {
72
82
  export interface AgentConversation {
73
83
  /** Unique identifier for the conversation. */
74
84
  id: string;
75
- /** Application ID. */
85
+ /** App ID. */
76
86
  app_id: string;
77
87
  /** Name of the agent in this conversation. */
78
88
  agent_name: string;
@@ -127,7 +137,7 @@ export interface AgentMessage {
127
137
  */
128
138
  export interface CreateConversationParams {
129
139
  /** The name of the agent to create a conversation with. */
130
- agent_name: string;
140
+ agent_name: AgentName;
131
141
  /** Optional metadata to attach to the conversation. */
132
142
  metadata?: Record<string, any>;
133
143
  }
@@ -138,9 +148,9 @@ export interface CreateConversationParams {
138
148
  export interface AgentsModuleConfig {
139
149
  /** Axios instance for HTTP requests */
140
150
  axios: AxiosInstance;
141
- /** Function to get WebSocket instance for real-time updates (lazy initialization) */
151
+ /** Function to get WebSocket instance for realtime updates (lazy initialization) */
142
152
  getSocket: () => ReturnType<typeof RoomsSocket>;
143
- /** Application ID */
153
+ /** App ID */
144
154
  appId: string;
145
155
  /** Server URL */
146
156
  serverUrl?: string;
@@ -151,7 +161,7 @@ export interface AgentsModuleConfig {
151
161
  * Agents module for managing AI agent conversations.
152
162
  *
153
163
  * This module provides methods to create and manage conversations with AI agents,
154
- * send messages, and subscribe to real-time updates. Conversations can be used
164
+ * send messages, and subscribe to realtime updates. Conversations can be used
155
165
  * for chat interfaces, support systems, or any interactive AI app.
156
166
  *
157
167
  * The agents module enables you to:
@@ -159,7 +169,7 @@ export interface AgentsModuleConfig {
159
169
  * - **Create conversations** with agents defined in the app.
160
170
  * - **Send messages** from users to agents and receive AI-generated responses.
161
171
  * - **Retrieve conversations** individually or as filtered lists with sorting and pagination.
162
- * - **Subscribe to real-time updates** using WebSocket connections to receive instant notifications when new messages arrive.
172
+ * - **Subscribe to realtime updates** using WebSocket connections to receive instant notifications when new messages arrive.
163
173
  * - **Attach metadata** to conversations for tracking context, categories, priorities, or linking to external systems.
164
174
  * - **Generate WhatsApp connection URLs** for users to interact with agents through WhatsApp.
165
175
  *
@@ -171,7 +181,7 @@ export interface AgentsModuleConfig {
171
181
  *
172
182
  * This module is available to use with a client in all authentication modes:
173
183
  *
174
- * - **Anonymous or User authentication** (`base44.agents`): Access is scoped to the current user's permissions. Anonymous users can create conversations but can't retrieve them later, while authenticated users can access conversations they created.
184
+ * - **Anonymous or User authentication** (`base44.agents`): Access is scoped to the current user's permissions. Users must be authenticated to create and access conversations.
175
185
  * - **Service role authentication** (`base44.asServiceRole.agents`): Operations have elevated admin-level permissions. Can access all conversations that the app's admin role has access to.
176
186
  *
177
187
  */
@@ -200,6 +210,8 @@ export interface AgentsModule {
200
210
  * Retrieves a single conversation using its unique identifier. To retrieve
201
211
  * all conversations, use {@linkcode getConversations | getConversations()} To filter, sort, or paginate conversations, use {@linkcode listConversations | listConversations()}.
202
212
  *
213
+ * This function returns the complete stored conversation including full tool call results, even for large responses.
214
+ *
203
215
  * @param conversationId - The unique identifier of the conversation.
204
216
  * @returns Promise resolving to the conversation, or undefined if not found.
205
217
  *
@@ -275,7 +287,7 @@ export interface AgentsModule {
275
287
  * Adds a message to a conversation.
276
288
  *
277
289
  * Sends a message to the agent and updates the conversation. This method
278
- * also updates the real-time socket to notify any subscribers.
290
+ * also updates the realtime socket to notify any subscribers.
279
291
  *
280
292
  * @param conversation - The conversation to add the message to.
281
293
  * @param message - The message to add.
@@ -293,19 +305,29 @@ export interface AgentsModule {
293
305
  */
294
306
  addMessage(conversation: AgentConversation, message: Partial<AgentMessage>): Promise<AgentMessage>;
295
307
  /**
296
- * Subscribes to real-time updates for a conversation.
308
+ * Subscribes to realtime updates for a conversation.
297
309
  *
298
310
  * Establishes a WebSocket connection to receive instant updates when new
299
311
  * messages are added to the conversation. Returns an unsubscribe function
300
312
  * to clean up the connection.
313
+ *
314
+ * <Note>
315
+ When receiving messages through this function, tool call data is truncated for efficiency. The `arguments_string` is limited to 500 characters and `results` to 50 characters. The complete tool call data is always saved in storage and can be retrieved by calling {@linkcode getConversation | getConversation()} after the message completes.
316
+ </Note>
301
317
  *
302
318
  * @param conversationId - The conversation ID to subscribe to.
303
- * @param onUpdate - Callback function called when the conversation is updated.
319
+ * @param onUpdate - Callback function called when the conversation is updated. The callback receives a conversation object with the following properties:
320
+ * - `id`: Unique identifier for the conversation.
321
+ * - `agent_name`: Name of the agent in this conversation.
322
+ * - `created_date`: ISO 8601 timestamp of when the conversation was created.
323
+ * - `updated_date`: ISO 8601 timestamp of when the conversation was last updated.
324
+ * - `messages`: Array of messages in the conversation. Each message includes `id`, `role` (`'user'`, `'assistant'`, or `'system'`), `content`, `created_date`, and optionally `tool_calls`, `reasoning`, `file_urls`, and `usage`.
325
+ * - `metadata`: Optional metadata associated with the conversation.
304
326
  * @returns Unsubscribe function to stop receiving updates.
305
327
  *
306
328
  * @example
307
329
  * ```typescript
308
- * // Subscribe to real-time updates
330
+ * // Subscribe to realtime updates
309
331
  * const unsubscribe = base44.agents.subscribeToConversation(
310
332
  * 'conv-123',
311
333
  * (updatedConversation) => {
@@ -336,5 +358,5 @@ export interface AgentsModule {
336
358
  * // User can open this URL to start a WhatsApp conversation
337
359
  * ```
338
360
  */
339
- getWhatsAppConnectURL(agentName: string): string;
361
+ getWhatsAppConnectURL(agentName: AgentName): string;
340
362
  }
@@ -1,8 +1,38 @@
1
+ /**
2
+ * Properties for analytics events.
3
+ *
4
+ * Key-value pairs with additional event data. Values can be strings, numbers, booleans, or null.
5
+ */
1
6
  export type TrackEventProperties = {
2
7
  [key: string]: string | number | boolean | null | undefined;
3
8
  };
9
+ /**
10
+ * Parameters for tracking an analytics event.
11
+ */
4
12
  export type TrackEventParams = {
13
+ /**
14
+ * Name of the event to track.
15
+ *
16
+ * Use descriptive names like `button_click`, `form_submit`, or `purchase_completed`.
17
+ */
5
18
  eventName: string;
19
+ /**
20
+ * Optional key-value pairs with additional event data.
21
+ *
22
+ * Values can be strings, numbers, booleans, or null.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * base44.analytics.track({
27
+ * eventName: 'add_to_cart',
28
+ * properties: {
29
+ * product_id: 'prod_123',
30
+ * price: 29.99,
31
+ * quantity: 2
32
+ * }
33
+ * });
34
+ * ```
35
+ */
6
36
  properties?: TrackEventProperties;
7
37
  };
8
38
  export type TrackEventIntrinsicData = {
@@ -37,6 +67,52 @@ export type AnalyticsModuleOptions = {
37
67
  batchSize?: number;
38
68
  heartBeatInterval?: number;
39
69
  };
40
- export type AnalyticsModule = {
41
- track: (params: TrackEventParams) => void;
42
- };
70
+ /**
71
+ * Analytics module for tracking custom events in your app.
72
+ *
73
+ * Use this module to track specific user actions. Track things like button clicks, form submissions, purchases, and feature usage.
74
+ *
75
+ * <Note> Analytics events tracked with this module appear as custom event cards in the [Analytics dashboard](/documentation/performance-and-seo/app-analytics).</Note>
76
+ *
77
+ * When tracking events:
78
+ *
79
+ * - Choose clear, descriptive event names in snake_case like `signup_button_click` or `purchase_completed` rather than generic names like `click`.
80
+ * - Include relevant context in your properties such as identifiers like `product_id`, measurements like `price`, and flags like `is_first_purchase`.
81
+ *
82
+ * This module is only available in user authentication mode (`base44.analytics`).
83
+ */
84
+ export interface AnalyticsModule {
85
+ /**
86
+ * Tracks a custom event that appears as a card in your Analytics dashboard.
87
+ *
88
+ * Each unique event name becomes its own card showing total count and trends over time. This method returns immediately and events are sent in batches in the background.
89
+ *
90
+ * @param params - Event parameters.
91
+ * @param params.eventName - Name of the event. This becomes the card title in your dashboard. Use descriptive names like `'signup_button_click'` or `'purchase_completed'`.
92
+ * @param params.properties - Optional data to attach to the event. You can filter and analyze events by these properties in the dashboard.
93
+ *
94
+ * @example Track a button click
95
+ * ```typescript
96
+ * // Track a button click
97
+ * base44.analytics.track({
98
+ * eventName: 'signup_button_click'
99
+ * });
100
+ * ```
101
+ *
102
+ * @example Track with properties
103
+ * ```typescript
104
+ * // Track with properties
105
+ * base44.analytics.track({
106
+ * eventName: 'add_to_cart',
107
+ * properties: {
108
+ * product_id: 'prod_123',
109
+ * product_name: 'Premium Widget',
110
+ * price: 29.99,
111
+ * quantity: 2,
112
+ * is_first_purchase: true
113
+ * }
114
+ * });
115
+ * ```
116
+ */
117
+ track(params: TrackEventParams): void;
118
+ }
@@ -20,7 +20,6 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
20
20
  },
21
21
  // Redirects the user to the app's login page
22
22
  redirectToLogin(nextUrl) {
23
- var _a;
24
23
  // This function only works in a browser environment
25
24
  if (typeof window === "undefined") {
26
25
  throw new Error("Login method can only be used in a browser environment");
@@ -30,7 +29,7 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
30
29
  ? new URL(nextUrl, window.location.origin).toString()
31
30
  : window.location.href;
32
31
  // Build the login URL
33
- const loginUrl = `${(_a = options.appBaseUrl) !== null && _a !== void 0 ? _a : ""}/login?from_url=${encodeURIComponent(redirectUrl)}`;
32
+ const loginUrl = `${options.appBaseUrl}/login?from_url=${encodeURIComponent(redirectUrl)}`;
34
33
  // Redirect to the login page
35
34
  window.location.href = loginUrl;
36
35
  },
@@ -40,34 +39,32 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
40
39
  const redirectUrl = new URL(fromUrl, window.location.origin).toString();
41
40
  // Build the provider login URL (google is the default, so no provider path needed)
42
41
  const providerPath = provider === "google" ? "" : `/${provider}`;
43
- const loginUrl = `${options.serverUrl}/api/apps/auth${providerPath}/login?app_id=${appId}&from_url=${encodeURIComponent(redirectUrl)}`;
42
+ const loginUrl = `${options.appBaseUrl}/api/apps/auth${providerPath}/login?app_id=${appId}&from_url=${encodeURIComponent(redirectUrl)}`;
44
43
  // Redirect to the provider login page
45
44
  window.location.href = loginUrl;
46
45
  },
47
46
  // Logout the current user
48
- // Removes the token from localStorage and optionally redirects to a URL or reloads the page
49
47
  logout(redirectUrl) {
50
- // Remove token from axios headers
48
+ // Remove token from axios headers (always do this)
51
49
  delete axios.defaults.headers.common["Authorization"];
52
- // Remove token from localStorage
53
- if (typeof window !== "undefined" && window.localStorage) {
54
- try {
55
- window.localStorage.removeItem("base44_access_token");
56
- // Remove "token" that is set by the built-in SDK of platform version 2
57
- window.localStorage.removeItem("token");
58
- }
59
- catch (e) {
60
- console.error("Failed to remove token from localStorage:", e);
61
- }
62
- }
63
- // Redirect if a URL is provided
50
+ // Only do the rest if in a browser environment
64
51
  if (typeof window !== "undefined") {
65
- if (redirectUrl) {
66
- window.location.href = redirectUrl;
67
- }
68
- else {
69
- window.location.reload();
52
+ // Remove token from localStorage
53
+ if (window.localStorage) {
54
+ try {
55
+ window.localStorage.removeItem("base44_access_token");
56
+ // Remove "token" that is set by the built-in SDK of platform version 2
57
+ window.localStorage.removeItem("token");
58
+ }
59
+ catch (e) {
60
+ console.error("Failed to remove token from localStorage:", e);
61
+ }
70
62
  }
63
+ // Determine the from_url parameter
64
+ const fromUrl = redirectUrl || window.location.href;
65
+ // Redirect to server-side logout endpoint to clear HTTP-only cookies
66
+ const logoutUrl = `${options.appBaseUrl}/api/apps/auth/logout?from_url=${encodeURIComponent(fromUrl)}`;
67
+ window.location.href = logoutUrl;
71
68
  }
72
69
  },
73
70
  // Set authentication token
@@ -90,8 +90,8 @@ export interface ResetPasswordParams {
90
90
  export interface AuthModuleOptions {
91
91
  /** Server URL for API requests. */
92
92
  serverUrl: string;
93
- /** Optional base URL for the app (used for login redirects). */
94
- appBaseUrl?: string;
93
+ /** Base URL for the app (used for login redirects). */
94
+ appBaseUrl: string;
95
95
  }
96
96
  /**
97
97
  * Authentication module for managing user authentication and authorization. The module automatically stores tokens in local storage when available and manages authorization headers for API requests.
@@ -174,10 +174,15 @@ export interface AuthModule {
174
174
  /**
175
175
  * Redirects the user to a third-party authentication provider's login page.
176
176
  *
177
- * Initiates OAuth/SSO login flow with providers like Google, Microsoft, etc. Requires a browser environment and can't be used in the backend.
177
+ * Initiates an OAuth login flow with one of the built-in providers. Requires a browser environment and can't be used in the backend.
178
178
  *
179
- * @param provider - Name of the supported authentication provider (e.g., 'google', 'microsoft').
180
- * @param fromUrl - URL to redirect to after successful authentication. Defaults to '/'.
179
+ * Supported providers:
180
+ * - `'google'` - {@link https://developers.google.com/identity/protocols/oauth2 | Google OAuth}. Enabled by default.
181
+ * - `'microsoft'` - {@link https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow | Microsoft OAuth}. Enable Microsoft in your app's authentication settings before specifying this provider.
182
+ * - `'facebook'` - {@link https://developers.facebook.com/docs/facebook-login | Facebook Login}. Enable this in your app's authentication settings before using.
183
+ *
184
+ * @param provider - The authentication provider to use: `'google'`, `'microsoft'`, or `'facebook'`.
185
+ * @param fromUrl - URL to redirect to after successful authentication. Defaults to `'/'`.
181
186
  *
182
187
  * @example
183
188
  * ```typescript
@@ -187,7 +192,7 @@ export interface AuthModule {
187
192
  *
188
193
  * @example
189
194
  * ```typescript
190
- * // Login with GitHub and redirect to dashboard
195
+ * // Login with Microsoft and redirect to dashboard
191
196
  * base44.auth.loginWithProvider('microsoft', '/dashboard');
192
197
  * ```
193
198
  */
@@ -1,7 +1,14 @@
1
+ /**
2
+ * Registry of connector integration types.
3
+ * Augment this interface to enable autocomplete for connector integration types.
4
+ */
5
+ export interface ConnectorIntegrationTypeRegistry {
6
+ }
1
7
  /**
2
8
  * The type of external integration/connector, such as `'googlecalendar'`, `'slack'`, or `'github'`.
9
+ * Uses registry keys if augmented, otherwise falls back to string.
3
10
  */
4
- export type ConnectorIntegrationType = string;
11
+ export type ConnectorIntegrationType = keyof ConnectorIntegrationTypeRegistry extends never ? string : keyof ConnectorIntegrationTypeRegistry;
5
12
  /**
6
13
  * Response from the connectors access token endpoint.
7
14
  */
@@ -11,9 +18,7 @@ export interface ConnectorAccessTokenResponse {
11
18
  /**
12
19
  * Connectors module for managing OAuth tokens for external services.
13
20
  *
14
- * This module allows you to retrieve OAuth access tokens for external services
15
- * that the app has connected to. Use these tokens to make API
16
- * calls to external services.
21
+ * This module allows you to retrieve OAuth access tokens for external services that the app has connected to. Connectors are app-scoped. When an app builder connects an integration like Google Calendar or Slack, all users of the app share that same connection.
17
22
  *
18
23
  * Unlike the integrations module that provides pre-built functions, connectors give you
19
24
  * raw OAuth tokens so you can call external service APIs directly with full control over
@@ -26,9 +31,9 @@ export interface ConnectorsModule {
26
31
  /**
27
32
  * Retrieves an OAuth access token for a specific external integration type.
28
33
  *
29
- * Returns the OAuth token string for an external service that the app
30
- * has connected to. You can then use this token to make authenticated API calls
31
- * to that external service.
34
+ * Returns the OAuth token string for an external service that an app builder
35
+ * has connected to. This token represents the connected app builder's account
36
+ * and can be used to make authenticated API calls to that external service on behalf of the app.
32
37
  *
33
38
  * @param integrationType - The type of integration, such as `'googlecalendar'`, `'slack'`, or `'github'`.
34
39
  * @returns Promise resolving to the access token string.
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * Parameters for calling a custom integration endpoint.
3
+ * @internal
3
4
  */
4
5
  export interface CustomIntegrationCallParams {
5
6
  /**
@@ -7,21 +8,17 @@ export interface CustomIntegrationCallParams {
7
8
  */
8
9
  payload?: Record<string, any>;
9
10
  /**
10
- * Path parameters to substitute in the URL (e.g., `{ owner: "user", repo: "repo" }`).
11
+ * Path parameters to substitute in the URL. For example, `{ owner: "user", repo: "repo" }`.
11
12
  */
12
13
  pathParams?: Record<string, string>;
13
14
  /**
14
15
  * Query string parameters to append to the URL.
15
16
  */
16
17
  queryParams?: Record<string, any>;
17
- /**
18
- * Additional headers to send with this specific request.
19
- * These are merged with the integration's configured headers.
20
- */
21
- headers?: Record<string, string>;
22
18
  }
23
19
  /**
24
20
  * Response from a custom integration call.
21
+ * @internal
25
22
  */
26
23
  export interface CustomIntegrationCallResponse {
27
24
  /**
@@ -39,60 +36,17 @@ export interface CustomIntegrationCallResponse {
39
36
  data: any;
40
37
  }
41
38
  /**
42
- * Module for calling custom workspace-level API integrations.
43
- *
44
- * Custom integrations allow workspace administrators to connect any external API
45
- * by importing an OpenAPI specification. Apps in the workspace can then call
46
- * these integrations using this module.
47
- *
48
- * Unlike the built-in integrations (like `Core`), custom integrations:
49
- * - Are defined per-workspace by importing OpenAPI specs
50
- * - Use a slug-based identifier instead of package names
51
- * - Proxy requests through Base44's backend (credentials never exposed to frontend)
52
- *
53
- * @example
54
- * ```typescript
55
- * // Call a custom GitHub integration
56
- * const response = await base44.integrations.custom.call(
57
- * "github", // integration slug (defined by workspace admin)
58
- * "listIssues", // operation ID from the OpenAPI spec
59
- * {
60
- * pathParams: { owner: "myorg", repo: "myrepo" },
61
- * queryParams: { state: "open", per_page: 100 }
62
- * }
63
- * );
39
+ * Module for calling custom pre-configured API integrations.
64
40
  *
65
- * if (response.success) {
66
- * console.log("Issues:", response.data);
67
- * } else {
68
- * console.error("API returned error:", response.status_code);
69
- * }
70
- * ```
71
- *
72
- * @example
73
- * ```typescript
74
- * // Call with request body payload
75
- * const response = await base44.integrations.custom.call(
76
- * "github",
77
- * "createIssue",
78
- * {
79
- * pathParams: { owner: "myorg", repo: "myrepo" },
80
- * payload: {
81
- * title: "Bug report",
82
- * body: "Something is broken",
83
- * labels: ["bug"]
84
- * }
85
- * }
86
- * );
87
- * ```
41
+ * Custom integrations allow workspace administrators to connect any external API by importing an OpenAPI specification. Apps in the workspace can then call these integrations using this module.
88
42
  */
89
43
  export interface CustomIntegrationsModule {
90
44
  /**
91
45
  * Call a custom integration endpoint.
92
46
  *
93
- * @param slug - The integration's unique identifier (slug), as defined by the workspace admin.
94
- * @param operationId - The operation ID from the OpenAPI spec (e.g., "listIssues", "getUser").
95
- * @param params - Optional parameters including payload, pathParams, queryParams, and headers.
47
+ * @param slug - The integration's unique identifier, as defined by the workspace admin.
48
+ * @param operationId - The endpoint in `method:path` format. For example, `"get:/contacts"`, or `"post:/users/{id}"`. The method is the HTTP verb in lowercase and the path matches the OpenAPI specification.
49
+ * @param params - Optional parameters including payload, pathParams, and queryParams.
96
50
  * @returns Promise resolving to the integration call response.
97
51
  *
98
52
  * @throws {Error} If slug is not provided.
@@ -100,6 +54,36 @@ export interface CustomIntegrationsModule {
100
54
  * @throws {Base44Error} If the integration or operation is not found (404).
101
55
  * @throws {Base44Error} If the external API call fails (502).
102
56
  * @throws {Base44Error} If the request times out (504).
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * // Call a custom CRM integration
61
+ * const response = await base44.integrations.custom.call(
62
+ * "my-crm",
63
+ * "get:/contacts",
64
+ * { queryParams: { limit: 10 } }
65
+ * );
66
+ *
67
+ * if (response.success) {
68
+ * console.log("Contacts:", response.data);
69
+ * }
70
+ * ```
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * // Call with path params and request body
75
+ * const response = await base44.integrations.custom.call(
76
+ * "github",
77
+ * "post:/repos/{owner}/{repo}/issues",
78
+ * {
79
+ * pathParams: { owner: "myorg", repo: "myrepo" },
80
+ * payload: {
81
+ * title: "Bug report",
82
+ * body: "Something is broken"
83
+ * }
84
+ * }
85
+ * );
86
+ * ```
103
87
  */
104
88
  call(slug: string, operationId: string, params?: CustomIntegrationCallParams): Promise<CustomIntegrationCallResponse>;
105
89
  }
@@ -4,12 +4,14 @@
4
4
  export type RealtimeEventType = "create" | "update" | "delete";
5
5
  /**
6
6
  * Payload received when a realtime event occurs.
7
+ *
8
+ * @typeParam T - The entity type for the data field. Defaults to `any`.
7
9
  */
8
- export interface RealtimeEvent {
10
+ export interface RealtimeEvent<T = any> {
9
11
  /** The type of change that occurred */
10
12
  type: RealtimeEventType;
11
13
  /** The entity data */
12
- data: any;
14
+ data: T;
13
15
  /** The unique identifier of the affected entity */
14
16
  id: string;
15
17
  /** ISO 8601 timestamp of when the event occurred */
@@ -17,29 +19,108 @@ export interface RealtimeEvent {
17
19
  }
18
20
  /**
19
21
  * Callback function invoked when a realtime event occurs.
22
+ *
23
+ * @typeParam T - The entity type for the event data. Defaults to `any`.
24
+ */
25
+ export type RealtimeCallback<T = any> = (event: RealtimeEvent<T>) => void;
26
+ /**
27
+ * Result returned when deleting a single entity.
28
+ */
29
+ export interface DeleteResult {
30
+ /** Whether the deletion was successful */
31
+ success: boolean;
32
+ }
33
+ /**
34
+ * Result returned when deleting multiple entities.
35
+ */
36
+ export interface DeleteManyResult {
37
+ /** Whether the deletion was successful */
38
+ success: boolean;
39
+ /** Number of entities that were deleted */
40
+ deleted: number;
41
+ }
42
+ /**
43
+ * Result returned when importing entities from a file.
44
+ *
45
+ * @typeParam T - The entity type for imported records. Defaults to `any`.
20
46
  */
21
- export type RealtimeCallback = (event: RealtimeEvent) => void;
47
+ export interface ImportResult<T = any> {
48
+ /** Status of the import operation */
49
+ status: "success" | "error";
50
+ /** Details message, e.g., "Successfully imported 3 entities with RLS enforcement" */
51
+ details: string | null;
52
+ /** Array of created entity objects when successful, or null on error */
53
+ output: T[] | null;
54
+ }
22
55
  /**
23
- * Function returned from subscribe, call it to unsubscribe.
56
+ * Sort field type for entity queries.
57
+ *
58
+ * Supports ascending (no prefix or `'+'`) and descending (`'-'`) sorting.
59
+ *
60
+ * @typeParam T - The entity type to derive sortable fields from.
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * // Ascending sort (default)
65
+ * 'created_date'
66
+ * '+created_date'
67
+ *
68
+ * // Descending sort
69
+ * '-created_date'
70
+ * ```
24
71
  */
25
- export type Subscription = () => void;
72
+ export type SortField<T> = (keyof T & string) | `+${keyof T & string}` | `-${keyof T & string}`;
73
+ /**
74
+ * Fields added by the server to every entity record (id, dates, created_by, etc.).
75
+ */
76
+ interface ServerEntityFields {
77
+ /** Unique identifier of the record */
78
+ id: string;
79
+ /** ISO 8601 timestamp when the record was created */
80
+ created_date: string;
81
+ /** ISO 8601 timestamp when the record was last updated */
82
+ updated_date: string;
83
+ /** Email of the user who created the record (may be hidden in some responses) */
84
+ created_by?: string | null;
85
+ /** ID of the user who created the record */
86
+ created_by_id?: string | null;
87
+ /** Whether the record is sample/seed data */
88
+ is_sample?: boolean;
89
+ }
90
+ /**
91
+ * Registry mapping entity names to their TypeScript types.
92
+ * Augment this interface with your entity schema (user-defined fields only).
93
+ */
94
+ export interface EntityTypeRegistry {
95
+ }
96
+ /**
97
+ * Full record type for each entity: schema fields + server-injected fields (id, created_date, etc.).
98
+ */
99
+ export type EntityRecord = {
100
+ [K in keyof EntityTypeRegistry]: EntityTypeRegistry[K] & ServerEntityFields;
101
+ };
26
102
  /**
27
103
  * Entity handler providing CRUD operations for a specific entity type.
28
104
  *
29
105
  * Each entity in the app gets a handler with these methods for managing data.
106
+ *
107
+ * @typeParam T - The entity type. Defaults to `any` for backward compatibility.
30
108
  */
31
- export interface EntityHandler {
109
+ export interface EntityHandler<T = any> {
32
110
  /**
33
111
  * Lists records with optional pagination and sorting.
34
112
  *
35
113
  * Retrieves all records of this type with support for sorting,
36
114
  * pagination, and field selection.
37
115
  *
116
+ * **Note:** The maximum limit is 5,000 items per request.
117
+ *
118
+ * @typeParam K - The fields to include in the response. Defaults to all fields.
38
119
  * @param sort - Sort parameter, such as `'-created_date'` for descending. Defaults to `'-created_date'`.
39
120
  * @param limit - Maximum number of results to return. Defaults to `50`.
40
121
  * @param skip - Number of results to skip for pagination. Defaults to `0`.
41
122
  * @param fields - Array of field names to include in the response. Defaults to all fields.
42
- * @returns Promise resolving to an array of records.
123
+ * @returns Promise resolving to an array of records with selected fields.
43
124
  *
44
125
  * @example
45
126
  * ```typescript
@@ -66,13 +147,16 @@ export interface EntityHandler {
66
147
  * const fields = await base44.entities.MyEntity.list('-created_date', 10, 0, ['name', 'status']);
67
148
  * ```
68
149
  */
69
- list(sort?: string, limit?: number, skip?: number, fields?: string[]): Promise<any>;
150
+ list<K extends keyof T = keyof T>(sort?: SortField<T>, limit?: number, skip?: number, fields?: K[]): Promise<Pick<T, K>[]>;
70
151
  /**
71
152
  * Filters records based on a query.
72
153
  *
73
154
  * Retrieves records that match specific criteria with support for
74
155
  * sorting, pagination, and field selection.
75
156
  *
157
+ * **Note:** The maximum limit is 5,000 items per request.
158
+ *
159
+ * @typeParam K - The fields to include in the response. Defaults to all fields.
76
160
  * @param query - Query object with field-value pairs. Each key should be a field name
77
161
  * from your entity schema, and each value is the criteria to match. Records matching all
78
162
  * specified criteria are returned. Field names are case-sensitive.
@@ -80,7 +164,7 @@ export interface EntityHandler {
80
164
  * @param limit - Maximum number of results to return. Defaults to `50`.
81
165
  * @param skip - Number of results to skip for pagination. Defaults to `0`.
82
166
  * @param fields - Array of field names to include in the response. Defaults to all fields.
83
- * @returns Promise resolving to an array of filtered records.
167
+ * @returns Promise resolving to an array of filtered records with selected fields.
84
168
  *
85
169
  * @example
86
170
  * ```typescript
@@ -122,7 +206,7 @@ export interface EntityHandler {
122
206
  * );
123
207
  * ```
124
208
  */
125
- filter(query: Record<string, any>, sort?: string, limit?: number, skip?: number, fields?: string[]): Promise<any>;
209
+ filter<K extends keyof T = keyof T>(query: Partial<T>, sort?: SortField<T>, limit?: number, skip?: number, fields?: K[]): Promise<Pick<T, K>[]>;
126
210
  /**
127
211
  * Gets a single record by ID.
128
212
  *
@@ -138,7 +222,7 @@ export interface EntityHandler {
138
222
  * console.log(record.name);
139
223
  * ```
140
224
  */
141
- get(id: string): Promise<any>;
225
+ get(id: string): Promise<T>;
142
226
  /**
143
227
  * Creates a new record.
144
228
  *
@@ -158,7 +242,7 @@ export interface EntityHandler {
158
242
  * console.log('Created record with ID:', newRecord.id);
159
243
  * ```
160
244
  */
161
- create(data: Record<string, any>): Promise<any>;
245
+ create(data: Partial<T>): Promise<T>;
162
246
  /**
163
247
  * Updates an existing record.
164
248
  *
@@ -187,7 +271,7 @@ export interface EntityHandler {
187
271
  * });
188
272
  * ```
189
273
  */
190
- update(id: string, data: Record<string, any>): Promise<any>;
274
+ update(id: string, data: Partial<T>): Promise<T>;
191
275
  /**
192
276
  * Deletes a single record by ID.
193
277
  *
@@ -200,10 +284,10 @@ export interface EntityHandler {
200
284
  * ```typescript
201
285
  * // Delete a record
202
286
  * const result = await base44.entities.MyEntity.delete('entity-123');
203
- * console.log('Deleted:', result);
287
+ * console.log('Deleted:', result.success);
204
288
  * ```
205
289
  */
206
- delete(id: string): Promise<any>;
290
+ delete(id: string): Promise<DeleteResult>;
207
291
  /**
208
292
  * Deletes multiple records matching a query.
209
293
  *
@@ -221,10 +305,10 @@ export interface EntityHandler {
221
305
  * status: 'completed',
222
306
  * priority: 'low'
223
307
  * });
224
- * console.log('Deleted:', result);
308
+ * console.log('Deleted:', result.deleted);
225
309
  * ```
226
310
  */
227
- deleteMany(query: Record<string, any>): Promise<any>;
311
+ deleteMany(query: Partial<T>): Promise<DeleteManyResult>;
228
312
  /**
229
313
  * Creates multiple records in a single request.
230
314
  *
@@ -244,7 +328,7 @@ export interface EntityHandler {
244
328
  * ]);
245
329
  * ```
246
330
  */
247
- bulkCreate(data: Record<string, any>[]): Promise<any>;
331
+ bulkCreate(data: Partial<T>[]): Promise<T[]>;
248
332
  /**
249
333
  * Imports records from a file.
250
334
  *
@@ -252,7 +336,7 @@ export interface EntityHandler {
252
336
  * The file format should match your entity structure. Requires a browser environment and can't be used in the backend.
253
337
  *
254
338
  * @param file - File object to import.
255
- * @returns Promise resolving to the import result.
339
+ * @returns Promise resolving to the import result containing status, details, and created records.
256
340
  *
257
341
  * @example
258
342
  * ```typescript
@@ -261,19 +345,27 @@ export interface EntityHandler {
261
345
  * const file = event.target.files?.[0];
262
346
  * if (file) {
263
347
  * const result = await base44.entities.MyEntity.importEntities(file);
264
- * console.log(`Imported ${result.count} records`);
348
+ * if (result.status === 'success' && result.output) {
349
+ * console.log(`Imported ${result.output.length} records`);
350
+ * }
265
351
  * }
266
352
  * };
267
353
  * ```
268
354
  */
269
- importEntities(file: File): Promise<any>;
355
+ importEntities(file: File): Promise<ImportResult<T>>;
270
356
  /**
271
357
  * Subscribes to realtime updates for all records of this entity type.
272
358
  *
273
- * Receives notifications whenever any record is created, updated, or deleted.
359
+ * Establishes a WebSocket connection to receive instant updates when any
360
+ * record is created, updated, or deleted. Returns an unsubscribe function
361
+ * to clean up the connection.
274
362
  *
275
- * @param callback - Function called when an entity changes.
276
- * @returns Unsubscribe function to stop listening.
363
+ * @param callback - Callback function called when an entity changes. The callback receives an event object with the following properties:
364
+ * - `type`: The type of change that occurred - `'create'`, `'update'`, or `'delete'`.
365
+ * - `data`: The entity data after the change.
366
+ * - `id`: The unique identifier of the affected entity.
367
+ * - `timestamp`: ISO 8601 timestamp of when the event occurred.
368
+ * @returns Unsubscribe function to stop receiving updates.
277
369
  *
278
370
  * @example
279
371
  * ```typescript
@@ -282,12 +374,24 @@ export interface EntityHandler {
282
374
  * console.log(`Task ${event.id} was ${event.type}d:`, event.data);
283
375
  * });
284
376
  *
285
- * // Later, unsubscribe
377
+ * // Later, clean up the subscription
286
378
  * unsubscribe();
287
379
  * ```
288
380
  */
289
- subscribe(callback: RealtimeCallback): Subscription;
381
+ subscribe(callback: RealtimeCallback<T>): () => void;
290
382
  }
383
+ /**
384
+ * Typed entities module - maps registry keys to typed handlers (full record type).
385
+ */
386
+ type TypedEntitiesModule = {
387
+ [K in keyof EntityTypeRegistry]: EntityHandler<EntityRecord[K]>;
388
+ };
389
+ /**
390
+ * Dynamic entities module - allows any entity name with untyped handler.
391
+ */
392
+ type DynamicEntitiesModule = {
393
+ [entityName: string]: EntityHandler<any>;
394
+ };
291
395
  /**
292
396
  * Entities module for managing app data.
293
397
  *
@@ -321,18 +425,5 @@ export interface EntityHandler {
321
425
  * const allUsers = await base44.asServiceRole.entities.User.list();
322
426
  * ```
323
427
  */
324
- export interface EntitiesModule {
325
- /**
326
- * Access any entity by name.
327
- *
328
- * Use this to access entities defined in the app.
329
- *
330
- * @example
331
- * ```typescript
332
- * // Access entities dynamically
333
- * base44.entities.MyEntity
334
- * base44.entities.AnotherEntity
335
- * ```
336
- */
337
- [entityName: string]: EntityHandler;
338
- }
428
+ export type EntitiesModule = TypedEntitiesModule & DynamicEntitiesModule;
429
+ export {};
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Registry of function names.
3
+ * Augment this interface to enable autocomplete for function names.
4
+ */
5
+ export interface FunctionNameRegistry {
6
+ }
7
+ /**
8
+ * Function name type - uses registry keys if augmented, otherwise string.
9
+ */
10
+ export type FunctionName = keyof FunctionNameRegistry extends never ? string : keyof FunctionNameRegistry;
1
11
  /**
2
12
  * Functions module for invoking custom backend functions.
3
13
  *
@@ -46,5 +56,5 @@ export interface FunctionsModule {
46
56
  * };
47
57
  * ```
48
58
  */
49
- invoke(functionName: string, data: Record<string, any>): Promise<any>;
59
+ invoke(functionName: FunctionName, data?: Record<string, any>): Promise<any>;
50
60
  }
@@ -320,22 +320,28 @@ export interface CoreIntegrations {
320
320
  CreateFileSignedUrl(params: CreateFileSignedUrlParams): Promise<CreateFileSignedUrlResult>;
321
321
  }
322
322
  /**
323
- * Integrations module for calling integration endpoints.
323
+ * Integrations module for calling integration methods.
324
324
  *
325
- * This module provides access to integration endpoints for interacting with external
326
- * services. Integrations are organized into packages. Base44 provides built-in integrations
327
- * in the `Core` package.
325
+ * This module provides access to integration methods for interacting with external services. Unlike the connectors module that gives you raw OAuth tokens, integrations provide pre-built functions that Base44 executes on your behalf.
328
326
  *
329
- * Unlike the connectors module that gives you raw OAuth tokens, integrations provide
330
- * pre-built functions that Base44 executes on your behalf.
327
+ * There are two types of integrations:
331
328
  *
332
- * Integration endpoints are accessed dynamically using the pattern:
333
- * `base44.integrations.PackageName.EndpointName(params)`
329
+ * - **Built-in integrations** (`Core`): Pre-built functions provided by Base44 for common tasks such as AI-powered text generation, image creation, file uploads, and email. Access core integration methods using:
330
+ * ```
331
+ * base44.integrations.Core.FunctionName(params)
332
+ * ```
333
+ *
334
+ * - **Custom integrations** (`custom`): Pre-configured external APIs. Custom integration calls are proxied through Base44's backend, so credentials are never exposed to the frontend. Access custom integration methods using:
335
+ * ```
336
+ * base44.integrations.custom.call(slug, operationId, params)
337
+ * ```
338
+ *
339
+ * <Info>To call a custom integration, it must be pre-configured by a workspace administrator who imports an OpenAPI specification.</Info>
334
340
  *
335
341
  * This module is available to use with a client in all authentication modes:
336
342
  *
337
- * - **Anonymous or User authentication** (`base44.integrations`): Integration endpoints are invoked with the current user's permissions. Anonymous users invoke endpoints without authentication, while authenticated users invoke endpoints with their authentication context.
338
- * - **Service role authentication** (`base44.asServiceRole.integrations`): Integration endpoints are invoked with elevated admin-level permissions. The endpoints execute with admin authentication context.
343
+ * - **Anonymous or User authentication** (`base44.integrations`): Integration methods are invoked with the current user's permissions. Anonymous users invoke methods without authentication, while authenticated users invoke methods with their authentication context.
344
+ * - **Service role authentication** (`base44.asServiceRole.integrations`): Integration methods are invoked with elevated admin-level permissions. The methods execute with admin authentication context.
339
345
  */
340
346
  export type IntegrationsModule = {
341
347
  /**
@@ -343,22 +349,7 @@ export type IntegrationsModule = {
343
349
  */
344
350
  Core: CoreIntegrations;
345
351
  /**
346
- * Custom integrations module for calling workspace-level API integrations.
347
- *
348
- * Allows calling external APIs that workspace admins have configured
349
- * by importing OpenAPI specifications.
350
- *
351
- * @example
352
- * ```typescript
353
- * const response = await base44.integrations.custom.call(
354
- * "github", // integration slug
355
- * "listIssues", // operation ID
356
- * {
357
- * pathParams: { owner: "myorg", repo: "myrepo" },
358
- * queryParams: { state: "open" }
359
- * }
360
- * );
361
- * ```
352
+ * Custom integrations module for calling pre-configured external APIs.
362
353
  */
363
354
  custom: CustomIntegrationsModule;
364
355
  } & {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44/sdk",
3
- "version": "0.8.18",
3
+ "version": "0.8.19",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -19,7 +19,8 @@
19
19
  "docs": "typedoc",
20
20
  "prepublishOnly": "npm run build",
21
21
  "create-docs": "npm run create-docs:generate && npm run create-docs:process",
22
- "push-docs": "node scripts/mintlify-post-processing/push-to-docs-repo.js",
22
+ "create-docs-local": "npm run create-docs && npm run copy-docs-local",
23
+ "copy-docs-local": "node scripts/mintlify-post-processing/copy-to-local-docs.js",
23
24
  "create-docs:generate": "typedoc",
24
25
  "create-docs:process": "node scripts/mintlify-post-processing/file-processing/file-processing.js"
25
26
  },