@adhub-so/adhub-nextjs-sdk 0.1.1
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 +205 -0
- package/dist/chunk-NF56G46G.js +140 -0
- package/dist/chunk-NF56G46G.js.map +1 -0
- package/dist/index.cjs +1206 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +133 -0
- package/dist/index.d.ts +133 -0
- package/dist/index.js +1178 -0
- package/dist/index.js.map +1 -0
- package/dist/server.cjs +358 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.d.cts +84 -0
- package/dist/server.d.ts +84 -0
- package/dist/server.js +275 -0
- package/dist/server.js.map +1 -0
- package/dist/testing.cjs +149 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +6 -0
- package/dist/testing.d.ts +6 -0
- package/dist/testing.js +72 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-DMUJO8Kj.d.cts +62 -0
- package/dist/types-DMUJO8Kj.d.ts +62 -0
- package/package.json +63 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1206 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
"use client";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var src_exports = {};
|
|
23
|
+
__export(src_exports, {
|
|
24
|
+
AdHubComponent: () => AdHubComponent,
|
|
25
|
+
getAdHubAnonymousIdCookieName: () => getAdHubAnonymousIdCookieName,
|
|
26
|
+
initAdHub: () => initAdHub,
|
|
27
|
+
readAdHubAnonymousIdFromCookie: () => readAdHubAnonymousIdFromCookie,
|
|
28
|
+
useAdHub: () => useAdHub
|
|
29
|
+
});
|
|
30
|
+
module.exports = __toCommonJS(src_exports);
|
|
31
|
+
var import_react = require("react");
|
|
32
|
+
|
|
33
|
+
// src/identity-cookie.ts
|
|
34
|
+
var COOKIE_PREFIX = "adhub_project_anonymous_id_";
|
|
35
|
+
function hashKey(input) {
|
|
36
|
+
let hash = 2166136261;
|
|
37
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
38
|
+
hash ^= input.charCodeAt(index);
|
|
39
|
+
hash = Math.imul(hash, 16777619);
|
|
40
|
+
}
|
|
41
|
+
return (hash >>> 0).toString(36);
|
|
42
|
+
}
|
|
43
|
+
function validAnonymousId(value) {
|
|
44
|
+
return value !== null && value.length >= 8 && value.length <= 255 && !/\s/.test(value);
|
|
45
|
+
}
|
|
46
|
+
function getAdHubAnonymousIdCookieName(projectKey) {
|
|
47
|
+
return `${COOKIE_PREFIX}${hashKey(projectKey.trim())}`;
|
|
48
|
+
}
|
|
49
|
+
function readAdHubAnonymousIdFromCookie(cookieHeader, projectKey) {
|
|
50
|
+
if (!cookieHeader) return null;
|
|
51
|
+
const cookieName = getAdHubAnonymousIdCookieName(projectKey);
|
|
52
|
+
for (const part of cookieHeader.split(";")) {
|
|
53
|
+
const [rawName, ...rawValue] = part.trim().split("=");
|
|
54
|
+
if (rawName !== cookieName) continue;
|
|
55
|
+
try {
|
|
56
|
+
const value = decodeURIComponent(rawValue.join("="));
|
|
57
|
+
return validAnonymousId(value) ? value : null;
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/utils.ts
|
|
66
|
+
var MAX_PARAM_LENGTH = 2048;
|
|
67
|
+
var MAX_ROUTE_LENGTH = 255;
|
|
68
|
+
var MAX_URL_LENGTH = 8192;
|
|
69
|
+
var MAX_UTM_KEYS = 50;
|
|
70
|
+
var MAX_VALUES_PER_PARAM = 10;
|
|
71
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
72
|
+
var EVENT_TYPE_PATTERN = /^[a-z][a-z0-9_.-]{0,127}$/;
|
|
73
|
+
var TIMEZONE_SUFFIX_PATTERN = /(?:z|[+-]\d{2}:\d{2})$/i;
|
|
74
|
+
var MAX_EVENT_ID_LENGTH = 255;
|
|
75
|
+
var MAX_EVENT_PROPERTIES_LENGTH = 32768;
|
|
76
|
+
var MAX_PROFILE_ID_LENGTH = 255;
|
|
77
|
+
var PROFILE_ID_CONTROL_PATTERN = /[\p{Cc}\p{Cf}]/u;
|
|
78
|
+
function nowIso() {
|
|
79
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
80
|
+
}
|
|
81
|
+
function randomId(prefix) {
|
|
82
|
+
const uuid = globalThis.crypto?.randomUUID?.();
|
|
83
|
+
if (uuid) return `${prefix}_${uuid}`;
|
|
84
|
+
const random = Math.random().toString(36).slice(2);
|
|
85
|
+
return `${prefix}_${Date.now().toString(36)}${random}`;
|
|
86
|
+
}
|
|
87
|
+
function truncate(value) {
|
|
88
|
+
return value.slice(0, MAX_PARAM_LENGTH);
|
|
89
|
+
}
|
|
90
|
+
function unique(values) {
|
|
91
|
+
return [...new Set(values.filter(Boolean).map(truncate))];
|
|
92
|
+
}
|
|
93
|
+
function valuesFor(searchParams, wantedKey) {
|
|
94
|
+
const values = [];
|
|
95
|
+
for (const [key, value] of searchParams.entries()) {
|
|
96
|
+
if (key.toLowerCase() === wantedKey) values.push(value);
|
|
97
|
+
}
|
|
98
|
+
return unique(values).slice(0, MAX_VALUES_PER_PARAM);
|
|
99
|
+
}
|
|
100
|
+
function isUuid(value) {
|
|
101
|
+
return UUID_PATTERN.test(value);
|
|
102
|
+
}
|
|
103
|
+
function normalizeProfileId(value) {
|
|
104
|
+
const normalized = value.trim();
|
|
105
|
+
if (!normalized || [...normalized].length > MAX_PROFILE_ID_LENGTH || PROFILE_ID_CONTROL_PATTERN.test(normalized)) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
return normalized;
|
|
109
|
+
}
|
|
110
|
+
function safePageUrl(input) {
|
|
111
|
+
try {
|
|
112
|
+
const url = new URL(input);
|
|
113
|
+
return `${url.origin}${url.pathname}`.slice(0, MAX_URL_LENGTH);
|
|
114
|
+
} catch {
|
|
115
|
+
return "";
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function safeReferrer(input) {
|
|
119
|
+
if (!input) return null;
|
|
120
|
+
const safe = safePageUrl(input);
|
|
121
|
+
return safe || null;
|
|
122
|
+
}
|
|
123
|
+
function captureTouchpoint(location, referrer, capturedAt = nowIso()) {
|
|
124
|
+
const url = new URL(location.href);
|
|
125
|
+
const clickIds = {
|
|
126
|
+
gclid: valuesFor(url.searchParams, "gclid"),
|
|
127
|
+
gbraid: valuesFor(url.searchParams, "gbraid"),
|
|
128
|
+
wbraid: valuesFor(url.searchParams, "wbraid")
|
|
129
|
+
};
|
|
130
|
+
const utm = {};
|
|
131
|
+
for (const key of [...new Set([...url.searchParams.keys()].map((key2) => key2.toLowerCase()))].filter((candidate) => candidate.startsWith("utm_")).slice(0, MAX_UTM_KEYS)) {
|
|
132
|
+
utm[key] = valuesFor(url.searchParams, key);
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
ahRoute: valuesFor(url.searchParams, "ah_route")[0]?.slice(0, MAX_ROUTE_LENGTH) ?? null,
|
|
136
|
+
clickIds,
|
|
137
|
+
utm,
|
|
138
|
+
landingUrl: safePageUrl(url.href),
|
|
139
|
+
referrer: safeReferrer(referrer),
|
|
140
|
+
// Browsers do not know Google's server-side click timestamp. This is the
|
|
141
|
+
// first-party observation time and is the upper bound available to the SDK.
|
|
142
|
+
clickTime: capturedAt
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function toJsonValue(value) {
|
|
146
|
+
if (value === void 0) return void 0;
|
|
147
|
+
try {
|
|
148
|
+
return JSON.parse(JSON.stringify(value));
|
|
149
|
+
} catch {
|
|
150
|
+
return void 0;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function normalizeEventFields(input) {
|
|
154
|
+
const eventType = input.eventType?.trim().toLowerCase();
|
|
155
|
+
if (!eventType || !EVENT_TYPE_PATTERN.test(eventType) && !isUuid(eventType)) {
|
|
156
|
+
throw new Error(
|
|
157
|
+
"AdHub eventType must be an Event Definition UUID or event key."
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
const occurredAtInput = input.occurredAt?.trim() || nowIso();
|
|
161
|
+
if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {
|
|
162
|
+
throw new Error("AdHub occurredAt must include a timezone offset.");
|
|
163
|
+
}
|
|
164
|
+
const occurredAtDate = new Date(occurredAtInput);
|
|
165
|
+
if (Number.isNaN(occurredAtDate.getTime())) {
|
|
166
|
+
throw new Error("AdHub occurredAt must be a valid ISO-8601 timestamp.");
|
|
167
|
+
}
|
|
168
|
+
const result = {
|
|
169
|
+
eventType,
|
|
170
|
+
occurredAt: occurredAtDate.toISOString()
|
|
171
|
+
};
|
|
172
|
+
if (input.eventId !== void 0) {
|
|
173
|
+
const eventId = input.eventId.trim();
|
|
174
|
+
if (!eventId || eventId.length > MAX_EVENT_ID_LENGTH || [...eventId].some((character) => character.charCodeAt(0) < 32 || character === "\x7F")) {
|
|
175
|
+
throw new Error("AdHub eventId must be 1-255 characters without control characters.");
|
|
176
|
+
}
|
|
177
|
+
result.eventId = eventId;
|
|
178
|
+
}
|
|
179
|
+
if (input.value !== void 0) {
|
|
180
|
+
if (!Number.isFinite(input.value) || input.value < 0) {
|
|
181
|
+
throw new Error("AdHub event value must be a finite non-negative number.");
|
|
182
|
+
}
|
|
183
|
+
result.value = input.value;
|
|
184
|
+
}
|
|
185
|
+
if (input.currency !== void 0) {
|
|
186
|
+
const currency = input.currency.trim().toUpperCase();
|
|
187
|
+
if (!/^[A-Z]{3}$/.test(currency)) {
|
|
188
|
+
throw new Error("AdHub event currency must be a three-letter ISO 4217 code.");
|
|
189
|
+
}
|
|
190
|
+
result.currency = currency;
|
|
191
|
+
}
|
|
192
|
+
if (input.properties !== void 0) {
|
|
193
|
+
const properties = toJsonValue(input.properties);
|
|
194
|
+
if (!properties || typeof properties !== "object" || Array.isArray(properties) || JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH) {
|
|
195
|
+
throw new Error("AdHub event properties must be a JSON object no larger than 32 KiB.");
|
|
196
|
+
}
|
|
197
|
+
result.properties = properties;
|
|
198
|
+
}
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
function normalizeBehaviorEventFields(input) {
|
|
202
|
+
const eventName = input.eventName?.trim().toLowerCase();
|
|
203
|
+
if (!eventName || !EVENT_TYPE_PATTERN.test(eventName)) {
|
|
204
|
+
throw new Error(
|
|
205
|
+
"AdHub behavior eventName must start with a letter and use letters, digits, _, . or -."
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
const occurredAtInput = input.occurredAt?.trim() || nowIso();
|
|
209
|
+
if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {
|
|
210
|
+
throw new Error("AdHub behavior occurredAt must include a timezone offset.");
|
|
211
|
+
}
|
|
212
|
+
const occurredAtDate = new Date(occurredAtInput);
|
|
213
|
+
if (Number.isNaN(occurredAtDate.getTime())) {
|
|
214
|
+
throw new Error("AdHub behavior occurredAt must be a valid ISO-8601 timestamp.");
|
|
215
|
+
}
|
|
216
|
+
const result = {
|
|
217
|
+
eventName,
|
|
218
|
+
occurredAt: occurredAtDate.toISOString()
|
|
219
|
+
};
|
|
220
|
+
if (input.eventId !== void 0) {
|
|
221
|
+
const eventId = input.eventId.trim();
|
|
222
|
+
if (!eventId || eventId.length > MAX_EVENT_ID_LENGTH || [...eventId].some((character) => character.charCodeAt(0) < 32 || character === "\x7F")) {
|
|
223
|
+
throw new Error("AdHub behavior eventId must be 1-255 characters without control characters.");
|
|
224
|
+
}
|
|
225
|
+
result.eventId = eventId;
|
|
226
|
+
}
|
|
227
|
+
if (input.pageUrl !== void 0) {
|
|
228
|
+
const pageUrl = safePageUrl(input.pageUrl);
|
|
229
|
+
if (pageUrl) result.pageUrl = pageUrl;
|
|
230
|
+
}
|
|
231
|
+
if (input.path !== void 0) {
|
|
232
|
+
const path = input.path.trim().slice(0, 2048);
|
|
233
|
+
if (path) result.path = path;
|
|
234
|
+
}
|
|
235
|
+
if (input.title !== void 0) {
|
|
236
|
+
result.title = input.title.trim().slice(0, 512);
|
|
237
|
+
}
|
|
238
|
+
if (input.referrer !== void 0) {
|
|
239
|
+
result.referrer = input.referrer === null ? null : safeReferrer(input.referrer);
|
|
240
|
+
}
|
|
241
|
+
if (input.properties !== void 0) {
|
|
242
|
+
const properties = toJsonValue(input.properties);
|
|
243
|
+
if (!properties || typeof properties !== "object" || Array.isArray(properties) || JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH) {
|
|
244
|
+
throw new Error("AdHub behavior properties must be a JSON object no larger than 32 KiB.");
|
|
245
|
+
}
|
|
246
|
+
result.properties = properties;
|
|
247
|
+
}
|
|
248
|
+
return result;
|
|
249
|
+
}
|
|
250
|
+
function normalizePageviewFields(input = {}) {
|
|
251
|
+
return {
|
|
252
|
+
...normalizeBehaviorEventFields({ eventName: "pageview", ...input }),
|
|
253
|
+
eventName: "pageview"
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function sanitizeProfile(profile) {
|
|
257
|
+
const profileId = normalizeProfileId(profile.profileId);
|
|
258
|
+
if (!profileId) return null;
|
|
259
|
+
const result = { profileId };
|
|
260
|
+
if (profile.email?.trim()) result.email = profile.email.trim().slice(0, 320);
|
|
261
|
+
if (profile.firstName?.trim()) result.firstName = profile.firstName.trim().slice(0, 200);
|
|
262
|
+
if (profile.lastName?.trim()) result.lastName = profile.lastName.trim().slice(0, 200);
|
|
263
|
+
if (profile.properties) {
|
|
264
|
+
const properties = toJsonValue(profile.properties);
|
|
265
|
+
if (properties && typeof properties === "object" && !Array.isArray(properties) && JSON.stringify(properties).length <= 32768) {
|
|
266
|
+
result.properties = properties;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// src/storage.ts
|
|
273
|
+
var COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 395;
|
|
274
|
+
var MAX_QUEUE_SIZE = 100;
|
|
275
|
+
function isPendingRequest(value) {
|
|
276
|
+
if (!value || typeof value !== "object") return false;
|
|
277
|
+
const item = value;
|
|
278
|
+
return typeof item.requestId === "string" && (item.path === "/api/v1/saas/sdk/touchpoints" || item.path === "/api/v1/saas/sdk/identify" || item.path === "/api/v1/saas/sdk/behavior-events" || item.path === "/api/v1/saas/sdk/page-engagements" || item.path === "/api/v1/saas/sdk/events") && typeof item.body === "object" && typeof item.attempts === "number" && typeof item.createdAt === "string";
|
|
279
|
+
}
|
|
280
|
+
var BrowserStore = class {
|
|
281
|
+
constructor(projectKey) {
|
|
282
|
+
this.suffix = getAdHubAnonymousIdCookieName(projectKey).slice("adhub_project_anonymous_id_".length);
|
|
283
|
+
}
|
|
284
|
+
get anonymousKey() {
|
|
285
|
+
return `adhub_project_anonymous_id_${this.suffix}`;
|
|
286
|
+
}
|
|
287
|
+
get queueKey() {
|
|
288
|
+
return `adhub_project_sdk_queue_${this.suffix}`;
|
|
289
|
+
}
|
|
290
|
+
get profileKey() {
|
|
291
|
+
return `adhub_project_profile_id_${this.suffix}`;
|
|
292
|
+
}
|
|
293
|
+
get sessionKey() {
|
|
294
|
+
return `adhub_project_session_${this.suffix}`;
|
|
295
|
+
}
|
|
296
|
+
readAnonymousId() {
|
|
297
|
+
const fromCookie = this.readCookie(this.anonymousKey);
|
|
298
|
+
if (this.validAnonymousId(fromCookie)) return fromCookie;
|
|
299
|
+
const fromLocal = this.readLocal(this.anonymousKey);
|
|
300
|
+
return this.validAnonymousId(fromLocal) ? fromLocal : null;
|
|
301
|
+
}
|
|
302
|
+
writeAnonymousId(anonymousId) {
|
|
303
|
+
this.writeLocal(this.anonymousKey, anonymousId);
|
|
304
|
+
try {
|
|
305
|
+
const secure = window.location.protocol === "https:" ? "; Secure" : "";
|
|
306
|
+
document.cookie = `${this.anonymousKey}=${encodeURIComponent(anonymousId)}; Path=/; Max-Age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secure}`;
|
|
307
|
+
} catch {
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
readProfileId() {
|
|
311
|
+
const stored = this.readLocal(this.profileKey);
|
|
312
|
+
return stored === null ? null : normalizeProfileId(stored);
|
|
313
|
+
}
|
|
314
|
+
writeProfile(profile) {
|
|
315
|
+
this.writeLocal(this.profileKey, profile.profileId);
|
|
316
|
+
}
|
|
317
|
+
clearProfile() {
|
|
318
|
+
try {
|
|
319
|
+
localStorage.removeItem(this.profileKey);
|
|
320
|
+
} catch {
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
readSession(maxAgeMs, now = Date.now()) {
|
|
324
|
+
const raw = this.readLocal(this.sessionKey);
|
|
325
|
+
if (!raw) return null;
|
|
326
|
+
try {
|
|
327
|
+
const value = JSON.parse(raw);
|
|
328
|
+
if (!value || typeof value !== "object") return null;
|
|
329
|
+
const record = value;
|
|
330
|
+
if (typeof record.id !== "string" || typeof record.lastSeenAt !== "number") return null;
|
|
331
|
+
if (!this.validAnonymousId(record.id)) return null;
|
|
332
|
+
if (now - record.lastSeenAt > maxAgeMs) return null;
|
|
333
|
+
return { id: record.id, lastSeenAt: record.lastSeenAt };
|
|
334
|
+
} catch {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
writeSession(id, lastSeenAt = Date.now()) {
|
|
339
|
+
this.writeLocal(this.sessionKey, JSON.stringify({ id, lastSeenAt }));
|
|
340
|
+
}
|
|
341
|
+
loadQueue() {
|
|
342
|
+
const raw = this.readLocal(this.queueKey);
|
|
343
|
+
if (!raw) return [];
|
|
344
|
+
try {
|
|
345
|
+
const value = JSON.parse(raw);
|
|
346
|
+
if (!Array.isArray(value)) return [];
|
|
347
|
+
return value.filter(isPendingRequest).slice(-MAX_QUEUE_SIZE);
|
|
348
|
+
} catch {
|
|
349
|
+
return [];
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
saveQueue(queue) {
|
|
353
|
+
this.writeLocal(this.queueKey, JSON.stringify(queue.slice(-MAX_QUEUE_SIZE)));
|
|
354
|
+
}
|
|
355
|
+
readCookie(name) {
|
|
356
|
+
try {
|
|
357
|
+
for (const part of document.cookie.split(";")) {
|
|
358
|
+
const [rawName, ...rawValue] = part.trim().split("=");
|
|
359
|
+
if (rawName === name) return decodeURIComponent(rawValue.join("="));
|
|
360
|
+
}
|
|
361
|
+
} catch {
|
|
362
|
+
}
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
readLocal(key) {
|
|
366
|
+
try {
|
|
367
|
+
return localStorage.getItem(key);
|
|
368
|
+
} catch {
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
writeLocal(key, value) {
|
|
373
|
+
try {
|
|
374
|
+
localStorage.setItem(key, value);
|
|
375
|
+
} catch {
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
validAnonymousId(value) {
|
|
379
|
+
return value !== null && value.length >= 8 && value.length <= 255 && !/\s/.test(value);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
// src/client.ts
|
|
384
|
+
var DEFAULT_ENDPOINT = "https://api.adhub.so";
|
|
385
|
+
var SDK_NAME = "nextjs";
|
|
386
|
+
var SDK_VERSION = "0.1.0";
|
|
387
|
+
var REQUEST_TIMEOUT_MS = 5e3;
|
|
388
|
+
var RETRY_INTERVAL_MS = 15e3;
|
|
389
|
+
var PAGE_ENGAGEMENT_INTERVAL_MS = 5e3;
|
|
390
|
+
var DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
391
|
+
var BEHAVIOR_EVENTS_PATH = "/api/v1/saas/sdk/behavior-events";
|
|
392
|
+
var PAGE_ENGAGEMENTS_PATH = "/api/v1/saas/sdk/page-engagements";
|
|
393
|
+
var EMPTY_STATE = {
|
|
394
|
+
initialized: false,
|
|
395
|
+
anonymousId: null,
|
|
396
|
+
sessionId: null,
|
|
397
|
+
profileId: null,
|
|
398
|
+
queuedCount: 0,
|
|
399
|
+
sending: false,
|
|
400
|
+
lastSentAt: null,
|
|
401
|
+
lastError: null,
|
|
402
|
+
lastIngest: null,
|
|
403
|
+
capturedTouchpoint: null
|
|
404
|
+
};
|
|
405
|
+
function parseIngestResult(value) {
|
|
406
|
+
if (!value || typeof value !== "object") return null;
|
|
407
|
+
const result = value;
|
|
408
|
+
const accepted = result.accepted;
|
|
409
|
+
const requestId = result.requestId;
|
|
410
|
+
const stored = result.stored;
|
|
411
|
+
const reason = result.reason;
|
|
412
|
+
const isCollectorResult = typeof accepted === "boolean" && typeof requestId === "string" && typeof stored === "boolean" && (reason === null || reason === void 0 || typeof reason === "string");
|
|
413
|
+
if (isCollectorResult) {
|
|
414
|
+
return {
|
|
415
|
+
accepted,
|
|
416
|
+
requestId,
|
|
417
|
+
stored,
|
|
418
|
+
reason: typeof reason === "string" ? reason : null
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
const eventId = result.eventId;
|
|
422
|
+
const externalEventId = result.externalEventId;
|
|
423
|
+
const attributionStatus = result.attributionStatus;
|
|
424
|
+
const attributionReason = result.attributionReason;
|
|
425
|
+
const deliveryStatus = result.deliveryStatus;
|
|
426
|
+
const googleRequestId = result.googleRequestId;
|
|
427
|
+
const isEventTrackResult = typeof eventId === "string" && typeof externalEventId === "string" && typeof attributionStatus === "string";
|
|
428
|
+
if (!isEventTrackResult) return null;
|
|
429
|
+
const eventResult = {
|
|
430
|
+
accepted: true,
|
|
431
|
+
requestId: externalEventId,
|
|
432
|
+
stored: true,
|
|
433
|
+
reason: typeof attributionReason === "string" ? attributionReason : null,
|
|
434
|
+
eventId,
|
|
435
|
+
externalEventId,
|
|
436
|
+
attributionStatus,
|
|
437
|
+
attributionReason: typeof attributionReason === "string" ? attributionReason : null,
|
|
438
|
+
deliveryStatus: typeof deliveryStatus === "string" ? deliveryStatus : null,
|
|
439
|
+
googleRequestId: typeof googleRequestId === "string" ? googleRequestId : null
|
|
440
|
+
};
|
|
441
|
+
if (typeof result.duplicate === "boolean") eventResult.duplicate = result.duplicate;
|
|
442
|
+
if (Array.isArray(result.deliveries)) {
|
|
443
|
+
const deliveries = result.deliveries.filter((item) => {
|
|
444
|
+
if (!item || typeof item !== "object") return false;
|
|
445
|
+
const delivery = item;
|
|
446
|
+
return typeof delivery.bindingId === "string" && typeof delivery.advertisingAccountId === "string" && typeof delivery.conversionActionId === "string" && typeof delivery.status === "string";
|
|
447
|
+
});
|
|
448
|
+
if (deliveries.length) eventResult.deliveries = deliveries;
|
|
449
|
+
}
|
|
450
|
+
return eventResult;
|
|
451
|
+
}
|
|
452
|
+
function browserAvailable() {
|
|
453
|
+
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
454
|
+
}
|
|
455
|
+
function dataAttributePropertyName(attributeName) {
|
|
456
|
+
return attributeName.slice("data-".length).split("-").filter(Boolean).map((part, index) => index === 0 ? part : `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join("");
|
|
457
|
+
}
|
|
458
|
+
function compactElementText(value) {
|
|
459
|
+
const text = value?.replace(/\s+/g, " ").trim().slice(0, 512);
|
|
460
|
+
return text || void 0;
|
|
461
|
+
}
|
|
462
|
+
function normalizeEndpoint(endpoint) {
|
|
463
|
+
const value = endpoint?.trim() || DEFAULT_ENDPOINT;
|
|
464
|
+
if (value.startsWith("/") && !value.startsWith("//")) {
|
|
465
|
+
return value === "/" ? "" : value.replace(/\/$/, "");
|
|
466
|
+
}
|
|
467
|
+
try {
|
|
468
|
+
const parsed = new URL(value);
|
|
469
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
470
|
+
return parsed.toString().replace(/\/$/, "");
|
|
471
|
+
} catch {
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
function errorMessage(error) {
|
|
476
|
+
return error instanceof Error ? error.message : "Unknown SDK delivery error";
|
|
477
|
+
}
|
|
478
|
+
function cloneState(state) {
|
|
479
|
+
return {
|
|
480
|
+
...state,
|
|
481
|
+
capturedTouchpoint: state.capturedTouchpoint ? {
|
|
482
|
+
...state.capturedTouchpoint,
|
|
483
|
+
clickIds: {
|
|
484
|
+
gclid: [...state.capturedTouchpoint.clickIds.gclid],
|
|
485
|
+
gbraid: [...state.capturedTouchpoint.clickIds.gbraid],
|
|
486
|
+
wbraid: [...state.capturedTouchpoint.clickIds.wbraid]
|
|
487
|
+
},
|
|
488
|
+
utm: Object.fromEntries(
|
|
489
|
+
Object.entries(state.capturedTouchpoint.utm).map(([key, values]) => [key, [...values]])
|
|
490
|
+
)
|
|
491
|
+
} : null
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
var AdHubBrowserClient = class {
|
|
495
|
+
constructor() {
|
|
496
|
+
this.state = cloneState(EMPTY_STATE);
|
|
497
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
498
|
+
this.store = null;
|
|
499
|
+
this.queue = [];
|
|
500
|
+
this.endpoint = DEFAULT_ENDPOINT;
|
|
501
|
+
this.projectKey = "";
|
|
502
|
+
this.debug = false;
|
|
503
|
+
this.flushPromise = null;
|
|
504
|
+
this.retryTimer = null;
|
|
505
|
+
this.pageEngagementTimer = null;
|
|
506
|
+
this.pageDebounceTimer = null;
|
|
507
|
+
this.activePageVisit = null;
|
|
508
|
+
this.lifecycleInstalled = false;
|
|
509
|
+
this.pageviewTrackingInstalled = false;
|
|
510
|
+
this.behaviorTrackingInstalled = false;
|
|
511
|
+
this.sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS;
|
|
512
|
+
this.autoFlush = true;
|
|
513
|
+
this.autoPageview = true;
|
|
514
|
+
this.autoPageEngagement = true;
|
|
515
|
+
this.autoTrackOutgoingLinks = true;
|
|
516
|
+
this.autoTrackDataAttributes = true;
|
|
517
|
+
this.trackHashChanges = false;
|
|
518
|
+
this.lastPageSignature = "";
|
|
519
|
+
this.originalPushState = null;
|
|
520
|
+
this.originalReplaceState = null;
|
|
521
|
+
this.patchedPushState = null;
|
|
522
|
+
this.patchedReplaceState = null;
|
|
523
|
+
this.onOnline = () => {
|
|
524
|
+
if (this.autoFlush) void this.flush();
|
|
525
|
+
};
|
|
526
|
+
this.onPageHide = () => {
|
|
527
|
+
this.pausePageVisit();
|
|
528
|
+
if (this.autoFlush) void this.flush();
|
|
529
|
+
};
|
|
530
|
+
this.onVisibilityChange = () => {
|
|
531
|
+
if (document.visibilityState === "hidden") {
|
|
532
|
+
this.pausePageVisit();
|
|
533
|
+
if (this.autoFlush) void this.flush();
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
this.resumePageVisit();
|
|
537
|
+
};
|
|
538
|
+
this.onLocationChange = () => {
|
|
539
|
+
if (this.pageDebounceTimer) clearTimeout(this.pageDebounceTimer);
|
|
540
|
+
this.pageDebounceTimer = setTimeout(() => this.page(), 50);
|
|
541
|
+
};
|
|
542
|
+
this.onPopState = () => {
|
|
543
|
+
window.dispatchEvent(new Event("locationchange"));
|
|
544
|
+
};
|
|
545
|
+
this.onHashChange = () => {
|
|
546
|
+
window.dispatchEvent(new Event("locationchange"));
|
|
547
|
+
};
|
|
548
|
+
this.onDocumentClick = (event) => {
|
|
549
|
+
if (!(event.target instanceof Element)) return;
|
|
550
|
+
if (this.autoTrackDataAttributes) this.trackDataAttributeClick(event.target);
|
|
551
|
+
if (this.autoTrackOutgoingLinks) this.trackOutgoingLinkClick(event.target);
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
init(options) {
|
|
555
|
+
try {
|
|
556
|
+
const projectKey = options.projectKey?.trim();
|
|
557
|
+
const endpoint = normalizeEndpoint(options.endpoint);
|
|
558
|
+
if (!projectKey || !isUuid(projectKey)) {
|
|
559
|
+
this.updateState({ lastError: "AdHub init requires projectKey to be a UUID." });
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
if (!endpoint) {
|
|
563
|
+
this.updateState({
|
|
564
|
+
lastError: "AdHub init requires an HTTP endpoint or same-origin path."
|
|
565
|
+
});
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
if (!browserAvailable()) return;
|
|
569
|
+
if (this.state.initialized && this.projectKey === projectKey && this.endpoint === endpoint) return;
|
|
570
|
+
this.projectKey = projectKey;
|
|
571
|
+
this.endpoint = endpoint;
|
|
572
|
+
this.debug = options.debug ?? false;
|
|
573
|
+
this.autoFlush = options.autoFlush ?? true;
|
|
574
|
+
this.autoPageview = options.autoPageview ?? true;
|
|
575
|
+
this.autoPageEngagement = options.autoPageEngagement ?? true;
|
|
576
|
+
this.autoTrackOutgoingLinks = options.autoTrackOutgoingLinks ?? true;
|
|
577
|
+
this.autoTrackDataAttributes = options.autoTrackDataAttributes ?? true;
|
|
578
|
+
this.trackHashChanges = options.trackHashChanges ?? false;
|
|
579
|
+
this.store = new BrowserStore(projectKey);
|
|
580
|
+
this.queue = this.store.loadQueue();
|
|
581
|
+
this.sessionTimeoutMs = Number.isFinite(options.sessionTimeoutMinutes) ? Math.max(1, Math.min(24 * 60, options.sessionTimeoutMinutes ?? 30)) * 60 * 1e3 : DEFAULT_SESSION_TIMEOUT_MS;
|
|
582
|
+
const anonymousId = this.store.readAnonymousId() ?? randomId("anon");
|
|
583
|
+
this.store.writeAnonymousId(anonymousId);
|
|
584
|
+
const session = this.currentSession();
|
|
585
|
+
const touchpoint = captureTouchpoint(window.location, document.referrer);
|
|
586
|
+
this.state = {
|
|
587
|
+
initialized: true,
|
|
588
|
+
anonymousId,
|
|
589
|
+
sessionId: session,
|
|
590
|
+
profileId: this.store.readProfileId(),
|
|
591
|
+
queuedCount: this.queue.length,
|
|
592
|
+
sending: false,
|
|
593
|
+
lastSentAt: null,
|
|
594
|
+
lastError: null,
|
|
595
|
+
lastIngest: null,
|
|
596
|
+
capturedTouchpoint: touchpoint
|
|
597
|
+
};
|
|
598
|
+
this.emit();
|
|
599
|
+
let timezone = null;
|
|
600
|
+
try {
|
|
601
|
+
timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || null;
|
|
602
|
+
} catch {
|
|
603
|
+
}
|
|
604
|
+
const data = {
|
|
605
|
+
...touchpoint,
|
|
606
|
+
sessionId: session,
|
|
607
|
+
locale: navigator.language || null,
|
|
608
|
+
timezone
|
|
609
|
+
};
|
|
610
|
+
this.enqueue("/api/v1/saas/sdk/touchpoints", "touchpoint.capture", data);
|
|
611
|
+
if (this.autoPageview) this.page();
|
|
612
|
+
this.installLifecycle();
|
|
613
|
+
if (this.autoPageview) this.installPageviewTracking();
|
|
614
|
+
if (this.autoTrackOutgoingLinks || this.autoTrackDataAttributes) {
|
|
615
|
+
this.installBehaviorTracking();
|
|
616
|
+
}
|
|
617
|
+
this.scheduleFlush();
|
|
618
|
+
} catch (error) {
|
|
619
|
+
this.reportError(error);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
identify(input) {
|
|
623
|
+
try {
|
|
624
|
+
if (!this.state.initialized || !this.store) {
|
|
625
|
+
this.updateState({ lastError: "Call init() before identify()." });
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
const profile = sanitizeProfile(input);
|
|
629
|
+
if (!profile) {
|
|
630
|
+
this.updateState({
|
|
631
|
+
lastError: "identify() requires profileId to be 1-255 characters without control characters."
|
|
632
|
+
});
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const dataProfile = { profileId: profile.profileId };
|
|
636
|
+
if (profile.email !== void 0) dataProfile.email = profile.email;
|
|
637
|
+
if (profile.firstName !== void 0) dataProfile.firstName = profile.firstName;
|
|
638
|
+
if (profile.lastName !== void 0) dataProfile.lastName = profile.lastName;
|
|
639
|
+
if (profile.properties !== void 0) {
|
|
640
|
+
const properties = toJsonValue(profile.properties);
|
|
641
|
+
if (properties !== void 0) dataProfile.properties = properties;
|
|
642
|
+
}
|
|
643
|
+
const data = {
|
|
644
|
+
profile: dataProfile,
|
|
645
|
+
identifiedAt: nowIso(),
|
|
646
|
+
pageUrl: safePageUrl(window.location.href)
|
|
647
|
+
};
|
|
648
|
+
this.store.writeProfile(profile);
|
|
649
|
+
this.updateState({ profileId: profile.profileId, lastError: null });
|
|
650
|
+
this.enqueue("/api/v1/saas/sdk/identify", "profile.identify", data);
|
|
651
|
+
this.scheduleFlush();
|
|
652
|
+
} catch (error) {
|
|
653
|
+
this.reportError(error);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
page(input = {}) {
|
|
657
|
+
try {
|
|
658
|
+
if (!this.state.initialized || !this.store) {
|
|
659
|
+
this.updateState({ lastError: "Call init() before page()." });
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
const normalized = normalizePageviewFields({
|
|
663
|
+
...this.currentPageFields(),
|
|
664
|
+
...input
|
|
665
|
+
});
|
|
666
|
+
const signature = [
|
|
667
|
+
normalized.pageUrl,
|
|
668
|
+
normalized.path,
|
|
669
|
+
normalized.title,
|
|
670
|
+
normalized.eventId
|
|
671
|
+
].join("|");
|
|
672
|
+
if (!input.eventId && signature === this.lastPageSignature) return;
|
|
673
|
+
this.lastPageSignature = signature;
|
|
674
|
+
this.finishPageVisit();
|
|
675
|
+
const pageViewId = normalized.eventId ?? randomId("page");
|
|
676
|
+
const sessionId = this.enqueueBehaviorEvent({ ...normalized, eventId: pageViewId });
|
|
677
|
+
if (this.autoPageEngagement) {
|
|
678
|
+
this.startPageVisit(normalized, pageViewId, sessionId);
|
|
679
|
+
}
|
|
680
|
+
} catch (error) {
|
|
681
|
+
this.reportError(error);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
behavior(input) {
|
|
685
|
+
try {
|
|
686
|
+
if (!this.state.initialized || !this.store) {
|
|
687
|
+
this.updateState({ lastError: "Call init() before behavior()." });
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
const normalized = normalizeBehaviorEventFields({
|
|
691
|
+
...this.currentPageFields(),
|
|
692
|
+
...input
|
|
693
|
+
});
|
|
694
|
+
this.enqueueBehaviorEvent(normalized);
|
|
695
|
+
} catch (error) {
|
|
696
|
+
this.reportError(error);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
track(input) {
|
|
700
|
+
try {
|
|
701
|
+
if (!this.state.initialized || !this.store) {
|
|
702
|
+
this.updateState({ lastError: "Call init() before track()." });
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
const profileId = this.state.profileId;
|
|
706
|
+
if (!profileId) {
|
|
707
|
+
this.updateState({ lastError: "Call identify() before track()." });
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
const normalized = normalizeEventFields(input);
|
|
711
|
+
const data = {
|
|
712
|
+
profileId,
|
|
713
|
+
eventType: normalized.eventType,
|
|
714
|
+
occurredAt: normalized.occurredAt
|
|
715
|
+
};
|
|
716
|
+
if (normalized.eventId !== void 0) data.eventId = normalized.eventId;
|
|
717
|
+
if (normalized.value !== void 0) data.value = normalized.value;
|
|
718
|
+
if (normalized.currency !== void 0) data.currency = normalized.currency;
|
|
719
|
+
if (normalized.properties !== void 0) data.properties = normalized.properties;
|
|
720
|
+
this.updateState({ lastError: null });
|
|
721
|
+
this.enqueue("/api/v1/saas/sdk/events", "event.track", data);
|
|
722
|
+
this.scheduleFlush();
|
|
723
|
+
} catch (error) {
|
|
724
|
+
this.reportError(error);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
reset() {
|
|
728
|
+
try {
|
|
729
|
+
if (!this.state.initialized || !this.store) return;
|
|
730
|
+
this.finishPageVisit();
|
|
731
|
+
const anonymousId = randomId("anon");
|
|
732
|
+
this.store.clearProfile();
|
|
733
|
+
this.store.writeAnonymousId(anonymousId);
|
|
734
|
+
const sessionId = randomId("sess");
|
|
735
|
+
this.store.writeSession(sessionId);
|
|
736
|
+
this.updateState({ anonymousId, sessionId, profileId: null, lastError: null });
|
|
737
|
+
this.lastPageSignature = "";
|
|
738
|
+
if (this.autoPageview) this.page();
|
|
739
|
+
} catch (error) {
|
|
740
|
+
this.reportError(error);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
flush() {
|
|
744
|
+
if (this.flushPromise) return this.flushPromise;
|
|
745
|
+
this.flushPromise = this.performFlush().catch((error) => {
|
|
746
|
+
this.reportError(error);
|
|
747
|
+
return { sent: 0, failed: this.queue.length, remaining: this.queue.length };
|
|
748
|
+
}).finally(() => {
|
|
749
|
+
this.flushPromise = null;
|
|
750
|
+
});
|
|
751
|
+
return this.flushPromise;
|
|
752
|
+
}
|
|
753
|
+
getState() {
|
|
754
|
+
return cloneState(this.state);
|
|
755
|
+
}
|
|
756
|
+
subscribe(listener) {
|
|
757
|
+
this.listeners.add(listener);
|
|
758
|
+
try {
|
|
759
|
+
listener(this.getState());
|
|
760
|
+
} catch {
|
|
761
|
+
}
|
|
762
|
+
return () => this.listeners.delete(listener);
|
|
763
|
+
}
|
|
764
|
+
destroy() {
|
|
765
|
+
this.finishPageVisit();
|
|
766
|
+
if (browserAvailable() && this.lifecycleInstalled) {
|
|
767
|
+
window.removeEventListener("online", this.onOnline);
|
|
768
|
+
window.removeEventListener("pagehide", this.onPageHide);
|
|
769
|
+
document.removeEventListener("visibilitychange", this.onVisibilityChange);
|
|
770
|
+
this.lifecycleInstalled = false;
|
|
771
|
+
}
|
|
772
|
+
if (browserAvailable() && this.pageviewTrackingInstalled) {
|
|
773
|
+
window.removeEventListener("locationchange", this.onLocationChange);
|
|
774
|
+
window.removeEventListener("popstate", this.onPopState);
|
|
775
|
+
window.removeEventListener("hashchange", this.onHashChange);
|
|
776
|
+
if (this.patchedPushState && history.pushState === this.patchedPushState && this.originalPushState) {
|
|
777
|
+
history.pushState = this.originalPushState;
|
|
778
|
+
}
|
|
779
|
+
if (this.patchedReplaceState && history.replaceState === this.patchedReplaceState && this.originalReplaceState) {
|
|
780
|
+
history.replaceState = this.originalReplaceState;
|
|
781
|
+
}
|
|
782
|
+
this.pageviewTrackingInstalled = false;
|
|
783
|
+
this.originalPushState = null;
|
|
784
|
+
this.originalReplaceState = null;
|
|
785
|
+
this.patchedPushState = null;
|
|
786
|
+
this.patchedReplaceState = null;
|
|
787
|
+
}
|
|
788
|
+
if (browserAvailable() && this.behaviorTrackingInstalled) {
|
|
789
|
+
document.removeEventListener("click", this.onDocumentClick, true);
|
|
790
|
+
this.behaviorTrackingInstalled = false;
|
|
791
|
+
}
|
|
792
|
+
if (this.pageDebounceTimer) {
|
|
793
|
+
clearTimeout(this.pageDebounceTimer);
|
|
794
|
+
this.pageDebounceTimer = null;
|
|
795
|
+
}
|
|
796
|
+
if (this.retryTimer) {
|
|
797
|
+
clearInterval(this.retryTimer);
|
|
798
|
+
this.retryTimer = null;
|
|
799
|
+
}
|
|
800
|
+
if (this.pageEngagementTimer) {
|
|
801
|
+
clearInterval(this.pageEngagementTimer);
|
|
802
|
+
this.pageEngagementTimer = null;
|
|
803
|
+
}
|
|
804
|
+
this.listeners.clear();
|
|
805
|
+
}
|
|
806
|
+
enqueue(path, type, data) {
|
|
807
|
+
if (!this.state.anonymousId || !this.store) return;
|
|
808
|
+
const requestId = randomId("req");
|
|
809
|
+
const body = {
|
|
810
|
+
schemaVersion: "1.0",
|
|
811
|
+
type,
|
|
812
|
+
requestId,
|
|
813
|
+
sentAt: nowIso(),
|
|
814
|
+
projectKey: this.projectKey,
|
|
815
|
+
anonymousId: this.state.anonymousId,
|
|
816
|
+
data
|
|
817
|
+
};
|
|
818
|
+
this.queue.push({ requestId, path, body, attempts: 0, createdAt: body.sentAt });
|
|
819
|
+
this.queue = this.queue.slice(-100);
|
|
820
|
+
this.persistQueue();
|
|
821
|
+
}
|
|
822
|
+
currentSession() {
|
|
823
|
+
if (!this.store) return randomId("sess");
|
|
824
|
+
const existing = this.store.readSession(this.sessionTimeoutMs);
|
|
825
|
+
const sessionId = existing?.id ?? randomId("sess");
|
|
826
|
+
this.store.writeSession(sessionId);
|
|
827
|
+
return sessionId;
|
|
828
|
+
}
|
|
829
|
+
currentPageFields() {
|
|
830
|
+
return {
|
|
831
|
+
pageUrl: safePageUrl(window.location.href),
|
|
832
|
+
path: window.location.pathname || "/",
|
|
833
|
+
title: document.title,
|
|
834
|
+
referrer: document.referrer || null
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
enqueueBehaviorEvent(normalized) {
|
|
838
|
+
const sessionId = this.currentSession();
|
|
839
|
+
if (sessionId !== this.state.sessionId) this.updateState({ sessionId });
|
|
840
|
+
const data = {
|
|
841
|
+
eventName: normalized.eventName,
|
|
842
|
+
occurredAt: normalized.occurredAt,
|
|
843
|
+
sessionId
|
|
844
|
+
};
|
|
845
|
+
if (this.state.profileId) data.profileId = this.state.profileId;
|
|
846
|
+
if (normalized.eventId !== void 0) data.eventId = normalized.eventId;
|
|
847
|
+
if (normalized.pageUrl !== void 0) data.pageUrl = normalized.pageUrl;
|
|
848
|
+
if (normalized.path !== void 0) data.path = normalized.path;
|
|
849
|
+
if (normalized.title !== void 0) data.title = normalized.title;
|
|
850
|
+
if (normalized.referrer !== void 0) data.referrer = normalized.referrer;
|
|
851
|
+
if (normalized.properties !== void 0) data.properties = normalized.properties;
|
|
852
|
+
this.updateState({ lastError: null });
|
|
853
|
+
this.enqueue(BEHAVIOR_EVENTS_PATH, "behavior.event", data);
|
|
854
|
+
this.scheduleFlush();
|
|
855
|
+
return sessionId;
|
|
856
|
+
}
|
|
857
|
+
startPageVisit(normalized, pageViewId, sessionId) {
|
|
858
|
+
const now = Date.now();
|
|
859
|
+
this.activePageVisit = {
|
|
860
|
+
pageViewId,
|
|
861
|
+
sessionId,
|
|
862
|
+
startedAtMs: now,
|
|
863
|
+
activeSinceMs: document.visibilityState === "hidden" ? null : now,
|
|
864
|
+
activeDurationMs: 0,
|
|
865
|
+
lastQueuedDurationSeconds: 0,
|
|
866
|
+
pageUrl: normalized.pageUrl ?? safePageUrl(window.location.href),
|
|
867
|
+
path: normalized.path ?? (window.location.pathname || "/"),
|
|
868
|
+
...normalized.title !== void 0 ? { title: normalized.title } : {},
|
|
869
|
+
...normalized.referrer !== void 0 ? { referrer: normalized.referrer } : {}
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
checkpointPageVisit(now = Date.now()) {
|
|
873
|
+
const visit = this.activePageVisit;
|
|
874
|
+
if (!visit || visit.activeSinceMs === null) return;
|
|
875
|
+
visit.activeDurationMs += Math.max(0, now - visit.activeSinceMs);
|
|
876
|
+
visit.activeSinceMs = now;
|
|
877
|
+
this.store?.writeSession(visit.sessionId, now);
|
|
878
|
+
}
|
|
879
|
+
queuePageEngagement() {
|
|
880
|
+
const visit = this.activePageVisit;
|
|
881
|
+
if (!visit) return;
|
|
882
|
+
const durationSeconds = Math.floor(visit.activeDurationMs / 1e3);
|
|
883
|
+
if (durationSeconds < 1 || durationSeconds <= visit.lastQueuedDurationSeconds) return;
|
|
884
|
+
const data = {
|
|
885
|
+
pageViewId: visit.pageViewId,
|
|
886
|
+
sessionId: visit.sessionId,
|
|
887
|
+
startedAt: new Date(visit.startedAtMs).toISOString(),
|
|
888
|
+
occurredAt: nowIso(),
|
|
889
|
+
durationSeconds,
|
|
890
|
+
pageUrl: visit.pageUrl,
|
|
891
|
+
path: visit.path
|
|
892
|
+
};
|
|
893
|
+
if (this.state.profileId) data.profileId = this.state.profileId;
|
|
894
|
+
if (visit.title !== void 0) data.title = visit.title;
|
|
895
|
+
if (visit.referrer !== void 0) data.referrer = visit.referrer;
|
|
896
|
+
this.queue = this.queue.filter((item) => {
|
|
897
|
+
if (item.path !== PAGE_ENGAGEMENTS_PATH) return true;
|
|
898
|
+
const body = item.body;
|
|
899
|
+
return body.data?.pageViewId !== visit.pageViewId;
|
|
900
|
+
});
|
|
901
|
+
visit.lastQueuedDurationSeconds = durationSeconds;
|
|
902
|
+
this.enqueue(PAGE_ENGAGEMENTS_PATH, "page.engagement", data);
|
|
903
|
+
this.scheduleFlush();
|
|
904
|
+
}
|
|
905
|
+
pausePageVisit() {
|
|
906
|
+
const visit = this.activePageVisit;
|
|
907
|
+
if (!visit || visit.activeSinceMs === null) return;
|
|
908
|
+
this.checkpointPageVisit();
|
|
909
|
+
visit.activeSinceMs = null;
|
|
910
|
+
this.queuePageEngagement();
|
|
911
|
+
}
|
|
912
|
+
resumePageVisit() {
|
|
913
|
+
const visit = this.activePageVisit;
|
|
914
|
+
if (!visit || visit.activeSinceMs !== null) return;
|
|
915
|
+
const session = this.store?.readSession(this.sessionTimeoutMs);
|
|
916
|
+
if (!session || session.id !== visit.sessionId) {
|
|
917
|
+
this.activePageVisit = null;
|
|
918
|
+
this.lastPageSignature = "";
|
|
919
|
+
if (this.autoPageview) this.page();
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
visit.activeSinceMs = Date.now();
|
|
923
|
+
}
|
|
924
|
+
finishPageVisit() {
|
|
925
|
+
if (!this.activePageVisit) return;
|
|
926
|
+
this.checkpointPageVisit();
|
|
927
|
+
this.queuePageEngagement();
|
|
928
|
+
this.activePageVisit = null;
|
|
929
|
+
}
|
|
930
|
+
async performFlush() {
|
|
931
|
+
if (!this.state.initialized || !this.queue.length || typeof fetch !== "function") {
|
|
932
|
+
return { sent: 0, failed: 0, remaining: this.queue.length };
|
|
933
|
+
}
|
|
934
|
+
this.updateState({ sending: true });
|
|
935
|
+
let sent = 0;
|
|
936
|
+
let failed = 0;
|
|
937
|
+
while (this.queue.length) {
|
|
938
|
+
const item = this.queue[0];
|
|
939
|
+
if (!item) break;
|
|
940
|
+
const controller = new AbortController();
|
|
941
|
+
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
942
|
+
try {
|
|
943
|
+
const response = await fetch(`${this.endpoint}${item.path}`, {
|
|
944
|
+
method: "POST",
|
|
945
|
+
headers: {
|
|
946
|
+
"Content-Type": "application/json",
|
|
947
|
+
"Idempotency-Key": item.requestId,
|
|
948
|
+
"X-AdHub-Project-Key": this.projectKey,
|
|
949
|
+
"X-AdHub-SDK": SDK_NAME,
|
|
950
|
+
"X-AdHub-SDK-Version": SDK_VERSION
|
|
951
|
+
},
|
|
952
|
+
body: JSON.stringify(item.body),
|
|
953
|
+
keepalive: true,
|
|
954
|
+
credentials: "omit",
|
|
955
|
+
signal: controller.signal
|
|
956
|
+
});
|
|
957
|
+
if (response.ok) {
|
|
958
|
+
let ingestResult = null;
|
|
959
|
+
try {
|
|
960
|
+
ingestResult = parseIngestResult(await response.json());
|
|
961
|
+
} catch {
|
|
962
|
+
}
|
|
963
|
+
this.removeRequest(item.requestId);
|
|
964
|
+
sent += 1;
|
|
965
|
+
this.updateState({
|
|
966
|
+
lastSentAt: nowIso(),
|
|
967
|
+
lastError: null,
|
|
968
|
+
...ingestResult ? { lastIngest: ingestResult } : {}
|
|
969
|
+
});
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
failed += 1;
|
|
973
|
+
const message = `AdHub endpoint returned HTTP ${response.status}.`;
|
|
974
|
+
const retryable = response.status === 408 || response.status === 429 || response.status >= 500;
|
|
975
|
+
if (retryable) {
|
|
976
|
+
item.attempts += 1;
|
|
977
|
+
} else {
|
|
978
|
+
this.removeRequest(item.requestId);
|
|
979
|
+
}
|
|
980
|
+
this.updateState({ lastError: message });
|
|
981
|
+
this.log(message);
|
|
982
|
+
if (retryable) break;
|
|
983
|
+
} catch (error) {
|
|
984
|
+
failed += 1;
|
|
985
|
+
item.attempts += 1;
|
|
986
|
+
this.updateState({ lastError: errorMessage(error) });
|
|
987
|
+
this.log(errorMessage(error));
|
|
988
|
+
break;
|
|
989
|
+
} finally {
|
|
990
|
+
clearTimeout(timeout);
|
|
991
|
+
this.persistQueue();
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
this.updateState({ sending: false, queuedCount: this.queue.length });
|
|
995
|
+
return { sent, failed, remaining: this.queue.length };
|
|
996
|
+
}
|
|
997
|
+
removeRequest(requestId) {
|
|
998
|
+
this.queue = this.queue.filter((item) => item.requestId !== requestId);
|
|
999
|
+
}
|
|
1000
|
+
persistQueue() {
|
|
1001
|
+
this.store?.saveQueue(this.queue);
|
|
1002
|
+
this.updateState({ queuedCount: this.queue.length });
|
|
1003
|
+
}
|
|
1004
|
+
installLifecycle() {
|
|
1005
|
+
if (this.lifecycleInstalled) return;
|
|
1006
|
+
window.addEventListener("online", this.onOnline);
|
|
1007
|
+
window.addEventListener("pagehide", this.onPageHide);
|
|
1008
|
+
document.addEventListener("visibilitychange", this.onVisibilityChange);
|
|
1009
|
+
if (this.autoFlush) {
|
|
1010
|
+
this.retryTimer = setInterval(() => {
|
|
1011
|
+
if (this.queue.length) void this.flush();
|
|
1012
|
+
}, RETRY_INTERVAL_MS);
|
|
1013
|
+
}
|
|
1014
|
+
if (this.autoPageEngagement) {
|
|
1015
|
+
this.pageEngagementTimer = setInterval(() => {
|
|
1016
|
+
if (document.visibilityState === "hidden") return;
|
|
1017
|
+
this.checkpointPageVisit();
|
|
1018
|
+
this.queuePageEngagement();
|
|
1019
|
+
}, PAGE_ENGAGEMENT_INTERVAL_MS);
|
|
1020
|
+
}
|
|
1021
|
+
this.lifecycleInstalled = true;
|
|
1022
|
+
}
|
|
1023
|
+
installPageviewTracking() {
|
|
1024
|
+
if (this.pageviewTrackingInstalled) return;
|
|
1025
|
+
this.originalPushState = history.pushState;
|
|
1026
|
+
this.originalReplaceState = history.replaceState;
|
|
1027
|
+
const dispatchLocationChange = () => {
|
|
1028
|
+
window.dispatchEvent(new Event("locationchange"));
|
|
1029
|
+
};
|
|
1030
|
+
const originalPushState = this.originalPushState;
|
|
1031
|
+
const originalReplaceState = this.originalReplaceState;
|
|
1032
|
+
this.patchedPushState = function pushState(...args) {
|
|
1033
|
+
const result = originalPushState.apply(this, args);
|
|
1034
|
+
dispatchLocationChange();
|
|
1035
|
+
return result;
|
|
1036
|
+
};
|
|
1037
|
+
this.patchedReplaceState = function replaceState(...args) {
|
|
1038
|
+
const result = originalReplaceState.apply(this, args);
|
|
1039
|
+
dispatchLocationChange();
|
|
1040
|
+
return result;
|
|
1041
|
+
};
|
|
1042
|
+
history.pushState = this.patchedPushState;
|
|
1043
|
+
history.replaceState = this.patchedReplaceState;
|
|
1044
|
+
window.addEventListener("locationchange", this.onLocationChange);
|
|
1045
|
+
window.addEventListener("popstate", this.onPopState);
|
|
1046
|
+
if (this.trackHashChanges) window.addEventListener("hashchange", this.onHashChange);
|
|
1047
|
+
this.pageviewTrackingInstalled = true;
|
|
1048
|
+
}
|
|
1049
|
+
installBehaviorTracking() {
|
|
1050
|
+
if (this.behaviorTrackingInstalled) return;
|
|
1051
|
+
document.addEventListener("click", this.onDocumentClick, true);
|
|
1052
|
+
this.behaviorTrackingInstalled = true;
|
|
1053
|
+
}
|
|
1054
|
+
trackDataAttributeClick(target) {
|
|
1055
|
+
const element = target.closest("[data-adhub-track], [data-track]");
|
|
1056
|
+
if (!element) return;
|
|
1057
|
+
const eventName = element.getAttribute("data-adhub-track") ?? element.getAttribute("data-track");
|
|
1058
|
+
if (!eventName) return;
|
|
1059
|
+
const properties = {};
|
|
1060
|
+
for (const attribute of Array.from(element.attributes)) {
|
|
1061
|
+
if (!attribute.name.startsWith("data-") || attribute.name === "data-adhub-track" || attribute.name === "data-track") {
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
const propertyName = dataAttributePropertyName(attribute.name);
|
|
1065
|
+
if (propertyName) properties[propertyName] = attribute.value;
|
|
1066
|
+
}
|
|
1067
|
+
this.behavior({
|
|
1068
|
+
eventName,
|
|
1069
|
+
...Object.keys(properties).length ? { properties } : {}
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
trackOutgoingLinkClick(target) {
|
|
1073
|
+
const link = target.closest("a[href]");
|
|
1074
|
+
const href = link?.getAttribute("href");
|
|
1075
|
+
if (!link || !href) return;
|
|
1076
|
+
try {
|
|
1077
|
+
const url = new URL(href, window.location.href);
|
|
1078
|
+
if (!["http:", "https:"].includes(url.protocol)) return;
|
|
1079
|
+
if (url.hostname === window.location.hostname) return;
|
|
1080
|
+
const properties = {
|
|
1081
|
+
href: safePageUrl(url.href)
|
|
1082
|
+
};
|
|
1083
|
+
const text = compactElementText(
|
|
1084
|
+
link.innerText || link.textContent || link.getAttribute("title") || target.getAttribute("alt") || target.getAttribute("title")
|
|
1085
|
+
);
|
|
1086
|
+
if (text) properties.text = text;
|
|
1087
|
+
if (link.target) properties.target = link.target;
|
|
1088
|
+
this.behavior({
|
|
1089
|
+
eventName: "link_out",
|
|
1090
|
+
properties
|
|
1091
|
+
});
|
|
1092
|
+
} catch {
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
scheduleFlush() {
|
|
1096
|
+
if (this.autoFlush) queueMicrotask(() => void this.flush());
|
|
1097
|
+
}
|
|
1098
|
+
updateState(patch) {
|
|
1099
|
+
this.state = { ...this.state, ...patch };
|
|
1100
|
+
this.emit();
|
|
1101
|
+
}
|
|
1102
|
+
emit() {
|
|
1103
|
+
const state = this.getState();
|
|
1104
|
+
for (const listener of this.listeners) {
|
|
1105
|
+
try {
|
|
1106
|
+
listener(state);
|
|
1107
|
+
} catch {
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
reportError(error) {
|
|
1112
|
+
const message = errorMessage(error);
|
|
1113
|
+
this.updateState({ lastError: message, sending: false });
|
|
1114
|
+
this.log(message);
|
|
1115
|
+
}
|
|
1116
|
+
log(message) {
|
|
1117
|
+
if (this.debug && typeof console !== "undefined") console.warn(`[AdHub SDK] ${message}`);
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
function createAdHubClient() {
|
|
1121
|
+
return new AdHubBrowserClient();
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// src/index.ts
|
|
1125
|
+
var adhub = createAdHubClient();
|
|
1126
|
+
var serverSnapshot = adhub.getState();
|
|
1127
|
+
var currentSnapshot = serverSnapshot;
|
|
1128
|
+
function refreshSnapshot() {
|
|
1129
|
+
currentSnapshot = adhub.getState();
|
|
1130
|
+
}
|
|
1131
|
+
function subscribe(listener) {
|
|
1132
|
+
return adhub.subscribe((state) => {
|
|
1133
|
+
currentSnapshot = state;
|
|
1134
|
+
listener();
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
var methods = {
|
|
1138
|
+
identify(profile) {
|
|
1139
|
+
adhub.identify(profile);
|
|
1140
|
+
refreshSnapshot();
|
|
1141
|
+
},
|
|
1142
|
+
page(input) {
|
|
1143
|
+
adhub.page(input);
|
|
1144
|
+
refreshSnapshot();
|
|
1145
|
+
},
|
|
1146
|
+
behavior(event) {
|
|
1147
|
+
adhub.behavior(event);
|
|
1148
|
+
refreshSnapshot();
|
|
1149
|
+
},
|
|
1150
|
+
track(event) {
|
|
1151
|
+
adhub.track(event);
|
|
1152
|
+
refreshSnapshot();
|
|
1153
|
+
},
|
|
1154
|
+
reset() {
|
|
1155
|
+
adhub.reset();
|
|
1156
|
+
refreshSnapshot();
|
|
1157
|
+
},
|
|
1158
|
+
async flush() {
|
|
1159
|
+
const result = await adhub.flush();
|
|
1160
|
+
refreshSnapshot();
|
|
1161
|
+
return result;
|
|
1162
|
+
},
|
|
1163
|
+
getState() {
|
|
1164
|
+
return adhub.getState();
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
function initAdHub(options) {
|
|
1168
|
+
adhub.init(options);
|
|
1169
|
+
refreshSnapshot();
|
|
1170
|
+
}
|
|
1171
|
+
function AdHubComponent({ profile, profileId, ...options }) {
|
|
1172
|
+
const identifiedProfile = profile !== void 0 ? profile : profileId !== void 0 ? profileId ? { profileId } : null : void 0;
|
|
1173
|
+
const optionsKey = JSON.stringify(options);
|
|
1174
|
+
const profileKey = JSON.stringify(identifiedProfile);
|
|
1175
|
+
(0, import_react.useEffect)(() => {
|
|
1176
|
+
initAdHub(options);
|
|
1177
|
+
}, [optionsKey]);
|
|
1178
|
+
(0, import_react.useEffect)(() => {
|
|
1179
|
+
const currentProfileId = methods.getState().profileId;
|
|
1180
|
+
if (identifiedProfile === void 0) return;
|
|
1181
|
+
if (!identifiedProfile) {
|
|
1182
|
+
if (currentProfileId) methods.reset();
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
if (currentProfileId && currentProfileId !== identifiedProfile.profileId) methods.reset();
|
|
1186
|
+
if (methods.getState().profileId !== identifiedProfile.profileId) methods.identify(identifiedProfile);
|
|
1187
|
+
}, [profileKey]);
|
|
1188
|
+
return null;
|
|
1189
|
+
}
|
|
1190
|
+
function useAdHub() {
|
|
1191
|
+
const state = (0, import_react.useSyncExternalStore)(
|
|
1192
|
+
subscribe,
|
|
1193
|
+
() => currentSnapshot,
|
|
1194
|
+
() => serverSnapshot
|
|
1195
|
+
);
|
|
1196
|
+
return (0, import_react.useMemo)(() => ({ state, ...methods }), [state]);
|
|
1197
|
+
}
|
|
1198
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1199
|
+
0 && (module.exports = {
|
|
1200
|
+
AdHubComponent,
|
|
1201
|
+
getAdHubAnonymousIdCookieName,
|
|
1202
|
+
initAdHub,
|
|
1203
|
+
readAdHubAnonymousIdFromCookie,
|
|
1204
|
+
useAdHub
|
|
1205
|
+
});
|
|
1206
|
+
//# sourceMappingURL=index.cjs.map
|