@base44-preview/platform 0.2.0-pr.313.e5d2766 → 0.2.0-pr.315.8896ad8

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 +29 -1
  2. package/dist/{modules → client/modules}/builder-socket.js +5 -2
  3. package/dist/react/chat-items.d.ts +51 -0
  4. package/dist/react/chat-items.js +152 -0
  5. package/dist/react/chat.types.d.ts +201 -0
  6. package/dist/react/chat.types.js +1 -0
  7. package/dist/react/index.d.ts +4 -0
  8. package/dist/react/index.js +2 -0
  9. package/dist/react/useBase44Chat.d.ts +46 -0
  10. package/dist/react/useBase44Chat.js +297 -0
  11. package/dist/server/index.d.ts +3 -0
  12. package/dist/server/index.js +2 -0
  13. package/dist/server/server-url.d.ts +2 -0
  14. package/dist/server/server-url.js +8 -0
  15. package/dist/server/server.d.ts +3 -0
  16. package/dist/server/server.js +8 -0
  17. package/dist/server/server.types.d.ts +10 -0
  18. package/dist/server/server.types.js +1 -0
  19. package/package.json +41 -10
  20. /package/dist/{client.d.ts → client/client.d.ts} +0 -0
  21. /package/dist/{client.js → client/client.js} +0 -0
  22. /package/dist/{client.types.d.ts → client/client.types.d.ts} +0 -0
  23. /package/dist/{client.types.js → client/client.types.js} +0 -0
  24. /package/dist/{errors.d.ts → client/errors.d.ts} +0 -0
  25. /package/dist/{errors.js → client/errors.js} +0 -0
  26. /package/dist/{errors.types.d.ts → client/errors.types.d.ts} +0 -0
  27. /package/dist/{errors.types.js → client/errors.types.js} +0 -0
  28. /package/dist/{index.d.ts → client/index.d.ts} +0 -0
  29. /package/dist/{index.js → client/index.js} +0 -0
  30. /package/dist/{modules → client/modules}/builder-protocol.d.ts +0 -0
  31. /package/dist/{modules → client/modules}/builder-protocol.js +0 -0
  32. /package/dist/{modules → client/modules}/builder-socket.d.ts +0 -0
  33. /package/dist/{modules → client/modules}/builder-subscription.d.ts +0 -0
  34. /package/dist/{modules → client/modules}/builder-subscription.js +0 -0
  35. /package/dist/{modules → client/modules}/builder.d.ts +0 -0
  36. /package/dist/{modules → client/modules}/builder.events.generated.d.ts +0 -0
  37. /package/dist/{modules → client/modules}/builder.events.generated.js +0 -0
  38. /package/dist/{modules → client/modules}/builder.events.types.d.ts +0 -0
  39. /package/dist/{modules → client/modules}/builder.events.types.js +0 -0
  40. /package/dist/{modules → client/modules}/builder.js +0 -0
  41. /package/dist/{modules → client/modules}/builder.types.d.ts +0 -0
  42. /package/dist/{modules → client/modules}/builder.types.js +0 -0
package/README.md CHANGED
@@ -124,7 +124,7 @@ redaction of generated prose or user content.
124
124
  ## Event types
125
125
 
126
126
  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
127
+ `asyncapi.json`. `src/client/modules/builder.events.generated.ts` is generated from it with
128
128
  `json-schema-to-typescript`: one type per schema, named after the backend model
129
129
  (`Message`, `StatusObject`, `QueueState`, one `*Call` per tool, one `*Approval` per
130
130
  guard), plus `ServerEventMap` and `ClientMessageMap`. Never edit it by hand.
@@ -170,3 +170,31 @@ exceptions, payloads and credentials are never attached.
170
170
 
171
171
  No SDK dependency, package version or lockfile changes are required. Socket.IO
172
172
  remains the existing SDK dependency. Chat commands and HTTP APIs are outside this entry point.
