@base44-preview/sdk 0.8.43-pr.260.38a957a → 0.8.43-pr.261.f8cbcf8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -12,7 +12,7 @@ import { createAppLogsModule } from "./modules/app-logs.js";
12
12
  import { createUsersModule } from "./modules/users.js";
13
13
  import { RoomsSocket } from "./utils/socket-utils.js";
14
14
  import { createAnalyticsModule } from "./modules/analytics.js";
15
- import { createActorsModule, resolveActorsHost, } from "./modules/actors.js";
15
+ import { createActorsModule, resolveActorsHost } from "./modules/actors.js";
16
16
  /**
17
17
  * Creates a Base44 client.
18
18
  *
@@ -110,15 +110,6 @@ export function createClient(config) {
110
110
  token: serviceToken,
111
111
  interceptResponses: false,
112
112
  });
113
- // Dedicated client for actor connection-token mints: no onError (a legacy
114
- // actor answers every mint with an expected 409 before the proxy fallback,
115
- // which must not reach the app's error handler — the actors module forwards
116
- // genuine failures itself via onMintError) and no constructor token
117
- // (auth is per-request so a login/logout is picked up on every reconnect).
118
- const actorsAxiosClient = createAxiosClient({
119
- baseURL: `${serverUrl}/api`,
120
- headers,
121
- });
122
113
  const userAuthModule = createAuthModule(axiosClient, functionsAxiosClient, appId, {
123
114
  appBaseUrl: normalizedAppBaseUrl,
124
115
  serverUrl,
@@ -136,26 +127,11 @@ export function createClient(config) {
136
127
  }
137
128
  const actorsModule = createActorsModule({
138
129
  appId,
139
- // serverUrl is often relative/empty (same-origin app); the proxy-fallback
140
- // URL needs an absolute host, so fall back to the page origin.
130
+ // serverUrl is often relative/empty (same-origin app); PartySocket needs an
131
+ // absolute host, so fall back to the page origin.
141
132
  host: resolveActorsHost(serverUrl, typeof window !== "undefined" ? (_a = window.location) === null || _a === void 0 ? void 0 : _a.origin : undefined),
142
133
  functionsVersion,
143
134
  getAuthToken: () => token || getAccessToken(),
144
- mintConnectionToken: async (actorName, room, connectionId) => {
145
- const authToken = token || getAccessToken();
146
- return await actorsAxiosClient.post(`/apps/${appId}/actors/${encodeURIComponent(actorName)}/connection-token`, { room, connection_id: connectionId }, {
147
- headers: {
148
- ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
149
- // The mint endpoint resolves draft vs published from this header;
150
- // only the functions axios clients send it by default.
151
- ...(functionsVersion
152
- ? { "Base44-Functions-Version": functionsVersion }
153
- : {}),
154
- },
155
- });
156
- },
157
- transport: options === null || options === void 0 ? void 0 : options.actorsTransport,
158
- onMintError: options === null || options === void 0 ? void 0 : options.onError,
159
135
  });
160
136
  const userModules = {
161
137
  entities: createEntitiesModule({
@@ -15,20 +15,8 @@ import type { ActorsModule } from "./modules/actors.types.js";
15
15
  export interface CreateClientOptions {
16
16
  /**
17
17
  * Optional error handler that will be called whenever an API error occurs.
18
- *
19
- * Also receives {@link ActorsModule | actors} connection failures. Errors
20
- * are usually {@linkcode Base44Error} instances — check `error.status`.
21
18
  */
22
19
  onError?: (error: Error) => void;
23
- /**
24
- * Forces the actors transport. `"auto"` (default) connects directly to the
25
- * actor and falls back to the platform proxy when the app's actors don't
26
- * support direct connections; `"proxy"` always uses the platform proxy
27
- * (ops rollback — no connection-token calls); `"direct"` disables the
28
- * fallback (validation environments).
29
- * @internal
30
- */
31
- actorsTransport?: "auto" | "proxy" | "direct";
32
20
  }
