@whilesmart/engagement 0.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/LICENSE +21 -0
- package/README.md +31 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +148 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/types.d.ts +43 -0
- package/dist/types.js +1 -0
- package/package.json +28 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 WhileSmart
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# WhileSmart Engagement
|
|
2
|
+
|
|
3
|
+
Framework-independent browser event tracking for `whilesmart/eloquent-engagement`.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @whilesmart/engagement
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Use
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createEngagementClient } from '@whilesmart/engagement'
|
|
15
|
+
|
|
16
|
+
const engagement = createEngagementClient({
|
|
17
|
+
endpoint: 'https://api.example.com/api/engagement/events',
|
|
18
|
+
siteKey: 'public-site-key',
|
|
19
|
+
consent: () => analyticsConsentGranted(),
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
engagement.track('signup.started', { plan: 'business' })
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The client records a random visitor ID in local storage and a random session ID in session storage. It derives source attribution from `utm_source`, then the referrer host, then `direct`. Events are batched, retried after failed requests, and flushed with `sendBeacon` when the page becomes hidden.
|
|
26
|
+
|
|
27
|
+
The site key identifies a website. It is not a secret. The server must also restrict accepted browser origins.
|
|
28
|
+
|
|
29
|
+
## License
|
|
30
|
+
|
|
31
|
+
MIT. WhileSmart LTD.
|
package/dist/client.d.ts
ADDED
package/dist/client.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
const visitorStorageKey = 'whilesmart.engagement.visitor';
|
|
2
|
+
const sessionStorageKey = 'whilesmart.engagement.session';
|
|
3
|
+
export function createEngagementClient(options) {
|
|
4
|
+
const batchSize = Math.min(Math.max(options.batchSize ?? 10, 1), 20);
|
|
5
|
+
const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
6
|
+
const browserLocation = options.location ?? globalThis.location;
|
|
7
|
+
const browserDocument = options.document ?? globalThis.document;
|
|
8
|
+
const browserNavigator = options.navigator ?? globalThis.navigator;
|
|
9
|
+
const localStorage = options.storage ?? safeStorage('localStorage');
|
|
10
|
+
const sessionStorage = options.sessionStorage ?? safeStorage('sessionStorage');
|
|
11
|
+
const browserCrypto = options.crypto ?? globalThis.crypto;
|
|
12
|
+
const visitorId = persistentId(localStorage, visitorStorageKey, browserCrypto);
|
|
13
|
+
const sessionId = persistentId(sessionStorage, sessionStorageKey, browserCrypto);
|
|
14
|
+
const queue = [];
|
|
15
|
+
let flushing;
|
|
16
|
+
const onVisibilityChange = () => {
|
|
17
|
+
if (browserDocument?.visibilityState === 'hidden')
|
|
18
|
+
void flush(true);
|
|
19
|
+
};
|
|
20
|
+
browserDocument?.addEventListener('visibilitychange', onVisibilityChange);
|
|
21
|
+
const timer = globalThis.setInterval(() => void flush(), options.flushInterval ?? 5000);
|
|
22
|
+
function track(name, properties, eventOptions = {}) {
|
|
23
|
+
if (options.consent && !options.consent())
|
|
24
|
+
return;
|
|
25
|
+
const event = {
|
|
26
|
+
name,
|
|
27
|
+
visitor_id: visitorId,
|
|
28
|
+
session_id: sessionId,
|
|
29
|
+
occurred_at: new Date().toISOString(),
|
|
30
|
+
};
|
|
31
|
+
const url = eventOptions.url ?? browserLocation?.href;
|
|
32
|
+
const referrer = eventOptions.referrer ?? browserDocument?.referrer;
|
|
33
|
+
const attribution = attributionFrom(browserLocation?.search, referrer);
|
|
34
|
+
const source = eventOptions.source ?? attribution.source;
|
|
35
|
+
if (url)
|
|
36
|
+
event.url = url;
|
|
37
|
+
if (referrer)
|
|
38
|
+
event.referrer = referrer;
|
|
39
|
+
if (source)
|
|
40
|
+
event.source = source;
|
|
41
|
+
if (attribution.utm_medium)
|
|
42
|
+
event.utm_medium = attribution.utm_medium;
|
|
43
|
+
if (attribution.utm_campaign)
|
|
44
|
+
event.utm_campaign = attribution.utm_campaign;
|
|
45
|
+
if (attribution.utm_term)
|
|
46
|
+
event.utm_term = attribution.utm_term;
|
|
47
|
+
if (attribution.utm_content)
|
|
48
|
+
event.utm_content = attribution.utm_content;
|
|
49
|
+
if (attribution.click_id)
|
|
50
|
+
event.click_id = attribution.click_id;
|
|
51
|
+
if (properties && Object.keys(properties).length > 0)
|
|
52
|
+
event.properties = properties;
|
|
53
|
+
queue.push(event);
|
|
54
|
+
if (queue.length >= batchSize)
|
|
55
|
+
void flush();
|
|
56
|
+
}
|
|
57
|
+
function page(properties) {
|
|
58
|
+
track('page.view', properties);
|
|
59
|
+
}
|
|
60
|
+
async function flush(useBeacon = false) {
|
|
61
|
+
if (flushing)
|
|
62
|
+
return flushing;
|
|
63
|
+
if (queue.length === 0)
|
|
64
|
+
return;
|
|
65
|
+
const events = queue.splice(0, batchSize);
|
|
66
|
+
const body = JSON.stringify({ site_key: options.siteKey, events });
|
|
67
|
+
if (useBeacon && browserNavigator?.sendBeacon?.(options.endpoint, new Blob([body], { type: 'application/json' }))) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (!fetcher) {
|
|
71
|
+
queue.unshift(...events);
|
|
72
|
+
throw new Error('No fetch implementation is available');
|
|
73
|
+
}
|
|
74
|
+
flushing = fetcher(options.endpoint, {
|
|
75
|
+
method: 'POST',
|
|
76
|
+
headers: {
|
|
77
|
+
'Content-Type': 'application/json',
|
|
78
|
+
'X-Engagement-Site-Key': options.siteKey,
|
|
79
|
+
},
|
|
80
|
+
body,
|
|
81
|
+
keepalive: true,
|
|
82
|
+
}).then((response) => {
|
|
83
|
+
if (!response.ok)
|
|
84
|
+
throw new Error(`Engagement request failed with status ${response.status}`);
|
|
85
|
+
}).catch((error) => {
|
|
86
|
+
queue.unshift(...events);
|
|
87
|
+
throw error;
|
|
88
|
+
}).finally(() => {
|
|
89
|
+
flushing = undefined;
|
|
90
|
+
});
|
|
91
|
+
return flushing;
|
|
92
|
+
}
|
|
93
|
+
async function destroy() {
|
|
94
|
+
globalThis.clearInterval(timer);
|
|
95
|
+
browserDocument?.removeEventListener('visibilitychange', onVisibilityChange);
|
|
96
|
+
await flush();
|
|
97
|
+
}
|
|
98
|
+
if (options.autoPageViews !== false)
|
|
99
|
+
page();
|
|
100
|
+
return { page, track, flush, destroy };
|
|
101
|
+
}
|
|
102
|
+
function persistentId(storage, key, crypto) {
|
|
103
|
+
const existing = storage?.getItem(key);
|
|
104
|
+
if (existing)
|
|
105
|
+
return existing;
|
|
106
|
+
const value = createId(crypto);
|
|
107
|
+
try {
|
|
108
|
+
storage?.setItem(key, value);
|
|
109
|
+
}
|
|
110
|
+
catch { }
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
function createId(crypto) {
|
|
114
|
+
if (crypto?.randomUUID)
|
|
115
|
+
return crypto.randomUUID();
|
|
116
|
+
const bytes = new Uint8Array(16);
|
|
117
|
+
crypto?.getRandomValues?.(bytes);
|
|
118
|
+
return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('') || `${Date.now()}-${Math.random()}`;
|
|
119
|
+
}
|
|
120
|
+
function safeStorage(name) {
|
|
121
|
+
try {
|
|
122
|
+
return globalThis[name];
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function attributionFrom(search = '', referrer = '') {
|
|
129
|
+
const params = new URLSearchParams(search);
|
|
130
|
+
const campaignSource = params.get('utm_source');
|
|
131
|
+
let source = campaignSource ?? 'direct';
|
|
132
|
+
if (!campaignSource && referrer) {
|
|
133
|
+
try {
|
|
134
|
+
source = new URL(referrer).hostname;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
source = referrer;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
source,
|
|
142
|
+
utm_medium: params.get('utm_medium') ?? undefined,
|
|
143
|
+
utm_campaign: params.get('utm_campaign') ?? undefined,
|
|
144
|
+
utm_term: params.get('utm_term') ?? undefined,
|
|
145
|
+
utm_content: params.get('utm_content') ?? undefined,
|
|
146
|
+
click_id: params.get('gclid') ?? params.get('fbclid') ?? params.get('msclkid') ?? undefined,
|
|
147
|
+
};
|
|
148
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createEngagementClient } from './client.js';
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export type EngagementValue = string | number | boolean | null;
|
|
2
|
+
export type EngagementProperties = Record<string, EngagementValue | EngagementValue[]>;
|
|
3
|
+
export interface EngagementEvent {
|
|
4
|
+
name: string;
|
|
5
|
+
visitor_id: string;
|
|
6
|
+
session_id: string;
|
|
7
|
+
url?: string;
|
|
8
|
+
referrer?: string;
|
|
9
|
+
source?: string;
|
|
10
|
+
utm_medium?: string;
|
|
11
|
+
utm_campaign?: string;
|
|
12
|
+
utm_term?: string;
|
|
13
|
+
utm_content?: string;
|
|
14
|
+
click_id?: string;
|
|
15
|
+
properties?: EngagementProperties;
|
|
16
|
+
occurred_at: string;
|
|
17
|
+
}
|
|
18
|
+
export interface TrackOptions {
|
|
19
|
+
url?: string;
|
|
20
|
+
referrer?: string;
|
|
21
|
+
source?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface EngagementClientOptions {
|
|
24
|
+
endpoint: string;
|
|
25
|
+
siteKey: string;
|
|
26
|
+
consent?: () => boolean;
|
|
27
|
+
autoPageViews?: boolean;
|
|
28
|
+
batchSize?: number;
|
|
29
|
+
flushInterval?: number;
|
|
30
|
+
fetch?: typeof globalThis.fetch;
|
|
31
|
+
storage?: Pick<Storage, 'getItem' | 'setItem'>;
|
|
32
|
+
sessionStorage?: Pick<Storage, 'getItem' | 'setItem'>;
|
|
33
|
+
location?: Pick<Location, 'href' | 'search'>;
|
|
34
|
+
document?: Pick<Document, 'referrer' | 'visibilityState' | 'addEventListener' | 'removeEventListener'>;
|
|
35
|
+
navigator?: Pick<Navigator, 'sendBeacon'>;
|
|
36
|
+
crypto?: Pick<Crypto, 'randomUUID' | 'getRandomValues'>;
|
|
37
|
+
}
|
|
38
|
+
export interface EngagementClient {
|
|
39
|
+
page(properties?: EngagementProperties): void;
|
|
40
|
+
track(name: string, properties?: EngagementProperties, options?: TrackOptions): void;
|
|
41
|
+
flush(useBeacon?: boolean): Promise<void>;
|
|
42
|
+
destroy(): Promise<void>;
|
|
43
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@whilesmart/engagement",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Framework-independent browser engagement tracking for WhileSmart applications.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.json",
|
|
19
|
+
"test": "npm run build && node --test tests/*.test.js"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"typescript": "^5.7.0"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/whilesmartjs/engagement.git"
|
|
27
|
+
}
|
|
28
|
+
}
|