@base44-preview/sdk 0.8.48-pr.284.e0a8d2f → 0.8.48-pr.286.d14ea24

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
@@ -151,3 +151,12 @@ npm run create-docs
151
151
  cd docs
152
152
  mintlify dev
153
153
  ```
154
+
155
+ ### Platform browser subscriptions
156
+
157
+ The separate `@base44/sdk/platform/client` entry point subscribes to public builder
158
+ updates through the white-label socket. It supports typed events, bounded delivery,
159
+ and reconnect replay using browser credentials supplied by your backend.
160
+ See [setup, public contract and recovery](platform-docs/client.md) and the
161
+ [TypeScript example](examples/platform-client.ts). Backend token integration and
162
+ workspace rollout are prerequisites; never use an API key in the browser.
@@ -0,0 +1,9 @@
1
+ import type { PlatformClientOptions } from "./client.types.js";
2
+ import type { BuilderModule } from "./modules/builder.types.js";
3
+ /** Browser platform client. Construction creates no sockets, timers or network requests. */
4
+ export declare class Base44PlatformClient {
5
+ /** Lazy builder subscriptions with independent session lifecycles. */
6
+ readonly builder: BuilderModule;
7
+ /** Configure shared service/auth settings; each module initializes its own resources. */
8
+ constructor(options: PlatformClientOptions);
9
+ }
@@ -0,0 +1,12 @@
1
+ import { createBuilder } from "./modules/builder.js";
2
+ /** Browser platform client. Construction creates no sockets, timers or network requests. */
3
+ export class Base44PlatformClient {
4
+ /** Configure shared service/auth settings; each module initializes its own resources. */
5
+ constructor(options) {
6
+ const url = new URL(options.serverUrl);
7
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
8
+ throw new TypeError("serverUrl must be an HTTP(S) origin without credentials, path, query or fragment");
9
+ }
10
+ this.builder = Object.freeze(createBuilder({ ...options, serverUrl: url.origin }));
11
+ }
12
+ }
@@ -0,0 +1,7 @@
1
+ /** Shared configuration for browser platform modules. Never supply an API key. */
2
+ export interface PlatformClientOptions {
3
+ /** Origin of the platform service, e.g. https://base44.app. No path/query/credentials. */
4
+ serverUrl: string;
5
+ /** Refresh a browser credential through your backend; called on every builder connection attempt. */
6
+ refreshToken: () => string | Promise<string>;
7
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { PlatformSocketErrorCode } from "./errors.types.js";
2
+ /** Sanitized failure. Original token-provider, handler and server exceptions are not retained. */
3
+ export declare class PlatformSocketError extends Error {
4
+ /** Stable machine-readable category. */
5
+ readonly code: PlatformSocketErrorCode;
6
+ /** Associated app, when the server identifies a valid room. */
7
+ readonly appId?: string;
8
+ /** Create a sanitized error with no credential-bearing cause or payload. */
9
+ constructor(code: PlatformSocketErrorCode, appId?: string);
10
+ }
@@ -0,0 +1,10 @@
1
+ /** Sanitized failure. Original token-provider, handler and server exceptions are not retained. */
2
+ export class PlatformSocketError extends Error {
3
+ /** Create a sanitized error with no credential-bearing cause or payload. */
4
+ constructor(code, appId) {
5
+ super(`Platform socket: ${code}`);
6
+ this.name = "PlatformSocketError";
7
+ this.code = code;
8
+ this.appId = appId;
9
+ }
10
+ }
@@ -0,0 +1,2 @@
1
+ /** Server subscription failures and client transport/processing failures. */
2
+ export type PlatformSocketErrorCode = "invalid_room" | "invalid_cursor" | "access_denied" | "subscription_limit" | "resync_required" | "stream_unavailable" | "connection_denied" | "connection_failed" | "token_unavailable" | "protocol_error" | "handler_failed" | "client_closed";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ /** Browser platform modules, separate from the runtime and server SDKs. */
2
+ export { Base44PlatformClient } from "./client.js";
3
+ export { PlatformSocketError } from "./errors.js";
4
+ export type { PlatformSocketErrorCode } from "./errors.types.js";
5
+ export type { PlatformClientOptions } from "./client.types.js";
6
+ export type { BuilderModule, BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./modules/builder.types.js";
7
+ export type { AppUpdate, ChatMessage, ToolCall, ToolDisplayProjection, ToolQuestionOption, ToolQuestion, ToolQuestionArguments, ToolSecretField, ToolSecretArguments, ToolPackageOperation, ToolPackageArguments, ToolPlanUpdate, ToolPlanArguments, ToolMediaArguments, ToolQuestionAnswer, ToolQuestionInput, ToolOutcome, QueueItem, QueueUpdate, TaskUpdate, ImageReady, Directive, PlatformEventMap, PlatformEvent, Joined } from "./modules/builder.events.types.js";
@@ -0,0 +1,3 @@
1
+ /** Browser platform modules, separate from the runtime and server SDKs. */
2
+ export { Base44PlatformClient } from "./client.js";
3
+ export { PlatformSocketError } from "./errors.js";
@@ -0,0 +1,11 @@
1
+ import type { Joined, PlatformEvent, PlatformEventMap } from "./builder.events.types.js";
2
+ export declare const eventNames: readonly ["update_model", "directive", "queue_update", "task_update", "image_ready"];
3
+ export declare const errorCodes: readonly ["invalid_room", "invalid_cursor", "access_denied", "subscription_limit", "resync_required", "stream_unavailable"];
4
+ export declare const appPattern: RegExp;
5
+ export declare const roomFor: (appId: string) => string;
6
+ export declare function object(value: unknown): Record<string, unknown>;
7
+ export declare function string(value: unknown): string;
8
+ export declare function appFromRoom(value: unknown): string | undefined;
9
+ export declare function eventApp(type: keyof PlatformEventMap, raw: unknown): string | undefined;
10
+ export declare function decode(type: keyof PlatformEventMap, appId: string, raw: unknown): PlatformEvent;
11
+ export declare function decodeJoined(raw: unknown): Joined;
@@ -0,0 +1,39 @@
1
+ export const eventNames = ["update_model", "directive", "queue_update", "task_update", "image_ready"];
2
+ export const errorCodes = ["invalid_room", "invalid_cursor", "access_denied", "subscription_limit", "resync_required", "stream_unavailable"];
3
+ export const appPattern = /^[a-f0-9]{24}$/;
4
+ export const roomFor = (appId) => `/apps/${appId}`;
5
+ export function object(value) {
6
+ if (!value || typeof value !== "object" || Array.isArray(value))
7
+ throw new Error("Invalid frame");
8
+ return value;
9
+ }
10
+ export function string(value) {
11
+ if (typeof value !== "string" || !value)
12
+ throw new Error("Invalid string");
13
+ return value;
14
+ }
15
+ export function appFromRoom(value) {
16
+ return typeof value === "string" && /^\/apps\/[a-f0-9]{24}$/.test(value) ? value.slice(6) : undefined;
17
+ }
18
+ export function eventApp(type, raw) {
19
+ const frame = object(raw);
20
+ return type === "queue_update"
21
+ ? typeof frame.app_id === "string" && appPattern.test(frame.app_id) ? frame.app_id : undefined
22
+ : appFromRoom(frame.room);
23
+ }
24
+ export function decode(type, appId, raw) {
25
+ const frame = object(raw);
26
+ const seq = string(frame.seq);
27
+ const wrapped = type === "update_model" || type === "task_update" || type === "image_ready";
28
+ const { seq: _, ...flat } = frame;
29
+ const data = wrapped ? object(JSON.parse(string(frame.data))) : flat;
30
+ // Payload schemas are owned by the service; only decode/validate the transport envelope here.
31
+ return { type, appId, seq, data };
32
+ }
33
+ export function decodeJoined(raw) {
34
+ const frame = object(raw);
35
+ if (!appFromRoom(frame.room) || !Number.isInteger(frame.max_entries) || !Number.isInteger(frame.inactivity_expiry_seconds))
36
+ throw new Error("Invalid boundary");
37
+ string(frame.seq);
38
+ return frame;
39
+ }
@@ -0,0 +1,35 @@
1
+ import type { PlatformClientOptions } from "../client.types.js";
2
+ import type { BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./builder.types.js";
3
+ /** @internal */
4
+ export declare class BuilderSocket implements BuilderSession {
5
+ private readonly socket;
6
+ private readonly subscriptions;
7
+ private readonly options;
8
+ private closed;
9
+ private needsFreshConnection;
10
+ private generation;
11
+ private authAttempt;
12
+ private cancelAuth?;
13
+ private connecting?;
14
+ private resolveConnect?;
15
+ private rejectConnect?;
16
+ constructor(config: PlatformClientOptions, options: BuilderInitOptions);
17
+ /** Connect using a freshly obtained token. Resolves on CONNECT, not on app replay completion.
18
+ * Unexpected transport loss retries up to five times and rejoins active subscriptions.
19
+ * Call again after addressing a connection/auth failure; concurrent calls share one attempt.
20
+ */
21
+ connect(): Promise<void>;
22
+ /** Subscribe before or after connecting. One subscription per app, maximum eight.
23
+ * Events and boundary callbacks are awaited in order per app. Failed application,
24
+ * invalid frames or server errors end the subscription without advancing its cursor.
25
+ */
26
+ subscribe(appId: string, options: SubscriptionOptions): PlatformSubscription;
27
+ /** Stop delivery, cancel reconnection and release all listeners. Idempotent and terminal. */
28
+ close(): void;
29
+ private join;
30
+ private authenticate;
31
+ private clearConnecting;
32
+ private connectionError;
33
+ private serverError;
34
+ private protocolError;
35
+ }
@@ -0,0 +1,213 @@
1
+ import { io } from "socket.io-client";
2
+ import { PlatformSocketError } from "../errors.js";
3
+ import { appFromRoom, appPattern, decode, decodeJoined, errorCodes, eventApp, eventNames, object, roomFor } from "./builder-protocol.js";
4
+ import { notify, Subscription } from "./builder-subscription.js";
5
+ /** @internal */
6
+ export class BuilderSocket {
7
+ constructor(config, options) {
8
+ this.subscriptions = new Map();
9
+ this.closed = false;
10
+ this.needsFreshConnection = false;
11
+ this.generation = 0;
12
+ this.authAttempt = 0;
13
+ this.options = { ...config, onError: options.onError };
14
+ this.socket = io(`${config.serverUrl}/partner`, {
15
+ path: "/ws-whitelabel/socket.io/", transports: ["websocket"], autoConnect: false,
16
+ forceNew: true, reconnectionAttempts: 5, reconnectionDelay: 1000, reconnectionDelayMax: 10000,
17
+ timeout: 20000,
18
+ auth: (callback) => { void this.authenticate(callback); },
19
+ });
20
+ this.socket.on("connect", () => {
21
+ var _a;
22
+ const generation = ++this.generation;
23
+ this.needsFreshConnection = false;
24
+ for (const subscription of this.subscriptions.values())
25
+ this.join(subscription, generation);
26
+ (_a = this.resolveConnect) === null || _a === void 0 ? void 0 : _a.call(this);
27
+ this.clearConnecting();
28
+ });
29
+ this.socket.on("disconnect", (reason) => {
30
+ ++this.generation;
31
+ ++this.authAttempt;
32
+ if (reason === "io server disconnect")
33
+ this.connectionError(new PlatformSocketError("connection_failed"));
34
+ });
35
+ this.socket.on("connect_error", (error) => {
36
+ var _a;
37
+ this.connectionError(new PlatformSocketError(((_a = error.data) === null || _a === void 0 ? void 0 : _a.code) === "connection_denied" ? "connection_denied" : "connection_failed"));
38
+ });
39
+ this.socket.io.on("reconnect_failed", () => this.connectionError(new PlatformSocketError("connection_failed")));
40
+ this.socket.on("joined", (raw) => {
41
+ var _a;
42
+ try {
43
+ const joined = decodeJoined(raw);
44
+ (_a = this.subscriptions.get(appFromRoom(joined.room))) === null || _a === void 0 ? void 0 : _a.joined(joined);
45
+ }
46
+ catch (_b) {
47
+ this.protocolError(raw);
48
+ }
49
+ });
50
+ this.socket.on("error", (raw) => this.serverError(raw));
51
+ for (const type of eventNames)
52
+ this.socket.on(type, (raw) => {
53
+ var _a;
54
+ try {
55
+ const appId = eventApp(type, raw);
56
+ if (!appId)
57
+ throw new Error("Invalid app");
58
+ (_a = this.subscriptions.get(appId)) === null || _a === void 0 ? void 0 : _a.event(decode(type, appId, raw));
59
+ }
60
+ catch (_b) {
61
+ this.protocolError(raw);
62
+ }
63
+ });
64
+ }
65
+ /** Connect using a freshly obtained token. Resolves on CONNECT, not on app replay completion.
66
+ * Unexpected transport loss retries up to five times and rejoins active subscriptions.
67
+ * Call again after addressing a connection/auth failure; concurrent calls share one attempt.
68
+ */
69
+ connect() {
70
+ if (this.closed)
71
+ return Promise.reject(new PlatformSocketError("client_closed"));
72
+ if (this.socket.connected)
73
+ return Promise.resolve();
74
+ if (this.connecting)
75
+ return this.connecting;
76
+ const promise = new Promise((resolve, reject) => {
77
+ this.resolveConnect = resolve;
78
+ this.rejectConnect = reject;
79
+ });
80
+ this.connecting = promise;
81
+ this.socket.connect();
82
+ return promise;
83
+ }
84
+ /** Subscribe before or after connecting. One subscription per app, maximum eight.
85
+ * Events and boundary callbacks are awaited in order per app. Failed application,
86
+ * invalid frames or server errors end the subscription without advancing its cursor.
87
+ */
88
+ subscribe(appId, options) {
89
+ if (this.closed)
90
+ throw new PlatformSocketError("client_closed");
91
+ if (!appPattern.test(appId))
92
+ throw new TypeError("appId must be 24 lowercase hexadecimal characters");
93
+ if (options.afterSeq !== undefined && (typeof options.afterSeq !== "string" || !options.afterSeq))
94
+ throw new TypeError("afterSeq must be a nonempty opaque cursor");
95
+ if (this.subscriptions.has(appId))
96
+ throw new TypeError("An app may only have one subscription per builder session");
97
+ if (this.subscriptions.size >= 8)
98
+ throw new PlatformSocketError("subscription_limit", appId);
99
+ const subscription = new Subscription(appId, { ...options }, () => {
100
+ this.subscriptions.delete(appId);
101
+ this.needsFreshConnection = true;
102
+ if (this.socket.connected)
103
+ this.socket.emit("leave", roomFor(appId));
104
+ });
105
+ this.subscriptions.set(appId, subscription);
106
+ if (this.socket.connected && this.needsFreshConnection) {
107
+ // Leave has no acknowledgement; a new transport fences late events from retired streams.
108
+ this.socket.disconnect();
109
+ void this.connect().catch(() => { }); // Connection errors are delivered through onError.
110
+ }
111
+ else if (this.socket.connected) {
112
+ this.join(subscription, this.generation);
113
+ }
114
+ return subscription;
115
+ }
116
+ /** Stop delivery, cancel reconnection and release all listeners. Idempotent and terminal. */
117
+ close() {
118
+ var _a, _b;
119
+ if (this.closed)
120
+ return;
121
+ this.closed = true;
122
+ ++this.authAttempt;
123
+ (_a = this.cancelAuth) === null || _a === void 0 ? void 0 : _a.call(this);
124
+ ++this.generation;
125
+ for (const subscription of this.subscriptions.values())
126
+ subscription.unsubscribe();
127
+ (_b = this.rejectConnect) === null || _b === void 0 ? void 0 : _b.call(this, new PlatformSocketError("client_closed"));
128
+ this.clearConnecting();
129
+ this.socket.removeAllListeners();
130
+ this.socket.io.removeAllListeners();
131
+ this.socket.disconnect();
132
+ }
133
+ join(subscription, generation) {
134
+ subscription.join((cursor) => {
135
+ if (this.socket.connected && generation === this.generation) {
136
+ this.socket.emit("join", roomFor(subscription.appId), cursor === undefined ? {} : { after_seq: cursor });
137
+ }
138
+ });
139
+ }
140
+ async authenticate(callback) {
141
+ var _a;
142
+ const attempt = ++this.authAttempt;
143
+ (_a = this.cancelAuth) === null || _a === void 0 ? void 0 : _a.call(this);
144
+ let timer;
145
+ const timeout = new Promise((_, reject) => {
146
+ timer = setTimeout(() => reject(new Error("Token timeout")), 20000);
147
+ this.cancelAuth = () => { clearTimeout(timer); reject(new Error("Cancelled")); };
148
+ });
149
+ try {
150
+ const token = await Promise.race([Promise.resolve().then(() => this.options.refreshToken()), timeout]);
151
+ if (this.closed || attempt !== this.authAttempt)
152
+ return;
153
+ if (typeof token !== "string" || !token.trim())
154
+ throw new Error("Missing token");
155
+ callback({ token });
156
+ }
157
+ catch (_b) {
158
+ if (this.closed || attempt !== this.authAttempt)
159
+ return;
160
+ this.socket.disconnect();
161
+ this.connectionError(new PlatformSocketError("token_unavailable"));
162
+ }
163
+ finally {
164
+ clearTimeout(timer);
165
+ if (attempt === this.authAttempt)
166
+ this.cancelAuth = undefined;
167
+ }
168
+ }
169
+ clearConnecting() {
170
+ this.connecting = undefined;
171
+ this.resolveConnect = undefined;
172
+ this.rejectConnect = undefined;
173
+ }
174
+ connectionError(error) {
175
+ var _a;
176
+ (_a = this.rejectConnect) === null || _a === void 0 ? void 0 : _a.call(this, error);
177
+ this.clearConnecting();
178
+ if (!this.closed)
179
+ notify(this.options.onError, error);
180
+ }
181
+ serverError(raw) {
182
+ var _a;
183
+ try {
184
+ const frame = object(raw);
185
+ const code = errorCodes.find((code) => code === frame.code);
186
+ if (!code)
187
+ throw new Error("Unknown error");
188
+ const appId = appFromRoom(frame.room);
189
+ if (appId)
190
+ (_a = this.subscriptions.get(appId)) === null || _a === void 0 ? void 0 : _a.fail(code);
191
+ else if (frame.room === null)
192
+ this.connectionError(new PlatformSocketError(code));
193
+ else
194
+ throw new Error("Invalid room");
195
+ }
196
+ catch (_b) {
197
+ this.protocolError(raw);
198
+ }
199
+ }
200
+ protocolError(raw) {
201
+ var _a, _b;
202
+ const frame = raw && typeof raw === "object" ? raw : {};
203
+ const appId = (_a = appFromRoom(frame.room)) !== null && _a !== void 0 ? _a : (typeof frame.app_id === "string" && appPattern.test(frame.app_id) ? frame.app_id : undefined);
204
+ if (appId)
205
+ (_b = this.subscriptions.get(appId)) === null || _b === void 0 ? void 0 : _b.fail("protocol_error");
206
+ else {
207
+ // Unknown routing means no app cursor can safely advance past this frame.
208
+ for (const subscription of [...this.subscriptions.values()])
209
+ subscription.fail("protocol_error");
210
+ this.connectionError(new PlatformSocketError("protocol_error"));
211
+ }
212
+ }
213
+ }
@@ -0,0 +1,24 @@
1
+ import type { Joined, PlatformEvent } from "./builder.events.types.js";
2
+ import { PlatformSocketError } from "../errors.js";
3
+ import type { PlatformSocketErrorCode } from "../errors.types.js";
4
+ import type { PlatformSubscription, SubscriptionOptions } from "./builder.types.js";
5
+ /** @internal */
6
+ export declare function notify(callback: (error: PlatformSocketError) => void, error: PlatformSocketError): void;
7
+ /** @internal */
8
+ export declare class Subscription implements PlatformSubscription {
9
+ readonly appId: string;
10
+ private options;
11
+ private remove;
12
+ cursor: string | undefined;
13
+ active: boolean;
14
+ private ready;
15
+ private pending;
16
+ private tail;
17
+ constructor(appId: string, options: SubscriptionOptions, remove: () => void);
18
+ enqueue(work: () => void | Promise<void>): void;
19
+ join(send: (cursor?: string) => void): void;
20
+ event(event: PlatformEvent): void;
21
+ joined(joined: Joined): void;
22
+ fail(code: PlatformSocketErrorCode): void;
23
+ unsubscribe(): void;
24
+ }
@@ -0,0 +1,69 @@
1
+ import { PlatformSocketError } from "../errors.js";
2
+ /** @internal */
3
+ export function notify(callback, error) {
4
+ try {
5
+ callback(error);
6
+ }
7
+ catch ( /* An error observer cannot interrupt other app subscriptions. */_a) { /* An error observer cannot interrupt other app subscriptions. */ }
8
+ }
9
+ /** @internal */
10
+ export class Subscription {
11
+ constructor(appId, options, remove) {
12
+ this.appId = appId;
13
+ this.options = options;
14
+ this.remove = remove;
15
+ this.active = true;
16
+ this.ready = false;
17
+ this.pending = 0;
18
+ this.tail = Promise.resolve();
19
+ this.cursor = options.afterSeq;
20
+ }
21
+ enqueue(work) {
22
+ if (!this.active)
23
+ return;
24
+ if (this.pending >= 1000) {
25
+ this.fail("resync_required");
26
+ return;
27
+ }
28
+ this.pending++;
29
+ this.tail = this.tail.then(async () => {
30
+ if (this.active)
31
+ await work();
32
+ }).catch(() => this.fail("handler_failed")).finally(() => { this.pending--; });
33
+ }
34
+ join(send) {
35
+ this.enqueue(() => { this.ready = false; send(this.cursor); });
36
+ }
37
+ event(event) {
38
+ this.enqueue(async () => {
39
+ // A fresh subscription starts at joined, not at any old in-flight room events.
40
+ if ((!this.ready && this.cursor === undefined) || event.seq === this.cursor)
41
+ return;
42
+ await this.options.onEvent(event);
43
+ if (this.active)
44
+ this.cursor = event.seq;
45
+ });
46
+ }
47
+ joined(joined) {
48
+ this.enqueue(async () => {
49
+ var _a, _b;
50
+ await ((_b = (_a = this.options).onJoined) === null || _b === void 0 ? void 0 : _b.call(_a, joined));
51
+ if (this.active) {
52
+ this.cursor = joined.seq;
53
+ this.ready = true;
54
+ }
55
+ });
56
+ }
57
+ fail(code) {
58
+ if (!this.active)
59
+ return;
60
+ this.unsubscribe();
61
+ notify(this.options.onError, new PlatformSocketError(code, this.appId));
62
+ }
63
+ unsubscribe() {
64
+ if (!this.active)
65
+ return;
66
+ this.active = false;
67
+ this.remove();
68
+ }
69
+ }
@@ -0,0 +1,4 @@
1
+ import type { PlatformClientOptions } from "../client.types.js";
2
+ import type { BuilderModule } from "./builder.types.js";
3
+ /** @internal */
4
+ export declare function createBuilder(config: PlatformClientOptions): BuilderModule;
@@ -0,0 +1,280 @@
1
+ /** A reviewed file, execution, or entity activity summary. */
2
+ export interface ToolDisplayProjection {
3
+ /** Changed file paths for a file operation. Source bodies and diffs are never included. */
4
+ file_paths?: string[];
5
+ /** Whether a file write intentionally used empty content. */
6
+ content_empty?: boolean;
7
+ /** Reviewed execution activity summary. Commands and execution output are never included. */
8
+ summary?: string;
9
+ /** Whether a reviewed execution action changed entity data. */
10
+ writes_entities?: boolean;
11
+ /** Entity type affected by an entity operation. Records and query values are never included. */
12
+ entity_name?: string;
13
+ /** Number of records affected when supplied by the producer. */
14
+ record_count?: number;
15
+ }
16
+ /** A reviewed selectable answer to a builder question. */
17
+ export interface ToolQuestionOption {
18
+ /** Visible option label. */
19
+ label: string;
20
+ }
21
+ /** A reviewed builder question. Image/HTML source and private design context are excluded. */
22
+ export interface ToolQuestion {
23
+ /** Visible question text. */
24
+ question?: string;
25
+ /** Existing question category. */
26
+ type?: string;
27
+ /** Optional visible supporting text. */
28
+ description?: string;
29
+ /** Whether more than one answer may be selected. */
30
+ multi_select?: boolean;
31
+ /** Optional existing plan section identifier. */
32
+ covers?: string;
33
+ /** Reviewed selectable options. */
34
+ options?: ToolQuestionOption[];
35
+ }
36
+ /** Reviewed question arguments, serialized in `ToolCall.arguments_string`. */
37
+ export interface ToolQuestionArguments {
38
+ /** Questions presented by a clarifying-question tool. */
39
+ questions: ToolQuestion[];
40
+ }
41
+ /** A requested secret field. The secret value is never sent over the socket. */
42
+ export interface ToolSecretField {
43
+ /** Requested secret name. */
44
+ secretName: string;
45
+ /** Optional explanation of where to obtain it. */
46
+ description?: string;
47
+ }
48
+ /** Reviewed secret-form arguments, serialized in `ToolCall.arguments_string`. */
49
+ export interface ToolSecretArguments {
50
+ /** Requested secret fields. */
51
+ secrets_schema: ToolSecretField[];
52
+ }
53
+ /** A reviewed package operation. Versions and package-manager output are excluded. */
54
+ export interface ToolPackageOperation {
55
+ /** Package name. */
56
+ name: string;
57
+ /** Requested package operation. */
58
+ action?: string;
59
+ }
60
+ /** Reviewed package arguments, serialized in `ToolCall.arguments_string`. */
61
+ export interface ToolPackageArguments {
62
+ /** Requested package operations. */
63
+ packages: ToolPackageOperation[];
64
+ }
65
+ /** A reviewed add-only builder plan update. */
66
+ export interface ToolPlanUpdate {
67
+ /** Existing update action. */
68
+ action?: string;
69
+ /** Plan section key. */
70
+ section?: string;
71
+ /** Optional user-facing section label. */
72
+ section_label?: string;
73
+ /** Reviewed plan point. */
74
+ text?: string;
75
+ }
76
+ /** Reviewed plan arguments, serialized in `ToolCall.arguments_string`. */
77
+ export interface ToolPlanArguments {
78
+ /** Plan updates in their emitted order. */
79
+ updates?: ToolPlanUpdate[];
80
+ /** Base plan sections the builder considers sufficiently specified. */
81
+ sections_with_enough?: string[];
82
+ }
83
+ /** Reviewed generated-media arguments, serialized in `ToolCall.arguments_string`. */
84
+ export interface ToolMediaArguments {
85
+ /** Visible media label. */
86
+ label?: string;
87
+ /** Requested image or video aspect ratio. */
88
+ aspect_ratio?: string;
89
+ }
90
+ /** A reviewed answer to a clarifying question. Secret-form input is never included. */
91
+ export interface ToolQuestionAnswer {
92
+ /** Zero-based question index. */
93
+ question_index?: number;
94
+ /** Labels selected by the user. */
95
+ selected_labels?: string[];
96
+ /** User-provided free-text answer. Structural filtering does not redact prose. */
97
+ custom_text?: string;
98
+ }
99
+ /** Reviewed clarifying-question input. */
100
+ export interface ToolQuestionInput {
101
+ /** Answers supplied to the question card. */
102
+ answers: ToolQuestionAnswer[];
103
+ }
104
+ /** Fixed reviewed completion text. Raw tool results and errors are never included. */
105
+ export type ToolOutcome = "Secret configuration completed." | "Package installation completed." | "Plan updated.";
106
+ /** Public progress of an existing builder tool. */
107
+ export interface ToolCall {
108
+ /** Stable tool call identifier, when included in the update. */
109
+ id?: string;
110
+ /** Tool name displayed by the builder. */
111
+ name?: string;
112
+ /** Current execution state. */
113
+ status?: "running" | "success" | "error" | "stopped" | "waiting_for_user_input";
114
+ /** Whether the tool needs a user response through the partner backend. */
115
+ requires_user_input?: boolean;
116
+ /** Whether the builder auto-approved the reviewed operation. */
117
+ auto_approved?: boolean | null;
118
+ /** Whether the reviewed mutation was applied. */
119
+ mutation_applied?: boolean | null;
120
+ /** Existing serialized interaction category; no raw interaction payload. */
121
+ waiting_on?: {
122
+ /** Kind of response expected. */
123
+ kind?: "approval" | "choice" | "input" | null;
124
+ } | null;
125
+ /**
126
+ * JSON containing one reviewed argument shape: ToolQuestionArguments,
127
+ * ToolSecretArguments, ToolPackageArguments, ToolPlanArguments, or ToolMediaArguments.
128
+ * It is omitted for all other tools and malformed/partial streaming arguments.
129
+ */
130
+ arguments_string?: string;
131
+ /** Reviewed activity metadata for file, execution, or entity tools. */
132
+ display_projection?: ToolDisplayProjection;
133
+ /** Reviewed clarifying-question answers only. */
134
+ user_input?: ToolQuestionInput;
135
+ /** Fixed reviewed success outcome only. */
136
+ results?: ToolOutcome;
137
+ }
138
+ /** Public message replacement. Omitted properties are not synthesized by the SDK. */
139
+ export interface ChatMessage {
140
+ /** Existing message identifier; replace a message with the same identifier. */
141
+ id?: string;
142
+ /** Public message author category. System messages are never delivered. */
143
+ role?: "user" | "assistant";
144
+ /** Generated or user-authored text. Structural filtering is not prose redaction. */
145
+ content?: string | null;
146
+ /** Attached file URLs. */
147
+ file_urls?: string[] | null;
148
+ /** Public tool progress with optional reviewed interaction details. */
149
+ tool_calls?: ToolCall[] | null;
150
+ /** Message timestamp, without author identity. */
151
+ metadata?: {
152
+ /** Existing timestamp string. */
153
+ created_date?: string | null;
154
+ } | null;
155
+ /** Existing checkpoint reference; mutations remain on the partner backend. */
156
+ checkpoint_id?: string | null;
157
+ }
158
+ /** Partial app update. Omitted keys mean unchanged; explicit null means clear. */
159
+ export interface AppUpdate {
160
+ /** Public builder state, without error diagnostics or billing context. */
161
+ status?: {
162
+ /** Current builder state. */
163
+ state?: "ready" | "processing" | "error";
164
+ /** Existing state timestamp. */
165
+ last_updated_date?: string | null;
166
+ } | null;
167
+ /** Whole-message replacement by identifier, not a recursive message patch. */
168
+ _last_msg?: ChatMessage | null;
169
+ /** Conversation containing the replacement message. */
170
+ _last_msg_conversation_id?: string | null;
171
+ /** Existing branch scope, if supplied by the producer. */
172
+ _scope_branch_id?: string | null;
173
+ /** Whether to reload the app preview. */
174
+ sandbox_should_reload?: boolean | null;
175
+ /** Existing preview navigation target. */
176
+ navigate_preview_to?: string | null;
177
+ /** Existing forced preview navigation target. */
178
+ navigate_preview_force_to?: string | null;
179
+ }
180
+ /** Public queued builder request. */
181
+ export interface QueueItem {
182
+ /** Stable queue item identifier. */
183
+ id: string;
184
+ /** User-authored request text. */
185
+ content: string;
186
+ /** Attached file URLs. */
187
+ file_urls?: string[] | null;
188
+ /** Existing creation timestamp. */
189
+ created_at: string;
190
+ /** Existing branch scope. */
191
+ branch_id?: string | null;
192
+ }
193
+ /** Full public queue snapshot, replacing the previous queue. */
194
+ export interface QueueUpdate {
195
+ /** App owning this queue. */
196
+ app_id: string;
197
+ /** Existing branch scope. */
198
+ branch_id?: string | null;
199
+ /** Current pending items. */
200
+ items: QueueItem[];
201
+ /** Whether queue processing is paused. */
202
+ is_paused: boolean;
203
+ /** Identifier of the item just processed, when supplied. */
204
+ processed_item_id?: string | null;
205
+ }
206
+ /** Public tool task progress. */
207
+ export interface TaskUpdate {
208
+ /** Existing task lifecycle event. */
209
+ event_type: "task_started" | "task_progress" | "task_completed" | "task_failed" | "task_cancelled";
210
+ /** Associated tool call. */
211
+ tool_call_id?: string | null;
212
+ /** Associated chat message. */
213
+ message_id?: string | null;
214
+ /** Existing branch scope. */
215
+ branch_id?: string | null;
216
+ /** Numeric progress only; diagnostic/free-text messages are withheld. */
217
+ progress?: {
218
+ /** Completed work units. */
219
+ current?: number | null;
220
+ /** Total work units, when known. */
221
+ total?: number | null;
222
+ /** Producer-supplied percentage. */
223
+ percentage?: number | null;
224
+ } | null;
225
+ }
226
+ /** Placeholder resolution or image-generation completion. */
227
+ export interface ImageReady {
228
+ /** Placeholder being resolved. */
229
+ placeholder_url: string;
230
+ /** Existing generation state. */
231
+ status: "pending" | "completed" | "failed";
232
+ /** Resolved image URL, or null when unavailable. */
233
+ image_url?: string | null;
234
+ }
235
+ /** Invalidation notice; fetch current state through the partner backend. */
236
+ export interface Directive {
237
+ /** Canonical app room. */
238
+ room: string;
239
+ /** Public invalidation category. */
240
+ type: "conversation_changed" | "app_files_changed";
241
+ /** Existing branch scope. */
242
+ branch_id?: string | null;
243
+ }
244
+ /** Mapping of wire event names to decoded public payloads. */
245
+ export interface PlatformEventMap {
246
+ /** Partial builder/app update. */
247
+ update_model: AppUpdate;
248
+ /** Conversation or file invalidation. */
249
+ directive: Directive;
250
+ /** Full queue snapshot. */
251
+ queue_update: QueueUpdate;
252
+ /** Numeric tool progress. */
253
+ task_update: TaskUpdate;
254
+ /** Image placeholder resolution. */
255
+ image_ready: ImageReady;
256
+ }
257
+ /** Ordered delivery with decoded data and the original event name and cursor. */
258
+ export type PlatformEvent = {
259
+ [K in keyof PlatformEventMap]: {
260
+ /** Original socket event name; narrows the payload type. */
261
+ type: K;
262
+ /** Authorized app receiving this event. */
263
+ appId: string;
264
+ /** Opaque replay cursor. Never parse, compare or increment it. */
265
+ seq: string;
266
+ /** Decoded payload; existing field names and omission/null semantics are retained. */
267
+ data: PlatformEventMap[K];
268
+ };
269
+ }[keyof PlatformEventMap];
270
+ /** Server replay boundary, delivered after all retained events through that boundary. */
271
+ export interface Joined {
272
+ /** Canonical app room. */
273
+ room: string;
274
+ /** Opaque boundary cursor; not an initial app snapshot. */
275
+ seq: string;
276
+ /** Server retention limit (currently 2,000 events per app). */
277
+ max_entries: number;
278
+ /** Server inactivity expiry (currently 3,600 seconds). */
279
+ inactivity_expiry_seconds: number;
280
+ }
@@ -0,0 +1,7 @@
1
+ import { BuilderSocket } from "./builder-socket.js";
2
+ /** @internal */
3
+ export function createBuilder(config) {
4
+ return {
5
+ init(options) { return new BuilderSocket(config, options); },
6
+ };
7
+ }
@@ -0,0 +1,48 @@
1
+ import type { Joined, PlatformEvent } from "./builder.events.types.js";
2
+ import type { PlatformSocketError } from "../errors.js";
3
+ /** Options for an independent builder socket session. */
4
+ export interface BuilderInitOptions {
5
+ /** Connection-level errors, sanitized to exclude tokens and server exception text. */
6
+ onError: (error: PlatformSocketError) => void;
7
+ }
8
+ /** Lazy builder module; no socket exists until init is called. */
9
+ export interface BuilderModule {
10
+ /** Create an independent session without connecting. Call connect on the returned session. */
11
+ init(options: BuilderInitOptions): BuilderSession;
12
+ }
13
+ /** One builder socket session. Owns its subscriptions and connection lifecycle. */
14
+ export interface BuilderSession {
15
+ /** Connect with a refreshed browser token; resolves on CONNECT, before app replay completes.
16
+ * Transport loss retries five times and rejoins active subscriptions from applied cursors.
17
+ * Call again after fixing connection/auth failures. Concurrent calls share one attempt.
18
+ */
19
+ connect(): Promise<void>;
20
+ /** Subscribe before or after connecting. One subscription per app, up to eight per session.
21
+ * Callbacks run serially per app; errors stop delivery without advancing the cursor.
22
+ */
23
+ subscribe(appId: string, options: SubscriptionOptions): PlatformSubscription;
24
+ /** Stop this session, its subscriptions and reconnection. Idempotent and terminal. */
25
+ close(): void;
26
+ }
27
+ /** One app subscription; at most eight may be active per builder session. */
28
+ export interface SubscriptionOptions {
29
+ /** Last successfully applied cursor for this app; omit for a fresh live boundary. */
30
+ afterSeq?: string;
31
+ /** Apply each event. Delivery is serial per app; rejection pauses this subscription. */
32
+ onEvent: (event: PlatformEvent) => void | Promise<void>;
33
+ /** Handle subscription errors. Reconcile on resync_required; never silently reset a cursor. */
34
+ onError: (error: PlatformSocketError) => void;
35
+ /** Optional replay-complete notification, awaited before advancing to the boundary cursor. */
36
+ onJoined?: (joined: Joined) => void | Promise<void>;
37
+ }
38
+ /** Subscription lifetime and last successfully applied cursor. */
39
+ export interface PlatformSubscription {
40
+ /** App identifier. */
41
+ readonly appId: string;
42
+ /** Last applied event/boundary cursor; persist alongside the state it describes. */
43
+ readonly cursor: string | undefined;
44
+ /** True while subscribed; false after an error or explicit unsubscribe. */
45
+ readonly active: boolean;
46
+ /** Stop this app's delivery and release its subscription slot. Idempotent. */
47
+ unsubscribe(): void;
48
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.48-pr.284.e0a8d2f",
3
+ "version": "0.8.48-pr.286.d14ea24",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -9,8 +9,8 @@
9
9
  "dist"
10
10
  ],
11
11
  "scripts": {
12
- "build": "tsc",
13
- "lint": "eslint src",
12
+ "build": "npm run build:runtime && npm run build:platform",
13
+ "lint": "eslint src platform-src examples/platform-client.ts",
14
14
  "test": "npm run test:types && vitest run",
15
15
  "test:types": "tsc --noEmit -p tsconfig.type-tests.json",
16
16
  "test:unit": "vitest run tests/unit",
@@ -23,7 +23,11 @@
23
23
  "create-docs-local": "npm run create-docs && npm run copy-docs-local",
24
24
  "copy-docs-local": "node scripts/mintlify-post-processing/copy-to-local-docs.js",
25
25
  "create-docs:generate": "typedoc",
26
- "create-docs:process": "node scripts/mintlify-post-processing/file-processing/file-processing.js"
26
+ "create-docs:process": "node scripts/mintlify-post-processing/file-processing/file-processing.js",
27
+ "build:runtime": "tsc",
28
+ "build:platform": "tsc -p tsconfig.platform.json",
29
+ "docs:platform-client": "typedoc --options typedoc.platform-client.json",
30
+ "test:package": "npm run build && node --test tests/package/platform-client.test.mjs"
27
31
  },
28
32
  "dependencies": {
29
33
  "axios": "^1.18.1",
@@ -63,5 +67,36 @@
63
67
  "bugs": {
64
68
  "url": "https://github.com/base44/javascript-sdk/issues"
65
69
  },
66
- "homepage": "https://github.com/base44/javascript-sdk#readme"
70
+ "homepage": "https://github.com/base44/javascript-sdk#readme",
71
+ "exports": {
72
+ ".": {
73
+ "types": "./dist/index.d.ts",
74
+ "default": "./dist/index.js"
75
+ },
76
+ "./dist/*.d.ts": "./dist/*.d.ts",
77
+ "./dist/*.js": {
78
+ "types": "./dist/*.d.ts",
79
+ "default": "./dist/*.js"
80
+ },
81
+ "./dist/*": {
82
+ "types": "./dist/*.d.ts",
83
+ "default": "./dist/*.js"
84
+ },
85
+ "./package.json": "./package.json",
86
+ "./*": "./*",
87
+ "./platform/client": {
88
+ "types": "./dist/platform/client/index.d.ts",
89
+ "default": "./dist/platform/client/index.js"
90
+ }
91
+ },
92
+ "typesVersions": {
93
+ "*": {
94
+ "platform/client": [
95
+ "dist/platform/client/index.d.ts"
96
+ ],
97
+ "*": [
98
+ "*"
99
+ ]
100
+ }
101
+ }
67
102
  }