@base44-preview/platform 0.2.0-pr.313.e5d2766 → 0.2.0-pr.315.9d1cad2

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.
Files changed (42) hide show
  1. package/README.md +31 -2
  2. package/dist/{modules → client/modules}/builder-socket.d.ts +1 -0
  3. package/dist/{modules → client/modules}/builder-socket.js +24 -7
  4. package/dist/{modules → client/modules}/builder.types.d.ts +6 -0
  5. package/dist/react/chat-items.d.ts +46 -0
  6. package/dist/react/chat-items.js +134 -0
  7. package/dist/react/chat.types.d.ts +201 -0
  8. package/dist/react/chat.types.js +1 -0
  9. package/dist/react/index.d.ts +4 -0
  10. package/dist/react/index.js +2 -0
  11. package/dist/react/useBase44Chat.d.ts +48 -0
  12. package/dist/react/useBase44Chat.js +280 -0
  13. package/dist/server/index.d.ts +3 -0
  14. package/dist/server/index.js +2 -0
  15. package/dist/server/server-url.d.ts +2 -0
  16. package/dist/server/server-url.js +8 -0
  17. package/dist/server/server.d.ts +3 -0
  18. package/dist/server/server.js +8 -0
  19. package/dist/server/server.types.d.ts +10 -0
  20. package/dist/server/server.types.js +1 -0
  21. package/package.json +43 -11
  22. /package/dist/{client.d.ts → client/client.d.ts} +0 -0
  23. /package/dist/{client.js → client/client.js} +0 -0
  24. /package/dist/{client.types.d.ts → client/client.types.d.ts} +0 -0
  25. /package/dist/{client.types.js → client/client.types.js} +0 -0
  26. /package/dist/{errors.d.ts → client/errors.d.ts} +0 -0
  27. /package/dist/{errors.js → client/errors.js} +0 -0
  28. /package/dist/{errors.types.d.ts → client/errors.types.d.ts} +0 -0
  29. /package/dist/{errors.types.js → client/errors.types.js} +0 -0
  30. /package/dist/{index.d.ts → client/index.d.ts} +0 -0
  31. /package/dist/{index.js → client/index.js} +0 -0
  32. /package/dist/{modules → client/modules}/builder-protocol.d.ts +0 -0
  33. /package/dist/{modules → client/modules}/builder-protocol.js +0 -0
  34. /package/dist/{modules → client/modules}/builder-subscription.d.ts +0 -0
  35. /package/dist/{modules → client/modules}/builder-subscription.js +0 -0
  36. /package/dist/{modules → client/modules}/builder.d.ts +0 -0
  37. /package/dist/{modules → client/modules}/builder.events.generated.d.ts +0 -0
  38. /package/dist/{modules → client/modules}/builder.events.generated.js +0 -0
  39. /package/dist/{modules → client/modules}/builder.events.types.d.ts +0 -0
  40. /package/dist/{modules → client/modules}/builder.events.types.js +0 -0
  41. /package/dist/{modules → client/modules}/builder.js +0 -0
  42. /package/dist/{modules → client/modules}/builder.types.js +0 -0
package/README.md CHANGED
@@ -101,7 +101,8 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
101
101
 
102
102
  - `PlatformClient` (`client.types.ts`): the `builder` module.
103
103
  - `BuilderModule` (`modules/builder.types.ts`): lazy `init(options)` factory.
104
- - `BuilderInitOptions`: `getSession` and the connection-level `onError` observer.
104
+ - `BuilderInitOptions`: `getSession`, the connection-level `onError` observer, and an optional
105
+ `onConnectionChange` that reports `connected` and `reconnecting`.
105
106
  - `SocketSession`: the `session_token`, `socket_url` and `socket_path` that `getSession` returns.
106
107
  - `BuilderSession`: `connect()`, `subscribe(appId, options)`, `close()`.
107
108
  - `SubscriptionOptions`: required `onSnapshot`, `onEvent` and `onError`.
@@ -124,7 +125,7 @@ redaction of generated prose or user content.
124
125
  ## Event types
125
126
 
126
127
  The socket protocol is defined by the service's AsyncAPI document, committed as
127
- `asyncapi.json`. `src/modules/builder.events.generated.ts` is generated from it with
128
+ `asyncapi.json`. `src/client/modules/builder.events.generated.ts` is generated from it with
128
129
  `json-schema-to-typescript`: one type per schema, named after the backend model
129
130
  (`Message`, `StatusObject`, `QueueState`, one `*Call` per tool, one `*Approval` per
130
131
  guard), plus `ServerEventMap` and `ClientMessageMap`. Never edit it by hand.
@@ -170,3 +171,31 @@ exceptions, payloads and credentials are never attached.
170
171
 
171
172
  No SDK dependency, package version or lockfile changes are required. Socket.IO
172
173
  remains the existing SDK dependency. Chat commands and HTTP APIs are outside this entry point.