33
21
  /**
34
22
  * Configuration for creating a Base44 client.
package/dist/index.d.ts CHANGED
@@ -14,6 +14,6 @@ export type { AppLogsModule } from "./modules/app-logs.types.js";
14
14
  export type { ActorsModule, ActorClient, ActorRef, Connection, ActorSubscription, ActorConnectOptions, ActorNameRegistry, ActorRegistry, } from "./modules/actors.types.js";
15
15
  export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
16
16
  export { Actor, type Conn } from "./actor.js";
17
- export type { ConnectorsModule, UserConnectorsModule, } from "./modules/connectors.types.js";
17
+ export type { ConnectorsModule, UserConnectorsModule, ConnectorApiRequest, ConnectorApiResponse, ConnectorApiResponsePhase, } from "./modules/connectors.types.js";
18
18
  export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
19
19
  export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
@@ -1,47 +1,21 @@
1
1
  import type { ActorRef } from "./actors.types.js";
2
- /** Credentials minted by the platform for one direct actor connection. */
3
- export interface ActorConnectionCredentials {
4
- /** Direct actor endpoint, already carrying `?_pk=<connectionId>`. */
5
- websocket_url: string;
6
- /** Short-lived JWT bound to (app, actor, room, connectionId); appended to
7
- * the URL as `token=` since browsers can't set WebSocket headers. */
8
- token: string;
9
- }
10
2
  interface ActorsConfig {
11
3
  appId: string;
12
- /** Current user access token, if authenticated. Rides the WS query on the
13
- * proxy-fallback path so the platform proxy can authenticate the connection;
14
- * anonymous connects omit it. */
4
+ /** Current user access token, if authenticated. Rides the WS query so the
5
+ * platform proxy can authenticate the connection; anonymous connects omit it. */
15
6
  getAuthToken(): string | null | undefined;
16
7
  /** Same semantics as function calls: editors with a non-prod version get the
17
8
  * draft actor script; everyone else gets the published one. */
18
9
  functionsVersion?: string;
19
- /** Absolute host for the proxy-fallback URL (scheme is swapped to wss, ws
10
+ /** Absolute host PartySocket dials (it strips the scheme and connects wss, ws
20
11
  * for localhost). Resolved by {@link resolveActorsHost}. */
21
12
  host: string;
22
- /** Mints a direct-connect credential for one (actor, room, connection).
23
- * Called per connection attempt: the token's expiry is checked at upgrade,
24
- * so every reconnect needs a fresh one. */
25
- mintConnectionToken(actorName: string, room: string, connectionId: string): Promise<ActorConnectionCredentials>;
26
- /** @internal Ops escape hatch: "proxy" never mints (legacy path only),
27
- * "direct" never falls back. Default "auto". */
28
- transport?: "auto" | "proxy" | "direct";
29
- /** Called when a mint fails for a reason other than the expected
30
- * direct→proxy fallback (which recovers by itself). Wired to the client's
31
- * `options.onError`. */
32
- onMintError?: (error: Error) => void;
33
13
  }
34
14
  /**
35
- * The legacy platform-proxy URL, byte-for-byte what PartySocket built before
36
- * the direct path existed: same scheme swap (including its localhost-needs-a-
37
- * port quirk), case-preserved party segment, `_pk` first in the query. The
38
- * `handler` param is load-bearing — the proxy reads it for the actor name.
39
- */
40
- export declare function buildProxyActorUrl(rawHost: string, actorName: string, instanceId: string, connectionId: string, appId: string, token: string | null | undefined, functionsVersion?: string): string;
41
- /**
42
- * Absolute host for the proxy-fallback actor URL. A relative/empty `serverUrl`
43
- * can't be dialed (same-origin apps use a relative `/api`, so `serverUrl` is
44
- * often `""`), so fall back to the page origin.
15
+ * Absolute host for the actor WebSocket. PartySocket needs an absolute host and
16
+ * can't resolve a relative/empty `serverUrl` (same-origin apps use a relative
17
+ * `/api`, so `serverUrl` is often `""`), so fall back to the page origin.
18
+ * PartySocket handles the scheme (https→wss, ws for localhost).
45
19
  */
46
20
  export declare function resolveActorsHost(serverUrl: string, browserOrigin?: string): string;
