@base44-preview/sdk 0.8.60-pr.377.428760d → 0.8.60-pr.377.d5ecb0f

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 CHANGED
@@ -17,22 +17,13 @@ export type ActorConnectionIdentity = Readonly<{
17
17
  type: "anonymous";
18
18
  anonymousId: string;
19
19
  }>;
20
- /** Who called one of the actor's callable methods: a client, or the app's server
21
- * code calling with the service role (`service`). */
22
- export type ActorCallIdentity = ActorConnectionIdentity | Readonly<{
20
+ /** Who sent a request to {@link Actor.handleRequest}: a client, or the app's
21
+ * server code posting with the service role (`service`). */
22
+ export type ActorRequestIdentity = ActorConnectionIdentity | Readonly<{
23
23
  type: "service";
24
24
  }>;
25
- /** What a callable method receives besides its args. */
26
- export interface ActorCallContext {
27
- identity: ActorCallIdentity;
28
- /** Carries the caller's own credential, so `createClientFromRequest(request)` acts
29
- * as the caller, as in a backend function. Don't store it. */
30
- request: Request;
31
- }
32
- /** Throw from a callable method to refuse the call with a 4xx status. */
33
- export declare class ActorError extends Error {
34
- readonly status: number;
35
- constructor(status: number, message: string);
25
+ export interface ActorRequestContext {
26
+ identity: ActorRequestIdentity;
36
27
  }
37
28
  /**
38
29
  * A single client connection. `Send` is the message type this connection accepts
@@ -88,25 +79,24 @@ export declare abstract class Actor<Incoming = unknown, Outgoing = unknown> {
88
79
  */
89
80
  protected handleWake(_key: string): void | Promise<void>;
90
81
  /**
91
- * The methods a caller may run on a session, as `base44.actors.<Name>(id).<method>(args)`
92
- * from a client or `base44.asServiceRole.actors.<Name>(id).<method>(args)` from server code.
93
- * Nothing else is callable, and a hook-shaped name (`handle*`, `on*`, `_*`) never is.
82
+ * Optional handler for requests sent to this session with `post()`, by a
83
+ * client or by the app's server code. Runs even when no client is connected,
84
+ * and can {@link broadcast} to the ones that are. Check `identity` before
85
+ * acting: a client can post to any session it can name.
94
86
  *
95
- * Each runs as `method(args, { identity, request })` (see {@link ActorCallContext}), even
96
- * when no client is connected, and can {@link broadcast} to the ones that are. Check
97
- * `identity` before acting: a client can call a method on any session it can name. The
98
- * return value is the caller's reply; throw an {@link ActorError} to refuse with a 4xx.
87
+ * Return a `Response` for the caller; returning nothing answers 204, and a
88
+ * throw answers 500. An actor without this method refuses requests with 404.
99
89
  *
100
90
  * @example
101
91
  * ```ts
102
- * static callable = ["videoReady"];
103
- * async videoReady(args, { identity }) {
104
- * if (identity.type !== "service") throw new ActorError(403, "Forbidden");
105
- * this.broadcast({ type: "video", ...args });
92
+ * async handleRequest(request, { identity }) {
93
+ * if (identity.type !== "service") return new Response("Forbidden", { status: 403 });
94
+ * const result = await request.json();
95
+ * this.broadcast({ type: "result", result });
106
96
  * }
107
97
  * ```
108
98
  */
109
- static callable?: readonly string[];
99
+ protected handleRequest?(request: Request, context: ActorRequestContext): Response | void | Promise<Response | void>;
110
100
  /**
111
101
  * Arm a one-shot wake at `at` (epoch ms or a `Date`), identified by `key`.
112
102
  * When it comes due the platform calls {@link handleWake} with this `key`.
package/dist/actor.js CHANGED
@@ -8,14 +8,6 @@
8
8
  * At deploy time the bundler replaces this import with the compiled
9
9
  * Cloudflare Durable Object implementation — this file provides types only.
10
10
  */
11
- /** Throw from a callable method to refuse the call with a 4xx status. */
12
- export class ActorError extends Error {
13
- constructor(status, message) {
14
- super(message);
15
- this.status = status;
16
- this.name = "ActorError";
17
- }
18
- }
19
11
  /**
20
12
  * Base class for an Actor.
21
13
  *
package/dist/client.js CHANGED
@@ -122,10 +122,10 @@ export function createClient(config) {
122
122
  interceptResponses: false,
123
123
  });
124
124
  // The backend authenticates the caller from the axios client's token (or the
125
- // anonymous id it adds in a browser) and relays the call to the room.
126
- const actorMethodCaller = (client) => async (actorName, room, method, args) => {
125
+ // anonymous id it adds in a browser) and relays the request to the room.
126
+ const actorRequestPoster = (client) => async (actorName, room, body) => {
127
127
  var _a;
128
- const response = await client.post(`/apps/${appId}/actors/${encodeURIComponent(actorName)}/rooms/${encodeURIComponent(room)}/requests`, JSON.stringify({ method, args }), {
128
+ const response = await client.post(`/apps/${appId}/actors/${encodeURIComponent(actorName)}/rooms/${encodeURIComponent(room)}/requests`, JSON.stringify(body !== null && body !== void 0 ? body : null), {
129
129
  headers: {
130
130
  "Content-Type": "application/json",
131
131
  // Draft vs published copy, as for a connection.
@@ -182,7 +182,7 @@ export function createClient(config) {
182
182
  },
183
183
  transport: options === null || options === void 0 ? void 0 : options.actorsTransport,
184
184
  onMintError: options === null || options === void 0 ? void 0 : options.onError,
185
- callMethod: actorMethodCaller(axiosClient),
185
+ postRequest: actorRequestPoster(axiosClient),
186
186
  });
187
187
  const userModules = {
188
188
  entities: createEntitiesModule({
@@ -275,7 +275,7 @@ export function createClient(config) {
275
275
  }),
276
276
  appLogs: createAppLogsModule(serviceRoleAxiosClient, appId),
277
277
  payments: createServiceRolePaymentsModule(serviceRoleAxiosClient, appId),
278
- actors: createServiceRoleActorsModule(actorMethodCaller(serviceRoleAxiosClient)),
278
+ actors: createServiceRoleActorsModule(actorRequestPoster(serviceRoleAxiosClient)),
279
279
  cleanup: () => {
280
280
  if (socket) {
281
281
  socket.disconnect();
package/dist/index.d.ts CHANGED
@@ -12,12 +12,12 @@ export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, Age
12
12
  export type { AiGatewayModule, AiGatewayConnection, AiGatewayConnectionOptions, } from "./modules/ai-gateway.types.js";
13
13
  export type { AppLogsModule } from "./modules/app-logs.types.js";
14
14
  export type { AppModule, AppPublicSettings, AppPublicSettingsResponse, } from "./modules/app.types.js";
15
- export type { ActorsModule, ActorClient, ActorRef, Connection, ActorSubscription, ActorConnectOptions, ActorNameRegistry, ActorRegistry, ActorConnectable, ActorMethods, ServiceRoleActorRef, ServiceRoleActorsModule, } from "./modules/actors.types.js";
15
+ export type { ActorsModule, ActorClient, ActorRef, Connection, ActorSubscription, ActorConnectOptions, ActorNameRegistry, ActorRegistry, ServiceRoleActorRef, ServiceRoleActorsModule, } from "./modules/actors.types.js";
16
16
  export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
17
17
  export type { PaymentsModule, ServiceRolePaymentsModule, PaymentsErrorCode, PaymentsRecurringFrequency, CheckoutBuyer, CheckoutFreeTrial, CheckoutItem, CheckoutItemRecurring, CheckoutPresentation, CheckoutShipping, CheckoutElement, CheckoutMount, MountableCheckout, CreateCheckoutParams, CreateCheckoutResult, CompleteCheckoutResult, EmbeddedCheckout, PayPalCheckoutOnClick, PayPalEmbeddedCheckout, StripeEmbeddedCheckout, MountCheckoutOptions, ListPurchasesParams, ServiceRoleListPurchasesParams, ListPurchasesResult, Purchase, PurchaseItem, PurchaseStatus, RefundParams, ShippingAddress, RefundResult, CancelSubscriptionOptions, SubscriptionResult, } from "./modules/payments.types.js";
18
18
  export type { BrowserModule, BrowserSession, BrowserSessionOptions, } from "./modules/browser.types.js";
19
19
  export type { VoiceModule, VoiceSession, VoiceSessionMessage, VoiceSessionOptions, } from "./modules/voice.types.js";
20
- export { Actor, type Conn, type ActorConnectionIdentity, ActorError, type ActorCallIdentity, type ActorCallContext, } from "./actor.js";
20
+ export { Actor, type Conn, type ActorConnectionIdentity, type ActorRequestIdentity, type ActorRequestContext, } from "./actor.js";
21
21
  export type { ConnectorsModule, UserConnectorsModule, ConnectorApiRequest, ConnectorApiResponse, ConnectorApiResponsePhase, } from "./modules/connectors.types.js";
22
22
  export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
23
23
  export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
package/dist/index.js CHANGED
@@ -3,4 +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, ActorError, } from "./actor.js";
6
+ export { Actor, } from "./actor.js";
@@ -1,6 +1,6 @@
1
1
  import type { ActorRef, ServiceRoleActorRef } from "./actors.types.js";
2
- /** Calls one of a session's callable methods; resolves to its JSON reply. */
3
- export type CallActorMethod = (actorName: string, room: string, method: string, args: unknown) => Promise<unknown>;
2
+ /** Sends one request to a session's `handleRequest`; resolves to its JSON reply. */
3
+ export type PostActorRequest = (actorName: string, room: string, body: unknown) => Promise<unknown>;
4
4
  /** Credentials minted by the platform for one direct actor connection. */
5
5
  export interface ActorConnectionCredentials {
6
6
  /** Direct actor endpoint, already carrying `?_pk=<connectionId>`. */
@@ -32,7 +32,7 @@ interface ActorsConfig {
32
32
  * direct→proxy fallback (which recovers by itself). Wired to the client's
33
33
  * `options.onError`. */
34
34
  onMintError?: (error: Error) => void;
35
- callMethod: CallActorMethod;
35
+ postRequest: PostActorRequest;
36
36
  }
37
37
  /**
38
38
  * The legacy platform-proxy URL, byte-for-byte what PartySocket built before
@@ -51,6 +51,6 @@ export declare function createActorsModule(config: ActorsConfig): {
51
51
  module: Record<string, (instanceId: string) => ActorRef>;
52
52
  closeAll: () => void;
53
53
  };
54
- /** `asServiceRole.actors`: server code can't hold a connection, so it only calls methods. */
55
- export declare function createServiceRoleActorsModule(callMethod: CallActorMethod): Record<string, (instanceId: string) => ServiceRoleActorRef>;
54
+ /** `asServiceRole.actors`: server code can't hold a connection, so it only posts. */
55
+ export declare function createServiceRoleActorsModule(postRequest: PostActorRequest): Record<string, (instanceId: string) => ServiceRoleActorRef>;
56
56
  export {};
@@ -1,23 +1,4 @@
1
1
  import { WebSocket as ReconnectingWebSocket } from "partysocket";
2
- // Never actor methods: the ref's own API, what `await`/JSON/frameworks probe for, and
3
- // Object.prototype (resolved through the `in` check below).
4
- const NOT_METHODS = new Set(["then", "catch", "finally", "toJSON", "asymmetricMatch", "nodeType", "constructor"]);
5
- function isMethodName(target, key) {
6
- return (typeof key === "string" &&
7
- !(key in target) &&
8
- !NOT_METHODS.has(key) &&
9
- !key.startsWith("$$") &&
10
- !key.startsWith("@@"));
11
- }
12
- function withMethods(target, call) {
13
- return new Proxy(target, {
14
- get(obj, key) {
15
- return isMethodName(obj, key)
16
- ? (args) => call(key, args)
17
- : Reflect.get(obj, key);
18
- },
19
- });
20
- }
21
2
  // Heartbeat / half-open detection: the socket only reconnects on a close/error
22
3
  // event, so ping periodically and force a reconnect if nothing returns in DEAD_MS.
23
4
  const PING_MS = 1000;
@@ -172,7 +153,7 @@ class Connection {
172
153
  /** Handle for one actor instance: `connect()` opens the socket (idempotent). */
173
154
  function makeActorRef(actorName, instanceId, config, connections) {
174
155
  let conn = null;
175
- const ref = {
156
+ return {
176
157
  connect(options) {
177
158
  if (conn)
178
159
  return conn;
@@ -185,8 +166,8 @@ function makeActorRef(actorName, instanceId, config, connections) {
185
166
  connections.add(c);
186
167
  return c;
187
168
  },
169
+ post: (body) => config.postRequest(actorName, instanceId, body),
188
170
  };
189
- return withMethods(ref, (method, args) => config.callMethod(actorName, instanceId, method, args));
190
171
  }
191
172
  /**
192
173
  * The legacy platform-proxy URL, byte-for-byte what PartySocket built before
@@ -246,13 +227,15 @@ export function createActorsModule(config) {
246
227
  },
247
228
  };
248
229
  }
249
- /** `asServiceRole.actors`: server code can't hold a connection, so it only calls methods. */
250
- export function createServiceRoleActorsModule(callMethod) {
230
+ /** `asServiceRole.actors`: server code can't hold a connection, so it only posts. */
231
+ export function createServiceRoleActorsModule(postRequest) {
251
232
  return new Proxy({}, {
252
233
  get(_, key) {
253
234
  if (typeof key !== "string" || key === "then")
254
235
  return undefined;
255
- return (instanceId) => withMethods({}, (method, args) => callMethod(key, instanceId, method, args));
236
+ return (instanceId) => ({
237
+ post: (body) => postRequest(key, instanceId, body),
238
+ });
256
239
  },
257
240
  });
258
241
  }
@@ -20,7 +20,6 @@
20
20
  * chatRoom: {
21
21
  * toClient: { type: "joined" | "left" | "message"; userId?: string; from?: string; text?: string };
22
22
  * toServer: { type: "message"; text: string };
23
- * methods: { kick: (args: { userId: string }) => { kicked: boolean } };
24
23
  * };
25
24
  * }
26
25
  * }
@@ -44,18 +43,6 @@ type ToClientFor<N extends string> = N extends keyof ActorRegistry ? ActorRegist
44
43
  type ToServerFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
45
44
  toServer: infer O;
46
45
  } ? O : unknown : unknown;
47
- type ActorMethodCall<F> = F extends (args: infer A, ...rest: never[]) => infer R ? undefined extends A ? (args?: A) => Promise<Awaited<R>> : (args: A) => Promise<Awaited<R>> : never;
48
- type UntypedActorMethods = Record<string, (args?: unknown) => Promise<unknown>>;
49
- /**
50
- * An actor's callable methods, as seen by a caller: each runs the actor's method of the same
51
- * name and resolves to its return value. Typed from the actor's `methods` in
52
- * {@linkcode ActorRegistry}; any name otherwise.
53
- */
54
- export type ActorMethods<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
55
- methods: infer M;
56
- } ? {
57
- [K in keyof M]: ActorMethodCall<M[K]>;
58
- } : UntypedActorMethods : UntypedActorMethods;
59
46
  /**
60
47
  * Configures the connection that {@linkcode ActorRef.connect | connect()} opens.
61
48
  */
@@ -147,19 +134,9 @@ export interface Connection<N extends string = string> {
147
134
  /**
148
135
  * Represents a reference to an actor session, identified by actor name and session ID.
149
136
  *
150
- * Call {@linkcode ActorRef.connect | connect()} to open the WebSocket and get a [connection](/developers/backend/resources/actors/overview#connections),
151
- * or call one of the actor's callable methods by name, such as `ref.kick({ userId })`: it runs
152
- * the actor's method with your identity, even when no client is connected, and resolves to
153
- * its return value. A refusal rejects with a `Base44Error` carrying the actor's status (404 for
154
- * a method the actor doesn't list in `static callable`).
155
- *
156
- * @example
157
- * ```typescript
158
- * // Call a method on a session
159
- * const { kicked } = await base44.actors.chatRoom("session-1").kick({ userId });
160
- * ```
137
+ * Call {@linkcode ActorRef.connect | connect()} to open the WebSocket and get a [connection](/developers/backend/resources/actors/overview#connections).
161
138
  */
162
- export interface ActorConnectable<N extends string = string> {
139
+ export interface ActorRef<N extends string = string> {
163
140
  /**
164
141
  * Creates or returns the connection for this session.
165
142
  *
@@ -179,27 +156,55 @@ export interface ActorConnectable<N extends string = string> {
179
156
  * ```
180
157
  */
181
158
  connect(options?: ActorConnectOptions): Connection<N>;
159
+ /**
160
+ * Sends a request to this session's `handleRequest` and returns its reply.
161
+ *
162
+ * The actor receives the request with the caller's identity: the logged-in
163
+ * user, or an anonymous visitor. Unlike {@linkcode ActorRef.connect | connect()},
164
+ * no connection is opened, so the request reaches the session even when no
165
+ * client is connected; the actor can still `broadcast()` from it.
166
+ *
167
+ * @param body - JSON-serializable request body, up to 64 KB.
168
+ * @returns The JSON body of the actor's response, or `undefined` when it has none.
169
+ * @throws {Base44Error} When the actor refuses the request or doesn't implement
170
+ * `handleRequest` (404), with the actor's status code.
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * // Send a request to a session
175
+ * const reply = await base44.actors.chatRoom("session-1").post({ type: "ping" });
176
+ * ```
177
+ */
178
+ post<T = unknown>(body?: unknown): Promise<T | undefined>;
182
179
  }
183
- export type ActorRef<N extends string = string> = ActorConnectable<N> & ActorMethods<N>;
184
180
  /**
185
181
  * Represents a reference to an actor session for server code running with the
186
182
  * [service role](/developers/references/sdk/getting-started/client#service-role).
187
- * Server code can't hold a connection, so it only calls methods; the actor sees the
188
- * `service` identity.
189
- *
190
- * @example
191
- * ```typescript
192
- * // Tell a user's session that their video is ready
193
- * await base44.asServiceRole.actors.VideoRoom(userId).videoReady({ id });
194
- * ```
183
+ * Server code can't hold a connection, so it only sends requests.
195
184
  */
196
- export type ServiceRoleActorRef<N extends string = string> = ActorMethods<N>;
185
+ export interface ServiceRoleActorRef {
186
+ /**
187
+ * Sends a request to this session's `handleRequest` as the app's server code,
188
+ * which the actor sees as the `service` identity, and returns its reply.
189
+ *
190
+ * @param body - JSON-serializable request body, up to 64 KB.
191
+ * @returns The JSON body of the actor's response, or `undefined` when it has none.
192
+ * @throws {Base44Error} When the actor refuses the request or doesn't implement
193
+ * `handleRequest` (404), with the actor's status code.
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * // Tell a user's session that their video is ready
198
+ * await base44.asServiceRole.actors.VideoRoom(userId).post({ type: "video_ready", id });
199
+ * ```
200
+ */
201
+ post<T = unknown>(body?: unknown): Promise<T | undefined>;
202
+ }
197
203
  /**
198
- * Actors module available with the service role: selects a session whose methods to call.
204
+ * Actors module available with the service role: selects a session to send
205
+ * requests to with {@linkcode ServiceRoleActorRef.post | post()}.
199
206
  */
200
- export type ServiceRoleActorsModule = {
201
- [K in AllActorNames]: (instanceId: string) => ServiceRoleActorRef<string & K>;
202
- } & Record<string, (instanceId: string) => ServiceRoleActorRef>;
207
+ export type ServiceRoleActorsModule = Record<string, (instanceId: string) => ServiceRoleActorRef>;
203
208
  /**
204
209
  * Selects a session for a named actor.
205
210
  *
@@ -236,7 +241,7 @@ export interface ActorClient<N extends string = string> {
236
241
  * - Manage connections: {@link ActorRef.connect | Open} and {@link Connection.close | close} a WebSocket connection to a session.
237
242
  * - Exchange messages: {@link Connection.send | Send} and {@link Connection.subscribe | listen} for messages to and from an actor.
238
243
  * - Manage subscriptions: {@link Connection.subscribe | Subscribe} and {@link ActorSubscription.unsubscribe | unsubscribe} from actor messages without closing the connection.
239
- * - Call methods: run one of an actor's callable methods on a session, without connecting.
244
+ * - Send requests: {@link ActorRef.post | Post} a request to a session's `handleRequest` without connecting.
240
245
  *
241
246
  * For a sample flow, see
242
247
  * [connect a client to a session](/developers/backend/resources/actors/sample-flows#connect-a-client-to-a-session).
@@ -246,12 +251,12 @@ export interface ActorClient<N extends string = string> {
246
251
  * This module is available to use with a client in anonymous or user authentication mode. Access it
247
252
  * through `base44.actors`. In
248
253
  * [service role authentication mode](/developers/references/sdk/getting-started/client#service-role),
249
- * `base44.asServiceRole.actors` only calls methods.
254
+ * `base44.asServiceRole.actors` only sends requests, with {@link ServiceRoleActorRef.post | post()}.
250
255
  *
251
256
  * The actor receives each client's [identity](/developers/backend/resources/actors/reference#connections)
252
- * when the client connects or calls a method. A client that hasn't logged in is anonymous, a client that
257
+ * when the client connects or posts. A client that hasn't logged in is anonymous, a client that
253
258
  * has [logged in](/developers/references/sdk/docs/interfaces/auth) is authenticated, and server
254
- * code calling with the service role is `service`.
259
+ * code posting with the service role is `service`.
255
260
  */
256
261
  export type ActorsModule = {
257
262
  [K in AllActorNames]: K extends keyof ActorRegistry ? ActorClient<string & K> : ActorClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.60-pr.377.428760d",
3
+ "version": "0.8.60-pr.377.d5ecb0f",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",