@blotoutio/providers-evo-search-sdk 1.70.2 → 1.71.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/core.js CHANGED
@@ -818,6 +818,16 @@ var ProvidersEvoSearchSdk = (function () {
818
818
  'evoSearchProductAddedToCart',
819
819
  'evoSearchProductPurchased',
820
820
  'evoSearchSearchIssued',
821
+ // Relevance-telemetry pair (PR2 task 3): one impressions beacon per
822
+ // finalized query, one click beacon per result click. Server handling
823
+ // (Task 4) wired in routes/user.ts.
824
+ 'evoSearchImpressions',
825
+ 'evoSearchResultClick',
826
+ // One beacon per Ask answer the assistant could not produce (generation
827
+ // failure, budget exhaustion) — the client-side counterpart to the worker's
828
+ // own degrade counters, and the only signal for a failure the worker never
829
+ // sees (the request never reaching it).
830
+ 'evoSearchAskDegraded',
821
831
  ]);
822
832
  new Set([...uiActions]);
823
833
 
@@ -855,6 +865,172 @@ var ProvidersEvoSearchSdk = (function () {
855
865
  },
856
866
  };
857
867
 
868
+ // Pure, DOM-free session-context logic: what the shopper's tab has seen this
869
+ // visit, kept small enough to ride along on every search request as a `ctx`
870
+ // query param and every finalized-query beacon. No PII — ids, capped query
871
+ // strings, and an enum page type only. Storage wiring (sessionStorage
872
+ // read/write, entry page detection from location.pathname) lives in
873
+ // utils.ts; this module only knows how to grow and shrink the shape
874
+ // immutably, and how to encode it for the wire.
875
+ // Single source of truth for the enum — utils.ts's sessionStorage parse
876
+ // validates membership against this (not just `typeof === 'string'`) before
877
+ // trusting a stored value, so a hostile/corrupted entry can't smuggle an
878
+ // arbitrary string into the wire payload.
879
+ const PAGE_TYPES = [
880
+ 'home',
881
+ 'plp',
882
+ 'pdp',
883
+ 'cart',
884
+ 'search',
885
+ 'other',
886
+ ];
887
+ const isPageType = (value) => typeof value === 'string' && PAGE_TYPES.includes(value);
888
+ const MAX_VIEWED = 20;
889
+ // A product id longer than this is not an id any catalog issues; it is a
890
+ // runaway string that would eat the whole byte budget on one entry. Mirrors
891
+ // the decoder's own per-id cap, which DROPS (never truncates) an oversized
892
+ // id — a truncated id silently becomes a different, wrong product.
893
+ const MAX_PRODUCT_ID_CHARS = 64;
894
+ // The platform's global-id form for a product. Hosts hand us whichever form
895
+ // their storefront layer has to hand; the catalog is keyed on the bare id, so
896
+ // normalize here rather than making every caller remember which one to pass.
897
+ const GLOBAL_ID_PREFIX = 'gid://shopify/Product/';
898
+ /**
899
+ * Coerces a caller-supplied product id into the id space the catalog uses, or
900
+ * null when it cannot be one. Accepts a number (storefront globals expose the
901
+ * id numerically) or a string, tolerates the platform's global-id form, and
902
+ * rejects empty/oversized values rather than putting an id on the wire that
903
+ * can never resolve.
904
+ */
905
+ const normalizeProductId = (value) => {
906
+ const raw = typeof value === 'number' && Number.isFinite(value)
907
+ ? String(value)
908
+ : typeof value === 'string'
909
+ ? value.trim()
910
+ : '';
911
+ const id = raw.startsWith(GLOBAL_ID_PREFIX)
912
+ ? raw.slice(GLOBAL_ID_PREFIX.length)
913
+ : raw;
914
+ if (!id || id.length > MAX_PRODUCT_ID_CHARS) {
915
+ return null;
916
+ }
917
+ return id;
918
+ };
919
+ // Hard cap enforced by serializeContext, measured in ENCODED UTF-8 BYTES —
920
+ // `.length` counts UTF-16 code units, which undercounts CJK/emoji text by up
921
+ // to 3x. Kept in sync with the `ctx` query param budget documented in the
922
+ // PR2 brief (base64url grows this ~4/3, so ~2.7KB encoded — comfortably
923
+ // inside URL limits).
924
+ const MAX_SERIALIZED_BYTES = 2048;
925
+ const pushViewed = (ctx, id) => ({
926
+ ...ctx,
927
+ viewed: [id, ...ctx.viewed.filter((viewedId) => viewedId !== id)].slice(0, MAX_VIEWED),
928
+ });
929
+ // Drops entries from the tail (pushViewed/pushQuery keep newest-first) until
930
+ // the ENCODED byte length fits the hard cap, in order of how much each byte
931
+ // is worth: the browse list first (its tail is the least recent thing the
932
+ // shopper looked at, and it is the longest list), then the cart, then the
933
+ // queries — fewest entries and the most intent per byte, so they yield last
934
+ // but are not exempt: five 200-char CJK queries alone encode to ~3KB, so a
935
+ // character-bounded list can still blow a byte budget.
936
+ const serializeContext = (ctx) => {
937
+ let working = {
938
+ ...ctx,
939
+ viewed: [...ctx.viewed],
940
+ cart: [...ctx.cart],
941
+ queries: [...ctx.queries],
942
+ };
943
+ let serialized = JSON.stringify(working);
944
+ while (textEncoder.encode(serialized).length > MAX_SERIALIZED_BYTES &&
945
+ (working.viewed.length > 0 ||
946
+ working.cart.length > 0 ||
947
+ working.queries.length > 0)) {
948
+ working =
949
+ working.viewed.length > 0
950
+ ? { ...working, viewed: working.viewed.slice(0, -1) }
951
+ : working.cart.length > 0
952
+ ? { ...working, cart: working.cart.slice(0, -1) }
953
+ : { ...working, queries: working.queries.slice(0, -1) };
954
+ serialized = JSON.stringify(working);
955
+ }
956
+ return serialized;
957
+ };
958
+ // Detected once per session from the entry URL — home/plp/pdp/cart by path
959
+ // shape, everything else is 'other'. Pure so it's testable alongside the
960
+ // rest of this module; utils.ts calls it exactly once, on first read.
961
+ const detectEntryPage = (pathname) => {
962
+ if (pathname === '/') {
963
+ return 'home';
964
+ }
965
+ if (pathname.startsWith('/products/')) {
966
+ return 'pdp';
967
+ }
968
+ if (pathname.startsWith('/collections/')) {
969
+ return 'plp';
970
+ }
971
+ if (pathname.startsWith('/cart')) {
972
+ return 'cart';
973
+ }
974
+ return 'other';
975
+ };
976
+ // Native TextEncoder + btoa, same as the CDN sibling's utils/user-auth.ts —
977
+ // jsdom's missing TextEncoder is a test-environment gap, polyfilled in
978
+ // jest.setup.ts rather than worked around in shipped code.
979
+ const textEncoder = new TextEncoder();
980
+ const toBase64Url = (bytes) => {
981
+ let bin = '';
982
+ for (let i = 0; i < bytes.length; i++) {
983
+ bin += String.fromCharCode(bytes[i]);
984
+ }
985
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
986
+ };
987
+ // Wire form for the `ctx` search query param: base64url(serializeContext(ctx)),
988
+ // no padding. Returns null when there's nothing worth the extra URL bytes —
989
+ // a context with no viewed products, cart lines or past queries yet (e.g. the very
990
+ // first search of a fresh tab) — so a brand-new session doesn't pay for a
991
+ // param carrying only the entryPage enum.
992
+ const encodeContextParam = (ctx) => {
993
+ if (ctx.viewed.length === 0 &&
994
+ ctx.cart.length === 0 &&
995
+ ctx.queries.length === 0) {
996
+ return null;
997
+ }
998
+ return toBase64Url(textEncoder.encode(serializeContext(ctx)));
999
+ };
1000
+
1001
+ // `crypto.randomUUID` is secure-context-only: on an `http://` storefront it is
1002
+ // undefined and calling it throws a TypeError. Called bare, that threw from
1003
+ // inside the autocomplete and image-search render paths — after results were
1004
+ // already assigned — so the catch cleared them and the shopper saw an error
1005
+ // state for a working search. `crypto.getRandomValues` has no such
1006
+ // restriction, so it carries the fallback; Math.random is the last resort for
1007
+ // an environment with no crypto at all. The output stays RFC4122-v4 shaped
1008
+ // either way, because the worker's beacon validators reject anything else.
1009
+ const randomBytes16 = () => {
1010
+ const bytes = new Uint8Array(16);
1011
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
1012
+ crypto.getRandomValues(bytes);
1013
+ return bytes;
1014
+ }
1015
+ for (let i = 0; i < bytes.length; i++) {
1016
+ bytes[i] = Math.floor(Math.random() * 256);
1017
+ }
1018
+ return bytes;
1019
+ };
1020
+ const mintId = () => {
1021
+ var _a, _b;
1022
+ if (typeof crypto !== 'undefined' &&
1023
+ typeof crypto.randomUUID === 'function') {
1024
+ return crypto.randomUUID();
1025
+ }
1026
+ const bytes = randomBytes16();
1027
+ // Version 4, variant 10xx — the two bits the shape check would otherwise
1028
+ // read as a malformed id.
1029
+ bytes[6] = (((_a = bytes[6]) !== null && _a !== void 0 ? _a : 0) & 0x0f) | 0x40;
1030
+ bytes[8] = (((_b = bytes[8]) !== null && _b !== void 0 ? _b : 0) & 0x3f) | 0x80;
1031
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
1032
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1033
+ };
858
1034
  // Intentionally duplicated from @blotoutio/providers/evo-search/config to keep the hooks bundle lean — importing from the config barrel pulls the shared/universal geo data into dist/hooks.mjs (~4KB gzipped). Drift between the two values is caught by utils.test.ts.
