@recapi/client 0.18.1 → 0.33.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.
package/src/client.js CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  resolveConfig,
19
19
  toWire
20
20
  } from './history.js';
21
+ import { REC_ID, bare, followProduct, pageOf, readProduct } from './page.js';
21
22
  import { createStore, defaultStorage, storageKey } from './storage.js';
22
23
  import { RecapiError, createTransport, defaultSleep, withRetry } from './transport.js';
23
24
 
@@ -54,9 +55,13 @@ const MAX_COUNT = 100;
54
55
  * so integrators don't have to learn the numbers. The API itself only
55
56
  * takes integers; the name is resolved here.
56
57
  */
58
+ // Per document and key, the client that follows the page: two copies of this file share it.
59
+ const FOLLOWING = Symbol.for('recapi.following');
57
60
  const LEVEL_NAMES = Object.freeze({ view: 3, cart: 5, purchase: 10, reject: -10 });
58
61
  /** The API's limit on a request's `exclude` list (docs/api.md). */
59
62
  const MAX_EXCLUDE = 500;
63
+ export const RECENTLY_VIEWED = 'recently_viewed';
64
+ export const BOUGHT_TOGETHER = 'bought_together';
60
65
  /**
61
66
  * Only a public key may travel in a URL: the API refuses a secret key from
62
67
  * `?key=`, because URLs end up in proxy and CDN logs.
@@ -86,6 +91,10 @@ const PUBLIC_KEY_PREFIX = 'rk_pub_';
86
91
  * @property {number} [timeoutMs] Per-request timeout.
87
92
  * @property {Partial<HistoryConfig>} [historyConfig]
88
93
  * @property {boolean} [consent] Initial storage consent (default `false`).
94
+ * @property {boolean} [describePages] In a browser, a product's first view
95
+ * sends the name and category the page gives search engines (default
96
+ * `true`), so a site that sent no catalog gets similar products by name.
97
+ * `false` sends nothing but the view.
89
98
  * @property {boolean} [respectDoNotTrack] When the browser sends Do Not
90
99
  * Track or Global Privacy Control (default `true`): store nothing, send no
91
100
  * events and no visitor ids; recommendations are still asked for.
@@ -165,13 +174,14 @@ export function createClient(options) {
165
174
  // the first storage access: never before consent, nor under Do Not Track.
166
175
  let adapter = options.storage;
167
176
  const storage = () => (adapter ??= defaultStorage(report));
177
+ const project = storageKey(options.project ?? apiKey.slice(0, 16));
168
178
  const store = createStore(
169
179
  {
170
180
  getItem: (key) => storage().getItem(key),
171
181
  setItem: (key, value) => storage().setItem(key, value),
172
182
  removeItem: (key) => storage().removeItem(key)
173
183
  },
174
- storageKey(options.project ?? apiKey.slice(0, 16)),
184
+ project,
175
185
  decodePersisted,
176
186
  report
177
187
  );
@@ -530,7 +540,200 @@ export function createClient(options) {
530
540
  globalThis.document?.addEventListener?.('visibilitychange', onVisibility);
531
541
  globalThis.window?.addEventListener?.('pagehide', flushOnHide);
532
542
 
543
+ // A product page's words, for a site that sent recapi no catalog: the
544
+ // name and category the page prints for search engines (page.js), which
545
+ // only ever name a product nothing signed described, and never draw a card
546
+ // (docs/api.md, POST /v1/products:seen). Nothing about the visitor, so
547
+ // sent with or without consent: once per product per browser where recapi
548
+ // may store, else once per page. Never under Do Not Track, which sends
549
+ // recapi nothing from the page. A module script runs after the page is
550
+ // parsed, but a classic one may not: WooCommerce prints its JSON-LD in the
551
+ // footer.
552
+ const describing = options.describePages !== false && auth === 'query' && typeof globalThis.document?.querySelectorAll === 'function';
553
+ const pagesKey = `${project}:pages`;
554
+ const described = new Map();
555
+ const describePage = (itemId) => {
556
+ const doc = globalThis.document;
557
+ if (doc.readyState === 'loading') {
558
+ doc.addEventListener('DOMContentLoaded', () => describePage(itemId), { once: true });
559
+ return;
560
+ }
561
+ let product;
562
+ try {
563
+ const href = String(globalThis.location?.href ?? '');
564
+ // A plain website's page whose markup we can't read still names its
565
+ // product's address: the site called it a product view, and our
566
+ // server draws the card from its title (Square Online adds its markup
567
+ // after this runs). A platform's plugin sends its catalog signed.
568
+ product = readProduct(pageOf(doc), href) ?? { name: '', category: '', url: options.platform === undefined ? bare(href) : '' };
569
+ } catch {
570
+ return;
571
+ }
572
+ if (!product.name && !product.category && !product.url) return;
573
+ const seen = compact({ id: itemId, title: product.name || undefined, category: product.category || undefined, page_url: product.url || undefined });
574
+ // FNV-1a: a short fingerprint of the words, to tell a change.
575
+ const text = JSON.stringify(seen);
576
+ let sum = 0x811c9dc5;
577
+ for (let i = 0; i < text.length; i++) sum = Math.imul(sum ^ text.charCodeAt(i), 0x01000193);
578
+ const hash = (sum >>> 0).toString(36);
579
+ let sent = {};
580
+ try {
581
+ if (consent) sent = JSON.parse(storage().getItem(pagesKey) ?? '{}') ?? {};
582
+ } catch {}
583
+ if (sent[itemId] === hash || described.get(itemId) === hash) return;
584
+ described.set(itemId, hash);
585
+ transport.request({ method: 'POST', path: '/v1/products:seen', body: { products: [seen] }, auth, keepalive: true }).then(() => {
586
+ if (!consent) return;
587
+ // Read again: other views (or tabs) answered meanwhile.
588
+ try {
589
+ sent = JSON.parse(storage().getItem(pagesKey) ?? '{}') ?? {};
590
+ } catch {
591
+ sent = {};
592
+ }
593
+ // The 100 products seen last: a visitor's storage stays small.
594
+ delete sent[itemId];
595
+ sent[itemId] = hash;
596
+ for (const old of Object.keys(sent).slice(0, -100)) delete sent[old];
597
+ storage().setItem(pagesKey, JSON.stringify(sent));
598
+ }, () => described.delete(itemId)).catch(() => {});
599
+ };
600
+
533
601
  let drawRow = null;
602
+ const placeRow = (slot, options) => {
603
+ // Rows called in one task still reach the drawer in one task, in order.
604
+ drawRow ??= import('./row.js').then(({ rows }) => rows(client));
605
+ drawRow.then((draw) => draw(slot, options), (error) => globalThis.console?.warn('recapi: the row failed to load:', error));
606
+ };
607
+
608
+ // Calls that name no product take the page's (page.js followProduct): a
609
+ // site with no ids of its own, or no way to print them in a template. Its
610
+ // views are sent again for each product the visitor moves to without a
611
+ // reload, and its rows drawn again; any other level goes once. Back or
612
+ // Forward to a page the browser shows from memory sends its view again,
613
+ // with no list (the card's link left the address with the first), and
614
+ // leaves its rows as the visitor saw them (row.js redraws a home page's
615
+ // Recently viewed). A single-page site calls them again on each of its
616
+ // routes: one view entry, and one entry per slot, follow the page, so a
617
+ // repeat sends no second view.
618
+ let unfollow = null;
619
+ let pageId = null;
620
+ let pageAt = null;
621
+ const onPage = new Set();
622
+ const here = () => String(globalThis.location?.href ?? '').split('#')[0];
623
+ const apply = (entry, id, again) => {
624
+ if (Object.hasOwn(entry, 'slot')) {
625
+ const { slot, options } = entry;
626
+ const doc = globalThis.document;
627
+ entry.waiting = false;
628
+ // The row placed for the last product goes with it.
629
+ if (entry.placed && (entry.placed.id !== id || !entry.placed.el.isConnected)) {
630
+ entry.placed.unfit();
631
+ entry.placed.el.remove();
632
+ entry.placed = null;
633
+ }
634
+ // A site-wide tag (Wix, Squarespace) has no element to fill: on a
635
+ // product page, the row goes under the product, above the footer.
636
+ const placeable = options.place !== false && typeof slot === 'string' && /^#[A-Za-z][\w-]*$/.test(slot);
637
+ if (placeable && !doc.querySelector?.(slot)) {
638
+ // The tag sits on every page of the site: one with no product needs
639
+ // no row, and its console no line about a missing element.
640
+ if (!id) return;
641
+ const { el, spot } = placeSlot(doc, slot.slice(1));
642
+ const unfit = fitSlot(doc, el);
643
+ const unkeep = spot ? keepSlot(doc, el, spot, unfit.fit) : () => {};
644
+ entry.placed = { el, id, unfit: () => (unkeep(), unfit()) };
645
+ }
646
+ // A row of the last page whose slot the new one doesn't have.
647
+ if (again && (typeof slot === 'string' ? !doc.querySelector?.(slot) : !slot?.isConnected)) return;
648
+ by(entry).placeRow(slot, { ...options, contextItemId: id || undefined });
649
+ return;
650
+ }
651
+ if (id) by(entry).track(id, entry.level, entry.options);
652
+ if (entry.level !== LEVEL_NAMES.view) onPage.delete(entry);
653
+ };
654
+ const repeat = (entry) => {
655
+ const row = Object.hasOwn(entry, 'slot');
656
+ // Any other level is an act of its own each time (a second cart).
657
+ if (!row && entry.level !== LEVEL_NAMES.view) return false;
658
+ for (const each of onPage) {
659
+ if (row ? each.slot !== entry.slot || !Object.hasOwn(each, 'slot') : each.level !== entry.level) continue;
660
+ // The latest call's options and client are the ones the next product gets.
661
+ each.options = entry.options;
662
+ each.by = entry.by;
663
+ if (!row || pageId === null) return true;
664
+ // A row asked again is drawn again, as one with an id is; right after
665
+ // a move, once the new page's product is read, not under the last one.
666
+ if (pageAt === here()) apply(each, pageId, false);
667
+ else each.waiting = true;
668
+ return true;
669
+ }
670
+ return false;
671
+ };
672
+ const followHere = (entry) => {
673
+ // A row's element that left the page (a single-page site's last route).
674
+ for (const each of onPage) if (Object.hasOwn(each, 'slot') && typeof each.slot !== 'string' && !each.slot?.isConnected) onPage.delete(each);
675
+ if (repeat(entry)) return;
676
+ onPage.add(entry);
677
+ if (unfollow) {
678
+ // Right after a move, once the new page's product is read.
679
+ if (pageAt === here()) apply(entry, pageId, false);
680
+ else if (pageId !== null) entry.waiting = true;
681
+ return;
682
+ }
683
+ unfollow = followProduct((id) => {
684
+ const again = pageId !== null;
685
+ pageId = id;
686
+ pageAt = here();
687
+ for (const each of [...onPage]) apply(each, id, again);
688
+ }, () => {
689
+ pageAt = here();
690
+ for (const each of [...onPage]) if (each.waiting) apply(each, pageId, true);
691
+ }, (id) => {
692
+ if (id) for (const each of onPage) if (!Object.hasOwn(each, 'slot')) by(each).track(id, each.level, { ...each.options, recommendationId: null });
693
+ });
694
+ };
695
+ // A site-wide tag run again on each page (Wix's "load code on each new
696
+ // page") makes a client per page: the first one's follower takes the
697
+ // others' calls as repeats, so a move sends one view and draws one row.
698
+ // A call still goes out through the client that made it (the latest
699
+ // repeat's), so under its own consent: the tag is printed without it and
700
+ // a banner gives it to each copy after the copy's first calls. Settings
701
+ // that send elsewhere or otherwise (project, platform) keep a follower of
702
+ // their own. Under the key, the first follower, as older copies call it;
703
+ // its `peers` the others.
704
+ let following = null;
705
+ const self = { track: (...args) => client.track(...args), placeRow, live: () => !destroyed };
706
+ // An older copy's entry names no client; a destroyed one sends nothing.
707
+ const by = (entry) => (entry.by?.live() ? entry.by : self);
708
+ const sendsAs = () => JSON.stringify([baseUrl, project, options.platform ?? null, quiet, describing]);
709
+ followHere.sendsAs = sendsAs;
710
+ const followPage = (entry) => {
711
+ entry.by = self;
712
+ following = globalThis.document[FOLLOWING] ??= new Map();
713
+ const head = following.get(apiKey);
714
+ // An older copy's follower says nothing of its settings: it takes the call, as it did.
715
+ const twin = [head, ...(head?.peers ?? [])].find((f) => f && (f === followHere || typeof f.sendsAs !== 'function' || f.sendsAs() === sendsAs()));
716
+ if (twin) return twin(entry);
717
+ if (head) (head.peers ??= []).push(followHere);
718
+ else following.set(apiKey, followHere);
719
+ followHere(entry);
720
+ };
721
+ const unfollowPage = () => {
722
+ const head = following?.get(apiKey);
723
+ if (!head) return;
724
+ if (head !== followHere) {
725
+ head.peers = head.peers?.filter((f) => f !== followHere);
726
+ return;
727
+ }
728
+ const [next, ...rest] = head.peers ?? [];
729
+ if (!next) {
730
+ following.delete(apiKey);
731
+ return;
732
+ }
733
+ next.peers = rest;
734
+ following.set(apiKey, next);
735
+ };
736
+
534
737
  const client = {
535
738
  /**
536
739
  * Records an interaction: updates the local history immediately (so the
@@ -547,28 +750,36 @@ export function createClient(options) {
547
750
  * An `itemId` the API would refuse (a page often takes it from a
548
751
  * visitor's URL) drops the event and goes to `onError`, without throwing.
549
752
  * @param {{ recommendationId?: string | null, value?: number,
550
- * currency?: string }} [options] `recommendationId` overrides the
753
+ * currency?: string, send?: boolean }} [options] `recommendationId` overrides the
551
754
  * automatic attribution; `null` (a fallback list's id) is no override.
552
755
  * `value` is what the buyer paid for a purchase's line (0 for a free
553
756
  * line), `currency` its ISO 4217 code (three letters, any case); a
554
757
  * currency needs a value. An invalid pair throws, as a bad level does.
555
758
  * Without a `recommendationId` key, an event above level 0 carries the
556
759
  * id a card's link brought to the page (`#rec_…` or `?rec=`), which it
557
- * takes out of the address.
760
+ * takes out of the address. `send: false` only records it in the
761
+ * visitor's history: your server sends the event itself (an order).
762
+ * Called with a level alone (`track('view')`, options second), the item
763
+ * is the page's product, by its address (page.js `pageProductId`): no
764
+ * product markup, nothing is sent; a view is sent again for each
765
+ * product the visitor moves to without a reload.
558
766
  */