173
+
174
+ ## React
175
+
176
+ `@base44/platform/react` adds one hook, `useBase44Chat`, that runs a builder chat for one
177
+ app on top of this client: it opens the live session and renews it, turns messages into items
178
+ 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
179
+ entry; the root entry stays framework-free.
180
+
181
+ ```tsx
182
+ import { useBase44Chat } from "@base44/platform/react";
183
+
184
+ const chat = useBase44Chat({ appId, backend, onAppCreated });
185
+ chat.items.map((item) =>
186
+ item.steps.map((step) => step.question?.kind === "approval" && <button onClick={step.question.approve}>Allow</button>),
187
+ );
188
+ ```
189
+
190
+ `backend` is four functions your backend provides, in any language behind them: `createApp`,
191
+ `openLiveSession`, `sendMessage` and `submitToolCallInput`, each wrapping one Base44 REST
192
+ call with your credentials, so the browser never holds a key. The hook returns `items`, a
193
+ `status` (`ready`, `submitted`, `building`, `waiting`, `error`), a `connection` (`connecting`,
194
+ `connected`, `disconnected`), an `error`, and the actions `send`, `create` and `clearError`. `send` needs an app; `create` makes
195
+ the first, and the chat watches it while `appId` is `null`. A sent prompt shows at once as a
196
+ `pending` item until Base44's own message arrives; a prompt sent mid-build waits in Base44's
197
+ queue meanwhile. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
198
+ actions its kind allows, and declining is always one of them. As in Base44's builder, only the
199
+ last assistant message makes the chat wait; a kind this release doesn't know is declined for you. Every shape has JSDoc in `src/react/chat.types.ts`, and
200
+ [`examples/react-chat/`](examples/react-chat) shows Tiny Sunny's chat built on it, with its `backend`.
@@ -123,8 +123,11 @@ export class BuilderSocket {
123
123
  socket.on(name, (raw) => this.roomNotice(code, raw));
124
124
  for (const name of eventNames)
125
125
  socket.on(name, (raw) => this.appEvent(name, raw));
126
- socket.onAny((name, raw) => { if (isUnknownEvent(name))
127
- this.appEvent(name, raw); });
126
+ // An unknown event with no app room (a future session-wide event) has nowhere to go: ignore it.
127
+ socket.onAny((name, raw) => {
128
+ if (isUnknownEvent(name) && appFromRoom(raw === null || raw === void 0 ? void 0 : raw.room))
129
+ this.appEvent(name, raw);
130
+ });
128
131
  socket.connect();
129
132
  }
