@recapi/client 0.12.0 → 0.14.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/README.md CHANGED
@@ -35,7 +35,7 @@ are, gzipped, and browsers cache them:
35
35
 
36
36
  ```html
37
37
  <script type="module">
38
- import { createClient } from 'https://api.example.com/sdk/0.12.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.14.0/index.js';
39
39
 
40
40
  const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
41
41
  // From your cookie banner, once the visitor agrees: recapi.setConsent(true).
@@ -543,6 +543,32 @@ pages it fills recapi's row, drawing each card from the item's `metadata`
543
543
  or, without it, from the store; the row is printed with the store's own
544
544
  products, which stay while recapi has none.
545
545
 
546
+ #### The served storefront code
547
+
548
+ From module 0.4.25 (library 0.13.0) the module's template holds only what
549
+ Magento knows about the page and the store's key: it imports
550
+ `/sdk/<version>/magento.js` from your API and makes one call, on Luma and on
551
+ Hyvä alike. The API serves that file beside `index.js`, with the same day of
552
+ cache, and an older version's address redirects to it. So a fix of the row,
553
+ consent or the events reaches every store within a day, with nothing to
554
+ install again. A fix of the module's PHP (catalog sync, orders) still needs
555
+ `composer update` or the new zip. The module's Content Security Policy
556
+ already allows the API's host, which serves both files.
557
+
558
+ The call and its options are a contract from 0.13.0 on: options may be added,
559
+ never renamed or dropped, as stores keep the module they installed.
560
+
561
+ | Call | Options |
562
+ |---|---|
563
+ | `magentoPage(page)` | `page`, as the module's block prints it: `api` (your API's address), `key` (the public key), `platform` (`magento/<module version>`), `product` (the product page's id, `null` elsewhere), `placement` (`product`, `cart` or `block`), `cookieRestriction` (`true` when Cookie Restriction Mode is on), `website` (the website's id, the key of the cookie notice's answer), `cards` (the store's card lookup for products without metadata), `currency` (the store's base currency, `null` while the visitor browses in another), `sdk` (the address it was imported from). Resolves once the page's work is set up. |
564
+
565
+ The storefront code of every module version is kept in
566
+ `test/fixtures/magento/<version>/` (`Block/Script.php` and the template;
567
+ 0.4.24: the last one holding its own page code), and
568
+ `test/magento_published.test.js` runs every case of `test/magento.test.js`
569
+ through each against the current `src/`: a change to that code needs a new
570
+ fixture, and a change to the served code must keep every older module working.
571
+
546
572
  ### Node
547
573
 
548
574
  ```js
@@ -1076,6 +1102,14 @@ minifier, to keep zero dev dependencies.
1076
1102
 
1077
1103
  ## Changes
1078
1104
 
1105
+ - 2026-11-21: version 0.14.0. Shopify: a row in a full-width section
1106
+ (Dawn's Custom Liquid) keeps to the theme's page width, four cards across
1107
+ (two on a phone); the theme editor's preview shows the row and sends or
1108
+ stores nothing. Pieces already pasted get both with nothing to paste again.
1109
+ - 2026-11-20: version 0.13.0. `magento.js`, served beside `index.js` with
1110
+ its day of cache: the Magento module's storefront code (the rows, consent,
1111
+ the view and the add-to-cart events). The module now prints only the page's
1112
+ values, so later fixes reach a store with nothing to install again.
1079
1113
  - 2026-11-20: version 0.12.0. `woocommerce.js`, served beside `index.js`
1080
1114
  with its day of cache: the WooCommerce plugin's page code (the rows,
1081
1115
  consent, cart and purchase events). The plugin now prints only the page's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Browser and Node client for the recapi recommendation API: local decayed history, event batching, attribution.",
5
5
  "homepage": "https://recapi.io/docs",