859
1035
  const previewKeyName = 'previewEvoSearch';
860
1036
  const hasPreviewKey = () => {
@@ -879,6 +1055,101 @@ var ProvidersEvoSearchSdk = (function () {
879
1055
  return false;
880
1056
  }
881
1057
  };
1058
+ // Cross-widget, cross-search shopper context (recently viewed products,
1059
+ // finalized queries, entry page) that rides along on every search
1060
+ // request as a `ctx` query param and every finalized-query beacon, so
1061
+ // ranking/telemetry can see the visit's shape without the worker
1062
+ // maintaining its own session. A query param, not a header, so /search
1063
+ // stays a CORS-simple request (no preflight on the per-keystroke hot path).
1064
+ // sessionStorage-scoped like the rest of this file's keys: it dies with the
1065
+ // tab and never needs a retention policy. No PII — see session-context.ts.
1066
+ const sessionContextKeyName = 'evoSearchSessionContext';
1067
+ const emptySessionContext = () => ({
1068
+ viewed: [],
1069
+ cart: [],
1070
+ queries: [],
1071
+ entryPage: detectEntryPage(typeof window !== 'undefined' ? window.location.pathname : ''),
1072
+ });
1073
+ const getSessionContext = () => {
1074
+ try {
1075
+ const raw = sessionStorage.getItem(sessionContextKeyName);
1076
+ if (raw) {
1077
+ const parsed = JSON.parse(raw);
1078
+ // Element types are checked, not just array-ness: a corrupted stored
1079
+ // value (e.g. viewed: [123]) must not flow onto the wire as non-string
1080
+ // data. Fall through to a fresh context instead, same as the
1081
+ // entryPage enum check below.
1082
+ const isStringArray = (value) => Array.isArray(value) && value.every((v) => typeof v === 'string');
1083
+ // Absent, not invalid: a tab that started on an older SDK has a stored
1084
+ // context with no `cart` key at all. Reading that as a shape failure
1085
+ // would throw away its viewed/queries history on every upgrade, so a
1086
+ // missing list reads as an empty one; a wrong-typed one still falls
1087
+ // through to a fresh context like any other corrupted array.
1088
+ const storedCart = parsed.cart === undefined ? [] : parsed.cart;
1089
+ if (isStringArray(parsed.viewed) &&
1090
+ isStringArray(parsed.queries) &&
1091
+ isStringArray(storedCart)) {
1092
+ return {
1093
+ viewed: parsed.viewed,
1094
+ cart: storedCart,
1095
+ queries: parsed.queries,
1096
+ // A hostile/corrupted stored value (or a future enum member from a
1097
+ // newer SDK version) falls back to 'other' rather than discarding
1098
+ // otherwise-good viewed/queries data, and rather than passing
1099
+ // an unvalidated string through to the wire.
1100
+ entryPage: isPageType(parsed.entryPage) ? parsed.entryPage : 'other',
1101
+ };
1102
+ }
1103
+ }
1104
+ }
1105
+ catch {
1106
+ // Storage unavailable or corrupt; fall through to a fresh context.
1107
+ }
1108
+ // First read this session: detect entryPage once and persist immediately
1109
+ // so a later navigation within the same tab doesn't re-detect it from a
1110
+ // different path.
1111
+ const fresh = emptySessionContext();
1112
+ setSessionContext(fresh);
1113
+ return fresh;
1114
+ };
1115
+ /** @internal */
1116
+ const setSessionContext = (ctx) => {
1117
+ try {
1118
+ sessionStorage.setItem(sessionContextKeyName, serializeContext(ctx));
1119
+ }
1120
+ catch {
1121
+ // Storage unavailable; the context is best-effort telemetry, not
1122
+ // functionality — swallow rather than fail whatever caller triggered it.
1123
+ }
1124
+ };
1125
+ // base64url-encoded form for the `ctx` search query param — null when
1126
+ // there's nothing worth adding to the URL yet (see encodeContextParam).
1127
+ // api.ts stays decoupled from session-context's internals. Memoized because
1128
+ // search() calls this on every debounced keystroke: the cache is keyed on
1129
+ // the raw stored string, so a hit costs one getItem + compare instead of the
1130
+ // parse/serialize/encode chain, and any writer (not just setSessionContext)
1131
+ // invalidates it naturally.
1132
+ let cachedContextRaw = null;
1133
+ let cachedContextParam = null;
1134
+ const getSessionContextParam = () => {
1135
+ let raw = null;
1136
+ try {
1137
+ raw = sessionStorage.getItem(sessionContextKeyName);
1138
+ }
1139
+ catch {
1140
+ // Storage unavailable — nothing stable to memoize against.
1141
+ return encodeContextParam(getSessionContext());
1142
+ }
1143
+ if (raw !== null && raw === cachedContextRaw) {
1144
+ return cachedContextParam;
1145
+ }
1146
+ const ctx = getSessionContext();
1147
+ cachedContextParam = encodeContextParam(ctx);
1148
+ // A null raw means getSessionContext just persisted a fresh context — key
1149
+ // the cache on what it wrote so the next call hits.
1150
+ cachedContextRaw = raw !== null && raw !== void 0 ? raw : serializeContext(ctx);
1151
+ return cachedContextParam;
1152
+ };
882
1153
 
883
1154
  var _a;
884
1155
  const registryKey = Symbol.for('evo-search');
@@ -915,6 +1186,260 @@ var ProvidersEvoSearchSdk = (function () {
915
1186
  notifySubscribers(registry.subscribers, 'notifyReady');
916
1187
  };
917
1188
 
1189
+ /**
1190
+ * Storefront-local helpers, deliberately separate from the worker-scoped API
1191
+ * client: `api.ts` injects identity params and headers that must never reach
1192
+ * the merchant's own origin, and its `credentials: omit` policy is the
1193
+ * opposite of what storefront requests (which ride the cart cookie) need.
1194
+ */
1195
+ /**
1196
+ * The storefront's root path. Shopify publishes it (locale prefix included,
1197
+ * e.g. `/en-ca/`) on `window.Shopify.routes.root`; default to `/`.
1198
+ */
1199
+ const storefrontRoot = () => {
1200
+ var _a, _b;
1201
+ if (typeof window === 'undefined') {
1202
+ return '/';
1203
+ }
1204
+ const root = (_b = (_a = window.Shopify) === null || _a === void 0 ? void 0 : _a.routes) === null || _b === void 0 ? void 0 : _b.root;
1205
+ return typeof root === 'string' && root.startsWith('/') && root.endsWith('/')
1206
+ ? root
1207
+ : '/';
1208
+ };
1209
+
1210
+ // Storefront-side producers for the shopper session context. `session-context.ts`
1211
+ // knows how to grow the shape and `utils.ts` how to persist it; this module is
1212
+ // the only place that decides, from the page itself, WHAT to put in it.
1213
+ //
1214
+ // Why it exists: the widget's product-click handler is the only other producer,
1215
+ // so a shopper who browses the storefront normally — landing on product pages
1216
+ // from a collection, an ad, or a link — contributes nothing to ranking until
1217
+ // they happen to click a result inside search. Capturing the product page the
1218
+ // shopper is standing on closes that gap.
1219
+ //
1220
+ // Constraints this module works under, all deliberate:
1221
+ // - No network calls. This runs on the merchant's storefront; every id comes
1222
+ // from something already in the page (a global the platform published, or
1223
+ // the page's own structured data) or from a host that hands it to us.
1224
+ // - No PII, no page text. Ids only — never titles, prices or descriptions.
1225
+ // - Never throws. Every source is optional and best-effort: a page that
1226
+ // exposes none of them simply contributes nothing.
1227
+ // - No consent gate of its own. The context is anonymous, client-held and
1228
+ // dies with the tab; the provider is loaded under the pixel's own consent
1229
+ // decision, so a suppressed init means no capture at all, and the
1230
+ // transport (the `ctx` search param) stays gated on the merchant opt-in
1231
+ // that api.ts checks.
1232
+ const shopifyMeta = () => {
1233
+ var _a, _b;
1234
+ const w = window;
1235
+ // Two spellings of the same platform-published object: themes render the
1236
+ // analytics one, and some render a bare `meta` as well. Neither is catalog
1237
+ // data — they are the platform's page-scoped conventions.
1238
+ return (_b = (_a = w.ShopifyAnalytics) === null || _a === void 0 ? void 0 : _a.meta) !== null && _b !== void 0 ? _b : w.meta;
1239
+ };
1240
+ /**
1241
+ * True when the page the shopper is on is a product page, by the two signals
1242
+ * a storefront publishes without us asking: the platform's own page-type
1243
+ * marker, and the product path shape under the storefront root (which carries
1244
+ * the locale prefix on localized stores, so `/fr/products/…` is recognized).
1245
+ */
1246
+ const onProductPage = () => {
1247
+ var _a, _b;
1248
+ if (((_b = (_a = shopifyMeta()) === null || _a === void 0 ? void 0 : _a.page) === null || _b === void 0 ? void 0 : _b.pageType) === 'product') {
1249
+ return true;
1250
+ }
1251
+ return window.location.pathname.startsWith(`${storefrontRoot()}products/`);
1252
+ };
1253
+ // Structured data is the last resort and the only source read out of the DOM,
1254
+ // so it is bounded on every axis: how many blocks are parsed, how big a block
1255
+ // may be, and how deep the search for a Product node goes.
1256
+ const MAX_LD_BLOCKS = 5;
1257
+ // A structured-data block far larger than this is a page-wide graph, not one
1258
+ // product's node; parsing it would cost more than the signal is worth.
1259
+ const MAX_LD_CHARS = 100000;
1260
+ const productIdFromLdNode = (node) => {
1261
+ if (!node || typeof node !== 'object') {
1262
+ return null;
1263
+ }
1264
+ if (Array.isArray(node)) {
1265
+ for (const entry of node) {
1266
+ const found = productIdFromLdNode(entry);
1267
+ if (found) {
1268
+ return found;
1269
+ }
1270
+ }
1271
+ return null;
1272
+ }
1273
+ const record = node;
1274
+ const graph = record['@graph'];
1275
+ if (Array.isArray(graph)) {
1276
+ return productIdFromLdNode(graph);
1277
+ }
1278
+ const type = record['@type'];
1279
+ const isProduct = Array.isArray(type)
1280
+ ? type.includes('Product')
1281
+ : type === 'Product';
1282
+ if (!isProduct) {
1283
+ return null;
1284
+ }
1285
+ const id = normalizeProductId(record['productID']);
1286
+ // Only an all-digits id is accepted here, and `sku` is never read: the
1287
+ // catalog is keyed on the platform's own numeric product id, whereas a
1288
+ // merchant SKU (or a handle) is a different id space entirely. An id from
1289
+ // the wrong space can never resolve server-side — it would silently occupy
1290
+ // one of the few recently-viewed slots and contribute nothing. A host whose
1291
+ // structured data carries something else should call `trackProductView`.
1292
+ return id && /^\d+$/.test(id) ? id : null;
1293
+ };
1294
+ const productIdFromStructuredData = () => {
1295
+ const blocks = document.querySelectorAll('script[type="application/ld+json"]');
1296
+ const limit = Math.min(blocks.length, MAX_LD_BLOCKS);
1297
+ for (let i = 0; i < limit; i++) {
1298
+ const text = blocks[i].textContent;
1299
+ if (!text || text.length > MAX_LD_CHARS) {
1300
+ continue;
1301
+ }
1302
+ try {
1303
+ const found = productIdFromLdNode(JSON.parse(text));
1304
+ if (found) {
1305
+ return found;
1306
+ }
1307
+ }
1308
+ catch {
1309
+ // A malformed block is one merchant app's problem, not ours; try the
1310
+ // next one.
1311
+ }
1312
+ }
1313
+ return null;
1314
+ };
1315
+ /**
1316
+ * The id of the product this page is about, or null when the page isn't a
1317
+ * product page (or doesn't say which product it is). Sources are tried
1318
+ * cheapest first and each one is optional.
1319
+ */
1320
+ const currentProductId = () => {
1321
+ var _a, _b;
1322
+ try {
1323
+ // The platform global is authoritative and free: it is only populated on
1324
+ // a product page, and it carries the id in the catalog's own id space.
1325
+ const fromGlobal = normalizeProductId((_b = (_a = shopifyMeta()) === null || _a === void 0 ? void 0 : _a.product) === null || _b === void 0 ? void 0 : _b.id);
1326
+ if (fromGlobal) {
1327
+ return fromGlobal;
1328
+ }
1329
+ if (!onProductPage()) {
1330
+ return null;
1331
+ }
1332
+ return productIdFromStructuredData();
1333
+ }
1334
+ catch {
1335
+ return null;
1336
+ }
1337
+ };
1338
+ const rememberView = (id) => {
1339
+ const ctx = getSessionContext();
1340
+ // Once per page load: a re-entrant call (a second capture attempt, a
1341
+ // re-init) must not churn storage for a product that is already the most
1342
+ // recent view. A LATER load of the same product is a different matter — by
1343
+ // then something else is at the head, so it pushes again and moves back to
1344
+ // the front, which is how recency is expressed. There is no repeat counter:
1345
+ // `viewed` is a deduplicated, newest-first list and the server tallies each
1346
+ // id once.
1347
+ if (ctx.viewed[0] === id) {
1348
+ return;
1349
+ }
1350
+ setSessionContext(pushViewed(ctx, id));
1351
+ };
1352
+ /**
1353
+ * Records the product page the shopper is currently on, if this is one.
1354
+ * Returns whether anything was recorded (the retry below is its only caller
1355
+ * that cares).
1356
+ */
1357
+ const captureProductView = () => {
1358
+ try {
1359
+ const id = currentProductId();
1360
+ if (!id) {
1361
+ return false;
1362
+ }
1363
+ rememberView(id);
1364
+ return true;
1365
+ }
1366
+ catch {
1367
+ // Storage or DOM unavailable — the context is best-effort ranking input,
1368
+ // never functionality.
1369
+ return false;
1370
+ }
1371
+ };
1372
+ /**
1373
+ * Called once from the SDK bootstrap. The platform's page globals are written
1374
+ * by the theme's own head markup, so a loader that runs ahead of them would
1375
+ * see nothing at init; when the document is still parsing and nothing was
1376
+ * found, try again once the DOM is complete.
1377
+ */
1378
+ const startProductViewCapture = () => {
1379
+ try {
1380
+ if (captureProductView()) {
1381
+ return;
1382
+ }
1383
+ if (document.readyState === 'loading') {
1384
+ document.addEventListener('DOMContentLoaded', () => {
1385
+ captureProductView();
1386
+ }, { once: true });
1387
+ }
1388
+ }
1389
+ catch {
1390
+ // See captureProductView.
1391
+ }
1392
+ };
1393
+
1394
+ const createSessionContextGate = (uiPreferences, fetchConfig,
1395
+ // Whether this shopper has accumulated anything worth sending yet. Spending
1396
+ // a request to ask permission to send nothing is the one case where the
1397
+ // probe is pure waste, and it is also the common one — a session that has
1398
+ // just started has an empty context.
1399
+ hasContext) => {
1400
+ let serverEnabled = false;
1401
+ // One probe per API instance, latched BEFORE the request is issued so a
1402
+ // slow or failing config fetch can never turn the per-keystroke search path
1403
+ // into a retry storm. A probe that fails leaves the gate off, which is the
1404
+ // safe answer: the context is best-effort ranking input, never correctness.
1405
+ let probed = false;
1406
+ const prime = () => {
1407
+ // An explicit merchant preference already decides the question in both
1408
+ // directions, so there is nothing to ask the server about.
1409
+ if (probed || (uiPreferences === null || uiPreferences === void 0 ? void 0 : uiPreferences.sessionContext) !== undefined) {
1410
+ return;
1411
+ }
1412
+ // Deliberately does NOT latch `probed`: a session with nothing to say yet
1413
+ // will have something to say later, and that later call is the one worth
1414
+ // spending the probe on.
1415
+ if (!hasContext()) {
1416
+ return;
1417
+ }
1418
+ probed = true;
1419
+ // Deferred to a microtask so the request that triggered the prime is
1420
+ // already on the wire: the probe must never compete with, delay, or
1421
+ // reorder the search it rides behind.
1422
+ void Promise.resolve().then(() => fetchConfig().catch(() => {
1423
+ // Swallowed deliberately — the gate simply stays off. The caller that
1424
+ // triggered this never learns of it, and never retries.
1425
+ }));
1426
+ };
1427
+ return {
1428
+ shouldSend: () => {
1429
+ var _a;
1430
+ prime();
1431
+ // The merchant preference is an explicit override in both directions;
1432
+ // absent — the normal state — defers to the server's last answer.
1433
+ return (_a = uiPreferences === null || uiPreferences === void 0 ? void 0 : uiPreferences.sessionContext) !== null && _a !== void 0 ? _a : serverEnabled;
1434
+ },
1435
+ prime,
1436
+ resolveFrom: (sessionContextEnabled) => {
1437
+ probed = true;
1438
+ serverEnabled = sessionContextEnabled === true;
1439
+ },
1440
+ };
1441
+ };
1442
+
918
1443
  // Resilience wrapper for /search requests. A transient network failure or a
919
1444
  // hung request must not wedge the UI: add a per-attempt timeout (a hang becomes
920
1445
  // a rejection), retry transient failures with backoff, and never retry a
@@ -1151,6 +1676,13 @@ var ProvidersEvoSearchSdk = (function () {
1151
1676
  // Ask can't reuse withSearchResilience: a half-consumed stream isn't retryable.
1152
1677
  // Idle timeout resets per chunk; both reject with TimeoutError so submitAsk
1153
1678
  // routes them to the search fallback rather than treating them as cancellation.
1679
+ // Ceiling for an assembled GET URL, past which the optional session-context
1680
+ // param is dropped (see getJSON). Chosen above the encoder's own worst case —
1681
+ // session-context.ts caps its payload at 2KB, which base64url-grows to ~2.7KB
1682
+ // — so a legitimately full context is never dropped on its own, and several
1683
+ // times under the request-line ceiling of the edge that terminates these
1684
+ // requests. It is a safety bound, not a tuning knob.
1685
+ const MAX_REQUEST_URL_CHARS = 4096;
1154
1686
  const QUICK_ADD_VALIDATE_TIMEOUT_MS = 7000;
1155
1687
  const ASK_REQUEST_TIMEOUT_MS = 7000;
1156
1688
  const ASK_SSE_IDLE_TIMEOUT_MS = 10000;
@@ -1164,6 +1696,16 @@ var ProvidersEvoSearchSdk = (function () {
1164
1696
  // Stand-in caller signal for `search()` calls that don't pass one. Module-level
1165
1697
  // and never aborted, so it carries no state between calls.
1166
1698
  const NEVER_ABORTED = new AbortController().signal;
1699
+ // Tells /search this client resolves the response's product and collection
1700
+ // lanes against the top-level arrays itself, so the lanes need only carry ids.
1701
+ // Without it the server repeats every lane entry in full, which roughly doubles
1702
+ // the body for entries the client already has. Sent on both search legs so
1703
+ // neither pays for the duplication.
1704
+ //
1705
+ // Opt-in from the client, not a server-side switch: the client is published
1706
+ // separately from the worker, so a storefront can be running any earlier
1707
+ // version of it. One that never sends this keeps receiving whole entries.
1708
+ const LANE_REFERENCES = { lanes: 'ids' };
1167
1709
  // Always defer to what the storefront itself is rendering — same source
1168
1710
  // shop-gpt reads from. Two widgets on the same page would otherwise drift:
1169
1711
  // shop-gpt picks Shopify, evo-search would pick its own override and show
@@ -1294,6 +1836,16 @@ var ProvidersEvoSearchSdk = (function () {
1294
1836
  if (!credentialed) {
1295
1837
  setIdentityParams(url);
1296
1838
  }
1839
+ // Measured only here, where the URL is finally assembled: the results-page
1840
+ // leg carries facets, filter selections, a continuation cursor and identity
1841
+ // on top of the query, so its length is not knowable at the call site. A
1842
+ // session context is a ranking hint, so an over-long URL drops the hint
1843
+ // rather than the request — a slightly less personalized answer beats a
1844
+ // refused one.
1845
+ if (url.href.length > MAX_REQUEST_URL_CHARS &&
1846
+ url.searchParams.has('ctx')) {
1847
+ url.searchParams.delete('ctx');
1848
+ }
1297
1849
  const response = await fetchImpl(url, {
1298
1850
  method: 'GET',
1299
1851
  ...(credentialed ? { headers: getHeaders() } : {}),
@@ -1313,9 +1865,21 @@ var ProvidersEvoSearchSdk = (function () {
1313
1865
  logger.info('EvoSearch API: Fetching trending searches');
1314
1866
  return getJSON('/trending', 'Trending', undefined, signal);
1315
1867
  };
1316
- const config = (signal) => {
1868
+ // Held in the gate rather than read off `uiPreferences` at each send site:
1869
+ // that object is captured by value when this API instance is built, and the
1870
+ // widget replaces its own copy after fetching config, so an overlay there
1871
+ // would never reach this closure. The gate starts closed, so a search that
1872
+ // races ahead of the first answer sends nothing — session context is
1873
+ // best-effort ranking input, never a correctness input. `config` is
1874
+ // referenced lazily (only once the probe fires, long after this line runs).
1875
+ const sessionContextGate = createSessionContextGate(uiPreferences, () => config(), () => getSessionContextParam() !== null);
1876
+ const config = async (signal) => {
1317
1877
  logger.info('EvoSearch API: Fetching ask config');
1318
- return getJSON('/config', 'Config', undefined, signal);
1878
+ const data = await getJSON('/config', 'Config', undefined, signal);
1879
+ // A worker deployed before this gate omits the field; an absent answer
1880
+ // must read as off rather than as an opt-in.
1881
+ sessionContextGate.resolveFrom(data.sessionContextEnabled);
1882
+ return data;
1319
1883
  };
1320
1884
  const searchPageDesign = (signal, previewToken) => {
1321
1885
  logger.info(`EvoSearch API: Fetching ${previewToken ? 'preview' : 'published'} search page design`);
@@ -1385,11 +1949,38 @@ var ProvidersEvoSearchSdk = (function () {
1385
1949
  };
1386
1950
  const deleteRecent = (value) => sendMutation('/user/recents', 'DeleteRecent', 'DELETE', { value });
1387
1951
  const clearRecents = () => sendMutation('/user/recents', 'ClearRecents', 'DELETE');
1952
+ // The single decision point for whether a request carries the shopper's
1953
+ // session context, shared by both search legs so the autocomplete and
1954
+ // results-page requests cannot drift apart on when it is sent — the results
1955
+ // page is where a shopper spends the most time, so a leg without it is a
1956
+ // silently unpersonalized surface.
1957
+ //
1958
+ // Best-effort shopper context (recently viewed, past queries, entry page)
1959
+ // for server-side ranking, capped well under 2KB by session-context.ts.
1960
+ // Carried as a query param rather than a header so /search stays a
1961
+ // CORS-simple request — no OPTIONS preflight on the per-keystroke hot path.
1962
+ // Omitted while there's nothing to say yet. Gated on the server, which is
1963
+ // the only side that knows whether a `ctx` consumer is live: sending browsing
1964
+ // history nobody reads is pure cost and pure exposure. The merchant
1965
+ // preference is an explicit override in both directions — set, it wins;
1966
+ // absent (the normal state), the server decides.
1967
+ const withSessionContext = (params) => {
1968
+ if (!sessionContextGate.shouldSend()) {
1969
+ return params;
1970
+ }
1971
+ const ctxParam = getSessionContextParam();
1972
+ return ctxParam ? { ...params, ctx: ctxParam } : params;
1973
+ };
1388
1974
  // Resilience lives here, not at each call site, so no consumer can opt out —
1389
1975
  // the headless channel previously had no deadline and no retry.
1390
1976
  const search = async (query, limit = 24, signal) => {
1391
1977
  logger.info(`EvoSearch API: Search request - query length: ${query.length}, limit: ${limit}`);
1392
- const data = await withSearchResilience((attemptSignal) => getJSON('/search', 'Search', { q: query, limit: String(limit) }, attemptSignal),
1978
+ const searchParams = withSessionContext({
1979
+ q: query,
1980
+ limit: String(limit),
1981
+ ...LANE_REFERENCES,
1982
+ });
1983
+ const data = await withSearchResilience((attemptSignal) => getJSON('/search', 'Search', searchParams, attemptSignal),
1393
1984
  // Shared stand-in is safe: the wrapper removes its abort listener per attempt.
1394
1985
  signal !== null && signal !== void 0 ? signal : NEVER_ABORTED);
1395
1986
  logger.info(`EvoSearch API: Search success - ${data.llmSuggestions.length} suggestions, ${data.products.length} products`);
@@ -1403,6 +1994,7 @@ var ProvidersEvoSearchSdk = (function () {
1403
1994
  const params = {
1404
1995
  q: query,
1405
1996
  facets: '1',
1997
+ ...LANE_REFERENCES,
1406
1998
  };
1407
1999
  if (options.limit != null) {
1408
2000
  params['limit'] = String(options.limit);
@@ -1436,7 +2028,12 @@ var ProvidersEvoSearchSdk = (function () {
1436
2028
  if ((filters === null || filters === void 0 ? void 0 : filters.priceMax) != null) {
1437
2029
  params['priceMax'] = String(filters.priceMax);
1438
2030
  }
1439
- return withSearchResilience((attemptSignal) => getJSON('/search', 'SearchResults', params, attemptSignal), (_f = options.signal) !== null && _f !== void 0 ? _f : NEVER_ABORTED);
2031
+ return withSearchResilience((attemptSignal) => getJSON('/search', 'SearchResults',
2032
+ // Applied per attempt, and to every page: a continuation (cursor) or
2033
+ // a numbered page (offset) is the same result set the shopper is
2034
+ // still reading, so dropping the context there would re-rank the
2035
+ // next page against a different profile than the first.
2036
+ withSessionContext(params), attemptSignal), (_f = options.signal) !== null && _f !== void 0 ? _f : NEVER_ABORTED);
1440
2037
  };
1441
2038
  // Same deadline as `validateQuickAdd`, and for the same reason: the only
1442
2039
  // caller passes no signal, so without one a stalled request never settles —
@@ -1693,7 +2290,7 @@ var ProvidersEvoSearchSdk = (function () {
1693
2290
  .catch(logger.error);
1694
2291
  // Also send to analytics via sendTag
1695
2292
  sendTag({
1696
- eventId: crypto.randomUUID(),
2293
+ eventId: mintId(),
1697
2294
  eventName: action,
1698
2295
  data: {
1699
2296
  ...actionData,
@@ -1761,6 +2358,17 @@ var ProvidersEvoSearchSdk = (function () {
1761
2358
  }
1762
2359
  };
1763
2360
 
2361
+ const FORCED_KEY = 'evsUiVersion';
2362
+ // ?evs=reset must also drop the QA force so a shopper returns to the configured version.
2363
+ const clearForcedUiVersion = () => {
2364
+ try {
2365
+ sessionStorage.removeItem(FORCED_KEY);
2366
+ }
2367
+ catch {
2368
+ /* no-op: storage unavailable */
2369
+ }
2370
+ };
2371
+
1764
2372
  const error = (message) => console.error(message);
1765
2373
  // Headless hosts render their own UI, so nothing else pings /warm for them.
1766
2374
  let disposeKeepWarm;
@@ -1833,6 +2441,7 @@ var ProvidersEvoSearchSdk = (function () {
1833
2441
  try {
1834
2442
  sessionStorage.removeItem(previewKeyName);
1835
2443
  sessionStorage.removeItem(disableKeyName);
2444
+ clearForcedUiVersion();
1836
2445
  logger.info('EvoSearch SDK: Reset to configured state via ?evs=reset URL param');
1837
2446
  }
1838
2447
  catch {
@@ -1852,6 +2461,13 @@ var ProvidersEvoSearchSdk = (function () {
1852
2461
  if (hasPreview) {
1853
2462
  logger.info('EvoSearch SDK: Preview mode enabled via sessionStorage');
1854
2463
  }
2464
+ // Before the UI/headless fork: a headless host returns early below, and
2465
+ // its shoppers browse product pages exactly like everyone else's. Not
2466
+ // gated on the session-context opt-in — that flag gates the TRANSPORT
2467
+ // (api.ts decides whether the context leaves the browser), and gating
2468
+ // capture too would leave a merchant who turns it on with an empty
2469
+ // history until the shopper navigates again.
2470
+ startProductViewCapture();
1855
2471
  const evoSearchAPI = createEvoSearchAPI({
1856
2472
  baseURL: params.baseUrl,
1857
2473
  userId: params.userId,
@@ -1863,7 +2479,7 @@ var ProvidersEvoSearchSdk = (function () {
1863
2479
  const uiImplementation = window[registryKey].ui;
1864
2480
  const headless = !uiImplementation;
1865
2481
  params.sendTag({
1866
- eventId: crypto.randomUUID(),
2482
+ eventId: mintId(),
1867
2483
  eventName: 'evoSearchInitialized',
1868
2484
  data: { mode, hasPreview, headless },
1869
2485
  providers: { evoSearch: true },
@@ -1895,7 +2511,7 @@ var ProvidersEvoSearchSdk = (function () {
1895
2511
  visualSearchEnabled,
1896
2512
  });
1897
2513
  params.sendTag({
1898
- eventId: crypto.randomUUID(),
2514
+ eventId: mintId(),
1899
2515
  eventName: 'evoSearchLoaded',
1900
2516
  data: {},
1901
2517
  providers: { evoSearch: true },
@@ -1915,7 +2531,7 @@ var ProvidersEvoSearchSdk = (function () {
1915
2531
  const tag = ({ data }) => {
1916
2532
  try {
1917
2533
  return {
1918
- sdkVersion: "1.70.2" || '',
2534
+ sdkVersion: "1.71.1" || '',
1919
2535
  searchQuery: data['searchQuery'],
1920
2536
  searchResults: data['searchResults'],
1921
2537
  timestamp: Date.now(),
@@ -1924,7 +2540,7 @@ var ProvidersEvoSearchSdk = (function () {
1924
2540
  catch (err) {
1925
2541
  console.error(`EvoSearch SDK: Tagging failed - ${err}`);
1926
2542
  return {
1927
- sdkVersion: "1.70.2" ,
2543
+ sdkVersion: "1.71.1" ,
1928
2544
  timestamp: Date.now(),
1929
2545
  };
1930
2546
  }