@base44-preview/sdk 0.8.39-pr.237.783a84a → 0.8.40-pr.212.2b700ea
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/dist/actor.d.ts +77 -0
- package/dist/actor.js +63 -0
- package/dist/client.js +28 -1
- package/dist/client.types.d.ts +14 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/modules/actors.d.ts +16 -0
- package/dist/modules/actors.js +134 -0
- package/dist/modules/actors.types.d.ts +89 -0
- package/dist/modules/actors.types.js +1 -0
- package/dist/modules/ai-gateway.types.d.ts +70 -19
- package/dist/modules/sso.d.ts +0 -1
- package/dist/modules/sso.js +5 -1
- package/dist/modules/sso.types.d.ts +50 -20
- package/package.json +3 -2
package/dist/actor.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type-only base class for Actors.
|
|
3
|
+
*
|
|
4
|
+
* Import and extend this in your actor files:
|
|
5
|
+
* import { Actor } from "@base44/sdk";
|
|
6
|
+
* export class MyActor extends Actor { ... }
|
|
7
|
+
*
|
|
8
|
+
* At deploy time the bundler replaces this import with the compiled
|
|
9
|
+
* Cloudflare Durable Object implementation — this file provides types only.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* A single client connection. `Send` is the message type this connection accepts
|
|
13
|
+
* via {@link send} — the actor's *outgoing* (server→client) messages.
|
|
14
|
+
*/
|
|
15
|
+
export interface Conn<Send = unknown> {
|
|
16
|
+
/** Unique per-connection id (one per socket/tab), the same value the client
|
|
17
|
+
* receives from `subscribe()`. Use this — not userId — to identify a distinct
|
|
18
|
+
* client, so multiple tabs of the same user are separate connections. */
|
|
19
|
+
id: string;
|
|
20
|
+
userId: string;
|
|
21
|
+
appId: string;
|
|
22
|
+
instanceId: string;
|
|
23
|
+
send(data: Send): void;
|
|
24
|
+
reject(code: number, reason: string): void;
|
|
25
|
+
}
|
|
26
|
+
export interface Storage {
|
|
27
|
+
get<T>(key: string): Promise<T | undefined>;
|
|
28
|
+
put(key: string, value: unknown): Promise<void>;
|
|
29
|
+
delete(key: string): Promise<boolean>;
|
|
30
|
+
/** Wipe the room's entire persisted storage (match-end cleanup). Safe: a
|
|
31
|
+
* later rejoin re-bootstraps exactly like a brand-new room. */
|
|
32
|
+
deleteAll(): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Base class for an Actor.
|
|
36
|
+
*
|
|
37
|
+
* @typeParam Incoming - messages this actor *receives* from clients
|
|
38
|
+
* (`handleMessage`'s `msg`) — the schema's `toServer` section.
|
|
39
|
+
* @typeParam Outgoing - messages this actor *sends* to clients
|
|
40
|
+
* (`conn.send`/`broadcast`) — the schema's `toClient` section.
|
|
41
|
+
*
|
|
42
|
+
* With a generated `schema.jsonc`, wire both from the registry so they can't drift
|
|
43
|
+
* from the client's types:
|
|
44
|
+
* ```ts
|
|
45
|
+
* type Reg = ActorRegistry["MyActor"];
|
|
46
|
+
* class MyActor extends Actor<Reg["toServer"], Reg["toClient"]> { ... }
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export declare abstract class Actor<Incoming = unknown, Outgoing = unknown> {
|
|
50
|
+
abstract handleConnect(conn: Conn<Outgoing>): void | Promise<void>;
|
|
51
|
+
abstract handleMessage(conn: Conn<Outgoing>, msg: Incoming): void | Promise<void>;
|
|
52
|
+
abstract handleClose(conn: Conn<Outgoing>): void | Promise<void>;
|
|
53
|
+
abstract handleTick(): void | Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Optional wake hook: runs once when the instance starts, before any
|
|
56
|
+
* connection is handled — safe to load persisted state here.
|
|
57
|
+
*/
|
|
58
|
+
handleStart(): void | Promise<void>;
|
|
59
|
+
/**
|
|
60
|
+
* Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
|
|
61
|
+
* {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
|
|
62
|
+
* and stops (letting the Durable Object hibernate — no compute cost) when it
|
|
63
|
+
* returns false. The platform owns scheduling, rescheduling, self-heal, and
|
|
64
|
+
* error-safety — you don't call {@link startLoop}/{@link stopLoop}.
|
|
65
|
+
*
|
|
66
|
+
* Re-evaluated after every connect/message/close and on every tick, so keep it
|
|
67
|
+
* cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
|
|
68
|
+
*/
|
|
69
|
+
protected tickIntervalMs: number;
|
|
70
|
+
protected shouldTick?(): boolean;
|
|
71
|
+
protected broadcast(_data: Outgoing): void;
|
|
72
|
+
protected getConnections(): Conn<Outgoing>[];
|
|
73
|
+
protected startLoop(_ms: number): Promise<void>;
|
|
74
|
+
protected stopLoop(): Promise<void>;
|
|
75
|
+
protected get instanceId(): string;
|
|
76
|
+
protected get storage(): Storage;
|
|
77
|
+
}
|
package/dist/actor.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type-only base class for Actors.
|
|
3
|
+
*
|
|
4
|
+
* Import and extend this in your actor files:
|
|
5
|
+
* import { Actor } from "@base44/sdk";
|
|
6
|
+
* export class MyActor extends Actor { ... }
|
|
7
|
+
*
|
|
8
|
+
* At deploy time the bundler replaces this import with the compiled
|
|
9
|
+
* Cloudflare Durable Object implementation — this file provides types only.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Base class for an Actor.
|
|
13
|
+
*
|
|
14
|
+
* @typeParam Incoming - messages this actor *receives* from clients
|
|
15
|
+
* (`handleMessage`'s `msg`) — the schema's `toServer` section.
|
|
16
|
+
* @typeParam Outgoing - messages this actor *sends* to clients
|
|
17
|
+
* (`conn.send`/`broadcast`) — the schema's `toClient` section.
|
|
18
|
+
*
|
|
19
|
+
* With a generated `schema.jsonc`, wire both from the registry so they can't drift
|
|
20
|
+
* from the client's types:
|
|
21
|
+
* ```ts
|
|
22
|
+
* type Reg = ActorRegistry["MyActor"];
|
|
23
|
+
* class MyActor extends Actor<Reg["toServer"], Reg["toClient"]> { ... }
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export class Actor {
|
|
27
|
+
constructor() {
|
|
28
|
+
/**
|
|
29
|
+
* Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
|
|
30
|
+
* {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
|
|
31
|
+
* and stops (letting the Durable Object hibernate — no compute cost) when it
|
|
32
|
+
* returns false. The platform owns scheduling, rescheduling, self-heal, and
|
|
33
|
+
* error-safety — you don't call {@link startLoop}/{@link stopLoop}.
|
|
34
|
+
*
|
|
35
|
+
* Re-evaluated after every connect/message/close and on every tick, so keep it
|
|
36
|
+
* cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
|
|
37
|
+
*/
|
|
38
|
+
this.tickIntervalMs = 100;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Optional wake hook: runs once when the instance starts, before any
|
|
42
|
+
* connection is handled — safe to load persisted state here.
|
|
43
|
+
*/
|
|
44
|
+
handleStart() { }
|
|
45
|
+
broadcast(_data) {
|
|
46
|
+
throw new Error("Actor.broadcast() is only available inside a deployed actor");
|
|
47
|
+
}
|
|
48
|
+
getConnections() {
|
|
49
|
+
throw new Error("Actor.getConnections() is only available inside a deployed actor");
|
|
50
|
+
}
|
|
51
|
+
startLoop(_ms) {
|
|
52
|
+
throw new Error("Actor.startLoop() is only available inside a deployed actor");
|
|
53
|
+
}
|
|
54
|
+
stopLoop() {
|
|
55
|
+
throw new Error("Actor.stopLoop() is only available inside a deployed actor");
|
|
56
|
+
}
|
|
57
|
+
get instanceId() {
|
|
58
|
+
throw new Error("Actor.instanceId is only available inside a deployed actor");
|
|
59
|
+
}
|
|
60
|
+
get storage() {
|
|
61
|
+
throw new Error("Actor.storage is only available inside a deployed actor");
|
|
62
|
+
}
|
|
63
|
+
}
|
package/dist/client.js
CHANGED
|
@@ -12,6 +12,7 @@ import { createAppLogsModule } from "./modules/app-logs.js";
|
|
|
12
12
|
import { createUsersModule } from "./modules/users.js";
|
|
13
13
|
import { RoomsSocket } from "./utils/socket-utils.js";
|
|
14
14
|
import { createAnalyticsModule } from "./modules/analytics.js";
|
|
15
|
+
import { createActorsModule } from "./modules/actors.js";
|
|
15
16
|
/**
|
|
16
17
|
* Creates a Base44 client.
|
|
17
18
|
*
|
|
@@ -51,9 +52,27 @@ import { createAnalyticsModule } from "./modules/analytics.js";
|
|
|
51
52
|
*/
|
|
52
53
|
export function createClient(config) {
|
|
53
54
|
var _a, _b;
|
|
54
|
-
const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, } = config;
|
|
55
|
+
const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, actorsWsUrl, } = config;
|
|
55
56
|
// Normalize appBaseUrl to always be a string (empty if not provided or invalid)
|
|
56
57
|
const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";
|
|
58
|
+
// Derive the Actor WebSocket URL if not explicitly provided. Default to
|
|
59
|
+
// the app's OWN origin (the app URL proxies /parties to the backend) so the
|
|
60
|
+
// socket is same-origin with the running app, not the API host: prefer an
|
|
61
|
+
// explicit appBaseUrl, then the browser origin, then fall back to serverUrl
|
|
62
|
+
// (Node/SSR, where there's no window). Convert https:// → wss:// (http → ws)
|
|
63
|
+
// and strip the trailing slash.
|
|
64
|
+
const resolvedActorsWsUrl = (() => {
|
|
65
|
+
var _a, _b;
|
|
66
|
+
if (actorsWsUrl)
|
|
67
|
+
return actorsWsUrl.replace(/\/$/, "");
|
|
68
|
+
const appOrigin = normalizedAppBaseUrl ||
|
|
69
|
+
// React Native has a bare `window` with no `location`, so guard both.
|
|
70
|
+
(typeof window !== "undefined" ? (_b = (_a = window.location) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : "" : "");
|
|
71
|
+
return (appOrigin || serverUrl)
|
|
72
|
+
.replace(/\/$/, "")
|
|
73
|
+
.replace(/^https:\/\//, "wss://")
|
|
74
|
+
.replace(/^http:\/\//, "ws://");
|
|
75
|
+
})();
|
|
57
76
|
const socketConfig = {
|
|
58
77
|
serverUrl,
|
|
59
78
|
mountPath: "/ws-user-apps/socket.io/",
|
|
@@ -123,6 +142,12 @@ export function createClient(config) {
|
|
|
123
142
|
userAuthModule.setToken(accessToken);
|
|
124
143
|
}
|
|
125
144
|
}
|
|
145
|
+
const actorsModule = createActorsModule({
|
|
146
|
+
appId,
|
|
147
|
+
actorsWsUrl: resolvedActorsWsUrl,
|
|
148
|
+
functionsVersion,
|
|
149
|
+
getAuthToken: () => token || getAccessToken(),
|
|
150
|
+
});
|
|
126
151
|
const userModules = {
|
|
127
152
|
entities: createEntitiesModule({
|
|
128
153
|
axios: axiosClient,
|
|
@@ -160,8 +185,10 @@ export function createClient(config) {
|
|
|
160
185
|
appId,
|
|
161
186
|
userAuthModule,
|
|
162
187
|
}),
|
|
188
|
+
actors: actorsModule.module,
|
|
163
189
|
cleanup: () => {
|
|
164
190
|
userModules.analytics.cleanup();
|
|
191
|
+
actorsModule.closeAll();
|
|
165
192
|
if (socket) {
|
|
166
193
|
socket.disconnect();
|
|
167
194
|
}
|
package/dist/client.types.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ import type { AgentsModule } from "./modules/agents.types.js";
|
|
|
8
8
|
import type { AiGatewayModule } from "./modules/ai-gateway.types.js";
|
|
9
9
|
import type { AppLogsModule } from "./modules/app-logs.types.js";
|
|
10
10
|
import type { AnalyticsModule } from "./modules/analytics.types.js";
|
|
11
|
+
import type { ActorsModule } from "./modules/actors.types.js";
|
|
11
12
|
/**
|
|
12
13
|
* Options for creating a Base44 client.
|
|
13
14
|
*/
|
|
@@ -73,6 +74,16 @@ export interface CreateClientConfig {
|
|
|
73
74
|
* Additional client options.
|
|
74
75
|
*/
|
|
75
76
|
options?: CreateClientOptions;
|
|
77
|
+
/**
|
|
78
|
+
* Base WebSocket URL for Actor connections.
|
|
79
|
+
*
|
|
80
|
+
* Defaults to the app's own origin (`appBaseUrl`, else the browser's
|
|
81
|
+
* `window.location.origin`, else `serverUrl`) with `https://` replaced by
|
|
82
|
+
* `wss://` (or `http://` by `ws://`) — so the Actor socket is same-origin
|
|
83
|
+
* with the running app, which proxies `/parties` to the backend dispatcher.
|
|
84
|
+
* Override only when the Actor host differs from the app origin.
|
|
85
|
+
*/
|
|
86
|
+
actorsWsUrl?: string;
|
|
76
87
|
}
|
|
77
88
|
/**
|
|
78
89
|
* The Base44 client instance.
|
|
@@ -88,6 +99,8 @@ export interface Base44Client {
|
|
|
88
99
|
analytics: AnalyticsModule;
|
|
89
100
|
/** {@link AppLogsModule | App logs module} for tracking app usage. */
|
|
90
101
|
appLogs: AppLogsModule;
|
|
102
|
+
/** {@link ActorsModule | Actors module} for subscribing to and sending messages via Cloudflare Durable Object-backed Actors. */
|
|
103
|
+
actors: ActorsModule;
|
|
91
104
|
/** {@link AuthModule | Auth module} for user authentication and management. */
|
|
92
105
|
auth: AuthModule;
|
|
93
106
|
/** {@link UserConnectorsModule | Connectors module} for app-user OAuth flows. */
|
|
@@ -139,9 +152,7 @@ export interface Base44Client {
|
|
|
139
152
|
functions: FunctionsModule;
|
|
140
153
|
/** {@link IntegrationsModule | Integrations module} with elevated permissions. */
|
|
141
154
|
integrations: IntegrationsModule;
|
|
142
|
-
/** {@link SsoModule | SSO module} for generating SSO tokens.
|
|
143
|
-
* @internal
|
|
144
|
-
*/
|
|
155
|
+
/** {@link SsoModule | SSO module} for generating SSO tokens. */
|
|
145
156
|
sso: SsoModule;
|
|
146
157
|
/** Cleanup function to disconnect WebSocket connections. */
|
|
147
158
|
cleanup: () => void;
|
package/dist/index.d.ts
CHANGED
|
@@ -11,7 +11,9 @@ export type { FunctionsModule, FunctionName, FunctionNameRegistry, } from "./mod
|
|
|
11
11
|
export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
|
|
12
12
|
export type { AiGatewayModule, AiGatewayConnection, } from "./modules/ai-gateway.types.js";
|
|
13
13
|
export type { AppLogsModule } from "./modules/app-logs.types.js";
|
|
14
|
+
export type { ActorsModule, ActorClient, ActorNameRegistry, ActorRegistry, } from "./modules/actors.types.js";
|
|
14
15
|
export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
|
|
16
|
+
export { Actor, type Conn } from "./actor.js";
|
|
15
17
|
export type { ConnectorsModule, UserConnectorsModule, } from "./modules/connectors.types.js";
|
|
16
18
|
export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
|
|
17
19
|
export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
|
package/dist/index.js
CHANGED
|
@@ -3,3 +3,4 @@ import { Base44Error } from "./utils/axios-client.js";
|
|
|
3
3
|
import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, } from "./utils/auth-utils.js";
|
|
4
4
|
export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
|
|
5
5
|
export * from "./types.js";
|
|
6
|
+
export { Actor } from "./actor.js";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ActorRoom } from "./actors.types.js";
|
|
2
|
+
interface ActorsConfig {
|
|
3
|
+
appId: string;
|
|
4
|
+
/** Current user access token, if authenticated. Rides the WS query so the
|
|
5
|
+
* platform proxy can authenticate the connection; anonymous connects omit it. */
|
|
6
|
+
getAuthToken(): string | null | undefined;
|
|
7
|
+
/** Same semantics as function calls: editors with a non-prod version get the
|
|
8
|
+
* draft actor script; everyone else gets the published one. */
|
|
9
|
+
functionsVersion?: string;
|
|
10
|
+
actorsWsUrl: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function createActorsModule(config: ActorsConfig): {
|
|
13
|
+
module: Record<string, (instanceId: string) => ActorRoom>;
|
|
14
|
+
closeAll: () => void;
|
|
15
|
+
};
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import PartySocket from "partysocket";
|
|
2
|
+
// Heartbeat / half-open detection: PartySocket only reconnects on a close/error
|
|
3
|
+
// event, so ping periodically and force a reconnect if nothing returns in DEAD_MS.
|
|
4
|
+
const PING_MS = 1000;
|
|
5
|
+
const DEAD_MS = 3000;
|
|
6
|
+
class Room {
|
|
7
|
+
constructor(actorName, instanceId, config, onClose) {
|
|
8
|
+
this.actorName = actorName;
|
|
9
|
+
this.instanceId = instanceId;
|
|
10
|
+
this.config = config;
|
|
11
|
+
this.onClose = onClose;
|
|
12
|
+
this.ws = null;
|
|
13
|
+
this.listeners = new Set();
|
|
14
|
+
this.heartbeat = null;
|
|
15
|
+
this.connId = null;
|
|
16
|
+
}
|
|
17
|
+
get id() {
|
|
18
|
+
if (!this.connId) {
|
|
19
|
+
throw new Error(`${this.actorName}:${this.instanceId}: connect() before reading id`);
|
|
20
|
+
}
|
|
21
|
+
return this.connId;
|
|
22
|
+
}
|
|
23
|
+
connect(options) {
|
|
24
|
+
var _a;
|
|
25
|
+
if (this.ws)
|
|
26
|
+
return this;
|
|
27
|
+
// The client picks its own conn id; it becomes _pk → the actor's conn.id.
|
|
28
|
+
const connId = (_a = options === null || options === void 0 ? void 0 : options.id) !== null && _a !== void 0 ? _a : crypto.randomUUID();
|
|
29
|
+
this.connId = connId;
|
|
30
|
+
const ws = new PartySocket({
|
|
31
|
+
host: this.config.actorsWsUrl,
|
|
32
|
+
party: this.actorName,
|
|
33
|
+
room: this.instanceId,
|
|
34
|
+
id: connId,
|
|
35
|
+
// Re-read on every (re)connect so a login/logout is picked up.
|
|
36
|
+
query: () => {
|
|
37
|
+
const token = this.config.getAuthToken();
|
|
38
|
+
return {
|
|
39
|
+
app_id: this.config.appId,
|
|
40
|
+
handler: this.actorName,
|
|
41
|
+
...(token ? { token } : {}),
|
|
42
|
+
...(this.config.functionsVersion ? { fv: this.config.functionsVersion } : {}),
|
|
43
|
+
};
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
this.ws = ws;
|
|
47
|
+
let lastMsg = Date.now();
|
|
48
|
+
const bumpAlive = () => { lastMsg = Date.now(); };
|
|
49
|
+
ws.addEventListener("open", bumpAlive);
|
|
50
|
+
ws.addEventListener("message", (ev) => {
|
|
51
|
+
bumpAlive();
|
|
52
|
+
let data;
|
|
53
|
+
try {
|
|
54
|
+
data = JSON.parse(ev.data);
|
|
55
|
+
}
|
|
56
|
+
catch (_a) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const msgType = data && typeof data === "object" ? data.type : undefined;
|
|
60
|
+
if (msgType === "__pong")
|
|
61
|
+
return;
|
|
62
|
+
for (const listener of this.listeners)
|
|
63
|
+
listener(data);
|
|
64
|
+
});
|
|
65
|
+
this.heartbeat = setInterval(() => {
|
|
66
|
+
if (Date.now() - lastMsg > DEAD_MS) {
|
|
67
|
+
bumpAlive(); // avoid a reconnect storm while the new socket comes up
|
|
68
|
+
ws.reconnect();
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
// The deployed shim echoes __ping → __pong (base44-userapp-bundler
|
|
73
|
+
// shim/actor.ts); without that, an idle room reconnects every DEAD_MS.
|
|
74
|
+
ws.send(JSON.stringify({ type: "__ping" }));
|
|
75
|
+
}
|
|
76
|
+
catch (_a) {
|
|
77
|
+
// not open; the watchdog above will reconnect
|
|
78
|
+
}
|
|
79
|
+
}, PING_MS);
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
subscribe(callback) {
|
|
83
|
+
if (!this.ws) {
|
|
84
|
+
throw new Error(`${this.actorName}:${this.instanceId}: connect() before subscribe()`);
|
|
85
|
+
}
|
|
86
|
+
this.listeners.add(callback);
|
|
87
|
+
return {
|
|
88
|
+
unsubscribe: () => { this.listeners.delete(callback); },
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
send(data) {
|
|
92
|
+
if (!this.ws) {
|
|
93
|
+
throw new Error(`${this.actorName}:${this.instanceId}: connect() before send()`);
|
|
94
|
+
}
|
|
95
|
+
this.ws.send(JSON.stringify(data));
|
|
96
|
+
}
|
|
97
|
+
close() {
|
|
98
|
+
var _a, _b;
|
|
99
|
+
if (this.heartbeat) {
|
|
100
|
+
clearInterval(this.heartbeat);
|
|
101
|
+
this.heartbeat = null;
|
|
102
|
+
}
|
|
103
|
+
this.listeners.clear();
|
|
104
|
+
(_a = this.ws) === null || _a === void 0 ? void 0 : _a.close();
|
|
105
|
+
this.ws = null;
|
|
106
|
+
this.connId = null;
|
|
107
|
+
(_b = this.onClose) === null || _b === void 0 ? void 0 : _b.call(this);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
export function createActorsModule(config) {
|
|
111
|
+
// Live rooms this client opened, so client.cleanup() can reclaim any the app
|
|
112
|
+
// forgot to close() (each room removes itself here on close).
|
|
113
|
+
const rooms = new Set();
|
|
114
|
+
const module = new Proxy({}, {
|
|
115
|
+
get(_, key) {
|
|
116
|
+
// Symbols and `then` resolve to undefined (so the module isn't mistaken
|
|
117
|
+
// for a thenable when awaited); any string key is an actor name.
|
|
118
|
+
if (typeof key !== "string" || key === "then")
|
|
119
|
+
return undefined;
|
|
120
|
+
return (instanceId) => {
|
|
121
|
+
const room = new Room(key, instanceId, config, () => rooms.delete(room));
|
|
122
|
+
rooms.add(room);
|
|
123
|
+
return room;
|
|
124
|
+
};
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
return {
|
|
128
|
+
module,
|
|
129
|
+
closeAll: () => {
|
|
130
|
+
for (const room of [...rooms])
|
|
131
|
+
room.close();
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extend this interface to add typed `subscribe` callbacks and `send` payloads
|
|
3
|
+
* for your deployed Actors.
|
|
4
|
+
*
|
|
5
|
+
* This is separate from {@link ActorNameRegistry} (which is auto-generated
|
|
6
|
+
* by `base44 types generate`), so there are no conflicts.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* declare module "@base44/sdk" {
|
|
11
|
+
* interface ActorRegistry {
|
|
12
|
+
* ChatRoom: {
|
|
13
|
+
* toClient: { type: "joined" | "left" | "message"; userId?: string; from?: string; text?: string };
|
|
14
|
+
* toServer: { type: "message"; text: string };
|
|
15
|
+
* };
|
|
16
|
+
* }
|
|
17
|
+
* }
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export interface ActorRegistry {
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Auto-populated by `base44 types generate` with the names of your deployed actors.
|
|
24
|
+
* Do not edit this interface manually — use {@link ActorRegistry} for message types.
|
|
25
|
+
*/
|
|
26
|
+
export interface ActorNameRegistry {
|
|
27
|
+
}
|
|
28
|
+
type AllActorNames = keyof ActorRegistry | keyof ActorNameRegistry;
|
|
29
|
+
type ToClientFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
|
|
30
|
+
toClient: infer I;
|
|
31
|
+
} ? I : unknown : unknown;
|
|
32
|
+
type ToServerFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
|
|
33
|
+
toServer: infer O;
|
|
34
|
+
} ? O : unknown : unknown;
|
|
35
|
+
/** Options for {@link ActorRoom.connect}. */
|
|
36
|
+
export interface ActorConnectOptions {
|
|
37
|
+
/**
|
|
38
|
+
* The connection id — becomes the actor's `conn.id`. Supply a stable value
|
|
39
|
+
* (e.g. persisted per tab) so a reconnect reuses the same server-side
|
|
40
|
+
* identity; omit for an auto-generated per-connection id.
|
|
41
|
+
*/
|
|
42
|
+
id?: string;
|
|
43
|
+
}
|
|
44
|
+
/** Handle for one listener registered via {@link ActorRoom.subscribe}. */
|
|
45
|
+
export interface ActorSubscription {
|
|
46
|
+
/** Remove this listener; other listeners and the socket stay live. */
|
|
47
|
+
unsubscribe(): void;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A single actor room. Obtained from {@link ActorClient} (`actors.MyActor(id)`)
|
|
51
|
+
* and made live with {@link connect}. The handle IS the connection: one socket,
|
|
52
|
+
* any number of {@link subscribe} listeners.
|
|
53
|
+
*/
|
|
54
|
+
export interface ActorRoom<N extends string = string> {
|
|
55
|
+
/** The connection id (the value the actor sees as `conn.id`). Throws before {@link connect}. */
|
|
56
|
+
readonly id: string;
|
|
57
|
+
/** Open the WebSocket (required before subscribe/send). Idempotent; returns this. */
|
|
58
|
+
connect(options?: ActorConnectOptions): this;
|
|
59
|
+
/** Register a message listener. Multiple are allowed; returns a per-listener unsubscribe. */
|
|
60
|
+
subscribe(callback: (data: ToClientFor<N>) => void): ActorSubscription;
|
|
61
|
+
/** Send a message. Throws before {@link connect}; buffered by the socket until open. */
|
|
62
|
+
send(data: ToServerFor<N>): void;
|
|
63
|
+
/** Tear down the socket, heartbeat, and all listeners. */
|
|
64
|
+
close(): void;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Client for a single named Actor — call it with a room id to get an
|
|
68
|
+
* {@link ActorRoom}. Typed automatically when the actor is registered in
|
|
69
|
+
* {@link ActorRegistry}.
|
|
70
|
+
*/
|
|
71
|
+
export interface ActorClient<N extends string = string> {
|
|
72
|
+
(instanceId: string): ActorRoom<N>;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The actors module provides access to Cloudflare Durable Object-backed
|
|
76
|
+
* Actors deployed by the Base44 platform.
|
|
77
|
+
*
|
|
78
|
+
* ```typescript
|
|
79
|
+
* const room = base44.actors.MyActor("room-1").connect();
|
|
80
|
+
* const sub = room.subscribe((msg) => console.log(msg)); // typed via ActorRegistry
|
|
81
|
+
* room.send({ type: "message", text: "hi" });
|
|
82
|
+
* sub.unsubscribe();
|
|
83
|
+
* room.close();
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export type ActorsModule = {
|
|
87
|
+
[K in AllActorNames]: K extends keyof ActorRegistry ? ActorClient<string & K> : ActorClient;
|
|
88
|
+
} & Record<string, ActorClient>;
|
|
89
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* Contains the base URL and bearer token to use with any OpenAI-compatible
|
|
5
|
-
* client pointed at the Base44 AI Gateway.
|
|
2
|
+
* Connection details for the Base44 AI Gateway.
|
|
6
3
|
*/
|
|
7
4
|
export interface AiGatewayConnection {
|
|
8
|
-
/** Base URL of the gateway's OpenAI-compatible endpoint. */
|
|
5
|
+
/** Base URL of the gateway's OpenAI-compatible Chat Completions endpoint. */
|
|
9
6
|
baseURL: string;
|
|
10
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Bearer token that authenticates the request. Empty string when the caller is
|
|
9
|
+
* unauthenticated.
|
|
10
|
+
*/
|
|
11
11
|
token: string;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
@@ -25,13 +25,45 @@ export interface AiGatewayModuleConfig {
|
|
|
25
25
|
/**
|
|
26
26
|
* AI Gateway module for calling Base44's managed AI models from your own code.
|
|
27
27
|
*
|
|
28
|
-
*
|
|
29
|
-
* OpenAI-compatible
|
|
30
|
-
*
|
|
31
|
-
*
|
|
28
|
+
* `connection()` hands you a `baseURL` and `token` that authenticate as your
|
|
29
|
+
* Base44 app. An OpenAI-compatible client is any library, such as the `openai`
|
|
30
|
+
* SDK or the Vercel AI SDK, that has the same request and response format
|
|
31
|
+
* as OpenAI's Chat Completions API and lets you point it at a custom `baseURL`
|
|
32
|
+
* instead of OpenAI's own servers. Pass `connection()`'s values to one of
|
|
33
|
+
* these clients and it works against Base44's gateway exactly as it would
|
|
34
|
+
* against the provider directly, no separate account, API key, or billing
|
|
35
|
+
* setup with the underlying model provider required.
|
|
36
|
+
*
|
|
37
|
+
* Call `connection()` from a backend function rather than the browser. This
|
|
38
|
+
* keeps your instructions, tools, and business logic server-side, and lets
|
|
39
|
+
* you enforce your own auth, rate, and spend limits around the call. The
|
|
40
|
+
* `token` it returns is the caller's regular session token, the same one
|
|
41
|
+
* used for every other SDK call.
|
|
42
|
+
*
|
|
43
|
+
* ## Models
|
|
44
|
+
*
|
|
45
|
+
* You can use any of the [models available through `InvokeLLM`](/developers/references/sdk/docs/type-aliases/integrations#invokellm).
|
|
46
|
+
* Pass `'automatic'` to let Base44 choose one, or pin a specific model such
|
|
47
|
+
* as `'claude_sonnet_4_6'`, `'gpt_5_5'`, or `'gemini_3_1_pro'`.
|
|
48
|
+
*
|
|
49
|
+
* ## Authentication Modes
|
|
50
|
+
*
|
|
51
|
+
* There's no permission difference between modes. Both just determine which
|
|
52
|
+
* token `connection()` returns:
|
|
53
|
+
*
|
|
54
|
+
* - **User authentication** (`base44.aiGateway`): Returns the signed-in app user's token.
|
|
55
|
+
* - **Service role authentication** (`base44.asServiceRole.aiGateway`): Returns the service-role token instead, for calling the gateway when there's no signed-in user, such as from a scheduled automation.
|
|
56
|
+
*
|
|
57
|
+
* ## Billing and limits
|
|
58
|
+
*
|
|
59
|
+
* Requests are billed to your app's credit quota, which is the same shared
|
|
60
|
+
* quota your app's built-in AI features use, and isn't split per user. If the
|
|
61
|
+
* app runs out of credits, the gateway stops working for every user of the
|
|
62
|
+
* app until the quota resets. A request is rejected before the model runs if
|
|
63
|
+
* the app is out of credits. If you need to cap usage per user, build that
|
|
64
|
+
* check yourself, for example by tracking calls per user in your own entity.
|
|
32
65
|
*
|
|
33
|
-
*
|
|
34
|
-
* service-role token via `base44.asServiceRole.aiGateway`.
|
|
66
|
+
* Streaming responses aren't supported yet, so leave `stream` unset on your requests.
|
|
35
67
|
*/
|
|
36
68
|
export interface AiGatewayModule {
|
|
37
69
|
/**
|
|
@@ -39,19 +71,38 @@ export interface AiGatewayModule {
|
|
|
39
71
|
*
|
|
40
72
|
* Returns the `baseURL` and `token` to pass to any OpenAI-compatible client.
|
|
41
73
|
*
|
|
42
|
-
* The `token` is the current caller's bearer token: the app user's token for
|
|
43
|
-
* `base44.aiGateway`, or the service-role token for `base44.asServiceRole.aiGateway`.
|
|
44
|
-
* When the caller is unauthenticated, `token` is an empty string.
|
|
45
|
-
*
|
|
46
74
|
* @returns The gateway {@linkcode AiGatewayConnection | connection} (`baseURL` and `token`).
|
|
47
75
|
*
|
|
48
76
|
* @example
|
|
49
77
|
* ```typescript
|
|
78
|
+
* // Call a model directly
|
|
79
|
+
* import { createClientFromRequest } from "@base44/sdk";
|
|
80
|
+
* import OpenAI from "openai";
|
|
81
|
+
*
|
|
82
|
+
* // Runs inside a backend function
|
|
83
|
+
* const base44 = createClientFromRequest(request);
|
|
84
|
+
* const { baseURL, token } = base44.aiGateway.connection();
|
|
85
|
+
* const openai = new OpenAI({ baseURL, apiKey: token });
|
|
86
|
+
*
|
|
87
|
+
* const response = await openai.chat.completions.create({
|
|
88
|
+
* model: "automatic",
|
|
89
|
+
* messages: [{ role: "user", content: "Summarize this week's top support tickets." }],
|
|
90
|
+
* });
|
|
91
|
+
*
|
|
92
|
+
* console.log(response.choices[0].message.content);
|
|
93
|
+
* ```
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```typescript
|
|
97
|
+
* // Use a tool-calling agent
|
|
98
|
+
* import { createClientFromRequest } from "@base44/sdk";
|
|
50
99
|
* import { ToolLoopAgent, tool, stepCountIs, hasToolCall } from "ai";
|
|
51
100
|
* import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
52
101
|
* import { z } from "zod";
|
|
53
102
|
*
|
|
54
|
-
*
|
|
103
|
+
* // Runs inside a backend function, reviewing a return request
|
|
104
|
+
* const base44 = createClientFromRequest(request);
|
|
105
|
+
* const returnRequest = await base44.entities.ReturnRequest.get(returnId);
|
|
55
106
|
* const { baseURL, token } = base44.aiGateway.connection();
|
|
56
107
|
* // Point any OpenAI-compatible client at `baseURL` with `apiKey: token`.
|
|
57
108
|
* const models = createOpenAICompatible({ name: "base44", baseURL, apiKey: token });
|
|
@@ -66,7 +117,7 @@ export interface AiGatewayModule {
|
|
|
66
117
|
* description: "This customer's past orders, optionally filtered by status",
|
|
67
118
|
* inputSchema: z.object({ status: z.string().optional() }),
|
|
68
119
|
* execute: ({ status }) => {
|
|
69
|
-
* const query = { customer_email:
|
|
120
|
+
* const query = { customer_email: returnRequest.customer_email };
|
|
70
121
|
* if (status) query.status = status;
|
|
71
122
|
* return base44.entities.Order.filter(query, "-created_date", 50);
|
|
72
123
|
* },
|
|
@@ -81,7 +132,7 @@ export interface AiGatewayModule {
|
|
|
81
132
|
* stopWhen: [stepCountIs(8), hasToolCall("submitVerdict")],
|
|
82
133
|
* });
|
|
83
134
|
*
|
|
84
|
-
* await agent.generate({ prompt: `Review this return request: ${JSON.stringify(
|
|
135
|
+
* await agent.generate({ prompt: `Review this return request: ${JSON.stringify(returnRequest)}` });
|
|
85
136
|
* ```
|
|
86
137
|
*/
|
|
87
138
|
connection(): AiGatewayConnection;
|
package/dist/modules/sso.d.ts
CHANGED
package/dist/modules/sso.js
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @param axios - Axios instance
|
|
5
5
|
* @param appId - Application ID
|
|
6
|
-
* @param userToken - User authentication token
|
|
7
6
|
* @returns SSO module with authentication methods
|
|
8
7
|
* @internal
|
|
9
8
|
*/
|
|
@@ -14,5 +13,10 @@ export function createSsoModule(axios, appId) {
|
|
|
14
13
|
const url = `/apps/${appId}/auth/sso/accesstoken/${userid}`;
|
|
15
14
|
return axios.get(url);
|
|
16
15
|
},
|
|
16
|
+
// Get the stored SSO OIDC ID token for a specific user
|
|
17
|
+
async getIdToken(userid) {
|
|
18
|
+
const url = `/apps/${appId}/auth/sso/idtoken/${userid}`;
|
|
19
|
+
return axios.get(url);
|
|
20
|
+
},
|
|
17
21
|
};
|
|
18
22
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Response from SSO access token endpoint.
|
|
3
|
-
* @internal
|
|
4
3
|
*/
|
|
5
4
|
export interface SsoAccessTokenResponse {
|
|
6
5
|
access_token: string;
|
|
@@ -8,37 +7,68 @@ export interface SsoAccessTokenResponse {
|
|
|
8
7
|
/**
|
|
9
8
|
* SSO (Single Sign-On) module for managing SSO authentication.
|
|
10
9
|
*
|
|
11
|
-
* This module provides methods for retrieving SSO
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* This module provides methods for retrieving SSO tokens for users. These
|
|
11
|
+
* tokens allow you to authenticate Base44 users with external systems or
|
|
12
|
+
* services.
|
|
14
13
|
*
|
|
15
14
|
* 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.
|
|
16
|
-
*
|
|
17
|
-
* @internal
|
|
18
|
-
*
|
|
19
|
-
* @example
|
|
20
|
-
* ```typescript
|
|
21
|
-
* // Access SSO module with service role
|
|
22
|
-
* const response = await base44.asServiceRole.sso.getAccessToken('user_123');
|
|
23
|
-
* console.log(response.data.access_token);
|
|
24
|
-
* ```
|
|
25
15
|
*/
|
|
26
16
|
export interface SsoModule {
|
|
27
17
|
/**
|
|
28
|
-
* Gets SSO access token for
|
|
18
|
+
* Gets an SSO access token for the user who made the current request.
|
|
29
19
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
20
|
+
* Use this token to authenticate the user with external systems or services.
|
|
21
|
+
* This only works for that same user. Create the client with
|
|
22
|
+
* {@link createClientFromRequest} so it acts on behalf of the request's user,
|
|
23
|
+
* then pass that user's ID as `userid`. If `userid` is any other user, the
|
|
24
|
+
* call fails. An expired token is refreshed automatically when a refresh token
|
|
25
|
+
* is available.
|
|
32
26
|
*
|
|
33
|
-
* @param userid - The user
|
|
27
|
+
* @param userid - The ID of the user who made the current request, such as the
|
|
28
|
+
* `id` returned by {@link AuthModule | base44.auth.me()}.
|
|
34
29
|
* @returns Promise resolving to the SSO access token response.
|
|
35
30
|
*
|
|
36
31
|
* @example
|
|
37
32
|
* ```typescript
|
|
38
|
-
* // Get SSO access token
|
|
39
|
-
*
|
|
40
|
-
*
|
|
33
|
+
* // Get the user's SSO access token to call an external system
|
|
34
|
+
* import { createClientFromRequest } from 'npm:@base44/sdk';
|
|
35
|
+
*
|
|
36
|
+
* Deno.serve(async (req) => {
|
|
37
|
+
* const base44 = createClientFromRequest(req);
|
|
38
|
+
* const user = await base44.auth.me();
|
|
39
|
+
* const { access_token } = await base44.asServiceRole.sso.getAccessToken(user.id);
|
|
40
|
+
*
|
|
41
|
+
* return Response.json({ access_token });
|
|
42
|
+
* });
|
|
41
43
|
* ```
|
|
42
44
|
*/
|
|
43
45
|
getAccessToken(userid: string): Promise<SsoAccessTokenResponse>;
|
|
46
|
+
/**
|
|
47
|
+
* Gets the stored SSO OIDC ID token for the user who made the current request.
|
|
48
|
+
*
|
|
49
|
+
* This only works for that same user, not for arbitrary users. Create the
|
|
50
|
+
* client with {@link createClientFromRequest} so it acts on behalf of the
|
|
51
|
+
* request's user, then pass that user's ID as `userid`. If `userid` is any
|
|
52
|
+
* other user, the call fails. The stored token is returned as-is and is never
|
|
53
|
+
* refreshed, so the call fails if the token has already expired.
|
|
54
|
+
*
|
|
55
|
+
* @param userid - The ID of the user who made the current request, such as the
|
|
56
|
+
* `id` returned by {@link AuthModule | base44.auth.me()}.
|
|
57
|
+
* @returns Promise resolving to the raw ID-token string.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // Get the user's ID token to read identity claims such as email
|
|
62
|
+
* import { createClientFromRequest } from 'npm:@base44/sdk';
|
|
63
|
+
*
|
|
64
|
+
* Deno.serve(async (req) => {
|
|
65
|
+
* const base44 = createClientFromRequest(req);
|
|
66
|
+
* const user = await base44.auth.me();
|
|
67
|
+
* const idToken = await base44.asServiceRole.sso.getIdToken(user.id);
|
|
68
|
+
*
|
|
69
|
+
* return Response.json({ idToken });
|
|
70
|
+
* });
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
getIdToken(userid: string): Promise<string>;
|
|
44
74
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@base44-preview/sdk",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.40-pr.212.2b700ea",
|
|
4
4
|
"description": "JavaScript SDK for Base44 API",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"create-docs:process": "node scripts/mintlify-post-processing/file-processing/file-processing.js"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"axios": "^1.
|
|
29
|
+
"axios": "^1.18.1",
|
|
30
|
+
"partysocket": "^0.0.23",
|
|
30
31
|
"socket.io-client": "^4.8.3",
|
|
31
32
|
"uuid": "^13.0.2"
|
|
32
33
|
},
|