@alpic-ai/insights 0.0.0-dev.g4a2e02d → 0.0.0-dev.g4a8e123
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/index.d.mts +57 -1
- package/dist/index.mjs +104 -1
- package/dist/react/index.d.mts +47 -4
- package/dist/react/index.mjs +142 -44
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -36,6 +36,53 @@ type McpMiddlewareFn = (request: {
|
|
|
36
36
|
*/
|
|
37
37
|
declare function intentMiddleware(options?: IntentMiddlewareOptions): McpMiddlewareFn;
|
|
38
38
|
//#endregion
|
|
39
|
+
//#region src/analytics-middleware.d.ts
|
|
40
|
+
interface CaptureOptions {
|
|
41
|
+
message?: string;
|
|
42
|
+
/** Duration of the operation the event describes, in milliseconds. */
|
|
43
|
+
duration?: number;
|
|
44
|
+
isError?: boolean;
|
|
45
|
+
error?: string;
|
|
46
|
+
/** Freeform event detail. Not indexed — filtering on a property key is a query-time scan. */
|
|
47
|
+
properties?: Record<string, unknown>;
|
|
48
|
+
}
|
|
49
|
+
interface Analytics {
|
|
50
|
+
/** Records a custom event on the current session's timeline, interleaved with tool calls. */
|
|
51
|
+
capture(name: string, options?: CaptureOptions): void;
|
|
52
|
+
/**
|
|
53
|
+
* Replaces the current request user's trait snapshot (e.g. email, name, plan). The target user
|
|
54
|
+
* is resolved by Alpic from the request auth context — no id or sessionId is passed.
|
|
55
|
+
*/
|
|
56
|
+
identify(traits: Record<string, string>): void;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Shape of the handler `extra` once `analyticsMiddleware()` (or `track(server)`) is installed.
|
|
60
|
+
* Cast the handler's `extra` to this to access `analytics` with types.
|
|
61
|
+
*/
|
|
62
|
+
interface AnalyticsExtra {
|
|
63
|
+
analytics: Analytics;
|
|
64
|
+
}
|
|
65
|
+
interface AnalyticsEvent extends CaptureOptions {
|
|
66
|
+
name: string;
|
|
67
|
+
timestamp: number;
|
|
68
|
+
}
|
|
69
|
+
interface AnalyticsBatch {
|
|
70
|
+
events: AnalyticsEvent[];
|
|
71
|
+
traits?: Record<string, string>;
|
|
72
|
+
}
|
|
73
|
+
interface AnalyticsMiddlewareOptions {
|
|
74
|
+
/** Receives each request's analytics locally, whether or not the server is hosted by Alpic. */
|
|
75
|
+
handler?: (batch: AnalyticsBatch) => Promise<void> | void;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Lets MCP server builders record custom analytics events and user traits from inside tool
|
|
79
|
+
* handlers, via `extra.analytics.capture(...)` / `extra.analytics.identify(...)`. Calls are
|
|
80
|
+
* buffered during the request. On Alpic, private environment-provided `_meta` keys carry them to
|
|
81
|
+
* the proxy for ingestion. Locally, pass a handler to receive them without exposing analytics in
|
|
82
|
+
* the MCP response.
|
|
83
|
+
*/
|
|
84
|
+
declare function analyticsMiddleware(options?: AnalyticsMiddlewareOptions): McpMiddlewareFn;
|
|
85
|
+
//#endregion
|
|
39
86
|
//#region src/feedback-middleware.d.ts
|
|
40
87
|
interface FeedbackData {
|
|
41
88
|
content: string;
|
|
@@ -77,4 +124,13 @@ declare const captureFeedback: (server: McpServer | Server, options?: FeedbackMi
|
|
|
77
124
|
*/
|
|
78
125
|
declare const captureIntents: (server: McpServer | Server, options?: IntentMiddlewareOptions) => void;
|
|
79
126
|
//#endregion
|
|
80
|
-
|
|
127
|
+
//#region src/track.d.ts
|
|
128
|
+
/**
|
|
129
|
+
* Enables custom analytics events on a vanilla `@modelcontextprotocol/sdk` server. Accepts the
|
|
130
|
+
* high-level `McpServer` or the low-level `Server` and patches the `tools/call` request handlers
|
|
131
|
+
* so tool handlers can call `extra.analytics.capture(...)` / `extra.analytics.identify(...)`.
|
|
132
|
+
* Pass a handler in `options` to receive analytics when running outside Alpic.
|
|
133
|
+
*/
|
|
134
|
+
declare const track: (server: McpServer | Server, options?: AnalyticsMiddlewareOptions) => void;
|
|
135
|
+
//#endregion
|
|
136
|
+
export { type Analytics, type AnalyticsBatch, type AnalyticsEvent, type AnalyticsExtra, type AnalyticsMiddlewareOptions, type CaptureOptions, type FeedbackData, type FeedbackMiddlewareOptions, type IntentMiddlewareOptions, type McpMiddlewareFn, type PromptData, analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,92 @@
|
|
|
1
1
|
import { CallToolRequestSchema, CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
//#region src/analytics-middleware.ts
|
|
3
|
+
const MAX_EVENTS_PER_REQUEST = 50;
|
|
4
|
+
function warnInDev(message) {
|
|
5
|
+
if (process.env.NODE_ENV !== "production") console.warn(`[insights] ${message}`);
|
|
6
|
+
}
|
|
7
|
+
function createAnalyticsBuffer() {
|
|
8
|
+
const events = [];
|
|
9
|
+
let traits;
|
|
10
|
+
let settled = false;
|
|
11
|
+
return {
|
|
12
|
+
analytics: {
|
|
13
|
+
capture(name, options) {
|
|
14
|
+
if (settled) {
|
|
15
|
+
warnInDev(`analytics.capture("${name}") was called after the request settled; the event was dropped. Capture events before the tool handler returns.`);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (events.length >= MAX_EVENTS_PER_REQUEST) {
|
|
19
|
+
warnInDev(`analytics.capture("${name}") exceeded the ${MAX_EVENTS_PER_REQUEST} events per request limit; the event was dropped.`);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
events.push({
|
|
23
|
+
...options,
|
|
24
|
+
name,
|
|
25
|
+
timestamp: Date.now()
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
identify(newTraits) {
|
|
29
|
+
if (settled) {
|
|
30
|
+
warnInDev("analytics.identify() was called after the request settled; the traits were dropped. Identify before the tool handler returns.");
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
traits = { ...newTraits };
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
settle: () => {
|
|
37
|
+
settled = true;
|
|
38
|
+
},
|
|
39
|
+
get events() {
|
|
40
|
+
return events;
|
|
41
|
+
},
|
|
42
|
+
get traits() {
|
|
43
|
+
return traits;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Lets MCP server builders record custom analytics events and user traits from inside tool
|
|
49
|
+
* handlers, via `extra.analytics.capture(...)` / `extra.analytics.identify(...)`. Calls are
|
|
50
|
+
* buffered during the request. On Alpic, private environment-provided `_meta` keys carry them to
|
|
51
|
+
* the proxy for ingestion. Locally, pass a handler to receive them without exposing analytics in
|
|
52
|
+
* the MCP response.
|
|
53
|
+
*/
|
|
54
|
+
function analyticsMiddleware(options) {
|
|
55
|
+
return async (request, extra, next) => {
|
|
56
|
+
if (request.method !== "tools/call" || extra === null || typeof extra !== "object") return next();
|
|
57
|
+
const buffer = createAnalyticsBuffer();
|
|
58
|
+
extra.analytics = buffer.analytics;
|
|
59
|
+
let rawResult;
|
|
60
|
+
try {
|
|
61
|
+
rawResult = await next();
|
|
62
|
+
} finally {
|
|
63
|
+
buffer.settle();
|
|
64
|
+
}
|
|
65
|
+
if (buffer.events.length === 0 && buffer.traits === void 0) return rawResult;
|
|
66
|
+
const batch = {
|
|
67
|
+
events: [...buffer.events],
|
|
68
|
+
...buffer.traits === void 0 ? {} : { traits: { ...buffer.traits } }
|
|
69
|
+
};
|
|
70
|
+
if (options?.handler) try {
|
|
71
|
+
await options.handler(batch);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error("Error calling analytics handler", error);
|
|
74
|
+
}
|
|
75
|
+
const eventsMetaKey = process.env.ALPIC_EVENTS_META_KEY || void 0;
|
|
76
|
+
const identifyMetaKey = process.env.ALPIC_IDENTIFY_META_KEY || void 0;
|
|
77
|
+
if (eventsMetaKey === void 0 && identifyMetaKey === void 0) return rawResult;
|
|
78
|
+
if (!CallToolResultSchema.safeParse(rawResult).success) return rawResult;
|
|
79
|
+
const result = rawResult;
|
|
80
|
+
const meta = { ...result._meta };
|
|
81
|
+
if (eventsMetaKey !== void 0 && buffer.events.length > 0) meta[eventsMetaKey] = buffer.events;
|
|
82
|
+
if (identifyMetaKey !== void 0 && buffer.traits !== void 0) meta[identifyMetaKey] = buffer.traits;
|
|
83
|
+
return {
|
|
84
|
+
...result,
|
|
85
|
+
_meta: meta
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
2
90
|
//#region src/feedback-middleware.ts
|
|
3
91
|
const FEEDBACK_TOOL_NAME = "send_feedback";
|
|
4
92
|
const FEEDBACK_TOOL_DESCRIPTION = "Send feedback about this MCP server to its operators. Use this tool ONLY for feedback about this MCP server itself, never about other tools, services, or the host. You MAY call this tool when you detect a genuine issue with this server (e.g. a tool that failed unexpectedly, an unhelpful response, a missing capability). You MAY also call it when the user explicitly asks to send feedback. Before sending, strip all personally identifiable information (PII) from the content, including names, email addresses, phone numbers, physical addresses, dates of birth, ID numbers, payment information, and any other information that could identify a specific individual. Replace stripped values with generic placeholders (e.g. \"[name]\", \"[email]\").";
|
|
@@ -271,4 +359,19 @@ const captureIntents = (server, options) => {
|
|
|
271
359
|
});
|
|
272
360
|
};
|
|
273
361
|
//#endregion
|
|
274
|
-
|
|
362
|
+
//#region src/track.ts
|
|
363
|
+
/**
|
|
364
|
+
* Enables custom analytics events on a vanilla `@modelcontextprotocol/sdk` server. Accepts the
|
|
365
|
+
* high-level `McpServer` or the low-level `Server` and patches the `tools/call` request handlers
|
|
366
|
+
* so tool handlers can call `extra.analytics.capture(...)` / `extra.analytics.identify(...)`.
|
|
367
|
+
* Pass a handler in `options` to receive analytics when running outside Alpic.
|
|
368
|
+
*/
|
|
369
|
+
const track = (server, options) => {
|
|
370
|
+
installCaptureMiddleware(server, {
|
|
371
|
+
middleware: analyticsMiddleware(options),
|
|
372
|
+
installedMarker: "__alpicTrackInstalled",
|
|
373
|
+
disabledWarning: "Analytics capture disabled."
|
|
374
|
+
});
|
|
375
|
+
};
|
|
376
|
+
//#endregion
|
|
377
|
+
export { analyticsMiddleware, captureFeedback, captureIntents, feedbackMiddleware, intentMiddleware, track };
|
package/dist/react/index.d.mts
CHANGED
|
@@ -1,24 +1,67 @@
|
|
|
1
1
|
import { ReactNode } from "react";
|
|
2
|
+
//#region src/react/analytics-transport.d.ts
|
|
3
|
+
interface AnalyticsEvent {
|
|
4
|
+
name: string;
|
|
5
|
+
timestamp: number;
|
|
6
|
+
message?: string;
|
|
7
|
+
properties?: Record<string, unknown>;
|
|
8
|
+
duration?: number;
|
|
9
|
+
isError?: boolean;
|
|
10
|
+
error?: string;
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
2
13
|
//#region src/react/analytics-client.d.ts
|
|
3
14
|
interface CaptureOptions {
|
|
4
15
|
message?: string;
|
|
5
16
|
properties?: Record<string, unknown>;
|
|
17
|
+
/** Duration of the operation the event describes, in milliseconds. */
|
|
18
|
+
duration?: number;
|
|
19
|
+
isError?: boolean;
|
|
20
|
+
error?: string;
|
|
6
21
|
}
|
|
22
|
+
/** Inspect, transform, or drop (return `null`) each event before it is buffered for delivery. */
|
|
23
|
+
type BeforeSend = (event: AnalyticsEvent) => AnalyticsEvent | null;
|
|
7
24
|
//#endregion
|
|
8
25
|
//#region src/react/alpic-analytics.d.ts
|
|
9
26
|
interface Analytics {
|
|
10
27
|
/** Queue a custom widget event for delivery to Alpic Analytics. */
|
|
11
28
|
capture: (name: string, options?: CaptureOptions) => void;
|
|
12
29
|
}
|
|
30
|
+
/** Toggles for the SDK's built-in event capture. Lifecycle and errors are on by default; interactions are opt-in. */
|
|
31
|
+
interface AutoCaptureOptions {
|
|
32
|
+
lifecycle?: boolean;
|
|
33
|
+
errors?: boolean;
|
|
34
|
+
interactions?: boolean;
|
|
35
|
+
}
|
|
36
|
+
interface AlpicAnalyticsProps {
|
|
37
|
+
children?: ReactNode;
|
|
38
|
+
/** Inspect, transform, or drop each event before delivery. Runs synchronously in `capture`. */
|
|
39
|
+
beforeSend?: BeforeSend;
|
|
40
|
+
autoCapture?: AutoCaptureOptions;
|
|
41
|
+
}
|
|
13
42
|
/**
|
|
14
43
|
* Provides Alpic Analytics to descendant components and configures itself from the widget host.
|
|
15
44
|
* Wrap the widget once, then call `useAnalytics()` from components that capture events.
|
|
16
45
|
* Events captured before configuration is available are buffered automatically.
|
|
17
46
|
*/
|
|
18
|
-
declare function AlpicAnalytics({ children }:
|
|
19
|
-
children?: ReactNode;
|
|
20
|
-
}): import("react").JSX.Element;
|
|
47
|
+
declare function AlpicAnalytics({ children, beforeSend, autoCapture }: AlpicAnalyticsProps): import("react").JSX.Element;
|
|
21
48
|
/** Returns the analytics client from the nearest `AlpicAnalytics` provider. */
|
|
22
49
|
declare function useAnalytics(): Analytics;
|
|
23
50
|
//#endregion
|
|
24
|
-
|
|
51
|
+
//#region src/react/auto-capture.d.ts
|
|
52
|
+
/**
|
|
53
|
+
* Reserved auto-capture event names. The `$` prefix marks events emitted by the SDK itself
|
|
54
|
+
* (lifecycle, errors, interactions) so the analytics UI can distinguish them from custom
|
|
55
|
+
* `capture()` calls. Keep in sync with the server-side reserved namespace.
|
|
56
|
+
*/
|
|
57
|
+
declare const AUTO_EVENT: {
|
|
58
|
+
readonly loaded: "$loaded";
|
|
59
|
+
readonly visible: "$visible";
|
|
60
|
+
readonly hidden: "$hidden";
|
|
61
|
+
readonly closed: "$closed";
|
|
62
|
+
readonly error: "$error";
|
|
63
|
+
};
|
|
64
|
+
/** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
|
|
65
|
+
declare const INTERACTION_ATTRIBUTE = "data-alpic-event";
|
|
66
|
+
//#endregion
|
|
67
|
+
export { AUTO_EVENT, AlpicAnalytics, type AlpicAnalyticsProps, type Analytics, type AutoCaptureOptions, type BeforeSend, type CaptureOptions, INTERACTION_ATTRIBUTE, useAnalytics };
|
package/dist/react/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createContext, useContext, useEffect, useState } from "react";
|
|
1
|
+
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
3
|
//#region src/react/analytics-transport.ts
|
|
4
4
|
function postAnalyticsBatch(ingestUrl, events) {
|
|
@@ -9,42 +9,23 @@ function postAnalyticsBatch(ingestUrl, events) {
|
|
|
9
9
|
body: JSON.stringify({ events })
|
|
10
10
|
}).then(() => void 0, () => void 0);
|
|
11
11
|
}
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/react/event-queue.ts
|
|
14
|
-
var EventQueue = class {
|
|
15
|
-
maxSize;
|
|
16
|
-
items = [];
|
|
17
|
-
constructor(maxSize) {
|
|
18
|
-
this.maxSize = maxSize;
|
|
19
|
-
}
|
|
20
|
-
get length() {
|
|
21
|
-
return this.items.length;
|
|
22
|
-
}
|
|
23
|
-
get isFull() {
|
|
24
|
-
return this.items.length >= this.maxSize;
|
|
25
|
-
}
|
|
26
|
-
push(item) {
|
|
27
|
-
if (this.items.length >= this.maxSize) return false;
|
|
28
|
-
this.items.push(item);
|
|
29
|
-
return true;
|
|
30
|
-
}
|
|
31
|
-
drain(maxItems) {
|
|
32
|
-
return this.items.splice(0, maxItems);
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
12
|
const FLUSH_DELAY_MS = 2e3;
|
|
36
13
|
var AnalyticsClient = class {
|
|
37
|
-
|
|
14
|
+
events = [];
|
|
15
|
+
beforeSend;
|
|
38
16
|
stamp = null;
|
|
39
17
|
flushTimer = null;
|
|
40
18
|
warnedBufferFull = false;
|
|
19
|
+
constructor(options) {
|
|
20
|
+
this.beforeSend = options?.beforeSend;
|
|
21
|
+
}
|
|
41
22
|
configure(stamp) {
|
|
42
23
|
if (this.stamp !== null && !isSameStamp(this.stamp, stamp)) this.flush();
|
|
43
24
|
this.stamp = stamp;
|
|
44
|
-
if (this.
|
|
25
|
+
if (this.events.length > 0) this.scheduleFlush();
|
|
45
26
|
}
|
|
46
27
|
capture = (name, options) => {
|
|
47
|
-
if (this.
|
|
28
|
+
if (this.events.length >= 100) {
|
|
48
29
|
if (!this.warnedBufferFull) {
|
|
49
30
|
console.warn("[@alpic-ai/insights] analytics buffer is full, dropping events");
|
|
50
31
|
this.warnedBufferFull = true;
|
|
@@ -57,8 +38,13 @@ var AnalyticsClient = class {
|
|
|
57
38
|
};
|
|
58
39
|
if (options?.message !== void 0) event.message = options.message;
|
|
59
40
|
if (options?.properties !== void 0) event.properties = options.properties;
|
|
60
|
-
|
|
61
|
-
if (
|
|
41
|
+
if (options?.duration !== void 0) event.duration = options.duration;
|
|
42
|
+
if (options?.isError !== void 0) event.isError = options.isError;
|
|
43
|
+
if (options?.error !== void 0) event.error = options.error;
|
|
44
|
+
const outgoing = this.beforeSend ? this.beforeSend(event) : event;
|
|
45
|
+
if (outgoing === null) return;
|
|
46
|
+
this.events.push(outgoing);
|
|
47
|
+
if (this.events.length >= 50) {
|
|
62
48
|
this.flush();
|
|
63
49
|
return;
|
|
64
50
|
}
|
|
@@ -70,9 +56,9 @@ var AnalyticsClient = class {
|
|
|
70
56
|
this.flushTimer = null;
|
|
71
57
|
}
|
|
72
58
|
if (this.stamp === null) return;
|
|
73
|
-
while (this.
|
|
74
|
-
const
|
|
75
|
-
postAnalyticsBatch(this.stamp.ingestUrl,
|
|
59
|
+
while (this.events.length > 0) {
|
|
60
|
+
const batch = this.events.splice(0, 50);
|
|
61
|
+
postAnalyticsBatch(this.stamp.ingestUrl, batch);
|
|
76
62
|
}
|
|
77
63
|
this.warnedBufferFull = false;
|
|
78
64
|
};
|
|
@@ -85,6 +71,88 @@ function isSameStamp(left, right) {
|
|
|
85
71
|
return left.distinctId === right.distinctId && left.sessionId === right.sessionId && left.ingestUrl === right.ingestUrl;
|
|
86
72
|
}
|
|
87
73
|
//#endregion
|
|
74
|
+
//#region src/react/auto-capture.ts
|
|
75
|
+
/**
|
|
76
|
+
* Reserved auto-capture event names. The `$` prefix marks events emitted by the SDK itself
|
|
77
|
+
* (lifecycle, errors, interactions) so the analytics UI can distinguish them from custom
|
|
78
|
+
* `capture()` calls. Keep in sync with the server-side reserved namespace.
|
|
79
|
+
*/
|
|
80
|
+
const AUTO_EVENT = {
|
|
81
|
+
loaded: "$loaded",
|
|
82
|
+
visible: "$visible",
|
|
83
|
+
hidden: "$hidden",
|
|
84
|
+
closed: "$closed",
|
|
85
|
+
error: "$error"
|
|
86
|
+
};
|
|
87
|
+
/** Public DOM contract for declarative interaction capture: the attribute value is the event name. */
|
|
88
|
+
const INTERACTION_ATTRIBUTE = "data-alpic-event";
|
|
89
|
+
const INTERACTION_DATASET_KEY = "alpicEvent";
|
|
90
|
+
const INTERACTION_DATASET_PREFIX = "alpic";
|
|
91
|
+
/**
|
|
92
|
+
* Resolves the nearest `[data-alpic-event]` ancestor of a click target into an event: the
|
|
93
|
+
* attribute value is the name, and every other `data-alpic-*` attribute becomes a property.
|
|
94
|
+
*/
|
|
95
|
+
function resolveInteractionEvent(target) {
|
|
96
|
+
if (!(target instanceof Element)) return null;
|
|
97
|
+
const element = target.closest(`[${INTERACTION_ATTRIBUTE}]`);
|
|
98
|
+
if (element === null) return null;
|
|
99
|
+
const name = element.dataset[INTERACTION_DATASET_KEY];
|
|
100
|
+
if (name === void 0 || name === "") return null;
|
|
101
|
+
const properties = {};
|
|
102
|
+
for (const [key, value] of Object.entries(element.dataset)) {
|
|
103
|
+
if (key === INTERACTION_DATASET_KEY || !key.startsWith(INTERACTION_DATASET_PREFIX) || value === void 0) continue;
|
|
104
|
+
const unprefixed = key.slice(5);
|
|
105
|
+
const propertyKey = unprefixed.charAt(0).toLowerCase() + unprefixed.slice(1);
|
|
106
|
+
properties[propertyKey] = value;
|
|
107
|
+
}
|
|
108
|
+
return Object.keys(properties).length > 0 ? {
|
|
109
|
+
name,
|
|
110
|
+
properties
|
|
111
|
+
} : { name };
|
|
112
|
+
}
|
|
113
|
+
/** Captures uncaught errors and unhandled rejections as `$error`, mapped onto the ingest error columns. */
|
|
114
|
+
function installErrorCapture(client) {
|
|
115
|
+
const onError = (event) => {
|
|
116
|
+
client.capture(AUTO_EVENT.error, {
|
|
117
|
+
isError: true,
|
|
118
|
+
error: event.message,
|
|
119
|
+
properties: {
|
|
120
|
+
stack: event.error instanceof Error ? event.error.stack : void 0,
|
|
121
|
+
source: event.filename
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
};
|
|
125
|
+
const onRejection = (event) => {
|
|
126
|
+
const reason = event.reason;
|
|
127
|
+
client.capture(AUTO_EVENT.error, {
|
|
128
|
+
isError: true,
|
|
129
|
+
error: reason instanceof Error ? reason.message : String(reason),
|
|
130
|
+
properties: {
|
|
131
|
+
stack: reason instanceof Error ? reason.stack : void 0,
|
|
132
|
+
source: "unhandledrejection"
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
window.addEventListener("error", onError);
|
|
137
|
+
window.addEventListener("unhandledrejection", onRejection);
|
|
138
|
+
return () => {
|
|
139
|
+
window.removeEventListener("error", onError);
|
|
140
|
+
window.removeEventListener("unhandledrejection", onRejection);
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/** Captures clicks on `[data-alpic-event]` elements via a single delegated `document` listener. */
|
|
144
|
+
function installInteractionCapture(client) {
|
|
145
|
+
const onClick = (event) => {
|
|
146
|
+
const resolved = resolveInteractionEvent(event.target);
|
|
147
|
+
if (resolved === null) return;
|
|
148
|
+
client.capture(resolved.name, resolved.properties ? { properties: resolved.properties } : void 0);
|
|
149
|
+
};
|
|
150
|
+
document.addEventListener("click", onClick);
|
|
151
|
+
return () => {
|
|
152
|
+
document.removeEventListener("click", onClick);
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
88
156
|
//#region src/react/stamp.ts
|
|
89
157
|
const ANALYTICS_META_KEY = "alpic/analytics";
|
|
90
158
|
function parseAnalyticsStamp(metadata) {
|
|
@@ -154,24 +222,54 @@ const AnalyticsContext = createContext(null);
|
|
|
154
222
|
* Wrap the widget once, then call `useAnalytics()` from components that capture events.
|
|
155
223
|
* Events captured before configuration is available are buffered automatically.
|
|
156
224
|
*/
|
|
157
|
-
function AlpicAnalytics({ children }) {
|
|
158
|
-
const
|
|
225
|
+
function AlpicAnalytics({ children, beforeSend, autoCapture }) {
|
|
226
|
+
const beforeSendRef = useRef(beforeSend);
|
|
227
|
+
beforeSendRef.current = beforeSend;
|
|
228
|
+
const [client] = useState(() => new AnalyticsClient({ beforeSend: (event) => {
|
|
229
|
+
const transform = beforeSendRef.current;
|
|
230
|
+
return transform ? transform(event) : event;
|
|
231
|
+
} }));
|
|
232
|
+
const lifecycle = autoCapture?.lifecycle ?? true;
|
|
233
|
+
const errors = autoCapture?.errors ?? true;
|
|
234
|
+
const interactions = autoCapture?.interactions ?? false;
|
|
159
235
|
useEffect(() => {
|
|
160
|
-
|
|
236
|
+
return subscribeToAnalyticsStamp((stamp) => {
|
|
161
237
|
client.configure(stamp);
|
|
162
238
|
});
|
|
163
|
-
|
|
164
|
-
|
|
239
|
+
}, [client]);
|
|
240
|
+
useEffect(() => {
|
|
241
|
+
if (lifecycle) client.capture(AUTO_EVENT.loaded);
|
|
242
|
+
let closed = false;
|
|
243
|
+
const onVisibilityChange = () => {
|
|
244
|
+
if (document.visibilityState === "hidden") {
|
|
245
|
+
if (lifecycle && !closed) client.capture(AUTO_EVENT.hidden);
|
|
246
|
+
client.flush();
|
|
247
|
+
} else {
|
|
248
|
+
closed = false;
|
|
249
|
+
if (lifecycle) client.capture(AUTO_EVENT.visible);
|
|
250
|
+
}
|
|
165
251
|
};
|
|
166
|
-
|
|
167
|
-
|
|
252
|
+
const onPageHide = () => {
|
|
253
|
+
if (lifecycle) client.capture(AUTO_EVENT.closed);
|
|
254
|
+
closed = true;
|
|
255
|
+
client.flush();
|
|
256
|
+
};
|
|
257
|
+
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
258
|
+
window.addEventListener("pagehide", onPageHide);
|
|
168
259
|
return () => {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
window.removeEventListener("pagehide", client.flush);
|
|
260
|
+
document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
261
|
+
window.removeEventListener("pagehide", onPageHide);
|
|
172
262
|
client.flush();
|
|
173
263
|
};
|
|
174
|
-
}, [client]);
|
|
264
|
+
}, [client, lifecycle]);
|
|
265
|
+
useEffect(() => {
|
|
266
|
+
if (!errors) return;
|
|
267
|
+
return installErrorCapture(client);
|
|
268
|
+
}, [client, errors]);
|
|
269
|
+
useEffect(() => {
|
|
270
|
+
if (!interactions) return;
|
|
271
|
+
return installInteractionCapture(client);
|
|
272
|
+
}, [client, interactions]);
|
|
175
273
|
return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
|
|
176
274
|
value: client,
|
|
177
275
|
children
|
|
@@ -184,4 +282,4 @@ function useAnalytics() {
|
|
|
184
282
|
return analytics;
|
|
185
283
|
}
|
|
186
284
|
//#endregion
|
|
187
|
-
export { AlpicAnalytics, useAnalytics };
|
|
285
|
+
export { AUTO_EVENT, AlpicAnalytics, INTERACTION_ATTRIBUTE, useAnalytics };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alpic-ai/insights",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.g4a8e123",
|
|
4
4
|
"description": "User insights middlewares for Alpic-hosted MCP servers",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.mjs",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"react-dom": "^19.2.7",
|
|
46
46
|
"shx": "^0.4.0",
|
|
47
47
|
"skybridge": "^1.2.7",
|
|
48
|
-
"tsdown": "^0.22.
|
|
48
|
+
"tsdown": "^0.22.9",
|
|
49
49
|
"typescript": "^6.0.3",
|
|
50
50
|
"vitest": "^4.1.10",
|
|
51
51
|
"zod": "^4.4.3"
|