@base44-preview/sdk 0.8.48-pr.280.dac0f98 → 0.8.48-pr.282.1b5a2bd

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 (36) hide show
  1. package/dist/client.js +68 -70
  2. package/dist/client.types.d.ts +5 -14
  3. package/dist/index.d.ts +0 -3
  4. package/dist/index.js +0 -1
  5. package/dist/modules/agents.d.ts +1 -1
  6. package/dist/modules/agents.js +3 -4
  7. package/dist/modules/agents.types.d.ts +2 -2
  8. package/dist/modules/ai-gateway.d.ts +1 -1
  9. package/dist/modules/ai-gateway.js +2 -3
  10. package/dist/modules/ai-gateway.types.d.ts +2 -2
  11. package/dist/modules/analytics.d.ts +4 -29
  12. package/dist/modules/analytics.js +82 -107
  13. package/dist/modules/auth.js +20 -38
  14. package/dist/modules/auth.types.d.ts +26 -13
  15. package/dist/utils/auth-utils.d.ts +2 -0
  16. package/dist/utils/auth-utils.js +11 -0
  17. package/dist/utils/embed-session.d.ts +50 -0
  18. package/dist/utils/embed-session.js +140 -0
  19. package/dist/utils/fetch-with-auth.js +0 -6
  20. package/dist/utils/socket-utils.d.ts +3 -1
  21. package/dist/utils/socket-utils.js +1 -2
  22. package/package.json +1 -1
  23. package/dist/modules/experiment-exposures.d.ts +0 -19
  24. package/dist/modules/experiment-exposures.js +0 -65
  25. package/dist/modules/experiments-config.types.d.ts +0 -39
  26. package/dist/modules/experiments-config.types.js +0 -1
  27. package/dist/modules/experiments-context.d.ts +0 -10
  28. package/dist/modules/experiments-context.js +0 -44
  29. package/dist/modules/experiments-evaluator.d.ts +0 -11
  30. package/dist/modules/experiments-evaluator.js +0 -45
  31. package/dist/modules/experiments-runtime.types.d.ts +0 -19
  32. package/dist/modules/experiments-runtime.types.js +0 -7
  33. package/dist/modules/experiments.d.ts +0 -16
  34. package/dist/modules/experiments.js +0 -134
  35. package/dist/modules/experiments.types.d.ts +0 -106
  36. package/dist/modules/experiments.types.js +0 -1
@@ -1,6 +1,5 @@
1
1
  import { getSharedInstance } from "../utils/sharedInstance.js";
2
2
  import { generateUuid, isReactNative } from "../utils/common.js";
3
- import { getExperimentsRuntime } from "./experiments-runtime.types.js";
4
3
  export const USER_HEARTBEAT_EVENT_NAME = "__user_heartbeat_event__";
5
4
  export const ANALYTICS_INITIALIZATION_EVENT_NAME = "__initialization_event__";
6
5
  export const ANALYTICS_SESSION_DURATION_EVENT_NAME = "__session_duration_event__";
