@base44-preview/platform 0.1.0-pr.323.0c3777e → 0.1.0-pr.332.986570f

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
@@ -12,15 +12,14 @@ The workspace must have white-label sockets enabled; this SDK does not open sess
12
12
  ```ts
13
13
  import { createPlatformClient } from "@base44/platform";
14
14
 
15
- const client = createPlatformClient({
16
- socketUrl, // the session's socket_url, from POST /api/service/socket-sessions
17
- async getSessionToken() {
15
+ const client = createPlatformClient();
16
+ const builder = client.builder.init({
17
+ // Returns the body of POST /api/service/socket-sessions, unchanged.
18
+ async getSession() {
18
19
  const response = await fetch("/api/builder-socket-session", { method: "POST" });
19
20
  if (!response.ok) throw new Error("Session request failed");
20
- return (await response.json()).session_token;
21
+ return response.json();
21
22
  },
22
- });
23
- const builder = client.builder.init({
24
23
  onError(error) { showConnectionError(error.code); },
25
24
  });
26
25
  const subscription = builder.subscribe(appId, {
@@ -38,34 +37,40 @@ builder.close();
38
37
 
39
38
  `/api/builder-socket-session` is your backend's route, not an SDK endpoint. It opens a
40
39
  socket session with its workspace key (`apps:watch` scope) through
41
- `POST /api/service/socket-sessions` with `{ app_ids }`, and returns only the
42
- `session_token` and `socket_url` to the browser. Pass `socket_url` as `socketUrl`. Never pass the workspace key or any other server
43
- credential to this client. Subscribe only to apps on the session's allowlist; your
40
+ `POST /api/service/socket-sessions` with `{ app_ids }`, and returns the response body
41
+ to the browser. `getSession` returns that body unchanged: the SDK reads `session_token`,
42
+ `socket_url` and `socket_path` and ignores other keys such as `session_id` and
43
+ `expires_in`. Never pass the workspace key or any other server credential to this client. Subscribe only to apps on the session's allowlist; your
44
44
  backend adds or removes apps with `PUT`/`DELETE /api/service/socket-sessions/{session_id}/rooms/{app_id}`.
45
45
 
46
46
  A session lasts one hour and is never extended. The token goes exclusively in
47
47
  CONNECT `auth.session_token`, never a URL, and the SDK keeps it in memory only. It
48
- is reused across automatic reconnects. `getSessionToken` is called when a builder
48
+ is reused across automatic reconnects. `getSession` is called when a builder
49
49
  session first connects, and again only when the server rejects the cached token or
50
- expires the session; the SDK then reconnects once with the new token. Retrieval has
51
- a twenty-second timeout and reports `session_unavailable` on failure.
50
+ expires the session; the SDK then reconnects once with the new session. If the new
51
+ session has a different `socket_url` or `socket_path`, the SDK closes the old socket,
52
+ opens one at the new address and rejoins every active subscription. Retrieval has a
53
+ twenty-second timeout. A failure, a timeout, or a session without a token, an
54
+ HTTP(S) origin as `socket_url` (no credentials, path, query or fragment) or an
55
+ absolute `socket_path` reports `session_unavailable`.
52
56
 
53
57
  One live socket per session: a newer connection with the same token replaces the
54
58
  older one, which stops with `session_replaced`. Open one session per page.
55
59
 
56
60
  ## Lifecycle
57
61
 
58
- `createPlatformClient({ socketUrl, getSessionToken })` creates a lightweight module
59
- container: no Socket.IO instance, timers, token request or network activity. Its
62
+ `createPlatformClient()` creates a lightweight module container: no Socket.IO
63
+ instance, timers, session request or network activity. It takes no options. Its
60
64
  `builder` module follows the server SDK's module-factory pattern.
61
65
 
62
- `client.builder.init({ onError })` synchronously creates an independent `BuilderSession`
63
- without connecting. Repeated calls create separate sessions, each owning its own
66
+ `client.builder.init({ getSession, onError })` synchronously creates an independent
67
+ `BuilderSession` without connecting or creating a socket. Repeated calls create separate sessions, each owning its own
64
68
  socket, listeners, subscriptions and cleanup. Close the returned session when its
65
69
  view is disposed; the root client and other sessions remain usable.
66
70
 
67
- `builder.connect()` resolves on CONNECT, before any snapshot. The socket uses the
68
- default namespace on `/ws/socket.io/`, WebSocket only, with a dedicated manager.
71
+ `builder.connect()` fetches the first session, creates the socket at its address and
72
+ resolves on CONNECT, before any snapshot. The socket uses the default namespace on the
73
+ session's `socket_path`, WebSocket only, with a dedicated manager.
69
74
  Transport reconnection uses five attempts, starting at one second and capped at ten
70
75
  seconds with jitter; each attempt has a twenty-second timeout. A temporary server
71
76
  refusal is retried the same way. After exhaustion, a refusal or `session_replaced`,
@@ -94,9 +99,10 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
94
99
 
95
100
  ## Public shapes
96
101
 
97
- - `PlatformClientOptions` (`client.types.ts`): `socketUrl`, `getSessionToken`.
102
+ - `PlatformClient` (`client.types.ts`): the `builder` module.
98
103
  - `BuilderModule` (`modules/builder.types.ts`): lazy `init(options)` factory.
99
- - `BuilderInitOptions`: connection-level `onError` observer.
104
+ - `BuilderInitOptions`: `getSession` and the connection-level `onError` observer.
105
+ - `SocketSession`: the `session_token`, `socket_url` and `socket_path` that `getSession` returns.
100
106
  - `BuilderSession`: `connect()`, `subscribe(appId, options)`, `close()`.
101
107
  - `SubscriptionOptions`: required `onSnapshot`, `onEvent` and `onError`.
102
108
  - `PlatformSubscription`: read-only `appId`, `active`, and `unsubscribe()`.
@@ -109,7 +115,9 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
109
115
  event is `{room, data}`; the SDK routes by `room` and validates the envelope, while
110
116
  payload schemas and private-field filtering are the server's. Omitted keys mean
111
117
  unchanged and explicit null clears. Events carrying `branch_id` belong to that branch;
112
- null or absent is main. Unknown event names are not forwarded. `PlatformSnapshot` is
118
+ null or absent is main. An event name the SDK doesn't know is forwarded as
119
+ `{type: "unknown", name, appId, data}` with only the envelope validated, so a new event reaches
120
+ partners when the service deploys it; new `room.*` notices are dropped. `PlatformSnapshot` is
113
121
  the service's `Snapshot` plus the app's `room`. Structural filtering does not promise
114
122
  redaction of generated prose or user content.
115
123
 
@@ -148,7 +156,7 @@ exceptions, payloads and credentials are never attached.
148
156
  | Error code | Action |
149
157
  | --- | --- |
150
158
  | `connection_denied` | The session was rejected even with a fresh token: the workspace, key or session is not usable. |
151
- | `session_unavailable` | `getSessionToken` failed or timed out; no provider details are forwarded. |
159
+ | `session_unavailable` | `getSession` failed, timed out or returned an invalid session; no provider details are forwarded. |
152
160
  | `session_replaced` | Another connection with the same session took over. Stop, or open a new session. |
153
161
  | `connection_failed` | Transport failure or exhausted retries; call `connect()` after fixing connectivity. |
154
162
  | `access_denied` | The join was refused: the app is not on the session's allowlist, or joins were rate limited. |
package/dist/client.d.ts CHANGED
@@ -1,31 +1,30 @@
1
- import type { PlatformClient, PlatformClientOptions } from "./client.types.js";
1
+ import type { PlatformClient } from "./client.types.js";
2
2
  /**
3
3
  * Creates a platform client.
4
4
  *
5
5
  * This is the entry point of the Platform SDK. The client gives your white-label app editor
6
6
  * access to the platform's modules, such as [`builder`](/developers/references/platform-sdk/docs/interfaces/builder).
7
+ * It takes no options and opens nothing: each builder session gets its socket session from the
8
+ * `getSession` you pass to `init()`.
7
9
  *
8
- * @param options - Configuration object for the client.
9
- * @returns A configured platform client with access to the platform's modules.
10
- * @throws {TypeError} When `socketUrl` isn't an HTTP or HTTPS origin.
10
+ * @returns A platform client with access to the platform's modules.
11
11
  *
12
12
  * @example
13
13
  * ```typescript
