@recapi/client 0.18.0 → 0.18.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/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.18.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.18.1/index.js';
39
39
 
40
40
  const ITEM_ID = ''; // this page's product id
41
41
 
@@ -294,6 +294,13 @@ fixture, and a change to the served code must keep every older piece
294
294
  working. The quick start fills in the current version, your address and your
295
295
  project (`jssdk.Shopify`).
296
296
 
297
+ `shopify.js` keeps what only Shopify gives: the page's data, the product
298
+ lookup for items without metadata, the currency, the consent banner, the
299
+ pasted options. The rules every row shares (lazy ask, link with the list's
300
+ id, hiding, the bought-together title, card styles) come from `cards.js`,
301
+ which [the ready row](#the-ready-row) uses too. Each piece's rows are pinned
302
+ to the byte in `test/fixtures/shopify/<version>/rows.txt`.
303
+
297
304
  Both files name themselves (`platform: 'shopify/<version>'`, sent as
298
305
  `?platform=` on every call), so recapi words its setup hints for Shopify.
299
306
 
@@ -836,7 +843,8 @@ or a selector) with up to 4 cards, the shop rows' rules in one call:
836
843
  `.recapi-price`), and pass a `style-src 'self'` CSP.
837
844
 
838
845
  There are no other options: for another look, draw `recommend()`'s list.
839
- The file (`row.js`) loads on the first call only.
846
+ The file (`row.js`, and `cards.js` it shares with the shop rows) loads on
847
+ the first call only.
840
848
 
841
849
  ### Errors and troubleshooting
842
850
 
@@ -1130,6 +1138,8 @@ minifier, to keep zero dev dependencies.
1130
1138
 
1131
1139
  ## Changes
1132
1140
 
1141
+ - 2026-11-24: version 0.18.1. No visible change: Shopify's row takes the
1142
+ rules it shares with `recapi.row()` from one file, `cards.js`.
1133
1143
  - 2026-11-24: version 0.18.0. `recapi.row(slot, { placement, contextItemId,
1134
1144
  heading })` draws a ready row of product cards from the items' metadata