@@ -18,41 +17,31 @@ const defaultConfiguration = {
18
17
  //// shared queue for analytics events ////
19
18
  ///////////////////////////////////////////////
20
19
  const ANALYTICS_SHARED_STATE_NAME = "analytics";
21
- function createAnalyticsState() {
22
- return {
23
- requestsQueue: [],
24
- isProcessing: false,
25
- isHeartBeatProcessing: false,
26
- wasInitializationTracked: false,
27
- sessionContext: null,
28
- sessionContextPromise: null,
29
- sessionStartTime: null,
30
- // Memoized session id for when `localStorage` can't persist one — see
31
- // getAnalyticsSessionId.
32
- fallbackSessionId: null,
33
- config: {
34
- ...defaultConfiguration,
35
- ...getAnalyticsConfigFromUrlParams(),
36
- },
37
- };
38
- }
39
- const analyticsSharedState = getSharedInstance(ANALYTICS_SHARED_STATE_NAME, createAnalyticsState);
40
- const serverAnalyticsStates = new WeakMap();
41
- /** @internal */
42
- export function isAnalyticsEnabled(enabled, state = analyticsSharedState) {
43
- return enabled && state.config.enabled && !isReactNative;
44
- }
45
- export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthModule, enabled, getVisitorId, experimentsContext, }) => {
46
- const state = typeof window === "undefined" ? createAnalyticsState() : analyticsSharedState;
47
- if (typeof window === "undefined")
48
- serverAnalyticsStates.set(axiosClient, state);
20
+ // shared state//
21
+ const analyticsSharedState = getSharedInstance(ANALYTICS_SHARED_STATE_NAME, () => ({
22
+ requestsQueue: [],
23
+ isProcessing: false,
24
+ isHeartBeatProcessing: false,
25
+ wasInitializationTracked: false,
26
+ sessionContext: null,
27
+ sessionStartTime: null,
28
+ // Memoized session id for when `localStorage` can't persist one — see
29
+ // getAnalyticsSessionId.
30
+ fallbackSessionId: null,
31
+ config: {
32
+ ...defaultConfiguration,
33
+ ...getAnalyticsConfigFromUrlParams(),
34
+ },
35
+ }));
36
+ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthModule, enabled, }) => {
37
+ var _a;
49
38
  // prevent overflow of events //
50
- const { maxQueueSize, throttleTime, batchSize } = state.config;
39
+ const { maxQueueSize, throttleTime, batchSize } = analyticsSharedState.config;
51
40
  // Disable analytics on React Native. It defines `window` but not `document`,
52
41
  // so the per-callsite `typeof window` guards below aren't enough to keep it
53
42
  // from touching `document` (e.g. `document.referrer` on init). Node/SSR is
54
43
  // still handled by those `window` guards, so this doesn't affect it.
55
- if (!isAnalyticsEnabled(enabled, state)) {
44
+ if (!enabled || !((_a = analyticsSharedState.config) === null || _a === void 0 ? void 0 : _a.enabled) || isReactNative) {
56
45
  return {
57
46
  track: () => { },
58
47
  cleanup: () => { },
@@ -81,17 +70,16 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
81
70
  }
82
71
  };
83
72
  const flush = async (eventsData, options = {}) => {
84
- var _a;
85
73
  if (eventsData.length === 0)
86
74
  return;
87
- const sessionContext_ = await getSessionContext(userAuthModule, state);
88
- const events = eventsData.map(transformEventDataToApiRequestData({ ...sessionContext_, session_id: (_a = getVisitorId === null || getVisitorId === void 0 ? void 0 : getVisitorId()) !== null && _a !== void 0 ? _a : sessionContext_.session_id }));
75
+ const sessionContext_ = await getSessionContext(userAuthModule);
76
+ const events = eventsData.map(transformEventDataToApiRequestData(sessionContext_));
89
77
  try {
90
78
  if (!options.isBeacon || !beaconRequest(events)) {
91
79
  await batchRequestFallback(events);
92
80
  }
93
81
  }
94
- catch (_b) {
82
+ catch (_a) {
95
83
  // do nothing
96
84
  }
97
85
  };
@@ -99,25 +87,16 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
99
87
  startAnalyticsProcessor(flush, {
100
88
  throttleTime,
101
89
  batchSize,
102
- }, state);
90
+ });
103
91
  };
