@temps-sdk/analytics-core 0.0.5 → 0.0.7-beta.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/dist/Analytics.d.ts.map +1 -1
- package/dist/Analytics.js +156 -8
- package/dist/AutoTracking.d.ts +127 -0
- package/dist/AutoTracking.d.ts.map +1 -0
- package/dist/AutoTracking.js +207 -0
- package/dist/FeatureFlags.d.ts +130 -0
- package/dist/FeatureFlags.d.ts.map +1 -0
- package/dist/FeatureFlags.js +271 -0
- package/dist/Identify.d.ts +51 -0
- package/dist/Identify.d.ts.map +1 -0
- package/dist/Identify.js +154 -0
- package/dist/SessionRecorder.d.ts +33 -1
- package/dist/SessionRecorder.d.ts.map +1 -1
- package/dist/SessionRecorder.js +64 -4
- package/dist/SpeedTracker.d.ts +5 -1
- package/dist/SpeedTracker.d.ts.map +1 -1
- package/dist/SpeedTracker.js +7 -1
- package/dist/SurveyWidget.d.ts +18 -0
- package/dist/SurveyWidget.d.ts.map +1 -0
- package/dist/SurveyWidget.js +195 -0
- package/dist/Surveys.d.ts +138 -0
- package/dist/Surveys.d.ts.map +1 -0
- package/dist/Surveys.js +351 -0
- package/dist/identity.d.ts +49 -0
- package/dist/identity.d.ts.map +1 -1
- package/dist/identity.js +126 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/request.d.ts +10 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/request.js +40 -0
- package/dist/types.d.ts +89 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +16 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +19 -2
- package/package.json +7 -2
package/dist/Surveys.js
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
/**
|
|
4
|
+
* In-app surveys (ADR 110 D1).
|
|
5
|
+
*
|
|
6
|
+
* Fetches the surveys this visitor may see from `{basePath}/surveys` on the
|
|
7
|
+
* page's own origin. The server has already applied sampling and flag
|
|
8
|
+
* conditions; this class applies the conditions that depend on the browser
|
|
9
|
+
* (page path, a triggering event, once per visitor) and records answers as
|
|
10
|
+
* ordinary analytics events:
|
|
11
|
+
*
|
|
12
|
+
* - `survey_shown` `{ survey_id, survey_name }`
|
|
13
|
+
* - `survey_dismissed` `{ survey_id, survey_name }`
|
|
14
|
+
* - `survey_sent` `{ survey_id, survey_name, responses: { [questionId]: answer } }`
|
|
15
|
+
*
|
|
16
|
+
* Rendering is separate (`SurveyWidget.ts`), so an app can draw its own UI
|
|
17
|
+
* with `eligible()`, `markShown()`, `dismiss()` and `submit()`.
|
|
18
|
+
*/
|
|
19
|
+
import { postJson, REQUEST_TIMEOUT_MS } from "./request";
|
|
20
|
+
import { isCookielessIdentity } from "./identity";
|
|
21
|
+
/** Longest open-text answer sent; the server cuts anything longer. */
|
|
22
|
+
export const MAX_OPEN_TEXT_LENGTH = 2000;
|
|
23
|
+
const SEEN_STORAGE_KEY = "temps_surveys_seen";
|
|
24
|
+
/** Surveys remembered as seen; the oldest are forgotten first. */
|
|
25
|
+
const MAX_SEEN = 200;
|
|
26
|
+
/**
|
|
27
|
+
* Largest `survey_sent` event data, UTF-8 encoded. The event endpoint
|
|
28
|
+
* refuses bodies above 64 KiB; the rest of the body (event name, page path
|
|
29
|
+
* and query, domain, language) gets the remaining 16 KiB.
|
|
30
|
+
*/
|
|
31
|
+
export const MAX_SURVEY_EVENT_BYTES = 48 * 1024;
|
|
32
|
+
/** First wait before a failed delivery request is retried; it doubles up to
|
|
33
|
+
* `MAX_RETRY_DELAY_MS`. */
|
|
34
|
+
const FIRST_RETRY_DELAY_MS = 15000;
|
|
35
|
+
const MAX_RETRY_DELAY_MS = 5 * 60000;
|
|
36
|
+
export class Surveys {
|
|
37
|
+
constructor(options) {
|
|
38
|
+
/** Bumped by `setContext`, so a request for the old context is ignored. */
|
|
39
|
+
this.generation = 0;
|
|
40
|
+
this.failures = 0;
|
|
41
|
+
this.retryAt = 0;
|
|
42
|
+
this.surveys = [];
|
|
43
|
+
this.inflight = null;
|
|
44
|
+
this.currentStatus = "idle";
|
|
45
|
+
this.listeners = new Set();
|
|
46
|
+
this.revision = 0;
|
|
47
|
+
/** Shown during this page's lifetime, whatever `once_per_visitor` says,
|
|
48
|
+
* so one page never shows a survey twice. */
|
|
49
|
+
this.shownHere = new Set();
|
|
50
|
+
this.basePath = options.basePath ?? "/api/_temps";
|
|
51
|
+
this.onEvent = options.onEvent;
|
|
52
|
+
this.onError =
|
|
53
|
+
options.onError ??
|
|
54
|
+
((error) => {
|
|
55
|
+
// eslint-disable-next-line no-console
|
|
56
|
+
console.warn("[temps-surveys] no surveys shown:", error.message);
|
|
57
|
+
});
|
|
58
|
+
this.fetchImpl = options.fetch;
|
|
59
|
+
this.storage = options.storage === undefined ? defaultStorage() : options.storage;
|
|
60
|
+
this.disabled = options.disabled ?? false;
|
|
61
|
+
this.now = options.now ?? Date.now;
|
|
62
|
+
this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
63
|
+
this.context = { key: options.key, attributes: options.attributes };
|
|
64
|
+
}
|
|
65
|
+
get status() {
|
|
66
|
+
return this.currentStatus;
|
|
67
|
+
}
|
|
68
|
+
/** Changes whenever the fetched surveys change. */
|
|
69
|
+
get version() {
|
|
70
|
+
return this.revision;
|
|
71
|
+
}
|
|
72
|
+
/** Every survey this visitor may see on some page. */
|
|
73
|
+
all() {
|
|
74
|
+
return [...this.surveys];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Fetch once; later calls return the same promise. After a failure, a
|
|
78
|
+
* later call tries again, waiting 15 seconds after the first failure and
|
|
79
|
+
* twice as long after each further one, up to 5 minutes.
|
|
80
|
+
*/
|
|
81
|
+
load() {
|
|
82
|
+
if (this.inflight)
|
|
83
|
+
return this.inflight;
|
|
84
|
+
if (this.disabled)
|
|
85
|
+
return Promise.resolve();
|
|
86
|
+
if (this.currentStatus === "error" && this.now() < this.retryAt)
|
|
87
|
+
return Promise.resolve();
|
|
88
|
+
const fetchImpl = this.fetchImpl ?? (typeof fetch === "function" ? fetch : undefined);
|
|
89
|
+
if (!fetchImpl) {
|
|
90
|
+
this.currentStatus = "error";
|
|
91
|
+
this.retryAt = Number.POSITIVE_INFINITY;
|
|
92
|
+
return Promise.resolve();
|
|
93
|
+
}
|
|
94
|
+
const generation = this.generation;
|
|
95
|
+
const context = this.context;
|
|
96
|
+
this.currentStatus = "loading";
|
|
97
|
+
const request = (async () => {
|
|
98
|
+
let surveys = null;
|
|
99
|
+
let failure = null;
|
|
100
|
+
try {
|
|
101
|
+
const parsed = await postJson(fetchImpl, `${this.basePath}/surveys`, JSON.stringify({ key: context.key, attributes: context.attributes ?? {} }), this.timeoutMs);
|
|
102
|
+
surveys = Array.isArray(parsed.surveys) ? parsed.surveys : [];
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
failure = error instanceof Error ? error : new Error(String(error));
|
|
106
|
+
}
|
|
107
|
+
// The context changed while this was in flight: its answer is for
|
|
108
|
+
// someone else, and the new context has its own request.
|
|
109
|
+
if (generation !== this.generation)
|
|
110
|
+
return;
|
|
111
|
+
if (surveys) {
|
|
112
|
+
this.surveys = surveys;
|
|
113
|
+
this.currentStatus = "ready";
|
|
114
|
+
this.failures = 0;
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
this.currentStatus = "error";
|
|
118
|
+
this.failures += 1;
|
|
119
|
+
const delay = Math.min(FIRST_RETRY_DELAY_MS * 2 ** (this.failures - 1), MAX_RETRY_DELAY_MS);
|
|
120
|
+
this.retryAt = this.now() + delay;
|
|
121
|
+
// Forget the failed request, so a later call can try again.
|
|
122
|
+
this.inflight = null;
|
|
123
|
+
if (failure)
|
|
124
|
+
this.onError(failure);
|
|
125
|
+
}
|
|
126
|
+
this.notify();
|
|
127
|
+
})();
|
|
128
|
+
this.inflight = request;
|
|
129
|
+
return request;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Replace the subject and attributes, e.g. once a user signs in. Surveys
|
|
133
|
+
* fetched for the previous context are dropped and the next `load()`
|
|
134
|
+
* fetches again. Surveys already shown on this page stay shown.
|
|
135
|
+
*/
|
|
136
|
+
setContext(key, attributes) {
|
|
137
|
+
this.generation += 1;
|
|
138
|
+
this.context = { key, attributes };
|
|
139
|
+
this.surveys = [];
|
|
140
|
+
this.inflight = null;
|
|
141
|
+
this.failures = 0;
|
|
142
|
+
this.retryAt = 0;
|
|
143
|
+
this.currentStatus = "idle";
|
|
144
|
+
this.notify();
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Surveys to show now on `pathname`. With `event`, only surveys triggered
|
|
148
|
+
* by that event; without it, only surveys shown on page load.
|
|
149
|
+
*/
|
|
150
|
+
eligible(pathname, event) {
|
|
151
|
+
const seen = this.seen();
|
|
152
|
+
return this.surveys.filter((survey) => {
|
|
153
|
+
const trigger = survey.display.trigger_event;
|
|
154
|
+
if (event === undefined ? Boolean(trigger) : trigger !== event)
|
|
155
|
+
return false;
|
|
156
|
+
if (survey.display.path_pattern && !pathMatches(survey.display.path_pattern, pathname)) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
if (this.shownHere.has(survey.id))
|
|
160
|
+
return false;
|
|
161
|
+
return !(survey.display.once_per_visitor && seen.has(survey.id));
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
/** Record that the survey was displayed. */
|
|
165
|
+
markShown(survey) {
|
|
166
|
+
this.shownHere.add(survey.id);
|
|
167
|
+
if (survey.display.once_per_visitor)
|
|
168
|
+
this.remember(survey.id);
|
|
169
|
+
this.emit("survey_shown", survey);
|
|
170
|
+
}
|
|
171
|
+
/** Record that the visitor closed the survey without answering. */
|
|
172
|
+
dismiss(survey) {
|
|
173
|
+
this.emit("survey_dismissed", survey);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Validate and record the visitor's answers. Returns the problems instead
|
|
177
|
+
* of sending when an answer is missing or malformed.
|
|
178
|
+
*/
|
|
179
|
+
submit(survey, answers) {
|
|
180
|
+
const checked = validateAnswers(survey, answers);
|
|
181
|
+
if (!checked.ok)
|
|
182
|
+
return checked;
|
|
183
|
+
const data = { survey_id: survey.id, survey_name: survey.name, responses: checked.responses };
|
|
184
|
+
if (encodedLength(JSON.stringify(data)) > MAX_SURVEY_EVENT_BYTES) {
|
|
185
|
+
// Sent anyway, the event endpoint would refuse it and the answers would
|
|
186
|
+
// be lost behind a "thanks". Keep the form open instead.
|
|
187
|
+
return { ok: false, errors: tooLongErrors(survey, checked.responses) };
|
|
188
|
+
}
|
|
189
|
+
this.emit("survey_sent", survey, { responses: checked.responses });
|
|
190
|
+
return { ok: true };
|
|
191
|
+
}
|
|
192
|
+
subscribe(listener) {
|
|
193
|
+
this.listeners.add(listener);
|
|
194
|
+
return () => {
|
|
195
|
+
this.listeners.delete(listener);
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
emit(name, survey, extra = {}) {
|
|
199
|
+
try {
|
|
200
|
+
this.onEvent(name, { survey_id: survey.id, survey_name: survey.name, ...extra });
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
// Recording is best effort; the visitor's UI must not break.
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
// In cookieless mode nothing is read from or written to the device, so
|
|
207
|
+
// `once_per_visitor` falls back to once per page (`shownHere`).
|
|
208
|
+
seen() {
|
|
209
|
+
if (isCookielessIdentity())
|
|
210
|
+
return new Set();
|
|
211
|
+
try {
|
|
212
|
+
const raw = this.storage?.getItem(SEEN_STORAGE_KEY);
|
|
213
|
+
const parsed = raw ? JSON.parse(raw) : [];
|
|
214
|
+
return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === "number") : []);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return new Set();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
remember(id) {
|
|
221
|
+
if (isCookielessIdentity())
|
|
222
|
+
return;
|
|
223
|
+
try {
|
|
224
|
+
const ids = [...this.seen()].filter((seen) => seen !== id);
|
|
225
|
+
ids.push(id);
|
|
226
|
+
this.storage?.setItem(SEEN_STORAGE_KEY, JSON.stringify(ids.slice(-MAX_SEEN)));
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
// Storage may be full or blocked; the survey is then shown again later.
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
notify() {
|
|
233
|
+
this.revision += 1;
|
|
234
|
+
for (const listener of [...this.listeners]) {
|
|
235
|
+
try {
|
|
236
|
+
listener();
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
// A failing subscriber must not stop the others.
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/** A map keyed by question id, with no prototype. */
|
|
245
|
+
export function idMap() {
|
|
246
|
+
return Object.create(null);
|
|
247
|
+
}
|
|
248
|
+
function encodedLength(text) {
|
|
249
|
+
return new TextEncoder().encode(text).length;
|
|
250
|
+
}
|
|
251
|
+
/** Errors for an answer set too large to send: on each written answer, the
|
|
252
|
+
* only kind that can grow that large. The visitor's answers stay in the form. */
|
|
253
|
+
function tooLongErrors(survey, responses) {
|
|
254
|
+
const message = "These answers are too long to send together. Shorten this one and send again.";
|
|
255
|
+
const errors = idMap();
|
|
256
|
+
for (const question of survey.questions) {
|
|
257
|
+
const answer = responses[question.id];
|
|
258
|
+
if (question.kind === "open_text" && typeof answer === "string" && answer.length > 0) {
|
|
259
|
+
errors[question.id] = message;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const first = survey.questions[0];
|
|
263
|
+
if (Object.keys(errors).length === 0 && first)
|
|
264
|
+
errors[first.id] = message;
|
|
265
|
+
return errors;
|
|
266
|
+
}
|
|
267
|
+
function defaultStorage() {
|
|
268
|
+
try {
|
|
269
|
+
return typeof window !== "undefined" ? window.localStorage : null;
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/** Whether `pathname` matches `pattern`, where `*` matches any run of
|
|
276
|
+
* characters and the whole path must match. */
|
|
277
|
+
export function pathMatches(pattern, pathname) {
|
|
278
|
+
const parts = pattern.split("*");
|
|
279
|
+
if (parts.length === 1)
|
|
280
|
+
return pattern === pathname;
|
|
281
|
+
const first = parts[0] ?? "";
|
|
282
|
+
const last = parts[parts.length - 1] ?? "";
|
|
283
|
+
if (!pathname.startsWith(first))
|
|
284
|
+
return false;
|
|
285
|
+
let position = first.length;
|
|
286
|
+
for (const middle of parts.slice(1, -1)) {
|
|
287
|
+
const found = pathname.indexOf(middle, position);
|
|
288
|
+
if (found === -1)
|
|
289
|
+
return false;
|
|
290
|
+
position = found + middle.length;
|
|
291
|
+
}
|
|
292
|
+
return pathname.length - position >= last.length && pathname.endsWith(last);
|
|
293
|
+
}
|
|
294
|
+
function scaleBounds(question) {
|
|
295
|
+
return question.kind === "nps" ? [0, 10] : [1, question.scale ?? 5];
|
|
296
|
+
}
|
|
297
|
+
/** Check answers against the survey; keep only answers to its questions. */
|
|
298
|
+
export function validateAnswers(survey, answers) {
|
|
299
|
+
// Keyed by question id: without a prototype, an id such as `__proto__`
|
|
300
|
+
// is an ordinary key, and nothing inherited reads as an answer.
|
|
301
|
+
const errors = idMap();
|
|
302
|
+
const responses = idMap();
|
|
303
|
+
for (const question of survey.questions) {
|
|
304
|
+
const answer = Object.prototype.hasOwnProperty.call(answers, question.id) ? answers[question.id] : undefined;
|
|
305
|
+
const empty = answer === undefined ||
|
|
306
|
+
answer === null ||
|
|
307
|
+
(typeof answer === "string" && answer.trim() === "") ||
|
|
308
|
+
(Array.isArray(answer) && answer.length === 0);
|
|
309
|
+
if (empty) {
|
|
310
|
+
if (!question.optional)
|
|
311
|
+
errors[question.id] = "This question needs an answer.";
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
switch (question.kind) {
|
|
315
|
+
case "open_text":
|
|
316
|
+
if (typeof answer !== "string")
|
|
317
|
+
errors[question.id] = "Expected text.";
|
|
318
|
+
else
|
|
319
|
+
responses[question.id] = answer.slice(0, MAX_OPEN_TEXT_LENGTH);
|
|
320
|
+
break;
|
|
321
|
+
case "single_choice":
|
|
322
|
+
if (typeof answer !== "string" || !(question.choices ?? []).includes(answer)) {
|
|
323
|
+
errors[question.id] = "Pick one of the choices.";
|
|
324
|
+
}
|
|
325
|
+
else
|
|
326
|
+
responses[question.id] = answer;
|
|
327
|
+
break;
|
|
328
|
+
case "multiple_choice": {
|
|
329
|
+
const choices = question.choices ?? [];
|
|
330
|
+
if (!Array.isArray(answer) || answer.some((item) => !choices.includes(item))) {
|
|
331
|
+
errors[question.id] = "Pick from the choices.";
|
|
332
|
+
}
|
|
333
|
+
else
|
|
334
|
+
responses[question.id] = [...new Set(answer)];
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
case "rating":
|
|
338
|
+
case "nps": {
|
|
339
|
+
const [min, max] = scaleBounds(question);
|
|
340
|
+
if (typeof answer !== "number" || !Number.isInteger(answer) || answer < min || answer > max) {
|
|
341
|
+
errors[question.id] = `Pick a number from ${min} to ${max}.`;
|
|
342
|
+
}
|
|
343
|
+
else
|
|
344
|
+
responses[question.id] = answer;
|
|
345
|
+
break;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return Object.keys(errors).length > 0 ? { ok: false, errors } : { ok: true, responses };
|
|
350
|
+
}
|
|
351
|
+
export { scaleBounds as surveyScaleBounds };
|
package/dist/identity.d.ts
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stop storing identity on the device and delete what an earlier visit
|
|
3
|
+
* stored, so switching a site to cookieless also forgets returning visitors'
|
|
4
|
+
* ids. Called by `createAnalytics({ cookieless: true })`.
|
|
5
|
+
*/
|
|
6
|
+
export declare function enableCookielessIdentity(): void;
|
|
7
|
+
/**
|
|
8
|
+
* Delete the stored visitor and session ids, so the next event starts a new
|
|
9
|
+
* visitor. Used by `reset()` on sign-out.
|
|
10
|
+
*/
|
|
11
|
+
export declare function clearStoredIdentity(): void;
|
|
12
|
+
/**
|
|
13
|
+
* The visitor id this tracker stored, without creating one. `undefined` in
|
|
14
|
+
* cookieless mode, before the first event, or when storage is blocked. On a
|
|
15
|
+
* site Temps serves, the server-side visitor is the `_temps_visitor_id`
|
|
16
|
+
* cookie instead, which the page cannot read (it is `HttpOnly`).
|
|
17
|
+
*/
|
|
18
|
+
export declare function getStoredVisitorId(): string | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* Run `listener` when the page switches to cookieless mode, so an analytics
|
|
21
|
+
* instance created earlier can stop what needs a stored id (session replay).
|
|
22
|
+
* Returns the unsubscribe function.
|
|
23
|
+
*/
|
|
24
|
+
export declare function onCookielessIdentity(listener: () => void): () => void;
|
|
25
|
+
/**
|
|
26
|
+
* The two moments of a `reset()`: `started` once the ids stored in the
|
|
27
|
+
* browser are gone, `confirmed` once the server has expired its tracking
|
|
28
|
+
* cookies too (at once on a cookieless page, which has none). A `reset()`
|
|
29
|
+
* the server did not confirm reports only `started`.
|
|
30
|
+
*/
|
|
31
|
+
export type IdentityResetPhase = "started" | "confirmed";
|
|
32
|
+
/**
|
|
33
|
+
* Whether a `reset()` has started but the server has not confirmed it yet
|
|
34
|
+
* (or refused it). Until then the device may still name the previous
|
|
35
|
+
* visitor, so a session replay must not start: a recorder created or
|
|
36
|
+
* started in that window waits for `confirmed`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function isIdentityResetPending(): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Run `listener` at each phase of a `reset()` (ADR 109 D4), so a session
|
|
41
|
+
* replay in progress ends when it starts, and the next one begins only once
|
|
42
|
+
* nothing on the device still names the previous visitor: two people's
|
|
43
|
+
* activity never shares a recording. Returns the unsubscribe function.
|
|
44
|
+
*/
|
|
45
|
+
export declare function onIdentityReset(listener: (phase: IdentityResetPhase) => void): () => void;
|
|
46
|
+
/** Tell every `onIdentityReset` listener that a reset reached `phase`. */
|
|
47
|
+
export declare function notifyIdentityReset(phase: IdentityResetPhase): void;
|
|
48
|
+
/** Whether identity storage is off for this page (see `enableCookielessIdentity`). */
|
|
49
|
+
export declare function isCookielessIdentity(): boolean;
|
|
1
50
|
/**
|
|
2
51
|
* Returns a stable visitor id, generating and persisting one on first call.
|
|
3
52
|
* `undefined` when `localStorage` is missing or unusable: outside a browser,
|
package/dist/identity.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AA+BA;;;;GAIG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAkB/C;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAU1C;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,GAAG,SAAS,CAQvD;AAID;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAKrE;AAED;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAAG,SAAS,GAAG,WAAW,CAAC;AAOzD;;;;;GAKG;AACH,wBAAgB,sBAAsB,IAAI,OAAO,CAEhD;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,kBAAkB,KAAK,IAAI,GAAG,MAAM,IAAI,CAKzF;AAED,0EAA0E;AAC1E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,kBAAkB,GAAG,IAAI,CAUnE;AAED,sFAAsF;AACtF,wBAAgB,oBAAoB,IAAI,OAAO,CAE9C;AAiBD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAazD;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAiBzD"}
|
package/dist/identity.js
CHANGED
|
@@ -18,6 +18,128 @@
|
|
|
18
18
|
const VISITOR_ID_KEY = "temps_visitor_id";
|
|
19
19
|
const SESSION_ID_KEY = "temps_session_id";
|
|
20
20
|
const SESSION_LAST_SEEN_KEY = "temps_session_last_seen";
|
|
21
|
+
/**
|
|
22
|
+
* Cookieless mode (ADR 109 D3). Once on, identity is never read from or
|
|
23
|
+
* written to the device: the server derives a daily visitor id from the
|
|
24
|
+
* request instead. It is one-way for the page's lifetime, so a second
|
|
25
|
+
* analytics instance configured without it cannot start storing ids again.
|
|
26
|
+
*/
|
|
27
|
+
let cookieless = false;
|
|
28
|
+
/**
|
|
29
|
+
* Stop storing identity on the device and delete what an earlier visit
|
|
30
|
+
* stored, so switching a site to cookieless also forgets returning visitors'
|
|
31
|
+
* ids. Called by `createAnalytics({ cookieless: true })`.
|
|
32
|
+
*/
|
|
33
|
+
export function enableCookielessIdentity() {
|
|
34
|
+
const switched = !cookieless;
|
|
35
|
+
cookieless = true;
|
|
36
|
+
clearStoredIdentity();
|
|
37
|
+
try {
|
|
38
|
+
if (typeof localStorage !== "undefined")
|
|
39
|
+
localStorage.removeItem("temps_identified");
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// Storage unusable: there is nothing stored to delete either.
|
|
43
|
+
}
|
|
44
|
+
if (!switched)
|
|
45
|
+
return;
|
|
46
|
+
for (const listener of Array.from(cookielessListeners)) {
|
|
47
|
+
try {
|
|
48
|
+
listener();
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
// eslint-disable-next-line no-console
|
|
52
|
+
console.error("[temps] cookieless switch listener failed:", error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Delete the stored visitor and session ids, so the next event starts a new
|
|
58
|
+
* visitor. Used by `reset()` on sign-out.
|
|
59
|
+
*/
|
|
60
|
+
export function clearStoredIdentity() {
|
|
61
|
+
try {
|
|
62
|
+
if (typeof localStorage !== "undefined") {
|
|
63
|
+
localStorage.removeItem(VISITOR_ID_KEY);
|
|
64
|
+
localStorage.removeItem(SESSION_ID_KEY);
|
|
65
|
+
localStorage.removeItem(SESSION_LAST_SEEN_KEY);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// Storage unusable: nothing was stored.
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The visitor id this tracker stored, without creating one. `undefined` in
|
|
74
|
+
* cookieless mode, before the first event, or when storage is blocked. On a
|
|
75
|
+
* site Temps serves, the server-side visitor is the `_temps_visitor_id`
|
|
76
|
+
* cookie instead, which the page cannot read (it is `HttpOnly`).
|
|
77
|
+
*/
|
|
78
|
+
export function getStoredVisitorId() {
|
|
79
|
+
if (cookieless)
|
|
80
|
+
return undefined;
|
|
81
|
+
try {
|
|
82
|
+
if (typeof localStorage === "undefined")
|
|
83
|
+
return undefined;
|
|
84
|
+
return localStorage.getItem(VISITOR_ID_KEY) ?? undefined;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const cookielessListeners = new Set();
|
|
91
|
+
/**
|
|
92
|
+
* Run `listener` when the page switches to cookieless mode, so an analytics
|
|
93
|
+
* instance created earlier can stop what needs a stored id (session replay).
|
|
94
|
+
* Returns the unsubscribe function.
|
|
95
|
+
*/
|
|
96
|
+
export function onCookielessIdentity(listener) {
|
|
97
|
+
cookielessListeners.add(listener);
|
|
98
|
+
return () => {
|
|
99
|
+
cookielessListeners.delete(listener);
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const identityResetListeners = new Set();
|
|
103
|
+
/** True from a reset's `started` until a reset reaches `confirmed`. */
|
|
104
|
+
let identityResetPending = false;
|
|
105
|
+
/**
|
|
106
|
+
* Whether a `reset()` has started but the server has not confirmed it yet
|
|
107
|
+
* (or refused it). Until then the device may still name the previous
|
|
108
|
+
* visitor, so a session replay must not start: a recorder created or
|
|
109
|
+
* started in that window waits for `confirmed`.
|
|
110
|
+
*/
|
|
111
|
+
export function isIdentityResetPending() {
|
|
112
|
+
return identityResetPending;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Run `listener` at each phase of a `reset()` (ADR 109 D4), so a session
|
|
116
|
+
* replay in progress ends when it starts, and the next one begins only once
|
|
117
|
+
* nothing on the device still names the previous visitor: two people's
|
|
118
|
+
* activity never shares a recording. Returns the unsubscribe function.
|
|
119
|
+
*/
|
|
120
|
+
export function onIdentityReset(listener) {
|
|
121
|
+
identityResetListeners.add(listener);
|
|
122
|
+
return () => {
|
|
123
|
+
identityResetListeners.delete(listener);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Tell every `onIdentityReset` listener that a reset reached `phase`. */
|
|
127
|
+
export function notifyIdentityReset(phase) {
|
|
128
|
+
identityResetPending = phase === "started";
|
|
129
|
+
for (const listener of Array.from(identityResetListeners)) {
|
|
130
|
+
try {
|
|
131
|
+
listener(phase);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
// eslint-disable-next-line no-console
|
|
135
|
+
console.error("[temps] identity reset listener failed:", error);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Whether identity storage is off for this page (see `enableCookielessIdentity`). */
|
|
140
|
+
export function isCookielessIdentity() {
|
|
141
|
+
return cookieless;
|
|
142
|
+
}
|
|
21
143
|
/**
|
|
22
144
|
* Mirrors the proxy's default session inactivity window
|
|
23
145
|
* (`session_max_age_minutes` in `crates/temps-proxy/src/traits.rs`) so
|
|
@@ -39,6 +161,8 @@ function randomId(prefix) {
|
|
|
39
161
|
* new visitor on every event, so the server's own identity is used instead.
|
|
40
162
|
*/
|
|
41
163
|
export function getOrCreateVisitorId() {
|
|
164
|
+
if (cookieless)
|
|
165
|
+
return undefined;
|
|
42
166
|
try {
|
|
43
167
|
if (typeof localStorage === "undefined")
|
|
44
168
|
return undefined;
|
|
@@ -59,6 +183,8 @@ export function getOrCreateVisitorId() {
|
|
|
59
183
|
* outbound request so `lastSeen` tracks real activity.
|
|
60
184
|
*/
|
|
61
185
|
export function getOrCreateSessionId() {
|
|
186
|
+
if (cookieless)
|
|
187
|
+
return undefined;
|
|
62
188
|
try {
|
|
63
189
|
if (typeof localStorage === "undefined")
|
|
64
190
|
return undefined;
|
package/dist/index.d.ts
CHANGED
|
@@ -4,5 +4,11 @@ export * from "./utils";
|
|
|
4
4
|
export { EngagementTracker, type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
|
|
5
5
|
export { SpeedTracker, type SpeedTrackerOptions } from "./SpeedTracker";
|
|
6
6
|
export { SessionRecorder, type SessionRecorderOptions } from "./SessionRecorder";
|
|
7
|
+
export { OUTBOUND_CLICK_EVENT, FILE_DOWNLOAD_EVENT, NOT_FOUND_EVENT, NOT_FOUND_MARKER_ATTRIBUTE, DEFAULT_FILE_DOWNLOAD_EXTENSIONS, NOT_FOUND_RECHECK_DELAY_MS, classifyLink, pathExtension, setupLinkTracking, notFoundEventData, hasNotFoundMarker, NotFoundMarkerWatcher, type AutoTrackOptions, type LinkClassification, type LinkLike, type ClassifyLinkOptions, } from "./AutoTracking";
|
|
8
|
+
export { enableCookielessIdentity, isCookielessIdentity, onCookielessIdentity, onIdentityReset, type IdentityResetPhase, clearStoredIdentity, getStoredVisitorId, } from "./identity";
|
|
9
|
+
export { identifyVisitor, resetVisitor, ResetFailedError, IDENTIFY_ENDPOINT, RESET_ENDPOINT, type IdentifyVisitorOptions, } from "./Identify";
|
|
7
10
|
export { createAnalytics } from "./Analytics";
|
|
11
|
+
export { FeatureFlags, exposureEventData, type FeatureFlagsOptions, type FlagContext, type FlagEvaluation, type FlagExposure, type FlagReason, type FlagsStatus, } from "./FeatureFlags";
|
|
12
|
+
export { Surveys, pathMatches, validateAnswers, MAX_OPEN_TEXT_LENGTH, type Survey, type SurveyAnswer, type SurveyAnswers, type SurveyDisplay, type SurveyQuestion, type SurveyQuestionKind, type SurveysOptions, type SurveysStatus, } from "./Surveys";
|
|
13
|
+
export { renderSurveyWidget, type SurveyWidgetHandlers } from "./SurveyWidget";
|
|
8
14
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AACjF,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,eAAe,EACf,0BAA0B,EAC1B,gCAAgC,EAChC,0BAA0B,EAC1B,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,qBAAqB,EACrB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,QAAQ,EACb,KAAK,mBAAmB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,oBAAoB,EACpB,eAAe,EACf,KAAK,kBAAkB,EACvB,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EACd,KAAK,sBAAsB,GAC5B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,KAAK,mBAAmB,EACxB,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,WAAW,GACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,OAAO,EACP,WAAW,EACX,eAAe,EACf,oBAAoB,EACpB,KAAK,MAAM,EACX,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,aAAa,GACnB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,KAAK,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -6,4 +6,10 @@ export * from "./utils";
|
|
|
6
6
|
export { EngagementTracker } from "./EngagementTracker";
|
|
7
7
|
export { SpeedTracker } from "./SpeedTracker";
|
|
8
8
|
export { SessionRecorder } from "./SessionRecorder";
|
|
9
|
+
export { OUTBOUND_CLICK_EVENT, FILE_DOWNLOAD_EVENT, NOT_FOUND_EVENT, NOT_FOUND_MARKER_ATTRIBUTE, DEFAULT_FILE_DOWNLOAD_EXTENSIONS, NOT_FOUND_RECHECK_DELAY_MS, classifyLink, pathExtension, setupLinkTracking, notFoundEventData, hasNotFoundMarker, NotFoundMarkerWatcher, } from "./AutoTracking";
|
|
10
|
+
export { enableCookielessIdentity, isCookielessIdentity, onCookielessIdentity, onIdentityReset, clearStoredIdentity, getStoredVisitorId, } from "./identity";
|
|
11
|
+
export { identifyVisitor, resetVisitor, ResetFailedError, IDENTIFY_ENDPOINT, RESET_ENDPOINT, } from "./Identify";
|
|
9
12
|
export { createAnalytics } from "./Analytics";
|
|
13
|
+
export { FeatureFlags, exposureEventData, } from "./FeatureFlags";
|
|
14
|
+
export { Surveys, pathMatches, validateAnswers, MAX_OPEN_TEXT_LENGTH, } from "./Surveys";
|
|
15
|
+
export { renderSurveyWidget } from "./SurveyWidget";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** How long a same-origin flags or surveys request may take, body included. */
|
|
2
|
+
export declare const REQUEST_TIMEOUT_MS = 10000;
|
|
3
|
+
/**
|
|
4
|
+
* POST `body` as JSON and parse the JSON answer, failing after `timeoutMs`
|
|
5
|
+
* whether the connection stalls before the headers or while the body is
|
|
6
|
+
* read. The request is aborted when the platform supports it; the deadline
|
|
7
|
+
* holds either way.
|
|
8
|
+
*/
|
|
9
|
+
export declare function postJson<T>(fetchImpl: typeof fetch, url: string, body: string, timeoutMs?: number): Promise<T>;
|
|
10
|
+
//# sourceMappingURL=request.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AAGA,+EAA+E;AAC/E,eAAO,MAAM,kBAAkB,QAAS,CAAC;AAEzC;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,CAAC,EAC9B,SAAS,EAAE,OAAO,KAAK,EACvB,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,SAAS,GAAE,MAA2B,GACrC,OAAO,CAAC,CAAC,CAAC,CA2BZ"}
|
package/dist/request.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
|
+
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
/** How long a same-origin flags or surveys request may take, body included. */
|
|
4
|
+
export const REQUEST_TIMEOUT_MS = 10000;
|
|
5
|
+
/**
|
|
6
|
+
* POST `body` as JSON and parse the JSON answer, failing after `timeoutMs`
|
|
7
|
+
* whether the connection stalls before the headers or while the body is
|
|
8
|
+
* read. The request is aborted when the platform supports it; the deadline
|
|
9
|
+
* holds either way.
|
|
10
|
+
*/
|
|
11
|
+
export async function postJson(fetchImpl, url, body, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
12
|
+
const controller = typeof AbortController === "function" ? new AbortController() : undefined;
|
|
13
|
+
let timer;
|
|
14
|
+
const deadline = new Promise((_, reject) => {
|
|
15
|
+
timer = setTimeout(() => {
|
|
16
|
+
controller?.abort();
|
|
17
|
+
reject(new Error(`${url} did not answer within ${Math.round(timeoutMs / 1000)}s`));
|
|
18
|
+
}, timeoutMs);
|
|
19
|
+
});
|
|
20
|
+
const exchange = (async () => {
|
|
21
|
+
const response = await fetchImpl(url, {
|
|
22
|
+
method: "POST",
|
|
23
|
+
headers: { "Content-Type": "application/json" },
|
|
24
|
+
credentials: "same-origin",
|
|
25
|
+
body,
|
|
26
|
+
signal: controller?.signal,
|
|
27
|
+
});
|
|
28
|
+
if (!response.ok)
|
|
29
|
+
throw new Error(`${url} returned ${response.status}`);
|
|
30
|
+
return (await response.json());
|
|
31
|
+
})();
|
|
32
|
+
try {
|
|
33
|
+
return await Promise.race([exchange, deadline]);
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
// The losing side's rejection is handled here, not reported as unhandled.
|
|
38
|
+
exchange.catch(() => undefined);
|
|
39
|
+
}
|
|
40
|
+
}
|