174
+
175
+ ## React
176
+
177
+ `@base44/platform/react` adds one hook, `useBase44Chat`, that runs a builder chat for one
178
+ app on top of this client: it opens the live session and renews it, turns messages into items
179
+ made for rendering, binds every question the builder asks to the step it belongs to. It renders nothing. React is an optional peer dependency, loaded only by this
180
+ entry; the root entry stays framework-free.
181
+
182
+ ```tsx
183
+ import { useBase44Chat } from "@base44/platform/react";
184
+
185
+ const chat = useBase44Chat({ appId, backend, onAppCreated });
186
+ chat.items.map((item) =>
187
+ item.steps.map((step) => step.question?.kind === "approval" && <button onClick={step.question.approve}>Allow</button>),
188
+ );
189
+ ```
190
+
191
+ `backend` is four functions your backend provides, in any language behind them: `createApp`,
192
+ `openLiveSession`, `sendMessage` and `submitToolCallInput`, each wrapping one Base44 REST
193
+ call with your credentials, so the browser never holds a key. The hook returns `items`, a
194
+ `status` (`ready`, `submitted`, `building`, `waiting`, `error`), a `connection` (`connecting`,
195
+ `connected`, `reconnecting`, `disconnected`), an `error`, and the actions `send`, `create` and `clearError`. `send` needs an app; `create` makes
196
+ the first, and the chat watches it while `appId` is `null`. A sent prompt shows at once as a
197
+ `pending` item; to let the user send only when the builder can take it now, disable the input
198
+ unless `status` is `ready` or `error`. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
199
+ actions its kind allows; declining is always one of them, and a kind this release doesn't know is
200
+ declined for you. Every shape has JSDoc in `src/react/chat.types.ts`, and
201
+ [`examples/react-chat/`](examples/react-chat) shows Tiny Sunny's chat built on it, with its `backend`.
@@ -40,6 +40,7 @@ export declare class BuilderSocket implements BuilderSession {
40
40
  private refused;
41
41
  private retryDenied;
42
42
  private clearConnecting;
43
+ private connectionChanged;
43
44
  private connectionError;
44
45
  private sessionEnded;
45
46
  private roomNotice;
@@ -11,7 +11,7 @@ export class BuilderSocket {
11
11
  this.tokenFresh = false;
12
12
  this.denialRetries = 0;
13
13
  this.authAttempt = 0;
14
- this.options = { getSession: options.getSession, onError: options.onError };
14
+ this.options = { getSession: options.getSession, onError: options.onError, onConnectionChange: options.onConnectionChange };
15
15
  }
16
16
  /** Connect with the session's token. Resolves on CONNECT, before snapshots arrive.
17
17
  * The first call fetches the session, whose address the socket opens on.
@@ -94,15 +94,22 @@ export class BuilderSocket {
94
94
  this.join(subscription);
95
95
  (_a = this.resolveConnect) === null || _a === void 0 ? void 0 : _a.call(this);
96
96
  this.clearConnecting();
97
+ this.connectionChanged("connected");
97
98
  });
98
99
  socket.on("disconnect", (reason) => {
99
100
  ++this.authAttempt;
100
- if (this.closed || reason !== "io server disconnect")
101
- return; // Transport loss reconnects by itself.
101
+ if (this.closed || reason === "io client disconnect")
102
+ return;
103
+ if (reason !== "io server disconnect") {
104
+ this.connectionChanged("reconnecting");
105
+ return;
106
+ } // Transport loss reconnects by itself.
102
107
  const ending = this.ending;
103
108
  this.ending = undefined;
104
- if (ending === "session_expired")
105
- socket.connect(); // Renew through getSession.
109
+ if (ending === "session_expired") { // Renew through getSession.
110
+ this.connectionChanged("reconnecting");
111
+ socket.connect();
112
+ }
106
113
  else
107
114
  this.connectionError(new PlatformSocketError(ending !== null && ending !== void 0 ? ending : "connection_failed"));
108
115
  });
@@ -123,8 +130,11 @@ export class BuilderSocket {
123
130
  socket.on(name, (raw) => this.roomNotice(code, raw));
124
131
  for (const name of eventNames)
125
132
  socket.on(name, (raw) => this.appEvent(name, raw));
126
- socket.onAny((name, raw) => { if (isUnknownEvent(name))
127
- this.appEvent(name, raw); });
133
+ // An unknown event with no app room (a future session-wide event) has nowhere to go: ignore it.
134
+ socket.onAny((name, raw) => {
135
+ if (isUnknownEvent(name) && appFromRoom(raw === null || raw === void 0 ? void 0 : raw.room))
136
+ this.appEvent(name, raw);
137
+ });
128
138
  socket.connect();
129
139
  }
130
140
  appEvent(name, raw) {
@@ -223,6 +233,13 @@ export class BuilderSocket {
223
233
  this.resolveConnect = undefined;
224
234
  this.rejectConnect = undefined;
225
235
  }
236
+ connectionChanged(state) {
237
+ var _a, _b;
238
+ try {
239
+ (_b = (_a = this.options).onConnectionChange) === null || _b === void 0 ? void 0 : _b.call(_a, state);
240
+ }
241
+ catch ( /* An observer cannot interrupt the connection. */_c) { /* An observer cannot interrupt the connection. */ }
242
+ }
226
243
  connectionError(error) {
227
244
  var _a;
228
245
  (_a = this.rejectConnect) === null || _a === void 0 ? void 0 : _a.call(this, error);
@@ -34,6 +34,12 @@ export interface BuilderInitOptions {
34
34
  * [error codes](/developers/references/platform-sdk/docs/classes/PlatformSocketError#platformsocketerrorcode).
35
35
  */
36
36
  onError: (error: PlatformSocketError) => void;
37
+ /**
38
+ * Called when the socket connects, and when a connected socket drops and will retry.
39
+ * `reconnecting` arrives on a lost connection or an expired session that renews; `connected`
40
+ * on every successful connect. A retry that gives up reports through `onError` instead.
41
+ */
42
+ onConnectionChange?: (state: "connected" | "reconnecting") => void;
37
43
  }
38
44
  /**
39
45
  * Builder module for following the AI chat in your users' apps live.
@@ -0,0 +1,46 @@
1
+ import type { Message } from "../client/modules/builder.events.generated.js";
2
+ import type { ToolCall } from "../client/modules/builder.events.types.js";
3
+ import type { ChatItem, ChatQuestion, ChatStep } from "./chat.types.js";
4
+ /** @internal Submits one reply for the tool call the question belongs to. */
5
+ export type Reply = (approve: boolean, extraUserInput?: Record<string, unknown>) => Promise<void>;
6
+ /** @internal Submits a reply for a given tool call in a given message. */
7
+ export type Respond = (toolCallId: string, messageId: string, approve: boolean, extraUserInput?: Record<string, unknown>) => Promise<void>;
8
+ /** @internal Events can arrive out of order, so messages are ordered by when they were created. */
9
+ export declare function sortMessages(messages: Message[]): Message[];
10
+ /** @internal Replaces the message with the same id in place, or adds it at the end. */
11
+ export declare function mergeMessage(all: Message[], message: Message): Message[];
12
+ /** @internal How many of the newest messages a snapshot holds. */
13
+ export declare const SNAPSHOT_SIZE = 50;
14
+ /** @internal A rejoin's snapshot holds only the newest messages: it is the truth for its window,
15
+ * and the messages before its oldest one stay. A snapshot with room to spare holds them all. */
16
+ export declare function mergeSnapshot(all: Message[], snapshot: Message[]): Message[];
17
+ /** @internal Turns sorted messages into items. Every tool call that waits, is not in `answered`
18
+ * and is of a kind this release knows carries its own question. */
19
+ export declare function toItems(sorted: Message[], answered: string[], respond: Respond): ChatItem[];
20
+ /** @internal Base44's tool call status, as a step's. */
21
+ export declare function stepStatus(tool: ToolCall): ChatStep["status"];
22
+ /** @internal Whether some tool call waits on the user and has not been answered here. */
23
+ export declare function isWaiting(sorted: Message[], answered: string[]): boolean;
24
+ /** @internal Waiting tool calls of a kind this release can't show, to decline. */
25
+ export declare function unknownWaiting(sorted: Message[]): {
26
+ toolCallId: string;
27
+ messageId: string;
28
+ }[];
29
+ /** @internal A prompt sent from this chat that Base44 has not confirmed, for the app it went to. */
30
+ export interface PendingPrompt {
31
+ id: string;
32
+ content: string;
33
+ createdAt: string;
34
+ appId: string;
35
+ }
36
+ /** @internal Prompts that arrived from Base44 as messages settle the pending ones
37
+ * with the same text. Base44's public send carries no client id, so text is the only link. With
38
+ * `oldestOtherwise`, an arrival that matches none settles the oldest, so a prompt Base44 changed
39
+ * on the way never stays pending. */
40
+ export declare function settlePending(pending: PendingPrompt[], appId: string, arrived: string[], oldestOtherwise: boolean): PendingPrompt[];
41
+ /** @internal Pending prompts as items, after the messages Base44 has. */
42
+ export declare function pendingItems(pending: PendingPrompt[]): ChatItem[];
43
+ /** @internal Base44's question formats, as one simple shape per kind, each bound to the reply that
44
+ * answers it. Base44 keys choice answers by position, so `picked` follows `questions`. A kind this
45
+ * release doesn't know has no shape. */
46
+ export declare function bindQuestion(tool: ToolCall, reply: Reply): ChatQuestion | undefined;
@@ -0,0 +1,134 @@
1
+ /** @internal Events can arrive out of order, so messages are ordered by when they were created. */
2
+ export function sortMessages(messages) {
3
+ return [...messages].sort((a, b) => { var _a, _b, _c, _d; return ((_b = (_a = a.metadata) === null || _a === void 0 ? void 0 : _a.created_date) !== null && _b !== void 0 ? _b : "").localeCompare((_d = (_c = b.metadata) === null || _c === void 0 ? void 0 : _c.created_date) !== null && _d !== void 0 ? _d : ""); });
4
+ }
5
+ /** @internal Replaces the message with the same id in place, or adds it at the end. */
6
+ export function mergeMessage(all, message) {
7
+ return all.some(m => m.id === message.id) ? all.map(m => (m.id === message.id ? message : m)) : [...all, message];
8
+ }
9
+ /** @internal How many of the newest messages a snapshot holds. */
10
+ export const SNAPSHOT_SIZE = 50;
11
+ /** @internal A rejoin's snapshot holds only the newest messages: it is the truth for its window,
12
+ * and the messages before its oldest one stay. A snapshot with room to spare holds them all. */
13
+ export function mergeSnapshot(all, snapshot) {
14
+ var _a, _b, _c;
15
+ if (snapshot.length < SNAPSHOT_SIZE)
16
+ return snapshot;
17
+ const oldest = (_c = (_b = (_a = sortMessages(snapshot)[0]) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.created_date) !== null && _c !== void 0 ? _c : "";
18
+ const fresh = new Set(snapshot.map(m => m.id));
19
+ return [...all.filter(m => { var _a, _b; return !fresh.has(m.id) && ((_b = (_a = m.metadata) === null || _a === void 0 ? void 0 : _a.created_date) !== null && _b !== void 0 ? _b : "") < oldest; }), ...snapshot];
20
+ }
21
+ /** @internal Turns sorted messages into items. Every tool call that waits, is not in `answered`
22
+ * and is of a kind this release knows carries its own question. */
23
+ export function toItems(sorted, answered, respond) {
24
+ return sorted.map(m => {
25
+ var _a, _b, _c, _d;
26
+ return ({
27
+ id: m.id,
28
+ role: m.role === "user" ? "user" : "assistant",
29
+ text: (_a = m.content) !== null && _a !== void 0 ? _a : "",
30
+ createdAt: (_c = (_b = m.metadata) === null || _b === void 0 ? void 0 : _b.created_date) !== null && _c !== void 0 ? _c : "",
31
+ pending: false,
32
+ steps: ((_d = m.tool_calls) !== null && _d !== void 0 ? _d : []).map(tool => toStep(tool, answered.includes(tool.id) ? undefined : (approve, extra) => respond(tool.id, m.id, approve, extra))),
33
+ });
34
+ });
35
+ }
36
+ function toStep(tool, reply) {
37
+ var _a, _b;
38
+ const name = (_a = tool.name) !== null && _a !== void 0 ? _a : "";
39
+ // Only file tools carry `display.file_paths`.
40
+ const display = "display" in tool ? tool.display : undefined;
41
+ const files = (_b = display === null || display === void 0 ? void 0 : display.file_paths) !== null && _b !== void 0 ? _b : [];
42
+ const status = stepStatus(tool);
43
+ const question = status === "waiting" && reply ? bindQuestion(tool, reply) : undefined;
44
+ return { id: tool.id, tool: name, files, label: [name, ...files].join(" "), status, ...(question && { question }) };
45
+ }
46
+ /** @internal Base44's tool call status, as a step's. */
47
+ export function stepStatus(tool) {
48
+ if (tool.status === "running")
49
+ return "running";
50
+ if (tool.status === "waiting_for_user_input")
51
+ return "waiting";
52
+ if (tool.status === "stopped")
53
+ return "stopped";
54
+ if (tool.status === "error")
55
+ return "error";
56
+ return "done";
57
+ }
58
+ /** @internal Whether some tool call waits on the user and has not been answered here. */
59
+ export function isWaiting(sorted, answered) {
60
+ return sorted.some(m => { var _a; return (_a = m.tool_calls) === null || _a === void 0 ? void 0 : _a.some(tool => tool.status === "waiting_for_user_input" && !answered.includes(tool.id)); });
61
+ }
62
+ const knownKinds = ["approval", "choice", "input"];
63
+ /** @internal Waiting tool calls of a kind this release can't show, to decline. */
64
+ export function unknownWaiting(sorted) {
65
+ return sorted.flatMap(m => {
66
+ var _a;
67
+ return ((_a = m.tool_calls) !== null && _a !== void 0 ? _a : [])
68
+ .filter(tool => { var _a, _b; return tool.status === "waiting_for_user_input" && !knownKinds.includes((_b = (_a = tool.waiting_on) === null || _a === void 0 ? void 0 : _a.kind) !== null && _b !== void 0 ? _b : ""); })
69
+ .map(tool => ({ toolCallId: tool.id, messageId: m.id }));
70
+ });
71
+ }
72
+ /** @internal Prompts that arrived from Base44 as messages settle the pending ones
73
+ * with the same text. Base44's public send carries no client id, so text is the only link. With
74
+ * `oldestOtherwise`, an arrival that matches none settles the oldest, so a prompt Base44 changed
75
+ * on the way never stays pending. */
76
+ export function settlePending(pending, appId, arrived, oldestOtherwise) {
77
+ var _a;
78
+ let rest = pending;
79
+ for (const text of arrived) {
80
+ const mine = rest.filter(p => p.appId === appId);
81
+ const match = (_a = mine.find(p => p.content.trim() === text.trim())) !== null && _a !== void 0 ? _a : (oldestOtherwise ? mine[0] : undefined);
82
+ if (match)
83
+ rest = rest.filter(p => p !== match);
84
+ }
85
+ return rest;
86
+ }
87
+ /** @internal Pending prompts as items, after the messages Base44 has. */
88
+ export function pendingItems(pending) {
89
+ return pending.map(p => ({ id: p.id, role: "user", text: p.content, createdAt: p.createdAt, steps: [], pending: true }));
90
+ }
91
+ /** @internal Base44's question formats, as one simple shape per kind, each bound to the reply that
92
+ * answers it. Base44 keys choice answers by position, so `picked` follows `questions`. A kind this
93
+ * release doesn't know has no shape. */
94
+ export function bindQuestion(tool, reply) {
95
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
96
+ const kind = (_a = tool.waiting_on) === null || _a === void 0 ? void 0 : _a.kind;
97
+ const decline = () => reply(false);
98
+ if (kind === "choice") {
99
+ const questions = (_c = (_b = argumentsOf(tool)) === null || _b === void 0 ? void 0 : _b.questions) !== null && _c !== void 0 ? _c : [];
100
+ return {
101
+ kind,
102
+ questions: questions.map(q => {
103
+ var _a, _b;
104
+ return ({
105
+ text: (_a = q.question) !== null && _a !== void 0 ? _a : "",
106
+ description: q.description,
107
+ options: ((_b = q.options) !== null && _b !== void 0 ? _b : []).map(o => { var _a; return (typeof o === "string" ? o : (_a = o.label) !== null && _a !== void 0 ? _a : ""); }),
108
+ multi: !!q.multi_select,
109
+ });
110
+ }),
111
+ answer: picked => reply(true, { answers: picked.map((labels, i) => ({ question_index: i, selected_labels: labels })).filter(a => a.selected_labels.length) }),
112
+ decline,
113
+ };
114
+ }
115
+ if (kind === "input") {
116
+ const fields = (_e = (_d = argumentsOf(tool)) === null || _d === void 0 ? void 0 : _d.secrets_schema) !== null && _e !== void 0 ? _e : [];
117
+ return {
118
+ kind: "secrets",
119
+ fields: fields.map(f => { var _a; return ({ name: (_a = f.secretName) !== null && _a !== void 0 ? _a : "", description: f.description }); }),
120
+ submit: values => reply(true, { secrets: values }),
121
+ decline,
122
+ };
123
+ }
124
+ if (kind === "approval") {
125
+ // Guards that declare a reason or a summary carry them; the others name only themselves.
126
+ const approval = tool.approval;
127
+ return { kind, action: (_f = tool.name) !== null && _f !== void 0 ? _f : "", reason: (_j = (_g = approval === null || approval === void 0 ? void 0 : approval.reason) !== null && _g !== void 0 ? _g : (_h = approval === null || approval === void 0 ? void 0 : approval.details) === null || _h === void 0 ? void 0 : _h.summary) !== null && _j !== void 0 ? _j : "", approve: () => reply(true), decline };
128
+ }
129
+ return undefined;
130
+ }
131
+ // The waiting kind says which arguments a call carries; the tool's name only narrows the union.
132
+ function argumentsOf(tool) {
133
+ return "arguments" in tool ? tool.arguments : undefined;
134
+ }
@@ -0,0 +1,201 @@
1
+ import type { SocketSession } from "../client/modules/builder.types.js";
2
+ /** An app the builder works on, as the chat needs it. */
3
+ export interface Base44App {
4
+ /** App identifier: 24 lowercase hexadecimal characters. */
5
+ id: string;
6
+ /** Display name. */
7
+ name: string;
8
+ }
9
+ /** A reply to a question the builder waits on. Declining is `approve: false`. */
10
+ export interface ToolCallAnswer {
11
+ /** The tool call being answered. */
12
+ toolCallId: string;
13
+ /** The assistant message that holds the tool call. */
14
+ messageId: string;
15
+ /** Whether to let the call run (`true`) or turn it down (`false`). */
16
+ approve: boolean;
17
+ /** Content the question asked for: `{ answers }` for a choice, `{ secrets }` for secrets. */
18
+ extraUserInput?: Record<string, unknown>;
19
+ }
20
+ /**
21
+ * The four calls your backend provides. Each wraps one Base44 REST call with your
22
+ * credentials, so the hook never holds a workspace key or an access token, and the
23
+ * backend can be written in any language:
24
+ *
25
+ * - `createApp`: `POST /api/apps` with the first prompt as `initial_message`.
26
+ * - `openLiveSession`: `POST /api/service/socket-sessions` with `{ app_ids: [appId] }`, returning
27
+ * Base44's response body unchanged. Called again whenever the session expires; sessions last
28
+ * one hour. The body holds a session token, never the workspace key.
29
+ * - `sendMessage`: `POST /api/apps/{id}/chat/message`. Base44 queues a prompt sent while the
30
+ * builder is busy, or refuses it with a 409 where the app has no queue: reject then.
31
+ * - `submitToolCallInput`: `POST /api/apps/{id}/chat/submit-tool-call-input`, with an
32
+ * `X-Request-ID` derived from the tool call id so a retry resumes the turn only once.
33
+ *
34
+ * Base44 holds `sendMessage` and `submitToolCallInput` open for the whole turn, so resolve once
35
+ * the request is accepted rather than when it returns: the live session shows the rest.
36
+ * A rejected promise from any of them lands in {@link Base44Chat.error}.
37
+ */
38
+ export interface Base44ChatBackend {
39
+ /** Creates an app from its first prompt. The build starts inside this call. */
40
+ createApp(message: string): Promise<Base44App>;
41
+ /** Opens a read-only live-updates session for one app. */
42
+ openLiveSession(appId: string): Promise<SocketSession>;
43
+ /** Sends a prompt to an existing app. */
44
+ sendMessage(appId: string, content: string): Promise<void>;
45
+ /** Answers, or declines, a question the builder waits on. */
46
+ submitToolCallInput(appId: string, answer: ToolCallAnswer): Promise<void>;
47
+ }
48
+ /** One message of the chat, in a shape made for rendering. */
49
+ export interface ChatItem {
50
+ /** Message identifier. */
51
+ id: string;
52
+ /** Who wrote it. */
53
+ role: "user" | "assistant";
54
+ /** Raw markdown; it comes before the steps. Empty when the message is only tool activity. */
55
+ text: string;
56
+ /** When Base44 created the message, as an ISO timestamp. */
57
+ createdAt: string;
58
+ /** One per tool call, in order. */
59
+ steps: ChatStep[];
60
+ /** A prompt sent from this chat that Base44 has not confirmed yet. It shows at once, and gives
61
+ * way to Base44's own message; a failed send removes it. A prompt sent while the builder is busy
62
+ * waits in Base44's queue and stays pending until it runs. */
63
+ pending: boolean;
64
+ }
65
+ /** One tool call, as a line of activity. */
66
+ export interface ChatStep {
67
+ /** The tool call id. */
68
+ id: string;
69
+ /** The tool's name, e.g. `write_file`. */
70
+ tool: string;
71
+ /** The paths it touched. */
72
+ files: string[];
73
+ /** Tool and files, ready to show. */
74
+ label: string;
75
+ /** Where the call is. `waiting` waits on the user; `stopped` was declined, or the build was stopped. */
76
+ status: "running" | "waiting" | "done" | "stopped" | "error";
77
+ /** The question this step waits on, bound to the actions that answer it. Only while `status` is
78
+ * `waiting`, and gone once answered. */
79
+ question?: ChatQuestion;
80
+ }
81
+ /**
82
+ * An open question, with the actions that answer this question and no other.
83
+ * Each kind carries only the actions that make sense for it, and every kind can be declined.
84
+ * A kind this release doesn't know is declined for you and never appears.
85
+ * The actions never throw: a failure lands in {@link Base44Chat.error} and the question opens again.
86
+ */
87
+ export type ChatQuestion = ChoiceQuestion | SecretsQuestion | ApprovalQuestion;
88
+ /** One of the questions a `choice` asks. */
89
+ export interface ChoiceEntry {
90
+ /** The question text. */
91
+ text: string;
92
+ /** Optional supporting text. */
93
+ description?: string;
94
+ /** The option labels to pick from. */
95
+ options: string[];
96
+ /** Whether more than one option may be picked. */
97
+ multi: boolean;
98
+ }
99
+ /** The builder offers options and wants a pick. */
100
+ export interface ChoiceQuestion {
101
+ /** Discriminator. */
102
+ kind: "choice";
103
+ /** The questions asked, in order. */
104
+ questions: ChoiceEntry[];
105
+ /** Answers with the picked labels: one list per question, in the same order as `questions`. An empty list skips that question. */
106
+ answer(picked: string[][]): Promise<void>;
107
+ /** Declines: the builder continues without the answer. */
108
+ decline(): Promise<void>;
109
+ }
110
+ /** A value the builder needs, such as an API key. */
111
+ export interface SecretField {
112
+ /** The field name, used as the key in `submit`. */
113
+ name: string;
114
+ /** Optional explanation of where to obtain the value. */
115
+ description?: string;
116
+ }
117
+ /** The builder needs secrets, such as API keys. They go to Base44 and are never kept here. */
118
+ export interface SecretsQuestion {
119
+ /** Discriminator. */
120
+ kind: "secrets";
121
+ /** The fields to fill. */
122
+ fields: SecretField[];
123
+ /** Submits the values, keyed by field name. */
124
+ submit(values: Record<string, string>): Promise<void>;
125
+ /** Declines: the builder continues without the values. */
126
+ decline(): Promise<void>;
127
+ }
128
+ /** The builder wants permission to run a proposed action. */
129
+ export interface ApprovalQuestion {
130
+ /** Discriminator. */
131
+ kind: "approval";
132
+ /** The tool that wants to run. */
133
+ action: string;
134
+ /** Why it was parked, when the guard says; empty otherwise. */
135
+ reason: string;
136
+ /** Lets the action run. */
137
+ approve(): Promise<void>;
138
+ /** Declines: the action never runs and the builder continues. */
139
+ decline(): Promise<void>;
140
+ }
141
+ /**
142
+ * What the builder is doing, one value at a time. The first that holds wins:
143
+ *
144
+ * - `error`: Base44 reports the app's build failed.
145
+ * - `waiting`: a step waits on the user.
146
+ * - `building`: the builder is working.
147
+ * - `submitted`: a prompt, a new app or an answer is on its way, until Base44 reports work,
148
+ * a reply or a queue change, or the call fails.
149
+ * - `ready`: everything else.
150
+ *
151
+ * To let the user send only when the builder can take a prompt now:
152
+ * `status === "ready" || status === "error"`.
153
+ */
154
+ export type ChatStatus = "ready" | "submitted" | "building" | "waiting" | "error";
155
+ /** Whether the chat sees the builder live: `connecting` until the first snapshot, `connected`
156
+ * after it, `reconnecting` while the socket retries a dropped connection, and `disconnected`
157
+ * once live updates have stopped for good: the session could not open, the retries ran out, or
158
+ * Base44 ended the session or the app's subscription. {@link Base44Chat.error} says why. Watching
159
+ * another app, or mounting the chat again, starts over. */
160
+ export type ChatConnection = "connecting" | "connected" | "reconnecting" | "disconnected";
161
+ /** A failure: of a call, of the live connection, or of the build itself. */
162
+ export interface ChatError {
163
+ /** What went wrong, for people. */
164
+ message: string;
165
+ /** For code: a `PlatformSocketErrorCode` for a connection error, or `build_failed` when Base44
166
+ * reports the build failed. Absent for a failed call. */
167
+ code?: string;
168
+ /** The original error, for logging. */
169
+ cause?: unknown;
170
+ }
171
+ /** Options of {@link useBase44Chat}. */
172
+ export interface Base44ChatOptions {
173
+ /** The app to watch, or `null` until an app exists. While it is `null`, the chat watches the
174
+ * app {@link Base44Chat.create} just made; any change to it forgets that app. */
175
+ appId: string | null;
176
+ /** Your backend's four calls. Read on every action, so an inline object is fine. */
177
+ backend: Base44ChatBackend;
178
+ /** Called with the new app after {@link Base44Chat.create} succeeds. The chat already watches
179
+ * it; pass its id back as `appId` to keep it watched from your own state. */
180
+ onAppCreated?: (app: Base44App) => void;
181
+ }
182
+ /** What {@link useBase44Chat} returns. */
183
+ export interface Base44Chat {
184
+ /** The conversation, oldest first, with open questions bound to their steps. */
185
+ items: ChatItem[];
186
+ /** What the builder is doing. */
187
+ status: ChatStatus;
188
+ /** Whether the chat sees it live. */
189
+ connection: ChatConnection;
190
+ /** Set whenever `status` is `error`, and on any failed call, until {@link Base44Chat.clearError}
191
+ * or the next action clears it. A failed build stays while Base44 reports it. */
192
+ error: ChatError | null;
193
+ /** Sends a prompt to the current app; Base44 queues it while the builder is busy. Resolves once
194
+ * the request is accepted, and the reply arrives through `items`. Needs an app: without one it
195
+ * sets `error`, and `create` makes the first. */
196
+ send(message: string): Promise<void>;
197
+ /** Creates a new app from its first prompt and reports it through `onAppCreated`. */
198
+ create(message: string): Promise<void>;
199
+ /** Clears a failed call's or the connection's {@link Base44Chat.error}. */
200
+ clearError(): void;
201
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ /** The `@base44/platform/react` entry: one app's builder chat as a hook. React is an optional peer, loaded only here. */
2
+ export { useBase44Chat } from "./useBase44Chat.js";
3
+ export type { ApprovalQuestion, Base44App, Base44Chat, Base44ChatOptions, Base44ChatBackend, ChatConnection, ChatError, ChatItem, ChatQuestion, ChatStatus, ChatStep, ChoiceEntry, ChoiceQuestion, SecretField, SecretsQuestion, ToolCallAnswer, } from "./chat.types.js";
4
+ export type { SocketSession } from "../client/modules/builder.types.js";
@@ -0,0 +1,2 @@
1
+ /** The `@base44/platform/react` entry: one app's builder chat as a hook. React is an optional peer, loaded only here. */
2
+ export { useBase44Chat } from "./useBase44Chat.js";
@@ -0,0 +1,48 @@
1
+ import type { Base44Chat, Base44ChatOptions } from "./chat.types.js";
2
+ /**
3
+ * Runs one app's builder chat, headless: it keeps the live connection through
4
+ * the platform client, turns Base44's messages into {@link ChatItem | items}, binds
5
+ * every open question to the step it belongs to. You render the items.
6
+ *
7
+ * All Base44 calls go through the {@link Base44ChatBackend | backend} you pass, so no
8
+ * credential reaches the browser. Actions never throw: a failure lands in
9
+ * {@link Base44Chat.error}, and a question whose reply failed opens again. A question kind
10
+ * this release doesn't know is declined for you.
11
+ *
12
+ * Requires a browser environment. One live session is opened per app and renewed through
13
+ * `backend.openLiveSession` when it expires; switching apps closes the old one and starts over.
14
+ *
15
+ * The chat watches `appId` when it is set. While it is `null`, the chat watches the app
16
+ * {@link Base44Chat.create} just made, so passing the new id back is optional; any change to
17
+ * `appId` forgets that app, so setting `appId` back to `null` starts a new chat.
18
+ *
19
+ * @param options - The app to watch, your backend's calls, and what to do with a created app.
20
+ * @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * // Render the items, answer a question
25
+ * const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
26
+ * return (
27
+ * <>
28
+ * {chat.items.map((item) => (
29
+ * <div key={item.id} className={item.role}>
30
+ * {item.text && <p>{item.text}</p>}
31
+ * {item.steps.map((step) =>
32
+ * step.question?.kind === "approval" ? (
33
+ * <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
34
+ * ) : (
35
+ * <small key={step.id}>{step.label}</small>
36
+ * ),
37
+ * )}
38
+ * </div>
39
+ * ))}
40
+ * {chat.error && <p role="alert">{chat.error.message}</p>}
41
+ * <button disabled={chat.status !== "ready" && chat.status !== "error"} onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>
42
+ * Send
43
+ * </button>
44
+ * </>
45
+ * );
46
+ * ```
47
+ */
48
+ export declare function useBase44Chat({ appId, backend, onAppCreated }: Base44ChatOptions): Base44Chat;
@@ -0,0 +1,280 @@
1
+ "use client";
2
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import { createPlatformClient } from "../client/client.js";
4
+ import { isWaiting, mergeMessage, mergeSnapshot, pendingItems, settlePending, sortMessages, toItems, unknownWaiting } from "./chat-items.js";
5
+ // Base44's public status carries no reason, so a failed build has one error.
6
+ const buildFailed = { message: "The build failed", code: "build_failed" };
7
+ // What `submitted` waits on while `create` runs, before the new app has an id.
8
+ const creating = "creating";
9
+ /**
10
+ * Runs one app's builder chat, headless: it keeps the live connection through
11
+ * the platform client, turns Base44's messages into {@link ChatItem | items}, binds
12
+ * every open question to the step it belongs to. You render the items.
13
+ *
14
+ * All Base44 calls go through the {@link Base44ChatBackend | backend} you pass, so no
15
+ * credential reaches the browser. Actions never throw: a failure lands in
16
+ * {@link Base44Chat.error}, and a question whose reply failed opens again. A question kind
17
+ * this release doesn't know is declined for you.
18
+ *
19
+ * Requires a browser environment. One live session is opened per app and renewed through
20
+ * `backend.openLiveSession` when it expires; switching apps closes the old one and starts over.
21
+ *
22
+ * The chat watches `appId` when it is set. While it is `null`, the chat watches the app
23
+ * {@link Base44Chat.create} just made, so passing the new id back is optional; any change to
24
+ * `appId` forgets that app, so setting `appId` back to `null` starts a new chat.
25
+ *
26
+ * @param options - The app to watch, your backend's calls, and what to do with a created app.
27
+ * @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * // Render the items, answer a question
32
+ * const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
33
+ * return (
34
+ * <>
35
+ * {chat.items.map((item) => (
36
+ * <div key={item.id} className={item.role}>
37
+ * {item.text && <p>{item.text}</p>}
38
+ * {item.steps.map((step) =>
39
+ * step.question?.kind === "approval" ? (
40
+ * <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
41
+ * ) : (
42
+ * <small key={step.id}>{step.label}</small>
43
+ * ),
44
+ * )}
45
+ * </div>
46
+ * ))}
47
+ * {chat.error && <p role="alert">{chat.error.message}</p>}
48
+ * <button disabled={chat.status !== "ready" && chat.status !== "error"} onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>
49
+ * Send
50
+ * </button>
51
+ * </>
52
+ * );
53
+ * ```
54
+ */
55
+ export function useBase44Chat({ appId, backend, onAppCreated }) {
56
+ const [messages, setMessages] = useState([]);
57
+ const [appState, setAppState] = useState();
58
+ const [connection, setConnection] = useState("connecting");
59
+ const [error, setError] = useState(null);
60
+ const [answered, setAnswered] = useState([]);
61
+ // The app a prompt or an answer went to, or `creating`, until Base44 reacts to it.
62
+ const [submitted, setSubmitted] = useState(null);
63
+ // Prompts sent from here, shown until Base44 has them.
64
+ const [pending, setPending] = useState([]);
65
+ const pendingCount = useRef(0);
66
+ // The app `create` made, shown while `appId` is null. Any change to `appId` forgets it.
67
+ const [createdAppId, setCreatedAppId] = useState(null);
68
+ const [lastAppIdProp, setLastAppIdProp] = useState(appId);
69
+ const appIdChanged = lastAppIdProp !== appId;
70
+ if (appIdChanged) {
71
+ setLastAppIdProp(appId);
72
+ setCreatedAppId(null);
73
+ }
74
+ // The app this chat shows.
75
+ const currentAppId = appId !== null && appId !== void 0 ? appId : (appIdChanged ? null : createdAppId);
76
+ // Switching apps starts over: the state resets in the same render that sees the new app.
77
+ // A `submitted` aimed at the new app, the one `create` just made, stays.
78
+ const [shownAppId, setShownAppId] = useState(currentAppId);
79
+ if (shownAppId !== currentAppId) {
80
+ setShownAppId(currentAppId);
81
+ setMessages([]);
82
+ setAppState(undefined);
83
+ setConnection("connecting");
84
+ setError(null);
85
+ setAnswered([]);
86
+ if (submitted !== currentAppId && submitted !== creating)
87
+ setSubmitted(null);
88
+ setPending(pending.filter(p => p.appId === currentAppId || p.appId === creating));
89
+ }
90
+ // The live session reads the backend through a ref, kept current after every render, so an
91
+ // inline `backend={{…}}` never reopens the socket. The actions below read it directly.
92
+ const backendRef = useRef(backend);
93
+ useEffect(() => {
94
+ backendRef.current = backend;
95
+ });
96
+ const fail = useCallback((e) => setError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Something went wrong", cause: e }), []);
97
+ // Live updates: a snapshot on every connect, then events.
98
+ useEffect(() => {
99
+ const id = currentAppId;
100
+ if (!id)
101
+ return;
102
+ let stopped = false;
103
+ let session;
104
+ const failLive = (e) => {
105
+ if (!stopped)
106
+ setError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Live updates failed", code: e === null || e === void 0 ? void 0 : e.code, cause: e });
107
+ };
108
+ // A failure of the session or the subscription ends live updates: nothing retries after it.
109
+ const endLive = (e) => {
110
+ failLive(e);
111
+ if (!stopped)
112
+ setConnection("disconnected");
113
+ };
114
+ // A reply this session hasn't seen ends `submitted`. A user message it hasn't seen is the
115
+ // echo of a prompt, which settles the pending one.
116
+ const seen = new Set();
117
+ const arrive = (list, oldestOtherwise) => {
118
+ const fresh = list.filter(m => m.id && !seen.has(m.id));
119
+ for (const m of list)
120
+ if (m.id)
121
+ seen.add(m.id);
122
+ if (fresh.some(m => m.role !== "user"))
123
+ setSubmitted(null);
124
+ const prompts = fresh.filter(m => m.role === "user").map(m => { var _a; return (_a = m.content) !== null && _a !== void 0 ? _a : ""; });
125
+ if (prompts.length)
126
+ setPending(all => settlePending(all, id, prompts, oldestOtherwise));
127
+ };
128
+ // A snapshot replaces the conversation when it is the first, or follows a rewrite of main
129
+ // (undo, restore, sync); after a plain rejoin the messages before its window stay.
130
+ let rewritten = true;
131
+ // Base44 can resend an earlier turn's status after the next turn has started: one older than
132
+ // the newest seen is stale.
133
+ let statusAt = "";
134
+ const applyState = (status) => {
135
+ var _a;
136
+ const at = (_a = status === null || status === void 0 ? void 0 : status.last_updated_date) !== null && _a !== void 0 ? _a : "";
137
+ if (at && at < statusAt)
138
+ return;
139
+ if (at)
140
+ statusAt = at;
141
+ const state = status === null || status === void 0 ? void 0 : status.state;
142
+ setAppState(state);
143
+ if (state === "processing" || state === "error")
144
+ setSubmitted(null);
145
+ };
146
+ // The client asks for a session on the first connect and whenever one expires, and forwards
147
+ // no detail of a failed call, so the backend's own error is kept to report.
148
+ let sessionFailure;
149
+ const builder = createPlatformClient().builder.init({
150
+ getSession: () => backendRef.current.openLiveSession(id).catch((e) => {
151
+ sessionFailure = e;
152
+ throw e;
153
+ }),
154
+ onError: e => {
155
+ if (e.code !== "session_unavailable" || !sessionFailure)
156
+ return endLive(e);
157
+ if (stopped)
158
+ return;
159
+ setError({ message: (sessionFailure === null || sessionFailure === void 0 ? void 0 : sessionFailure.message) || e.message, code: e.code, cause: sessionFailure });
160
+ setConnection("disconnected");
161
+ },
162
+ onConnectionChange: state => {
163
+ if (state === "reconnecting")
164
+ setConnection("reconnecting");
165
+ },
166
+ });
167
+ session = builder;
168
+ builder.subscribe(id, {
169
+ onSnapshot: snapshot => {
170
+ // A snapshot holds old prompts too, so only an exact match settles one.
171
+ arrive(snapshot.messages, false);
172
+ const replace = rewritten;
173
+ rewritten = false;
174
+ setMessages(all => (replace ? snapshot.messages : mergeSnapshot(all, snapshot.messages)));
175
+ applyState(snapshot.status);
176
+ setConnection("connected");
177
+ },
178
+ onEvent: event => {
179
+ if (event.type === "message.updated") {
180
+ arrive([event.data.message], true);
181
+ setMessages(all => mergeMessage(all, event.data.message));
182
+ }
183
+ if (event.type === "message.removed")
184
+ setMessages(all => all.filter(m => m.id !== event.data.message_id));
185
+ if (event.type === "app.status_changed")
186
+ applyState(event.data.status);
187
+ if (event.type === "conversation.changed" && event.data.branch_id == null)
188
+ rewritten = true;
189
+ // A prompt sent while the builder is busy waits in Base44's queue: Base44 has it, and
190
+ // it stays pending until it runs.
191
+ if (event.type === "queue.updated" && event.data.branch_id == null)
192
+ setSubmitted(null);
193
+ },
194
+ // Only snapshot_unavailable leaves the subscription running.
195
+ onError: e => (e.code === "snapshot_unavailable" ? failLive(e) : endLive(e)),
196
+ });
197
+ // A failed connect also reaches onError, which reports it.
198
+ builder.connect().catch(() => { });
199
+ return () => {
200
+ stopped = true;
201
+ session === null || session === void 0 ? void 0 : session.close();
202
+ };
203
+ }, [currentAppId]);
204
+ // Answers one tool call. Its id leaves `answered` again if the submit fails, so the question comes back.
205
+ const respond = useCallback((toolCallId, messageId, approve, extraUserInput) => {
206
+ if (!currentAppId)
207
+ return Promise.resolve();
208
+ setError(null);
209
+ setSubmitted(currentAppId);
210
+ setAnswered(ids => [...ids, toolCallId]);
211
+ return backend.submitToolCallInput(currentAppId, { toolCallId, messageId, approve, extraUserInput }).catch((e) => {
212
+ setAnswered(ids => ids.filter(id => id !== toolCallId));
213
+ setSubmitted(null);
214
+ fail(e);
215
+ });
216
+ }, [currentAppId, backend, fail]);
217
+ const sorted = useMemo(() => sortMessages(messages), [messages]);
218
+ const shownPending = useMemo(() => pending.filter(p => p.appId === currentAppId || (p.appId === creating && !currentAppId)), [pending, currentAppId]);
219
+ const items = useMemo(() => [...toItems(sorted, answered, respond), ...pendingItems(shownPending)], [sorted, answered, respond, shownPending]);
220
+ const waiting = useMemo(() => isWaiting(sorted, answered), [sorted, answered]);
221
+ // A question kind this release doesn't know is declined once per tool call; Base44 then
222
+ // reports its step stopped. If the decline fails, the step waits again and the error shows.
223
+ const declined = useRef(new Set());
224
+ useEffect(() => {
225
+ const id = currentAppId;
226
+ if (!id)
227
+ return;
228
+ for (const { toolCallId, messageId } of unknownWaiting(sorted)) {
229
+ const key = `${id}:${toolCallId}`;
230
+ if (declined.current.has(key))
231
+ continue;
232
+ declined.current.add(key);
233
+ setAnswered(ids => [...ids, toolCallId]);
234
+ backendRef.current.submitToolCallInput(id, { toolCallId, messageId, approve: false }).catch((e) => {
235
+ setAnswered(ids => ids.filter(other => other !== toolCallId));
236
+ fail(e);
237
+ });
238
+ }
239
+ }, [currentAppId, sorted, fail]);
240
+ const status = appState === "error" ? "error" : waiting ? "waiting" : appState === "processing" ? "building"
241
+ : (submitted === creating && !currentAppId) || (submitted !== null && submitted === currentAppId) ? "submitted" : "ready";
242
+ const addPending = useCallback((content, appId) => {
243
+ const prompt = { id: `pending-${++pendingCount.current}`, content, createdAt: new Date().toISOString(), appId };
244
+ setPending(all => [...all, prompt]);
245
+ return prompt;
246
+ }, []);
247
+ const send = useCallback((message) => {
248
+ if (!currentAppId) {
249
+ setError({ message: "There is no app to send to yet: create one first" });
250
+ return Promise.resolve();
251
+ }
252
+ setError(null);
253
+ setSubmitted(currentAppId);
254
+ const prompt = addPending(message, currentAppId);
255
+ return backend.sendMessage(currentAppId, message).catch((e) => {
256
+ setSubmitted(null);
257
+ setPending(all => all.filter(p => p !== prompt));
258
+ fail(e);
259
+ });
260
+ }, [currentAppId, backend, fail, addPending]);
261
+ const create = useCallback(async (message) => {
262
+ setError(null);
263
+ setSubmitted(creating);
264
+ const prompt = addPending(message, creating);
265
+ try {
266
+ const app = await backend.createApp(message);
267
+ setCreatedAppId(app.id);
268
+ setSubmitted(app.id);
269
+ setPending(all => all.map(p => (p === prompt ? { ...p, appId: app.id } : p)));
270
+ onAppCreated === null || onAppCreated === void 0 ? void 0 : onAppCreated(app);
271
+ }
272
+ catch (e) {
273
+ setSubmitted(null);
274
+ setPending(all => all.filter(p => p !== prompt));
275
+ fail(e);
276
+ }
277
+ }, [backend, onAppCreated, fail, addPending]);
278
+ const clearError = useCallback(() => setError(null), []);
279
+ return { items, status, connection, error: error !== null && error !== void 0 ? error : (appState === "error" ? buildFailed : null), send, create, clearError };
280
+ }
@@ -0,0 +1,3 @@
1
+ /** Server platform modules, authenticated with a workspace API key. */
2
+ export { createPlatformServer } from "./server.js";
3
+ export type { PlatformServer, PlatformServerOptions } from "./server.types.js";
@@ -0,0 +1,2 @@
1
+ /** Server platform modules, authenticated with a workspace API key. */
2
+ export { createPlatformServer } from "./server.js";
@@ -0,0 +1,2 @@
1
+ /** Validate a platform origin and return it normalized. Used by the server entrypoint. */
2
+ export declare function normalizeServerUrl(serverUrl: string): string;
@@ -0,0 +1,8 @@
1
+ /** Validate a platform origin and return it normalized. Used by the server entrypoint. */
2
+ export function normalizeServerUrl(serverUrl) {
3
+ const url = new URL(serverUrl);
4
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
5
+ throw new TypeError("serverUrl must be an HTTP(S) origin without credentials, path, query or fragment");
6
+ }
7
+ return url.origin;
8
+ }
@@ -0,0 +1,3 @@
1
+ import type { PlatformServer, PlatformServerOptions } from "./server.types.js";
2
+ /** Create a server platform client, authenticated with a workspace API key. Performs no network requests. */
3
+ export declare function createPlatformServer(options: PlatformServerOptions): PlatformServer;
@@ -0,0 +1,8 @@
1
+ import { normalizeServerUrl } from "./server-url.js";
2
+ /** Create a server platform client, authenticated with a workspace API key. Performs no network requests. */
3
+ export function createPlatformServer(options) {
4
+ if (!options.apiKey)
5
+ throw new TypeError("apiKey is required");
6
+ normalizeServerUrl(options.serverUrl);
7
+ return Object.freeze({});
8
+ }
@@ -0,0 +1,10 @@
1
+ /** Shared configuration for server platform modules. */
2
+ export interface PlatformServerOptions {
3
+ /** Origin of the platform service, e.g. https://base44.app. No path/query/credentials. */
4
+ serverUrl: string;
5
+ /** Workspace API key. Keep it on your server; never ship it to a browser. */
6
+ apiKey: string;
7
+ }
8
+ /** Server platform client, returned by `createPlatformServer`. Modules are added as properties. */
9
+ export interface PlatformServer {
10
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,17 +1,35 @@
1
1
  {
2
2
  "name": "@base44-preview/platform",
3
- "version": "0.2.0-pr.313.e5d2766",
4
- "description": "Browser client for building on the Base44 platform",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
3
+ "version": "0.2.0-pr.315.9d1cad2",
4
+ "description": "Client and server SDK for building on the Base44 platform, with a React hook for the builder chat",
5
+ "main": "dist/client/index.js",
6
+ "types": "dist/client/index.d.ts",
7
7
  "type": "module",
8
8
  "exports": {
9
9
  ".": {
10
- "types": "./dist/index.d.ts",
11
- "default": "./dist/index.js"
10
+ "types": "./dist/client/index.d.ts",
11
+ "default": "./dist/client/index.js"
12
+ },
13
+ "./server": {
14
+ "types": "./dist/server/index.d.ts",
15
+ "default": "./dist/server/index.js"
16
+ },
17
+ "./react": {
18
+ "types": "./dist/react/index.d.ts",
19
+ "default": "./dist/react/index.js"
12
20
  },
13
21
  "./package.json": "./package.json"
14
22
  },
23
+ "typesVersions": {
24
+ "*": {
25
+ "server": [
26
+ "dist/server/index.d.ts"
27
+ ],
28
+ "react": [
29
+ "dist/react/index.d.ts"
30
+ ]
31
+ }
32
+ },
15
33
  "files": [
16
34
  "dist"
17
35
  ],
@@ -38,10 +56,27 @@
38
56
  "dependencies": {
39
57
  "socket.io-client": "^4.8.3"
40
58
  },
59
+ "peerDependencies": {
60
+ "react": "^18.0.0 || ^19.0.0"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "react": {
64
+ "optional": true
65
+ }
66
+ },
67
+ "devDependencies": {
68
+ "@types/react": "^19.0.0",
69
+ "@types/react-dom": "^19.0.0",
70
+ "jsdom": "^26.0.0",
71
+ "json-schema-to-typescript": "16.0.0",
72
+ "react": "^19.0.0",
73
+ "react-dom": "^19.0.0"
74
+ },
41
75
  "keywords": [
42
76
  "base44",
43
77
  "platform",
44
- "white-label"
78
+ "white-label",
79
+ "react"
45
80
  ],
46
81
  "author": "Base44",
47
82
  "license": "MIT",
@@ -53,8 +88,5 @@
53
88
  "bugs": {
54
89
  "url": "https://github.com/base44/javascript-sdk/issues"
55
90
  },
56
- "homepage": "https://github.com/base44/javascript-sdk/tree/main/packages/platform#readme",
57
- "devDependencies": {
58
- "json-schema-to-typescript": "16.0.0"
59
- }
91
+ "homepage": "https://github.com/base44/javascript-sdk/tree/main/packages/platform#readme"
60
92
  }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes