@base44-preview/sdk 0.8.6-pr.57.0298afb → 0.8.6-pr.57.2eea21a

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
@@ -124,6 +124,7 @@ export function createClient(config) {
124
124
  userAuthModule,
125
125
  }),
126
126
  cleanup: () => {
127
+ userModules.analytics.cleanup();
127
128
  if (socket) {
128
129
  socket.disconnect();
129
130
  }
@@ -6,6 +6,7 @@ import type { ConnectorsModule } from "./modules/connectors.types.js";
6
6
  import type { FunctionsModule } from "./modules/functions.types.js";
7
7
  import type { AgentsModule } from "./modules/agents.types.js";
8
8
  import type { AppLogsModule } from "./modules/app-logs.types.js";
9
+ import type { AnalyticsModule } from "./modules/analytics.types.js";
9
10
  /**
10
11
  * Options for creating a Base44 client.
11
12
  */
@@ -82,6 +83,8 @@ export interface Base44Client {
82
83
  agents: AgentsModule;
83
84
  /** {@link AppLogsModule | App logs module} for tracking app usage. */
84
85
  appLogs: AppLogsModule;
86
+ /** {@link AnalyticsModule | Analytics module} for tracking app usage. */
87
+ analytics: AnalyticsModule;
85
88
  /** Cleanup function to disconnect WebSocket connections. Call when you're done with the client. */
86
89
  cleanup: () => void;
87
90
  /**
@@ -1,6 +1,7 @@
1
1
  import { AxiosInstance } from "axios";
2
2
  import { TrackEventParams, AnalyticsModuleOptions } from "./analytics.types";
3
3
  import type { AuthModule } from "./auth.types";
4
+ export declare const USER_HEARTBEAT_EVENT_NAME = "__user_heartbeat_event__";
4
5
  export interface AnalyticsModuleArgs {
5
6
  axiosClient: AxiosInstance;
6
7
  serverUrl: string;
@@ -9,5 +10,6 @@ export interface AnalyticsModuleArgs {
9
10
  }
10
11
  export declare const createAnalyticsModule: ({ axiosClient, serverUrl, appId, userAuthModule, }: AnalyticsModuleArgs) => {
11
12
  track: (params: TrackEventParams) => void;
13
+ cleanup: () => void;
12
14
  };
13
- export declare function getAnalyticsModuleOptionsFromUrlParams(): AnalyticsModuleOptions | undefined;
15
+ export declare function getAnalyticsModuleOptionsFromLocalStorage(): AnalyticsModuleOptions | undefined;
@@ -1,4 +1,12 @@
1
- import { getSharedInstance, } from "../utils/singleton";
1
+ import { getSharedInstance } from "../utils/sharedInstance";
2
+ export const USER_HEARTBEAT_EVENT_NAME = "__user_heartbeat_event__";
3
+ const defaultConfiguration = {
4
+ enabled: true,
5
+ maxQueueSize: 1000,
6
+ throttleTime: 1000,
7
+ batchSize: 30,
8
+ heartBeatInterval: 60 * 1000,
9
+ };
2
10
  ///////////////////////////////////////////////
3
11
  //// shared queue for analytics events ////
4
12
  ///////////////////////////////////////////////
@@ -7,32 +15,18 @@ const ANALYTICS_SHARED_STATE_NAME = "analytics";
7
15
  const analyticsSharedState = getSharedInstance(ANALYTICS_SHARED_STATE_NAME, () => ({
8
16
  requestsQueue: [],
9
17
  isProcessing: false,
18
+ isHeartBeatProcessing: false,
19
+ sessionContext: null,
20
+ config: {
21
+ ...defaultConfiguration,
22
+ ...getAnalyticsModuleOptionsFromLocalStorage(),
23
+ },
10
24
  }));
11
25
  export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthModule, }) => {
12
- var _a;
13
26
  // prevent overflow of events //
14
- const { enabled = true, maxQueueSize = 1000, throttleTime = 1000, batchSize = 30, } = (_a = getAnalyticsModuleOptionsFromUrlParams()) !== null && _a !== void 0 ? _a : {};
27
+ const { enabled, maxQueueSize, throttleTime, batchSize } = analyticsSharedState.config;
28
+ let clearHeartBeatProcessor = undefined;
15
29
  const trackBatchUrl = `${serverUrl}/api/apps/${appId}/analytics/track/batch`;
16
- let sessionContext = null;
17
- const getSessionContext = async () => {
18
- if (sessionContext)
19
- return sessionContext;
20
- const user = await userAuthModule.me();
21
- sessionContext = {
22
- user_id: user.id,
23
- };
24
- return sessionContext;
25
- };
26
- const track = (params) => {
27
- if (!enabled || analyticsSharedState.requestsQueue.length >= maxQueueSize) {
28
- return;
29
- }
30
- const intrinsicData = getEventIntrinsicData();
31
- analyticsSharedState.requestsQueue.push({
32
- ...params,
33
- ...intrinsicData,
34
- });
35
- };
36
30
  const batchRequestFallback = async (events) => {
37
31
  await axiosClient.request({
38
32
  method: "POST",
@@ -41,27 +35,53 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
41
35
  });
42
36
  };
43
37
  const flush = async (eventsData) => {
44
- const sessionContext_ = sessionContext !== null && sessionContext !== void 0 ? sessionContext : (await getSessionContext());
38
+ const sessionContext_ = await getSessionContext(userAuthModule);
45
39
  const events = eventsData.map(transformEventDataToApiRequestData(sessionContext_));
46
40
  const beaconPayload = JSON.stringify({ events });
47
- if (typeof navigator === "undefined" ||
48
- beaconPayload.length > 60000 ||
49
- !navigator.sendBeacon(trackBatchUrl, beaconPayload)) {
50
- // beacon didn't work, fallback to axios
51
- await batchRequestFallback(events);
41
+ try {
42
+ if (typeof navigator === "undefined" ||
43
+ beaconPayload.length > 60000 ||
44
+ !navigator.sendBeacon(trackBatchUrl, beaconPayload)) {
45
+ // beacon didn't work, fallback to axios
46
+ await batchRequestFallback(events);
47
+ }
48
+ }
49
+ catch (_a) {
50
+ // TODO: think about retries if needed
52
51
  }
53
52
  };
54
- const onDocHidden = () => {
55
- analyticsSharedState.isProcessing = false;
56
- // flush entire queue on visibility change and hope for the best //
57
- const eventsData = analyticsSharedState.requestsQueue.splice(0);
58
- flush(eventsData);
53
+ const startProcessing = () => {
54
+ if (!enabled)
55
+ return;
56
+ startAnalyticsProcessor(flush, {
57
+ throttleTime,
58
+ batchSize,
59
+ });
60
+ };
61
+ const track = (params) => {
62
+ if (!enabled || analyticsSharedState.requestsQueue.length >= maxQueueSize) {
63
+ return;
64
+ }
65
+ const intrinsicData = getEventIntrinsicData();
66
+ analyticsSharedState.requestsQueue.push({
67
+ ...params,
68
+ ...intrinsicData,
69
+ });
70
+ startProcessing();
59
71
  };
60
72
  const onDocVisible = () => {
61
73
  startAnalyticsProcessor(flush, {
62
74
  throttleTime,
63
75
  batchSize,
64
76
  });
77
+ clearHeartBeatProcessor = startHeartBeatProcessor(track);
78
+ };
79
+ const onDocHidden = () => {
80
+ stopAnalyticsProcessor();
81
+ // flush entire queue on visibility change and hope for the best //
82
+ const eventsData = analyticsSharedState.requestsQueue.splice(0);
83
+ flush(eventsData);
84
+ clearHeartBeatProcessor === null || clearHeartBeatProcessor === void 0 ? void 0 : clearHeartBeatProcessor();
65
85
  };
66
86
  const onVisibilityChange = () => {
67
87
  if (typeof window === "undefined")
@@ -73,39 +93,58 @@ export const createAnalyticsModule = ({ axiosClient, serverUrl, appId, userAuthM
73
93
  onDocVisible();
74
94
  }
75
95
  };
96
+ const cleanup = () => {
97
+ stopAnalyticsProcessor();
98
+ clearHeartBeatProcessor === null || clearHeartBeatProcessor === void 0 ? void 0 : clearHeartBeatProcessor();
99
+ if (typeof window !== "undefined") {
100
+ window.removeEventListener("visibilitychange", onVisibilityChange);
101
+ }
102
+ };
103
+ // start the flusing process ///
104
+ startProcessing();
105
+ // start the heart beat processor //
106
+ clearHeartBeatProcessor = startHeartBeatProcessor(track);
107
+ // start the visibility change listener //
76
108
  if (typeof window !== "undefined" && enabled) {
77
109
  window.addEventListener("visibilitychange", onVisibilityChange);
78
110
  }
79
- // start analytics processor only if it's the first instance and analytics is enabled //
80
- if (enabled) {
81
- startAnalyticsProcessor(flush, {
82
- throttleTime,
83
- batchSize,
84
- });
85
- }
86
111
  return {
87
112
  track,
113
+ cleanup,
88
114
  };
89
115
  };
116
+ function stopAnalyticsProcessor() {
117
+ analyticsSharedState.isProcessing = false;
118
+ }
90
119
  async function startAnalyticsProcessor(handleTrack, options) {
91
120
  if (analyticsSharedState.isProcessing) {
121
+ // only one instance of the analytics processor can be running at a time //
92
122
  return;
93
123
  }
94
124
  analyticsSharedState.isProcessing = true;
95
125
  const { throttleTime = 1000, batchSize = 30 } = options !== null && options !== void 0 ? options : {};
96
- while (analyticsSharedState.isProcessing) {
126
+ while (analyticsSharedState.isProcessing &&
127
+ analyticsSharedState.requestsQueue.length > 0) {
97
128
  const requests = analyticsSharedState.requestsQueue.splice(0, batchSize);
98
- if (requests.length > 0) {
99
- try {
100
- await handleTrack(requests);
101
- }
102
- catch (error) {
103
- // TODO: think about retries if needed
104
- console.error("Error processing analytics request:", error);
105
- }
106
- }
129
+ requests.length && (await handleTrack(requests));
107
130
  await new Promise((resolve) => setTimeout(resolve, throttleTime));
108
131
  }
132
+ analyticsSharedState.isProcessing = false;
133
+ }
134
+ function startHeartBeatProcessor(track) {
135
+ var _a;
136
+ if (analyticsSharedState.isHeartBeatProcessing ||
137
+ ((_a = analyticsSharedState.config.heartBeatInterval) !== null && _a !== void 0 ? _a : 0) < 10) {
138
+ return () => { };
139
+ }
140
+ analyticsSharedState.isHeartBeatProcessing = true;
141
+ const interval = setInterval(() => {
142
+ track({ eventName: USER_HEARTBEAT_EVENT_NAME });
143
+ }, analyticsSharedState.config.heartBeatInterval);
144
+ return () => {
145
+ clearInterval(interval);
146
+ analyticsSharedState.isHeartBeatProcessing = false;
147
+ };
109
148
  }
110
149
  function getEventIntrinsicData() {
111
150
  return {
@@ -122,14 +161,30 @@ function transformEventDataToApiRequestData(sessionContext) {
122
161
  ...sessionContext,
123
162
  });
124
163
  }
125
- export function getAnalyticsModuleOptionsFromUrlParams() {
164
+ let sessionContextPromise = null;
165
+ async function getSessionContext(userAuthModule) {
166
+ if (!analyticsSharedState.sessionContext) {
167
+ if (!sessionContextPromise) {
168
+ sessionContextPromise = userAuthModule
169
+ .me()
170
+ .then((user) => ({
171
+ user_id: user.id,
172
+ }))
173
+ .catch(() => ({
174
+ user_id: "unknown: error getting session context",
175
+ }));
176
+ }
177
+ analyticsSharedState.sessionContext = await sessionContextPromise;
178
+ }
179
+ return analyticsSharedState.sessionContext;
180
+ }
181
+ export function getAnalyticsModuleOptionsFromLocalStorage() {
126
182
  if (typeof window === "undefined")
127
183
  return undefined;
128
- const urlParams = new URLSearchParams(window.location.search);
129
- const jsonString = urlParams.get("analytics");
130
- if (!jsonString)
131
- return undefined;
132
184
  try {
185
+ const jsonString = localStorage.getItem("base44_analytics_config");
186
+ if (!jsonString)
187
+ return undefined;
133
188
  return JSON.parse(jsonString);
134
189
  }
135
190
  catch (_a) {
@@ -34,4 +34,8 @@ export type AnalyticsModuleOptions = {
34
34
  maxQueueSize?: number;
35
35
  throttleTime?: number;
36
36
  batchSize?: number;
37
+ heartBeatInterval?: number;
38
+ };
39
+ export type AnalyticsModule = {
40
+ track: (params: TrackEventParams) => void;
37
41
  };
@@ -1,2 +1 @@
1
1
  export declare function getSharedInstance<T>(name: string, factory: () => T): T;
2
- export declare function getSharedInstanceRefCount<T>(name: string): number;
@@ -9,13 +9,7 @@ export function getSharedInstance(name, factory) {
9
9
  if (!windowObj.base44SharedInstances[name]) {
10
10
  windowObj.base44SharedInstances[name] = {
11
11
  instance: factory(),
12
- _refCount: 0,
13
12
  };
14
13
  }
15
- windowObj.base44SharedInstances[name]._refCount++;
16
14
  return windowObj.base44SharedInstances[name].instance;
17
15
  }
18
- export function getSharedInstanceRefCount(name) {
19
- var _a, _b, _c;
20
- return (_c = (_b = (_a = windowObj.base44SharedInstances) === null || _a === void 0 ? void 0 : _a[name]) === null || _b === void 0 ? void 0 : _b._refCount) !== null && _c !== void 0 ? _c : 0;
21
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.6-pr.57.0298afb",
3
+ "version": "0.8.6-pr.57.2eea21a",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",