14
14
  * // Create a client for your app editor
15
15
  * import { createPlatformClient } from '@base44/platform';
16
16
  *
17
- * const client = createPlatformClient({
18
- * socketUrl,
19
- * async getSessionToken() {
17
+ * const client = createPlatformClient();
18
+ *
19
+ * // Use the client to follow the AI chat in an app
20
+ * const builder = client.builder.init({
21
+ * async getSession() {
20
22
  * const response = await fetch('/api/builder-socket-session', { method: 'POST' });
21
- * const { session_token } = await response.json();
22
- * return session_token;
23
+ * return response.json();
23
24
  * },
25
+ * onError: (error) => console.error(error.code),
24
26
  * });
25
- *
26
- * // Use the client to follow the AI chat in an app
27
- * const builder = client.builder.init({ onError: (error) => console.error(error.code) });
28
27
  * await builder.connect();
29
28
  * ```
30
29
  */
31
- export declare function createPlatformClient(options: PlatformClientOptions): PlatformClient;
30
+ export declare function createPlatformClient(): PlatformClient;
package/dist/client.js CHANGED
@@ -4,34 +4,29 @@ import { createBuilder } from "./modules/builder.js";
4
4
  *
5
5
  * This is the entry point of the Platform SDK. The client gives your white-label app editor
6
6
  * access to the platform's modules, such as [`builder`](/developers/references/platform-sdk/docs/interfaces/builder).
7
+ * It takes no options and opens nothing: each builder session gets its socket session from the
8
+ * `getSession` you pass to `init()`.
7
9
  *
8
- * @param options - Configuration object for the client.
9
- * @returns A configured platform client with access to the platform's modules.
10
- * @throws {TypeError} When `socketUrl` isn't an HTTP or HTTPS origin.
10
+ * @returns A platform client with access to the platform's modules.
11
11
  *
12
12
  * @example
13
13
  * ```typescript
14
14
  * // Create a client for your app editor
15
15
  * import { createPlatformClient } from '@base44/platform';
16
16
  *
17
- * const client = createPlatformClient({
18
- * socketUrl,
19
- * async getSessionToken() {
17
+ * const client = createPlatformClient();
18
+ *
19
+ * // Use the client to follow the AI chat in an app
20
+ * const builder = client.builder.init({
21
+ * async getSession() {
20
22
  * const response = await fetch('/api/builder-socket-session', { method: 'POST' });
21
- * const { session_token } = await response.json();
22
- * return session_token;
23
+ * return response.json();
23
24
  * },
25
+ * onError: (error) => console.error(error.code),
24
26
  * });
25
- *
26
- * // Use the client to follow the AI chat in an app
27
- * const builder = client.builder.init({ onError: (error) => console.error(error.code) });
28
27
  * await builder.connect();
29
28
  * ```
30
29
  */
31
- export function createPlatformClient(options) {
32
- const url = new URL(options.socketUrl);
33
- if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
34
- throw new TypeError("socketUrl must be an HTTP(S) origin without credentials, path, query or fragment");
35
- }
36
- return Object.freeze({ builder: Object.freeze(createBuilder({ ...options, socketUrl: url.origin })) });
30
+ export function createPlatformClient() {
31
+ return Object.freeze({ builder: Object.freeze(createBuilder()) });
37
32
  }
@@ -1,30 +1,4 @@
1
1
  import type { BuilderModule } from "./modules/builder.types.js";
2
- /**
3
- * Options for {@linkcode createPlatformClient | createPlatformClient()}.
4
- *
5
- * The client runs in the browser and never sees your workspace API key. Your server opens a socket
6
- * session with the key and hands the browser only the session's token and socket URL.
7
- */
8
- export interface PlatformClientOptions {
9
- /**
10
- * Origin of the platform socket.
11
- *
12
- * Use the `socket_url` your server receives from `POST /api/service/socket-sessions`. It's the same
13
- * for every session in an environment, so your server can pass it to the page once. It must be an
14
- * origin with no path, query, fragment, or credentials.
15
- */
16
- socketUrl: string;
17
- /**
18
- * Returns a socket session token from your server.
19
- *
20
- * Your server opens a session with `POST /api/service/socket-sessions` and returns its
21
- * `session_token`. The client calls this when it connects, and again when the token expires.
22
- * Return a new token on every call.
23
- *
24
- * @returns The session token, or a promise resolving to it.
25
- */
26
- getSessionToken: () => string | Promise<string>;
27
- }
28
2
  /**
29
3
  * The platform client.
30
4
  *
@@ -4,9 +4,11 @@
4
4
  */
5
5
  export type SessionErrorCode =
6
6
  /**
7
- * `getSessionToken` threw, took longer than 20 seconds or returned no token.
7
+ * `getSession` threw, took longer than 20 seconds, or returned a session without a valid
8
+ * `session_token`, `socket_url` (an HTTP or HTTPS origin) or `socket_path` (an absolute path).
8
9
  *
9
- * Check the endpoint that opens sessions, then call `connect()` again. Retryable.
10
+ * Check the endpoint that opens sessions, then call `connect()` again. Retryable, except that an
11
+ * invalid field needs a fix on your server first.
10
12
  */
11
13
  "session_unavailable"
12
14
  /**
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  export { createPlatformClient } from "./client.js";
3
3
  export { PlatformSocketError } from "./errors.js";
4
4
  export type { AppErrorCode, PlatformSocketErrorCode, SessionErrorCode } from "./errors.types.js";
5
- export type { PlatformClient, PlatformClientOptions } from "./client.types.js";
6
- export type { BuilderModule, BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./modules/builder.types.js";
5
+ export type { PlatformClient } from "./client.types.js";
6
+ export type { BuilderModule, BuilderInitOptions, BuilderSession, PlatformSubscription, SocketSession, SubscriptionOptions } from "./modules/builder.types.js";
7
7
  export type { GuardApproval, PlatformEvent, PlatformEventMap, PlatformSnapshot, ToolCall } from "./modules/builder.events.types.js";
8
8
  export type * from "./modules/builder.events.generated.js";
@@ -1,6 +1,9 @@
1
- import type { PlatformEvent, PlatformEventMap, PlatformSnapshot } from "./builder.events.types.js";
1
+ import type { PlatformEvent, PlatformSnapshot } from "./builder.events.types.js";
2
+ import type { SocketSession } from "./builder.types.js";
2
3
  /** App events delivered to `onEvent`: every server event except the session events the socket handles. */
3
4
  export declare const eventNames: ("message.updated" | "message.removed" | "app.status_changed" | "preview.reload_requested" | "preview.navigation_requested" | "queue.updated" | "task.progressed" | "image.resolved" | "conversation.changed" | "files.changed" | "branch.deleted" | "repository.changed" | "pull_request.changed")[];
5
+ /** A name newer than this SDK's protocol, delivered to `onEvent` as `unknown`. New `room.*` notices have no error code, so they are dropped. */
6
+ export declare const isUnknownEvent: (name: string) => boolean;
4
7
  /** Notices that name an app room, by the error code each one reports. A new notice fails to compile until it has one. */
5
8
  export declare const roomNotices: {
6
9
  readonly "room.access_denied": "access_denied";
@@ -17,5 +20,7 @@ export declare const roomFor: (appId: string) => string;
17
20
  export declare function object(value: unknown): Record<string, unknown>;
18
21
  export declare function appFromRoom(value: unknown): string | undefined;
19
22
  /** Every event is `{room, data}`; payload schemas are the service's, so only the envelope is validated. */
20
- export declare function decode(type: keyof PlatformEventMap, appId: string, raw: unknown): PlatformEvent;
23
+ export declare function decode(name: string, appId: string, raw: unknown): PlatformEvent;
21
24
  export declare function decodeSnapshot(raw: unknown): PlatformSnapshot;
25
+ /** Keeps only the fields the socket needs; a URL with credentials, a path, query or fragment is refused. */
26
+ export declare function decodeSession(raw: unknown): SocketSession;
@@ -2,6 +2,9 @@ import { serverEventNames } from "./builder.events.generated.js";
2
2
  const sessionEvents = ["app.snapshot", "session.ended"];
3
3
  /** App events delivered to `onEvent`: every server event except the session events the socket handles. */
4
4
  export const eventNames = serverEventNames.filter((name) => !sessionEvents.includes(name) && !name.startsWith("room."));
5
+ const knownNames = serverEventNames;
6
+ /** A name newer than this SDK's protocol, delivered to `onEvent` as `unknown`. New `room.*` notices have no error code, so they are dropped. */
7
+ export const isUnknownEvent = (name) => !knownNames.includes(name) && !name.startsWith("room.");
5
8
  /** Notices that name an app room, by the error code each one reports. A new notice fails to compile until it has one. */
6
9
  export const roomNotices = {
7
10
  "room.access_denied": "access_denied",
@@ -25,8 +28,9 @@ export function appFromRoom(value) {
25
28
  return typeof value === "string" && /^\/apps\/[a-f0-9]{24}$/.test(value) ? value.slice(6) : undefined;
26
29
  }
27
30
  /** Every event is `{room, data}`; payload schemas are the service's, so only the envelope is validated. */
28
- export function decode(type, appId, raw) {
29
- return { type, appId, data: object(object(raw).data) };
31
+ export function decode(name, appId, raw) {
32
+ const data = object(object(raw).data);
33
+ return (knownNames.includes(name) ? { type: name, appId, data } : { type: "unknown", name, appId, data });
30
34
  }
31
35
  export function decodeSnapshot(raw) {
32
36
  const frame = object(raw);
@@ -37,3 +41,16 @@ export function decodeSnapshot(raw) {
37
41
  const queue = data.queue !== null && typeof data.queue === "object" ? { queue: data.queue } : {};
38
42
  return { room: frame.room, status: data.status, messages: data.messages, ...queue };
39
43
  }
44
+ /** Keeps only the fields the socket needs; a URL with credentials, a path, query or fragment is refused. */
45
+ export function decodeSession(raw) {
46
+ const { session_token, socket_url, socket_path } = object(raw);
47
+ if (typeof session_token !== "string" || !session_token.trim())
48
+ throw new Error("Invalid session token");
49
+ if (typeof socket_url !== "string" || typeof socket_path !== "string" || !/^\/(?!\/)[^?#\s]*$/.test(socket_path))
50
+ throw new Error("Invalid socket address");
51
+ const url = new URL(socket_url);
52
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
53
+ throw new Error("Invalid socket URL");
54
+ }
55
+ return { session_token, socket_url: url.origin, socket_path };
56
+ }
@@ -1,12 +1,12 @@
1
- import type { PlatformClientOptions } from "../client.types.js";
2
1
  import type { BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./builder.types.js";
3
2
  /** @internal */
4
3
  export declare class BuilderSocket implements BuilderSession {
5
- private readonly socket;
4
+ private socket?;
5
+ private address?;
6
6
  private readonly subscriptions;
7
7
  private readonly options;
8
8
  private closed;
9
- private token?;
9
+ private session?;
10
10
  private tokenFresh;
11
11
  private ending?;
12
12
  private denialRetries;
@@ -16,8 +16,9 @@ export declare class BuilderSocket implements BuilderSession {
16
16
  private connecting?;
17
17
  private resolveConnect?;
18
18
  private rejectConnect?;
19
- constructor(config: PlatformClientOptions, options: BuilderInitOptions);
20
- /** Connect with the session token. Resolves on CONNECT, before snapshots arrive.
19
+ constructor(options: BuilderInitOptions);
20
+ /** Connect with the session's token. Resolves on CONNECT, before snapshots arrive.
21
+ * The first call fetches the session, whose address the socket opens on.
21
22
  * Transport loss retries up to five times and rejoins active subscriptions.
22
23
  * Call again after a failure or `session_replaced`; concurrent calls share one attempt.
23
24
  */
@@ -29,7 +30,11 @@ export declare class BuilderSocket implements BuilderSession {
29
30
  subscribe(appId: string, options: SubscriptionOptions): PlatformSubscription;
30
31
  /** Stop delivery, cancel reconnection and release all listeners. Idempotent and terminal. */
31
32
  close(): void;
33
+ private open;
34
+ private appEvent;
35
+ private discard;
32
36
  private join;
37
+ /** Without a callback, or when a new session moves the socket, opens a socket at the session's address. */
33
38
  private authenticate;
34
39
  /** A connect the server refused. Transport errors are Socket.IO's to retry. */
35
40
  private refused;