@base44-preview/platform 0.2.0-pr.335.2bd5f4f → 0.2.0-pr.336.059c4cd

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 (37) hide show
  1. package/README.md +68 -62
  2. package/dist/server/errors.d.ts +53 -0
  3. package/dist/server/errors.js +56 -0
  4. package/dist/server/errors.types.d.ts +60 -0
  5. package/dist/server/index.d.ts +6 -2
  6. package/dist/server/index.js +2 -1
  7. package/dist/server/modules/webhooks-signature.d.ts +11 -0
  8. package/dist/server/modules/webhooks-signature.js +65 -0
  9. package/dist/server/modules/webhooks.d.ts +3 -0
  10. package/dist/server/modules/webhooks.events.generated.d.ts +176 -0
  11. package/dist/server/modules/webhooks.events.generated.js +4 -0
  12. package/dist/server/modules/webhooks.js +91 -0
  13. package/dist/server/modules/webhooks.types.d.ts +218 -0
  14. package/dist/server/server.d.ts +28 -3
  15. package/dist/server/server.js +31 -7
  16. package/dist/server/server.types.d.ts +8 -8
  17. package/package.json +14 -28
  18. package/dist/react/Base44ChatProvider.d.ts +0 -43
  19. package/dist/react/Base44ChatProvider.js +0 -68
  20. package/dist/react/Message.d.ts +0 -39
  21. package/dist/react/Message.js +0 -55
  22. package/dist/react/chat-items.d.ts +0 -51
  23. package/dist/react/chat-items.js +0 -174
  24. package/dist/react/chat.types.d.ts +0 -299
  25. package/dist/react/components.types.d.ts +0 -63
  26. package/dist/react/context.d.ts +0 -50
  27. package/dist/react/context.js +0 -57
  28. package/dist/react/fallbacks.d.ts +0 -3
  29. package/dist/react/fallbacks.js +0 -13
  30. package/dist/react/index.d.ts +0 -8
  31. package/dist/react/index.js +0 -5
  32. package/dist/react/useBase44Chat.d.ts +0 -48
  33. package/dist/react/useBase44Chat.js +0 -312
  34. package/dist/server/server-url.d.ts +0 -2
  35. package/dist/server/server-url.js +0 -8
  36. /package/dist/{react/chat.types.js → server/errors.types.js} +0 -0
  37. /package/dist/{react/components.types.js → server/modules/webhooks.types.js} +0 -0