559
767
  track(itemId, level, options = {}) {
768
+ // track('view'): the page's product, which may not be read yet.
769
+ if ((level === undefined || (level !== null && typeof level === 'object')) && (Number.isInteger(itemId) || (typeof itemId === 'string' && Object.hasOwn(LEVEL_NAMES, itemId)))) {
770
+ const named = typeof itemId === 'string' ? LEVEL_NAMES[itemId] : itemId;
771
+ checkLevel(named);
772
+ checkAmount(level?.value, level?.currency);
773
+ if (typeof globalThis.document?.querySelectorAll === 'function') followPage({ level: named, options: level ?? {} });
774
+ return;
775
+ }
560
776
  start();
561
777
  const { value, currency } = options;
562
778
  // A fallback list has a null id, and a page passing it on must not
563
779
  // send `null` or lose the item's earlier, real attribution.
564
780
  let recommendationId = options.recommendationId ?? undefined;
565
781
  if (typeof level === 'string' && Object.hasOwn(LEVEL_NAMES, level)) level = LEVEL_NAMES[level];
566
- if (!Number.isInteger(level) || level < -10 || level > 10) {
567
- throw new RecapiError(
568
- 'invalid_request',
569
- "level must be an integer between -10 and 10, or 'view', 'cart', 'purchase' or 'reject'"
570
- );
571
- }
782
+ checkLevel(level);
572
783
  checkAmount(value, currency);
573
784
  // A page often takes this id from a visitor's URL, so a crafted link
574
785
  // must not fail it. Nothing is kept: in the history it would make the
@@ -576,10 +787,18 @@ export function createClient(options) {
576
787
  if (!isId(itemId)) {
577
788
  // An empty id is most often the quick start's tag pasted before its
578
789
  // ITEM_ID was set: the line says which constant to fill in.
579
- const rule = itemId === '' ? "itemId is empty, nothing sent: set ITEM_ID in recapi's tag to this page's product id" : idRule('itemId');
790
+ const rule = itemId === '' ? "itemId is empty, nothing sent: fill in ITEM_ID in recapi's tag, or remove it and call recapi.track('view') to take the page's product" : idRule('itemId');
580
791
  report(new RecapiError('invalid_request', rule), true);
581
792
  return;
582
793
  }
794
+ if (options.send === false) {
795
+ // Nothing goes out, so the list in the address stays for an event that does.
796
+ if (quiet) return;
797
+ mutate(() => {
798
+ history = applyEvent(history, { item: itemId, level, t: now() }, config);
799
+ });
800
+ return;
801
+ }
583
802
  // The landing view: without consent nothing on the device remembers
584
803
  // the list the visitor clicked, so the card's link carried its id. A
585
804
  // page that passes the key reads the address itself (the shop rows).
@@ -606,6 +825,7 @@ export function createClient(options) {
606
825
  timestamp: new Date(t).toISOString(),
607
826
  event_id: uuid()
608
827
  }));
