@base44-preview/sdk 0.8.17-pr.77.f633c05 → 0.8.18-pr.78.cf66512

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,6 +1,21 @@
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
+ Install the SDK via npm:
13
+
14
+ ```bash
15
+ npm install @base44/sdk
16
+ ```
17
+
18
+ > **Note**: In Base44-generated apps, the SDK is already installed for you.
4
19
 
5
20
  ## Modules
6
21
 
@@ -12,11 +27,15 @@ The SDK provides access to Base44's functionality through the following modules:
12
27
  - **[`connectors`](https://docs.base44.com/sdk-docs/interfaces/connectors)**: Manage OAuth connections and access tokens for third-party services.
13
28
  - **[`entities`](https://docs.base44.com/sdk-docs/interfaces/entities)**: Work with your app's data entities using CRUD operations.
14
29
  - **[`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.
30
+ - **[`integrations`](https://docs.base44.com/sdk-docs/type-aliases/integrations)**: Pre-built integrations for external services.
16
31
 
17
- ## Example
32
+ ## Quick starts
18
33
 
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:
34
+ How you get started depends on your context:
35
+
36
+ ### Inside a Base44 app
37
+
38
+ In Base44-generated apps, the client is pre-configured. Just import and use it:
20
39
 
21
40
  ```typescript
22
41
  import { base44 } from "@/api/base44Client";
@@ -37,6 +56,45 @@ await base44.entities.Task.update(newTask.id, {
37
56
  const tasks = await base44.entities.Task.list();
38
57
  ```
39
58
 
59
+ ### External apps
60
+
61
+ When using Base44 as a backend for your own app, create and configure the client yourself:
62
+
63
+ ```typescript
64
+ import { createClient } from '@base44/sdk';
65
+
66
+ // Create a client for your Base44 app
67
+ const base44 = createClient({
68
+ appId: 'your-app-id' // Find this in the Base44 editor URL
69
+ });
70
+
71
+ // Read public data (anonymous access)
72
+ const products = await base44.entities.Products.list();
73
+
74
+ // Authenticate a user (token is automatically set)
75
+ await base44.auth.loginViaEmailPassword('user@example.com', 'password');
76
+
77
+ // Now operations use the authenticated user's permissions
78
+ const userOrders = await base44.entities.Orders.list();
79
+ ```
80
+
81
+ ### Service role
82
+
83
+ For backend code that needs admin-level access, use the service role. Service role is only available in Base44-hosted backend functions:
84
+
85
+ ```typescript
86
+ import { createClientFromRequest } from 'npm:@base44/sdk';
87
+
88
+ Deno.serve(async (req) => {
89
+ const base44 = createClientFromRequest(req);
90
+
91
+ // Access all data with admin-level permissions
92
+ const allOrders = await base44.asServiceRole.entities.Orders.list();
93
+
94
+ return Response.json({ orders: allOrders });
95
+ });
96
+ ```
97
+
40
98
  ## Learn more
41
99
 
42
100
  For complete documentation, guides, and API reference, visit the **[Base44 SDK Documentation](https://docs.base44.com/sdk-getting-started/overview)**.
@@ -45,6 +103,8 @@ For complete documentation, guides, and API reference, visit the **[Base44 SDK D
45
103
 
46
104
  ### Build the SDK
47
105
 
106
+ Build the SDK from source:
107
+
48
108
  ```bash
49
109
  npm install
50
110
  npm run build
@@ -52,6 +112,8 @@ npm run build
52
112
 
53
113
  ### Run tests
54
114
 
115
+ Run the test suite:
116
+
55
117
  ```bash
56
118
  # Run all tests
57
119
  npm test
@@ -64,6 +126,7 @@ npm run test:coverage
64
126
  ```
65
127
 
66
128
  For E2E tests, create a `tests/.env` file with:
129
+
67
130
  ```
68
131
  BASE44_APP_ID=your_app_id
69
132
  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.
@@ -224,7 +226,7 @@ export function createClient(config) {
224
226
  /**
225
227
  * Provides access to service role modules.
226
228
  *
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.
229
+ * 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
230
  *
229
231
  * @throws {Error} When accessed without providing a serviceToken during client creation.
230
232
  *
@@ -251,7 +253,9 @@ export function createClient(config) {
251
253
  /**
252
254
  * Creates a Base44 client from an HTTP request.
253
255
  *
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.
256
+ * This function is designed for use in Base44-hosted backend functions. For frontends and external backends, use {@linkcode createClient | createClient()} instead.
257
+ *
258
+ * 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
259
  *
256
260
  * To learn more about the Base44 client, see {@linkcode createClient | createClient()}.
257
261
  *
@@ -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
  /**
@@ -1,6 +1,8 @@
1
1
  import { getAccessToken } from "../utils/auth-utils.js";
2
2
  export function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }) {
3
3
  const baseURL = `/apps/${appId}/agents`;
4
+ // Track active conversations
5
+ const currentConversations = {};
4
6
  const getConversations = () => {
5
7
  return axios.get(`${baseURL}/conversations`);
6
8
  };
@@ -16,22 +18,39 @@ export function createAgentsModule({ axios, getSocket, appId, serverUrl, token,
16
18
  return axios.post(`${baseURL}/conversations`, conversation);
17
19
  };
18
20
  const addMessage = async (conversation, message) => {
19
- const room = `/agent-conversations/${conversation.id}`;
20
- const socket = getSocket();
21
- await socket.updateModel(room, {
22
- ...conversation,
23
- messages: [...(conversation.messages || []), message],
24
- });
25
- return axios.post(`${baseURL}/conversations/${conversation.id}/messages`, message);
21
+ return axios.post(`${baseURL}/conversations/v2/${conversation.id}/messages`, message);
26
22
  };
27
23
  const subscribeToConversation = (conversationId, onUpdate) => {
28
24
  const room = `/agent-conversations/${conversationId}`;
29
25
  const socket = getSocket();
26
+ // Store the promise for initial conversation state
27
+ const conversationPromise = getConversation(conversationId).then((conv) => {
28
+ currentConversations[conversationId] = conv;
29
+ return conv;
30
+ });
30
31
  return socket.subscribeToRoom(room, {
31
32
  connect: () => { },
32
- update_model: ({ data: jsonStr }) => {
33
- const conv = JSON.parse(jsonStr);
34
- onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(conv);
33
+ update_model: async ({ data: jsonStr }) => {
34
+ const data = JSON.parse(jsonStr);
35
+ if (data._message) {
36
+ // Wait for initial conversation to be loaded
37
+ await conversationPromise;
38
+ const message = data._message;
39
+ // Update shared conversation state
40
+ const currentConversation = currentConversations[conversationId];
41
+ if (currentConversation) {
42
+ const messages = currentConversation.messages || [];
43
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
44
+ const updatedMessages = existingIndex !== -1
45
+ ? messages.map((m, i) => (i === existingIndex ? message : m))
46
+ : [...messages, message];
47
+ currentConversations[conversationId] = {
48
+ ...currentConversation,
49
+ messages: updatedMessages,
50
+ };
51
+ onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(currentConversations[conversationId]);
52
+ }
53
+ }
35
54
  },
36
55
  });
37
56
  };
@@ -25,28 +25,25 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
25
25
  if (typeof window === "undefined") {
26
26
  throw new Error("Login method can only be used in a browser environment");
27
27
  }
28
- const hostname = window.location.hostname;
29
- const isPreview = hostname.startsWith("preview--");
30
- // Skip redirect if already on login page (but not on preview - preview should redirect to main app)
31
- if (window.location.pathname === "/login" && !isPreview) {
32
- return;
33
- }
34
28
  // If nextUrl is not provided, use the current URL
35
29
  const redirectUrl = nextUrl
36
30
  ? new URL(nextUrl, window.location.origin).toString()
37
31
  : window.location.href;
38
- // For preview URLs (preview--*), redirect to main app's login page
39
- // but keep from_url pointing to the preview URL
40
- let loginBaseUrl = (_a = options.appBaseUrl) !== null && _a !== void 0 ? _a : "";
41
- if (isPreview) {
42
- const mainHostname = hostname.replace(/^preview--/, "");
43
- loginBaseUrl = `${window.location.protocol}//${mainHostname}${window.location.port ? ":" + window.location.port : ""}`;
44
- }
45
32
  // Build the login URL
46
- const loginUrl = `${loginBaseUrl}/login?from_url=${encodeURIComponent(redirectUrl)}`;
33
+ const loginUrl = `${(_a = options.appBaseUrl) !== null && _a !== void 0 ? _a : ""}/login?from_url=${encodeURIComponent(redirectUrl)}`;
47
34
  // Redirect to the login page
48
35
  window.location.href = loginUrl;
49
36
  },
37
+ // Redirects the user to a provider's login page
38
+ loginWithProvider(provider, fromUrl = "/") {
39
+ // Build the full redirect URL
40
+ const redirectUrl = new URL(fromUrl, window.location.origin).toString();
41
+ // Build the provider login URL (google is the default, so no provider path needed)
42
+ const providerPath = provider === "google" ? "" : `/${provider}`;
43
+ const loginUrl = `${options.serverUrl}/api/apps/auth${providerPath}/login?app_id=${appId}&from_url=${encodeURIComponent(redirectUrl)}`;
44
+ // Redirect to the provider login page
45
+ window.location.href = loginUrl;
46
+ },
50
47
  // Logout the current user
51
48
  // Removes the token from localStorage and optionally redirects to a URL or reloads the page
52
49
  logout(redirectUrl) {
@@ -171,6 +171,27 @@ export interface AuthModule {
171
171
  * ```
172
172
  */
173
173
  redirectToLogin(nextUrl: string): void;
174
+ /**
175
+ * Redirects the user to a third-party authentication provider's login page.
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.
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 '/'.
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * // Login with Google and return to current page
185
+ * base44.auth.loginWithProvider('google', window.location.pathname);
186
+ * ```
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * // Login with GitHub and redirect to dashboard
191
+ * base44.auth.loginWithProvider('microsoft', '/dashboard');
192
+ * ```
193
+ */
194
+ loginWithProvider(provider: string, fromUrl?: string): void;
174
195
  /**
175
196
  * Logs out the current user.
176
197
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.17-pr.77.f633c05",
3
+ "version": "0.8.18-pr.78.cf66512",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",