6
6
  "bugs": {
package/src/magento.js ADDED
@@ -0,0 +1,262 @@
1
+ /**
2
+ * What a Magento store's pages run: the visitor's consent (Cookie Restriction
3
+ * Mode), the add-to-cart events, the product view and the rows in
4
+ * `#recapi-recommendations` and `#recapi-bought-together`. The module's
5
+ * template (sdk/php/magento/view/frontend/templates/script.phtml) prints only
6
+ * what Magento knows about the page and imports this file from the API, on
7
+ * Luma and on Hyvä alike, so a fix here reaches every store within a day (the
8
+ * entry's cache), with nothing to install again. Its options are a contract:
9
+ * add, never rename or drop one (each published module's storefront code is a
10
+ * test fixture, test/fixtures/magento/).
11
+ *
12
+ * A file of its own rather than exports of index.js, which every other site
13
+ * loads: they would download a Magento row they never draw.
14
+ *
15
+ * @module @recapi/client/magento
16
+ */
17
+
18
+ import { createClient } from './index.js';
19
+
20
+ /**
21
+ * Runs a page of the store. Resolves once the page's work is set up (the row
22
+ * loads later, as the shopper scrolls near it, or at once without
23
+ * IntersectionObserver).
24
+ *
25
+ * @param {{ api: string, key: string, platform: string, product: string|null,
26
+ * placement: string, cookieRestriction: boolean, website: string,
27
+ * cards: string, currency: string|null }} page
28
+ */
29
+ export async function magentoPage(page) {
30
+ // The server sends the orders and can't read the browser's storage: each
31
+ // time the library saves the visitor's state, the "recapi" cookie gets what
32
+ // a purchase needs, the visitor's id and the recommendation each clicked
33
+ // product came from (the saved list entries that have a click time). The
34
+ // library saves only with consent. A day, as long as the library credits a
35
+ // click.
36
+ const secure = location.protocol === 'https:' ? '; secure' : '';
37
+ const cookie = (value, maxAge) => {
38
+ document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
39
+ };
40
+ const mirror = (saved) => {
41
+ let state;
42
+ try {
43
+ state = JSON.parse(saved);
44
+ } catch {
45
+ return;
46
+ }
47
+ if (typeof state?.anonId !== 'string') return;
48
+ const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
49
+ // A browser drops a cookie over 4 KB: the products shown last stay.
50
+ let value;
51
+ do {
52
+ value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
53
+ } while (value.length > 3000 && clicked.shift());
54
+ cookie(value, 86400);
55
+ };
56
+ const storage = {
57
+ getItem: (key) => localStorage.getItem(key),
58
+ setItem: (key, value) => {
59
+ localStorage.setItem(key, value);
60
+ mirror(value);
61
+ },
62
+ removeItem: (key) => localStorage.removeItem(key)
63
+ };
64
+
65
+ // Magento's Cookie Restriction Mode is the store's consent switch: on, the
66
+ // visitor's device keeps nothing until they accept the cookie notice, which
67
+ // writes {"<website id>": 1} into user_allowed_save_cookie. Without consent
68
+ // events still go out, without a visitor id.
69
+ const allowed = () => {
70
+ if (!page.cookieRestriction) return true;
71
+ const raw = /(?:^|;\s*)user_allowed_save_cookie=([^;]*)/.exec(document.cookie)?.[1];
72
+ try {
73
+ return JSON.parse(decodeURIComponent(raw))[page.website] === 1;
74
+ } catch {
75
+ return false;
76
+ }
77
+ };
78
+ const consent = allowed();
79
+ const recapi = createClient({ apiKey: page.key, baseUrl: page.api, consent, storage, platform: page.platform });
80
+ // A visitor who took their consent back (deleted the notice's cookie) leaves
81
+ // no ids for their next order.
82
+ if (!consent && /(?:^|;\s*)recapi=/.test(document.cookie)) cookie('', 0);
83
+
84
+ // Luma and its children announce through jQuery, which RequireJS loads:
85
+ // the cookie notice's accept and the Ajax add to cart, with its products.
86
+ const jquery = (use) => {
87
+ if (typeof window.require === 'function') window.require(['jquery'], use);
88
+ else if (window.jQuery) use(window.jQuery);
89
+ };
90
+ jquery(($) => {
91
+ $(document).on('user:allowed:save:cookie', () => recapi.setConsent(allowed()));
92
+ $(document).on('ajax:addToCart', (event, data) => {
93
+ for (const id of data?.productIds ?? []) if (id) recapi.track(String(id), 'cart');
94
+ });
95
+ });
96
+ // Hyvä's cookie notice announces the accept on the window instead: the
97
+ // consent applies on the same page there too, not only from the next one.
98
+ window.addEventListener('user-allowed-save-cookie', () => recapi.setConsent(allowed()));
99
+ // Themes without jQuery (Hyvä) post the add-to-cart form, and the next page
100
+ // loads: counted at the submit, once no script stopped it for an Ajax call.
101
+ // Window listeners run last, so defaultPrevented is final here.
102
+ window.addEventListener('submit', (event) => {
103
+ const form = event.target;
104
+ if (event.defaultPrevented || !/\/checkout\/cart\/add\b/.test(form?.action ?? '')) return;
105
+ const id = form.querySelector?.('[name="product"]')?.value;
106
+ if (id) recapi.track(String(id), 'cart');
107
+ });
108
+
109
+ // The product id is the item id. A card's link carries its recommendation:
110
+ // without consent nothing on the device remembers which list showed it. In the
111
+ // fragment, which no server or page cache sees: an unknown ?rec= gave every
112
+ // click from the row its own entry in the full-page cache. ?rec= is still read:
113
+ // links already out there, and the cards that can't use a fragment (below).
114
+ const inFragment = /^#rec_[0-9a-f]+$/;
115
+ const viewed = () => {
116
+ const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
117
+ const linked = fragment ?? new URLSearchParams(location.search).get('rec');
118
+ recapi.track(page.product, 'view', { recommendationId: linked });
119
+ // recapi credits an explicit id to whoever brings it: drop it from the
120
+ // address so a copied or shared link doesn't credit strangers' visits.
121
+ if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
122
+ else if (linked !== null) {
123
+ const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
124
+ history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
125
+ }
126
+ };
127
+ // A browser may preload the link under the pointer, and a page it prerenders
128
+ // runs this script though nobody may ever open it: a click nobody made must
129
+ // not be credited.
130
+ if (page.product && document.prerendering) document.addEventListener('prerenderingchange', viewed);
131
+ else if (page.product) viewed();
132
+
133
+ // recapi's row (the product page's recommendations block) arrives printed
134
+ // with the store's own products in it: recapi's cards replace them when it
135
+ // has some to show, else they stay. A product page has a second row under it,
136
+ // "Often bought together" (unless the store turned it off), printed hidden
137
+ // and empty: it shows only once recapi has products for it.
138
+ const slot = document.getElementById('recapi-recommendations');
139
+ const together = page.product ? document.getElementById('recapi-bought-together') : null;
140
+ const rows = [
141
+ { slot, placement: page.placement },
142
+ ...(slot && together ? [{ slot: together, placement: 'bought_together', together: true }] : [])
143
+ ];
144
+ const blockOf = (element) => element.closest?.('.recapi-recommendations') ?? element;
145
+ const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
146
+ // Only http(s) addresses: metadata is the shop's, but a javascript: link
147
+ // must never reach the page.
148
+ const web = (address) => {
149
+ try {
150
+ const url = new URL(address, location.href);
151
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
152
+ } catch {
153
+ return null;
154
+ }
155
+ };
156
+ const lang = document.documentElement?.lang || undefined;
157
+ const money = (amount) => {
158
+ if (typeof amount === 'string') return amount;
159
+ if (typeof amount !== 'number' || !Number.isFinite(amount) || !page.currency) return null;
160
+ try {
161
+ return new Intl.NumberFormat(lang, { style: 'currency', currency: page.currency }).format(amount);
162
+ } catch {
163
+ return null;
164
+ }
165
+ };
166
+ // An item's metadata draws its card when it has a name and a link (and a
167
+ // price the visitor's currency can show); the others come from the store.
168
+ const fromMetadata = (metadata) => {
169
+ if (typeof metadata?.name !== 'string' || typeof metadata.url !== 'string' || !web(metadata.url)) return null;
170
+ const price = metadata.price === undefined || metadata.price === null ? '' : money(metadata.price);
171
+ if (price === null) return null;
172
+ return { name: metadata.name, url: metadata.url, picture: typeof metadata.picture === 'string' ? metadata.picture : '', price };
173
+ };
174
+ // A row shows 4 cards. recapi counts every product of a list as shown, so
175
+ // a spare asked for would get an impression and could be credited a view it
176
+ // never caused: each row asks for 4. recapi may not know a product sold out
177
+ // or was disabled since the last sync; one more call, for the rows left
178
+ // short only and without the products already listed, then fills the gaps.
179
+ const ROW = 4;
180
+ // Through the call that takes all of a page's rows: billed as one, the
181
+ // history sent once, and no product on two rows (the first row's go first).
182
+ // Each row its own placement.
183
+ const ask = (wanted, exclude) => recapi.recommendLists({
184
+ lists: wanted.map(({ count, placement }) => ({ count, placement, ...(page.product ? { contextItemId: page.product } : {}) })),
185
+ ...(exclude.length ? { exclude } : {})
186
+ });
187
+ // A list's cards, in recapi's order, each with the list's id: those whose
188
+ // metadata draws them, the others from the store in one request.
189
+ const cardsOf = async ({ recommendationId, items }) => {
190
+ const cards = new Map(items.map(({ itemId, metadata }) => [itemId, fromMetadata(metadata)]));
191
+ const missing = [...cards].filter(([id, card]) => !card && /^\d+$/.test(id)).map(([id]) => id);
192
+ if (missing.length) {
193
+ const url = new URL(page.cards, location.href);
194
+ url.searchParams.set('ids', missing.join(','));
195
+ const response = await fetch(url.href, { headers: { Accept: 'application/json' } }).catch(() => null);
196
+ const found = (response?.ok ? await response.json().catch(() => null) : null)?.cards;
197
+ for (const card of Array.isArray(found) ? found : []) if (cards.has(String(card?.id))) cards.set(String(card.id), card);
198
+ }
199
+ return [...cards.values()].filter((card) => card && web(card.url)).map((card) => ({ ...card, recommendationId }));
200
+ };
201
+ const html = (cards) => cards.slice(0, ROW).map(({ recommendationId, ...card }) => {
202
+ const link = web(card.url);
203
+ // ?rec= only where a fragment can't carry the id: the address has its own
204
+ // (a theme's, not ours to overwrite), it's the page already open (a
205
+ // fragment wouldn't load it, so no view), or the page wouldn't read it back.
206
+ const open = link.href.split('#')[0] === location.href.split('#')[0];
207
+ if (recommendationId && (link.hash || open || !inFragment.test(`#${recommendationId}`))) link.searchParams.set('rec', recommendationId);
208
+ else if (recommendationId) link.hash = recommendationId;
209
+ const picture = web(card.picture);
210
+ return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
211
+ `<span>${escape(card.name)}</span>${card.price ? `<span class="recapi-price">${escape(card.price)}</span>` : ''}</a>`;
212
+ });
213
+ // Each row's cards, drawn as far as recapi got: a row never waits on, nor
214
+ // loses its cards to, the other row or a later call.
215
+ const draw = async () => {
216
+ const lists = await ask(rows.map(({ placement }) => ({ count: ROW, placement })), []);
217
+ // Popular items (recapi slow, down or at a limit) are no bought-together row.
218
+ const cards = await Promise.all(lists.map((list, i) => (rows[i].together && list.fallback ? [] : cardsOf(list))));
219
+ // Only a full list that couldn't fill its row: a shorter one means recapi
220
+ // has no more to give, and a fallback would only wait again.
221
+ const short = rows.map((row, i) => i).filter((i) => cards[i].length < ROW && lists[i].items.length >= ROW && !lists[i].fallback);
222
+ if (short.length) {
223
+ try {
224
+ const more = await ask(short.map((i) => ({ count: ROW - cards[i].length, placement: rows[i].placement })),
225
+ lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)));
226
+ const extra = await Promise.all(more.map(cardsOf));
227
+ short.forEach((i, k) => cards[i].push(...extra[k]));
228
+ } catch (error) {
229
+ // Rejected (a key revoked mid-page): the cards of the first call stay.
230
+ console.warn('recapi:', error);
231
+ }
232
+ }
233
+ rows.forEach((row, i) => {
234
+ const drawn = html(cards[i]);
235
+ if (drawn.length) {
236
+ row.slot.innerHTML = drawn.join('');
237
+ blockOf(row.slot).hidden = false;
238
+ }
239
+ });
240
+ };
241
+ // A row with no card at all (no store product either) hides, title included.
242
+ // A rejected request (a revoked key: recapi's own error) keeps the store's.
243
+ const fill = async () => {
244
+ await draw().catch(() => 0);
245
+ for (const row of rows) if (!row.slot.children.length) blockOf(row.slot).hidden = true;
246
+ };
247
+ // Only once the row comes within 400px of the screen, as Magento's lazy
248
+ // images load: each list is billed and counted as shown, and a shopper who
249
+ // never scrolls down saw none. The view above went at once. The block is
250
+ // watched, not the cards' div: with no store product that div is empty, and
251
+ // a theme hiding every empty div (div:empty { display: none }, Dawn's rule)
252
+ // would leave nothing to come near the screen; the block has its title.
253
+ if (slot && typeof IntersectionObserver !== 'function') await fill();
254
+ else if (slot) {
255
+ const observer = new IntersectionObserver((entries) => {
256
+ if (!entries.some((entry) => entry.isIntersecting)) return undefined;
257
+ observer.disconnect();
258
+ return fill();
259
+ }, { rootMargin: '0px 0px 400px 0px' });
260
+ observer.observe(blockOf(slot));
261
+ }
262
+ }
package/src/shopify.js CHANGED
@@ -40,7 +40,11 @@ export async function shopifyTheme(options) {
40
40
  window.Shopify.loadFeatures([{ name: 'consent-tracking-api', version: '0.2' }],
41
41
  (error) => done(error ? null : window.Shopify.customerPrivacy));
42
42
  });
43
- const consent = privacy?.analyticsProcessingAllowed?.() === true;
43
+ // The theme editor's preview is the shop's own staff placing the row: it
44
+ // shows, but nothing is stored or sent about them (no view, cart or click).
45
+ // Its lists still count as shown: the API has no way to ask without counting.
46
+ const editor = window.Shopify?.designMode === true;
47
+ const consent = !editor && privacy?.analyticsProcessingAllowed?.() === true;
44
48
 
45
49
  // Shopify doesn't promise that the checkout's pixel can read this page's
46
50
  // storage, so the cart, which Shopify carries into the checkout, holds the
@@ -82,7 +86,7 @@ export async function shopifyTheme(options) {
82
86
  // is: withdrawing consent forgets it too.
83
87
  const DESCRIBED = 'recapi:described';
84
88
  document.addEventListener('visitorConsentCollected', (event) => {
85
- recapi.setConsent(event.detail?.analyticsAllowed === true);
89
+ recapi.setConsent(!editor && event.detail?.analyticsAllowed === true);
86
90
  if (recapi.getAnonId() === null) local.removeItem(DESCRIBED);
87
91
  });
88
92
 
@@ -164,7 +168,7 @@ export async function shopifyTheme(options) {
164
168
  // The page's number tells recapi which page this is: an empty one ends the list.
165
169
  await seen(JSON.stringify({ page, products }), false).catch(() => null);
166
170
  };
167
- if (product) describe();
171
+ if (product && !editor) describe();
168
172
  // A card's link carries its recommendation: without consent nothing on the
169
173
  // device remembers which list showed the product. In the fragment, which no
170
174
  // server or crawler sees: each list's new ?rec= looks like another page.
@@ -187,20 +191,31 @@ export async function shopifyTheme(options) {
187
191
  // A browser may preload the link under the pointer, and a page it prerenders
188
192
  // runs this script though nobody may ever open it: a click nobody made must
189
193
  // not be credited.
190
- if (handle && document.prerendering) document.addEventListener('prerenderingchange', viewed);
191
- else if (handle) viewed();
194
+ if (handle && !editor && document.prerendering) document.addEventListener('prerenderingchange', viewed);
195
+ else if (handle && !editor) viewed();
192
196
 
193
197
  // Fills <div id="recapi-recommendations">&nbsp;</div> wherever the theme has one.
194
198
  const slot = document.getElementById('recapi-recommendations');
195
199
  // A product row in the theme's colours and fonts. :where() weighs
196
- // nothing, so any rule of the theme's restyles the cards.
200
+ // nothing, so any rule of the theme's restyles the cards. Four cards
201
+ // across, as the theme's product grids show them, two where four would be
202
+ // narrower than 150px (a phone). The page-width rule is for themes with
203
+ // no page-width class of their own (below).
197
204
  const styleOf = (id) => '<style>' +
198
- `:where(#${id}){display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:1rem;align-items:start;align-content:start}` +
205
+ `:where(#${id}){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;align-content:start}` +
206
+ ':where(#recapi-recommendations.page-width,.recapi-bought-together.page-width){box-sizing:border-box;max-width:var(--page-width,1200px);margin-inline:auto;padding-inline:1.5rem}' +
199
207
  `:where(#${id} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
200
208
  `:where(#${id} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
201
209
  `:where(#${id} .recapi-price){font-weight:600}` +
202
210
  '</style>';
203
211
  const style = styleOf('recapi-recommendations');
212
+ // Dawn's Custom Liquid section spans the whole screen (no page-width box),
213
+ // so a row there took 15 narrow columns from the left edge: it keeps to
214
+ // the page width through the theme's own page-width class (Dawn's max-width
215
+ // and side margins). Horizon's puts its content in the page's column
216
+ // (section--page-width) unless the shop chose full width.
217
+ const wide = slot && !slot.closest('.page-width, .section--page-width');
218
+ if (wide) slot.classList.add('page-width');
204
219
  // Dawn and the themes built on it hide every empty div (div:empty
205
220
  // { display: none }): a slot pasted empty, as the quick start once
206
221
  // printed it, has no box, never comes near the screen, and the row would
@@ -331,7 +346,7 @@ export async function shopifyTheme(options) {
331
346
  // styles its title.
332
347
  if (second.length && !lists[1].fallback) {
333
348
  const title = together ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
334
- slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${second.join('')}</div></div>`);
349
+ slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${second.join('')}</div></div>`);
335
350
  }
336
351
  };
337
352
  // recommendLists() rejects only on a bad request: a page still loses no more than its rows.