@base44-preview/sdk 0.8.48-pr.282.6ea0687 → 0.8.48-pr.282.7b5ff6d

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
@@ -5,7 +5,7 @@ import { createAuthModule } from "./modules/auth.js";
5
5
  import { createSsoModule } from "./modules/sso.js";
6
6
  import { createConnectorsModule, createUserConnectorsModule, } from "./modules/connectors.js";
7
7
  import { getAccessToken } from "./utils/auth-utils.js";
8
- import { exchangeEmbedToken, takeEmbedTokenFromUrl, } from "./utils/embed-session.js";
8
+ import { exchangeEmbedToken, frameSession, takeEmbedTokenFromUrl, } from "./utils/embed-session.js";
9
9
  import { createFetchWithAuth } from "./utils/fetch-with-auth.js";
10
10
  import { createFunctionsModule } from "./modules/functions.js";
11
11
  import { createAgentsModule } from "./modules/agents.js";
@@ -59,7 +59,9 @@ export function createClient(config) {
59
59
  // Normalize appBaseUrl to always be a string (empty if not provided or invalid)
60
60
  const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";
61
61
  const embedOtt = takeEmbedTokenFromUrl();
62
- // A declaration, not a const: this block sits above the auth module.
62
+ // Asked again on every use, so a session that arrives later — from the
63
+ // exchange, or from a login — reaches the socket and every other module.
64
+ // A declaration, not a const, so this block can stay above the auth module.
63
65
  function getToken() {
64
66
  var _a;
65
67
  return (_a = userAuthModule.getToken()) !== null && _a !== void 0 ? _a : (embedOtt ? null : getAccessToken());
@@ -80,8 +82,7 @@ export function createClient(config) {
80
82
  }
81
83
  return socket;
82
84
  };
83
- // Apps pass getAccessToken() in as `token`, which in a frame is the OTT —
84
- // what the exchange trades for a session, never a bearer itself.
85
+ // In a frame the caller's token is the OTT itself, which is not a session.
85
86
  const token = embedOtt ? undefined : config.token;
86
87
  const headers = {
87
88
  ...optionalHeaders,
@@ -136,26 +137,32 @@ export function createClient(config) {
136
137
  serverUrl,
137
138
  token,
138
139
  embedded: Boolean(embedOtt),
139
- // The socket carries its token on the handshake, so it can only pick a
140
- // new one up by redialling — or, on logout, by dropping what it has.
140
+ // The socket carries its token on the handshake, so an identity change
141
+ // only reaches it by opening a new connection — or, on logout, by
142
+ // dropping the one still running as the user who just left.
141
143
  onSessionChange: (hasSession) => hasSession ? socket === null || socket === void 0 ? void 0 : socket.reconnect() : socket === null || socket === void 0 ? void 0 : socket.disconnect(),
142
144
  });
143
145
  // Apply the access token before any module that may issue authenticated
144
146
  // requests during construction (notably analytics, which fires an init
145
147
  // event whose flush calls auth.me()). Without this, the first User/me
146
148
  // request is built before setToken runs and goes out unauthenticated.
147
- // Not in a frame: a stored token there belongs to an earlier visitor.
149
+ // Not in a frame: a stored token there belongs to an earlier visitor, not to
150
+ // this session, which only the exchange below can produce.
148
151
  if (typeof window !== "undefined" && !embedOtt) {
149
152
  const accessToken = token || getAccessToken();
150
153
  if (accessToken) {
151
154
  userAuthModule.setToken(accessToken);
152
155
  }
153
156
  }
157
+ // The exchange belongs to the frame, not to one client: the token is off the
158
+ // URL after the first `createClient`, so a second one in the same document
159
+ // joins the session already being negotiated rather than going anonymous.
154
160
  const session = embedOtt
155
- ? exchangeEmbedToken({ serverUrl, appId, ott: embedOtt })
156
- : null;
157
- // Never rejects: every request waits on it, so one failure here must not
158
- // become a rejection on each of them.
161
+ ? frameSession(appId, () => exchangeEmbedToken({ serverUrl, appId, ott: embedOtt }))
162
+ : frameSession(appId);
163
+ // Settles once the exchanged session is applied (memory only); at once
164
+ // otherwise. Never rejects: every request waits on it, so a failure here
165
+ // must not turn into a rejection on each of them.
159
166
  const authReady = session
160
167
  ? session
161
168
  .then((sessionToken) => {
@@ -164,6 +171,8 @@ export function createClient(config) {
164
171
  userAuthModule.setToken(sessionToken, false);
165
172
  return;
166
173
  }
174
+ // The app is about to run anonymous. Say why, once, instead of
175
+ // leaving only the 401s that follow.
167
176
  const error = new Error("Base44: the embed token was refused, so this app is not signed in.");
168
177
  console.error(error.message);
169
178
  (_a = options === null || options === void 0 ? void 0 : options.onError) === null || _a === void 0 ? void 0 : _a.call(options, error);
@@ -173,8 +182,8 @@ export function createClient(config) {
173
182
  })
174
183
  : Promise.resolve();
175
184
  if (session) {
176
- // Registered after createAxiosClient's so it runs first (axios unshifts),
177
- // letting the anonymous-visitor header see the Authorization we just set.
185
+ // Requests issued during the exchange wait for it. Registered after createAxiosClient's
186
+ // interceptors so it runs first and the anonymous-visitor header sees the Authorization.
178
187
  for (const client of [axiosClient, functionsAxiosClient]) {
179
188
  client.interceptors.request.use(async (requestConfig) => {
180
189
  await authReady;
@@ -239,7 +248,8 @@ export function createClient(config) {
239
248
  getSocket,
240
249
  appId,
241
250
  serverUrl,
242
- // Sync, unlike everything else: these return a URL, not a promise.
251
+ // Read synchronously, unlike everything else: these build a URL rather
252
+ // than issue a request, so during the exchange they see no token.
243
253
  getToken,
244
254
  }),
245
255
  aiGateway: createAiGatewayModule({ serverUrl, getToken, appId }),
@@ -287,8 +297,9 @@ export function createClient(config) {
287
297
  getSocket,
288
298
  appId,
289
299
  serverUrl,
290
- // The user's token, deliberately: this is read only for the `?token=` on
291
- // a channel URL handed to that user. Never the service credential.
300
+ // The user's token, as on the user-scoped module: the only thing this is
301
+ // read for is the `?token=` on a channel URL handed to that user, which
302
+ // the app's service credential must never end up in.
292
303
  getToken,
293
304
  }),
294
305
  aiGateway: createAiGatewayModule({
@@ -11,9 +11,8 @@ interface ActorsConfig {
11
11
  appId: string;
12
12
  /** Current user access token, if authenticated. Rides the WS query on the
13
13
  * proxy-fallback path so the platform proxy can authenticate the connection;
14
- * anonymous connects omit it. Awaited per dial, so a session still being
15
- * exchanged is in hand before the URL is built. */
16
- getAuthToken(): Promise<string | null | undefined>;
14
+ * anonymous connects omit it. */
15
+ getAuthToken(): string | null | undefined | Promise<string | null | undefined>;
17
16
  /** Same semantics as function calls: editors with a non-prod version get the
18
17
  * draft actor script; everyone else gets the published one. */
19
18
  functionsVersion?: string;
@@ -161,7 +161,7 @@ export interface AgentsModuleConfig {
161
161
  /** Server URL */
162
162
  serverUrl?: string;
163
163
  /** Returns the current authentication token, if any */
164
- getToken: () => string | null;
164
+ getToken: () => string | null | undefined;
165
165
  }
166
166
  /**
167
167
  * Agents module for managing AI agent conversations.
@@ -360,9 +360,7 @@ export interface AgentsModule {
360
360
  * Gets WhatsApp connection URL for an agent.
361
361
  *
362
362
  * Generates a URL that users can use to connect with the agent through WhatsApp.
363
- * The URL includes authentication if a token is available. In an app a
364
- * platform has embedded, that is only once the session has been exchanged —
365
- * await a call such as `base44.auth.me()` before building the URL.
363
+ * The URL includes authentication if a token is available.
366
364
  *
367
365
  * @param agentName - The name of the agent.
368
366
  * @returns WhatsApp connection URL.
@@ -380,9 +378,7 @@ export interface AgentsModule {
380
378
  * Gets Telegram connection URL for an agent.
381
379
  *
382
380
  * Generates a URL that users can use to connect with the agent through Telegram.
383
- * The URL includes authentication if a token is available. In an app a
384
- * platform has embedded, that is only once the session has been exchanged —
385
- * await a call such as `base44.auth.me()` before building the URL. When the user opens
381
+ * The URL includes authentication if a token is available. When the user opens
386
382
  * this URL, they are redirected to the agent's Telegram bot with an activation
387
383
  * code that securely links their account.
388
384
  *
@@ -98,11 +98,16 @@ export interface AuthModuleOptions {
98
98
  * which is how the server-side SDK reports a token it never sets explicitly.
99
99
  */
100
100
  token?: string;
101
- /** Whether a host platform embedded this client in a frame. */
101
+ /**
102
+ * Whether this client runs embedded in a host platform's frame, where a
103
+ * session is minted by the platform and cannot be renewed by a login redirect.
104
+ */
102
105
  embedded?: boolean;
103
106
  /**
104
- * Called when the identity changes: `true` on `setToken`, `false` on
105
- * `logout`. Lets the client redial the socket, which holds its own copy.
107
+ * Called whenever the identity changes: `true` when a token is set, `false`
108
+ * on logout. Lets the client reach what holds its own copy of the identity —
109
+ * the realtime socket, which carries a token on the handshake and so has to
110
+ * open a new connection to pick one up, or drop the one it has.
106
111
  */
107
112
  onSessionChange?: (hasSession: boolean) => void;
108
113
  }
@@ -187,13 +192,13 @@ export interface AuthModule {
187
192
  */
188
193
  redirectToLogin(nextUrl: string): void;
189
194
  /**
190
- * Whether a host platform embedded this app and signed its user in.
195
+ * Whether the app is running embedded in a host platform.
191
196
  *
192
- * Only the platform can renew that session, so {@linkcode AuthModule.redirectToLogin | redirectToLogin()} and {@linkcode AuthModule.logout | logout()} show a "session ended" notice rather than a login page. Use this to render your own notice, or to hide sign-in controls that cannot work in the frame.
197
+ * A platform embeds an app in an iframe and signs its user in by minting a one-time token onto the frame's URL; the SDK trades it for a session as the client is created. That session is held in memory only and can be renewed only by the platform, so when it ends there is no login page to send the user to — {@linkcode AuthModule.redirectToLogin | redirectToLogin()} and {@linkcode AuthModule.logout | logout()} show a "session ended" notice instead. Use this to render your own notice or to hide sign-in and sign-out controls that cannot work inside the frame.
193
198
  *
194
- * The session lives in memory, so a reload inside the frame ends it and returns `false` here. Prefer client-side navigation.
199
+ * Because the session lives in memory, it does not survive a full page load inside the frame: routing within the app keeps it, while a reload or a real navigation ends it and the platform has to embed the app again — and this returns `false` on that load, since nothing about it says it was embedded. Prefer client-side navigation in an embedded app.
195
200
  *
196
- * @returns `true` when a host platform embedded this app.
201
+ * @returns `true` when the app was embedded by a host platform, `false` otherwise.
197
202
  *
198
203
  * @example
199
204
  * ```typescript
@@ -564,6 +569,9 @@ export interface InternalAuthModule extends AuthModule {
564
569
  * could not succeed without a session, not to decide that one is valid.
565
570
  */
566
571
  hasToken(): boolean;
567
- /** The token currently set on the client, or `null`. */
572
+ /**
573
+ * The access token currently set on the client, or `null` when there is none.
574
+ * Follows {@linkcode AuthModule.setToken | setToken} and {@linkcode AuthModule.logout | logout}.
575
+ */
568
576
  getToken(): string | null;
569
577
  }
@@ -9,9 +9,7 @@
9
9
  *
10
10
  * Taking the token off the URL is unconditional — a one-time token must not be
11
11
  * left in the address bar, in history, or in a shared link — but it is only
12
- * reported back inside a frame, the only place one is redeemed. It is gone once
13
- * the first client has taken it, so the session belongs to that client — an app
14
- * creates one.
12
+ * reported back inside a frame, the only place one is redeemed.
15
13
  *
16
14
  * The exchange endpoint is rate limited per app, and its limiter refuses before
17
15
  * the one-time token is redeemed — so a 429 leaves the token still valid and is
@@ -21,6 +19,8 @@
21
19
  */
22
20
  export declare const EMBED_TOKEN_PARAM = "ott";
23
21
  /** @internal */
22
+ export declare function frameSession(appId: string, start?: () => Promise<string | null>): Promise<string | null> | null;
23
+ /** @internal */
24
24
  export declare function takeEmbedTokenFromUrl(): string | null;
25
25
  /** @internal */
26
26
  export declare function isFramed(): boolean;
@@ -9,9 +9,7 @@
9
9
  *
10
10
  * Taking the token off the URL is unconditional — a one-time token must not be
11
11
  * left in the address bar, in history, or in a shared link — but it is only
12
- * reported back inside a frame, the only place one is redeemed. It is gone once
13
- * the first client has taken it, so the session belongs to that client — an app
14
- * creates one.
12
+ * reported back inside a frame, the only place one is redeemed.
15
13
  *
16
14
  * The exchange endpoint is rate limited per app, and its limiter refuses before
17
15
  * the one-time token is redeemed — so a 429 leaves the token still valid and is
@@ -26,6 +24,20 @@ const RATE_LIMITED = 429;
26
24
  const RATE_LIMIT_RETRY_MS = 1000;
27
25
  const EXCHANGE_TIMEOUT_MS = 15000;
28
26
  const SESSION_ENDED_ELEMENT_ID = "base44-embed-session-ended";
27
+ const FRAME_SESSIONS_KEY = "__base44EmbedSessions";
28
+ /** @internal */
29
+ export function frameSession(appId, start) {
30
+ var _a, _b;
31
+ var _c;
32
+ if (typeof window === "undefined") {
33
+ return start ? start() : null;
34
+ }
35
+ const sessions = ((_a = (_c = window)[FRAME_SESSIONS_KEY]) !== null && _a !== void 0 ? _a : (_c[FRAME_SESSIONS_KEY] = {}));
36
+ if (!sessions[appId] && start) {
37
+ sessions[appId] = start();
38
+ }
39
+ return (_b = sessions[appId]) !== null && _b !== void 0 ? _b : null;
40
+ }
29
41
  /** @internal */
30
42
  export function takeEmbedTokenFromUrl() {
31
43
  if (typeof window === "undefined" || !window.location) {
@@ -40,5 +40,6 @@ export declare function createFetchWithAuth({ axios, serviceRoleAxios, appId, se
40
40
  serverUrl: string;
41
41
  functionsVersion?: string;
42
42
  platformHeaders?: Record<string, string>;
43
+ /** Resolves once the client's session is settled. */
43
44
  waitForAuth?: () => Promise<void>;
44
45
  }): (path: string, init?: FetchWithAuthInit) => Promise<Response>;
@@ -4,6 +4,7 @@ export interface RoomsSocketConfig {
4
4
  mountPath: string;
5
5
  transports: string[];
6
6
  appId: string;
7
+ /** Asked on every connect, so the socket always carries the current session. */
7
8
  getToken: () => string | null;
8
9
  }
9
10
  export type TSocketRoom = string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.48-pr.282.6ea0687",
3
+ "version": "0.8.48-pr.282.7b5ff6d",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",