828
+ if (level === LEVEL_NAMES.view && describing) describePage(itemId);
609
829
  },
610
830
 
611
831
  /**
@@ -736,6 +956,8 @@ export function createClient(options) {
736
956
  consent = Boolean(value);
737
957
  if (!consent) {
738
958
  store.remove();
959
+ // What the pages sent is remembered as the history is.
960
+ storage().removeItem(pagesKey);
739
961
  anonId = null;
740
962
  return;
741
963
  }
@@ -787,6 +1009,14 @@ export function createClient(options) {
787
1009
  */
788
1010
  destroy() {
789
1011
  destroyed = true;
1012
+ unfollow?.();
1013
+ // The rows this client placed go with it, and their listeners.
1014
+ for (const each of onPage) {
1015
+ each.placed?.unfit();
1016
+ each.placed?.el.remove();
1017
+ each.placed = null;
1018
+ }
1019
+ unfollowPage();
790
1020
  if (timer) clearTimeout(timer);
791
1021
  timer = null;
792
1022
  globalThis.document?.removeEventListener?.('visibilitychange', onVisibility);
@@ -801,27 +1031,214 @@ export function createClient(options) {
801
1031
  * link carries its list's id. Rows asked for together share one call. The
802
1032
  * row hides when no card can be drawn; under the `bought_together`
803
1033
  * placement, `heading` shows only over a product bought with this one.
804
- * Does nothing outside a browser.
1034
+ * Without a `contextItemId` key, the context is the page's product, as
1035
+ * `track('view')` reads it, and the row is drawn again when the visitor
1036
+ * moves to another without a reload; `''` is no context. Then a `#id`
1037
+ * slot missing from a product page is added under the product (end of
1038
+ * `<main>`, else before the footer, else end of `<body>`) with the side
1039
+ * margins of the page's content, unless `place: false`; on another page
1040
+ * it is left out silently. Does nothing outside a browser.
805
1041
  *
806
1042
  * @param {Element | string} slot
807
- * @param {{ placement?: string, contextItemId?: string, heading?: string }} [options]
1043
+ * @param {{ placement?: string, contextItemId?: string, heading?: string, place?: boolean }} [options]
808
1044
  */
809
1045
  row(slot, options) {
810
1046
  if (typeof globalThis.document === 'undefined') return;
811
- // Rows called in one task still reach the drawer in one task, in order.
812
- drawRow ??= import('./row.js').then(({ rows }) => rows(client));
813
- drawRow.then((draw) => draw(slot, options), (error) => globalThis.console?.warn('recapi: the row failed to load:', error));
1047
+ if (options?.contextItemId === undefined && typeof globalThis.document.querySelectorAll === 'function') followPage({ slot, options: options ?? {} });
1048
+ else placeRow(slot, options);
814
1049
  }
815
1050
  };
816
1051
  return client;
817
1052
  }
818
1053
 
1054
+ // The shape of an id the API makes; page.js owns it, cards.js and shops.js read it here.
1055
+ export { REC_ID };
1056
+
1057
+ /**
1058
+ * Adds a row's element under the page's product, above its footer: at the
1059
+ * end of Wix Stores' product section, else of `<main>`, else before the
1060
+ * first footer with a size, else at the end of `<body>`. A
1061
+ * spot is kept only if, given a pixel of height, the footer doesn't cover
1062
+ * it and it starts below the product's name: a site builder's fixed grid
1063
+ * (Wix) lays a block added to `<main>` under its footer, and one before the
1064
+ * footer above the product; only its product section's own row grows with
1065
+ * what it holds (docs/customer-walks.md, "Wix's row above the footer").
1066
+ * Returns the element and, at Wix's spot, what finds that spot again
1067
+ * (keepSlot moves the row there once Wix's render is done with it).
1068
+ */
1069
+ function placeSlot(doc, id) {
1070
+ const el = doc.createElement('div');
1071
+ el.id = id;
1072
+ const main = doc.querySelector('main');
1073
+ // Not an empty one in an article or a hidden form (PrestaShop, Lightspeed).
1074
+ const foot = [...doc.querySelectorAll('footer,[role=contentinfo]')].find((f) => f.getBoundingClientRect().height);
1075
+ const wix = wixSection(doc);
1076
+ // A Wix page may hold a dozen h1s, the first one not the product's.
1077
+ const name = ((wix && doc.querySelector('[data-hook="product-title"]')) || doc.querySelector('h1'))?.getBoundingClientRect();
1078
+ for (const [put, spot] of [[wix && (() => wix.append(el)), () => wixSection(doc)], [main && (() => main.append(el))], [foot && (() => foot.before(el))]]) {
1079
+ if (!put) continue;
1080
+ put();
1081
+ el.style.setProperty('height', '1px');
1082
+ const box = el.getBoundingClientRect();
1083
+ const below = foot?.getBoundingClientRect();
1084
+ el.style.removeProperty('height');
1085
+ // A hidden heading has no box to compare with.
1086
+ if (!((!below || box.bottom <= below.top) && (!name?.height || box.top >= name.bottom))) continue;
1087
+ // Until React has hydrated Wix's section, a block of ours in it is a
1088
+ // mismatch: React drew the section again, and the product with it, and
1089
+ // on some loads lost the product. The row waits at the page's end.
1090
+ if (spot && !hydrated(wix)) doc.body.append(el);
1091
+ return { el, spot };
1092
+ }
1093
+ doc.body.append(el);
1094
+ return { el };
1095
+ }
1096
+
1097
+ /** The page section holding Wix Stores' product widget, or null. */
1098
+ function wixSection(doc) {
1099
+ return doc.querySelector('[data-hook="product-page"]')?.closest?.('section[id^="comp-"]') ?? null;
1100
+ }
1101
+
1102
+ /** Whether React has hydrated an element: it marks each one it owns (React 17 and later). */
1103
+ function hydrated(el) {
1104
+ return Object.keys(el).some((key) => key.startsWith('__reactFiber$'));
1105
+ }
1106
+
1107
+ /**
1108
+ * Bounds of keepSlot. On the sample's Wix pages React hydrated the product
1109
+ * section 2 to 22 s after the page opened, while it was on screen: the row
1110
+ * waits up to `ms` for it, then stays at the page's end. Moved in before
1111
+ * hydration, the row broke the product's widget on some loads: it never
1112
+ * goes in early.
1113
+ */
1114
+ const KEEP_SLOT = { ms: 60000, every: 250 };
1115
+
1116
+ /**
1117
+ * Moves a row placed at the page's end into Wix's product section (`spot`)
1118
+ * once React has hydrated it, within KEEP_SLOT's bounds; `moved` fits it
1119
+ * again. Then it stops: no live load removed the row once moved in (AP-1162,
1120
+ * 0 of 36), so nothing watches the page after. Returns what stops it; the
1121
+ * follower calls it before it takes the row away itself.
1122
+ */
1123
+ function keepSlot(doc, el, spot, moved) {
1124
+ if (el.parentElement && el.parentElement === spot()) return () => {};
1125
+ const view = doc.defaultView ?? globalThis.window;
1126
+ const Observer = view?.MutationObserver ?? globalThis.MutationObserver;
1127
+ const start = Date.now();
1128
+ let watch = null;
1129
+ const stop = () => {
1130
+ watch?.disconnect();
1131
+ clearInterval(poll);
1132
+ clearTimeout(end);
1133
+ };
1134
+ const settle = () => {
1135
+ // The clock too: a background tab's timers may come late.
1136
+ if (Date.now() - start > KEEP_SLOT.ms) return stop();
1137
+ const at = spot();
1138
+ if (!at || !hydrated(at)) return;
1139
+ stop();
1140
+ at.append(el);
1141
+ moved?.();
1142
+ };
1143
+ // Hydration changes no node: a timer looks for it.
1144
+ const poll = setInterval(settle, KEEP_SLOT.every);
1145
+ // A section being drawn again may not be there yet: its arrival is a mutation too.
1146
+ if (typeof Observer === 'function' && doc.body) {
1147
+ watch = new Observer(settle);
1148
+ watch.observe(doc.body, { childList: true, subtree: true });
1149
+ }
1150
+ const end = setTimeout(stop, KEEP_SLOT.ms);
1151
+ return stop;
1152
+ }
1153
+
819
1154
  /**
820
- * The shape of an id the API makes (internal/ids: rec_ and hex), the only one
821
- * read from an address: any other value is the site's own. Internal, shared
822
- * with row.js; index.js doesn't export it.
1155
+ * Gives a row placed by itself the side margins of the page's own content,
1156
+ * again when the page's width changes: on site builders (Squarespace,
1157
+ * Gambio, PrestaShop) `<main>` spans the screen and an inner block carries
1158
+ * the margin, so a row at its width touched the screen's edges. The content
1159
+ * is the narrowest block around the page's visible heading (or the
1160
+ * visible element with a hidden heading's words), short of the
1161
+ * row's own container, whose inner box is centred in the row's (within a
1162
+ * tenth of its width, unless as wide as Wix's product widget) and leaves
1163
+ * it more than half: a block in one column
1164
+ * of two (the product's text beside its pictures) is not the page's
1165
+ * content, nor is a heading's own padding. None: the container's width.
1166
+ * Set through CSSOM: a strict CSP refuses style attributes, not this.
1167
+ * Returns what stops it, whose `fit` fits it again.
823
1168
  */
824
- export const REC_ID = /^rec_[0-9a-f]+$/;
1169
+ function fitSlot(doc, el) {
1170
+ const view = doc.defaultView ?? globalThis.window;
1171
+ const style = (e) => view?.getComputedStyle?.(e);
1172
+ const shows = (e) => e?.isConnected && e.getBoundingClientRect().width > 0;
1173
+ const words = (e) => e.textContent.replace(/\s+/g, ' ').trim();
1174
+ let twin = null;
1175
+ // The page's visible heading; hidden (Gambio's on a phone), the visible element with its words.
1176
+ const heading = () => {
1177
+ // Wix's product name; its page's first h1 may be another's.
1178
+ const own = doc.querySelector('[data-hook="product-title"]');
1179
+ if (shows(own)) return own;
1180
+ const all = [...doc.querySelectorAll('h1')];
1181
+ const shown = all.find(shows);
1182
+ if (shown || !all.length || typeof doc.createTreeWalker !== 'function') return shown;
1183
+ const text = words(all[0]);
1184
+ if (!text) return null;
1185
+ if (shows(twin) && words(twin) === text) return twin;
1186
+ const walk = doc.createTreeWalker(doc.body, 4);
1187
+ for (let at = walk.nextNode(); at; at = walk.nextNode()) {
1188
+ if (at.data.trim() && text.startsWith(at.data.replace(/\s+/g, ' ').trim()) && shows(at.parentElement) && words(at.parentElement) === text) return (twin = at.parentElement);
1189
+ }
1190
+ return null;
1191
+ };
1192
+ const fit = () => {
1193
+ const name = heading();
1194
+ const mine = style(el);
1195
+ if (!el.isConnected || !name || !mine) return;
1196
+ const at = el.getBoundingClientRect();
1197
+ // The row's box as its container gives it, before the margins of the last fit.
1198
+ const left = at.left - (parseFloat(mine.marginLeft) || 0);
1199
+ const right = at.right + (parseFloat(mine.marginRight) || 0);
1200
+ const width = right - left;
1201
+ // Wix may lay its whole product off-centre in the section (one shop's phone
1202
+ // page: 20 px left, 60 right): a block as wide as the product's widget is
1203
+ // the product, not one of its columns, so its own margins count.
1204
+ const whole = doc.querySelector('[data-hook="product-page"]')?.getBoundingClientRect().width;
1205
+ let side = [0, 0];
1206
+ for (let up = name; up && !up.contains(el); up = up.parentElement) {
1207
+ const r = up.getBoundingClientRect();
1208
+ const s = style(up);
1209
+ if (!r.width || !s) continue;
1210
+ const pair = [r.left + (parseFloat(s.borderLeftWidth) || 0) + (parseFloat(s.paddingLeft) || 0) - left, right - r.right + (parseFloat(s.borderRightWidth) || 0) + (parseFloat(s.paddingRight) || 0)];
1211
+ if (pair.some((m) => m < 0) || pair[0] + pair[1] >= width / 2 || (Math.abs(pair[0] - pair[1]) > width / 10 && !(r.width >= whole))) continue;
1212
+ if (pair[0] + pair[1] > side[0] + side[1]) side = pair;
1213
+ }
1214
+ ['margin-left', 'margin-right'].forEach((key, k) => {
1215
+ if (side[k] >= 1) el.style.setProperty(key, `${Math.round(side[k])}px`);
1216
+ else el.style.removeProperty(key);
1217
+ });
1218
+ };
1219
+ fit();
1220
+ let frame = 0;
1221
+ const again = () => {
1222
+ if (frame) return;
1223
+ frame = (view?.requestAnimationFrame ?? setTimeout)(() => {
1224
+ frame = 0;
1225
+ fit();
1226
+ });
1227
+ };
1228
+ view?.addEventListener?.('resize', again);
1229
+ // A scroll bar that comes with the cards narrows the page without a resize.
1230
+ const seen = typeof view?.ResizeObserver === 'function' ? new view.ResizeObserver(again) : null;
1231
+ seen?.observe(doc.documentElement);
1232
+ const stop = () => {
1233
+ view?.removeEventListener?.('resize', again);
1234
+ seen?.disconnect();
1235
+ if (frame) (view?.cancelAnimationFrame ?? clearTimeout)(frame);
1236
+ frame = 0;
1237
+ };
1238
+ // A row moved to another spot (keepSlot) fits that one.
1239
+ stop.fit = again;
1240
+ return stop;
1241
+ }
825
1242
 
