@proofhorn/next 0.0.0-stage → 0.3.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,903 @@
1
+ /*! Proofhorn runtime 1.0.0 | MIT License | (c) 2026 Khushrav Ventures */
2
+
3
+ // packages/runtime/src/core.js
4
+ function fnv1a32(str) {
5
+ let h = 2166136261;
6
+ for (let i = 0; i < str.length; i++) {
7
+ h ^= str.charCodeAt(i);
8
+ h = Math.imul(h, 16777619);
9
+ }
10
+ return h >>> 0;
11
+ }
12
+ function assignVariant(variants, visitorId, widgetId) {
13
+ const list = Array.isArray(variants) ? variants : [];
14
+ let total = 0;
15
+ for (const v of list) total += Math.max(0, Number(v && v.weight) || 0);
16
+ if (!total) return null;
17
+ let bucket = fnv1a32(visitorId + ":" + widgetId) % total;
18
+ for (const v of list) {
19
+ bucket -= Math.max(0, Number(v && v.weight) || 0);
20
+ if (bucket < 0) return v;
21
+ }
22
+ return null;
23
+ }
24
+ function defaultVariant(variants) {
25
+ return (Array.isArray(variants) ? variants : []).find((v) => v && !v.holdout && Math.max(0, Number(v.weight) || 0) > 0) || null;
26
+ }
27
+ var ESSENTIAL = { who: 1, item: 1, count: 1, stock: 1 };
28
+ var PLACEHOLDER = /\{([a-zA-Z_]+)((?:\|[a-z]+(?::[^|}]*)?)*)\}/g;
29
+ function titleCase(text) {
30
+ return text.toLowerCase().replace(/(^|[\s\-'])(\S)/g, function(m, pre, ch) {
31
+ return pre + ch.toUpperCase();
32
+ });
33
+ }
34
+ function applyFilters(text, filters) {
35
+ let bold = false;
36
+ for (const f of filters) {
37
+ const i = f.indexOf(":");
38
+ const name = i === -1 ? f : f.slice(0, i);
39
+ const arg = i === -1 ? "" : f.slice(i + 1);
40
+ if (name === "or") {
41
+ if (!text.trim()) text = arg;
42
+ } else if (name === "bold") {
43
+ bold = true;
44
+ } else if (name === "title") {
45
+ text = titleCase(text);
46
+ } else if (name === "truncate") {
47
+ const n = /^\d+$/.test(arg) ? parseInt(arg, 10) : 0;
48
+ const chars = Array.from(text);
49
+ if (n >= 1 && n <= 80 && chars.length > n) text = chars.slice(0, n).join("").replace(/\s+$/, "") + "\u2026";
50
+ }
51
+ }
52
+ return { text, bold };
53
+ }
54
+ function renderTemplate(template, values) {
55
+ if (typeof template !== "string" || !template.trim()) return null;
56
+ const out = [];
57
+ const re = new RegExp(PLACEHOLDER.source, "g");
58
+ let last = 0;
59
+ let m;
60
+ while (m = re.exec(template)) {
61
+ if (m.index > last) out.push({ kind: "text", text: template.slice(last, m.index) });
62
+ const name = m[1];
63
+ const raw = values && Object.prototype.hasOwnProperty.call(values, name) ? values[name] : "";
64
+ const filtered = applyFilters(raw == null ? "" : String(raw), m[2] ? m[2].slice(1).split("|") : []);
65
+ const text2 = filtered.text;
66
+ if (!text2.trim() && ESSENTIAL[name]) return null;
67
+ if (text2) out.push(filtered.bold ? { kind: name, text: text2, bold: true } : { kind: name, text: text2 });
68
+ last = re.lastIndex;
69
+ }
70
+ if (last < template.length) out.push({ kind: "text", text: template.slice(last) });
71
+ const text = out.map((s) => s.text).join("").replace(/\s+/g, " ").trim();
72
+ if (!text) return null;
73
+ return { text, segments: out };
74
+ }
75
+ function pickTemplate(variant, lang) {
76
+ const base = variant && typeof variant.template === "string" ? variant.template : "";
77
+ const tr = variant && variant.translations && typeof variant.translations === "object" ? variant.translations : null;
78
+ if (!tr || typeof lang !== "string" || !lang) return base;
79
+ const want = lang.toLowerCase();
80
+ const primary = want.split("-")[0];
81
+ let exact = null;
82
+ let prim = null;
83
+ for (const k in tr) {
84
+ if (typeof tr[k] !== "string" || !tr[k].trim()) continue;
85
+ const key = k.toLowerCase();
86
+ if (key === want) exact = tr[k];
87
+ else if (key === primary) prim = tr[k];
88
+ }
89
+ return exact || prim || base;
90
+ }
91
+ function formatAmount(amount, lang) {
92
+ if (!amount || typeof amount !== "object" || !Number.isFinite(amount.amountMinor) || typeof amount.currency !== "string") return "";
93
+ try {
94
+ const nf = new Intl.NumberFormat(lang || "en", { style: "currency", currency: amount.currency.toUpperCase() });
95
+ const digits = nf.resolvedOptions().maximumFractionDigits;
96
+ return nf.format(amount.amountMinor / Math.pow(10, digits));
97
+ } catch (e) {
98
+ return "";
99
+ }
100
+ }
101
+ function countryName(code, lang) {
102
+ if (typeof code !== "string" || !/^[A-Za-z]{2}$/.test(code)) return "";
103
+ try {
104
+ return new Intl.DisplayNames([lang || "en"], { type: "region" }).of(code.toUpperCase()) || code.toUpperCase();
105
+ } catch (e) {
106
+ return code.toUpperCase();
107
+ }
108
+ }
109
+ function rowValues(row, now, lang) {
110
+ return {
111
+ who: row.who,
112
+ verb: row.verb,
113
+ item: row.item,
114
+ time: relativeTime(row.at, now, lang),
115
+ firstName: row.firstName || "",
116
+ initials: row.initials || "",
117
+ city: row.city || "",
118
+ country: countryName(row.country, lang),
119
+ amount: formatAmount(row.amount, lang)
120
+ };
121
+ }
122
+ function textMatches(cond, value) {
123
+ if (!cond || typeof cond !== "object" || typeof cond.value !== "string") return false;
124
+ const v = String(value || "").toLowerCase();
125
+ const want = cond.value.toLowerCase();
126
+ if (cond.op === "contains") return v.indexOf(want) !== -1;
127
+ if (cond.op === "starts_with") return v.indexOf(want) === 0;
128
+ if (cond.op === "equals") {
129
+ const strip = (p) => p.length > 1 ? p.replace(/\/+$/, "") : p;
130
+ return strip(v) === strip(want);
131
+ }
132
+ return false;
133
+ }
134
+ function ruleMatches(rule, ctx) {
135
+ if (!rule || typeof rule !== "object") return false;
136
+ const c = ctx || {};
137
+ let any = false;
138
+ if (rule.path !== void 0) {
139
+ any = true;
140
+ if (!textMatches(rule.path, c.path)) return false;
141
+ }
142
+ if (rule.placement !== void 0) {
143
+ any = true;
144
+ if (rule.placement !== c.placement) return false;
145
+ }
146
+ if (rule.device !== void 0) {
147
+ any = true;
148
+ if (rule.device !== c.device) return false;
149
+ }
150
+ if (rule.visitor !== void 0) {
151
+ any = true;
152
+ if (!c.visitor || rule.visitor !== c.visitor) return false;
153
+ }
154
+ if (rule.utmCampaign !== void 0) {
155
+ any = true;
156
+ if (!textMatches(rule.utmCampaign, c.utmCampaign)) return false;
157
+ }
158
+ return any;
159
+ }
160
+ function rulesAllow(rules, ctx) {
161
+ const list = Array.isArray(rules) ? rules : [];
162
+ for (const r of list) {
163
+ if (ruleMatches(r, ctx)) return r.action !== "hide";
164
+ }
165
+ return true;
166
+ }
167
+ var HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
168
+ function sanitizeCss(css) {
169
+ if (typeof css !== "string") return "";
170
+ const out = [];
171
+ for (const part of css.slice(0, 2e3).split(";")) {
172
+ const decl = part.trim();
173
+ if (!decl) continue;
174
+ if (/[{}<>@\\]|\/\*|url\s*\(|expression\s*\(|image-set|import/i.test(decl)) continue;
175
+ const m = /^(-{0,2}[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*([^;]+)$/.exec(decl);
176
+ if (m) out.push(m[1].toLowerCase() + ":" + m[2].trim());
177
+ }
178
+ return out.join(";");
179
+ }
180
+ function normalizeDesign(d) {
181
+ const o = d && typeof d === "object" ? d : {};
182
+ const radius = Number(o.radius);
183
+ return {
184
+ theme: o.theme === "dark" ? "dark" : "light",
185
+ bg: HEX_COLOR.test(o.bg) ? o.bg : null,
186
+ fg: HEX_COLOR.test(o.fg) ? o.fg : null,
187
+ accent: HEX_COLOR.test(o.accent) ? o.accent : null,
188
+ radius: o.radius != null && Number.isFinite(radius) && radius >= 0 && radius <= 24 ? Math.round(radius) : 12,
189
+ shadow: o.shadow === "none" || o.shadow === "strong" ? o.shadow : "soft",
190
+ size: o.size === "s" || o.size === "l" ? o.size : "m",
191
+ font: o.font === "inherit" ? "inherit" : "system",
192
+ customCss: sanitizeCss(o.customCss)
193
+ };
194
+ }
195
+ var INCENTIVE_LABEL = "Incentivized review: the reviewer received a reward for writing it.";
196
+ function reviewLabels(review) {
197
+ const labels = [];
198
+ if (review && review.verified === true) labels.push("Verified");
199
+ if (review && review.incentivized === true) labels.push(INCENTIVE_LABEL);
200
+ return labels;
201
+ }
202
+ var KNOWN_WIDGET_TYPES = ["recent_activity", "recent_purchase", "star_rating", "review_list", "review_carousel"];
203
+ function normalizeConfig(config) {
204
+ if (!config || typeof config !== "object" || config.v !== 1) return null;
205
+ const site = config.site && typeof config.site === "object" ? config.site : {};
206
+ const widgets = (Array.isArray(config.widgets) ? config.widgets : []).filter(
207
+ (w) => w && typeof w.id === "string" && KNOWN_WIDGET_TYPES.indexOf(w.type) !== -1
208
+ );
209
+ const feed = (Array.isArray(config.feed) ? config.feed : []).filter(
210
+ (f) => f && typeof f.who === "string" && typeof f.item === "string"
211
+ );
212
+ return {
213
+ site: {
214
+ platform: typeof site.platform === "string" ? site.platform : "custom",
215
+ locale: typeof site.locale === "string" ? site.locale : "en",
216
+ consentMode: site.consentMode === "required" ? "required" : "none",
217
+ branding: site.branding !== false,
218
+ design: normalizeDesign(site.design),
219
+ rules: Array.isArray(site.rules) ? site.rules : []
220
+ },
221
+ widgets: widgets.map((w) => ({
222
+ id: w.id,
223
+ type: w.type === "recent_purchase" ? "recent_activity" : w.type,
224
+ placement: typeof w.placement === "string" ? w.placement : "all",
225
+ design: w.design && typeof w.design === "object" ? w.design : {},
226
+ targeting: w.targeting && typeof w.targeting === "object" ? w.targeting : {},
227
+ variants: Array.isArray(w.variants) ? w.variants : []
228
+ })),
229
+ feed
230
+ };
231
+ }
232
+ function placementMatches(widgetPlacement, pagePlacement) {
233
+ return !widgetPlacement || widgetPlacement === "all" || widgetPlacement === pagePlacement;
234
+ }
235
+ function deviceMatches(targeting, device) {
236
+ const devices = targeting && Array.isArray(targeting.devices) ? targeting.devices : null;
237
+ return !devices || !devices.length || devices.indexOf(device) !== -1;
238
+ }
239
+ var BROWSER_EVENT_TYPES = [
240
+ "page_view",
241
+ "product_view",
242
+ "proof_impression",
243
+ "proof_interaction",
244
+ "proof_click",
245
+ "review_view",
246
+ "review_submission",
247
+ "add_to_cart",
248
+ "checkout_started",
249
+ "intent",
250
+ "referral_view",
251
+ "referral_click",
252
+ "ugc_view",
253
+ "ugc_interaction"
254
+ ];
255
+ function isBrowserEventType(t) {
256
+ return BROWSER_EVENT_TYPES.indexOf(t) !== -1;
257
+ }
258
+ var MINUTE = 60;
259
+ var HOUR = 3600;
260
+ var DAY_S = 86400;
261
+ var AGE_UNITS = [
262
+ ["year", 365.25 * DAY_S, 365 * DAY_S],
263
+ ["month", 30.4375 * DAY_S, 30 * DAY_S],
264
+ ["week", 7 * DAY_S, 14 * DAY_S],
265
+ ["day", DAY_S, DAY_S],
266
+ ["hour", HOUR, HOUR],
267
+ ["minute", MINUTE, MINUTE]
268
+ ];
269
+ function relativeTime(iso, now, lang) {
270
+ const t = new Date(iso).getTime();
271
+ if (!Number.isFinite(t) || !Number.isFinite(now)) return "";
272
+ const age = Math.max(0, (now - t) / 1e3);
273
+ try {
274
+ const rtf = new Intl.RelativeTimeFormat(lang || "en", { numeric: "always" });
275
+ for (const [unit, size, from] of AGE_UNITS) {
276
+ if (age >= from) return rtf.format(-Math.max(1, Math.round(age / size)), unit);
277
+ }
278
+ return new Intl.RelativeTimeFormat(lang || "en", { numeric: "auto" }).format(0, "second");
279
+ } catch (e) {
280
+ return "";
281
+ }
282
+ }
283
+
284
+ // packages/runtime/src/card.js
285
+ var CARD_CSS = ":host{all:initial}.c{position:fixed;bottom:20px;z-index:2147483000;display:flex;gap:12px;align-items:center;max-width:min(360px,calc(100vw - 32px));padding:12px 36px 12px 12px;box-sizing:border-box;background:var(--phn-bg,#fff);color:var(--phn-fg,#1a1a1a);border-radius:var(--phn-r,12px);box-shadow:var(--phn-sh,0 6px 24px rgba(0,0,0,.18));font:var(--phn-fs,14px)/1.4 var(--phn-ff,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif);opacity:0;transform:translateY(12px);transition:opacity .3s,transform .3s}.c.l{left:16px}.c.r{right:16px}.c.tp{top:20px;bottom:auto;transform:translateY(-12px)}.c.s{opacity:1;transform:none}img,.pin{width:var(--phn-im,56px);height:var(--phn-im,56px);border-radius:8px;object-fit:cover;flex:none}.pin{display:flex;align-items:center;justify-content:center;background:var(--phn-ac,#2c6ecb);color:#fff}.pin svg{width:50%;height:50%;fill:currentColor}a{color:var(--phn-ac,inherit);font-weight:600}b{font-weight:600}.t{display:block;margin-top:2px;font-size:.86em;color:var(--phn-mu,#616161)}.p{display:block;margin-top:2px;font-size:10px;color:var(--phn-mu,#8a8a8a)}.e{display:block;margin-bottom:4px;font-size:10px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:#8a5a00}.x{position:absolute;top:6px;right:6px;width:24px;height:24px;border:0;background:none;color:var(--phn-mu,#616161);font-size:18px;line-height:1;cursor:pointer;border-radius:4px}.x:focus-visible,a:focus-visible{outline:2px solid var(--phn-ac,#005bd3)}@media (prefers-reduced-motion:reduce){.c{transition:none}}";
286
+ var SIZES = { s: ["13px", "48px"], m: ["14px", "56px"], l: ["16px", "64px"] };
287
+ var SHADOWS = { none: "none", soft: "0 6px 24px rgba(0,0,0,.18)", strong: "0 10px 36px rgba(0,0,0,.36)" };
288
+ function designCss(siteDesign) {
289
+ const d = normalizeDesign(siteDesign);
290
+ const dark = d.theme === "dark";
291
+ const size = SIZES[d.size];
292
+ const vars = [
293
+ "--phn-bg:" + (d.bg || (dark ? "#1f1f1f" : "#fff")),
294
+ "--phn-fg:" + (d.fg || (dark ? "#f2f2f2" : "#1a1a1a")),
295
+ "--phn-mu:" + (dark ? "#b5b5b5" : "#616161"),
296
+ "--phn-r:" + d.radius + "px",
297
+ "--phn-sh:" + SHADOWS[d.shadow],
298
+ "--phn-fs:" + size[0],
299
+ "--phn-im:" + size[1]
300
+ ];
301
+ if (d.accent) vars.push("--phn-ac:" + d.accent);
302
+ if (d.font === "inherit") vars.push("--phn-ff:inherit");
303
+ return (d.font === "inherit" ? ":host{font-family:inherit}" : "") + ".c{" + vars.join(";") + "}" + (d.customCss ? ".c{" + d.customCss + "}" : "");
304
+ }
305
+ function withUtm(url, utm) {
306
+ if (!utm || typeof utm !== "object") return url;
307
+ try {
308
+ const rel = url.charAt(0) === "/";
309
+ const u = new URL(url, "https://relative.invalid");
310
+ for (const k of ["source", "medium", "campaign"]) {
311
+ const v = utm[k];
312
+ if (typeof v === "string" && v.trim()) u.searchParams.set("utm_" + k, v.trim().slice(0, 100));
313
+ }
314
+ return rel ? u.pathname + u.search + u.hash : u.toString();
315
+ } catch (e) {
316
+ return url;
317
+ }
318
+ }
319
+ var PIN_PATH = "M12 2a7 7 0 0 0-7 7c0 5.2 7 13 7 13s7-7.8 7-13a7 7 0 0 0-7-7zm0 9.5A2.5 2.5 0 1 1 12 6.5a2.5 2.5 0 0 1 0 5z";
320
+ function picture(doc, row, wd) {
321
+ const mode = wd.image === "custom" || wd.image === "pin" || wd.image === "none" ? wd.image : "item";
322
+ const src = mode === "custom" ? wd.imageUrl : mode === "item" ? row.image : null;
323
+ if (mode === "pin") {
324
+ const box = doc.createElement("span");
325
+ box.className = "pin";
326
+ box.setAttribute("aria-hidden", "true");
327
+ const NS = "http://www.w3.org/2000/svg";
328
+ const svg = doc.createElementNS(NS, "svg");
329
+ svg.setAttribute("viewBox", "0 0 24 24");
330
+ const path = doc.createElementNS(NS, "path");
331
+ path.setAttribute("d", PIN_PATH);
332
+ svg.appendChild(path);
333
+ box.appendChild(svg);
334
+ return box;
335
+ }
336
+ if (typeof src !== "string" || !/^https:\/\//.test(src)) return null;
337
+ const img = doc.createElement("img");
338
+ img.src = src;
339
+ img.alt = "";
340
+ img.width = 56;
341
+ img.height = 56;
342
+ img.loading = "lazy";
343
+ return img;
344
+ }
345
+ function buildCard(doc, row, line, opts) {
346
+ const wd = opts.widgetDesign && typeof opts.widgetDesign === "object" ? opts.widgetDesign : {};
347
+ const card = doc.createElement("div");
348
+ card.className = "c " + (opts.side === "r" ? "r" : "l") + (opts.top ? " tp" : "");
349
+ card.setAttribute("role", "status");
350
+ card.setAttribute("aria-live", "polite");
351
+ const pic = picture(doc, row, wd);
352
+ if (pic) card.appendChild(pic);
353
+ const text = doc.createElement("div");
354
+ if (opts.exampleLabel) {
355
+ const e = doc.createElement("span");
356
+ e.className = "e";
357
+ e.textContent = opts.exampleLabel;
358
+ text.appendChild(e);
359
+ }
360
+ const linkable = wd.click !== "none" && row.url && /^(https?:\/\/|\/)/.test(row.url);
361
+ const span = doc.createElement("span");
362
+ for (const seg of line.segments) {
363
+ let el;
364
+ if (seg.kind === "item" && linkable) {
365
+ el = doc.createElement("a");
366
+ el.href = withUtm(row.url, wd.utm);
367
+ el.textContent = seg.text;
368
+ if (opts.onItemClick) el.addEventListener("click", opts.onItemClick);
369
+ } else if (seg.kind === "who" || seg.kind === "item" || seg.bold) {
370
+ el = doc.createElement("b");
371
+ el.textContent = seg.text;
372
+ } else {
373
+ el = doc.createTextNode(seg.text);
374
+ }
375
+ span.appendChild(el);
376
+ }
377
+ text.appendChild(span);
378
+ if (String(opts.template || "").indexOf("{time") === -1) {
379
+ const when = doc.createElement("span");
380
+ when.className = "t";
381
+ when.textContent = relativeTime(row.at, opts.now, opts.lang);
382
+ text.appendChild(when);
383
+ }
384
+ if (opts.branding) {
385
+ const p = doc.createElement("span");
386
+ p.className = "p";
387
+ p.textContent = "Powered by Proofhorn";
388
+ text.appendChild(p);
389
+ }
390
+ card.appendChild(text);
391
+ const close = doc.createElement("button");
392
+ close.className = "x";
393
+ close.type = "button";
394
+ close.setAttribute("aria-label", "Close");
395
+ close.textContent = "\xD7";
396
+ if (opts.onClose) close.addEventListener("click", opts.onClose);
397
+ card.appendChild(close);
398
+ return card;
399
+ }
400
+
401
+ // packages/runtime/src/runtime.js
402
+ var DEFAULT_API = "https://proofhorn.khushrav.com";
403
+ var HEX24 = /^[0-9a-f]{24}$/;
404
+ function store(kind) {
405
+ try {
406
+ const s = window[kind];
407
+ const k = "__phn_probe";
408
+ s.setItem(k, "1");
409
+ s.removeItem(k);
410
+ return s;
411
+ } catch (e) {
412
+ return null;
413
+ }
414
+ }
415
+ function randomHex24() {
416
+ const a = new Uint8Array(12);
417
+ (window.crypto || window.msCrypto).getRandomValues(a);
418
+ let out = "";
419
+ for (let i = 0; i < a.length; i++) out += ("0" + a[i].toString(16)).slice(-2);
420
+ return out;
421
+ }
422
+ function safe(fn) {
423
+ return function() {
424
+ try {
425
+ return fn.apply(this, arguments);
426
+ } catch (e) {
427
+ }
428
+ };
429
+ }
430
+ function createRuntime(options) {
431
+ const opts = options || {};
432
+ const publicKey = opts.publicKey || "";
433
+ const apiBase = String(opts.apiBase || DEFAULT_API).replace(/\/$/, "");
434
+ const base = apiBase + "/v1/public/" + encodeURIComponent(publicKey);
435
+ const local = store("localStorage");
436
+ const session = store("sessionStorage");
437
+ const device = window.matchMedia && window.matchMedia("(max-width: 749px)").matches ? "m" : "d";
438
+ let consentMode = opts.consentMode || "none";
439
+ let consented = null;
440
+ let ids = { visitorId: null, sessionId: null };
441
+ let referralCode = null;
442
+ let configPromise = null;
443
+ let config = null;
444
+ const queue = [];
445
+ let flushTimer = null;
446
+ function measuring() {
447
+ return consentMode !== "required" || consented === true;
448
+ }
449
+ function ensureIds() {
450
+ if (!measuring()) return;
451
+ if (!ids.visitorId) {
452
+ let vid = local && local.getItem("phn_vid");
453
+ if (!vid || !HEX24.test(vid)) {
454
+ vid = randomHex24();
455
+ if (local) local.setItem("phn_vid", vid);
456
+ }
457
+ ids.visitorId = vid;
458
+ }
459
+ if (!ids.sessionId) {
460
+ let sid = session && session.getItem("phn_sid");
461
+ if (!sid || !HEX24.test(sid)) {
462
+ sid = randomHex24();
463
+ if (session) session.setItem("phn_sid", sid);
464
+ }
465
+ ids.sessionId = sid;
466
+ }
467
+ if (local && !local.getItem("phn_first")) {
468
+ local.setItem("phn_first", String(Date.now()));
469
+ if (session) session.setItem("phn_new", "1");
470
+ }
471
+ try {
472
+ const utm = new URLSearchParams(location.search).get("utm_campaign");
473
+ if (utm && session) session.setItem("phn_utm", utm.slice(0, 200));
474
+ } catch (e) {
475
+ }
476
+ try {
477
+ const ref = new URLSearchParams(location.search).get("ref");
478
+ if (ref && /^[A-Za-z0-9._:-]{1,128}$/.test(ref)) {
479
+ if (session) session.setItem("phn_ref", ref);
480
+ track("referral_view", null, null);
481
+ }
482
+ referralCode = session && session.getItem("phn_ref") || ref || null;
483
+ } catch (e) {
484
+ }
485
+ }
486
+ function sessionJSON(key) {
487
+ try {
488
+ return JSON.parse(session && session.getItem(key) || "{}") || {};
489
+ } catch (e) {
490
+ return {};
491
+ }
492
+ }
493
+ function setSessionJSON(key, value) {
494
+ if (session && measuring()) session.setItem(key, JSON.stringify(value));
495
+ }
496
+ function track(type, variantId, itemKey, name) {
497
+ if (!publicKey || !measuring()) return;
498
+ queue.push({ t: type, w: variantId || void 0, i: itemKey || void 0, n: name || void 0, ts: Date.now() });
499
+ if (queue.length >= 20) flush();
500
+ else if (!flushTimer) flushTimer = setTimeout(flush, 5e3);
501
+ }
502
+ const flush = safe(function() {
503
+ clearTimeout(flushTimer);
504
+ flushTimer = null;
505
+ if (!queue.length || !measuring()) return;
506
+ ensureIds();
507
+ const body = JSON.stringify({ vid: ids.visitorId, sid: ids.sessionId, d: device, events: queue.splice(0, 50) });
508
+ const url = base + "/events";
509
+ if (!(navigator.sendBeacon && navigator.sendBeacon(url, body))) {
510
+ fetch(url, { method: "POST", body, keepalive: true, credentials: "omit", mode: "no-cors" }).catch(function() {
511
+ });
512
+ }
513
+ });
514
+ if (typeof document !== "undefined") {
515
+ document.addEventListener("visibilitychange", function() {
516
+ if (document.visibilityState === "hidden") flush();
517
+ });
518
+ window.addEventListener("pagehide", flush);
519
+ }
520
+ function expose(variantId, itemKey) {
521
+ const exposed = sessionJSON("phn_exposed");
522
+ if (exposed[variantId]) return;
523
+ exposed[variantId] = 1;
524
+ setSessionJSON("phn_exposed", exposed);
525
+ track("proof_impression", variantId, itemKey);
526
+ }
527
+ const syncCart = safe(function() {
528
+ if (!config || config.site.platform !== "shopify" || !measuring()) return;
529
+ ensureIds();
530
+ if (session && session.getItem("phn_cart") === ids.sessionId) return;
531
+ fetch("/cart/update.js", {
532
+ method: "POST",
533
+ credentials: "same-origin",
534
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
535
+ body: JSON.stringify({ attributes: { _phn_vid: ids.visitorId, _phn_sid: ids.sessionId } })
536
+ }).then(function(res) {
537
+ if (res.ok && session) session.setItem("phn_cart", ids.sessionId);
538
+ }).catch(function() {
539
+ });
540
+ });
541
+ function onAddToCart(itemKey) {
542
+ const exposed = sessionJSON("phn_exposed");
543
+ const carted = sessionJSON("phn_carted");
544
+ for (const id in exposed) {
545
+ if (!carted[id]) {
546
+ carted[id] = 1;
547
+ track("add_to_cart", id, itemKey);
548
+ }
549
+ }
550
+ setSessionJSON("phn_carted", carted);
551
+ flush();
552
+ setTimeout(syncCart, 1200);
553
+ }
554
+ function loadConfig() {
555
+ if (configPromise) return configPromise;
556
+ if (!publicKey) return configPromise = Promise.resolve(null);
557
+ const controller = window.AbortController ? new AbortController() : null;
558
+ const timer = setTimeout(function() {
559
+ if (controller) controller.abort();
560
+ }, 4e3);
561
+ configPromise = fetch(base + "/config", { credentials: "omit", signal: controller ? controller.signal : void 0 }).then(function(res) {
562
+ return res.ok ? res.json() : null;
563
+ }).then(function(raw) {
564
+ clearTimeout(timer);
565
+ config = normalizeConfig(raw);
566
+ if (config && !opts.consentMode) consentMode = config.site.consentMode;
567
+ return config;
568
+ }).catch(function() {
569
+ return null;
570
+ });
571
+ return configPromise;
572
+ }
573
+ function pageContext(mo) {
574
+ let utm = null;
575
+ try {
576
+ utm = new URLSearchParams(location.search).get("utm_campaign");
577
+ } catch (e) {
578
+ }
579
+ let visitor = null;
580
+ if (measuring()) {
581
+ ensureIds();
582
+ visitor = session && session.getItem("phn_new") || !(local && local.getItem("phn_first")) ? "new" : "returning";
583
+ utm = utm || session && session.getItem("phn_utm");
584
+ }
585
+ return { path: location.pathname, placement: mo.placement || "other", device, visitor, utmCampaign: utm || "" };
586
+ }
587
+ const CSS = CARD_CSS;
588
+ function shadowHost() {
589
+ const host = document.createElement("div");
590
+ host.setAttribute("data-proofhorn", "");
591
+ document.body.appendChild(host);
592
+ const shadow = host.attachShadow ? host.attachShadow({ mode: "open" }) : host;
593
+ const style = document.createElement("style");
594
+ style.textContent = CSS + designCss(config && config.site.design);
595
+ shadow.appendChild(style);
596
+ return { host, shadow };
597
+ }
598
+ function runActivityPopup(widget, feed, mountOpts, cleanups) {
599
+ const variant = measuring() ? (ensureIds(), assignVariant(widget.variants, ids.visitorId, widget.id)) : defaultVariant(widget.variants);
600
+ if (!variant) return;
601
+ if (!feed.length) return;
602
+ expose(variant.id, mountOpts.itemKey);
603
+ if (variant.holdout) return;
604
+ const design = widget.design;
605
+ const delay = design.delayMs || 4e3;
606
+ const display = design.displayMs || 6e3;
607
+ const gap = design.gapMs || 12e3;
608
+ const max = design.maxPerSession || 5;
609
+ const perPage = design.maxPerPage > 0 ? design.maxPerPage : Infinity;
610
+ const loop = design.loop !== false;
611
+ const side = design.position === "bottom-right" ? "r" : "l";
612
+ const top = device === "m" && design.positionMobile === "top";
613
+ const lang = document.documentElement.lang || config.site.locale;
614
+ const template = pickTemplate(variant, lang);
615
+ const ordered = feed.slice().sort(function(a, b) {
616
+ return (b.itemKey === mountOpts.itemKey) - (a.itemKey === mountOpts.itemKey);
617
+ });
618
+ let ui = null;
619
+ let index = 0;
620
+ let timer = null;
621
+ let shownThisPage = 0;
622
+ const next = safe(function() {
623
+ const shown = sessionJSON("phn_shown");
624
+ const count = measuring() ? shown[widget.id] || 0 : shownThisPage;
625
+ if (count >= max || shownThisPage >= perPage || sessionJSON("phn_closed")[widget.id]) return;
626
+ let row = null;
627
+ let line = null;
628
+ for (let tries = 0; tries < ordered.length && !line; tries++) {
629
+ if (!loop && index >= ordered.length) return;
630
+ row = ordered[index++ % ordered.length];
631
+ line = renderTemplate(template, rowValues(row, Date.now(), lang));
632
+ }
633
+ if (!line) return;
634
+ shown[widget.id] = count + 1;
635
+ shownThisPage++;
636
+ setSessionJSON("phn_shown", shown);
637
+ ui = ui || shadowHost();
638
+ const card = buildCard(document, row, line, {
639
+ side,
640
+ top,
641
+ widgetDesign: design,
642
+ template,
643
+ lang,
644
+ now: Date.now(),
645
+ branding: config.site.branding,
646
+ onItemClick: function() {
647
+ track("proof_click", variant.id, row.itemKey);
648
+ flush();
649
+ },
650
+ onClose: function() {
651
+ const closed = sessionJSON("phn_closed");
652
+ closed[widget.id] = 1;
653
+ setSessionJSON("phn_closed", closed);
654
+ track("proof_interaction", variant.id, row.itemKey);
655
+ clearTimeout(timer);
656
+ hide(card);
657
+ }
658
+ });
659
+ ui.shadow.appendChild(card);
660
+ requestAnimationFrame(function() {
661
+ requestAnimationFrame(function() {
662
+ card.classList.add("s");
663
+ });
664
+ });
665
+ timer = setTimeout(function() {
666
+ hide(card);
667
+ timer = setTimeout(next, gap);
668
+ }, display);
669
+ });
670
+ function hide(card) {
671
+ card.classList.remove("s");
672
+ setTimeout(function() {
673
+ if (card.parentNode) card.parentNode.removeChild(card);
674
+ }, 400);
675
+ }
676
+ timer = setTimeout(next, delay);
677
+ cleanups.push(function() {
678
+ clearTimeout(timer);
679
+ if (ui && ui.host.parentNode) ui.host.parentNode.removeChild(ui.host);
680
+ });
681
+ }
682
+ const INLINE_CSS = ".phn-stars{display:inline-flex;align-items:center;gap:6px;color:inherit;text-decoration:none}.phn-stars__track{position:relative;display:inline-block;color:#d0d0d0;letter-spacing:2px;line-height:1}.phn-stars__fill{position:absolute;inset:0 auto 0 0;overflow:hidden;white-space:nowrap;color:var(--phn-star,#f5a623)}.phn-reviews{display:block}.phn-review{list-style:none;padding:16px 0;border-top:1px solid rgba(0,0,0,.08)}.phn-review__meta{display:flex;flex-wrap:wrap;gap:8px;align-items:center;font-size:.9em}.phn-review__label{font-size:.8em;padding:1px 6px;border-radius:4px;background:rgba(0,0,0,.06)}.phn-review__disclosure{font-size:.85em;font-style:italic;margin:6px 0 0}.phn-review__photos{display:flex;gap:6px;margin-top:8px}.phn-review__photos img{width:72px;height:72px;object-fit:cover;border-radius:6px}.phn-review__reply{margin-top:8px;padding:8px 12px;background:rgba(0,0,0,.04);border-radius:6px}.phn-carousel{display:flex;gap:12px;overflow-x:auto;scroll-snap-type:x mandatory;padding:0;margin:0}.phn-carousel .phn-review{flex:0 0 min(320px,85%);scroll-snap-align:start;border:1px solid rgba(0,0,0,.08);border-radius:8px;padding:12px}.phn-more{margin-top:12px}";
683
+ let inlineStyled = false;
684
+ function inlineStyles() {
685
+ if (inlineStyled) return;
686
+ inlineStyled = true;
687
+ const style = document.createElement("style");
688
+ style.textContent = INLINE_CSS;
689
+ document.head.appendChild(style);
690
+ }
691
+ function el(tag, cls, text) {
692
+ const node = document.createElement(tag);
693
+ if (cls) node.className = cls;
694
+ if (text != null) node.textContent = text;
695
+ return node;
696
+ }
697
+ function stars(average, label) {
698
+ const wrap = el("span", "phn-stars");
699
+ wrap.setAttribute("role", "img");
700
+ wrap.setAttribute("aria-label", label);
701
+ const track2 = el("span", "phn-stars__track", "\u2605\u2605\u2605\u2605\u2605");
702
+ track2.setAttribute("aria-hidden", "true");
703
+ const fill = el("span", "phn-stars__fill", "\u2605\u2605\u2605\u2605\u2605");
704
+ fill.style.width = Math.max(0, Math.min(5, average)) / 5 * 100 + "%";
705
+ track2.appendChild(fill);
706
+ wrap.appendChild(track2);
707
+ return wrap;
708
+ }
709
+ function reviewNode(review, lang) {
710
+ const li = el("li", "phn-review");
711
+ const meta = el("div", "phn-review__meta");
712
+ meta.appendChild(stars(review.rating, review.rating + " out of 5 stars"));
713
+ meta.appendChild(el("span", "phn-review__author", review.author));
714
+ if (review.verified === true) meta.appendChild(el("span", "phn-review__label", "Verified"));
715
+ try {
716
+ meta.appendChild(el("span", "phn-review__date", new Date(review.date).toLocaleDateString(lang, { year: "numeric", month: "short", day: "numeric" })));
717
+ } catch (e) {
718
+ }
719
+ li.appendChild(meta);
720
+ if (review.title) li.appendChild(el("strong", "phn-review__title", review.title));
721
+ if (review.body) li.appendChild(el("p", "phn-review__body", review.body));
722
+ const media = Array.isArray(review.media) ? review.media : [];
723
+ const photos = el("div", "phn-review__photos");
724
+ for (const m of media) {
725
+ const url = m && typeof m === "object" ? m.url : m;
726
+ if (m && m.type && m.type !== "image" || typeof url !== "string" || !/^https:\/\//.test(url)) continue;
727
+ const img = el("img");
728
+ img.src = url;
729
+ img.alt = "Photo from " + review.author;
730
+ img.loading = "lazy";
731
+ img.width = 72;
732
+ img.height = 72;
733
+ photos.appendChild(img);
734
+ }
735
+ if (photos.childNodes.length) li.appendChild(photos);
736
+ if (reviewLabels(review).indexOf(INCENTIVE_LABEL) !== -1) li.appendChild(el("p", "phn-review__disclosure", INCENTIVE_LABEL));
737
+ if (review.reply) {
738
+ const reply = el("div", "phn-review__reply");
739
+ reply.appendChild(el("strong", null, "Reply: "));
740
+ reply.appendChild(document.createTextNode(review.reply));
741
+ li.appendChild(reply);
742
+ }
743
+ return li;
744
+ }
745
+ function getJSON(path) {
746
+ return fetch(base + path, { credentials: "omit" }).then(function(res) {
747
+ if (!res.ok) throw new Error(String(res.status));
748
+ return res.json();
749
+ });
750
+ }
751
+ const fillInline = safe(function(node) {
752
+ if (node.__phn) return;
753
+ node.__phn = true;
754
+ const type = node.getAttribute("data-proofhorn-widget");
755
+ const itemKey = node.getAttribute("data-proofhorn-item") || "";
756
+ const lang = document.documentElement.lang || "en";
757
+ inlineStyles();
758
+ if (type === "star_rating" && itemKey) {
759
+ getJSON("/ratings?items=" + encodeURIComponent(itemKey)).then(function(data) {
760
+ const r = data && data.ratings && data.ratings[itemKey];
761
+ if (!r || !r.count) return;
762
+ const out = el("span", "phn-stars");
763
+ out.appendChild(stars(r.average, "Rated " + r.average + " out of 5, " + r.count + " reviews"));
764
+ out.appendChild(el("span", "phn-stars__label", r.average.toFixed(1) + " (" + r.count + ")"));
765
+ node.textContent = "";
766
+ node.appendChild(out);
767
+ }).catch(function() {
768
+ });
769
+ return;
770
+ }
771
+ if (type === "review_list" || type === "review_carousel") {
772
+ const carousel = type === "review_carousel";
773
+ let page = 0;
774
+ let shown = 0;
775
+ let list = null;
776
+ let more = null;
777
+ let viewed = false;
778
+ const load = safe(function() {
779
+ page++;
780
+ const path = carousel ? "/reviews?page=" + page + "&minRating=4" : "/items/" + encodeURIComponent(itemKey) + "/reviews?page=" + page + "&sort=newest";
781
+ getJSON(path).then(function(data) {
782
+ const reviews = (data && Array.isArray(data.reviews) ? data.reviews : []).filter(function(r) {
783
+ return r && typeof r.rating === "number";
784
+ });
785
+ if (!list) {
786
+ if (!reviews.length) return;
787
+ node.textContent = "";
788
+ list = el(carousel ? "ul" : "ol", carousel ? "phn-carousel" : "phn-reviews");
789
+ node.appendChild(list);
790
+ if (!carousel) {
791
+ more = el("button", "phn-more", "Show more reviews");
792
+ more.type = "button";
793
+ more.addEventListener("click", load);
794
+ node.appendChild(more);
795
+ }
796
+ }
797
+ for (const r of reviews) list.appendChild(reviewNode(r, lang));
798
+ shown += reviews.length;
799
+ if (more) more.hidden = !(reviews.length === data.pageSize && shown < data.total);
800
+ if (!viewed && shown) {
801
+ viewed = true;
802
+ track("review_view", null, itemKey || null);
803
+ }
804
+ }).catch(function() {
805
+ });
806
+ });
807
+ if (carousel || itemKey) {
808
+ if ("IntersectionObserver" in window) {
809
+ const io = new IntersectionObserver(
810
+ function(entries) {
811
+ if (entries[0].isIntersecting) {
812
+ io.disconnect();
813
+ load();
814
+ }
815
+ },
816
+ { rootMargin: "400px" }
817
+ );
818
+ io.observe(node);
819
+ } else load();
820
+ }
821
+ }
822
+ });
823
+ const api = {
824
+ version: "1.0.0",
825
+ getVisitor: function() {
826
+ if (measuring()) ensureIds();
827
+ return { visitorId: ids.visitorId, sessionId: ids.sessionId, referralCode };
828
+ },
829
+ consent: safe(function(granted) {
830
+ consented = !!granted;
831
+ if (consented) {
832
+ ensureIds();
833
+ syncCart();
834
+ }
835
+ }),
836
+ track: safe(function(type, data) {
837
+ const d = data || {};
838
+ track(type, d.variantId, d.itemKey, d.name);
839
+ }),
840
+ /** Shows the widgets for this page. Returns a function that removes them. */
841
+ mount: function(mountOptions) {
842
+ const mo = mountOptions || {};
843
+ const cleanups = [];
844
+ let stopped = false;
845
+ safe(function() {
846
+ const nodes = document.querySelectorAll("[data-proofhorn-widget]");
847
+ for (let i = 0; i < nodes.length; i++) fillInline(nodes[i]);
848
+ if (mo.itemKey && mo.placement === "item") track("product_view", null, mo.itemKey);
849
+ loadConfig().then(
850
+ safe(function(cfg) {
851
+ if (!cfg || stopped) return;
852
+ if (measuring()) ensureIds();
853
+ syncCart();
854
+ let popup = false;
855
+ const ctx = pageContext(mo);
856
+ if (!rulesAllow(cfg.site.rules, ctx)) return;
857
+ for (const w of cfg.widgets) {
858
+ if (w.type !== "recent_activity" || popup) continue;
859
+ if (!placementMatches(w.placement, mo.placement || "other") || !deviceMatches(w.targeting, device)) continue;
860
+ if (!rulesAllow(w.targeting.rules, ctx)) continue;
861
+ popup = true;
862
+ runActivityPopup(w, cfg.feed, mo, cleanups);
863
+ }
864
+ })
865
+ );
866
+ })();
867
+ return function() {
868
+ stopped = true;
869
+ for (const fn of cleanups) safe(fn)();
870
+ flush();
871
+ };
872
+ },
873
+ onAddToCart: safe(onAddToCart),
874
+ // For tests and conformance only.
875
+ _assign: assignVariant,
876
+ _fnv1a32: fnv1a32
877
+ };
878
+ return api;
879
+ }
880
+ export {
881
+ BROWSER_EVENT_TYPES,
882
+ INCENTIVE_LABEL,
883
+ KNOWN_WIDGET_TYPES,
884
+ assignVariant,
885
+ countryName,
886
+ createRuntime,
887
+ defaultVariant,
888
+ deviceMatches,
889
+ fnv1a32,
890
+ formatAmount,
891
+ isBrowserEventType,
892
+ normalizeConfig,
893
+ normalizeDesign,
894
+ pickTemplate,
895
+ placementMatches,
896
+ relativeTime,
897
+ renderTemplate,
898
+ reviewLabels,
899
+ rowValues,
900
+ ruleMatches,
901
+ rulesAllow,
902
+ sanitizeCss
903
+ };