104
92
  const track = (params) => {
105
- var _a;
106
- if (state.requestsQueue.length >= maxQueueSize) {
93
+ if (analyticsSharedState.requestsQueue.length >= maxQueueSize) {
107
94
  return;
108
95
  }
109
96
  const intrinsicData = getEventIntrinsicData();
110
- const preview = Object.fromEntries(Object.entries((_a = experimentsContext === null || experimentsContext === void 0 ? void 0 : experimentsContext.preview) !== null && _a !== void 0 ? _a : {}).filter(([, value]) => typeof value === "boolean"));
111
- const properties = { ...params.properties };
112
- delete properties.__b44_experiment_preview;
113
- if (Object.keys(preview).length) {
114
- // Capture now: a queued event must retain its occurrence-time preview.
115
- properties.__b44_experiment_preview = JSON.stringify(preview);
116
- }
117
- state.requestsQueue.push({
97
+ analyticsSharedState.requestsQueue.push({
118
98
  ...params,
119
99
  ...intrinsicData,
120
- properties: params.properties || Object.keys(properties).length ? properties : undefined,
121
100
  });
122
101
  startProcessing();
123
102
  };
@@ -125,16 +104,16 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
125
104
  startAnalyticsProcessor(flush, {
126
105
  throttleTime,
127
106
  batchSize,
128
- }, state);
129
- clearHeartBeatProcessor = startHeartBeatProcessor(track, state);
130
- setSessionDurationTimerStart(state);
107
+ });
108
+ clearHeartBeatProcessor = startHeartBeatProcessor(track);
109
+ setSessionDurationTimerStart();
131
110
  };
132
111
  const onDocHidden = () => {
133
- stopAnalyticsProcessor(state);
112
+ stopAnalyticsProcessor();
134
113
  clearHeartBeatProcessor === null || clearHeartBeatProcessor === void 0 ? void 0 : clearHeartBeatProcessor();
135
- trackSessionDurationEvent(track, state);
114
+ trackSessionDurationEvent(track);
136
115
  // flush entire queue on visibility change and hope for the best //
137
- const eventsData = state.requestsQueue.splice(0);
116
+ const eventsData = analyticsSharedState.requestsQueue.splice(0);
138
117
  flush(eventsData, { isBeacon: true });
139
118
  };
140
119
  const onVisibilityChange = () => {
@@ -148,7 +127,7 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
148
127
  }
149
128
  };
150
129
  const cleanup = () => {
151
- stopAnalyticsProcessor(state);
130
+ stopAnalyticsProcessor();
152
131
  clearHeartBeatProcessor === null || clearHeartBeatProcessor === void 0 ? void 0 : clearHeartBeatProcessor();
153
132
  if (typeof window !== "undefined") {
154
133
  window.removeEventListener("visibilitychange", onVisibilityChange);
@@ -157,9 +136,9 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
157
136
  // start the flusing process ///
158
137
  startProcessing();
159
138
  // start the heart beat processor //
160
- clearHeartBeatProcessor = startHeartBeatProcessor(track, state);
139
+ clearHeartBeatProcessor = startHeartBeatProcessor(track);
161
140
  // track the referrer event //
162
- trackInitializationEvent(track, state);
141
+ trackInitializationEvent(track);
163
142
  // start the visibility change listener //
164
143
  if (typeof window !== "undefined") {
165
144
  window.addEventListener("visibilitychange", onVisibilityChange);
@@ -169,50 +148,50 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
169
148
  cleanup,
170
149
  };
171
150
  };
172
- function stopAnalyticsProcessor(state) {
173
- state.isProcessing = false;
151
+ function stopAnalyticsProcessor() {
152
+ analyticsSharedState.isProcessing = false;
174
153
  }
175
- async function startAnalyticsProcessor(handleTrack, options, state) {
176
- if (state.isProcessing) {
154
+ async function startAnalyticsProcessor(handleTrack, options) {
155
+ if (analyticsSharedState.isProcessing) {
177
156
  // only one instance of the analytics processor can be running at a time //
178
157
  return;
179
158
  }
180
- state.isProcessing = true;
159
+ analyticsSharedState.isProcessing = true;
181
160
  const { throttleTime = 1000, batchSize = 30 } = options !== null && options !== void 0 ? options : {};
182
- while (state.isProcessing &&
183
- state.requestsQueue.length > 0) {
184
- const requests = state.requestsQueue.splice(0, batchSize);
161
+ while (analyticsSharedState.isProcessing &&
162
+ analyticsSharedState.requestsQueue.length > 0) {
163
+ const requests = analyticsSharedState.requestsQueue.splice(0, batchSize);
185
164
  requests.length && (await handleTrack(requests));
186
165
  await new Promise((resolve) => setTimeout(resolve, throttleTime));
187
166
  }
188
- state.isProcessing = false;
167
+ analyticsSharedState.isProcessing = false;
189
168
  }
190
- function startHeartBeatProcessor(track, state) {
169
+ function startHeartBeatProcessor(track) {
191
170
  var _a;
192
171
  // Browser-only, like the other automatic events here (initialization, session
193
172
  // duration, visibility). Outside a browser this timer fired a `me()` every
194
173
  // interval for the lifetime of a long-lived server-side client, and kept the
195
174
  // Node event loop alive. Explicit `analytics.track()` calls still work.
196
175
  if (typeof window === "undefined" ||
197
- state.isHeartBeatProcessing ||
198
- ((_a = state.config.heartBeatInterval) !== null && _a !== void 0 ? _a : 0) < 10) {
176
+ analyticsSharedState.isHeartBeatProcessing ||
177
+ ((_a = analyticsSharedState.config.heartBeatInterval) !== null && _a !== void 0 ? _a : 0) < 10) {
199
178
  return () => { };
200
179
  }
201
- state.isHeartBeatProcessing = true;
180
+ analyticsSharedState.isHeartBeatProcessing = true;
202
181
  const interval = setInterval(() => {
203
182
  track({ eventName: USER_HEARTBEAT_EVENT_NAME });
204
- }, state.config.heartBeatInterval);
183
+ }, analyticsSharedState.config.heartBeatInterval);
205
184
  return () => {
206
185
  clearInterval(interval);
207
- state.isHeartBeatProcessing = false;
186
+ analyticsSharedState.isHeartBeatProcessing = false;
208
187
  };
209
188
  }
210
- function trackInitializationEvent(track, state) {
189
+ function trackInitializationEvent(track) {
211
190
  if (typeof window === "undefined" ||
212
- state.wasInitializationTracked) {
191
+ analyticsSharedState.wasInitializationTracked) {
213
192
  return;
214
193
  }
215
- state.wasInitializationTracked = true;
194
+ analyticsSharedState.wasInitializationTracked = true;
216
195
  track({
217
196
  eventName: ANALYTICS_INITIALIZATION_EVENT_NAME,
218
197
  properties: {
@@ -220,20 +199,20 @@ function trackInitializationEvent(track, state) {
220
199
  },
221
200
  });
222
201
  }
223
- function setSessionDurationTimerStart(state) {
202
+ function setSessionDurationTimerStart() {
224
203
  if (typeof window === "undefined" ||
225
- state.sessionStartTime !== null) {
204
+ analyticsSharedState.sessionStartTime !== null) {
226
205
  return;
227
206
  }
228
- state.sessionStartTime = new Date().toISOString();
207
+ analyticsSharedState.sessionStartTime = new Date().toISOString();
229
208
  }
230
- function trackSessionDurationEvent(track, state) {
209
+ function trackSessionDurationEvent(track) {
231
210
  if (typeof window === "undefined" ||
232
- state.sessionStartTime === null)
211
+ analyticsSharedState.sessionStartTime === null)
233
212
  return;
234
213
  const sessionDuration = new Date().getTime() -
235
- new Date(state.sessionStartTime).getTime();
236
- state.sessionStartTime = null;
214
+ new Date(analyticsSharedState.sessionStartTime).getTime();
215
+ analyticsSharedState.sessionStartTime = null;
237
216
  track({
238
217
  eventName: ANALYTICS_SESSION_DURATION_EVENT_NAME,
239
218
  properties: { sessionDuration },
@@ -256,6 +235,7 @@ function transformEventDataToApiRequestData(sessionContext) {
256
235
  ...sessionContext,
257
236
  });
258
237
  }
238
+ let sessionContextPromise = null;
259
239
  /**
260
240
  * Clears the memoized analytics session context.
261
241
  *
@@ -266,24 +246,22 @@ function transformEventDataToApiRequestData(sessionContext) {
266
246
  *
267
247
  * @internal
268
248
  */
269
- export function resetAnalyticsSessionContext(axiosClient) {
270
- var _a;
271
- const state = axiosClient ? (_a = serverAnalyticsStates.get(axiosClient)) !== null && _a !== void 0 ? _a : analyticsSharedState : analyticsSharedState;
272
- state.sessionContext = null;
273
- state.sessionContextPromise = null;
249
+ export function resetAnalyticsSessionContext() {
250
+ analyticsSharedState.sessionContext = null;
251
+ sessionContextPromise = null;
274
252
  }
275
- async function getSessionContext(userAuthModule, state) {
276
- if (!state.sessionContext) {
253
+ async function getSessionContext(userAuthModule) {
254
+ if (!analyticsSharedState.sessionContext) {
277
255
  // With no token there is no identity to resolve: `me()` can only answer 401,
278
256
  // which the browser logs to the console before any handler here sees it. On
279
257
  // a public page that request is the sole reason an error appears, so skip
280
258
  // it. This is not memoized — a visitor who logs in later must still resolve.
281
259
  if (!userAuthModule.hasToken()) {
282
- return { user_id: null, session_id: getAnalyticsSessionId(state) };
260
+ return { user_id: null, session_id: getAnalyticsSessionId() };
283
261
  }
284
- if (!state.sessionContextPromise) {
285
- const sessionId = getAnalyticsSessionId(state);
286
- state.sessionContextPromise = userAuthModule
262
+ if (!sessionContextPromise) {
263
+ const sessionId = getAnalyticsSessionId();
264
+ sessionContextPromise = userAuthModule
287
265
  .me()
288
266
  .then((user) => ({
289
267
  user_id: user.id,
@@ -294,7 +272,7 @@ async function getSessionContext(userAuthModule, state) {
294
272
  session_id: sessionId,
295
273
  }));
296
274
  }
297
- const pending = state.sessionContextPromise;
275
+ const pending = sessionContextPromise;
298
276
  const context = await pending;
299
277
  // Publish only if this lookup is still the current one. A reset that lands
300
278
  // while the request is in flight nulls `sessionContextPromise`, and an
@@ -302,12 +280,12 @@ async function getSessionContext(userAuthModule, state) {
302
280
  // for the rest of the session. The awaited value is still returned: these
303
281
  // events were queued before the identity changed, so that is who they
304
282
  // belong to.
305
- if (state.sessionContextPromise === pending) {
306
- state.sessionContext = context;
283
+ if (sessionContextPromise === pending) {
284
+ analyticsSharedState.sessionContext = context;
307
285
  }
308
286
  return context;
309
287
  }
310
- return state.sessionContext;
288
+ return analyticsSharedState.sessionContext;
311
289
  }
312
290
  export function getAnalyticsConfigFromUrlParams() {
313
291
  // `window.location` is absent on React Native. This runs at module load (via
@@ -329,18 +307,15 @@ export function getAnalyticsConfigFromUrlParams() {
329
307
  // return the config object //
330
308
  return { enabled: analyticsEnable === "true" };
331
309
  }
332
- // Without persistent storage, keep the id stable within this analytics state.
333
- function getFallbackSessionId(state) {
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() {
334
313
  var _a;
335
- return ((_a = state.fallbackSessionId) !== null && _a !== void 0 ? _a : (state.fallbackSessionId = generateUuid()));
314
+ return ((_a = analyticsSharedState.fallbackSessionId) !== null && _a !== void 0 ? _a : (analyticsSharedState.fallbackSessionId = generateUuid()));
336
315
  }
337
- export function getAnalyticsSessionId(state = analyticsSharedState) {
338
- var _a;
339
- const visitorId = (_a = getExperimentsRuntime()) === null || _a === void 0 ? void 0 : _a.visitorId;
340
- if (visitorId && visitorId !== "anon")
341
- return visitorId;
316
+ export function getAnalyticsSessionId() {
342
317
  if (typeof window === "undefined") {
343
- return getFallbackSessionId(state);
318
+ return getFallbackSessionId();
344
319
  }
345
320
  try {
346
321
  const sessionId = localStorage.getItem(ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY);
@@ -351,7 +326,7 @@ export function getAnalyticsSessionId(state = analyticsSharedState) {
351
326
  }
352
327
  return sessionId;
353
328
  }
354
- catch (_b) {
355
- return getFallbackSessionId(state);
329
+ catch (_a) {
330
+ return getFallbackSessionId();
356
331
  }
357
332
  }
@@ -1,4 +1,5 @@
1
1
  import { resetAnalyticsSessionContext } from "./analytics.js";
2
+ import { showEmbedSessionEnded } from "../utils/embed-session.js";
2
3
  function isInsideIframe() {
3
4
  if (typeof window === "undefined")
4
5
  return false;
@@ -75,47 +76,26 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
75
76
  // requests would leave the app rendering a stale identity after logout or a
76
77
  // session swap.
77
78
  let pendingMe = null;
78
- let identityGeneration = 0;
79
79
  const clearPendingMe = () => {
80
- identityGeneration += 1;
81
80
  pendingMe = null;
82
81
  };
83
82
  // Tracked here rather than read off `axios.defaults` so the answer stays tied
84
83
  // to the identity transitions below (`setToken`, `logout`) instead of to the
85
84
  // header a caller may have set on the instance directly.
86
- let hasAccessToken = Boolean(options.token);
87
- const notifyAuthState = (state) => {
88
- var _a;
89
- try {
90
- (_a = options.onAuthStateChange) === null || _a === void 0 ? void 0 : _a.call(options, state);
91
- }
92
- catch (_b) {
93
- // Optional observers must not interrupt authentication or logout redirects.
94
- }
95
- };
85
+ let accessToken = options.token || null;
96
86
  return {
97
87
  hasToken() {
98
- return hasAccessToken;
88
+ return accessToken !== null;
89
+ },
90
+ getToken() {
91
+ return accessToken;
92
+ },
93
+ isEmbedded() {
94
+ return Boolean(options.embedded);
99
95
  },
100
96
  // Get current user information
101
97
  async me() {
102
- const generation = identityGeneration;
103
- const request = pendingMe !== null && pendingMe !== void 0 ? pendingMe : axios.get(`/apps/${appId}/entities/User/me`).then((user) => {
104
- if (generation === identityGeneration) {
105
- notifyAuthState({ status: "authenticated", userId: user.id });
106
- }
107
- return user;
108
- }, (error) => {
109
- var _a, _b;
110
- if (generation === identityGeneration) {
111
- const authError = error;
112
- const status = (_a = authError === null || authError === void 0 ? void 0 : authError.status) !== null && _a !== void 0 ? _a : (_b = authError === null || authError === void 0 ? void 0 : authError.response) === null || _b === void 0 ? void 0 : _b.status;
113
- notifyAuthState({
114
- status: status === 401 || status === 403 ? "anonymous" : "error",
115
- });
116
- }
117
- throw error;
118
- }).finally(() => {
98
+ const request = pendingMe !== null && pendingMe !== void 0 ? pendingMe : axios.get(`/apps/${appId}/entities/User/me`).finally(() => {
119
99
  // Only retire this request if it is still the shared one. An identity
120
100
  // change mid-flight clears `pendingMe` and the next caller starts a
121
101
  // fresh request; an unconditional clear here would retire that newer
@@ -136,6 +116,12 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
136
116
  if (typeof window === "undefined") {
137
117
  throw new Error("Login method can only be used in a browser environment");
138
118
  }
119
+ // An embedded session can only be renewed by the host platform; the
120
+ // login round trip cannot complete inside its frame.
121
+ if (options.embedded) {
122
+ showEmbedSessionEnded();
123
+ return;
124
+ }
139
125
  // If nextUrl is not provided, use the current URL
140
126
  const redirectUrl = nextUrl
141
127
  ? new URL(nextUrl, window.location.origin).toString()
@@ -177,9 +163,8 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
177
163
  // Drop identity resolved under the previous session: a `me()` already in
178
164
  // flight would otherwise resolve into callers that run after the logout.
179
165
  clearPendingMe();
180
- resetAnalyticsSessionContext(axios);
181
- hasAccessToken = false;
182
- notifyAuthState({ status: "anonymous" });
166
+ resetAnalyticsSessionContext();
167
+ accessToken = null;
183
168
  // Only do the rest if in a browser environment
184
169
  if (typeof window !== "undefined") {
185
170
  // Remove token from localStorage
@@ -207,12 +192,11 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
207
192
  // Same reasoning as in `logout`: the identity changes here, so anything
208
193
  // resolved for the previous one must not be handed to later callers.
209
194
  clearPendingMe();
210
- resetAnalyticsSessionContext(axios);
211
- hasAccessToken = true;
195
+ resetAnalyticsSessionContext();
196
+ accessToken = token;
212
197
  // handle token change for axios clients
213
198
  axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
214
199
  functionsAxiosClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
215
- notifyAuthState({ status: "pending" });
216
200
  // Save token to localStorage if requested
217
201
  if (saveToStorage &&
218
202
  typeof window !== "undefined" &&
@@ -239,8 +223,6 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
239
223
  const { access_token, user } = response;
240
224
  if (access_token) {
241
225
  this.setToken(access_token);
242
- if (typeof (user === null || user === void 0 ? void 0 : user.id) === "string")
243
- notifyAuthState({ status: "authenticated", userId: user.id });
244
226
  }
245
227
  return {
246
228
  access_token,
@@ -84,17 +84,6 @@ export interface ResetPasswordParams {
84
84
  /** New password to set. */
85
85
  newPassword: string;
86
86
  }
87
- /** @internal */
88
- export type AuthState = {
89
- status: "pending";
90
- } | {
91
- status: "anonymous";
92
- } | {
93
- status: "authenticated";
94
- userId: string;
95
- } | {
96
- status: "error";
97
- };
98
87
  /**
99
88
  * Configuration options for the auth module.
100
89
  */
@@ -109,8 +98,11 @@ export interface AuthModuleOptions {
109
98
  * which is how the server-side SDK reports a token it never sets explicitly.
110
99
  */
111
100
  token?: string;
112
- /** @internal */
113
- onAuthStateChange?: (state: AuthState) => void;
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
+ */
105
+ embedded?: boolean;
114
106
  }
115
107
  /**
116
108
  * Authentication module for managing user authentication and authorization. The module automatically stores tokens in local storage when available and manages authorization headers for API requests.
@@ -192,6 +184,22 @@ export interface AuthModule {
192
184
  * ```
193
185
  */
194
186
  redirectToLogin(nextUrl: string): void;
187
+ /**
188
+ * Whether the app is running embedded in a host platform.
189
+ *
190
+ * 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()} shows 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.
191
+ *
192
+ * @returns `true` when the app was embedded by a host platform, `false` otherwise.
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * // Show your own message instead of a login screen
197
+ * if (!user && base44.auth.isEmbedded()) {
198
+ * return <SessionEnded />;
199
+ * }
200
+ * ```
201
+ */
202
+ isEmbedded(): boolean;
195
203
  /**
196
204
  * Redirects the user to a third-party authentication provider's login page.
197
205
  *
@@ -552,4 +560,9 @@ export interface InternalAuthModule extends AuthModule {
552
560
  * could not succeed without a session, not to decide that one is valid.
553
561
  */
554
562
  hasToken(): boolean;
563
+ /**
564
+ * The access token currently set on the client, or `null` when there is none.
565
+ * Follows {@linkcode AuthModule.setToken | setToken} and {@linkcode AuthModule.logout | logout}.
566
+ */
567
+ getToken(): string | null;
555
568
  }
@@ -5,6 +5,8 @@ import { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions
5
5
  * Low-level utility for manually retrieving tokens. In most cases, the Base44 client handles
6
6
  * token management automatically. This function is useful for custom authentication flows or when you need direct access to stored tokens. Requires a browser environment and can't be used in the backend.
7
7
  *
8
+ * When a host platform has embedded the app with a one-time token (`?ott=`), that token is returned as it stands: it is what {@linkcode createClient} trades for the session, so a page that gates on "is there a token?" as it loads sees one. It is neither stored nor removed from the URL here.
9
+ *
8
10
  * @internal
9
11
  *
10
12
  * @param options - Configuration options for token retrieval.
@@ -1,9 +1,12 @@
1
+ import { EMBED_TOKEN_PARAM } from "./embed-session.js";
1
2
  /**
2
3
  * Retrieves an access token from URL parameters or local storage.
3
4
  *
4
5
  * Low-level utility for manually retrieving tokens. In most cases, the Base44 client handles
5
6
  * token management automatically. This function is useful for custom authentication flows or when you need direct access to stored tokens. Requires a browser environment and can't be used in the backend.
6
7
  *
8
+ * When a host platform has embedded the app with a one-time token (`?ott=`), that token is returned as it stands: it is what {@linkcode createClient} trades for the session, so a page that gates on "is there a token?" as it loads sees one. It is neither stored nor removed from the URL here.
9
+ *
7
10
  * @internal
8
11
  *
9
12
  * @param options - Configuration options for token retrieval.
@@ -56,6 +59,14 @@ export function getAccessToken(options = {}) {
56
59
  }
57
60
  return token;
58
61
  }
62
+ // A platform-embedded load carries a one-time token instead. It is not a
63
+ // session yet — createClient takes it off the URL and exchanges it — but
64
+ // it is the identity this load arrives with, and callers that read this
65
+ // once as the page loads must not conclude there is none.
66
+ const embedToken = urlParams.get(EMBED_TOKEN_PARAM);
67
+ if (embedToken) {
68
+ return embedToken;
69
+ }
59
70
  }
60
71
  catch (e) {
61
72
  console.error("Error retrieving token from URL:", e);
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Sessions for apps embedded in a host platform.
3
+ *
4
+ * The platform's server mints a one-time token for one of its users and puts
5
+ * it on the iframe URL as `?ott=`. The client takes it off the URL as it is
6
+ * created, trades it for an app-user session through the OAuth token-exchange
7
+ * grant (RFC 8693), and keeps the result in memory only — never in storage — so
8
+ * the session lives and dies with the frame.
9
+ *
10
+ * @internal
11
+ */
12
+ /** The query parameter a host platform puts the one-time token on. @internal */
13
+ export declare const EMBED_TOKEN_PARAM = "ott";
14
+ /**
15
+ * Reads the one-time token off the current URL and strips it, so it is never
16
+ * left in the address bar, in history, or in a shared link.
17
+ *
18
+ * @internal
19
+ */
20
+ export declare function takeEmbedTokenFromUrl(): string | null;
21
+ /**
22
+ * Whether this tab previously redeemed an embed token. Counts only inside a
23
+ * frame: a top-level tab that once carried a token must fall back to the
24
+ * regular login, or it could never sign in again.
25
+ *
26
+ * @internal
27
+ */
28
+ export declare function isEmbeddedTab(): boolean;
29
+ /** @internal */
30
+ export declare function markEmbeddedTab(): void;
31
+ /**
32
+ * Trades a one-time embed token for an app-user session token. Resolves to
33
+ * `null` when the platform refuses the token; never throws.
34
+ *
35
+ * @internal
36
+ */
37
+ export declare function exchangeEmbedToken({ serverUrl, appId, ott, fetchImpl, }: {
38
+ serverUrl: string;
39
+ appId: string;
40
+ ott: string;
41
+ fetchImpl?: typeof fetch;
42
+ }): Promise<string | null>;
43
+ /**
44
+ * Covers the page with a plain "session ended" notice. An embedded session can
45
+ * only be renewed by the host platform (by reloading its own page), so this
46
+ * stands in for the login redirect, which cannot complete inside a frame.
47
+ *
48
+ * @internal
49
+ */
50
+ export declare function showEmbedSessionEnded(): void;