1135
1145
  ([The ready row](#the-ready-row)). `track()` above level 0 without a
package/index.d.ts CHANGED
@@ -132,6 +132,7 @@ export interface RecommendListsParams {
132
132
  /** An item's reason code: map the ones you want to your own label, show none for an unknown one. */
133
133
  export type ReasonCode =
134
134
  | 'for_you' | 'similar' | 'next' | 'bought_together' | 'trending' | 'popular' | 'new' | 'explore' | 'more'
135
+ | 'viewed_earlier'
135
136
  | (string & {});
136
137
 
137
138
  /** The object stored with the item (`PUT /v1/items`, `metadata`): name, picture, link, price... */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
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/cards.js ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The rules of every recommendation row, recapi.row()'s and the shop
3
+ * platforms': changed here once. Each row keeps its own markup, which shops
4
+ * have styled.
5
+ *
6
+ * @module cards
7
+ */
8
+
9
+ import { REC_ID } from './client.js';
10
+
11
+ /** recapi counts every item of a list as shown: a spare could be credited a view it never caused. */
12
+ export const ROW = 4;
13
+
14
+ // :where() weighs nothing: any rule of the site's restyles the cards. Two
15
+ // across where four would be narrower than 150px (a phone).
16
+ export const GRID = 'display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start';
17
+
18
+ export const cardStyle = (scope) => `:where(${scope} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
19
+ `:where(${scope} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
20
+ `:where(${scope} .recapi-price){font-weight:600}`;
21
+
22
+ export const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
23
+
24
+ /** Only http(s): a `javascript:` link in metadata must never reach the page. */
25
+ export function web(address) {
26
+ if (typeof address !== 'string') return null;
27
+ try {
28
+ const url = new URL(address, location.href);
29
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ export const cardLink = (metadata) => (metadata?.available !== false && typeof metadata?.name === 'string' ? web(metadata.url) : null);
36
+
37
+ /**
38
+ * The list's id in the fragment, which no server or crawler sees, unless the
39
+ * address has its own (not ours to overwrite), it is the page already open (a
40
+ * fragment wouldn't load it, so no view), or the page wouldn't read it back.
41
+ */
42
+ export function carry(url, recommendationId) {
43
+ if (!recommendationId) return url;
44
+ const open = url.href.split('#')[0] === location.href.split('#')[0];
45
+ if (url.hash || open || !REC_ID.test(recommendationId)) url.searchParams.set('rec', recommendationId);
46
+ else url.hash = recommendationId;
47
+ return url;
48
+ }
49
+
50
+ /** The bought-together title only over a real pair: similar products under it would be true cards under a false title. */
51
+ export const paired = (cards) => cards.some(({ why }) => why === 'bought_together');
52
+
53
+ /** Not only [hidden]: any display rule of the site's beats that one. */
54
+ export function hide(el) {
55
+ el.hidden = true;
56
+ el.style.setProperty('display', 'none', 'important');
57
+ }
58
+
59
+ /**
60
+ * `then` once any element comes within 400px of the screen: each list is
61
+ * billed and counted as shown, and a visitor who never scrolls down saw none.
62
+ */
63
+ export function near(elements, then) {
64
+ if (typeof IntersectionObserver !== 'function') return then();
65
+ const observer = new IntersectionObserver((entries) => {
66
+ if (!entries.some((entry) => entry.isIntersecting)) return undefined;
67
+ observer.disconnect();
68
+ return then();
69
+ }, { rootMargin: '0px 0px 400px 0px' });
70
+ for (const el of elements) observer.observe(el);
71
+ return undefined;
72
+ }
package/src/row.js CHANGED
@@ -8,46 +8,11 @@
8
8
  * @module row
9
9
  */
10
10
 
11
- import { REC_ID } from './client.js';
11
+ import { GRID, ROW, cardLink, cardStyle, carry, escape, hide, near, paired, web } from './cards.js';
12
12
 
13
- /** A row shows 4 cards: recapi counts every item of a list as shown. */
14
- const ROW = 4;
15
-
16
- // :where() weighs nothing, so any rule of the site's restyles the cards. Four
17
- // across, two where four would be narrower than 150px (a phone). The height
18
- // is held while the list loads, so the page doesn't jump.
13
+ // The height is held while the list loads, so the page doesn't jump.
19
14
  const CSS = ':where(.recapi-row[aria-busy=true]){min-height:20rem}' +
20
- ':where(.recapi-row ul){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;list-style:none;margin:0;padding:0}' +
21
- ':where(.recapi-row a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
22
- ':where(.recapi-row img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
23
- ':where(.recapi-row .recapi-price){font-weight:600}';
24
-
25
- const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
26
-
27
- /** Only http(s) addresses: a `javascript:` link in metadata must never reach the page. */
28
- function web(address) {
29
- if (typeof address !== 'string') return null;
30
- try {
31
- const url = new URL(address, location.href);
32
- return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
33
- } catch {
34
- return null;
35
- }
36
- }
37
-
38
- /**
39
- * A card's link with its list's id: in the fragment, unless the address has
40
- * its own (the site's, not ours to overwrite), it is the page already open (a
41
- * fragment wouldn't load it, so no view), or the id isn't one `landed()` reads
42
- * from a fragment.
43
- */
44
- function carry(url, recommendationId) {
45
- if (!recommendationId) return url;
46
- const open = url.href.split('#')[0] === location.href.split('#')[0];
47
- if (url.hash || open || !REC_ID.test(recommendationId)) url.searchParams.set('rec', recommendationId);
48
- else url.hash = recommendationId;
49
- return url;
50
- }
15
+ `:where(.recapi-row ul){${GRID};list-style:none;margin:0;padding:0}${cardStyle('.recapi-row')}`;
51
16
 
52
17
  /** The page's currency, as shops print it for search engines. */
53
18
  function pageCurrency() {
@@ -84,15 +49,13 @@ export function rows(client) {
84
49
  }
85
50
  };
86
51
 
87
- const hide = (el) => {
52
+ const away = (el) => {
88
53
  el.removeAttribute('aria-busy');
89
- // Not only [hidden]: any display rule of the site's beats that one.
90
- el.hidden = true;
91
- el.style.setProperty('display', 'none', 'important');
54
+ hide(el);
92
55
  };
93
56
 
94
57
  const card = ({ metadata: m }, recommendationId, money) => {
95
- const link = m && m.available !== false && typeof m.name === 'string' ? web(m.url) : null;
58
+ const link = cardLink(m);
96
59
  if (!link) return null;
97
60
  let price = typeof m.price === 'string' ? m.price : '';
98
61
  if (typeof m.price === 'number') {
@@ -121,11 +84,9 @@ export function rows(client) {
121
84
  const missing = ['name', 'url'].filter((key) => list.items.every(({ metadata }) => typeof metadata?.[key] !== 'string'));
122
85
  console.warn(`recapi: no card to draw: send each item's metadata with ${missing.join(' and ') || 'a name and an http(s) url'} (PUT /v1/items)`);
123
86
  }
124
- return hide(el);
87
+ return away(el);
125
88
  }
126
- // The title only over a real pair: a product nobody bought with another
127
- // yet gets similar ones, true cards under a false title.
128
- const titled = heading && (!together || cards.some(({ why }) => why === 'bought_together'));
89
+ const titled = heading && (!together || paired(cards));
129
90
  el.innerHTML = `${titled ? `<h2 class="recapi-heading">${escape(heading)}</h2>` : ''}<ul role="list">${cards.map(({ html }) => html).join('')}</ul>`;
130
91
  el.removeAttribute('aria-busy');
131
92
  };
@@ -146,23 +107,14 @@ export function rows(client) {
146
107
  }
147
108
  } catch (error) {
148
109
  // recommendLists() rejects only on a bad request: the page loses no more than its rows.
149
- members.forEach(({ el }) => hide(el));
110
+ members.forEach(({ el }) => away(el));
150
111
  console.warn('recapi:', error);
151
112
  }
152
113
  };
153
114
 
154
- const watch = (members) => {
155
- if (typeof IntersectionObserver !== 'function') return fill(members);
156
- // Each list is billed and counted as shown: a visitor who never scrolls
157
- // down saw none.
158
- const observer = new IntersectionObserver((entries) => {
159
- if (!entries.some((entry) => entry.isIntersecting)) return undefined;
160
- observer.disconnect();
161
- return fill(members);
162
- }, { rootMargin: '0px 0px 400px 0px' });
163
- for (const { el } of members) observer.observe(el);
164
- return undefined;
165
- };
115
+ // Each list is billed and counted as shown: a visitor who never scrolls
116
+ // down saw none.
117
+ const watch = (members) => near(members.map(({ el }) => el), () => fill(members));
166
118
 
167
119
  return (slot, { placement, contextItemId, heading } = {}) => {
168
120
  const el = typeof slot === 'string' ? document.querySelector(slot) : slot;
package/src/shopify.js CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { createClient, localStorageAdapter, memoryStorage } from './index.js';
16
+ import { GRID, ROW, cardLink, cardStyle, carry, escape, hide, near, paired, web } from './cards.js';
16
17
 
17
18
  /**
18
19
  * The theme's piece: the visitor's consent, the cart attribute the pixel
@@ -96,14 +97,11 @@ export async function shopifyTheme(options) {
96
97
  const { shopCurrency } = options;
97
98
  if (options.customerId) recapi.identify(String(options.customerId));
98
99
 
99
- // What the shop's admin says the product is: recapi names the product from
100
- // it when the shop sent no catalog (no products export, no webhook), so a
101
- // shop that only pasted this snippet gets similar products by name. Only
102
- // words: recapi never lets them overwrite what the shop sent itself. Sent
103
- // once per product per browser, again when the shop changes them. They say
104
- // nothing about the visitor, so they go with or without consent; what was
105
- // sent is remembered only where recapi may store (else once per page view,
106
- // which recapi writes only when the words changed).
100
+ // What the shop's admin says the product is: recapi names products from it
101
+ // when the shop sent no catalog (no export, no webhook), never over what
102
+ // the shop sent. Nothing about the visitor, so sent with or without
103
+ // consent: once per product per browser where recapi may store, else once
104
+ // per view (recapi writes only words that changed).
107
105
  const product = handle && { handle, title: options.product.title ?? null, type: options.product.type ?? null, tags: options.product.tags ?? null };
108
106
  const describe = () => {
109
107
  const body = JSON.stringify({ products: [product] });
@@ -139,15 +137,12 @@ export async function shopifyTheme(options) {
139
137
  body,
140
138
  keepalive
141
139
  });
142
- // While recapi has no catalog from the shop, it asks, in the answer above,
143
- // for a page of the shop's own product list, which every Shopify storefront
144
- // serves at /products.json to its visitors: a page of 250 products per page
145
- // view, so a shop that only pasted this snippet has its whole catalog named
146
- // after a few product views, its owner's own click-through included. recapi
147
- // keeps the progress, so this needs nothing stored on the device, and hands
148
- // each page to one browser at a time. Only once the browser is idle and the
149
- // row (when it is being drawn) is on the page; a refused or failed read
150
- // waits for the next page view, which gets the same page again.
140
+ // While recapi has no catalog from the shop, its answer above asks for a
141
+ // page of the shop's /products.json, which every storefront serves its
142
+ // visitors: 250 products a view, so a bare shop is named after a few views.
143
+ // recapi keeps the progress and hands each page to one browser at a time.
144
+ // Only once the browser is idle and the row drawn; a failed read waits for
145
+ // the next view, which gets the same page.
151
146
  let drawing = null;
152
147
  const idle = (callback) => (window.requestIdleCallback ? window.requestIdleCallback(callback, { timeout: 10000 }) : setTimeout(callback, 2000));
153
148
  const relay = async (page) => {
@@ -169,11 +164,8 @@ export async function shopifyTheme(options) {
169
164
  await seen(JSON.stringify({ page, products }), false).catch(() => null);
170
165
  };
171
166
  if (product && !editor) describe();
172
- // A card's link carries its recommendation: without consent nothing on the
173
- // device remembers which list showed the product. In the fragment, which no
174
- // server or crawler sees: each list's new ?rec= looks like another page.
175
- // ?rec= is still read: links already out there, and the cards that can't use
176
- // a fragment (below).
167
+ // A card's link carries its list's id (cards.js carry): without consent
168
+ // nothing on the device remembers which list showed the product.
177
169
  const inFragment = /^#rec_[0-9a-f]+$/;
178
170
  const viewed = () => {
179
171
  const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
@@ -196,53 +188,30 @@ export async function shopifyTheme(options) {
196
188
 
197
189
  // Fills <div id="recapi-recommendations">&nbsp;</div> wherever the theme has one.
198
190
  const slot = document.getElementById('recapi-recommendations');
199
- // A product row in the theme's colours and fonts. :where() weighs
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).
204
- const styleOf = (id) => '<style>' +
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}` +
191
+ // A product row in the theme's colours and fonts. The page-width rule is
192
+ // for themes with no page-width class of their own (below).
193
+ const styleOf = (id) => `<style>:where(#${id}){${GRID};align-content:start}` +
206
194
  ':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}' +
207
- `:where(#${id} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
208
- `:where(#${id} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
209
- `:where(#${id} .recapi-price){font-weight:600}` +
210
- '</style>';
195
+ `${cardStyle(`#${id}`)}</style>`;
211
196
  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.
197
+ // Dawn's Custom Liquid section spans the whole screen: a row there took 15
198
+ // narrow columns, so it takes the theme's page-width class. Horizon's
199
+ // section--page-width keeps to the page's column already.
217
200
  const wide = slot && !slot.closest('.page-width, .section--page-width');
218
201
  if (wide) slot.classList.add('page-width');
219
- // Dawn and the themes built on it hide every empty div (div:empty
220
- // { display: none }): a slot pasted empty, as the quick start once
221
- // printed it, has no box, never comes near the screen, and the row would
222
- // never load. Its style, there at once, makes it not empty. A slot still
223
- // without a box is hidden by the theme or a section around it: the row
224
- // loads if that changes, and the shop's developer is told why it doesn't.
202
+ // Dawn hides every empty div: a slot pasted empty (as the quick start once
203
+ // printed it) would have no box, never come near the screen, never load.
204
+ // Its style, there at once, fills it. A slot still without a box is hidden
205
+ // by the theme: the row loads if that changes, and the developer is told.
225
206
  if (slot && !slot.getClientRects().length) {
226
207
  slot.insertAdjacentHTML('afterbegin', style);
227
208
  if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
228
209
  }
229
- // Not only [hidden]: any display rule of the theme's beats that one, and
230
- // would leave a blank where the row should be.
231
- const hide = () => {
232
- slot.hidden = true;
233
- slot.style.setProperty('display', 'none', 'important');
234
- };
235
210
  // Each row its own placement, so the dashboard and the lift test tell them
236
211
  // apart. An unconfigured placement serves as the default one and joins its
237
212
  // lift test, so a shop's settings carry over.
238
213
  const { pageType } = options;
239
214
  const placement = handle ? 'product' : pageType === 'cart' ? 'cart' : 'section';
240
- // The row shows 4 cards. recapi counts every product of a list as shown,
241
- // so a spare asked for would get an impression and could be credited a
242
- // view it never caused: the row asks for 4. recapi learns products from
243
- // events and may not know one sold out or was deleted; one more list,
244
- // without the products already listed, then fills the gap.
245
- const ROW = 4;
246
215
  // A product page has a second row under the first: what shoppers bought
247
216
  // with the product on screen, under its own placement, which recapi serves
248
217
  // as bought together until the shop gives it settings of its own. The
@@ -253,15 +222,13 @@ export async function shopifyTheme(options) {
253
222
  : null;
254
223
  const rows = [{ placement, ...(handle ? { contextItemId: handle } : {}) }];
255
224
  if (together !== null) rows.push({ placement: 'bought_together', contextItemId: handle });
256
- // Through the call that takes all of a page's rows: billed as one, the
257
- // history sent once, and no product on two rows, the first row's first.
258
- // `counts` holds [row, count] pairs, the lists come back in their order.
225
+ // One call for all of a page's rows: billed once, the history sent once,
226
+ // no product on two rows. `counts` holds [row, count] pairs.
259
227
  const ask = (counts, exclude) => recapi.recommendLists({
260
228
  lists: counts.map(([row, count]) => ({ count, ...rows[row] })),
261
229
  ...(exclude.length ? { exclude } : {})
262
230
  });
263
231
  const draw = async () => {
264
- const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
265
232
  // Prices are in the currency's subunit (100000 is ¥1,000), in the
266
233
  // visitor's currency. A number and a symbol need no translation.
267
234
  const currency = window.Shopify?.currency?.active;
@@ -269,33 +236,14 @@ export async function shopifyTheme(options) {
269
236
  let money = null;
270
237
  try { if (currency && lang) money = new Intl.NumberFormat(lang, { style: 'currency', currency }); } catch {}
271
238
  const tag = (amount) => `<span class="recapi-price">${escape(amount)}</span>`;
272
- // Only http(s) addresses: metadata is the shop's, but a javascript: link
273
- // must never reach the page.
274
- const web = (address) => {
275
- try {
276
- const url = new URL(address, location.href);
277
- return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
278
- } catch {
279
- return null;
280
- }
281
- };
282
- // ?rec= only where a fragment can't carry the id: the address has its own
283
- // (a theme's, not ours to overwrite), it's the page already open (a
284
- // fragment wouldn't load it, so no view), or the page wouldn't read it back.
285
- const carry = (url, recommendationId) => {
286
- const open = url.href.split('#')[0] === location.href.split('#')[0];
287
- if (recommendationId && (url.hash || open || !inFragment.test(`#${recommendationId}`))) url.searchParams.set('rec', recommendationId);
288
- else if (recommendationId) url.hash = recommendationId;
289
- return url;
290
- };
291
- // An item's metadata (sent with PUT /v1/items) draws its card when it has
292
- // a name and a link, with no request to Shopify. Its price is text shown
239
+ // An item's metadata draws its card with no request to Shopify. Its price is text shown
293
240
  // as it is, or a number in the shop's currency: a visitor browsing in
294
241
  // another one gets Shopify's converted price from the lookup instead, as
295
242
  // does a product Shopify's webhook marked "available": false: it may be
296
243
  // sold out, or its stock untracked, and only the lookup knows which.
244
+ const anchor = (href, src, name, price) => `<a href="${escape(href)}">${src === null ? '' : `<img src="${escape(src)}" alt="" loading="lazy">`}<span>${escape(name)}</span>${price}</a>`;
297
245
  const fromMetadata = (metadata, recommendationId) => {
298
- const link = metadata?.available !== false && typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? web(metadata.url) : null;
246
+ const link = cardLink(metadata);
299
247
  if (!link) return null;
300
248
  let price = '';
301
249
  if (typeof metadata.price === 'string') price = tag(metadata.price);
@@ -304,8 +252,7 @@ export async function shopifyTheme(options) {
304
252
  if (money) price = tag(money.format(metadata.price));
305
253
  }
306
254
  carry(link, recommendationId);
307
- const picture = typeof metadata.picture === 'string' ? web(metadata.picture) : null;
308
- return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}<span>${escape(metadata.name)}</span>${price}</a>`;
255
+ return anchor(link.href, web(metadata.picture)?.href ?? null, metadata.name, price);
309
256
  };
310
257
  // Shopify's CDN resizes on ?width=: a card needs no 2048 px original.
311
258
  const image = (src) => (src ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
@@ -315,10 +262,10 @@ export async function shopifyTheme(options) {
315
262
  return `${url.pathname}${url.search}${url.hash}`;
316
263
  };
317
264
  const fromProduct = (p, recommendationId) => (p?.available
318
- ? `<a href="${escape(path(p.url, recommendationId))}"><img src="${escape(image(p.featured_image))}" alt="" loading="lazy"><span>${escape(p.title)}</span>${money && Number.isFinite(p.price_min) ? tag(money.format(p.price_min / 100)) : ''}</a>`
265
+ ? anchor(path(p.url, recommendationId), image(p.featured_image), p.title, money && Number.isFinite(p.price_min) ? tag(money.format(p.price_min / 100)) : '')
319
266
  : null);
320
- // A list's cards, in recapi's order, each with its reason code. The
321
- // others come from the product's own page data, one request each.
267
+ // A list's cards in recapi's order, with their reason codes; those
268
+ // without metadata from the product's page data, one request each.
322
269
  const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata, why }) => {
323
270
  let html = fromMetadata(metadata, recommendationId);
324
271
  if (!html) {
@@ -329,19 +276,17 @@ export async function shopifyTheme(options) {
329
276
  }))).filter(Boolean);
330
277
  const lists = await ask(rows.map((_, row) => [row, ROW]), []);
331
278
  const cards = await Promise.all(lists.map(cardsOf));
332
- // Only a full list that couldn't fill its row: a shorter one means recapi
279
+ // recapi may not know a product sold out or was deleted: one more call
280
+ // fills a full list's gaps, without any product listed. A shorter list
333
281
  // has no more to give, and a fallback (recapi slow, down or at a limit)
334
- // would only wait again. One more call for the short rows, without any
335
- // product either row listed.
282
+ // would only wait again.
336
283
  const short = lists.map((_, row) => row).filter((row) => cards[row].length < ROW && lists[row].items.length >= ROW && !lists[row].fallback);
337
284
  if (short.length) {
338
285
  // Refused (a key revoked mid-page): the rows keep the cards they have.
339
286
  const more = await ask(short.map((row) => [row, ROW - cards[row].length]), lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)))
340
287
  .catch((error) => { console.warn('recapi:', error); return []; });
341
- // A popular top-up (recapi slow or at a limit on this call) fills the
342
- // first row's gap with what that row shows anyway when recapi is down,
343
- // but under the bought-together title it would mislead: that row keeps
344
- // the cards it has.
288
+ // A popular top-up fills the first row's gap (what it shows anyway when
289
+ // recapi is down), never bought together's.
345
290
  await Promise.all(more.map(async (list, k) => {
346
291
  if (short[k] === 1 && list.fallback) return;
347
292
  cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)];
@@ -349,39 +294,25 @@ export async function shopifyTheme(options) {
349
294
  }
350
295
  const [first, second = []] = cards.map((row) => row.slice(0, ROW));
351
296
  if (first.length) slot.innerHTML = style + first.map(({ html }) => html).join('');
352
- else hide();
353
- // Each row shows or hides on its own. A popular fallback is not what was
354
- // bought together, so that row then stays away. The theme's own h2 rule
355
- // styles its title.
297
+ else hide(slot);
298
+ // Each row shows or hides on its own; a popular fallback is not what was
299
+ // bought together, so that row stays away.
356
300
  if (second.length && !lists[1].fallback) {
357
- // The title only over a real pair among the cards drawn: a product
358
- // nobody bought with another yet gets similar ones, true cards under a
359
- // false title, so they show untitled, the first row's gap apart, and
301
+ // Without a pair they show untitled, the first row's gap apart, and
360
302
  // read as more of it.
361
- const paired = second.some(({ why }) => why === 'bought_together');
362
- const title = together && paired ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
363
- const more = paired ? '' : '<style>:where(.recapi-bought-together.recapi-more){margin-top:1rem}</style>';
364
- slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}${paired ? '' : ' recapi-more'}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${more}${second.map(({ html }) => html).join('')}</div></div>`);
303
+ const pair = paired(second);
304
+ const title = together && pair ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
305
+ const more = pair ? '' : '<style>:where(.recapi-bought-together.recapi-more){margin-top:1rem}</style>';
306
+ slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}${pair ? '' : ' recapi-more'}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${more}${second.map(({ html }) => html).join('')}</div></div>`);
365
307
  }
366
308
  };
367
309
  // recommendLists() rejects only on a bad request: a page still loses no more than its rows.
368
310
  const fill = () => (drawing = draw().catch((error) => {
369
- hide();
311
+ hide(slot);
370
312
  console.warn('recapi:', error);
371
313
  }));
372
- // Only once the row comes within 400px of the screen, as Shopify's own
373
- // themes load theirs: each list is billed and counted as shown, and a
374
- // shopper who never scrolls down saw none. The div's min-height holds its
375
- // place meanwhile. The view above went at once.
376
- if (slot && typeof IntersectionObserver !== 'function') await fill();
377
- else if (slot) {
378
- const observer = new IntersectionObserver((entries) => {
379
- if (!entries.some((entry) => entry.isIntersecting)) return undefined;
380
- observer.disconnect();
381
- return fill();
382
- }, { rootMargin: '0px 0px 400px 0px' });
383
- observer.observe(slot);
384
- }
314
+ // The view above went at once.
315
+ if (slot) await near([slot], fill);
385
316
  }
386
317
 
387
318
  // Product URLs end in /products/<handle>, the theme's item id.