@@ -1,50 +0,0 @@
1
- import type { ChatActions, ChatState, MessageComponents, QuestionComponents } from "./components.types.js";
2
- /** @internal The parts with the fallbacks applied, as {@link Base44ChatProvider} shares them. */
3
- export interface ResolvedComponents {
4
- message: MessageComponents;
5
- question: QuestionComponents;
6
- }
7
- /** @internal Filled by {@link Base44ChatProvider}. State changes on every event; actions and parts do not. */
8
- export declare const StateContext: import("react").Context<ChatState | null>;
9
- /** @internal */
10
- export declare const ActionsContext: import("react").Context<ChatActions | null>;
11
- /** @internal */
12
- export declare const ComponentsContext: import("react").Context<ResolvedComponents | null>;
13
- /**
14
- * Reads the chat's state from the nearest {@link Base44ChatProvider}: `items`, `status`,
15
- * `connection` and `error`. A component that calls it re-renders on every live event.
16
- *
17
- * @returns The state of the chat the provider runs.
18
- * @throws {Error} When there is no provider above the component.
19
- *
20
- * @example
21
- * ```tsx
22
- * // The message list
23
- * function Messages() {
24
- * const { items } = useChatState();
25
- * return items.map((item) => <div key={item.id}><Message item={item} /></div>);
26
- * }
27
- * ```
28
- */
29
- export declare function useChatState(): ChatState;
30
- /**
31
- * Reads the chat's actions from the nearest {@link Base44ChatProvider}: `send`, `create` and
32
- * `clearError`. They keep their identity while the app stays the same, also with an inline
33
- * `backend` or `onAppCreated`, so a component that reads only actions doesn't re-render when a
34
- * message arrives.
35
- *
36
- * @returns The actions of the chat the provider runs.
37
- * @throws {Error} When there is no provider above the component.
38
- *
39
- * @example
40
- * ```tsx
41
- * // A button outside the chat that starts a new app
42
- * function NewAppButton({ prompt }: { prompt: string }) {
43
- * const { create } = useChatActions();
44
- * return <button onClick={() => create(prompt)}>Create</button>;
45
- * }
46
- * ```
47
- */
48
- export declare function useChatActions(): ChatActions;
49
- /** @internal The parts from the nearest provider. */
50
- export declare function useResolvedComponents(component: string): ResolvedComponents;
@@ -1,57 +0,0 @@
1
- "use client";
2
- import { createContext, useContext } from "react";
3
- /** @internal Filled by {@link Base44ChatProvider}. State changes on every event; actions and parts do not. */
4
- export const StateContext = createContext(null);
5
- /** @internal */
6
- export const ActionsContext = createContext(null);
7
- /** @internal */
8
- export const ComponentsContext = createContext(null);
9
- /**
10
- * Reads the chat's state from the nearest {@link Base44ChatProvider}: `items`, `status`,
11
- * `connection` and `error`. A component that calls it re-renders on every live event.
12
- *
13
- * @returns The state of the chat the provider runs.
14
- * @throws {Error} When there is no provider above the component.
15
- *
16
- * @example
17
- * ```tsx
18
- * // The message list
19
- * function Messages() {
20
- * const { items } = useChatState();
21
- * return items.map((item) => <div key={item.id}><Message item={item} /></div>);
22
- * }
23
- * ```
24
- */
25
- export function useChatState() {
26
- return inside(useContext(StateContext), "useChatState");
27
- }
28
- /**
29
- * Reads the chat's actions from the nearest {@link Base44ChatProvider}: `send`, `create` and
30
- * `clearError`. They keep their identity while the app stays the same, also with an inline
31
- * `backend` or `onAppCreated`, so a component that reads only actions doesn't re-render when a
32
- * message arrives.
33
- *
34
- * @returns The actions of the chat the provider runs.
35
- * @throws {Error} When there is no provider above the component.
36
- *
37
- * @example
38
- * ```tsx
39
- * // A button outside the chat that starts a new app
40
- * function NewAppButton({ prompt }: { prompt: string }) {
41
- * const { create } = useChatActions();
42
- * return <button onClick={() => create(prompt)}>Create</button>;
43
- * }
44
- * ```
45
- */
46
- export function useChatActions() {
47
- return inside(useContext(ActionsContext), "useChatActions");
48
- }
49
- /** @internal The parts from the nearest provider. */
50
- export function useResolvedComponents(component) {
51
- return inside(useContext(ComponentsContext), component);
52
- }
53
- function inside(value, reader) {
54
- if (!value)
55
- throw new Error(`${reader} needs a <Base44ChatProvider> above it`);
56
- return value;
57
- }
@@ -1,3 +0,0 @@
1
- import type { MessageComponents } from "./components.types.js";
2
- /** @internal */
3
- export declare const fallbackMessageComponents: MessageComponents;
@@ -1,13 +0,0 @@
1
- "use client";
2
- import { jsx as _jsx } from "react/jsx-runtime";
3
- // The message parts a partner does not replace: plain HTML, no classes, so the library has no look
4
- // of its own. Each carries a `data-base44` attribute for CSS to hook on. Questions have no
5
- // fallback: the partner supplies a part for every kind.
6
- function Text({ text, role, pending }) {
7
- return (_jsx("p", { "data-base44": "text", "data-role": role, "data-pending": pending || undefined, children: text }));
8
- }
9
- function Step({ label, status }) {
10
- return (_jsx("p", { "data-base44": "step", "data-status": status, children: label }));
11
- }
12
- /** @internal */
13
- export const fallbackMessageComponents = { Text, Step };
@@ -1,8 +0,0 @@
1
- /** The `@base44/platform/react` entry: the AI chat for one app, as a hook and as a provider that draws it with your parts. React is an optional peer, loaded only here. */
2
- export { useBase44Chat } from "./useBase44Chat.js";
3
- export { Base44ChatProvider } from "./Base44ChatProvider.js";
4
- export { useChatActions, useChatState } from "./context.js";
5
- export { Message, Question } from "./Message.js";
6
- export type { ApprovalQuestion, Base44App, Base44Chat, Base44ChatOptions, Base44ChatBackend, ChatConnection, ChatError, ChatItem, ChatQuestion, ChatStatus, ChatStep, ChoiceEntry, ChoiceQuestion, SecretField, SecretsQuestion, ToolCallAnswer, } from "./chat.types.js";
7
- export type { Base44ChatProviderProps, ChatActions, ChatComponents, ChatState, MessageComponents, MessageProps, QuestionComponents, QuestionProps, StepProps, TextProps, } from "./components.types.js";
8
- export type { SocketSession } from "../client/modules/builder.types.js";
@@ -1,5 +0,0 @@
1
- /** The `@base44/platform/react` entry: the AI chat for one app, as a hook and as a provider that draws it with your parts. React is an optional peer, loaded only here. */
2
- export { useBase44Chat } from "./useBase44Chat.js";
3
- export { Base44ChatProvider } from "./Base44ChatProvider.js";
4
- export { useChatActions, useChatState } from "./context.js";
5
- export { Message, Question } from "./Message.js";
@@ -1,48 +0,0 @@
1
- import type { Base44Chat, Base44ChatOptions } from "./chat.types.js";
2
- /**
3
- * Runs the AI chat for one app in your own UI.
4
- *
5
- * The hook renders nothing. It gives you the conversation and the actions, and you draw them:
6
- * - Follows the app live, and renews its socket session when it expires.
7
- * - Turns Base44's messages into {@link ChatItem | items}, with each open question bound to the step it belongs to.
8
- * - Reports what the AI is doing in {@link Base44Chat.status}, and the live connection in {@link Base44Chat.connection}.
9
- * - Sends prompts, creates apps and answers questions through the {@link Base44ChatBackend | backend} you pass, so no credential reaches the browser.
10
- *
11
- * The actions never throw. A failure sets {@link Base44Chat.error}, and a question whose answer
12
- * failed opens again. The chat declines a question kind this release doesn't know.
13
- *
14
- * Requires a browser environment and can't be used in the backend.
15
- *
16
- * The chat follows `appId` when it's set. While `appId` is `null`, it follows the app
17
- * {@link Base44Chat.create} made, so passing the new ID back is optional. Any change to `appId`
18
- * forgets that app, so setting it back to `null` starts a new chat. Switching apps closes the old
19
- * session and starts over.
20
- *
21
- * @param options - The app to follow, your backend's calls, and what to do with a created app.
22
- * @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
23
- *
24
- * @example
25
- * ```typescript
26
- * // Draw the chat and answer an approval
27
- * const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
28
- * return (
29
- * <>
30
- * {chat.items.map((item) => (
31
- * <div key={item.id} className={item.role}>
32
- * {item.text && <p>{item.text}</p>}
33
- * {item.steps.map((step) =>
34
- * step.question?.kind === "approval" ? (
35
- * <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
36
- * ) : (
37
- * <small key={step.id}>{step.label}</small>
38
- * ),
39
- * )}
40
- * </div>
41
- * ))}
42
- * {chat.error && <p role="alert">{chat.error.message}</p>}
43
- * <button onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
44
- * </>
45
- * );
46
- * ```
47
- */
48
- export declare function useBase44Chat({ appId, backend, onAppCreated }: Base44ChatOptions): Base44Chat;
@@ -1,312 +0,0 @@
1
- "use client";
2
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
- import { createPlatformClient } from "../client/client.js";
4
- import { isWaitingForUser, mergeMessage, mergeSnapshot, pendingPromptItems, settlePendingPrompts, sortMessages, toItems, unknownKindToolCalls, waitingToolCallIds } from "./chat-items.js";
5
- // Base44's public status carries no reason, so a failed build has one error.
6
- const BUILD_FAILED_ERROR = { message: "The build failed", code: "build_failed" };
7
- // The target of `submittedTo` while `create` runs, before the new app has an id.
8
- const NEW_APP = "new-app";
9
- /**
10
- * Runs the AI chat for one app in your own UI.
11
- *
12
- * The hook renders nothing. It gives you the conversation and the actions, and you draw them:
13
- * - Follows the app live, and renews its socket session when it expires.
14
- * - Turns Base44's messages into {@link ChatItem | items}, with each open question bound to the step it belongs to.
15
- * - Reports what the AI is doing in {@link Base44Chat.status}, and the live connection in {@link Base44Chat.connection}.
16
- * - Sends prompts, creates apps and answers questions through the {@link Base44ChatBackend | backend} you pass, so no credential reaches the browser.
17
- *
18
- * The actions never throw. A failure sets {@link Base44Chat.error}, and a question whose answer
19
- * failed opens again. The chat declines a question kind this release doesn't know.
20
- *
21
- * Requires a browser environment and can't be used in the backend.
22
- *
23
- * The chat follows `appId` when it's set. While `appId` is `null`, it follows the app
24
- * {@link Base44Chat.create} made, so passing the new ID back is optional. Any change to `appId`
25
- * forgets that app, so setting it back to `null` starts a new chat. Switching apps closes the old
26
- * session and starts over.
27
- *
28
- * @param options - The app to follow, your backend's calls, and what to do with a created app.
29
- * @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
30
- *
31
- * @example
32
- * ```typescript
33
- * // Draw the chat and answer an approval
34
- * const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
35
- * return (
36
- * <>
37
- * {chat.items.map((item) => (
38
- * <div key={item.id} className={item.role}>
39
- * {item.text && <p>{item.text}</p>}
40
- * {item.steps.map((step) =>
41
- * step.question?.kind === "approval" ? (
42
- * <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
43
- * ) : (
44
- * <small key={step.id}>{step.label}</small>
45
- * ),
46
- * )}
47
- * </div>
48
- * ))}
49
- * {chat.error && <p role="alert">{chat.error.message}</p>}
50
- * <button onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
51
- * </>
52
- * );
53
- * ```
54
- */
55
- export function useBase44Chat({ appId, backend, onAppCreated }) {
56
- var _a;
57
- const [messages, setMessages] = useState([]);
58
- const [buildState, setBuildState] = useState();
59
- const [connection, setConnection] = useState("connecting");
60
- // A failed action's error, which the next action clears, and the connection's, which it doesn't.
61
- const [actionError, setActionError] = useState(null);
62
- const [connectionError, setConnectionError] = useState(null);
63
- // Tool calls answered here while Base44 still reports them waiting.
64
- const [answeredToolCallIds, setAnsweredToolCallIds] = useState([]);
65
- // The app a prompt, a new app or an answer went to, until Base44 reacts to it.
66
- const [submittedTo, setSubmittedTo] = useState(null);
67
- // Prompts sent from here, shown until Base44 has them.
68
- const [pendingPrompts, setPendingPrompts] = useState([]);
69
- const pendingPromptCount = useRef(0);
70
- // Tool calls declined for the user, and those whose decline failed and may try again.
71
- const declinedToolCalls = useRef(new Set());
72
- const failedDeclines = useRef(new Set());
73
- // The app `create` made, shown while `appId` is null. Any change to `appId` forgets it.
74
- const [createdAppId, setCreatedAppId] = useState(null);
75
- const [previousAppIdProp, setPreviousAppIdProp] = useState(appId);
76
- const appIdPropChanged = previousAppIdProp !== appId;
77
- if (appIdPropChanged) {
78
- setPreviousAppIdProp(appId);
79
- setCreatedAppId(null);
80
- }
81
- // The app this chat shows.
82
- const currentAppId = appId !== null && appId !== void 0 ? appId : (appIdPropChanged ? null : createdAppId);
83
- // Switching apps starts over: the state resets in the same render that sees the new app.
84
- // A submission aimed at the new app, the one `create` just made, stays.
85
- const [stateAppId, setStateAppId] = useState(currentAppId);
86
- if (stateAppId !== currentAppId) {
87
- setStateAppId(currentAppId);
88
- setMessages([]);
89
- setBuildState(undefined);
90
- setConnection("connecting");
91
- setActionError(null);
92
- setConnectionError(null);
93
- setAnsweredToolCallIds([]);
94
- if (submittedTo !== currentAppId && submittedTo !== NEW_APP)
95
- setSubmittedTo(null);
96
- setPendingPrompts(pendingPrompts.filter(prompt => prompt.appId === currentAppId || prompt.appId === NEW_APP));
97
- }
98
- // The backend is read through a ref, kept current after every render, so an inline
99
- // `backend={{…}}` never reopens the socket or changes the actions' identity.
100
- const backendRef = useRef(backend);
101
- useEffect(() => {
102
- backendRef.current = backend;
103
- });
104
- const reportActionError = useCallback((error) => setActionError({ message: (error === null || error === void 0 ? void 0 : error.message) || "Something went wrong", cause: error }), []);
105
- // Live updates: a snapshot on every connect, then events.
106
- useEffect(() => {
107
- const followedAppId = currentAppId;
108
- if (!followedAppId)
109
- return;
110
- let closed = false;
111
- const reportConnectionError = (error) => {
112
- if (closed)
113
- return;
114
- setConnectionError({ message: (error === null || error === void 0 ? void 0 : error.message) || "Live updates failed", code: error === null || error === void 0 ? void 0 : error.code, cause: error });
115
- };
116
- // A failure of the session or the subscription ends live updates: nothing retries after it.
117
- const endLiveUpdates = (error) => {
118
- reportConnectionError(error);
119
- if (!closed)
120
- setConnection("disconnected");
121
- };
122
- // A new reply ends the submission. A new user message is Base44's copy of a prompt, which
123
- // settles the pending one.
124
- const seenMessageIds = new Set();
125
- const handleIncomingMessages = (incomingMessages, settleOldestIfUnmatched) => {
126
- const newMessages = incomingMessages.filter(message => message.id && !seenMessageIds.has(message.id));
127
- for (const message of incomingMessages)
128
- if (message.id)
129
- seenMessageIds.add(message.id);
130
- if (newMessages.some(message => message.role !== "user"))
131
- setSubmittedTo(null);
132
- const arrivedPrompts = newMessages.filter(message => message.role === "user").map(message => { var _a; return (_a = message.content) !== null && _a !== void 0 ? _a : ""; });
133
- if (arrivedPrompts.length) {
134
- setPendingPrompts(prompts => settlePendingPrompts(prompts, followedAppId, arrivedPrompts, settleOldestIfUnmatched));
135
- }
136
- };
137
- // A snapshot replaces the conversation when it is the first, or follows a rewrite of main
138
- // (undo, restore, sync); after a plain rejoin the messages before its window stay.
139
- let nextSnapshotReplaces = true;
140
- // Base44 can resend an earlier turn's status after the next turn has started: one older than
141
- // the newest seen is stale.
142
- let latestStatusDate = "";
143
- const applyBuildStatus = (buildStatus) => {
144
- var _a;
145
- const statusDate = (_a = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.last_updated_date) !== null && _a !== void 0 ? _a : "";
146
- if (statusDate && statusDate < latestStatusDate)
147
- return;
148
- if (statusDate)
149
- latestStatusDate = statusDate;
150
- const state = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.state;
151
- setBuildState(state);
152
- if (state === "processing" || state === "error")
153
- setSubmittedTo(null);
154
- };
155
- // The client asks for a session on the first connect and whenever one expires, and forwards
156
- // no detail of a failed call, so the backend's own error is kept to report.
157
- let lastSessionError;
158
- const builderSession = createPlatformClient().builder.init({
159
- getSession: () => backendRef.current.openLiveSession(followedAppId).then(socketSession => {
160
- lastSessionError = undefined;
161
- return socketSession;
162
- }, (error) => {
163
- lastSessionError = error;
164
- throw error;
165
- }),
166
- onError: error => {
167
- if (error.code !== "session_unavailable" || !lastSessionError)
168
- return endLiveUpdates(error);
169
- if (closed)
170
- return;
171
- setConnectionError({ message: (lastSessionError === null || lastSessionError === void 0 ? void 0 : lastSessionError.message) || error.message, code: error.code, cause: lastSessionError });
172
- setConnection("disconnected");
173
- },
174
- });
175
- builderSession.subscribe(followedAppId, {
176
- onSnapshot: snapshot => {
177
- // A snapshot holds old prompts too, so only an exact match settles one.
178
- handleIncomingMessages(snapshot.messages, false);
179
- const replaceMessages = nextSnapshotReplaces;
180
- nextSnapshotReplaces = false;
181
- setMessages(heldMessages => (replaceMessages ? snapshot.messages : mergeSnapshot(heldMessages, snapshot.messages)));
182
- applyBuildStatus(snapshot.status);
183
- // A declined call that failed tries again on the next snapshot, after a reconnect.
184
- for (const declineKey of failedDeclines.current)
185
- declinedToolCalls.current.delete(declineKey);
186
- failedDeclines.current.clear();
187
- setConnection("connected");
188
- },
189
- onEvent: event => {
190
- if (event.type === "message.updated") {
191
- handleIncomingMessages([event.data.message], true);
192
- setMessages(heldMessages => mergeMessage(heldMessages, event.data.message));
193
- }
194
- if (event.type === "message.removed") {
195
- setMessages(heldMessages => heldMessages.filter(message => message.id !== event.data.message_id));
196
- }
197
- if (event.type === "app.status_changed")
198
- applyBuildStatus(event.data.status);
199
- if (event.type === "conversation.changed" && event.data.branch_id == null)
200
- nextSnapshotReplaces = true;
201
- // A prompt sent while the AI is working waits in Base44's queue: Base44 has it, and it
202
- // stays pending until it runs.
203
- if (event.type === "queue.updated" && event.data.branch_id == null)
204
- setSubmittedTo(null);
205
- },
206
- // Only snapshot_unavailable leaves the subscription running.
207
- onError: error => (error.code === "snapshot_unavailable" ? reportConnectionError(error) : endLiveUpdates(error)),
208
- });
209
- // A failed connect also reaches onError, which reports it.
210
- builderSession.connect().catch(() => { });
211
- return () => {
212
- closed = true;
213
- builderSession.close();
214
- };
215
- }, [currentAppId]);
216
- // Answers one tool call. Its id leaves the answered list again if the submit fails, so the
217
- // question comes back.
218
- const submitAnswer = useCallback((toolCallId, messageId, approve, extraUserInput) => {
219
- if (!currentAppId)
220
- return Promise.resolve();
221
- setActionError(null);
222
- setSubmittedTo(currentAppId);
223
- setAnsweredToolCallIds(ids => [...ids, toolCallId]);
224
- const answer = { toolCallId, messageId, approve, extraUserInput };
225
- return backendRef.current.submitToolCallInput(currentAppId, answer).catch((error) => {
226
- setAnsweredToolCallIds(ids => ids.filter(answeredId => answeredId !== toolCallId));
227
- setSubmittedTo(null);
228
- reportActionError(error);
229
- });
230
- }, [currentAppId, reportActionError]);
231
- const sortedMessages = useMemo(() => sortMessages(messages), [messages]);
232
- const pendingForCurrentApp = useMemo(() => pendingPrompts.filter(prompt => prompt.appId === currentAppId || (prompt.appId === NEW_APP && !currentAppId)), [pendingPrompts, currentAppId]);
233
- const items = useMemo(() => [...toItems(sortedMessages, answeredToolCallIds, submitAnswer), ...pendingPromptItems(pendingForCurrentApp)], [sortedMessages, answeredToolCallIds, submitAnswer, pendingForCurrentApp]);
234
- const waitingForUser = useMemo(() => isWaitingForUser(sortedMessages, answeredToolCallIds), [sortedMessages, answeredToolCallIds]);
235
- // A kind this release doesn't know is declined once per tool call. If that fails, the step waits
236
- // again, the error shows, and the next snapshot tries once more.
237
- useEffect(() => {
238
- const followedAppId = currentAppId;
239
- if (!followedAppId)
240
- return;
241
- for (const { toolCallId, messageId } of unknownKindToolCalls(sortedMessages)) {
242
- const declineKey = `${followedAppId}:${toolCallId}`;
243
- if (declinedToolCalls.current.has(declineKey))
244
- continue;
245
- declinedToolCalls.current.add(declineKey);
246
- setAnsweredToolCallIds(ids => [...ids, toolCallId]);
247
- backendRef.current.submitToolCallInput(followedAppId, { toolCallId, messageId, approve: false }).catch((error) => {
248
- failedDeclines.current.add(declineKey);
249
- setAnsweredToolCallIds(ids => ids.filter(answeredId => answeredId !== toolCallId));
250
- reportActionError(error);
251
- });
252
- }
253
- }, [currentAppId, sortedMessages, reportActionError]);
254
- // An answered call stays hidden while Base44 still reports it waiting, and is forgotten once it
255
- // doesn't: if Base44 parks it again, its question comes back.
256
- useEffect(() => {
257
- const stillWaiting = waitingToolCallIds(sortedMessages);
258
- setAnsweredToolCallIds(ids => (ids.every(answeredId => stillWaiting.has(answeredId)) ? ids : ids.filter(answeredId => stillWaiting.has(answeredId))));
259
- }, [sortedMessages]);
260
- const submissionInFlight = (submittedTo === NEW_APP && !currentAppId) || (submittedTo !== null && submittedTo === currentAppId);
261
- let status = "ready";
262
- if (buildState === "error")
263
- status = "error";
264
- else if (waitingForUser)
265
- status = "waiting";
266
- else if (buildState === "processing")
267
- status = "building";
268
- else if (submissionInFlight)
269
- status = "submitted";
270
- const addPendingPrompt = useCallback((content, targetAppId) => {
271
- const pendingPrompt = { id: `pending-${++pendingPromptCount.current}`, content, createdAt: new Date().toISOString(), appId: targetAppId };
272
- setPendingPrompts(prompts => [...prompts, pendingPrompt]);
273
- return pendingPrompt;
274
- }, []);
275
- const send = useCallback((prompt) => {
276
- if (!currentAppId) {
277
- setActionError({ message: "There is no app to send to yet: create one first" });
278
- return Promise.resolve();
279
- }
280
- setActionError(null);
281
- setSubmittedTo(currentAppId);
282
- const pendingPrompt = addPendingPrompt(prompt, currentAppId);
283
- return backendRef.current.sendMessage(currentAppId, prompt).catch((error) => {
284
- setSubmittedTo(null);
285
- setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
286
- reportActionError(error);
287
- });
288
- }, [currentAppId, reportActionError, addPendingPrompt]);
289
- const create = useCallback(async (prompt) => {
290
- setActionError(null);
291
- setSubmittedTo(NEW_APP);
292
- const pendingPrompt = addPendingPrompt(prompt, NEW_APP);
293
- try {
294
- const app = await backendRef.current.createApp(prompt);
295
- setCreatedAppId(app.id);
296
- setSubmittedTo(app.id);
297
- setPendingPrompts(prompts => prompts.map(other => (other === pendingPrompt ? { ...other, appId: app.id } : other)));
298
- onAppCreated === null || onAppCreated === void 0 ? void 0 : onAppCreated(app);
299
- }
300
- catch (error) {
301
- setSubmittedTo(null);
302
- setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
303
- reportActionError(error);
304
- }
305
- }, [onAppCreated, reportActionError, addPendingPrompt]);
306
- const clearError = useCallback(() => {
307
- setActionError(null);
308
- setConnectionError(null);
309
- }, []);
310
- const error = (_a = actionError !== null && actionError !== void 0 ? actionError : connectionError) !== null && _a !== void 0 ? _a : (buildState === "error" ? BUILD_FAILED_ERROR : null);
311
- return { items, status, connection, error, send, create, clearError };
312
- }
@@ -1,2 +0,0 @@
1
- /** Validate a platform origin and return it normalized. Used by the server entrypoint. */
2
- export declare function normalizeServerUrl(serverUrl: string): string;
@@ -1,8 +0,0 @@
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
- }