47
21
  export declare function createActorsModule(config: ActorsConfig): {
@@ -1,30 +1,8 @@
1
- import { WebSocket as ReconnectingWebSocket } from "partysocket";
2
- // Heartbeat / half-open detection: the socket only reconnects on a close/error
1
+ import PartySocket from "partysocket";
2
+ // Heartbeat / half-open detection: PartySocket only reconnects on a close/error
3
3
  // event, so ping periodically and force a reconnect if nothing returns in DEAD_MS.
4
4
  const PING_MS = 1000;
5
5
  const DEAD_MS = 3000;
6
- // Mint responses that mean "direct can't serve this connection, the proxy can":
7
- // 409 = legacy-family actor script, 503 = direct connections not provisioned,
8
- // 422 = no principal (e.g. anonymous outside a browser) or an id/room only the
9
- // proxy's looser validation accepts. The proxy serves migrated actors too, so
10
- // falling back is always safe.
11
- const PROXY_FALLBACK_STATUSES = new Set([409, 422, 503]);
12
- // Mint responses no retry can fix (bad request / forbidden / not found): the
13
- // connection closes instead of re-minting forever; a fresh connect() re-probes.
14
- // 401 is deliberately absent — the auth token is re-read on every attempt, so a
15
- // login recovers on the next retry. Disjoint from PROXY_FALLBACK_STATUSES.
16
- const TERMINAL_MINT_STATUSES = new Set([400, 403, 404]);
17
- /** The mint's rejection can be anything; a `Base44Error` carries a numeric
18
- * `.status` (absent for network failures). */
19
- function mintErrorStatus(err) {
20
- const status = err && typeof err === "object"
21
- ? err.status
22
- : undefined;
23
- return typeof status === "number" ? status : undefined;
24
- }
25
- function toError(err) {
26
- return err instanceof Error ? err : new Error(String(err));
27
- }
28
6
  /**
29
7
  * A live connection to an actor instance. Only obtainable from
30
8
  * {@link ActorRef.connect}, so `subscribe`/`send` are always valid — the socket
@@ -36,54 +14,23 @@ class Connection {
36
14
  this.onClose = onClose;
37
15
  this.listeners = new Set();
38
16
  this.heartbeat = null;
39
- this.closed = false;
40
17
  this.id = (_a = options === null || options === void 0 ? void 0 : options.id) !== null && _a !== void 0 ? _a : crypto.randomUUID();
41
- // Direct-first with proxy fallback, decided per connection attempt. Once a
42
- // mint answers with a fallback status the choice is sticky for this
43
- // socket's lifetime (a fresh connect() after close() probes direct again,
44
- // picking up actors migrated in the meantime). Any other mint failure
45
- // rejects, which ReconnectingWebSocket retries with backoff — except the
46
- // terminal statuses, which close this connection for good.
47
- let useProxy = config.transport === "proxy";
48
- const urlProvider = async () => {
49
- var _a;
50
- if (this.closed)
51
- throw new Error("Actor connection is closed");
52
- if (!useProxy) {
53
- try {
54
- const { websocket_url, token } = await config.mintConnectionToken(actorName, instanceId, this.id);
55
- const sep = websocket_url.includes("?") ? "&" : "?";
56
- return `${websocket_url}${sep}token=${encodeURIComponent(token)}`;
57
- }
58
- catch (err) {
59
- const status = mintErrorStatus(err);
60
- const isFallback = config.transport !== "direct" &&
61
- status !== undefined &&
62
- PROXY_FALLBACK_STATUSES.has(status);
63
- if (!isFallback) {
64
- if (status !== undefined && TERMINAL_MINT_STATUSES.has(status)) {
65
- // close() before notifying: ws.close() stops the redial the
66
- // rethrow below would otherwise schedule, and a handler that
67
- // immediately calls connect() gets a clean new connection.
68
- this.close();
69
- }
70
- // Reported from here because the socket's error event only
71
- // preserves `err.message`, never `.status`.
72
- try {
73
- (_a = config.onMintError) === null || _a === void 0 ? void 0 : _a.call(config, toError(err));
74
- }
75
- catch (_b) {
76
- // an app handler must not break the dial loop or mask `err`
77
- }
78
- throw err;
79
- }
80
- useProxy = true;
81
- }
82
- }
83
- // Rebuilt per attempt so a login/logout is picked up on reconnect.
84
- return buildProxyActorUrl(config.host, actorName, instanceId, this.id, config.appId, config.getAuthToken(), config.functionsVersion);
85
- };
86
- const ws = new ReconnectingWebSocket(urlProvider);
18
+ const ws = new PartySocket({
19
+ host: config.host,
20
+ party: actorName,
21
+ room: instanceId,
22
+ id: this.id,
23
+ // Re-read on every (re)connect so a login/logout is picked up.
24
+ query: () => {
25
+ const token = config.getAuthToken();
26
+ return {
27
+ app_id: config.appId,
28
+ handler: actorName,
29
+ ...(token ? { token } : {}),
30
+ ...(config.functionsVersion ? { fv: config.functionsVersion } : {}),
31
+ };
32
+ },
33
+ });
87
34
  this.ws = ws;
88
35
  let lastMsg = Date.now();
89
36
  const bumpAlive = () => { lastMsg = Date.now(); };
@@ -106,11 +53,7 @@ class Connection {
106
53
  this.heartbeat = setInterval(() => {
107
54
  if (Date.now() - lastMsg > DEAD_MS) {
108
55
  bumpAlive(); // avoid a reconnect storm while the new socket comes up
109
- // Only kick a half-open socket (OPEN but silent). When it isn't open
110
- // the socket is already redialing with backoff, and reconnect() would
111
- // reset that backoff into a mint call every DEAD_MS.
112
- if (ws.readyState === ws.OPEN)
113
- ws.reconnect();
56
+ ws.reconnect();
114
57
  return;
115
58
  }
116
59
  try {
@@ -130,15 +73,9 @@ class Connection {
130
73
  };
131
74
  }
132
75
  send(data) {
133
- // after close() the socket would buffer forever (unbounded enqueue)
134
- if (this.closed)
135
- return;
136
76
  this.ws.send(JSON.stringify(data));
137
77
  }
138
78
  close() {
139
- if (this.closed)
140
- return;
141
- this.closed = true;
142
79
  if (this.heartbeat) {
143
80
  clearInterval(this.heartbeat);
144
81
  this.heartbeat = null;
@@ -167,38 +104,10 @@ function makeActorRef(actorName, instanceId, config, connections) {
167
104
  };
168
105
  }
169
106
  /**
170
- * The legacy platform-proxy URL, byte-for-byte what PartySocket built before
171
- * the direct path existed: same scheme swap (including its localhost-needs-a-
172
- * port quirk), case-preserved party segment, `_pk` first in the query. The
173
- * `handler` param is load-bearing — the proxy reads it for the actor name.
174
- */
175
- export function buildProxyActorUrl(rawHost, actorName, instanceId, connectionId, appId, token, functionsVersion) {
176
- let host = rawHost.replace(/^(http|https|ws|wss):\/\//, "");
177
- if (host.endsWith("/"))
178
- host = host.slice(0, -1);
179
- const insecure = host.startsWith("localhost:") ||
180
- host.startsWith("127.0.0.1:") ||
181
- host.startsWith("192.168.") ||
182
- host.startsWith("10.") ||
183
- (host.startsWith("172.") &&
184
- host.split(".")[1] >= "16" &&
185
- host.split(".")[1] <= "31") ||
186
- host.startsWith("[::ffff:7f00:1]:");
187
- const query = new URLSearchParams([
188
- ["_pk", connectionId],
189
- ["app_id", appId],
190
- ["handler", actorName],
191
- ]);
192
- if (token)
193
- query.append("token", token);
194
- if (functionsVersion)
195
- query.append("fv", functionsVersion);
196
- return `${insecure ? "ws" : "wss"}://${host}/parties/${actorName}/${instanceId}?${query}`;
197
- }
198
- /**
199
- * Absolute host for the proxy-fallback actor URL. A relative/empty `serverUrl`
200
- * can't be dialed (same-origin apps use a relative `/api`, so `serverUrl` is
201
- * often `""`), so fall back to the page origin.
107
+ * Absolute host for the actor WebSocket. PartySocket needs an absolute host and
108
+ * can't resolve a relative/empty `serverUrl` (same-origin apps use a relative
109
+ * `/api`, so `serverUrl` is often `""`), so fall back to the page origin.
110
+ * PartySocket handles the scheme (https→wss, ws for localhost).
202
111
  */
203
112
  export function resolveActorsHost(serverUrl, browserOrigin) {
204
113
  return serverUrl && !serverUrl.startsWith("/") ? serverUrl : browserOrigin !== null && browserOrigin !== void 0 ? browserOrigin : serverUrl;
@@ -56,14 +56,9 @@ export interface Connection<N extends string = string> {
56
56
  readonly id: string;
57
57
  /** Register a message listener. Multiple are allowed; returns a per-listener unsubscribe. */
58
58
  subscribe(callback: (data: ToClientFor<N>) => void): ActorSubscription;
59
- /** Send a message. Buffered by the socket until it's open; dropped after
60
- * {@link close}. */
59
+ /** Send a message. Buffered by the socket until it's open. */
61
60
  send(data: ToServerFor<N>): void;
62
- /**
63
- * Tear down the socket, heartbeat, and all listeners. Safe to call more
64
- * than once. A connection also closes itself when it fails permanently —
65
- * see {@link ActorRef.connect}.
66
- */
61
+ /** Tear down the socket, heartbeat, and all listeners. */
67
62
  close(): void;
68
63
  }
69
64
  /**
@@ -71,15 +66,7 @@ export interface Connection<N extends string = string> {
71
66
  * {@link connect} to open the socket and get a {@link Connection}.
72
67
  */
73
68
  export interface ActorRef<N extends string = string> {
74
- /**
75
- * Open the WebSocket and return the {@link Connection}. Idempotent while the
76
- * connection is open.
77
- *
78
- * A connection that fails permanently (for example, the actor doesn't exist
79
- * or the caller isn't allowed to connect) closes itself and reports the
80
- * error to the client's `onError` handler. Call `connect()` again after
81
- * fixing the cause to get a fresh {@link Connection}, and re-subscribe.
82
- */
69
+ /** Open the WebSocket and return the {@link Connection}. Idempotent. */
83
70
  connect(options?: ActorConnectOptions): Connection<N>;
84
71
  }
85
72
  /**
@@ -25,9 +25,6 @@ const analyticsSharedState = getSharedInstance(ANALYTICS_SHARED_STATE_NAME, () =
25
25
  wasInitializationTracked: false,
26
26
  sessionContext: null,
27
27
  sessionStartTime: null,
28
- // Memoized session id for when `localStorage` can't persist one — see
29
- // getAnalyticsSessionId.
30
- fallbackSessionId: null,
31
28
  config: {
32
29
  ...defaultConfiguration,
33
30
  ...getAnalyticsConfigFromUrlParams(),
@@ -219,11 +216,9 @@ function trackSessionDurationEvent(track) {
219
216
  });
220
217
  }
221
218
  function getEventIntrinsicData() {
222
- var _a, _b;
223
219
  return {
224
220
  timestamp: new Date().toISOString(),
225
- // `window.location` is absent on React Native, so read it optionally.
226
- pageUrl: typeof window !== "undefined" ? (_b = (_a = window.location) === null || _a === void 0 ? void 0 : _a.pathname) !== null && _b !== void 0 ? _b : null : null,
221
+ pageUrl: typeof window !== "undefined" ? window.location.pathname : null,
227
222
  };
228
223
  }
229
224
  function transformEventDataToApiRequestData(sessionContext) {
@@ -307,15 +302,9 @@ export function getAnalyticsConfigFromUrlParams() {
307
302
  // return the config object //
308
303
  return { enabled: analyticsEnable === "true" };
309
304
  }
310
- // When the id can't be persisted (React Native has no `localStorage`), keep
311
- // it stable for the process instead of minting a fresh one per call.
312
- function getFallbackSessionId() {
313
- var _a;
314
- return ((_a = analyticsSharedState.fallbackSessionId) !== null && _a !== void 0 ? _a : (analyticsSharedState.fallbackSessionId = generateUuid()));
315
- }
316
305
  export function getAnalyticsSessionId() {
317
306
  if (typeof window === "undefined") {
318
- return getFallbackSessionId();
307
+ return generateUuid();
319
308
  }
320
309
  try {
321
310
  const sessionId = localStorage.getItem(ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY);
@@ -327,6 +316,6 @@ export function getAnalyticsSessionId() {
327
316
  return sessionId;
328
317
  }
329
318
  catch (_a) {
330
- return getFallbackSessionId();
319
+ return generateUuid();
331
320
  }
332
321
  }
@@ -1,3 +1,11 @@
1
+ const CONNECTOR_API_METHODS = new Set([
2
+ "GET",
3
+ "POST",
4
+ "PUT",
5
+ "PATCH",
6
+ "DELETE",
7
+ "HEAD",
8
+ ]);
1
9
  /**
2
10
  * Creates the Connectors module for the Base44 SDK.
3
11
  *
@@ -17,7 +25,7 @@ export function createConnectorsModule(axios, appId) {
17
25
  if (!integrationType || typeof integrationType !== "string") {
18
26
  throw new Error("Integration type is required and must be a string");
19
27
  }
20
- const response = await axios.get(`/apps/${appId}/external-auth/tokens/${integrationType}`);
28
+ const response = await axios.get(`/apps/${appId}/external-auth/tokens/${encodeURIComponent(integrationType)}`);
21
29
  // @ts-expect-error
22
30
  return response.access_token;
23
31
  },
@@ -26,7 +34,7 @@ export function createConnectorsModule(axios, appId) {
26
34
  if (!integrationType || typeof integrationType !== "string") {
27
35
  throw new Error("Integration type is required and must be a string");
28
36
  }
29
- const response = await axios.get(`/apps/${appId}/external-auth/tokens/${integrationType}`);
37
+ const response = await axios.get(`/apps/${appId}/external-auth/tokens/${encodeURIComponent(integrationType)}`);
30
38
  const data = response;
31
39
  return {
32
40
  accessToken: data.access_token,
@@ -38,7 +46,7 @@ export function createConnectorsModule(axios, appId) {
38
46
  if (!connectorId || typeof connectorId !== "string") {
39
47
  throw new Error("Connector ID is required and must be a string");
40
48
  }
41
- const response = await axios.get(`/apps/${appId}/external-auth/tokens/connectors/${connectorId}`);
49
+ const response = await axios.get(`/apps/${appId}/external-auth/tokens/connectors/${encodeURIComponent(connectorId)}`);
42
50
  const data = response;
43
51
  return {
44
52
  accessToken: data.access_token,
@@ -52,7 +60,7 @@ export function createConnectorsModule(axios, appId) {
52
60
  if (!connectorId || typeof connectorId !== "string") {
53
61
  throw new Error("Connector ID is required and must be a string");
54
62
  }
55
- const response = await axios.get(`/apps/${appId}/app-user-auth/connectors/${connectorId}/token`);
63
+ const response = await axios.get(`/apps/${appId}/app-user-auth/connectors/${encodeURIComponent(connectorId)}/token`);
56
64
  const data = response;
57
65
  return data.access_token;
58
66
  },
@@ -61,13 +69,65 @@ export function createConnectorsModule(axios, appId) {
61
69
  if (!connectorId || typeof connectorId !== "string") {
62
70
  throw new Error("Connector ID is required and must be a string");
63
71
  }
64
- const response = await axios.get(`/apps/${appId}/app-user-auth/connectors/${connectorId}/token`);
72
+ const response = await axios.get(`/apps/${appId}/app-user-auth/connectors/${encodeURIComponent(connectorId)}/token`);
65
73
  const data = response;
66
74
  return {
67
75
  accessToken: data.access_token,
68
76
  connectionConfig: (_a = data.connection_config) !== null && _a !== void 0 ? _a : null,
69
77
  };
70
78
  },
79
+ async callApi(integrationType, request) {
80
+ assertNonEmptyString(integrationType, "Integration type");
81
+ // Encoded so a runtime-built identifier can only ever select a
82
+ // connector, never re-target another route under this token.
83
+ return proxyCall(axios, `/apps/${appId}/connectors/${encodeURIComponent(integrationType)}/call`, request);
84
+ },
85
+ };
86
+ }
87
+ function assertNonEmptyString(value, label) {
88
+ if (!value || typeof value !== "string") {
89
+ throw new Error(`${label} is required and must be a string`);
90
+ }
91
+ }
92
+ /**
93
+ * POST a request to the connector proxy and normalize the response.
94
+ *
95
+ * The proxy reports upstream outcomes in the body rather than as HTTP status, so
96
+ * a provider 4xx/5xx arrives here as a resolved response with `success: false` —
97
+ * only Base44-side failures reject through the axios error interceptor.
98
+ *
99
+ * @internal
100
+ */
101
+ async function proxyCall(axios, url, request) {
102
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
103
+ if (!request || typeof request !== "object") {
104
+ throw new Error("Request is required and must be an object");
105
+ }
106
+ assertNonEmptyString(request.path, "Request path");
107
+ const method = (_a = request.method) !== null && _a !== void 0 ? _a : "GET";
108
+ if (!CONNECTOR_API_METHODS.has(method)) {
109
+ throw new Error("Request method must be one of GET, POST, PUT, PATCH, DELETE, or HEAD");
110
+ }
111
+ const response = await axios.post(url, {
112
+ method,
113
+ // Omitted when unset (undefined or null, since untyped callers write
114
+ // either) so the proxy applies the connector's declared default host.
115
+ ...(request.host == null ? {} : { host: request.host }),
116
+ path: request.path,
117
+ query: (_b = request.query) !== null && _b !== void 0 ? _b : {},
118
+ headers: (_c = request.headers) !== null && _c !== void 0 ? _c : {},
119
+ body: (_d = request.body) !== null && _d !== void 0 ? _d : null,
120
+ });
121
+ const data = response;
122
+ return {
123
+ success: data.success,
124
+ phase: data.phase,
125
+ status: (_e = data.status_code) !== null && _e !== void 0 ? _e : null,
126
+ data: data.data,
127
+ dataBase64: (_f = data.data_base64) !== null && _f !== void 0 ? _f : null,
128
+ contentType: (_g = data.content_type) !== null && _g !== void 0 ? _g : null,
129
+ headers: (_h = data.headers) !== null && _h !== void 0 ? _h : {},
130
+ creditsCharged: (_j = data.credits_charged) !== null && _j !== void 0 ? _j : 0,
71
131
  };
72
132
  }
73
133
  /**
@@ -84,7 +144,7 @@ export function createUserConnectorsModule(axios, appId) {
84
144
  if (!connectorId || typeof connectorId !== "string") {
85
145
  throw new Error("Connector ID is required and must be a string");
86
146
  }
87
- const response = await axios.post(`/apps/${appId}/app-user-auth/connectors/${connectorId}/initiate`);
147
+ const response = await axios.post(`/apps/${appId}/app-user-auth/connectors/${encodeURIComponent(connectorId)}/initiate`);
88
148
  const data = response;
89
149
  return data.redirect_url;
90
150
  },
@@ -92,7 +152,7 @@ export function createUserConnectorsModule(axios, appId) {
92
152
  if (!connectorId || typeof connectorId !== "string") {
93
153
  throw new Error("Connector ID is required and must be a string");
94
154
  }
95
- await axios.delete(`/apps/${appId}/app-user-auth/connectors/${connectorId}`);
155
+ await axios.delete(`/apps/${appId}/app-user-auth/connectors/${encodeURIComponent(connectorId)}`);
96
156
  },
97
157
  };
98
158
  }
@@ -41,6 +41,81 @@ export interface AppUserConnectorConnectionResponse {
41
41
  /** Key-value configuration for the connection, or `null` if the connector does not provide one. */
42
42
  connectionConfig: Record<string, string> | null;
43
43
  }
44
+ /**
45
+ * How far a metered connector call progressed through the Base44 proxy.
46
+ *
47
+ * Only `not_sent` proves that the provider did not execute the request.
48
+ * `timed_out` and `sent_unconfirmed` may have executed upstream, so do not
49
+ * automatically retry non-idempotent requests based on those phases.
50
+ */
51
+ export type ConnectorApiResponsePhase = "not_sent" | "responded" | "timed_out" | "sent_unconfirmed";
52
+ /**
53
+ * A request to forward to a metered connector's API through the Base44 proxy.
54
+ */
55
+ export interface ConnectorApiRequest {
56
+ /** HTTP method for the upstream request. Defaults to `'GET'`. */
57
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
58
+ /**
59
+ * Which of the connector's API hosts to call, by the name it declares.
60
+ * Omit for its default host (the first one declared). Only relevant for
61
+ * connectors that expose more than one host.
62
+ */
63
+ host?: string;
64
+ /**
65
+ * Path relative to the connector's API root, starting with `/`, such as `'/2/tweets'`.
66
+ *
67
+ * Must not be an absolute URL. Query parameters may be included here or passed
68
+ * separately as {@link query}; either way they are forwarded and priced identically.
69
+ */
70
+ path: string;
71
+ /** Query parameters. Merged into the request URL alongside any already present in {@link path}. */
72
+ query?: Record<string, string | number | boolean | Array<string | number>>;
73
+ /** Extra request headers. Only headers the connector explicitly allows are forwarded; the rest are dropped. */
74
+ headers?: Record<string, string>;
75
+ /** JSON request body. Ignored for `GET` and `HEAD`. */
76
+ body?: unknown;
77
+ }
78
+ /**
79
+ * The upstream API's response, as returned by the Base44 connector proxy.
80
+ */
81
+ export interface ConnectorApiResponse<T = unknown> {
82
+ /** `true` only when the upstream API returned a 2xx status. Proxy and upstream errors are `false`. */
83
+ success: boolean;
84
+ /** How far the call progressed. Only `not_sent` proves the provider did not execute it. */
85
+ phase: ConnectorApiResponsePhase;
86
+ /** The upstream HTTP status code, or `null` when no response was received. */
87
+ status: number | null;
88
+ /**
89
+ * The parsed upstream response body, or proxy error details when no response
90
+ * was received. `null` when the response was binary — see {@link dataBase64}.
91
+ */
92
+ data: T | null;
93
+ /**
94
+ * The response body base64-encoded, for the media types the connector declares
95
+ * as binary (images, PDFs). Set instead of {@link data}, never alongside it.
96
+ */
97
+ dataBase64: string | null;
98
+ /** The response media type, set only alongside {@link dataBase64}. */
99
+ contentType: string | null;
100
+ /** The subset of upstream response headers the connector exposes, typically rate-limit counters. */
101
+ headers: Record<string, string>;
102
+ /** Integration credits billed to the workspace for this call. */
103
+ creditsCharged: number;
104
+ }
105
+ /**
106
+ * Raw proxy response shape. Mapped to {@link ConnectorApiResponse} before being returned.
107
+ * @internal
108
+ */
109
+ export interface ConnectorProxyRawResponse {
110
+ success: boolean;
111
+ phase: ConnectorApiResponsePhase;
112
+ status_code: number | null;
113
+ data: unknown;
114
+ data_base64: string | null;
115
+ content_type: string | null;
116
+ headers: Record<string, string>;
117
+ credits_charged: number;
118
+ }
44
119
  /**
45
120
  * Connectors module for managing OAuth tokens for external services.
46
121
  *
@@ -71,6 +146,18 @@ export interface AppUserConnectorConnectionResponse {
71
146
  * 3. In a backend function, call {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()} using the service role client (`base44.asServiceRole.connectors`) with the connector ID to retrieve the app user's token.
72
147
  * 4. Use the returned `accessToken` to call the external service's API directly. Some connectors also return a `connectionConfig` with additional values such as a subdomain for building the API URL.
73
148
  *
149
+ * ## Metered connectors
150
+ *
151
+ * A few [platform connectors](#shared-connectors) are backed by paid third-party APIs that charge Base44 per call. For those, the OAuth token is **not** available to your code — {@linkcode getConnection | getConnection()} rejects with a `403`. Call them with {@linkcode callApi | callApi()} instead: Base44 attaches the credential server-side, forwards the request, and bills your workspace's integration credits for the call.
152
+ *
153
+ * This applies to platform connectors only. A workspace-registered or app user connector runs on **your own** OAuth app, so the provider invoices you directly and there is nothing for Base44 to meter — those keep normal token access via {@linkcode getWorkspaceConnection | getWorkspaceConnection()} and {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()}.
154
+ *
155
+ * Two things to keep in mind when writing against a metered connector:
156
+ *
157
+ * - **Cost varies by endpoint, sometimes sharply.** The same connector can charge two orders of magnitude more for one endpoint than another, so avoid putting an expensive call inside a loop and batch wherever the provider supports it. Each response reports what it actually cost as `creditsCharged`.
158
+ * - **Provider and transport outcomes are returned, not thrown.** A provider `4xx`/`5xx` or a connection failure comes back as `success: false` with its `phase`; authorization, quota, and invalid proxy requests reject the promise.
159
+ * - **Only `phase: 'not_sent'` proves the provider did not execute the request.** A timeout or in-flight failure may have executed upstream, so do not automatically retry a non-idempotent call unless the provider supports an idempotency key.
160
+ *
74
161
  * ## Available connectors
75
162
  *
76
163
  * The connectors below can be used as shared connectors or as app user connectors. For a shared platform connector, pass the integration type string to {@linkcode getConnection | getConnection()}. For a connector you register in Workspace Settings with your own OAuth app, use the connector ID with {@linkcode getWorkspaceConnection | getWorkspaceConnection()} for a shared token, or with {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()} for a per-user token.
@@ -328,6 +415,41 @@ export interface ConnectorsModule {
328
415
  * ```
329
416
  */
330
417
  getCurrentAppUserConnection(connectorId: string): Promise<AppUserConnectorConnectionResponse>;
418
+ /**
419
+ * Calls a [metered connector's](#metered-connectors) API through the Base44 proxy.
420
+ *
421
+ * Use this for a shared platform connector identified by an integration type. Base44 adds the OAuth credential to the outgoing request, forwards it, and bills the workspace for the call, so you never handle the token yourself.
422
+ *
423
+ * @param integrationType - The type of integration, such as `'x'`. See [Available connectors](#available-connectors).
424
+ * @param request - The upstream request to forward. See {@link ConnectorApiRequest}.
425
+ * @returns Promise resolving to a {@link ConnectorApiResponse}. Note that an upstream error is reported in `success` and `status`, not thrown — only Base44-side failures reject.
426
+ *
427
+ * @example
428
+ * ```typescript
429
+ * // Post to X
430
+ * const res = await base44.asServiceRole.connectors.callApi('x', {
431
+ * method: 'POST',
432
+ * path: '/2/tweets',
433
+ * body: { text: 'Shipped!' },
434
+ * });
435
+ *
436
+ * if (!res.success) {
437
+ * console.error('X rejected the post', res.status, res.data);
438
+ * }
439
+ * ```
440
+ *
441
+ * @example
442
+ * ```typescript
443
+ * // Read, with query parameters and a look at what the call cost
444
+ * const res = await base44.asServiceRole.connectors.callApi('x', {
445
+ * path: '/2/tweets/search/recent',
446
+ * query: { query: 'base44', max_results: 10 },
447
+ * });
448
+ *
449
+ * console.log(`${res.creditsCharged} credits`, res.data);
450
+ * ```
451
+ */
452
+ callApi<T = unknown>(integrationType: ConnectorIntegrationType, request: ConnectorApiRequest): Promise<ConnectorApiResponse<T>>;
331
453
  }
332
454
  /**
333
455
  * User-scoped connectors module for managing app user OAuth connections.
@@ -132,10 +132,8 @@ export function createAxiosClient({ baseURL, headers = {}, token, interceptRespo
132
132
  client.interceptors.request.use((config) => {
133
133
  // `window.location` is absent on React Native (where `window` still exists),
134
134
  // so guard on it before reading `.href`.
135
- if (typeof window !== "undefined") {
136
- if (window.location) {
137
- config.headers.set("X-Origin-URL", window.location.href);
138
- }
135
+ if (typeof window !== "undefined" && window.location) {
136
+ config.headers.set("X-Origin-URL", window.location.href);
139
137
  // On unauthenticated requests, attach a stable anonymous visitor id so the
140
138
  // backend can support anonymous agent access (conversation grouping + ownership).
141
139
  // Authenticated requests are identified by their Authorization header instead.
@@ -187,11 +185,11 @@ export function createAxiosClient({ baseURL, headers = {}, token, interceptRespo
187
185
  }
188
186
  return response.data;
189
187
  }, (error) => {
190
- var _a, _b, _c, _d, _e, _f, _g, _h;
188
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
191
189
  const message = ((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.message) ||
192
190
  ((_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.detail) ||
193
191
  error.message;
194
- const base44Error = new Base44Error(message, (_e = error.response) === null || _e === void 0 ? void 0 : _e.status, (_g = (_f = error.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.code, (_h = error.response) === null || _h === void 0 ? void 0 : _h.data, error);
192
+ const base44Error = new Base44Error(message, (_e = error.response) === null || _e === void 0 ? void 0 : _e.status, (_m = (_h = (_g = (_f = error.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.code) !== null && _h !== void 0 ? _h : (_l = (_k = (_j = error.response) === null || _j === void 0 ? void 0 : _j.headers) === null || _k === void 0 ? void 0 : _k.get) === null || _l === void 0 ? void 0 : _l.call(_k, "x-base44-connector-error")) !== null && _m !== void 0 ? _m : (_p = (_o = error.response) === null || _o === void 0 ? void 0 : _o.headers) === null || _p === void 0 ? void 0 : _p["x-base44-connector-error"], (_q = error.response) === null || _q === void 0 ? void 0 : _q.data, error);
195
193
  // Log errors in development
196
194
  if (process.env.NODE_ENV !== "production") {
197
195
  safeErrorLog("[Base44 SDK Error]", base44Error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.43-pr.260.38a957a",
3
+ "version": "0.8.43-pr.261.f8cbcf8",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",