@faceyoga/analytics 0.0.0-stage → 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/dist/chunk-BN7JI6EH.js +176 -0
- package/dist/chunk-BN7JI6EH.js.map +1 -0
- package/dist/client.d.ts +97 -0
- package/dist/client.js +305 -0
- package/dist/client.js.map +1 -0
- package/dist/names-MWUOMlPa.d.ts +61 -0
- package/dist/server.d.ts +186 -0
- package/dist/server.js +275 -0
- package/dist/server.js.map +1 -0
- package/package.json +43 -3
- package/README.md +0 -3
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// ../schema/src/assign.ts
|
|
2
|
+
var BUCKETS = 1e4;
|
|
3
|
+
var encoder = new TextEncoder();
|
|
4
|
+
function murmur3(key, seed = 0) {
|
|
5
|
+
const bytes = encoder.encode(key);
|
|
6
|
+
const length = bytes.length;
|
|
7
|
+
const blocks = length >>> 2;
|
|
8
|
+
const c1 = 3432918353;
|
|
9
|
+
const c2 = 461845907;
|
|
10
|
+
let h = seed >>> 0;
|
|
11
|
+
for (let i = 0; i < blocks; i++) {
|
|
12
|
+
const o = i * 4;
|
|
13
|
+
let k = (bytes[o] | bytes[o + 1] << 8 | bytes[o + 2] << 16 | bytes[o + 3] << 24) >>> 0;
|
|
14
|
+
k = Math.imul(k, c1);
|
|
15
|
+
k = k << 15 | k >>> 17;
|
|
16
|
+
k = Math.imul(k, c2);
|
|
17
|
+
h ^= k;
|
|
18
|
+
h = h << 13 | h >>> 19;
|
|
19
|
+
h = Math.imul(h, 5) + 3864292196 >>> 0;
|
|
20
|
+
}
|
|
21
|
+
const tail = blocks * 4;
|
|
22
|
+
let k1 = 0;
|
|
23
|
+
switch (length & 3) {
|
|
24
|
+
case 3:
|
|
25
|
+
k1 ^= bytes[tail + 2] << 16;
|
|
26
|
+
// falls through
|
|
27
|
+
case 2:
|
|
28
|
+
k1 ^= bytes[tail + 1] << 8;
|
|
29
|
+
// falls through
|
|
30
|
+
case 1:
|
|
31
|
+
k1 ^= bytes[tail];
|
|
32
|
+
k1 = Math.imul(k1, c1);
|
|
33
|
+
k1 = k1 << 15 | k1 >>> 17;
|
|
34
|
+
k1 = Math.imul(k1, c2);
|
|
35
|
+
h ^= k1;
|
|
36
|
+
}
|
|
37
|
+
h ^= length;
|
|
38
|
+
h ^= h >>> 16;
|
|
39
|
+
h = Math.imul(h, 2246822507);
|
|
40
|
+
h ^= h >>> 13;
|
|
41
|
+
h = Math.imul(h, 3266489909);
|
|
42
|
+
h ^= h >>> 16;
|
|
43
|
+
return h >>> 0;
|
|
44
|
+
}
|
|
45
|
+
function bucketFor(salt, unitId) {
|
|
46
|
+
return murmur3(`${salt}.${unitId}`) % BUCKETS;
|
|
47
|
+
}
|
|
48
|
+
function matchesTargeting(experiment, unit) {
|
|
49
|
+
const { countries, locales } = experiment.targeting ?? {};
|
|
50
|
+
if (countries?.length) {
|
|
51
|
+
const country = unit.country?.toUpperCase();
|
|
52
|
+
if (!country || !countries.includes(country)) return false;
|
|
53
|
+
}
|
|
54
|
+
if (locales?.length) {
|
|
55
|
+
const language = unit.locale?.toLowerCase().split(/[-_]/)[0];
|
|
56
|
+
if (!language || !locales.includes(language)) return false;
|
|
57
|
+
}
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
function notFound(key) {
|
|
61
|
+
return { experiment: key, variant: null, params: {}, reason: "not_found" };
|
|
62
|
+
}
|
|
63
|
+
function assign(experiment, unit) {
|
|
64
|
+
const empty = (reason) => ({
|
|
65
|
+
experiment: experiment.key,
|
|
66
|
+
variant: null,
|
|
67
|
+
params: {},
|
|
68
|
+
reason
|
|
69
|
+
});
|
|
70
|
+
if (experiment.status === "launched") {
|
|
71
|
+
const launched = experiment.variants.find((v) => v.key === experiment.launchedVariant);
|
|
72
|
+
if (!launched) return empty("not_found");
|
|
73
|
+
return { experiment: experiment.key, variant: launched.key, params: launched.params, reason: "launched" };
|
|
74
|
+
}
|
|
75
|
+
if (!matchesTargeting(experiment, unit)) return empty("targeting");
|
|
76
|
+
if (bucketFor(`${experiment.salt}:alloc`, unit.id) >= Math.round(experiment.allocation * BUCKETS)) {
|
|
77
|
+
return empty("not_allocated");
|
|
78
|
+
}
|
|
79
|
+
const totalWeight = experiment.variants.reduce((sum, v) => sum + Math.max(0, v.weight), 0);
|
|
80
|
+
if (totalWeight <= 0) return empty("not_allocated");
|
|
81
|
+
const point = bucketFor(`${experiment.salt}:variant`, unit.id) / BUCKETS * totalWeight;
|
|
82
|
+
let cumulative = 0;
|
|
83
|
+
for (const variant of experiment.variants) {
|
|
84
|
+
cumulative += Math.max(0, variant.weight);
|
|
85
|
+
if (point < cumulative) {
|
|
86
|
+
return { experiment: experiment.key, variant: variant.key, params: variant.params, reason: "assigned" };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const last = [...experiment.variants].reverse().find((v) => v.weight > 0);
|
|
90
|
+
return { experiment: experiment.key, variant: last.key, params: last.params, reason: "assigned" };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ../schema/src/names.ts
|
|
94
|
+
var EventNames = {
|
|
95
|
+
// Emitted by the SDK
|
|
96
|
+
PageView: "page_view",
|
|
97
|
+
SessionStart: "session_start",
|
|
98
|
+
ExperimentExposure: "experiment_exposure",
|
|
99
|
+
Identify: "identify",
|
|
100
|
+
// Ecommerce funnel (pithos `TrackingEventName` and Hoola GTM events map onto these)
|
|
101
|
+
ViewContent: "view_content",
|
|
102
|
+
AddToCart: "add_to_cart",
|
|
103
|
+
InitiateCheckout: "initiate_checkout",
|
|
104
|
+
CheckoutEmailCaptured: "checkout_email_captured",
|
|
105
|
+
Purchase: "purchase",
|
|
106
|
+
Upsell: "upsell",
|
|
107
|
+
FailedOrder: "failed_order",
|
|
108
|
+
FailedTransaction: "failed_transaction",
|
|
109
|
+
// Engagement
|
|
110
|
+
CtaClicked: "cta_clicked",
|
|
111
|
+
QuizStepViewed: "quiz_step_viewed",
|
|
112
|
+
QuizStepCompleted: "quiz_step_completed",
|
|
113
|
+
QuizCompleted: "quiz_completed"
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
// src/shared/experiment.ts
|
|
117
|
+
function sameType(value, fallback) {
|
|
118
|
+
if (fallback === null || fallback === void 0) return value !== void 0;
|
|
119
|
+
if (Array.isArray(fallback)) return Array.isArray(value);
|
|
120
|
+
return value !== null && typeof value === typeof fallback && !Array.isArray(value);
|
|
121
|
+
}
|
|
122
|
+
function toExperiment(assignment) {
|
|
123
|
+
return {
|
|
124
|
+
key: assignment.experiment,
|
|
125
|
+
variant: assignment.variant,
|
|
126
|
+
reason: assignment.reason,
|
|
127
|
+
params: assignment.params,
|
|
128
|
+
get(param, fallback) {
|
|
129
|
+
const value = assignment.params[param];
|
|
130
|
+
return sameType(value, fallback) ? value : fallback;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// src/shared/util.ts
|
|
136
|
+
var LIBRARY = { name: "@faceyoga/analytics", version: "0.1.1" };
|
|
137
|
+
function uuid() {
|
|
138
|
+
const c = globalThis.crypto;
|
|
139
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
140
|
+
const bytes = new Uint8Array(16);
|
|
141
|
+
if (c?.getRandomValues) c.getRandomValues(bytes);
|
|
142
|
+
else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
143
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
144
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
145
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
146
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
147
|
+
}
|
|
148
|
+
var MAX_PROP_KEYS = 50;
|
|
149
|
+
var MAX_STRING = 2048;
|
|
150
|
+
function cleanProps(props) {
|
|
151
|
+
if (!props) return void 0;
|
|
152
|
+
const out = {};
|
|
153
|
+
let count = 0;
|
|
154
|
+
for (const [rawKey, value] of Object.entries(props)) {
|
|
155
|
+
if (value === void 0) continue;
|
|
156
|
+
if (count >= MAX_PROP_KEYS) break;
|
|
157
|
+
const key = rawKey.slice(0, 64);
|
|
158
|
+
if (value === null || typeof value === "boolean") out[key] = value;
|
|
159
|
+
else if (typeof value === "string") out[key] = value.slice(0, MAX_STRING);
|
|
160
|
+
else if (typeof value === "number") {
|
|
161
|
+
if (!Number.isFinite(value)) continue;
|
|
162
|
+
out[key] = value;
|
|
163
|
+
} else out[key] = (JSON.stringify(value) ?? "").slice(0, MAX_STRING);
|
|
164
|
+
count++;
|
|
165
|
+
}
|
|
166
|
+
return count ? out : void 0;
|
|
167
|
+
}
|
|
168
|
+
function toEventName(name) {
|
|
169
|
+
const snake = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
|
|
170
|
+
const prefixed = /^[a-z]/.test(snake) ? snake : `e_${snake}`;
|
|
171
|
+
return prefixed.slice(0, 64);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export { EventNames, LIBRARY, assign, cleanProps, notFound, toEventName, toExperiment, uuid };
|
|
175
|
+
//# sourceMappingURL=chunk-BN7JI6EH.js.map
|
|
176
|
+
//# sourceMappingURL=chunk-BN7JI6EH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../schema/src/assign.ts","../../schema/src/names.ts","../src/shared/experiment.ts","../src/shared/util.ts"],"names":[],"mappings":";AAaO,IAAM,OAAA,GAAU,GAAA;AAEvB,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAGzB,SAAS,OAAA,CAAQ,GAAA,EAAa,IAAA,GAAO,CAAA,EAAW;AACrD,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,MAAA,CAAO,GAAG,CAAA;AAChC,EAAA,MAAM,SAAS,KAAA,CAAM,MAAA;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AM,WAAW,QAAA,CAAS,IAAA,CAAK,KAAK,CAAA,GAAI,KAAA,GAAQ,KAAK,KAAK,CAAA,CAAA;AAE1D,EAAA,OAAO,QAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAC7B","file":"chunk-BN7JI6EH.js","sourcesContent":["import type { ExperimentConfig } from \"./experiments\";\n\n/**\n * Deterministic experiment assignment. Pure and synchronous so it runs in the Next.js server,\n * the edge proxy, or the browser and always gives the same answer for the same user.\n *\n * Two independent hashes are used:\n * - `salt:alloc` decides whether the user is in the test at all (compared to `allocation`)\n * - `salt:variant` decides which variant they get\n * Keeping them independent means raising allocation from 10% to 50% only adds users; nobody\n * already in the test changes variant.\n */\n\nexport const BUCKETS = 10_000;\n\nconst encoder = new TextEncoder();\n\n/** MurmurHash3 x86 32-bit over the UTF-8 bytes of `key`. */\nexport function murmur3(key: string, seed = 0): number {\n const bytes = encoder.encode(key);\n const length = bytes.length;\n const blocks = length >>> 2;\n const c1 = 0xcc9e2d51;\n const c2 = 0x1b873593;\n let h = seed >>> 0;\n\n for (let i = 0; i < blocks; i++) {\n const o = i * 4;\n let k = (bytes[o]! | (bytes[o + 1]! << 8) | (bytes[o + 2]! << 16) | (bytes[o + 3]! << 24)) >>> 0;\n k = Math.imul(k, c1);\n k = (k << 15) | (k >>> 17);\n k = Math.imul(k, c2);\n h ^= k;\n h = (h << 13) | (h >>> 19);\n h = (Math.imul(h, 5) + 0xe6546b64) >>> 0;\n }\n\n const tail = blocks * 4;\n let k1 = 0;\n switch (length & 3) {\n case 3:\n k1 ^= bytes[tail + 2]! << 16;\n // falls through\n case 2:\n k1 ^= bytes[tail + 1]! << 8;\n // falls through\n case 1:\n k1 ^= bytes[tail]!;\n k1 = Math.imul(k1, c1);\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = Math.imul(k1, c2);\n h ^= k1;\n }\n\n h ^= length;\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h >>> 0;\n}\n\n/** Bucket 0..BUCKETS-1 for a unit id under a salt. */\nexport function bucketFor(salt: string, unitId: string): number {\n return murmur3(`${salt}.${unitId}`) % BUCKETS;\n}\n\nexport interface AssignmentUnit {\n /** Anonymous id. Experiments are assigned per device/browser, not per login. */\n id: string;\n country?: string;\n locale?: string;\n}\n\nexport type AssignmentReason =\n /** In the test; an exposure should be logged when a param is read. */\n | \"assigned\"\n /** Experiment is launched; everyone gets the launched variant and no exposure is logged. */\n | \"launched\"\n /** Outside the allocation percentage. Gets fallbacks. */\n | \"not_allocated\"\n /** Country or locale outside the targeting rules. Gets fallbacks. */\n | \"targeting\"\n /** No running or launched experiment with that key. Gets fallbacks. */\n | \"not_found\";\n\nexport interface Assignment {\n experiment: string;\n /** Variant key, or null when the user gets fallbacks. */\n variant: string | null;\n params: Record<string, unknown>;\n reason: AssignmentReason;\n}\n\nfunction matchesTargeting(experiment: ExperimentConfig, unit: AssignmentUnit): boolean {\n const { countries, locales } = experiment.targeting ?? {};\n if (countries?.length) {\n const country = unit.country?.toUpperCase();\n if (!country || !countries.includes(country)) return false;\n }\n if (locales?.length) {\n const language = unit.locale?.toLowerCase().split(/[-_]/)[0];\n if (!language || !locales.includes(language)) return false;\n }\n\n return true;\n}\n\nexport function notFound(key: string): Assignment {\n return { experiment: key, variant: null, params: {}, reason: \"not_found\" };\n}\n\nexport function assign(experiment: ExperimentConfig, unit: AssignmentUnit): Assignment {\n const empty = (reason: AssignmentReason): Assignment => ({\n experiment: experiment.key,\n variant: null,\n params: {},\n reason,\n });\n\n if (experiment.status === \"launched\") {\n const launched = experiment.variants.find((v) => v.key === experiment.launchedVariant);\n if (!launched) return empty(\"not_found\");\n\n return { experiment: experiment.key, variant: launched.key, params: launched.params, reason: \"launched\" };\n }\n\n if (!matchesTargeting(experiment, unit)) return empty(\"targeting\");\n\n if (bucketFor(`${experiment.salt}:alloc`, unit.id) >= Math.round(experiment.allocation * BUCKETS)) {\n return empty(\"not_allocated\");\n }\n\n const totalWeight = experiment.variants.reduce((sum, v) => sum + Math.max(0, v.weight), 0);\n if (totalWeight <= 0) return empty(\"not_allocated\");\n\n const point = (bucketFor(`${experiment.salt}:variant`, unit.id) / BUCKETS) * totalWeight;\n let cumulative = 0;\n for (const variant of experiment.variants) {\n cumulative += Math.max(0, variant.weight);\n if (point < cumulative) {\n return { experiment: experiment.key, variant: variant.key, params: variant.params, reason: \"assigned\" };\n }\n }\n\n // Floating-point edge: fall through to the last weighted variant.\n const last = [...experiment.variants].reverse().find((v) => v.weight > 0)!;\n\n return { experiment: experiment.key, variant: last.key, params: last.params, reason: \"assigned\" };\n}\n","/**\n * Canonical event names. Products may send any snake_case name, but these have fixed meaning\n * in dashboards, funnels and experiment metrics, so map onto them where one fits.\n */\nexport const EventNames = {\n // Emitted by the SDK\n PageView: \"page_view\",\n SessionStart: \"session_start\",\n ExperimentExposure: \"experiment_exposure\",\n Identify: \"identify\",\n\n // Ecommerce funnel (pithos `TrackingEventName` and Hoola GTM events map onto these)\n ViewContent: \"view_content\",\n AddToCart: \"add_to_cart\",\n InitiateCheckout: \"initiate_checkout\",\n CheckoutEmailCaptured: \"checkout_email_captured\",\n Purchase: \"purchase\",\n Upsell: \"upsell\",\n FailedOrder: \"failed_order\",\n FailedTransaction: \"failed_transaction\",\n\n // Engagement\n CtaClicked: \"cta_clicked\",\n QuizStepViewed: \"quiz_step_viewed\",\n QuizStepCompleted: \"quiz_step_completed\",\n QuizCompleted: \"quiz_completed\",\n} as const;\n\nexport type EventName = (typeof EventNames)[keyof typeof EventNames];\n\n/** Props keys with fixed meaning on `experiment_exposure`. */\nexport const ExposureProps = {\n experiment: \"experiment\",\n variant: \"variant\",\n} as const;\n","import type { Assignment, AssignmentReason } from \"@faceyoga/analytics-schema/assign\";\n\n/** What `getExperiment` returns on both client and server. Mirrors Statsig's `experiment.get(name, fallback)`. */\nexport interface Experiment {\n key: string;\n /** Variant key, or null when the user gets fallbacks (not allocated, not targeted, unknown key). */\n variant: string | null;\n reason: AssignmentReason;\n /** Read a variant parameter. Returns `fallback` when the param is missing or of a different type. */\n get<T>(param: string, fallback: T): T;\n /** All params of the assigned variant. */\n params: Record<string, unknown>;\n}\n\nfunction sameType(value: unknown, fallback: unknown): boolean {\n if (fallback === null || fallback === undefined) return value !== undefined;\n if (Array.isArray(fallback)) return Array.isArray(value);\n\n return value !== null && typeof value === typeof fallback && !Array.isArray(value);\n}\n\nexport function toExperiment(assignment: Assignment): Experiment {\n return {\n key: assignment.experiment,\n variant: assignment.variant,\n reason: assignment.reason,\n params: assignment.params,\n get<T>(param: string, fallback: T): T {\n const value = assignment.params[param];\n\n return sameType(value, fallback) ? (value as T) : fallback;\n },\n };\n}\n","export const LIBRARY = { name: \"@faceyoga/analytics\", version: \"0.1.1\" } as const;\n\nexport function uuid(): string {\n const c = globalThis.crypto;\n if (c?.randomUUID) return c.randomUUID();\n\n // RFC 4122 v4 fallback for old in-app browsers without randomUUID.\n const bytes = new Uint8Array(16);\n if (c?.getRandomValues) c.getRandomValues(bytes);\n else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst MAX_PROP_KEYS = 50;\nconst MAX_STRING = 2048;\n\n/**\n * Coerce props into what the collector accepts: flat primitives, at most 50 keys, strings\n * capped at 2,048 chars. Nested objects (e.g. quiz answers) are JSON-stringified rather than\n * dropped, so nothing silently disappears and no new Axiom columns get created.\n */\nexport function cleanProps(\n props: Record<string, unknown> | undefined\n): Record<string, string | number | boolean | null> | undefined {\n if (!props) return undefined;\n const out: Record<string, string | number | boolean | null> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(props)) {\n if (value === undefined) continue;\n if (count >= MAX_PROP_KEYS) break;\n const key = rawKey.slice(0, 64);\n if (value === null || typeof value === \"boolean\") out[key] = value;\n else if (typeof value === \"string\") out[key] = value.slice(0, MAX_STRING);\n else if (typeof value === \"number\") {\n if (!Number.isFinite(value)) continue;\n out[key] = value;\n } else out[key] = (JSON.stringify(value) ?? \"\").slice(0, MAX_STRING);\n count++;\n }\n\n return count ? out : undefined;\n}\n\n/** Map arbitrary names (`PageView`, `quiz-step viewed`) onto the collector's snake_case rule. */\nexport function toEventName(name: string): string {\n const snake = name\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .toLowerCase();\n const prefixed = /^[a-z]/.test(snake) ? snake : `e_${snake}`;\n\n return prefixed.slice(0, 64);\n}\n"]}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { E as Experiment, A as Assignment } from './names-MWUOMlPa.js';
|
|
2
|
+
export { a as EventNames } from './names-MWUOMlPa.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Browser pixel. One instance per page app, created once (module scope or a root provider).
|
|
6
|
+
*
|
|
7
|
+
* - Events are queued and sent in batches (`maxBatchSize` or every `flushIntervalMs`).
|
|
8
|
+
* - When the tab is hidden or closed, the queue is drained with `navigator.sendBeacon`.
|
|
9
|
+
* - Bodies are `text/plain` JSON so cross-origin sends never need a CORS preflight; better still,
|
|
10
|
+
* send to the app's own `/a/collect` route (`createCollectHandler`) so ad blockers leave it alone.
|
|
11
|
+
*/
|
|
12
|
+
type SendResult = "ok" | "retry" | "drop";
|
|
13
|
+
interface Transport {
|
|
14
|
+
send(body: string, options: {
|
|
15
|
+
beacon: boolean;
|
|
16
|
+
}): Promise<SendResult>;
|
|
17
|
+
}
|
|
18
|
+
interface ClientExperimentBootstrap {
|
|
19
|
+
/** From `experiments.getClientBootstrap(unit)` on the server. */
|
|
20
|
+
assignments: Record<string, Assignment>;
|
|
21
|
+
/** The server's deployment environment; used when `environment` is not passed. */
|
|
22
|
+
environment?: string;
|
|
23
|
+
}
|
|
24
|
+
interface AnalyticsOptions {
|
|
25
|
+
/**
|
|
26
|
+
* Where batches go. Preferred: `/a/collect`, a same-origin route built with
|
|
27
|
+
* `createCollectHandler` from `@faceyoga/analytics/server`; no `writeKey` is needed then.
|
|
28
|
+
* Alternatively the collector itself, `https://analytics.example.com/api/collect`, with a `writeKey`.
|
|
29
|
+
*/
|
|
30
|
+
endpoint: string;
|
|
31
|
+
/** Public per-product key. Only for sending straight to the collector, not through `/a/collect`. */
|
|
32
|
+
writeKey?: string;
|
|
33
|
+
/**
|
|
34
|
+
* `production` | `preview` | `development`. Default: the server's value from `bootstrap`, else
|
|
35
|
+
* `unknown`. Ignored when sending through `/a/collect`, which stamps the server's own environment.
|
|
36
|
+
*/
|
|
37
|
+
environment?: string;
|
|
38
|
+
/**
|
|
39
|
+
* Cookie that already holds the product's anonymous id (pithos `{product}_user_id`,
|
|
40
|
+
* Hoola `hoola-userId`). Reusing it keeps ids identical to Statsig, Meta `external_id` and Axiom.
|
|
41
|
+
* When missing, the SDK mints its own `fya_aid` cookie.
|
|
42
|
+
*/
|
|
43
|
+
anonymousIdCookie?: string;
|
|
44
|
+
/** Explicit anonymous id; wins over the cookie. */
|
|
45
|
+
anonymousId?: string;
|
|
46
|
+
/** Logged-in user id, if known at startup. */
|
|
47
|
+
userId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Experiment assignments to tag onto every event (experiment key -> variant), e.g. from
|
|
50
|
+
* `experiments.getAssignments(unit)`. This is what lets heatmaps and replays be split by variant.
|
|
51
|
+
*/
|
|
52
|
+
assignments?: Record<string, string>;
|
|
53
|
+
/** Full client-side experiment values for apps that read params in the browser (Hoola). */
|
|
54
|
+
bootstrap?: ClientExperimentBootstrap;
|
|
55
|
+
flushIntervalMs?: number;
|
|
56
|
+
maxBatchSize?: number;
|
|
57
|
+
maxQueueSize?: number;
|
|
58
|
+
/** Inactivity after which the next event starts a new session. Default 30 minutes. */
|
|
59
|
+
sessionTimeoutMs?: number;
|
|
60
|
+
autocapture?: {
|
|
61
|
+
/** Initial load plus client-side navigations (history API). Default true. */
|
|
62
|
+
pageViews?: boolean;
|
|
63
|
+
};
|
|
64
|
+
/** Skip automated browsers (Playwright smoke tests). Default true. */
|
|
65
|
+
ignoreAutomation?: boolean;
|
|
66
|
+
disabled?: boolean;
|
|
67
|
+
debug?: boolean;
|
|
68
|
+
/** Test seam; defaults to fetch + sendBeacon. */
|
|
69
|
+
transport?: Transport;
|
|
70
|
+
}
|
|
71
|
+
interface TrackOptions {
|
|
72
|
+
/** Event id. Use the order id for purchases so retries de-duplicate. */
|
|
73
|
+
id?: string;
|
|
74
|
+
value?: number;
|
|
75
|
+
currency?: string;
|
|
76
|
+
orderId?: string;
|
|
77
|
+
}
|
|
78
|
+
interface Analytics {
|
|
79
|
+
/** Queue an event. Returns its id. */
|
|
80
|
+
track(name: string, props?: Record<string, unknown>, options?: TrackOptions): string;
|
|
81
|
+
page(props?: Record<string, unknown>): string;
|
|
82
|
+
/** Attach a logged-in user id to this device and all following events. */
|
|
83
|
+
identify(userId: string, traits?: Record<string, unknown>): void;
|
|
84
|
+
/** Forget the user id (logout). The anonymous id stays. */
|
|
85
|
+
reset(): void;
|
|
86
|
+
/** Read a client-side experiment; logs one exposure per experiment per session. */
|
|
87
|
+
getExperiment(key: string): Experiment;
|
|
88
|
+
setAssignments(assignments: Record<string, string>): void;
|
|
89
|
+
getAnonymousId(): string;
|
|
90
|
+
getSessionId(): string;
|
|
91
|
+
flush(): Promise<void>;
|
|
92
|
+
shutdown(): void;
|
|
93
|
+
}
|
|
94
|
+
declare function createFetchTransport(endpoint: string): Transport;
|
|
95
|
+
declare function createAnalytics(options: AnalyticsOptions): Analytics;
|
|
96
|
+
|
|
97
|
+
export { type Analytics, type AnalyticsOptions, Assignment, type ClientExperimentBootstrap, Experiment, type SendResult, type TrackOptions, type Transport, createAnalytics, createFetchTransport };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { uuid, notFound, EventNames, toExperiment, LIBRARY, toEventName, cleanProps } from './chunk-BN7JI6EH.js';
|
|
2
|
+
export { EventNames } from './chunk-BN7JI6EH.js';
|
|
3
|
+
|
|
4
|
+
// src/client/storage.ts
|
|
5
|
+
function readCookie(name) {
|
|
6
|
+
if (typeof document === "undefined") return void 0;
|
|
7
|
+
try {
|
|
8
|
+
const prefix = `${encodeURIComponent(name)}=`;
|
|
9
|
+
for (const part of document.cookie.split(";")) {
|
|
10
|
+
const trimmed = part.trim();
|
|
11
|
+
if (trimmed.startsWith(prefix)) return decodeURIComponent(trimmed.slice(prefix.length)) || void 0;
|
|
12
|
+
}
|
|
13
|
+
} catch {
|
|
14
|
+
}
|
|
15
|
+
return void 0;
|
|
16
|
+
}
|
|
17
|
+
function writeCookie(name, value, maxAgeSeconds) {
|
|
18
|
+
if (typeof document === "undefined") return;
|
|
19
|
+
try {
|
|
20
|
+
const secure = typeof location !== "undefined" && location.protocol === "https:" ? "; Secure" : "";
|
|
21
|
+
document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax${secure}`;
|
|
22
|
+
} catch {
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function readJson(kind, key) {
|
|
26
|
+
try {
|
|
27
|
+
const raw = globalThis[kind]?.getItem(key);
|
|
28
|
+
return raw ? JSON.parse(raw) : void 0;
|
|
29
|
+
} catch {
|
|
30
|
+
return void 0;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function writeJson(kind, key, value) {
|
|
34
|
+
try {
|
|
35
|
+
globalThis[kind]?.setItem(key, JSON.stringify(value));
|
|
36
|
+
} catch {
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/client/index.ts
|
|
41
|
+
var OWN_ANON_COOKIE = "fya_aid";
|
|
42
|
+
var USER_KEY = "fya_uid";
|
|
43
|
+
var SESSION_KEY = "fya_session";
|
|
44
|
+
var EXPOSED_KEY = "fya_exposed";
|
|
45
|
+
var ONE_YEAR = 365 * 24 * 60 * 60;
|
|
46
|
+
function createNoop() {
|
|
47
|
+
const empty = toExperiment(notFound(""));
|
|
48
|
+
return {
|
|
49
|
+
track: () => "",
|
|
50
|
+
page: () => "",
|
|
51
|
+
identify: () => {
|
|
52
|
+
},
|
|
53
|
+
reset: () => {
|
|
54
|
+
},
|
|
55
|
+
getExperiment: (key) => ({ ...empty, key }),
|
|
56
|
+
setAssignments: () => {
|
|
57
|
+
},
|
|
58
|
+
getAnonymousId: () => "",
|
|
59
|
+
getSessionId: () => "",
|
|
60
|
+
flush: async () => {
|
|
61
|
+
},
|
|
62
|
+
shutdown: () => {
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function createFetchTransport(endpoint) {
|
|
67
|
+
return {
|
|
68
|
+
async send(body, { beacon }) {
|
|
69
|
+
if (beacon && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
|
|
70
|
+
try {
|
|
71
|
+
if (navigator.sendBeacon(endpoint, new Blob([body], { type: "text/plain;charset=UTF-8" }))) return "ok";
|
|
72
|
+
} catch {
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const response = await fetch(endpoint, {
|
|
77
|
+
method: "POST",
|
|
78
|
+
body,
|
|
79
|
+
headers: { "Content-Type": "text/plain;charset=UTF-8" },
|
|
80
|
+
// keepalive bodies are capped at 64 KB per page.
|
|
81
|
+
keepalive: body.length < 6e4,
|
|
82
|
+
credentials: "omit"
|
|
83
|
+
});
|
|
84
|
+
if (response.ok) return "ok";
|
|
85
|
+
return response.status === 429 || response.status >= 500 ? "retry" : "drop";
|
|
86
|
+
} catch {
|
|
87
|
+
return "retry";
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function createAnalytics(options) {
|
|
93
|
+
if (typeof window === "undefined" || options.disabled) return createNoop();
|
|
94
|
+
if ((options.ignoreAutomation ?? true) && typeof navigator !== "undefined" && navigator.webdriver) {
|
|
95
|
+
return createNoop();
|
|
96
|
+
}
|
|
97
|
+
const flushIntervalMs = options.flushIntervalMs ?? 3e3;
|
|
98
|
+
const maxBatchSize = Math.min(options.maxBatchSize ?? 20, 100);
|
|
99
|
+
const maxQueueSize = options.maxQueueSize ?? 500;
|
|
100
|
+
const sessionTimeoutMs = options.sessionTimeoutMs ?? 30 * 60 * 1e3;
|
|
101
|
+
const environment = options.environment ?? options.bootstrap?.environment ?? "unknown";
|
|
102
|
+
const transport = options.transport ?? createFetchTransport(options.endpoint);
|
|
103
|
+
const log = (...args) => {
|
|
104
|
+
if (options.debug) console.debug("[analytics]", ...args);
|
|
105
|
+
};
|
|
106
|
+
let anonymousId = options.anonymousId || (options.anonymousIdCookie ? readCookie(options.anonymousIdCookie) : void 0) || readCookie(OWN_ANON_COOKIE) || "";
|
|
107
|
+
if (!anonymousId) {
|
|
108
|
+
anonymousId = uuid();
|
|
109
|
+
writeCookie(OWN_ANON_COOKIE, anonymousId, ONE_YEAR);
|
|
110
|
+
}
|
|
111
|
+
let userId = options.userId || readJson("localStorage", USER_KEY);
|
|
112
|
+
if (options.userId) writeJson("localStorage", USER_KEY, options.userId);
|
|
113
|
+
const bootstrapAssignments = options.bootstrap?.assignments ?? {};
|
|
114
|
+
let assignments = { ...options.assignments };
|
|
115
|
+
for (const assignment of Object.values(bootstrapAssignments)) {
|
|
116
|
+
if (assignment.reason === "assigned" && assignment.variant) assignments[assignment.experiment] = assignment.variant;
|
|
117
|
+
}
|
|
118
|
+
const exposed = new Set(readJson("sessionStorage", EXPOSED_KEY) ?? []);
|
|
119
|
+
let sessionId = "";
|
|
120
|
+
function touchSession(now) {
|
|
121
|
+
const stored = readJson("localStorage", SESSION_KEY);
|
|
122
|
+
const isNew = !stored || now - stored.last > sessionTimeoutMs;
|
|
123
|
+
sessionId = isNew ? uuid() : stored.id;
|
|
124
|
+
writeJson("localStorage", SESSION_KEY, { id: sessionId, last: now });
|
|
125
|
+
return isNew;
|
|
126
|
+
}
|
|
127
|
+
const queue = [];
|
|
128
|
+
let timer;
|
|
129
|
+
let flushing = false;
|
|
130
|
+
let backoffMs = 0;
|
|
131
|
+
const serialize = (events) => JSON.stringify({
|
|
132
|
+
writeKey: options.writeKey,
|
|
133
|
+
sentAt: Date.now(),
|
|
134
|
+
source: "client",
|
|
135
|
+
environment,
|
|
136
|
+
library: LIBRARY,
|
|
137
|
+
events
|
|
138
|
+
});
|
|
139
|
+
function trimQueue() {
|
|
140
|
+
if (queue.length > maxQueueSize) queue.splice(0, queue.length - maxQueueSize);
|
|
141
|
+
}
|
|
142
|
+
function schedule() {
|
|
143
|
+
if (timer || queue.length === 0) return;
|
|
144
|
+
timer = setTimeout(() => {
|
|
145
|
+
timer = void 0;
|
|
146
|
+
void flush();
|
|
147
|
+
}, flushIntervalMs + backoffMs);
|
|
148
|
+
}
|
|
149
|
+
async function flush() {
|
|
150
|
+
if (flushing) return;
|
|
151
|
+
flushing = true;
|
|
152
|
+
if (timer) {
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
timer = void 0;
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
while (queue.length) {
|
|
158
|
+
const events = queue.splice(0, maxBatchSize);
|
|
159
|
+
const result = await transport.send(serialize(events), { beacon: false });
|
|
160
|
+
log("flush", events.length, result);
|
|
161
|
+
if (result === "retry") {
|
|
162
|
+
queue.unshift(...events);
|
|
163
|
+
trimQueue();
|
|
164
|
+
backoffMs = Math.min(backoffMs ? backoffMs * 2 : 1e3, 3e4);
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
backoffMs = 0;
|
|
168
|
+
}
|
|
169
|
+
} finally {
|
|
170
|
+
flushing = false;
|
|
171
|
+
schedule();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function drainWithBeacon() {
|
|
175
|
+
if (timer) {
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
timer = void 0;
|
|
178
|
+
}
|
|
179
|
+
while (queue.length) void transport.send(serialize(queue.splice(0, maxBatchSize)), { beacon: true });
|
|
180
|
+
}
|
|
181
|
+
function enqueue(event) {
|
|
182
|
+
queue.push(event);
|
|
183
|
+
trimQueue();
|
|
184
|
+
log("track", event.name, event);
|
|
185
|
+
if (queue.length >= maxBatchSize) void flush();
|
|
186
|
+
else schedule();
|
|
187
|
+
}
|
|
188
|
+
function build(name, props, extra = {}) {
|
|
189
|
+
const event = {
|
|
190
|
+
id: extra.id || uuid(),
|
|
191
|
+
name: toEventName(name),
|
|
192
|
+
ts: Date.now(),
|
|
193
|
+
anonymousId,
|
|
194
|
+
sessionId,
|
|
195
|
+
url: location.href.slice(0, 2048)
|
|
196
|
+
};
|
|
197
|
+
if (userId) event.userId = userId;
|
|
198
|
+
if (extra.value !== void 0 && Number.isFinite(extra.value)) event.value = extra.value;
|
|
199
|
+
if (extra.currency) event.currency = extra.currency;
|
|
200
|
+
if (extra.orderId) event.orderId = extra.orderId;
|
|
201
|
+
if (extra.referrer) event.referrer = extra.referrer.slice(0, 2048);
|
|
202
|
+
if (Object.keys(assignments).length) event.experiments = { ...assignments };
|
|
203
|
+
const cleaned = cleanProps(props);
|
|
204
|
+
if (cleaned) event.props = cleaned;
|
|
205
|
+
return event;
|
|
206
|
+
}
|
|
207
|
+
function track(name, props, extra) {
|
|
208
|
+
if (touchSession(Date.now())) {
|
|
209
|
+
enqueue(build(EventNames.SessionStart, { landing_url: location.href, referrer: document.referrer || null }));
|
|
210
|
+
}
|
|
211
|
+
const event = build(name, props, extra);
|
|
212
|
+
enqueue(event);
|
|
213
|
+
return event.id;
|
|
214
|
+
}
|
|
215
|
+
let lastPageUrl;
|
|
216
|
+
let previousUrl;
|
|
217
|
+
function page(props) {
|
|
218
|
+
const href = location.href;
|
|
219
|
+
const referrer = previousUrl ?? (document.referrer || void 0);
|
|
220
|
+
previousUrl = href;
|
|
221
|
+
lastPageUrl = href;
|
|
222
|
+
return track(
|
|
223
|
+
EventNames.PageView,
|
|
224
|
+
{ path: location.pathname, title: document.title || null, ...props },
|
|
225
|
+
referrer ? { referrer } : void 0
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
const cleanups = [];
|
|
229
|
+
if (options.autocapture?.pageViews ?? true) {
|
|
230
|
+
const onNavigate = () => {
|
|
231
|
+
setTimeout(() => {
|
|
232
|
+
const href = location.href.split("#")[0];
|
|
233
|
+
if (href !== lastPageUrl?.split("#")[0]) page();
|
|
234
|
+
}, 0);
|
|
235
|
+
};
|
|
236
|
+
const { pushState, replaceState } = history;
|
|
237
|
+
history.pushState = function(...args) {
|
|
238
|
+
pushState.apply(this, args);
|
|
239
|
+
onNavigate();
|
|
240
|
+
};
|
|
241
|
+
history.replaceState = function(...args) {
|
|
242
|
+
replaceState.apply(this, args);
|
|
243
|
+
onNavigate();
|
|
244
|
+
};
|
|
245
|
+
window.addEventListener("popstate", onNavigate);
|
|
246
|
+
cleanups.push(() => {
|
|
247
|
+
history.pushState = pushState;
|
|
248
|
+
history.replaceState = replaceState;
|
|
249
|
+
window.removeEventListener("popstate", onNavigate);
|
|
250
|
+
});
|
|
251
|
+
setTimeout(() => {
|
|
252
|
+
if (!lastPageUrl) page();
|
|
253
|
+
}, 0);
|
|
254
|
+
}
|
|
255
|
+
const onHide = () => {
|
|
256
|
+
if (document.visibilityState === "hidden") drainWithBeacon();
|
|
257
|
+
};
|
|
258
|
+
document.addEventListener("visibilitychange", onHide);
|
|
259
|
+
window.addEventListener("pagehide", drainWithBeacon);
|
|
260
|
+
cleanups.push(() => {
|
|
261
|
+
document.removeEventListener("visibilitychange", onHide);
|
|
262
|
+
window.removeEventListener("pagehide", drainWithBeacon);
|
|
263
|
+
});
|
|
264
|
+
return {
|
|
265
|
+
track,
|
|
266
|
+
page,
|
|
267
|
+
identify(id, traits) {
|
|
268
|
+
if (!id) return;
|
|
269
|
+
const changed = id !== userId;
|
|
270
|
+
userId = id;
|
|
271
|
+
writeJson("localStorage", USER_KEY, id);
|
|
272
|
+
if (changed) track(EventNames.Identify, traits);
|
|
273
|
+
},
|
|
274
|
+
reset() {
|
|
275
|
+
userId = void 0;
|
|
276
|
+
try {
|
|
277
|
+
localStorage.removeItem(USER_KEY);
|
|
278
|
+
} catch {
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
getExperiment(key) {
|
|
282
|
+
const assignment = bootstrapAssignments[key] ?? notFound(key);
|
|
283
|
+
if (assignment.reason === "assigned" && assignment.variant && !exposed.has(key)) {
|
|
284
|
+
exposed.add(key);
|
|
285
|
+
writeJson("sessionStorage", EXPOSED_KEY, [...exposed]);
|
|
286
|
+
track(EventNames.ExperimentExposure, { experiment: key, variant: assignment.variant });
|
|
287
|
+
}
|
|
288
|
+
return toExperiment(assignment);
|
|
289
|
+
},
|
|
290
|
+
setAssignments(next) {
|
|
291
|
+
assignments = { ...next };
|
|
292
|
+
},
|
|
293
|
+
getAnonymousId: () => anonymousId,
|
|
294
|
+
getSessionId: () => sessionId,
|
|
295
|
+
flush,
|
|
296
|
+
shutdown() {
|
|
297
|
+
for (const cleanup of cleanups) cleanup();
|
|
298
|
+
drainWithBeacon();
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export { createAnalytics, createFetchTransport };
|
|
304
|
+
//# sourceMappingURL=client.js.map
|
|
305
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/storage.ts","../src/client/index.ts"],"names":[],"mappings":";;;;AAEO,SAAS,WAAW,IAAA,EAAkC;AAC3D,EAAA,IAAI,OAAO,QAAA,KAAa,WAAA,EAAa,OAAO,MAAA;AAC5C,EAAA,IAAI;AACF,IAAA,M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AA,IACA,eAAe,IAAA,EAAM;AACnB,MAAA,WAAA,GAAc,EAAE,GAAG,IAAA,EAAK;AAAA,IAC1B,CAAA;AAAA,IACA,gBAAgB,MAAM,WAAA;AAAA,IACtB,cAAc,MAAM,SAAA;AAAA,IACpB,KAAA;AAAA,IACA,QAAA,GAAW;AACT,MAAA,KAAA,MAAW,OAAA,IAAW,UAAU,OAAA,EAAQ;AACxC,MAAA,eAAA,EAAgB;AAAA,IAClB;AAAA,GACF;AACF","file":"client.js","sourcesContent":["/** Storage helpers that never throw: private mode, blocked cookies and quota errors are all \"no value\". */\n\nexport function readCookie(name: string): string | undefined {\n if (typeof document === \"undefined\") return undefined;\n try {\n const prefix = `${encodeURIComponent(name)}=`;\n for (const part of document.cookie.split(\";\")) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) return decodeURIComponent(trimmed.slice(prefix.length)) || undefined;\n }\n } catch {\n // Cookies disabled.\n }\n\n return undefined;\n}\n\nexport function writeCookie(name: string, value: string, maxAgeSeconds: number) {\n if (typeof document === \"undefined\") return;\n try {\n const secure = typeof location !== \"undefined\" && location.protocol === \"https:\" ? \"; Secure\" : \"\";\n document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax${secure}`;\n } catch {\n // Cookies disabled.\n }\n}\n\ntype StorageKind = \"localStorage\" | \"sessionStorage\";\n\nexport function readJson<T>(kind: StorageKind, key: string): T | undefined {\n try {\n const raw = globalThis[kind]?.getItem(key);\n\n return raw ? (JSON.parse(raw) as T) : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function writeJson(kind: StorageKind, key: string, value: unknown) {\n try {\n globalThis[kind]?.setItem(key, JSON.stringify(value));\n } catch {\n // Private mode or quota.\n }\n}\n","import type { AnalyticsEvent, EventProps } from \"@faceyoga/analytics-schema/events\";\nimport { notFound, type Assignment } from \"@faceyoga/analytics-schema/assign\";\nimport { EventNames } from \"@faceyoga/analytics-schema/names\";\nimport { toExperiment, type Experiment } from \"../shared/experiment\";\nimport { cleanProps, LIBRARY, toEventName, uuid } from \"../shared/util\";\nimport { readCookie, readJson, writeCookie, writeJson } from \"./storage\";\n\nexport type { Experiment } from \"../shared/experiment\";\nexport type { Assignment } from \"@faceyoga/analytics-schema/assign\";\nexport { EventNames } from \"@faceyoga/analytics-schema/names\";\n\n/**\n * Browser pixel. One instance per page app, created once (module scope or a root provider).\n *\n * - Events are queued and sent in batches (`maxBatchSize` or every `flushIntervalMs`).\n * - When the tab is hidden or closed, the queue is drained with `navigator.sendBeacon`.\n * - Bodies are `text/plain` JSON so cross-origin sends never need a CORS preflight; better still,\n * send to the app's own `/a/collect` route (`createCollectHandler`) so ad blockers leave it alone.\n */\n\nexport type SendResult = \"ok\" | \"retry\" | \"drop\";\n\nexport interface Transport {\n send(body: string, options: { beacon: boolean }): Promise<SendResult>;\n}\n\nexport interface ClientExperimentBootstrap {\n /** From `experiments.getClientBootstrap(unit)` on the server. */\n assignments: Record<string, Assignment>;\n /** The server's deployment environment; used when `environment` is not passed. */\n environment?: string;\n}\n\nexport interface AnalyticsOptions {\n /**\n * Where batches go. Preferred: `/a/collect`, a same-origin route built with\n * `createCollectHandler` from `@faceyoga/analytics/server`; no `writeKey` is needed then.\n * Alternatively the collector itself, `https://analytics.example.com/api/collect`, with a `writeKey`.\n */\n endpoint: string;\n /** Public per-product key. Only for sending straight to the collector, not through `/a/collect`. */\n writeKey?: string;\n /**\n * `production` | `preview` | `development`. Default: the server's value from `bootstrap`, else\n * `unknown`. Ignored when sending through `/a/collect`, which stamps the server's own environment.\n */\n environment?: string;\n /**\n * Cookie that already holds the product's anonymous id (pithos `{product}_user_id`,\n * Hoola `hoola-userId`). Reusing it keeps ids identical to Statsig, Meta `external_id` and Axiom.\n * When missing, the SDK mints its own `fya_aid` cookie.\n */\n anonymousIdCookie?: string;\n /** Explicit anonymous id; wins over the cookie. */\n anonymousId?: string;\n /** Logged-in user id, if known at startup. */\n userId?: string;\n /**\n * Experiment assignments to tag onto every event (experiment key -> variant), e.g. from\n * `experiments.getAssignments(unit)`. This is what lets heatmaps and replays be split by variant.\n */\n assignments?: Record<string, string>;\n /** Full client-side experiment values for apps that read params in the browser (Hoola). */\n bootstrap?: ClientExperimentBootstrap;\n flushIntervalMs?: number;\n maxBatchSize?: number;\n maxQueueSize?: number;\n /** Inactivity after which the next event starts a new session. Default 30 minutes. */\n sessionTimeoutMs?: number;\n autocapture?: {\n /** Initial load plus client-side navigations (history API). Default true. */\n pageViews?: boolean;\n };\n /** Skip automated browsers (Playwright smoke tests). Default true. */\n ignoreAutomation?: boolean;\n disabled?: boolean;\n debug?: boolean;\n /** Test seam; defaults to fetch + sendBeacon. */\n transport?: Transport;\n}\n\nexport interface TrackOptions {\n /** Event id. Use the order id for purchases so retries de-duplicate. */\n id?: string;\n value?: number;\n currency?: string;\n orderId?: string;\n}\n\nexport interface Analytics {\n /** Queue an event. Returns its id. */\n track(name: string, props?: Record<string, unknown>, options?: TrackOptions): string;\n page(props?: Record<string, unknown>): string;\n /** Attach a logged-in user id to this device and all following events. */\n identify(userId: string, traits?: Record<string, unknown>): void;\n /** Forget the user id (logout). The anonymous id stays. */\n reset(): void;\n /** Read a client-side experiment; logs one exposure per experiment per session. */\n getExperiment(key: string): Experiment;\n setAssignments(assignments: Record<string, string>): void;\n getAnonymousId(): string;\n getSessionId(): string;\n flush(): Promise<void>;\n shutdown(): void;\n}\n\nconst OWN_ANON_COOKIE = \"fya_aid\";\nconst USER_KEY = \"fya_uid\";\nconst SESSION_KEY = \"fya_session\";\nconst EXPOSED_KEY = \"fya_exposed\";\nconst ONE_YEAR = 365 * 24 * 60 * 60;\n\nfunction createNoop(): Analytics {\n const empty = toExperiment(notFound(\"\"));\n\n return {\n track: () => \"\",\n page: () => \"\",\n identify: () => {},\n reset: () => {},\n getExperiment: (key) => ({ ...empty, key }),\n setAssignments: () => {},\n getAnonymousId: () => \"\",\n getSessionId: () => \"\",\n flush: async () => {},\n shutdown: () => {},\n };\n}\n\nexport function createFetchTransport(endpoint: string): Transport {\n return {\n async send(body, { beacon }) {\n if (beacon && typeof navigator !== \"undefined\" && typeof navigator.sendBeacon === \"function\") {\n try {\n if (navigator.sendBeacon(endpoint, new Blob([body], { type: \"text/plain;charset=UTF-8\" }))) return \"ok\";\n } catch {\n // Fall through to fetch.\n }\n }\n try {\n const response = await fetch(endpoint, {\n method: \"POST\",\n body,\n headers: { \"Content-Type\": \"text/plain;charset=UTF-8\" },\n // keepalive bodies are capped at 64 KB per page.\n keepalive: body.length < 60_000,\n credentials: \"omit\",\n });\n if (response.ok) return \"ok\";\n\n return response.status === 429 || response.status >= 500 ? \"retry\" : \"drop\";\n } catch {\n return \"retry\";\n }\n },\n };\n}\n\nexport function createAnalytics(options: AnalyticsOptions): Analytics {\n if (typeof window === \"undefined\" || options.disabled) return createNoop();\n if ((options.ignoreAutomation ?? true) && typeof navigator !== \"undefined\" && navigator.webdriver) {\n return createNoop();\n }\n\n const flushIntervalMs = options.flushIntervalMs ?? 3_000;\n const maxBatchSize = Math.min(options.maxBatchSize ?? 20, 100);\n const maxQueueSize = options.maxQueueSize ?? 500;\n const sessionTimeoutMs = options.sessionTimeoutMs ?? 30 * 60 * 1000;\n const environment = options.environment ?? options.bootstrap?.environment ?? \"unknown\";\n const transport = options.transport ?? createFetchTransport(options.endpoint);\n const log = (...args: unknown[]) => {\n if (options.debug) console.debug(\"[analytics]\", ...args);\n };\n\n // --- identity -------------------------------------------------------------\n let anonymousId =\n options.anonymousId ||\n (options.anonymousIdCookie ? readCookie(options.anonymousIdCookie) : undefined) ||\n readCookie(OWN_ANON_COOKIE) ||\n \"\";\n if (!anonymousId) {\n anonymousId = uuid();\n writeCookie(OWN_ANON_COOKIE, anonymousId, ONE_YEAR);\n }\n let userId: string | undefined = options.userId || readJson<string>(\"localStorage\", USER_KEY);\n if (options.userId) writeJson(\"localStorage\", USER_KEY, options.userId);\n\n // --- experiments ----------------------------------------------------------\n const bootstrapAssignments = options.bootstrap?.assignments ?? {};\n let assignments: Record<string, string> = { ...options.assignments };\n for (const assignment of Object.values(bootstrapAssignments)) {\n if (assignment.reason === \"assigned\" && assignment.variant) assignments[assignment.experiment] = assignment.variant;\n }\n const exposed = new Set<string>(readJson<string[]>(\"sessionStorage\", EXPOSED_KEY) ?? []);\n\n // --- session --------------------------------------------------------------\n let sessionId = \"\";\n function touchSession(now: number): boolean {\n const stored = readJson<{ id: string; last: number }>(\"localStorage\", SESSION_KEY);\n const isNew = !stored || now - stored.last > sessionTimeoutMs;\n sessionId = isNew ? uuid() : stored.id;\n writeJson(\"localStorage\", SESSION_KEY, { id: sessionId, last: now });\n\n return isNew;\n }\n\n // --- queue + transport ----------------------------------------------------\n const queue: AnalyticsEvent[] = [];\n let timer: ReturnType<typeof setTimeout> | undefined;\n let flushing = false;\n let backoffMs = 0;\n\n const serialize = (events: AnalyticsEvent[]) =>\n JSON.stringify({\n writeKey: options.writeKey,\n sentAt: Date.now(),\n source: \"client\",\n environment,\n library: LIBRARY,\n events,\n });\n\n function trimQueue() {\n if (queue.length > maxQueueSize) queue.splice(0, queue.length - maxQueueSize);\n }\n\n function schedule() {\n if (timer || queue.length === 0) return;\n timer = setTimeout(() => {\n timer = undefined;\n void flush();\n }, flushIntervalMs + backoffMs);\n }\n\n async function flush(): Promise<void> {\n if (flushing) return;\n flushing = true;\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n try {\n while (queue.length) {\n const events = queue.splice(0, maxBatchSize);\n const result = await transport.send(serialize(events), { beacon: false });\n log(\"flush\", events.length, result);\n if (result === \"retry\") {\n queue.unshift(...events);\n trimQueue();\n backoffMs = Math.min(backoffMs ? backoffMs * 2 : 1_000, 30_000);\n break;\n }\n backoffMs = 0;\n }\n } finally {\n flushing = false;\n schedule();\n }\n }\n\n function drainWithBeacon() {\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n while (queue.length) void transport.send(serialize(queue.splice(0, maxBatchSize)), { beacon: true });\n }\n\n function enqueue(event: AnalyticsEvent) {\n queue.push(event);\n trimQueue();\n log(\"track\", event.name, event);\n if (queue.length >= maxBatchSize) void flush();\n else schedule();\n }\n\n type InternalOptions = TrackOptions & { referrer?: string };\n\n function build(\n name: string,\n props: Record<string, unknown> | undefined,\n extra: InternalOptions = {}\n ): AnalyticsEvent {\n const event: AnalyticsEvent = {\n id: extra.id || uuid(),\n name: toEventName(name),\n ts: Date.now(),\n anonymousId,\n sessionId,\n url: location.href.slice(0, 2048),\n };\n if (userId) event.userId = userId;\n if (extra.value !== undefined && Number.isFinite(extra.value)) event.value = extra.value;\n if (extra.currency) event.currency = extra.currency;\n if (extra.orderId) event.orderId = extra.orderId;\n if (extra.referrer) event.referrer = extra.referrer.slice(0, 2048);\n if (Object.keys(assignments).length) event.experiments = { ...assignments };\n const cleaned = cleanProps(props) as EventProps | undefined;\n if (cleaned) event.props = cleaned;\n\n return event;\n }\n\n function track(name: string, props?: Record<string, unknown>, extra?: InternalOptions): string {\n if (touchSession(Date.now())) {\n enqueue(build(EventNames.SessionStart, { landing_url: location.href, referrer: document.referrer || null }));\n }\n const event = build(name, props, extra);\n enqueue(event);\n\n return event.id;\n }\n\n // --- page views -----------------------------------------------------------\n let lastPageUrl: string | undefined;\n let previousUrl: string | undefined;\n\n function page(props?: Record<string, unknown>): string {\n const href = location.href;\n const referrer = previousUrl ?? (document.referrer || undefined);\n previousUrl = href;\n lastPageUrl = href;\n\n return track(\n EventNames.PageView,\n { path: location.pathname, title: document.title || null, ...props },\n referrer ? { referrer } : undefined\n );\n }\n\n const cleanups: Array<() => void> = [];\n\n if (options.autocapture?.pageViews ?? true) {\n const onNavigate = () => {\n // Next.js updates the URL before rendering; wait a tick so document.title is the new page's.\n setTimeout(() => {\n const href = location.href.split(\"#\")[0];\n if (href !== lastPageUrl?.split(\"#\")[0]) page();\n }, 0);\n };\n const { pushState, replaceState } = history;\n history.pushState = function (...args: Parameters<History[\"pushState\"]>) {\n pushState.apply(this, args);\n onNavigate();\n };\n history.replaceState = function (...args: Parameters<History[\"replaceState\"]>) {\n replaceState.apply(this, args);\n onNavigate();\n };\n window.addEventListener(\"popstate\", onNavigate);\n cleanups.push(() => {\n history.pushState = pushState;\n history.replaceState = replaceState;\n window.removeEventListener(\"popstate\", onNavigate);\n });\n // Initial view on the next tick so callers can set assignments / identify first.\n setTimeout(() => {\n if (!lastPageUrl) page();\n }, 0);\n }\n\n const onHide = () => {\n if (document.visibilityState === \"hidden\") drainWithBeacon();\n };\n document.addEventListener(\"visibilitychange\", onHide);\n window.addEventListener(\"pagehide\", drainWithBeacon);\n cleanups.push(() => {\n document.removeEventListener(\"visibilitychange\", onHide);\n window.removeEventListener(\"pagehide\", drainWithBeacon);\n });\n\n return {\n track,\n page,\n identify(id, traits) {\n if (!id) return;\n const changed = id !== userId;\n userId = id;\n writeJson(\"localStorage\", USER_KEY, id);\n if (changed) track(EventNames.Identify, traits);\n },\n reset() {\n userId = undefined;\n try {\n localStorage.removeItem(USER_KEY);\n } catch {\n // Private mode.\n }\n },\n getExperiment(key) {\n const assignment = bootstrapAssignments[key] ?? notFound(key);\n if (assignment.reason === \"assigned\" && assignment.variant && !exposed.has(key)) {\n exposed.add(key);\n writeJson(\"sessionStorage\", EXPOSED_KEY, [...exposed]);\n track(EventNames.ExperimentExposure, { experiment: key, variant: assignment.variant });\n }\n\n return toExperiment(assignment);\n },\n setAssignments(next) {\n assignments = { ...next };\n },\n getAnonymousId: () => anonymousId,\n getSessionId: () => sessionId,\n flush,\n shutdown() {\n for (const cleanup of cleanups) cleanup();\n drainWithBeacon();\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
interface AssignmentUnit {
|
|
2
|
+
/** Anonymous id. Experiments are assigned per device/browser, not per login. */
|
|
3
|
+
id: string;
|
|
4
|
+
country?: string;
|
|
5
|
+
locale?: string;
|
|
6
|
+
}
|
|
7
|
+
type AssignmentReason =
|
|
8
|
+
/** In the test; an exposure should be logged when a param is read. */
|
|
9
|
+
"assigned"
|
|
10
|
+
/** Experiment is launched; everyone gets the launched variant and no exposure is logged. */
|
|
11
|
+
| "launched"
|
|
12
|
+
/** Outside the allocation percentage. Gets fallbacks. */
|
|
13
|
+
| "not_allocated"
|
|
14
|
+
/** Country or locale outside the targeting rules. Gets fallbacks. */
|
|
15
|
+
| "targeting"
|
|
16
|
+
/** No running or launched experiment with that key. Gets fallbacks. */
|
|
17
|
+
| "not_found";
|
|
18
|
+
interface Assignment {
|
|
19
|
+
experiment: string;
|
|
20
|
+
/** Variant key, or null when the user gets fallbacks. */
|
|
21
|
+
variant: string | null;
|
|
22
|
+
params: Record<string, unknown>;
|
|
23
|
+
reason: AssignmentReason;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What `getExperiment` returns on both client and server. Mirrors Statsig's `experiment.get(name, fallback)`. */
|
|
27
|
+
interface Experiment {
|
|
28
|
+
key: string;
|
|
29
|
+
/** Variant key, or null when the user gets fallbacks (not allocated, not targeted, unknown key). */
|
|
30
|
+
variant: string | null;
|
|
31
|
+
reason: AssignmentReason;
|
|
32
|
+
/** Read a variant parameter. Returns `fallback` when the param is missing or of a different type. */
|
|
33
|
+
get<T>(param: string, fallback: T): T;
|
|
34
|
+
/** All params of the assigned variant. */
|
|
35
|
+
params: Record<string, unknown>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Canonical event names. Products may send any snake_case name, but these have fixed meaning
|
|
40
|
+
* in dashboards, funnels and experiment metrics, so map onto them where one fits.
|
|
41
|
+
*/
|
|
42
|
+
declare const EventNames: {
|
|
43
|
+
readonly PageView: "page_view";
|
|
44
|
+
readonly SessionStart: "session_start";
|
|
45
|
+
readonly ExperimentExposure: "experiment_exposure";
|
|
46
|
+
readonly Identify: "identify";
|
|
47
|
+
readonly ViewContent: "view_content";
|
|
48
|
+
readonly AddToCart: "add_to_cart";
|
|
49
|
+
readonly InitiateCheckout: "initiate_checkout";
|
|
50
|
+
readonly CheckoutEmailCaptured: "checkout_email_captured";
|
|
51
|
+
readonly Purchase: "purchase";
|
|
52
|
+
readonly Upsell: "upsell";
|
|
53
|
+
readonly FailedOrder: "failed_order";
|
|
54
|
+
readonly FailedTransaction: "failed_transaction";
|
|
55
|
+
readonly CtaClicked: "cta_clicked";
|
|
56
|
+
readonly QuizStepViewed: "quiz_step_viewed";
|
|
57
|
+
readonly QuizStepCompleted: "quiz_step_completed";
|
|
58
|
+
readonly QuizCompleted: "quiz_completed";
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export { type Assignment as A, type Experiment as E, EventNames as a, type AssignmentUnit as b };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { b as AssignmentUnit, E as Experiment, A as Assignment } from './names-MWUOMlPa.js';
|
|
3
|
+
export { a as EventNames } from './names-MWUOMlPa.js';
|
|
4
|
+
|
|
5
|
+
declare const experimentSchema: z.ZodObject<{
|
|
6
|
+
key: z.ZodString;
|
|
7
|
+
status: z.ZodEnum<{
|
|
8
|
+
launched: "launched";
|
|
9
|
+
running: "running";
|
|
10
|
+
}>;
|
|
11
|
+
salt: z.ZodString;
|
|
12
|
+
allocation: z.ZodNumber;
|
|
13
|
+
variants: z.ZodArray<z.ZodObject<{
|
|
14
|
+
key: z.ZodString;
|
|
15
|
+
weight: z.ZodNumber;
|
|
16
|
+
params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
17
|
+
}, z.core.$strip>>;
|
|
18
|
+
launchedVariant: z.ZodOptional<z.ZodString>;
|
|
19
|
+
targeting: z.ZodOptional<z.ZodObject<{
|
|
20
|
+
countries: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
21
|
+
locales: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
22
|
+
}, z.core.$strip>>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
declare const experimentsPayloadSchema: z.ZodObject<{
|
|
25
|
+
product: z.ZodString;
|
|
26
|
+
version: z.ZodString;
|
|
27
|
+
experiments: z.ZodArray<z.ZodObject<{
|
|
28
|
+
key: z.ZodString;
|
|
29
|
+
status: z.ZodEnum<{
|
|
30
|
+
launched: "launched";
|
|
31
|
+
running: "running";
|
|
32
|
+
}>;
|
|
33
|
+
salt: z.ZodString;
|
|
34
|
+
allocation: z.ZodNumber;
|
|
35
|
+
variants: z.ZodArray<z.ZodObject<{
|
|
36
|
+
key: z.ZodString;
|
|
37
|
+
weight: z.ZodNumber;
|
|
38
|
+
params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
39
|
+
}, z.core.$strip>>;
|
|
40
|
+
launchedVariant: z.ZodOptional<z.ZodString>;
|
|
41
|
+
targeting: z.ZodOptional<z.ZodObject<{
|
|
42
|
+
countries: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
43
|
+
locales: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
44
|
+
}, z.core.$strip>>;
|
|
45
|
+
}, z.core.$strip>>;
|
|
46
|
+
}, z.core.$strip>;
|
|
47
|
+
type ExperimentConfig = z.infer<typeof experimentSchema>;
|
|
48
|
+
type ExperimentsPayload = z.infer<typeof experimentsPayloadSchema>;
|
|
49
|
+
|
|
50
|
+
declare const eventSchema: z.ZodObject<{
|
|
51
|
+
id: z.ZodString;
|
|
52
|
+
name: z.ZodString;
|
|
53
|
+
ts: z.ZodNumber;
|
|
54
|
+
anonymousId: z.ZodString;
|
|
55
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
56
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
57
|
+
url: z.ZodOptional<z.ZodString>;
|
|
58
|
+
referrer: z.ZodOptional<z.ZodString>;
|
|
59
|
+
value: z.ZodOptional<z.ZodNumber>;
|
|
60
|
+
currency: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
61
|
+
orderId: z.ZodOptional<z.ZodString>;
|
|
62
|
+
experiments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
63
|
+
props: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>>;
|
|
64
|
+
}, z.core.$strip>;
|
|
65
|
+
/** An event as the SDK sends it. */
|
|
66
|
+
type AnalyticsEvent = z.input<typeof eventSchema>;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Server-side event sender for events that originate on the server (pithos `dispatchTrackingEvent`,
|
|
70
|
+
* upsell charges from cron, webhook-driven purchases) and for experiment exposures.
|
|
71
|
+
*
|
|
72
|
+
* Serverless functions freeze after the response, so nothing is sent on a timer: queue with
|
|
73
|
+
* `track()` and call `flush()` inside Next.js `after()` (or `waitUntil`) before the request ends.
|
|
74
|
+
*/
|
|
75
|
+
interface ServerAnalyticsOptions {
|
|
76
|
+
/** Collector URL, e.g. `https://analytics.example.com/api/collect`. */
|
|
77
|
+
endpoint: string;
|
|
78
|
+
/** Secret server key for the product. Never ship it to the browser. */
|
|
79
|
+
serverKey: string;
|
|
80
|
+
/** `production` | `preview` | `development`. Default: `VERCEL_ENV`, or `development` when unset. */
|
|
81
|
+
environment?: string;
|
|
82
|
+
/** Flush automatically once this many events are queued. Default 100 (the batch cap). */
|
|
83
|
+
maxBatchSize?: number;
|
|
84
|
+
fetch?: typeof fetch;
|
|
85
|
+
onError?: (error: unknown) => void;
|
|
86
|
+
}
|
|
87
|
+
type ServerEventInput = Omit<AnalyticsEvent, "id" | "ts" | "name" | "props"> & {
|
|
88
|
+
name: string;
|
|
89
|
+
id?: string;
|
|
90
|
+
ts?: number;
|
|
91
|
+
props?: Record<string, unknown>;
|
|
92
|
+
};
|
|
93
|
+
interface ServerAnalytics {
|
|
94
|
+
track(event: ServerEventInput): string;
|
|
95
|
+
flush(): Promise<void>;
|
|
96
|
+
/** Events waiting to be sent. */
|
|
97
|
+
pending(): number;
|
|
98
|
+
}
|
|
99
|
+
declare function createServerAnalytics(options: ServerAnalyticsOptions): ServerAnalytics;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Server-side experiments, the replacement for `statsig.getExperiment(user, name)`.
|
|
103
|
+
*
|
|
104
|
+
* Config is fetched from the analytics app and kept in memory; assignment is a local hash, so
|
|
105
|
+
* `getExperiment` never waits on the network once `ready()` has resolved. Stale config is
|
|
106
|
+
* refreshed in the background on the next read after `refreshIntervalMs`.
|
|
107
|
+
*/
|
|
108
|
+
interface ExperimentsOptions {
|
|
109
|
+
/** Analytics app base URL, e.g. `https://analytics.example.com`. */
|
|
110
|
+
baseUrl: string;
|
|
111
|
+
serverKey: string;
|
|
112
|
+
/** Exposures are queued here; flush it in `after()`. Without it no exposures are logged. */
|
|
113
|
+
analytics?: ServerAnalytics;
|
|
114
|
+
refreshIntervalMs?: number;
|
|
115
|
+
/**
|
|
116
|
+
* Max wait for one config request. On timeout or error the last loaded config is kept, or
|
|
117
|
+
* every `get()` returns its fallback when none was loaded. Default 1000 ms.
|
|
118
|
+
*/
|
|
119
|
+
timeoutMs?: number;
|
|
120
|
+
/** Seed config, e.g. a build-time snapshot, so the very first request has values. */
|
|
121
|
+
initial?: ExperimentsPayload;
|
|
122
|
+
fetch?: typeof fetch;
|
|
123
|
+
onError?: (error: unknown) => void;
|
|
124
|
+
}
|
|
125
|
+
interface ExperimentUnit extends AssignmentUnit {
|
|
126
|
+
/** Logged-in user id, copied onto exposure events. */
|
|
127
|
+
userId?: string;
|
|
128
|
+
/** Page URL, copied onto exposure events. */
|
|
129
|
+
url?: string;
|
|
130
|
+
}
|
|
131
|
+
interface Experiments {
|
|
132
|
+
/**
|
|
133
|
+
* Resolves after the first config load, at most `timeoutMs` later (immediately when `initial`
|
|
134
|
+
* was given). Never rejects; failures go to `onError`.
|
|
135
|
+
*/
|
|
136
|
+
ready(): Promise<void>;
|
|
137
|
+
/** Assign and log one exposure (per unit and experiment, per instance) when the user is in the test. */
|
|
138
|
+
getExperiment(unit: ExperimentUnit, key: string): Experiment;
|
|
139
|
+
/** Assign without logging an exposure, e.g. to decide what to prefetch. */
|
|
140
|
+
peek(unit: AssignmentUnit, key: string): Experiment;
|
|
141
|
+
/** Experiment key -> variant for every test the unit is in. Tag client events with this. */
|
|
142
|
+
getAssignments(unit: AssignmentUnit): Record<string, string>;
|
|
143
|
+
/** Everything a browser needs to evaluate experiments locally (Hoola-style client reads). */
|
|
144
|
+
getClientBootstrap(unit: AssignmentUnit): {
|
|
145
|
+
assignments: Record<string, Assignment>;
|
|
146
|
+
environment: string;
|
|
147
|
+
};
|
|
148
|
+
/** Force a config reload. */
|
|
149
|
+
refresh(): Promise<void>;
|
|
150
|
+
/** Version of the config currently in memory, or null before the first load. */
|
|
151
|
+
version(): string | null;
|
|
152
|
+
}
|
|
153
|
+
declare function createExperiments(options: ExperimentsOptions): Experiments;
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Same-origin collect route for a storefront. The browser pixel posts to `/a/collect` on the
|
|
157
|
+
* storefront itself, which:
|
|
158
|
+
* - keeps analytics requests first-party, so ad blockers and CORS never get involved;
|
|
159
|
+
* - means the browser needs no key at all: this route signs the batch with the server key;
|
|
160
|
+
* - forwards the visitor's Vercel geo headers and user agent, which the collector would not
|
|
161
|
+
* see on a server-to-server request (or reliably through a rewrite);
|
|
162
|
+
* - stamps the batch with this deployment's environment, so preview and local traffic is never
|
|
163
|
+
* counted as production whatever the browser sent.
|
|
164
|
+
*
|
|
165
|
+
* // app/a/collect/route.ts
|
|
166
|
+
* export const POST = createCollectHandler({
|
|
167
|
+
* collectorUrl: `${process.env.ANALYTICS_URL}/api/collect`,
|
|
168
|
+
* serverKey: process.env.ANALYTICS_SERVER_KEY!,
|
|
169
|
+
* });
|
|
170
|
+
*
|
|
171
|
+
* The collector answers before it writes to Axiom, so awaiting it adds little latency, and its
|
|
172
|
+
* status is passed back so the pixel retries on 429 / 5xx.
|
|
173
|
+
*/
|
|
174
|
+
interface CollectHandlerOptions {
|
|
175
|
+
/** Collector URL, e.g. `https://analytics.example.com/api/collect`. */
|
|
176
|
+
collectorUrl: string;
|
|
177
|
+
/** Secret server key for the product. */
|
|
178
|
+
serverKey: string;
|
|
179
|
+
/** Overrides the batch's `environment`. Default: `VERCEL_ENV`, or `development` when unset. */
|
|
180
|
+
environment?: string;
|
|
181
|
+
fetch?: typeof fetch;
|
|
182
|
+
onError?: (error: unknown) => void;
|
|
183
|
+
}
|
|
184
|
+
declare function createCollectHandler(options: CollectHandlerOptions): (request: Request) => Promise<Response>;
|
|
185
|
+
|
|
186
|
+
export { type AnalyticsEvent, Assignment, AssignmentUnit, type CollectHandlerOptions, Experiment, type ExperimentConfig, type ExperimentUnit, type Experiments, type ExperimentsOptions, type ExperimentsPayload, type ServerAnalytics, type ServerAnalyticsOptions, type ServerEventInput, createCollectHandler, createExperiments, createServerAnalytics };
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { toEventName, uuid, cleanProps, assign, toExperiment, notFound, EventNames, LIBRARY } from './chunk-BN7JI6EH.js';
|
|
2
|
+
export { EventNames } from './chunk-BN7JI6EH.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
// src/server/environment.ts
|
|
6
|
+
function serverEnvironment() {
|
|
7
|
+
return typeof process !== "undefined" && process.env.VERCEL_ENV || "development";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// src/server/analytics.ts
|
|
11
|
+
function createServerAnalytics(options) {
|
|
12
|
+
const maxBatchSize = Math.min(options.maxBatchSize ?? 100, 100);
|
|
13
|
+
const environment = options.environment ?? serverEnvironment();
|
|
14
|
+
const doFetch = options.fetch ?? fetch;
|
|
15
|
+
const onError = options.onError ?? ((error) => console.error("[analytics] server flush failed:", error));
|
|
16
|
+
const queue = [];
|
|
17
|
+
let inFlight = Promise.resolve();
|
|
18
|
+
async function send(events) {
|
|
19
|
+
try {
|
|
20
|
+
const response = await doFetch(options.endpoint, {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${options.serverKey}` },
|
|
23
|
+
body: JSON.stringify({
|
|
24
|
+
sentAt: Date.now(),
|
|
25
|
+
source: "server",
|
|
26
|
+
environment,
|
|
27
|
+
library: LIBRARY,
|
|
28
|
+
events
|
|
29
|
+
})
|
|
30
|
+
});
|
|
31
|
+
if (!response.ok) onError(new Error(`collector responded ${response.status}: ${await response.text()}`));
|
|
32
|
+
} catch (error) {
|
|
33
|
+
onError(error);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function flush() {
|
|
37
|
+
const batches = [];
|
|
38
|
+
while (queue.length) batches.push(queue.splice(0, maxBatchSize));
|
|
39
|
+
inFlight = inFlight.then(() => Promise.all(batches.map(send)).then(() => {
|
|
40
|
+
}));
|
|
41
|
+
return inFlight;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
track(input) {
|
|
45
|
+
const { props, name, id, ts, ...rest } = input;
|
|
46
|
+
const event = {
|
|
47
|
+
...rest,
|
|
48
|
+
id: id || uuid(),
|
|
49
|
+
name: toEventName(name),
|
|
50
|
+
ts: ts ?? Date.now()
|
|
51
|
+
};
|
|
52
|
+
const cleaned = cleanProps(props);
|
|
53
|
+
if (cleaned) event.props = cleaned;
|
|
54
|
+
queue.push(event);
|
|
55
|
+
if (queue.length >= maxBatchSize) void flush();
|
|
56
|
+
return event.id;
|
|
57
|
+
},
|
|
58
|
+
flush,
|
|
59
|
+
pending: () => queue.length
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
var variantSchema = z.object({
|
|
63
|
+
key: z.string().min(1).max(64),
|
|
64
|
+
/** Relative weight. Weights do not need to sum to 100. */
|
|
65
|
+
weight: z.number().min(0),
|
|
66
|
+
/** Parameters read with `experiment.get(name, fallback)`, e.g. `{ preselect_3_pack: true }`. */
|
|
67
|
+
params: z.record(z.string(), z.unknown()).default({})
|
|
68
|
+
});
|
|
69
|
+
var targetingSchema = z.object({
|
|
70
|
+
/** ISO 3166 alpha-2, upper case. Empty or missing = all countries. */
|
|
71
|
+
countries: z.array(z.string().length(2)).optional(),
|
|
72
|
+
/** Lower-case language codes, e.g. `en`, `de`. Empty or missing = all locales. */
|
|
73
|
+
locales: z.array(z.string().min(2).max(16)).optional()
|
|
74
|
+
});
|
|
75
|
+
var experimentSchema = z.object({
|
|
76
|
+
key: z.string().min(1).max(128),
|
|
77
|
+
status: z.enum(["running", "launched"]),
|
|
78
|
+
/**
|
|
79
|
+
* Hash salt. Defaults to the key; changing it reshuffles every user, so only do that when
|
|
80
|
+
* restarting a test from scratch.
|
|
81
|
+
*/
|
|
82
|
+
salt: z.string().min(1).max(128),
|
|
83
|
+
/** Share of eligible traffic in the test, 0..1. Raising it only adds users; nobody switches variant. */
|
|
84
|
+
allocation: z.number().min(0).max(1),
|
|
85
|
+
variants: z.array(variantSchema).min(1),
|
|
86
|
+
/** Required when `status` is `launched`: everyone gets this variant and no exposures are logged. */
|
|
87
|
+
launchedVariant: z.string().optional(),
|
|
88
|
+
targeting: targetingSchema.optional()
|
|
89
|
+
});
|
|
90
|
+
var experimentsPayloadSchema = z.object({
|
|
91
|
+
product: z.string(),
|
|
92
|
+
/** Changes whenever any served experiment changes, so SDKs can skip re-parsing. */
|
|
93
|
+
version: z.string(),
|
|
94
|
+
experiments: z.array(experimentSchema)
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// src/server/experiments.ts
|
|
98
|
+
var EXPOSURE_CACHE_LIMIT = 5e4;
|
|
99
|
+
function createExperiments(options) {
|
|
100
|
+
const refreshIntervalMs = options.refreshIntervalMs ?? 3e4;
|
|
101
|
+
const timeoutMs = options.timeoutMs ?? 1e3;
|
|
102
|
+
const doFetch = options.fetch ?? fetch;
|
|
103
|
+
const onError = options.onError ?? ((error) => console.error("[analytics] experiments refresh failed:", error));
|
|
104
|
+
const url = `${options.baseUrl.replace(/\/+$/, "")}/api/experiments`;
|
|
105
|
+
let byKey = /* @__PURE__ */ new Map();
|
|
106
|
+
let currentVersion = null;
|
|
107
|
+
let loadedAt = 0;
|
|
108
|
+
let loading = null;
|
|
109
|
+
const exposed = /* @__PURE__ */ new Set();
|
|
110
|
+
function apply(payload) {
|
|
111
|
+
byKey = new Map(payload.experiments.map((e) => [e.key, e]));
|
|
112
|
+
currentVersion = payload.version;
|
|
113
|
+
}
|
|
114
|
+
if (options.initial) {
|
|
115
|
+
apply(experimentsPayloadSchema.parse(options.initial));
|
|
116
|
+
loadedAt = Date.now();
|
|
117
|
+
}
|
|
118
|
+
async function fetchConfig(signal) {
|
|
119
|
+
const response = await doFetch(url, {
|
|
120
|
+
headers: {
|
|
121
|
+
Authorization: `Bearer ${options.serverKey}`,
|
|
122
|
+
...currentVersion ? { "If-None-Match": `"${currentVersion}"` } : {}
|
|
123
|
+
},
|
|
124
|
+
cache: "no-store",
|
|
125
|
+
signal
|
|
126
|
+
});
|
|
127
|
+
if (response.status === 304) return;
|
|
128
|
+
if (!response.ok) throw new Error(`experiments endpoint responded ${response.status}`);
|
|
129
|
+
apply(experimentsPayloadSchema.parse(await response.json()));
|
|
130
|
+
}
|
|
131
|
+
async function load() {
|
|
132
|
+
const controller = new AbortController();
|
|
133
|
+
let timer;
|
|
134
|
+
const timedOut = new Promise((_, reject) => {
|
|
135
|
+
timer = setTimeout(() => {
|
|
136
|
+
const error = new Error(`experiments request timed out after ${timeoutMs} ms`);
|
|
137
|
+
controller.abort(error);
|
|
138
|
+
reject(error);
|
|
139
|
+
}, timeoutMs);
|
|
140
|
+
});
|
|
141
|
+
try {
|
|
142
|
+
await Promise.race([fetchConfig(controller.signal), timedOut]);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
onError(error);
|
|
145
|
+
} finally {
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
loadedAt = Date.now();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function refresh() {
|
|
151
|
+
if (!loading) {
|
|
152
|
+
loading = load().finally(() => {
|
|
153
|
+
loading = null;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return loading;
|
|
157
|
+
}
|
|
158
|
+
function maybeRefresh() {
|
|
159
|
+
if (Date.now() - loadedAt > refreshIntervalMs) void refresh();
|
|
160
|
+
}
|
|
161
|
+
function resolve(unit, key) {
|
|
162
|
+
maybeRefresh();
|
|
163
|
+
const config = byKey.get(key);
|
|
164
|
+
return config ? assign(config, unit) : notFound(key);
|
|
165
|
+
}
|
|
166
|
+
function logExposure(unit, assignment) {
|
|
167
|
+
if (!options.analytics || assignment.reason !== "assigned" || !assignment.variant) return;
|
|
168
|
+
const cacheKey = `${assignment.experiment}\0${assignment.variant}\0${unit.id}`;
|
|
169
|
+
if (exposed.has(cacheKey)) return;
|
|
170
|
+
exposed.add(cacheKey);
|
|
171
|
+
if (exposed.size > EXPOSURE_CACHE_LIMIT) exposed.delete(exposed.values().next().value);
|
|
172
|
+
options.analytics.track({
|
|
173
|
+
name: EventNames.ExperimentExposure,
|
|
174
|
+
anonymousId: unit.id,
|
|
175
|
+
...unit.userId && { userId: unit.userId },
|
|
176
|
+
...unit.url && { url: unit.url },
|
|
177
|
+
experiments: { [assignment.experiment]: assignment.variant },
|
|
178
|
+
props: {
|
|
179
|
+
experiment: assignment.experiment,
|
|
180
|
+
variant: assignment.variant,
|
|
181
|
+
...unit.country && { country: unit.country },
|
|
182
|
+
...unit.locale && { locale: unit.locale }
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
ready: () => loadedAt ? Promise.resolve() : refresh(),
|
|
188
|
+
getExperiment(unit, key) {
|
|
189
|
+
const assignment = resolve(unit, key);
|
|
190
|
+
logExposure(unit, assignment);
|
|
191
|
+
return toExperiment(assignment);
|
|
192
|
+
},
|
|
193
|
+
peek: (unit, key) => toExperiment(resolve(unit, key)),
|
|
194
|
+
getAssignments(unit) {
|
|
195
|
+
maybeRefresh();
|
|
196
|
+
const out = {};
|
|
197
|
+
for (const config of byKey.values()) {
|
|
198
|
+
if (config.status !== "running") continue;
|
|
199
|
+
const assignment = assign(config, unit);
|
|
200
|
+
if (assignment.reason === "assigned" && assignment.variant) out[config.key] = assignment.variant;
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
},
|
|
204
|
+
getClientBootstrap(unit) {
|
|
205
|
+
maybeRefresh();
|
|
206
|
+
const assignments = {};
|
|
207
|
+
for (const config of byKey.values()) assignments[config.key] = assign(config, unit);
|
|
208
|
+
return { assignments, environment: serverEnvironment() };
|
|
209
|
+
},
|
|
210
|
+
refresh,
|
|
211
|
+
version: () => currentVersion
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ../schema/src/forwarding.ts
|
|
216
|
+
var FORWARD_HEADERS = {
|
|
217
|
+
/** Marks a forwarded browser batch: stored as `source: "client"` and bot-filtered. */
|
|
218
|
+
forwarded: "x-fya-forwarded",
|
|
219
|
+
userAgent: "x-fya-client-user-agent",
|
|
220
|
+
country: "x-fya-client-country",
|
|
221
|
+
region: "x-fya-client-region",
|
|
222
|
+
city: "x-fya-client-city"
|
|
223
|
+
};
|
|
224
|
+
var VERCEL_GEO_HEADERS = {
|
|
225
|
+
"x-vercel-ip-country": FORWARD_HEADERS.country,
|
|
226
|
+
"x-vercel-ip-country-region": FORWARD_HEADERS.region,
|
|
227
|
+
"x-vercel-ip-city": FORWARD_HEADERS.city
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
// src/server/collect-handler.ts
|
|
231
|
+
var MAX_BODY_BYTES = 512 * 1024;
|
|
232
|
+
function createCollectHandler(options) {
|
|
233
|
+
const doFetch = options.fetch ?? fetch;
|
|
234
|
+
const environment = options.environment ?? serverEnvironment();
|
|
235
|
+
const onError = options.onError ?? ((error) => console.error("[analytics] collect forward failed:", error));
|
|
236
|
+
return async function collect(request) {
|
|
237
|
+
if (request.method !== "POST") return new Response(null, { status: 405, headers: { Allow: "POST" } });
|
|
238
|
+
if (Number(request.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) return new Response(null, { status: 413 });
|
|
239
|
+
const raw = await request.text();
|
|
240
|
+
if (raw.length > MAX_BODY_BYTES) return new Response(null, { status: 413 });
|
|
241
|
+
const body = withEnvironment(raw, environment);
|
|
242
|
+
const headers = new Headers({
|
|
243
|
+
"Content-Type": "application/json",
|
|
244
|
+
Authorization: `Bearer ${options.serverKey}`,
|
|
245
|
+
[FORWARD_HEADERS.forwarded]: "1"
|
|
246
|
+
});
|
|
247
|
+
const userAgent = request.headers.get("user-agent");
|
|
248
|
+
if (userAgent) headers.set(FORWARD_HEADERS.userAgent, userAgent);
|
|
249
|
+
for (const [vercel, forwarded] of Object.entries(VERCEL_GEO_HEADERS)) {
|
|
250
|
+
const value = request.headers.get(vercel);
|
|
251
|
+
if (value) headers.set(forwarded, value);
|
|
252
|
+
}
|
|
253
|
+
try {
|
|
254
|
+
const response = await doFetch(options.collectorUrl, { method: "POST", headers, body });
|
|
255
|
+
if (response.status >= 500) onError(new Error(`collector responded ${response.status}`));
|
|
256
|
+
return new Response(null, { status: response.ok ? 204 : response.status });
|
|
257
|
+
} catch (error) {
|
|
258
|
+
onError(error);
|
|
259
|
+
return new Response(null, { status: 502 });
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
function withEnvironment(body, environment) {
|
|
264
|
+
try {
|
|
265
|
+
const batch = JSON.parse(body);
|
|
266
|
+
if (!batch || typeof batch !== "object" || Array.isArray(batch)) return body;
|
|
267
|
+
return JSON.stringify({ ...batch, environment });
|
|
268
|
+
} catch {
|
|
269
|
+
return body;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export { createCollectHandler, createExperiments, createServerAnalytics };
|
|
274
|
+
//# sourceMappingURL=server.js.map
|
|
275
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/environment.ts","../src/server/analytics.ts","../../schema/src/experiments.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aAAa,CAAA;AAAA,EACjD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"server.js","sourcesContent":["/**\n * Deployment tier of the app this SDK runs in: Vercel's `VERCEL_ENV` (`production`, `preview`,\n * `development`), or `development` when it is unset (local runs, tests). Apps not hosted on\n * Vercel pass `environment` explicitly.\n */\nexport function serverEnvironment(): string {\n return (typeof process !== \"undefined\" && process.env.VERCEL_ENV) || \"development\";\n}\n","import type { AnalyticsEvent } from \"@faceyoga/analytics-schema/events\";\nimport { cleanProps, LIBRARY, toEventName, uuid } from \"../shared/util\";\nimport { serverEnvironment } from \"./environment\";\n\n/**\n * Server-side event sender for events that originate on the server (pithos `dispatchTrackingEvent`,\n * upsell charges from cron, webhook-driven purchases) and for experiment exposures.\n *\n * Serverless functions freeze after the response, so nothing is sent on a timer: queue with\n * `track()` and call `flush()` inside Next.js `after()` (or `waitUntil`) before the request ends.\n */\n\nexport interface ServerAnalyticsOptions {\n /** Collector URL, e.g. `https://analytics.example.com/api/collect`. */\n endpoint: string;\n /** Secret server key for the product. Never ship it to the browser. */\n serverKey: string;\n /** `production` | `preview` | `development`. Default: `VERCEL_ENV`, or `development` when unset. */\n environment?: string;\n /** Flush automatically once this many events are queued. Default 100 (the batch cap). */\n maxBatchSize?: number;\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n}\n\nexport type ServerEventInput = Omit<AnalyticsEvent, \"id\" | \"ts\" | \"name\" | \"props\"> & {\n name: string;\n id?: string;\n ts?: number;\n props?: Record<string, unknown>;\n};\n\nexport interface ServerAnalytics {\n track(event: ServerEventInput): string;\n flush(): Promise<void>;\n /** Events waiting to be sent. */\n pending(): number;\n}\n\nexport function createServerAnalytics(options: ServerAnalyticsOptions): ServerAnalytics {\n const maxBatchSize = Math.min(options.maxBatchSize ?? 100, 100);\n const environment = options.environment ?? serverEnvironment();\n const doFetch = options.fetch ?? fetch;\n const onError = options.onError ?? ((error) => console.error(\"[analytics] server flush failed:\", error));\n const queue: AnalyticsEvent[] = [];\n let inFlight: Promise<void> = Promise.resolve();\n\n async function send(events: AnalyticsEvent[]) {\n try {\n const response = await doFetch(options.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${options.serverKey}` },\n body: JSON.stringify({\n sentAt: Date.now(),\n source: \"server\",\n environment,\n library: LIBRARY,\n events,\n }),\n });\n if (!response.ok) onError(new Error(`collector responded ${response.status}: ${await response.text()}`));\n } catch (error) {\n onError(error);\n }\n }\n\n function flush(): Promise<void> {\n const batches: AnalyticsEvent[][] = [];\n while (queue.length) batches.push(queue.splice(0, maxBatchSize));\n inFlight = inFlight.then(() => Promise.all(batches.map(send)).then(() => {}));\n\n return inFlight;\n }\n\n return {\n track(input) {\n const { props, name, id, ts, ...rest } = input;\n const event: AnalyticsEvent = {\n ...rest,\n id: id || uuid(),\n name: toEventName(name),\n ts: ts ?? Date.now(),\n };\n const cleaned = cleanProps(props);\n if (cleaned) event.props = cleaned;\n queue.push(event);\n if (queue.length >= maxBatchSize) void flush();\n\n return event.id;\n },\n flush,\n pending: () => queue.length,\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Experiment config as served to SDKs by `GET /api/experiments`. Only `running` and `launched`\n * experiments are sent; drafts and stopped tests never reach a storefront. The source of truth\n * is the `experiments` / `experiment_variants` tables in Turso.\n */\n\nexport const variantSchema = z.object({\n key: z.string().min(1).max(64),\n /** Relative weight. Weights do not need to sum to 100. */\n weight: z.number().min(0),\n /** Parameters read with `experiment.get(name, fallback)`, e.g. `{ preselect_3_pack: true }`. */\n params: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const targetingSchema = z.object({\n /** ISO 3166 alpha-2, upper case. Empty or missing = all countries. */\n countries: z.array(z.string().length(2)).optional(),\n /** Lower-case language codes, e.g. `en`, `de`. Empty or missing = all locales. */\n locales: z.array(z.string().min(2).max(16)).optional(),\n});\n\nexport const experimentSchema = z.object({\n key: z.string().min(1).max(128),\n status: z.enum([\"running\", \"launched\"]),\n /**\n * Hash salt. Defaults to the key; changing it reshuffles every user, so only do that when\n * restarting a test from scratch.\n */\n salt: z.string().min(1).max(128),\n /** Share of eligible traffic in the test, 0..1. Raising it only adds users; nobody switches variant. */\n allocation: z.number().min(0).max(1),\n variants: z.array(variantSchema).min(1),\n /** Required when `status` is `launched`: everyone gets this variant and no exposures are logged. */\n launchedVariant: z.string().optional(),\n targeting: targetingSchema.optional(),\n});\n\nexport const experimentsPayloadSchema = z.object({\n product: z.string(),\n /** Changes whenever any served experiment changes, so SDKs can skip re-parsing. */\n version: z.string(),\n experiments: z.array(experimentSchema),\n});\n\nexport type Variant = z.infer<typeof variantSchema>;\nexport type Targeting = z.infer<typeof targetingSchema>;\nexport type ExperimentConfig = z.infer<typeof experimentSchema>;\nexport type ExperimentsPayload = z.infer<typeof experimentsPayloadSchema>;\n","import {\n experimentsPayloadSchema,\n type ExperimentConfig,\n type ExperimentsPayload,\n} from \"@faceyoga/analytics-schema/experiments\";\nimport { assign, notFound, type Assignment, type AssignmentUnit } from \"@faceyoga/analytics-schema/assign\";\nimport { EventNames } from \"@faceyoga/analytics-schema/names\";\nimport { toExperiment, type Experiment } from \"../shared/experiment\";\nimport type { ServerAnalytics } from \"./analytics\";\nimport { serverEnvironment } from \"./environment\";\n\n/**\n * Server-side experiments, the replacement for `statsig.getExperiment(user, name)`.\n *\n * Config is fetched from the analytics app and kept in memory; assignment is a local hash, so\n * `getExperiment` never waits on the network once `ready()` has resolved. Stale config is\n * refreshed in the background on the next read after `refreshIntervalMs`.\n */\n\nexport interface ExperimentsOptions {\n /** Analytics app base URL, e.g. `https://analytics.example.com`. */\n baseUrl: string;\n serverKey: string;\n /** Exposures are queued here; flush it in `after()`. Without it no exposures are logged. */\n analytics?: ServerAnalytics;\n refreshIntervalMs?: number;\n /**\n * Max wait for one config request. On timeout or error the last loaded config is kept, or\n * every `get()` returns its fallback when none was loaded. Default 1000 ms.\n */\n timeoutMs?: number;\n /** Seed config, e.g. a build-time snapshot, so the very first request has values. */\n initial?: ExperimentsPayload;\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n}\n\nexport interface ExperimentUnit extends AssignmentUnit {\n /** Logged-in user id, copied onto exposure events. */\n userId?: string;\n /** Page URL, copied onto exposure events. */\n url?: string;\n}\n\nexport interface Experiments {\n /**\n * Resolves after the first config load, at most `timeoutMs` later (immediately when `initial`\n * was given). Never rejects; failures go to `onError`.\n */\n ready(): Promise<void>;\n /** Assign and log one exposure (per unit and experiment, per instance) when the user is in the test. */\n getExperiment(unit: ExperimentUnit, key: string): Experiment;\n /** Assign without logging an exposure, e.g. to decide what to prefetch. */\n peek(unit: AssignmentUnit, key: string): Experiment;\n /** Experiment key -> variant for every test the unit is in. Tag client events with this. */\n getAssignments(unit: AssignmentUnit): Record<string, string>;\n /** Everything a browser needs to evaluate experiments locally (Hoola-style client reads). */\n getClientBootstrap(unit: AssignmentUnit): { assignments: Record<string, Assignment>; environment: string };\n /** Force a config reload. */\n refresh(): Promise<void>;\n /** Version of the config currently in memory, or null before the first load. */\n version(): string | null;\n}\n\nconst EXPOSURE_CACHE_LIMIT = 50_000;\n\nexport function createExperiments(options: ExperimentsOptions): Experiments {\n const refreshIntervalMs = options.refreshIntervalMs ?? 30_000;\n const timeoutMs = options.timeoutMs ?? 1_000;\n const doFetch = options.fetch ?? fetch;\n const onError = options.onError ?? ((error) => console.error(\"[analytics] experiments refresh failed:\", error));\n const url = `${options.baseUrl.replace(/\\/+$/, \"\")}/api/experiments`;\n\n let byKey = new Map<string, ExperimentConfig>();\n let currentVersion: string | null = null;\n let loadedAt = 0;\n let loading: Promise<void> | null = null;\n // Insertion-ordered set used as a small LRU so exposures are logged once per user per instance.\n const exposed = new Set<string>();\n\n function apply(payload: ExperimentsPayload) {\n byKey = new Map(payload.experiments.map((e) => [e.key, e]));\n currentVersion = payload.version;\n }\n\n if (options.initial) {\n apply(experimentsPayloadSchema.parse(options.initial));\n loadedAt = Date.now();\n }\n\n async function fetchConfig(signal: AbortSignal): Promise<void> {\n const response = await doFetch(url, {\n headers: {\n Authorization: `Bearer ${options.serverKey}`,\n ...(currentVersion ? { \"If-None-Match\": `\"${currentVersion}\"` } : {}),\n },\n cache: \"no-store\",\n signal,\n });\n if (response.status === 304) return;\n if (!response.ok) throw new Error(`experiments endpoint responded ${response.status}`);\n apply(experimentsPayloadSchema.parse(await response.json()));\n }\n\n async function load(): Promise<void> {\n // The timer also bounds a custom fetch that ignores the abort signal.\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new Error(`experiments request timed out after ${timeoutMs} ms`);\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n });\n\n try {\n await Promise.race([fetchConfig(controller.signal), timedOut]);\n } catch (error) {\n // Keep serving the last good config (or fallbacks when there is none).\n onError(error);\n } finally {\n clearTimeout(timer);\n loadedAt = Date.now();\n }\n }\n\n function refresh(): Promise<void> {\n if (!loading) {\n loading = load().finally(() => {\n loading = null;\n });\n }\n\n return loading;\n }\n\n function maybeRefresh() {\n if (Date.now() - loadedAt > refreshIntervalMs) void refresh();\n }\n\n function resolve(unit: AssignmentUnit, key: string): Assignment {\n maybeRefresh();\n const config = byKey.get(key);\n\n return config ? assign(config, unit) : notFound(key);\n }\n\n function logExposure(unit: ExperimentUnit, assignment: Assignment) {\n if (!options.analytics || assignment.reason !== \"assigned\" || !assignment.variant) return;\n const cacheKey = `${assignment.experiment}\\u0000${assignment.variant}\\u0000${unit.id}`;\n if (exposed.has(cacheKey)) return;\n exposed.add(cacheKey);\n if (exposed.size > EXPOSURE_CACHE_LIMIT) exposed.delete(exposed.values().next().value!);\n\n options.analytics.track({\n name: EventNames.ExperimentExposure,\n anonymousId: unit.id,\n ...(unit.userId && { userId: unit.userId }),\n ...(unit.url && { url: unit.url }),\n experiments: { [assignment.experiment]: assignment.variant },\n props: {\n experiment: assignment.experiment,\n variant: assignment.variant,\n ...(unit.country && { country: unit.country }),\n ...(unit.locale && { locale: unit.locale }),\n },\n });\n }\n\n return {\n ready: () => (loadedAt ? Promise.resolve() : refresh()),\n getExperiment(unit, key) {\n const assignment = resolve(unit, key);\n logExposure(unit, assignment);\n\n return toExperiment(assignment);\n },\n peek: (unit, key) => toExperiment(resolve(unit, key)),\n getAssignments(unit) {\n maybeRefresh();\n const out: Record<string, string> = {};\n for (const config of byKey.values()) {\n if (config.status !== \"running\") continue;\n const assignment = assign(config, unit);\n if (assignment.reason === \"assigned\" && assignment.variant) out[config.key] = assignment.variant;\n }\n\n return out;\n },\n getClientBootstrap(unit) {\n maybeRefresh();\n const assignments: Record<string, Assignment> = {};\n for (const config of byKey.values()) assignments[config.key] = assign(config, unit);\n\n return { assignments, environment: serverEnvironment() };\n },\n refresh,\n version: () => currentVersion,\n };\n}\n","/**\n * Headers a storefront's same-origin collect route (`createCollectHandler`) adds when it forwards\n * a browser batch to the collector with its server key. The storefront sees the visitor's\n * Vercel geo headers and user agent; the collector, receiving a server-to-server request, does\n * not. The collector honours these only on requests authenticated with a server key.\n */\nexport const FORWARD_HEADERS = {\n /** Marks a forwarded browser batch: stored as `source: \"client\"` and bot-filtered. */\n forwarded: \"x-fya-forwarded\",\n userAgent: \"x-fya-client-user-agent\",\n country: \"x-fya-client-country\",\n region: \"x-fya-client-region\",\n city: \"x-fya-client-city\",\n} as const;\n\n/** Vercel request headers on the storefront, mapped to the forwarding header that carries each. */\nexport const VERCEL_GEO_HEADERS = {\n \"x-vercel-ip-country\": FORWARD_HEADERS.country,\n \"x-vercel-ip-country-region\": FORWARD_HEADERS.region,\n \"x-vercel-ip-city\": FORWARD_HEADERS.city,\n} as const;\n","import { FORWARD_HEADERS, VERCEL_GEO_HEADERS } from \"@faceyoga/analytics-schema/forwarding\";\nimport { serverEnvironment } from \"./environment\";\n\n/**\n * Same-origin collect route for a storefront. The browser pixel posts to `/a/collect` on the\n * storefront itself, which:\n * - keeps analytics requests first-party, so ad blockers and CORS never get involved;\n * - means the browser needs no key at all: this route signs the batch with the server key;\n * - forwards the visitor's Vercel geo headers and user agent, which the collector would not\n * see on a server-to-server request (or reliably through a rewrite);\n * - stamps the batch with this deployment's environment, so preview and local traffic is never\n * counted as production whatever the browser sent.\n *\n * // app/a/collect/route.ts\n * export const POST = createCollectHandler({\n * collectorUrl: `${process.env.ANALYTICS_URL}/api/collect`,\n * serverKey: process.env.ANALYTICS_SERVER_KEY!,\n * });\n *\n * The collector answers before it writes to Axiom, so awaiting it adds little latency, and its\n * status is passed back so the pixel retries on 429 / 5xx.\n */\n\nexport interface CollectHandlerOptions {\n /** Collector URL, e.g. `https://analytics.example.com/api/collect`. */\n collectorUrl: string;\n /** Secret server key for the product. */\n serverKey: string;\n /** Overrides the batch's `environment`. Default: `VERCEL_ENV`, or `development` when unset. */\n environment?: string;\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n}\n\n/** Same cap as the collector. */\nconst MAX_BODY_BYTES = 512 * 1024;\n\nexport function createCollectHandler(options: CollectHandlerOptions): (request: Request) => Promise<Response> {\n const doFetch = options.fetch ?? fetch;\n const environment = options.environment ?? serverEnvironment();\n const onError = options.onError ?? ((error) => console.error(\"[analytics] collect forward failed:\", error));\n\n return async function collect(request) {\n if (request.method !== \"POST\") return new Response(null, { status: 405, headers: { Allow: \"POST\" } });\n if (Number(request.headers.get(\"content-length\") ?? 0) > MAX_BODY_BYTES) return new Response(null, { status: 413 });\n\n const raw = await request.text();\n if (raw.length > MAX_BODY_BYTES) return new Response(null, { status: 413 });\n const body = withEnvironment(raw, environment);\n\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${options.serverKey}`,\n [FORWARD_HEADERS.forwarded]: \"1\",\n });\n const userAgent = request.headers.get(\"user-agent\");\n if (userAgent) headers.set(FORWARD_HEADERS.userAgent, userAgent);\n for (const [vercel, forwarded] of Object.entries(VERCEL_GEO_HEADERS)) {\n const value = request.headers.get(vercel);\n if (value) headers.set(forwarded, value);\n }\n\n try {\n const response = await doFetch(options.collectorUrl, { method: \"POST\", headers, body });\n if (response.status >= 500) onError(new Error(`collector responded ${response.status}`));\n\n return new Response(null, { status: response.ok ? 204 : response.status });\n } catch (error) {\n onError(error);\n\n return new Response(null, { status: 502 });\n }\n };\n}\n\n/** Sets `environment` on a JSON batch. Anything that is not a JSON object is forwarded unchanged for the collector to reject. */\nfunction withEnvironment(body: string, environment: string): string {\n try {\n const batch: unknown = JSON.parse(body);\n if (!batch || typeof batch !== \"object\" || Array.isArray(batch)) return body;\n\n return JSON.stringify({ ...batch, environment });\n } catch {\n return body;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@faceyoga/analytics",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"license": "UNLICENSED",
|
|
5
|
+
"description": "FaceYoga analytics SDK: browser pixel, server event sender and experiment assignment.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"exports": {
|
|
12
|
+
"./client": {
|
|
13
|
+
"types": "./dist/client.d.ts",
|
|
14
|
+
"import": "./dist/client.js"
|
|
15
|
+
},
|
|
16
|
+
"./server": {
|
|
17
|
+
"types": "./dist/server.d.ts",
|
|
18
|
+
"import": "./dist/server.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"registry": "https://registry.npmjs.org",
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "https://github.com/FaceYoga/analytics.git",
|
|
28
|
+
"directory": "packages/sdk"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"zod": "^4.6.7"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"jsdom": "^29.0.2",
|
|
35
|
+
"tsup": "^8.5.0",
|
|
36
|
+
"typescript": "^5.9.3",
|
|
37
|
+
"vitest": "^4.1.12",
|
|
38
|
+
"@faceyoga/analytics-schema": "0.0.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsup",
|
|
42
|
+
"dev": "tsup --watch",
|
|
43
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
44
|
+
"test": "vitest run"
|
|
45
|
+
}
|
|
6
46
|
}
|
package/README.md
DELETED