826
1243
  /**
827
1244
  * The recommendation id a card's link brought to this page, taken out of the
@@ -867,6 +1284,15 @@ function toItem({ item_id: itemId, score, why, metadata }, slot) {
867
1284
  return item;
868
1285
  }
869
1286
 
1287
+ function checkLevel(level) {
1288
+ if (!Number.isInteger(level) || level < -10 || level > 10) {
1289
+ throw new RecapiError(
1290
+ 'invalid_request',
1291
+ "level must be an integer between -10 and 10, or 'view', 'cart', 'purchase' or 'reject'"
1292
+ );
1293
+ }
1294
+ }
1295
+
870
1296
  /** The API's rule for ids, for messages that never quote the id: a visitor may have written it. */
871
1297
  function idRule(name) {
872
1298
  return `${name} must be 1-256 bytes of UTF-8 without control characters`;
package/src/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * @module @recapi/client
5
5
  */
6
6
 
7
- export { createClient } from './client.js';
7
+ export { createClient, RECENTLY_VIEWED, BOUGHT_TOGETHER } from './client.js';
8
8
  export { RecapiError } from './transport.js';
9
9
  export { memoryStorage, localStorageAdapter } from './storage.js';
10
10
  export {
@@ -18,3 +18,5 @@ export {
18
18
  fromSnapshot,
19
19
  merge
20
20
  } from './history.js';
21
+ // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
22
+ import './page.js';