@faceyoga/analytics 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,233 @@
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
+ function previewAssignment(experiment, variantKey) {
93
+ const variant = experiment.variants.find((v) => v.key === variantKey);
94
+ return variant ? { experiment: experiment.key, variant: variant.key, params: variant.params, reason: "preview" } : null;
95
+ }
96
+
97
+ // ../schema/src/names.ts
98
+ var EventNames = {
99
+ // Emitted by the SDK
100
+ PageView: "page_view",
101
+ SessionStart: "session_start",
102
+ ExperimentExposure: "experiment_exposure",
103
+ Identify: "identify",
104
+ // Ecommerce funnel (pithos `TrackingEventName` and Hoola GTM events map onto these)
105
+ ViewContent: "view_content",
106
+ AddToCart: "add_to_cart",
107
+ InitiateCheckout: "initiate_checkout",
108
+ CheckoutEmailCaptured: "checkout_email_captured",
109
+ Purchase: "purchase",
110
+ Upsell: "upsell",
111
+ FailedOrder: "failed_order",
112
+ FailedTransaction: "failed_transaction",
113
+ // Engagement
114
+ CtaClicked: "cta_clicked",
115
+ QuizStepViewed: "quiz_step_viewed",
116
+ QuizStepCompleted: "quiz_step_completed",
117
+ QuizCompleted: "quiz_completed"
118
+ };
119
+
120
+ // ../schema/src/preview.ts
121
+ var PREVIEW_PARAM = "fy_preview";
122
+ var QA_PARAM = "fy_qa";
123
+ var PREVIEW_COOKIE = "fy_preview";
124
+ var QA_COOKIE = "fy_qa";
125
+ var QA_ENVIRONMENT = "test";
126
+ var QA_MAX_AGE_SECONDS = 24 * 60 * 60;
127
+ var KEY = /^[a-z0-9][a-z0-9_-]{0,127}$/;
128
+ var MAX_OVERRIDES = 10;
129
+ function parsePreview(value) {
130
+ const out = {};
131
+ if (!value) return out;
132
+ for (const pair of value.split(",").slice(0, MAX_OVERRIDES)) {
133
+ const [experiment, variant, ...rest] = pair.trim().split(":");
134
+ if (!experiment || !variant || rest.length || !KEY.test(experiment) || !KEY.test(variant)) continue;
135
+ out[experiment] = variant;
136
+ }
137
+ return out;
138
+ }
139
+ function formatPreview(overrides) {
140
+ return Object.entries(overrides).map(([experiment, variant]) => `${experiment}:${variant}`).join(",");
141
+ }
142
+ var OFF = /* @__PURE__ */ new Set(["off", "0", "false"]);
143
+ function readPreviewState(search, cookies) {
144
+ const params = typeof search === "string" ? new URLSearchParams(search) : search;
145
+ const previewParam = params?.get(PREVIEW_PARAM);
146
+ const qaParam = params?.get(QA_PARAM);
147
+ if (previewParam && OFF.has(previewParam) || qaParam && OFF.has(qaParam)) {
148
+ return { qa: false, overrides: {}, change: { action: "clear" } };
149
+ }
150
+ if (previewParam || qaParam) {
151
+ const overrides = parsePreview(previewParam);
152
+ return { qa: true, overrides, change: { action: "set", preview: formatPreview(overrides) } };
153
+ }
154
+ const qa = Boolean(cookies(QA_COOKIE));
155
+ return { qa, overrides: qa ? parsePreview(cookies(PREVIEW_COOKIE)) : {}, change: null };
156
+ }
157
+ function cookieFromHeader(header, name) {
158
+ if (!header) return void 0;
159
+ for (const part of header.split(";")) {
160
+ const index = part.indexOf("=");
161
+ if (index < 0) continue;
162
+ if (part.slice(0, index).trim() === name) {
163
+ try {
164
+ return decodeURIComponent(part.slice(index + 1).trim()) || void 0;
165
+ } catch {
166
+ return void 0;
167
+ }
168
+ }
169
+ }
170
+ return void 0;
171
+ }
172
+
173
+ // src/shared/experiment.ts
174
+ function sameType(value, fallback) {
175
+ if (fallback === null || fallback === void 0) return value !== void 0;
176
+ if (Array.isArray(fallback)) return Array.isArray(value);
177
+ return value !== null && typeof value === typeof fallback && !Array.isArray(value);
178
+ }
179
+ function toExperiment(assignment) {
180
+ return {
181
+ key: assignment.experiment,
182
+ variant: assignment.variant,
183
+ reason: assignment.reason,
184
+ params: assignment.params,
185
+ get(param, fallback) {
186
+ const value = assignment.params[param];
187
+ return sameType(value, fallback) ? value : fallback;
188
+ }
189
+ };
190
+ }
191
+
192
+ // src/shared/util.ts
193
+ var LIBRARY = { name: "@faceyoga/analytics", version: "0.2.0" };
194
+ function uuid() {
195
+ const c = globalThis.crypto;
196
+ if (c?.randomUUID) return c.randomUUID();
197
+ const bytes = new Uint8Array(16);
198
+ if (c?.getRandomValues) c.getRandomValues(bytes);
199
+ else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
200
+ bytes[6] = bytes[6] & 15 | 64;
201
+ bytes[8] = bytes[8] & 63 | 128;
202
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
203
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
204
+ }
205
+ var MAX_PROP_KEYS = 50;
206
+ var MAX_STRING = 2048;
207
+ function cleanProps(props) {
208
+ if (!props) return void 0;
209
+ const out = {};
210
+ let count = 0;
211
+ for (const [rawKey, value] of Object.entries(props)) {
212
+ if (value === void 0) continue;
213
+ if (count >= MAX_PROP_KEYS) break;
214
+ const key = rawKey.slice(0, 64);
215
+ if (value === null || typeof value === "boolean") out[key] = value;
216
+ else if (typeof value === "string") out[key] = value.slice(0, MAX_STRING);
217
+ else if (typeof value === "number") {
218
+ if (!Number.isFinite(value)) continue;
219
+ out[key] = value;
220
+ } else out[key] = (JSON.stringify(value) ?? "").slice(0, MAX_STRING);
221
+ count++;
222
+ }
223
+ return count ? out : void 0;
224
+ }
225
+ function toEventName(name) {
226
+ const snake = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
227
+ const prefixed = /^[a-z]/.test(snake) ? snake : `e_${snake}`;
228
+ return prefixed.slice(0, 64);
229
+ }
230
+
231
+ export { EventNames, LIBRARY, PREVIEW_COOKIE, PREVIEW_PARAM, QA_COOKIE, QA_ENVIRONMENT, QA_MAX_AGE_SECONDS, QA_PARAM, assign, cleanProps, cookieFromHeader, notFound, previewAssignment, readPreviewState, toEventName, toExperiment, uuid };
232
+ //# sourceMappingURL=chunk-J4RHGPNT.js.map
233
+ //# sourceMappingURL=chunk-J4RHGPNT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../schema/src/assign.ts","../../schema/src/names.ts","../../schema/src/preview.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,CA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AA,EAAG,UAAU,CAAA;AAAA,SAAA,IAC/D,OAAO,UAAU,QAAA,EAAU;AAClC,MAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,EAAG;AAC7B,MAAA,GAAA,CAAI,GAAG,CAAA,GAAI,KAAA;AAAA,IACb,CAAA,MAAO,GAAA,CAAI,GAAG,CAAA,GAAA,CAAK,IAAA,CAAK,SAAA,CAAU,KAAK,CAAA,IAAK,EAAA,EAAI,KAAA,CAAM,CAAA,EAAG,UAAU,CAAA;AACnE,IAAA,KAAA,EAAA;AAAA,EACF;AAEA,EAAA,OAAO,QAAQ,GAAA,GAAM,MAAA;AACvB;AAGO,SAAS,YAAY,IAAA,EAAsB;AAChD,EAAA,MAAM,KAAA,GAAQ,IAAA,CACX,OAAA,CAAQ,oBAAA,EAAsB,OAAO,CAAA,CACrC,OAAA,CAAQ,gBAAA,EAAkB,GAAG,CAAA,CAC7B,OAAA,CAAQ,UAAA,EAAY,EAAE,EACtB,WAAA,EAAY;AACf,EAAA,MAAM,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-J4RHGPNT.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 /** Variant forced by a preview link (QA mode). No exposure is logged. */\n | \"preview\";\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/**\n * A variant forced by a preview link. Separate from `assign()` so bucketing never changes;\n * works for draft and stopped experiments too, so variants can be checked before a test starts.\n * Returns null when the variant doesn't exist (the caller then assigns normally).\n */\nexport function previewAssignment(\n experiment: { key: string; variants: { key: string; params: Record<string, unknown> }[] },\n variantKey: string\n): Assignment | null {\n const variant = experiment.variants.find((v) => v.key === variantKey);\n\n return variant ? { experiment: experiment.key, variant: variant.key, params: variant.params, reason: \"preview\" } : null;\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","/**\n * Preview links and QA mode. Pure and dependency-free: used by the browser pixel, the server SDK\n * and the collector.\n *\n * ?fy_preview=<experiment>:<variant>[,<experiment>:<variant>] force variants for this browser\n * ?fy_qa=1 QA mode only, no forced variant\n * ?fy_preview=off (or ?fy_qa=0) back to normal\n *\n * Either parameter turns on QA mode for a day: every event from that browser, and every server\n * event for the same visitor id (purchases, upsells), is stored with environment `test`, so it\n * never counts in production numbers but can still be inspected in Live events.\n */\n\nexport const PREVIEW_PARAM = \"fy_preview\";\nexport const QA_PARAM = \"fy_qa\";\nexport const PREVIEW_COOKIE = \"fy_preview\";\nexport const QA_COOKIE = \"fy_qa\";\n/** Environment stored on events from a browser in QA mode. */\nexport const QA_ENVIRONMENT = \"test\";\nexport const QA_MAX_AGE_SECONDS = 24 * 60 * 60;\n\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,127}$/;\nconst MAX_OVERRIDES = 10;\n\n/** `exp:variant,exp2:variant2` → `{ exp: \"variant\", exp2: \"variant2\" }`. Invalid pairs are skipped. */\nexport function parsePreview(value: string | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!value) return out;\n for (const pair of value.split(\",\").slice(0, MAX_OVERRIDES)) {\n const [experiment, variant, ...rest] = pair.trim().split(\":\");\n if (!experiment || !variant || rest.length || !KEY.test(experiment) || !KEY.test(variant)) continue;\n out[experiment] = variant;\n }\n\n return out;\n}\n\nexport function formatPreview(overrides: Record<string, string>): string {\n return Object.entries(overrides)\n .map(([experiment, variant]) => `${experiment}:${variant}`)\n .join(\",\");\n}\n\nconst OFF = new Set([\"off\", \"0\", \"false\"]);\n\nexport interface PreviewState {\n qa: boolean;\n overrides: Record<string, string>;\n /**\n * What the URL asked for, if anything: `set` to store new cookies, `clear` to remove them.\n * Null when the URL had no preview parameters (keep whatever the cookies say).\n */\n change: { action: \"set\"; preview: string } | { action: \"clear\" } | null;\n}\n\n/**\n * Combines the URL parameters (which win) with the existing cookies.\n * `cookies` is a lookup, e.g. `(name) => cookieStore.get(name)?.value`.\n */\nexport function readPreviewState(\n search: string | URLSearchParams | null | undefined,\n cookies: (name: string) => string | undefined\n): PreviewState {\n const params = typeof search === \"string\" ? new URLSearchParams(search) : search;\n const previewParam = params?.get(PREVIEW_PARAM);\n const qaParam = params?.get(QA_PARAM);\n\n if ((previewParam && OFF.has(previewParam)) || (qaParam && OFF.has(qaParam))) {\n return { qa: false, overrides: {}, change: { action: \"clear\" } };\n }\n if (previewParam || qaParam) {\n const overrides = parsePreview(previewParam);\n\n return { qa: true, overrides, change: { action: \"set\", preview: formatPreview(overrides) } };\n }\n\n const qa = Boolean(cookies(QA_COOKIE));\n\n return { qa, overrides: qa ? parsePreview(cookies(PREVIEW_COOKIE)) : {}, change: null };\n}\n\n/** Reads one cookie from a `Cookie` request header. */\nexport function cookieFromHeader(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index < 0) continue;\n if (part.slice(0, index).trim() === name) {\n try {\n return decodeURIComponent(part.slice(index + 1).trim()) || undefined;\n } catch {\n return undefined;\n }\n }\n }\n\n return undefined;\n}\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.2.0\" } 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"]}
@@ -0,0 +1,99 @@
1
+ import { E as Experiment, A as Assignment } from './names-CWW29ek_.js';
2
+ export { a as EventNames } from './names-CWW29ek_.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
+ /** True while this browser is in QA mode (opened a preview link): its events are stored as `test`. */
92
+ isQa(): boolean;
93
+ flush(): Promise<void>;
94
+ shutdown(): void;
95
+ }
96
+ declare function createFetchTransport(endpoint: string): Transport;
97
+ declare function createAnalytics(options: AnalyticsOptions): Analytics;
98
+
99
+ export { type Analytics, type AnalyticsOptions, Assignment, type ClientExperimentBootstrap, Experiment, type SendResult, type TrackOptions, type Transport, createAnalytics, createFetchTransport };