130
133
  appEvent(name, raw) {
@@ -0,0 +1,51 @@
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. A waiting tool call that is not in `answered` and is
18
+ * of a kind this release knows carries its own question, in the last assistant message only: the
19
+ * one that makes the chat wait. Older waiting calls keep their status but no question. */
20
+ export declare function toItems(sorted: Message[], answered: string[], respond: Respond): ChatItem[];
21
+ /** @internal Base44's tool call status, as a step's. */
22
+ export declare function stepStatus(tool: ToolCall): ChatStep["status"];
23
+ /** @internal Whether the chat waits on the user. Like Base44's builder, only the last assistant
24
+ * message counts, and a call answered or declined here stops counting. */
25
+ export declare function isWaiting(sorted: Message[], answered: string[]): boolean;
26
+ /** @internal Waiting calls on the last assistant message whose kind Base44 names and this release
27
+ * doesn't know, to decline. A call with no kind comes only from old messages and is left alone. */
28
+ export declare function unknownWaiting(sorted: Message[]): {
29
+ toolCallId: string;
30
+ messageId: string;
31
+ }[];
32
+ /** @internal The ids of tool calls Base44 reports waiting. */
33
+ export declare function waitingIds(sorted: Message[]): Set<string>;
34
+ /** @internal A prompt sent from this chat that Base44 has not confirmed, for the app it went to. */
35
+ export interface PendingPrompt {
36
+ id: string;
37
+ content: string;
38
+ createdAt: string;
39
+ appId: string;
40
+ }
41
+ /** @internal Prompts that arrived from Base44 as messages settle the pending ones
42
+ * with the same text. Base44's public send carries no client id, so text is the only link. With
43
+ * `oldestOtherwise`, an arrival that matches none settles the oldest, so a prompt Base44 changed
44
+ * on the way never stays pending. */
45
+ export declare function settlePending(pending: PendingPrompt[], appId: string, arrived: string[], oldestOtherwise: boolean): PendingPrompt[];
46
+ /** @internal Pending prompts as items, after the messages Base44 has. */
47
+ export declare function pendingItems(pending: PendingPrompt[]): ChatItem[];
48
+ /** @internal Base44's question formats, as one simple shape per kind, each bound to the reply that
49
+ * answers it. Base44 keys choice answers by position, so `picked` follows `questions`. A kind this
50
+ * release doesn't know has no shape. */
51
+ export declare function bindQuestion(tool: ToolCall, reply: Reply): ChatQuestion | undefined;
@@ -0,0 +1,152 @@
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 An assistant message that answers a turn. Base44 injects notices that expect no reply. */
22
+ function isActionable(m) {
23
+ var _a;
24
+ return (m === null || m === void 0 ? void 0 : m.role) === "assistant" && !((_a = m.additional_message_params) === null || _a === void 0 ? void 0 : _a.skip_ai_response);
25
+ }
26
+ /** @internal Turns sorted messages into items. A waiting tool call that is not in `answered` and is
27
+ * of a kind this release knows carries its own question, in the last assistant message only: the
28
+ * one that makes the chat wait. Older waiting calls keep their status but no question. */
29
+ export function toItems(sorted, answered, respond) {
30
+ const last = lastActionable(sorted);
31
+ return sorted.map(m => {
32
+ var _a, _b, _c, _d;
33
+ return ({
34
+ id: m.id,
35
+ role: m.role === "user" ? "user" : "assistant",
36
+ text: (_a = m.content) !== null && _a !== void 0 ? _a : "",
37
+ createdAt: (_c = (_b = m.metadata) === null || _b === void 0 ? void 0 : _b.created_date) !== null && _c !== void 0 ? _c : "",
38
+ pending: false,
39
+ steps: ((_d = m.tool_calls) !== null && _d !== void 0 ? _d : []).map(tool => toStep(tool, m === last && !answered.includes(tool.id) ? (approve, extra) => respond(tool.id, m.id, approve, extra) : undefined)),
40
+ });
41
+ });
42
+ }
43
+ /** @internal The last assistant message that answers a turn, as Base44's builder finds it. */
44
+ function lastActionable(sorted) {
45
+ return [...sorted].reverse().find(isActionable);
46
+ }
47
+ function toStep(tool, reply) {
48
+ var _a, _b;
49
+ const name = (_a = tool.name) !== null && _a !== void 0 ? _a : "";
50
+ // Only file tools carry `display.file_paths`.
51
+ const display = "display" in tool ? tool.display : undefined;
52
+ const files = (_b = display === null || display === void 0 ? void 0 : display.file_paths) !== null && _b !== void 0 ? _b : [];
53
+ const status = stepStatus(tool);
54
+ const question = status === "waiting" && reply ? bindQuestion(tool, reply) : undefined;
55
+ return { id: tool.id, tool: name, files, label: [name, ...files].join(" "), status, ...(question && { question }) };
56
+ }
57
+ /** @internal Base44's tool call status, as a step's. */
58
+ export function stepStatus(tool) {
59
+ if (tool.status === "running")
60
+ return "running";
61
+ if (tool.status === "waiting_for_user_input")
62
+ return "waiting";
63
+ if (tool.status === "stopped")
64
+ return "stopped";
65
+ if (tool.status === "error")
66
+ return "error";
67
+ return "done";
68
+ }
69
+ /** @internal Whether the chat waits on the user. Like Base44's builder, only the last assistant
70
+ * message counts, and a call answered or declined here stops counting. */
71
+ export function isWaiting(sorted, answered) {
72
+ var _a;
73
+ const last = lastActionable(sorted);
74
+ return !!((_a = last === null || last === void 0 ? void 0 : last.tool_calls) === null || _a === void 0 ? void 0 : _a.some(tool => tool.status === "waiting_for_user_input" && !answered.includes(tool.id)));
75
+ }
76
+ const knownKinds = ["approval", "choice", "input"];
77
+ /** @internal Waiting calls on the last assistant message whose kind Base44 names and this release
78
+ * doesn't know, to decline. A call with no kind comes only from old messages and is left alone. */
79
+ export function unknownWaiting(sorted) {
80
+ var _a;
81
+ const last = lastActionable(sorted);
82
+ return ((_a = last === null || last === void 0 ? void 0 : last.tool_calls) !== null && _a !== void 0 ? _a : [])
83
+ .filter(tool => { var _a; return tool.status === "waiting_for_user_input" && ((_a = tool.waiting_on) === null || _a === void 0 ? void 0 : _a.kind) && !knownKinds.includes(tool.waiting_on.kind); })
84
+ .map(tool => ({ toolCallId: tool.id, messageId: last.id }));
85
+ }
86
+ /** @internal The ids of tool calls Base44 reports waiting. */
87
+ export function waitingIds(sorted) {
88
+ return new Set(sorted.flatMap(m => { var _a; return ((_a = m.tool_calls) !== null && _a !== void 0 ? _a : []).filter(t => t.status === "waiting_for_user_input").map(t => t.id); }));
89
+ }
90
+ /** @internal Prompts that arrived from Base44 as messages settle the pending ones
91
+ * with the same text. Base44's public send carries no client id, so text is the only link. With
92
+ * `oldestOtherwise`, an arrival that matches none settles the oldest, so a prompt Base44 changed
93
+ * on the way never stays pending. */
94
+ export function settlePending(pending, appId, arrived, oldestOtherwise) {
95
+ var _a;
96
+ let rest = pending;
97
+ for (const text of arrived) {
98
+ const mine = rest.filter(p => p.appId === appId);
99
+ const match = (_a = mine.find(p => p.content.trim() === text.trim())) !== null && _a !== void 0 ? _a : (oldestOtherwise ? mine[0] : undefined);
100
+ if (match)
101
+ rest = rest.filter(p => p !== match);
102
+ }
103
+ return rest;
104
+ }
105
+ /** @internal Pending prompts as items, after the messages Base44 has. */
106
+ export function pendingItems(pending) {
107
+ return pending.map(p => ({ id: p.id, role: "user", text: p.content, createdAt: p.createdAt, steps: [], pending: true }));
108
+ }
109
+ /** @internal Base44's question formats, as one simple shape per kind, each bound to the reply that
110
+ * answers it. Base44 keys choice answers by position, so `picked` follows `questions`. A kind this
111
+ * release doesn't know has no shape. */
112
+ export function bindQuestion(tool, reply) {
113
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
114
+ const kind = (_a = tool.waiting_on) === null || _a === void 0 ? void 0 : _a.kind;
115
+ const decline = () => reply(false);
116
+ if (kind === "choice") {
117
+ const questions = (_c = (_b = argumentsOf(tool)) === null || _b === void 0 ? void 0 : _b.questions) !== null && _c !== void 0 ? _c : [];
118
+ return {
119
+ kind,
120
+ questions: questions.map(q => {
121
+ var _a, _b;
122
+ return ({
123
+ text: (_a = q.question) !== null && _a !== void 0 ? _a : "",
124
+ description: q.description,
125
+ 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 : ""); }),
126
+ multi: !!q.multi_select,
127
+ });
128
+ }),
129
+ answer: picked => reply(true, { answers: picked.map((labels, i) => ({ question_index: i, selected_labels: labels })).filter(a => a.selected_labels.length) }),
130
+ decline,
131
+ };
132
+ }
133
+ if (kind === "input") {
134
+ const fields = (_e = (_d = argumentsOf(tool)) === null || _d === void 0 ? void 0 : _d.secrets_schema) !== null && _e !== void 0 ? _e : [];
135
+ return {
136
+ kind: "secrets",
137
+ fields: fields.map(f => { var _a; return ({ name: (_a = f.secretName) !== null && _a !== void 0 ? _a : "", description: f.description }); }),
138
+ submit: values => reply(true, { secrets: values }),
139
+ decline,
140
+ };
141
+ }
142
+ if (kind === "approval") {
143
+ // Guards that declare a reason or a summary carry them; the others name only themselves.
144
+ const approval = tool.approval;
145
+ 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 };
146
+ }
147
+ return undefined;
148
+ }
149
+ // The waiting kind says which arguments a call carries; the tool's name only narrows the union.
150
+ function argumentsOf(tool) {
151
+ return "arguments" in tool ? tool.arguments : undefined;
152
+ }
@@ -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(prompt: 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 the message was created, as an ISO timestamp: Base44's for its messages, which carry no
57
+ * time zone and are UTC, and the browser's for a pending prompt. */
58
+ createdAt: string;
59
+ /** One per tool call, in order. */
60
+ steps: ChatStep[];
61
+ /** A prompt sent from this chat that Base44 has not confirmed yet. It shows at once, and gives
62
+ * way to Base44's own message; a failed send removes it. A prompt sent while the builder is busy
63
+ * waits in Base44's queue and stays pending until it runs. */
64
+ pending: boolean;
65
+ }
66
+ /** One tool call, as a line of activity. */
67
+ export interface ChatStep {
68
+ /** The tool call id. */
69
+ id: string;
70
+ /** The tool's name, e.g. `write_file`. */
71
+ tool: string;
72
+ /** The paths it touched. */
73
+ files: string[];
74
+ /** Tool and files, ready to show. */
75
+ label: string;
76
+ /** Where the call is. `waiting` waits on the user; `stopped` was declined, or the build was stopped. */
77
+ status: "running" | "waiting" | "done" | "stopped" | "error";
78
+ /** The question this step waits on, bound to the actions that answer it. Only while `status` is
79
+ * `waiting`, and only in the last assistant message, the one that makes the chat wait. Gone once
80
+ * answered, and absent for a kind this release doesn't know. */
81
+ question?: ChatQuestion;
82
+ }
83
+ /**
84
+ * An open question, with the actions that answer this question and no other.
85
+ * Each kind carries only the actions that make sense for it, and every kind can be declined.
86
+ * A kind this release doesn't know is declined for you, once per tool call, when Base44 names
87
+ * it on the last assistant message; if that fails, `error` says so and a reconnect tries again.
88
+ * The actions never throw: a failure lands in {@link Base44Chat.error} and the question opens again.
89
+ */
90
+ export type ChatQuestion = ChoiceQuestion | SecretsQuestion | ApprovalQuestion;
91
+ /** One of the questions a `choice` asks. */
92
+ export interface ChoiceEntry {
93
+ /** The question text. */
94
+ text: string;
95
+ /** Optional supporting text. */
96
+ description?: string;
97
+ /** The option labels to pick from. */
98
+ options: string[];
99
+ /** Whether more than one option may be picked. */
100
+ multi: boolean;
101
+ }
102
+ /** The builder offers options and wants a pick. */
103
+ export interface ChoiceQuestion {
104
+ /** Discriminator. */
105
+ kind: "choice";
106
+ /** The questions asked, in order. */
107
+ questions: ChoiceEntry[];
108
+ /** Answers with the picked labels: one list per question, in the same order as `questions`. An empty list skips that question. */
109
+ answer(picked: string[][]): Promise<void>;
110
+ /** Declines: the builder continues without the answer. */
111
+ decline(): Promise<void>;
112
+ }
113
+ /** A value the builder needs, such as an API key. */
114
+ export interface SecretField {
115
+ /** The field name, used as the key in `submit`. */
116
+ name: string;
117
+ /** Optional explanation of where to obtain the value. */
118
+ description?: string;
119
+ }
120
+ /** The builder needs secrets, such as API keys. They go to Base44 and are never kept here. */
121
+ export interface SecretsQuestion {
122
+ /** Discriminator. */
123
+ kind: "secrets";
124
+ /** The fields to fill. */
125
+ fields: SecretField[];
126
+ /** Submits the values, keyed by field name. */
127
+ submit(values: Record<string, string>): Promise<void>;
128
+ /** Declines: the builder continues without the values. */
129
+ decline(): Promise<void>;
130
+ }
131
+ /** The builder wants permission to run a proposed action. */
132
+ export interface ApprovalQuestion {
133
+ /** Discriminator. */
134
+ kind: "approval";
135
+ /** The tool that wants to run. */
136
+ action: string;
137
+ /** Why it was parked, when the guard says; empty otherwise. */
138
+ reason: string;
139
+ /** Lets the action run. */
140
+ approve(): Promise<void>;
141
+ /** Declines: the action never runs and the builder continues. */
142
+ decline(): Promise<void>;
143
+ }
144
+ /**
145
+ * What the builder is doing, one value at a time. The first that holds wins:
146
+ *
147
+ * - `error`: Base44 reports the app's build failed.
148
+ * - `waiting`: a step waits on the user.
149
+ * - `building`: the builder is working.
150
+ * - `submitted`: a prompt, a new app or an answer is on its way, until Base44 reports work,
151
+ * a reply or a queue change, or the call fails.
152
+ * - `ready`: everything else.
153
+
154
+ */
155
+ export type ChatStatus = "ready" | "submitted" | "building" | "waiting" | "error";
156
+ /** Whether the chat sees the builder live: `connecting` until the first snapshot, `connected`
157
+ * after it, and `disconnected` 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" | "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(prompt: string): Promise<void>;
197
+ /** Creates a new app from its first prompt and reports it through `onAppCreated`. */
198
+ create(prompt: 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,46 @@
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 onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
42
+ * </>
43
+ * );
44
+ * ```
45
+ */
46
+ export declare function useBase44Chat({ appId, backend, onAppCreated }: Base44ChatOptions): Base44Chat;
@@ -0,0 +1,297 @@
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, waitingIds } 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 onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
49
+ * </>
50
+ * );
51
+ * ```
52
+ */
53
+ export function useBase44Chat({ appId, backend, onAppCreated }) {
54
+ var _a;
55
+ const [messages, setMessages] = useState([]);
56
+ const [appState, setAppState] = useState();
57
+ const [connection, setConnection] = useState("connecting");
58
+ // A failed call's error, which the next action clears, and the live connection's, which it doesn't.
59
+ const [callError, setCallError] = useState(null);
60
+ const [liveError, setLiveError] = useState(null);
61
+ const [answered, setAnswered] = useState([]);
62
+ // The app a prompt or an answer went to, or `creating`, until Base44 reacts to it.
63
+ const [submitted, setSubmitted] = useState(null);
64
+ // Prompts sent from here, shown until Base44 has them.
65
+ const [pending, setPending] = useState([]);
66
+ const pendingCount = useRef(0);
67
+ // Tool calls declined for the user, and those whose decline failed and may try again.
68
+ const declined = useRef(new Set());
69
+ const failedDeclines = useRef(new Set());
70
+ // The app `create` made, shown while `appId` is null. Any change to `appId` forgets it.
71
+ const [createdAppId, setCreatedAppId] = useState(null);
72
+ const [lastAppIdProp, setLastAppIdProp] = useState(appId);
73
+ const appIdChanged = lastAppIdProp !== appId;
74
+ if (appIdChanged) {
75
+ setLastAppIdProp(appId);
76
+ setCreatedAppId(null);
77
+ }
78
+ // The app this chat shows.
79
+ const currentAppId = appId !== null && appId !== void 0 ? appId : (appIdChanged ? null : createdAppId);
80
+ // Switching apps starts over: the state resets in the same render that sees the new app.
81
+ // A `submitted` aimed at the new app, the one `create` just made, stays.
82
+ const [shownAppId, setShownAppId] = useState(currentAppId);
83
+ if (shownAppId !== currentAppId) {
84
+ setShownAppId(currentAppId);
85
+ setMessages([]);
86
+ setAppState(undefined);
87
+ setConnection("connecting");
88
+ setCallError(null);
89
+ setLiveError(null);
90
+ setAnswered([]);
91
+ if (submitted !== currentAppId && submitted !== creating)
92
+ setSubmitted(null);
93
+ setPending(pending.filter(p => p.appId === currentAppId || p.appId === creating));
94
+ }
95
+ // The backend is read through a ref, kept current after every render, so an inline
96
+ // `backend={{…}}` never reopens the socket or changes the actions' identity.
97
+ const backendRef = useRef(backend);
98
+ useEffect(() => {
99
+ backendRef.current = backend;
100
+ });
101
+ const fail = useCallback((e) => setCallError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Something went wrong", cause: e }), []);
102
+ // Live updates: a snapshot on every connect, then events.
103
+ useEffect(() => {
104
+ const id = currentAppId;
105
+ if (!id)
106
+ return;
107
+ let stopped = false;
108
+ let session;
109
+ const failLive = (e) => {
110
+ if (!stopped)
111
+ setLiveError({ 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 });
112
+ };
113
+ // A failure of the session or the subscription ends live updates: nothing retries after it.
114
+ const endLive = (e) => {
115
+ failLive(e);
116
+ if (!stopped)
117
+ setConnection("disconnected");
118
+ };
119
+ // A reply this session hasn't seen ends `submitted`. A user message it hasn't seen is the
120
+ // echo of a prompt, which settles the pending one.
121
+ const seen = new Set();
122
+ const arrive = (list, oldestOtherwise) => {
123
+ const fresh = list.filter(m => m.id && !seen.has(m.id));
124
+ for (const m of list)
125
+ if (m.id)
126
+ seen.add(m.id);
127
+ if (fresh.some(m => m.role !== "user"))
128
+ setSubmitted(null);
129
+ const prompts = fresh.filter(m => m.role === "user").map(m => { var _a; return (_a = m.content) !== null && _a !== void 0 ? _a : ""; });
130
+ if (prompts.length)
131
+ setPending(all => settlePending(all, id, prompts, oldestOtherwise));
132
+ };
133
+ // A snapshot replaces the conversation when it is the first, or follows a rewrite of main
134
+ // (undo, restore, sync); after a plain rejoin the messages before its window stay.
135
+ let rewritten = true;
136
+ // Base44 can resend an earlier turn's status after the next turn has started: one older than
137
+ // the newest seen is stale.
138
+ let statusAt = "";
139
+ const applyState = (status) => {
140
+ var _a;
141
+ const at = (_a = status === null || status === void 0 ? void 0 : status.last_updated_date) !== null && _a !== void 0 ? _a : "";
142
+ if (at && at < statusAt)
143
+ return;
144
+ if (at)
145
+ statusAt = at;
146
+ const state = status === null || status === void 0 ? void 0 : status.state;
147
+ setAppState(state);
148
+ if (state === "processing" || state === "error")
149
+ setSubmitted(null);
150
+ };
151
+ // The client asks for a session on the first connect and whenever one expires, and forwards
152
+ // no detail of a failed call, so the backend's own error is kept to report.
153
+ let sessionFailure;
154
+ const builder = createPlatformClient().builder.init({
155
+ getSession: () => backendRef.current.openLiveSession(id).then(session => {
156
+ sessionFailure = undefined;
157
+ return session;
158
+ }, (e) => {
159
+ sessionFailure = e;
160
+ throw e;
161
+ }),
162
+ onError: e => {
163
+ if (e.code !== "session_unavailable" || !sessionFailure)
164
+ return endLive(e);
165
+ if (stopped)
166
+ return;
167
+ setLiveError({ message: (sessionFailure === null || sessionFailure === void 0 ? void 0 : sessionFailure.message) || e.message, code: e.code, cause: sessionFailure });
168
+ setConnection("disconnected");
169
+ },
170
+ });
171
+ session = builder;
172
+ builder.subscribe(id, {
173
+ onSnapshot: snapshot => {
174
+ // A snapshot holds old prompts too, so only an exact match settles one.
175
+ arrive(snapshot.messages, false);
176
+ const replace = rewritten;
177
+ rewritten = false;
178
+ setMessages(all => (replace ? snapshot.messages : mergeSnapshot(all, snapshot.messages)));
179
+ applyState(snapshot.status);
180
+ // A declined call that failed tries again on the next snapshot, after a reconnect.
181
+ for (const key of failedDeclines.current)
182
+ declined.current.delete(key);
183
+ failedDeclines.current.clear();
184
+ setConnection("connected");
185
+ },
186
+ onEvent: event => {
187
+ if (event.type === "message.updated") {
188
+ arrive([event.data.message], true);
189
+ setMessages(all => mergeMessage(all, event.data.message));
190
+ }
191
+ if (event.type === "message.removed")
192
+ setMessages(all => all.filter(m => m.id !== event.data.message_id));
193
+ if (event.type === "app.status_changed")
194
+ applyState(event.data.status);
195
+ if (event.type === "conversation.changed" && event.data.branch_id == null)
196
+ rewritten = true;
197
+ // A prompt sent while the builder is busy waits in Base44's queue: Base44 has it, and
198
+ // it stays pending until it runs.
199
+ if (event.type === "queue.updated" && event.data.branch_id == null)
200
+ setSubmitted(null);
201
+ },
202
+ // Only snapshot_unavailable leaves the subscription running.
203
+ onError: e => (e.code === "snapshot_unavailable" ? failLive(e) : endLive(e)),
204
+ });
205
+ // A failed connect also reaches onError, which reports it.
206
+ builder.connect().catch(() => { });
207
+ return () => {
208
+ stopped = true;
209
+ session === null || session === void 0 ? void 0 : session.close();
210
+ };
211
+ }, [currentAppId]);
212
+ // Answers one tool call. Its id leaves `answered` again if the submit fails, so the question comes back.
213
+ const respond = useCallback((toolCallId, messageId, approve, extraUserInput) => {
214
+ if (!currentAppId)
215
+ return Promise.resolve();
216
+ setCallError(null);
217
+ setSubmitted(currentAppId);
218
+ setAnswered(ids => [...ids, toolCallId]);
219
+ return backendRef.current.submitToolCallInput(currentAppId, { toolCallId, messageId, approve, extraUserInput }).catch((e) => {
220
+ setAnswered(ids => ids.filter(id => id !== toolCallId));
221
+ setSubmitted(null);
222
+ fail(e);
223
+ });
224
+ }, [currentAppId, fail]);
225
+ const sorted = useMemo(() => sortMessages(messages), [messages]);
226
+ const shownPending = useMemo(() => pending.filter(p => p.appId === currentAppId || (p.appId === creating && !currentAppId)), [pending, currentAppId]);
227
+ const items = useMemo(() => [...toItems(sorted, answered, respond), ...pendingItems(shownPending)], [sorted, answered, respond, shownPending]);
228
+ const waiting = useMemo(() => isWaiting(sorted, answered), [sorted, answered]);
229
+ // A kind this release doesn't know is declined once per tool call. If that fails, the step waits
230
+ // again, the error shows, and the next snapshot tries once more.
231
+ useEffect(() => {
232
+ const id = currentAppId;
233
+ if (!id)
234
+ return;
235
+ for (const { toolCallId, messageId } of unknownWaiting(sorted)) {
236
+ const key = `${id}:${toolCallId}`;
237
+ if (declined.current.has(key))
238
+ continue;
239
+ declined.current.add(key);
240
+ setAnswered(ids => [...ids, toolCallId]);
241
+ backendRef.current.submitToolCallInput(id, { toolCallId, messageId, approve: false }).catch((e) => {
242
+ failedDeclines.current.add(key);
243
+ setAnswered(ids => ids.filter(other => other !== toolCallId));
244
+ fail(e);
245
+ });
246
+ }
247
+ }, [currentAppId, sorted, fail]);
248
+ // An answered call stays hidden while Base44 still reports it waiting, and is forgotten once it
249
+ // doesn't: if Base44 parks it again, its question comes back.
250
+ useEffect(() => {
251
+ const waiting = waitingIds(sorted);
252
+ setAnswered(ids => (ids.every(id => waiting.has(id)) ? ids : ids.filter(id => waiting.has(id))));
253
+ }, [sorted]);
254
+ const status = appState === "error" ? "error" : waiting ? "waiting" : appState === "processing" ? "building"
255
+ : (submitted === creating && !currentAppId) || (submitted !== null && submitted === currentAppId) ? "submitted" : "ready";
256
+ const addPending = useCallback((content, appId) => {
257
+ const prompt = { id: `pending-${++pendingCount.current}`, content, createdAt: new Date().toISOString(), appId };
258
+ setPending(all => [...all, prompt]);
259
+ return prompt;
260
+ }, []);
261
+ const send = useCallback((prompt) => {
262
+ if (!currentAppId) {
263
+ setCallError({ message: "There is no app to send to yet: create one first" });
264
+ return Promise.resolve();
265
+ }
266
+ setCallError(null);
267
+ setSubmitted(currentAppId);
268
+ const shown = addPending(prompt, currentAppId);
269
+ return backendRef.current.sendMessage(currentAppId, prompt).catch((e) => {
270
+ setSubmitted(null);
271
+ setPending(all => all.filter(p => p !== shown));
272
+ fail(e);
273
+ });
274
+ }, [currentAppId, fail, addPending]);
275
+ const create = useCallback(async (prompt) => {
276
+ setCallError(null);
277
+ setSubmitted(creating);
278
+ const shown = addPending(prompt, creating);
279
+ try {
280
+ const app = await backendRef.current.createApp(prompt);
281
+ setCreatedAppId(app.id);
282
+ setSubmitted(app.id);
283
+ setPending(all => all.map(p => (p === shown ? { ...p, appId: app.id } : p)));
284
+ onAppCreated === null || onAppCreated === void 0 ? void 0 : onAppCreated(app);
285
+ }
286
+ catch (e) {
287
+ setSubmitted(null);
288
+ setPending(all => all.filter(p => p !== shown));
289
+ fail(e);
290
+ }
291
+ }, [onAppCreated, fail, addPending]);
292
+ const clearError = useCallback(() => {
293
+ setCallError(null);
294
+ setLiveError(null);
295
+ }, []);
296
+ return { items, status, connection, error: (_a = callError !== null && callError !== void 0 ? callError : liveError) !== null && _a !== void 0 ? _a : (appState === "error" ? buildFailed : null), send, create, clearError };
297
+ }
@@ -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.8896ad8",
4
+ "description": "Client and server SDK for building on the Base44 platform",
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,6 +56,22 @@
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",
@@ -53,8 +87,5 @@
53
87
  "bugs": {
54
88
  "url": "https://github.com/base44/javascript-sdk/issues"
55
89
  },
56
- "homepage": "https://github.com/base44/javascript-sdk/tree/main/packages/platform#readme",
57
- "devDependencies": {
58
- "json-schema-to-typescript": "16.0.0"
59
- }
90
+ "homepage": "https://github.com/base44/javascript-sdk/tree/main/packages/platform#readme"
60
91
  }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes