pulsemetrics-sdk 0.0.0-stage → 1.1.0

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/README.md CHANGED
@@ -1,3 +1,198 @@
1
- # Temporary Holding Version
1
+ # pulsemetrics-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A simple and lightweight client SDK to track Daily Active Users (DAU) in modern web applications (React, Next.js, Node.js, Vue, etc.).
4
+
5
+ ---
6
+
7
+ ## Getting Started
8
+
9
+ ### Step 1: Get your API Key
10
+ 1. Create a project on the dashboard.
11
+ 2. Go to **Project Settings**.
12
+ 3. Copy your **API Key**.
13
+
14
+ ### Step 2: Install the Package
15
+
16
+ ```bash
17
+ npm install pulsemetrics-sdk
18
+ ```
19
+
20
+ Or using bun, yarn, or pnpm:
21
+
22
+ ```bash
23
+ bun add pulsemetrics-sdk
24
+ # or
25
+ yarn add pulsemetrics-sdk
26
+ # or
27
+ pnpm add pulsemetrics-sdk
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Basic Setup
33
+
34
+ Create a centralized tracker instance (e.g., `lib/dau.js` or `utils/dau.ts`):
35
+
36
+ ```javascript
37
+ import Pulsemetrics from "pulsemetrics-sdk";
38
+
39
+ export const dau = new Pulsemetrics("YOUR_API_KEY");
40
+ ```
41
+
42
+ ### Method 1: `init`
43
+ Available for Free to Enterprise plans.
44
+
45
+ ```javascript
46
+ await dau.init("logged_in_user_id");
47
+ ```
48
+
49
+ ### Method 2: `trackWithName`
50
+ Available for Pro and Enterprise plans.
51
+
52
+ ```javascript
53
+ await dau.trackWithName({
54
+ userId: "logged_in_user_id",
55
+ userName: "GUEST", // e.g. userName: string = "GUEST"
56
+ });
57
+ ```
58
+
59
+ ---
60
+
61
+ ## Examples (React / Next.js)
62
+
63
+ Daily active users can be captured effectively at multiple stages of the user lifecycle using either `dau.init` (Free to Enterprise plans) or `dau.trackWithName` (Pro and Enterprise plans):
64
+
65
+ ### Pattern 1: Right After Successful Login
66
+ Call `dau.init` or `dau.trackWithName` immediately when the user logs in via email/password or OAuth:
67
+
68
+ ```javascript
69
+ import { dau } from "@/lib/dau";
70
+
71
+ async function handleLogin(credentials) {
72
+ const response = await api.post("/auth/login", credentials);
73
+ const user = response.data.user;
74
+
75
+ // Option 1: Free to Enterprise plans
76
+ await dau.init(user.id);
77
+
78
+ // Option 2: Pro and Enterprise plans
79
+ await dau.trackWithName({
80
+ userId: user.id,
81
+ userName: user.name || "GUEST",
82
+ });
83
+ }
84
+ ```
85
+
86
+ ---
87
+
88
+ ### Pattern 2: On Page Refresh / Session Restore (`/api/me`)
89
+ In SPAs and Next.js apps, users refresh pages while remaining logged in. Modern apps usually call an endpoint like `/api/me`, `/api/auth/session`, or "Who Am I" to restore session state. Trigger DAU tracking right after this call:
90
+
91
+ ```javascript
92
+ import { useEffect } from "react";
93
+ import { dau } from "@/lib/dau";
94
+
95
+ export function useSessionRestore() {
96
+ useEffect(() => {
97
+ async function fetchCurrentUser() {
98
+ try {
99
+ const response = await fetch("/api/me");
100
+ if (response.ok) {
101
+ const userData = await response.json();
102
+
103
+ // Option 1: Free to Enterprise plans
104
+ await dau.init(userData.id);
105
+
106
+ // Option 2: Pro and Enterprise plans
107
+ await dau.trackWithName({
108
+ userId: userData.id,
109
+ userName: userData.name || "GUEST",
110
+ });
111
+ }
112
+ } catch (error) {
113
+ console.error("Session restore error:", error);
114
+ }
115
+ }
116
+
117
+ fetchCurrentUser();
118
+ }, []);
119
+ }
120
+ ```
121
+
122
+ ---
123
+
124
+ ### Pattern 3: Auth Interceptor & Token Refresh
125
+ When an access token expires and an HTTP interceptor (like Axios or custom fetch) refreshes the token to regain access, trigger DAU tracking:
126
+
127
+ ```javascript
128
+ import axios from "axios";
129
+ import { dau } from "@/lib/dau";
130
+
131
+ axios.interceptors.response.use(
132
+ (response) => response,
133
+ async (error) => {
134
+ if (error.response?.status === 401) {
135
+ // 1. Refresh token
136
+ const newSession = await refreshAccessToken();
137
+
138
+ // 2. Track DAU upon successful re-authentication
139
+ if (newSession?.user?.id) {
140
+ // Option 1: Free to Enterprise plans
141
+ await dau.init(newSession.user.id);
142
+
143
+ // Option 2: Pro and Enterprise plans
144
+ await dau.trackWithName({
145
+ userId: newSession.user.id,
146
+ userName: newSession.user.name || "GUEST",
147
+ });
148
+ }
149
+
150
+ // 3. Retry original request
151
+ return axios(error.config);
152
+ }
153
+ return Promise.reject(error);
154
+ }
155
+ );
156
+ ```
157
+
158
+ ---
159
+
160
+ ### Pattern 4: Centralized Inside Auth Context
161
+ If you use an `AuthProvider` in React or Next.js, place `dau.init` or `dau.trackWithName` inside your global auth state listener:
162
+
163
+ ```javascript
164
+ import React, { createContext, useEffect, useState } from "react";
165
+ import { dau } from "@/lib/dau";
166
+
167
+ export const AuthContext = createContext(null);
168
+
169
+ export function AuthProvider({ children }) {
170
+ const [user, setUser] = useState(null);
171
+
172
+ useEffect(() => {
173
+ if (user?.id) {
174
+ // Option 1: Free to Enterprise plans
175
+ dau.init(user.id).catch(console.error);
176
+
177
+ // Option 2: Pro and Enterprise plans
178
+ dau
179
+ .trackWithName({
180
+ userId: user.id,
181
+ userName: user.name || "GUEST",
182
+ })
183
+ .catch(console.error);
184
+ }
185
+ }, [user?.id, user?.name]);
186
+
187
+ return (
188
+ <AuthContext.Provider value={{ user, setUser }}>
189
+ {children}
190
+ </AuthContext.Provider>
191
+ );
192
+ }
193
+ ```
194
+
195
+ ---
196
+
197
+ ## License
198
+ MIT
@@ -0,0 +1,33 @@
1
+ export interface PulsemetricsResponse {
2
+ success?: boolean;
3
+ message?: string;
4
+ [key: string]: any;
5
+ }
6
+ export interface ITrackWithUserNameParams {
7
+ userId: string;
8
+ userName: string;
9
+ }
10
+ export declare class Pulsemetrics {
11
+ private apiKey;
12
+ private apiUrl;
13
+ /**
14
+ * Creates an instance of Pulsemetrics.
15
+ * @param apiKey The API key passed in headers for authentication.
16
+ */
17
+ constructor(apiKey: string);
18
+ /**
19
+ * Initializes and sends a tracking record for a user.
20
+ * @param userId The unique identifier of the user.
21
+ */
22
+ init(userId: string): Promise<PulsemetricsResponse>;
23
+ /**
24
+ * Sends a DAU tracking record with both a user ID and user name.
25
+ *
26
+ * @remarks Available on Pro and Enterprise plans only. Free and Starter plans are not supported.
27
+ * @param params - User tracking payload.
28
+ * @param params.userId - The unique identifier of the user.
29
+ * @param params.userName - The display name of the user.
30
+ */
31
+ trackWithName({ userId, userName, }: ITrackWithUserNameParams): Promise<PulsemetricsResponse>;
32
+ }
33
+ export default Pulsemetrics;
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Pulsemetrics = void 0;
4
+ class Pulsemetrics {
5
+ /**
6
+ * Creates an instance of Pulsemetrics.
7
+ * @param apiKey The API key passed in headers for authentication.
8
+ */
9
+ constructor(apiKey) {
10
+ this.apiUrl = "https://api.pulsemetrics.in/api/v1/dau";
11
+ if (!apiKey || typeof apiKey !== "string" || apiKey.trim() === "") {
12
+ throw new Error("Pulsemetrics: API key is required and must be a valid string.");
13
+ }
14
+ this.apiKey = apiKey.trim();
15
+ }
16
+ /**
17
+ * Initializes and sends a tracking record for a user.
18
+ * @param userId The unique identifier of the user.
19
+ */
20
+ async init(userId) {
21
+ if (!userId || typeof userId !== "string" || userId.trim() === "") {
22
+ throw new Error("Pulsemetrics: User ID is required and must be a valid string.");
23
+ }
24
+ const response = await fetch(`${this.apiUrl}/track`, {
25
+ method: "POST",
26
+ headers: {
27
+ "Content-Type": "application/json",
28
+ "x-api-key": this.apiKey,
29
+ },
30
+ body: JSON.stringify({ user: userId.trim() }),
31
+ });
32
+ if (!response.ok) {
33
+ const errorBody = await response.text().catch(() => "");
34
+ throw new Error(`Pulsemetrics: Request failed with status ${response.status} (${response.statusText}). ${errorBody}`);
35
+ }
36
+ return (await response.json());
37
+ }
38
+ /**
39
+ * Sends a DAU tracking record with both a user ID and user name.
40
+ *
41
+ * @remarks Available on Pro and Enterprise plans only. Free and Starter plans are not supported.
42
+ * @param params - User tracking payload.
43
+ * @param params.userId - The unique identifier of the user.
44
+ * @param params.userName - The display name of the user.
45
+ */
46
+ async trackWithName({ userId, userName, }) {
47
+ if (!userId || typeof userId !== "string" || userId.trim() === "") {
48
+ throw new Error("Pulsemetrics: User ID is required and must be a valid string.");
49
+ }
50
+ if (!userName ||
51
+ typeof userName !== "string" ||
52
+ userName.trim() === "") {
53
+ throw new Error("Pulsemetrics: User name is required and must be a valid string.");
54
+ }
55
+ const payload = {
56
+ userId: userId.trim(),
57
+ userName: userName.trim(),
58
+ };
59
+ const response = await fetch(`${this.apiUrl}/track-with-name`, {
60
+ method: "POST",
61
+ headers: {
62
+ "Content-Type": "application/json",
63
+ "x-api-key": this.apiKey,
64
+ },
65
+ body: JSON.stringify(payload),
66
+ });
67
+ if (!response.ok) {
68
+ const errorBody = await response.text().catch(() => "");
69
+ throw new Error(`Pulsemetrics: Request failed with status ${response.status} (${response.statusText}). ${errorBody}`);
70
+ }
71
+ return (await response.json());
72
+ }
73
+ }
74
+ exports.Pulsemetrics = Pulsemetrics;
75
+ exports.default = Pulsemetrics;
76
+ if (typeof module !== "undefined" && module.exports) {
77
+ module.exports = Pulsemetrics;
78
+ module.exports.default = Pulsemetrics;
79
+ module.exports.Pulsemetrics = Pulsemetrics;
80
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "pulsemetrics-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Client SDK for tracking Daily Active Users (DAU)",
5
+ "homepage": "https://pulsemetrics.in",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md"
11
+ ],
12
+ "scripts": {
13
+ "build": "tsc"
14
+ },
15
+ "keywords": [
16
+ "pulsemetrics",
17
+ "dau",
18
+ "analytics",
19
+ "tracker",
20
+ "sdk"
21
+ ],
22
+ "author": "Galerin",
23
+ "license": "MIT",
24
+ "devDependencies": {
25
+ "typescript": "^5.0.0"
26
+ }
27
+ }