@recapi/client 0.9.0 → 0.11.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 +100 -16
- package/package.json +1 -1
- package/src/shopify.js +427 -0
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.
|
|
38
|
+
import { createClient } from 'https://api.example.com/sdk/0.11.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).
|
|
@@ -113,7 +113,14 @@ recapi.track('item-77', 'view');
|
|
|
113
113
|
### Shopify
|
|
114
114
|
|
|
115
115
|
Shopify's checkout runs no theme code, so a Shopify shop installs recapi
|
|
116
|
-
in two places, both shown with your address in the dashboard's quick start
|
|
116
|
+
in two places, both shown with your address in the dashboard's quick start.
|
|
117
|
+
Each is a short piece, pasted once: it holds the shop's keys and what only
|
|
118
|
+
Liquid or the pixel's sandbox can give, then imports
|
|
119
|
+
`/sdk/<version>/shopify.js` from your API and makes one call. The API serves
|
|
120
|
+
that file as it does `index.js`: an older version's address redirects to the
|
|
121
|
+
current one, cached a day, so every fix reaches a shop within a day with
|
|
122
|
+
nothing to paste again. A file of its own rather than more exports of
|
|
123
|
+
`index.js`, which every other site loads.
|
|
117
124
|
|
|
118
125
|
- [`shopify/theme.liquid`](shopify/theme.liquid), pasted in a *Custom
|
|
119
126
|
Liquid* section the theme editor adds to the footer group, so it runs on
|
|
@@ -121,22 +128,65 @@ in two places, both shown with your address in the dashboard's quick start:
|
|
|
121
128
|
([Updating themes](https://help.shopify.com/en/manual/online-store/themes/managing-themes/updating-themes)).
|
|
122
129
|
A theme whose footer takes no sections gets it before `</body>` in
|
|
123
130
|
`layout/theme.liquid` instead, again after each update. Its Liquid is
|
|
124
|
-
`product.handle`
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
131
|
+
`product.handle`, `product.title`, `product.type`, `product.tags`,
|
|
132
|
+
`customer.id` and `request.page_type`, which a section
|
|
133
|
+
reads as the layout does, and it stays far below the setting's 50 KB. It identifies a
|
|
134
|
+
logged-in customer, tracks product views, sends each product page's title,
|
|
135
|
+
type and tags to `POST /v1/shopify/products:seen` (once per product per
|
|
136
|
+
browser where it may store, again when they change; recapi uses them only
|
|
137
|
+
for products the shop never described), relays the shop's `/products.json`
|
|
138
|
+
a page of 250 per product view while recapi's answer asks for one (once the
|
|
139
|
+
browser is idle and after the row; recapi keeps the progress, so nothing is
|
|
140
|
+
stored), and fills the
|
|
141
|
+
`<div id="recapi-recommendations" style="min-height: 320px"> </div>`
|
|
142
|
+
the shop pastes where the row goes with 4 product
|
|
143
|
+
cards it loads from Shopify's `/products/<handle>.js`. The ` ` matters:
|
|
144
|
+
Dawn and the themes built on it hide every empty `div`, and a hidden box
|
|
145
|
+
never comes near the screen; the snippet also puts its style in a box
|
|
146
|
+
pasted empty at once, and warns in the console when the page still hides it. Like the row of
|
|
128
147
|
Shopify's own themes, it asks for them only once the div comes within
|
|
129
148
|
400px of the screen (an `IntersectionObserver`, at once in a browser
|
|
130
149
|
without one): each list is billed and counted as an impression, and a
|
|
131
150
|
visitor who never scrolls down saw none. The view goes at page load. A
|
|
132
151
|
shop moving from an earlier snippet sees fewer served lists and its CTR
|
|
133
152
|
rise once, since lists nobody reached no longer count. The product handle
|
|
134
|
-
is the item id.
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
153
|
+
is the item id. The snippet asks for the 4 products it shows: recapi
|
|
154
|
+
counts every product of a list as shown, so a spare would get an
|
|
155
|
+
impression and could be credited a view it never caused. It skips
|
|
156
|
+
products that are sold out (`available: false`) or deleted (404), which
|
|
157
|
+
recapi may not know about; a full list that leaves a gap that way is topped
|
|
158
|
+
up once with a second list of the missing count, without the first list's
|
|
159
|
+
products (not after the popular fallback, nor after a list shorter than 4,
|
|
160
|
+
which is all recapi has). It asks through `recommendLists()`, the call that
|
|
138
161
|
takes all of a page's rows ([Several rows in one call](#several-rows-in-one-call)):
|
|
139
|
-
|
|
162
|
+
a page costs one call (two with a top-up), billed as one recommendation
|
|
163
|
+
each, a product page's second row included (below). Each row asks for its own placement: `product` on
|
|
164
|
+
product pages, `cart` on the cart page (Shopify's `request.page_type`),
|
|
165
|
+
`section` elsewhere, so the Overview's "By placement" and a lift test tell
|
|
166
|
+
them apart; one not configured in the dashboard serves as `default`, with
|
|
167
|
+
its settings and its running lift test. A shop that pasted an earlier
|
|
168
|
+
snippet keeps it, with every row on `default` and 6 products asked for,
|
|
169
|
+
until it pastes this one: its served lists and CTR then read on 4 products
|
|
170
|
+
a list, and "By placement" splits `default` into the rows above.
|
|
171
|
+
|
|
172
|
+
From 0.11.0 a product page has a second row, under the first: what
|
|
173
|
+
shoppers bought with the product on screen, placement `bought_together`,
|
|
174
|
+
which recapi serves as its Bought together list until the shop gives that
|
|
175
|
+
placement settings of its own. It goes in the same call as the first row,
|
|
176
|
+
so it costs nothing more, and the API keeps a product off both rows. Its
|
|
177
|
+
cards go in a `<div id="recapi-bought-together">` the snippet adds after the
|
|
178
|
+
slot, styled like the first row, under an `<h2 class="recapi-heading">`
|
|
179
|
+
holding the `boughtTogether` option: "Often bought together" by default,
|
|
180
|
+
any text of the shop's, `''` for no title, `false` for no second row.
|
|
181
|
+
Pieces pasted before 0.11.0 get the row too, with the default title.
|
|
182
|
+
|
|
183
|
+
Each row shows or hides on its own: an empty first row hides its slot and
|
|
184
|
+
leaves the second; a short row is topped up in the one more call, with
|
|
185
|
+
only the short rows, without any product either row listed. A refused top-up
|
|
186
|
+
(a key revoked mid-page) keeps the cards already drawn. The second row
|
|
187
|
+
never shows the popular fallback (recapi slow, down or at a limit): popular
|
|
188
|
+
items are not what was bought together.
|
|
189
|
+
Each card shows the picture (resized by Shopify's
|
|
140
190
|
CDN with `?width=400`), the title and `price_min` formatted with
|
|
141
191
|
`Intl.NumberFormat` in `Shopify.currency.active` and the page's `lang`
|
|
142
192
|
(no price if either is missing). An item whose
|
|
@@ -221,11 +271,23 @@ the SDK can't read is ignored. An item shown again in a later list loses its
|
|
|
221
271
|
click (as in storage), and orders that don't go through the online store's
|
|
222
272
|
cart (POS, draft orders, subscription renewals) carry no attribute.
|
|
223
273
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
274
|
+
The two calls, and their options, are a contract from 0.10.0 on: options
|
|
275
|
+
may be added, never renamed or dropped, as shops never paste again.
|
|
276
|
+
|
|
277
|
+
| Call | Options |
|
|
278
|
+
|---|---|
|
|
279
|
+
| `shopifyTheme(options)` (theme) | `apiKey`, `baseUrl`, `project`, `platform`; `product` (`handle`, `title`, `type`, `tags`: Liquid's `product`, all `null` off a product page); `shopCurrency`; `customerId` (`''` for a guest); `pageType` (`request.page_type`); `boughtTogether` (from 0.11.0: the product page's second row's title, `false` for none). Resolves once the page's work is set up. |
|
|
280
|
+
| `shopifyPixel(options, name, event)` (pixel) | `apiKey`, `baseUrl`, `project`, `platform`, `browser` (the sandbox's); `name` is the subscribed event's, `event` Shopify's. Other names are ignored. |
|
|
281
|
+
|
|
282
|
+
`test/shopify.test.js` runs both pieces with `src/shopify.js` as the quick
|
|
283
|
+
start shows them: a view, a click on a recommendation, an add to cart, then a
|
|
284
|
+
purchase in the checkout. Every piece the quick start ever printed is kept in
|
|
285
|
+
`test/fixtures/shopify/<version>/` (0.9.0: the long snippet that held its
|
|
286
|
+
own code), and `test/shopify_published.test.js` runs every case through each
|
|
287
|
+
against the current `src/shopify.js`: a change to the pieces needs a new
|
|
288
|
+
fixture, and a change to the served code must keep every older piece
|
|
289
|
+
working. The quick start fills in the current version, your address and your
|
|
290
|
+
project (`jssdk.Shopify`).
|
|
229
291
|
|
|
230
292
|
Both files name themselves (`platform: 'shopify/<version>'`, sent as
|
|
231
293
|
`?platform=` on every call), so recapi words its setup hints for Shopify.
|
|
@@ -311,6 +373,18 @@ placement" and a lift test tell them apart. A placement not configured in
|
|
|
311
373
|
the dashboard serves as `default`, with its settings and its running lift
|
|
312
374
|
test, so a shop that set `default` up keeps it.
|
|
313
375
|
|
|
376
|
+
A product page has a second row under the first: "Often bought together"
|
|
377
|
+
(translatable in the `recapi` text domain, reworded with the
|
|
378
|
+
`recapi_bought_together_heading` filter), under the `bought_together`
|
|
379
|
+
placement, which serves the Bought together list type until the shop
|
|
380
|
+
configures it. Both lists come from the same `recommendLists` call, billed
|
|
381
|
+
as one, the first row first so no product is on both. The script adds the
|
|
382
|
+
row as `<div id="recapi-bought-together">` (with its heading) right after
|
|
383
|
+
the first row's div once it has cards: the printed page doesn't change,
|
|
384
|
+
and a row with nothing to show leaves nothing. One row empty never hides
|
|
385
|
+
the other. *WooCommerce → recapi* turns it off ("Your product pages",
|
|
386
|
+
option `recapi_bought_together`); the cart and shortcode rows never have it.
|
|
387
|
+
|
|
314
388
|
The widget fills it like the Shopify snippet's, once it nears the screen,
|
|
315
389
|
asking for the 4 products it shows (recapi counts every product of a list
|
|
316
390
|
as shown, so a spare would get an impression and could be credited a view it
|
|
@@ -319,6 +393,9 @@ never caused), loading them in one request to WooCommerce's public Store API
|
|
|
319
393
|
out of stock. A full list that leaves a gap that way (without a secret key
|
|
320
394
|
recapi may not know a product sold out) is topped up once with a second
|
|
321
395
|
list of as many products, excluding the first's; a fallback list is not.
|
|
396
|
+
One more call tops up every row left short, excluding every product either
|
|
397
|
+
row listed, and if it is refused (a key revoked mid-page) the rows keep the
|
|
398
|
+
cards they had.
|
|
322
399
|
The row asks through `recommendLists()`, the call that takes all of a page's
|
|
323
400
|
rows, billed as one recommendation with no product on two rows ([Several
|
|
324
401
|
rows in one call](#several-rows-in-one-call)). A page has one recapi row (the
|
|
@@ -967,6 +1044,13 @@ minifier, to keep zero dev dependencies.
|
|
|
967
1044
|
|
|
968
1045
|
## Changes
|
|
969
1046
|
|
|
1047
|
+
- 2026-11-19: version 0.11.0. The Shopify snippet's product pages get a
|
|
1048
|
+
second row, bought together, in the same call (`boughtTogether` turns it
|
|
1049
|
+
off or retitles it), and a refused top-up keeps the cards already drawn.
|
|
1050
|
+
- 2026-11-18: version 0.10.0. `shopify.js`, served beside `index.js`
|
|
1051
|
+
with its day of cache: the code of the Shopify pieces, which now hold only
|
|
1052
|
+
the shop's keys and Liquid values, so later fixes reach a shop with no new
|
|
1053
|
+
paste.
|
|
970
1054
|
- 2026-11-15: version 0.9.0. The `platform` option names the integration
|
|
971
1055
|
making the calls (`?platform=woocommerce/0.9.0` on every request), so recapi
|
|
972
1056
|
can word its setup hints for the shop's platform. Unset, requests are unchanged.
|
package/package.json
CHANGED
package/src/shopify.js
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a Shopify shop runs: the theme's row and events, and the checkout's
|
|
3
|
+
* pixel. The pieces a shop pastes (sdk/js/shopify/) hold only what Liquid or
|
|
4
|
+
* the pixel's sandbox can give, and import this file from the API, so a fix
|
|
5
|
+
* here reaches every shop within a day (the entry's cache), with nothing to
|
|
6
|
+
* paste again. Their options are a contract: add, never rename or drop one
|
|
7
|
+
* (each published piece is a test fixture, test/fixtures/shopify/).
|
|
8
|
+
*
|
|
9
|
+
* A file of its own rather than exports of index.js, which every other site
|
|
10
|
+
* loads: they would download a Shopify row they never draw.
|
|
11
|
+
*
|
|
12
|
+
* @module @recapi/client/shopify
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createClient, localStorageAdapter, memoryStorage } from './index.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The theme's piece: the visitor's consent, the cart attribute the pixel
|
|
19
|
+
* reads, the product's view and words, and the row in `#recapi-recommendations`.
|
|
20
|
+
* Resolves once the page's work is set up (the row loads later, as the
|
|
21
|
+
* shopper scrolls near it, or at once without IntersectionObserver).
|
|
22
|
+
*
|
|
23
|
+
* @param {{ apiKey: string, baseUrl: string, project: string, platform: string,
|
|
24
|
+
* shopCurrency?: string|null, pageType?: string|null, customerId?: string|number|null,
|
|
25
|
+
* boughtTogether?: string|false,
|
|
26
|
+
* product?: { handle: string|null, title?: string|null, type?: string|null, tags?: string[]|null }|null }} options
|
|
27
|
+
*/
|
|
28
|
+
export async function shopifyTheme(options) {
|
|
29
|
+
|
|
30
|
+
// Shopify's cookie banner decides whether recapi may keep a history on the
|
|
31
|
+
// visitor's device (ePrivacy art. 5(3)), under Analytics like the pixel.
|
|
32
|
+
// Where no consent is needed it reports allowed. If it fails to load,
|
|
33
|
+
// nothing is stored: events still go out, without a visitor id. 0.2 is the
|
|
34
|
+
// version shopify.dev/docs/api/customer-privacy documents; it no longer
|
|
35
|
+
// mentions 0.1, which Shopify could stop serving.
|
|
36
|
+
const privacy = await new Promise((resolve) => {
|
|
37
|
+
const done = (api) => { clearTimeout(timer); resolve(api); };
|
|
38
|
+
const timer = setTimeout(done, 2000, null);
|
|
39
|
+
if (!window.Shopify?.loadFeatures) return done(null);
|
|
40
|
+
window.Shopify.loadFeatures([{ name: 'consent-tracking-api', version: '0.2' }],
|
|
41
|
+
(error) => done(error ? null : window.Shopify.customerPrivacy));
|
|
42
|
+
});
|
|
43
|
+
const consent = privacy?.analyticsProcessingAllowed?.() === true;
|
|
44
|
+
|
|
45
|
+
// Shopify doesn't promise that the checkout's pixel can read this page's
|
|
46
|
+
// storage, so the cart, which Shopify carries into the checkout, holds the
|
|
47
|
+
// visitor's id and the recommendations they clicked too, in an attribute
|
|
48
|
+
// whose leading _ hides it from the buyer. Only what recapi stores (so only
|
|
49
|
+
// with consent) and only when it changes: a request per click on a card,
|
|
50
|
+
// none per page. A failed request is retried by the next page.
|
|
51
|
+
const root = window.Shopify?.routes?.root ?? '/';
|
|
52
|
+
const local = localStorageAdapter() ?? memoryStorage();
|
|
53
|
+
const remember = (key, value) => (value ? local.setItem(key, value) : local.removeItem(key));
|
|
54
|
+
const toCart = (key, state) => {
|
|
55
|
+
let value = '';
|
|
56
|
+
try {
|
|
57
|
+
const { anonId, shown } = JSON.parse(state);
|
|
58
|
+
const clicked = shown.filter((entry) => entry.length > 3).slice(-10);
|
|
59
|
+
if (clicked.length) value = JSON.stringify({ anonId, shown: clicked });
|
|
60
|
+
} catch {}
|
|
61
|
+
const memo = `${key}:cart`;
|
|
62
|
+
const sent = local.getItem(memo) ?? '';
|
|
63
|
+
if (value === sent) return;
|
|
64
|
+
remember(memo, value);
|
|
65
|
+
fetch(`${root}cart/update.js`, {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
headers: { 'Content-Type': 'application/json' },
|
|
68
|
+
body: JSON.stringify({ attributes: { _recapi: value } }),
|
|
69
|
+
keepalive: true
|
|
70
|
+
}).then((response) => { if (!response.ok) throw new Error(`cart ${response.status}`); })
|
|
71
|
+
.catch(() => { if ((local.getItem(memo) ?? '') === value) remember(memo, sent); });
|
|
72
|
+
};
|
|
73
|
+
const storage = {
|
|
74
|
+
getItem: (key) => local.getItem(key),
|
|
75
|
+
setItem: (key, state) => { local.setItem(key, state); toCart(key, state); },
|
|
76
|
+
removeItem: (key) => { local.removeItem(key); toCart(key, null); }
|
|
77
|
+
};
|
|
78
|
+
// The pixel reads this state under the same project, whatever key it holds.
|
|
79
|
+
const api = { apiKey: options.apiKey, baseUrl: options.baseUrl, platform: options.platform };
|
|
80
|
+
const recapi = createClient({ ...api, project: options.project, consent, storage });
|
|
81
|
+
// What the product pages sent (below) is remembered as recapi's history
|
|
82
|
+
// is: withdrawing consent forgets it too.
|
|
83
|
+
const DESCRIBED = 'recapi:described';
|
|
84
|
+
document.addEventListener('visitorConsentCollected', (event) => {
|
|
85
|
+
recapi.setConsent(event.detail?.analyticsAllowed === true);
|
|
86
|
+
if (recapi.getAnonId() === null) local.removeItem(DESCRIBED);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// The product handle is the item id: the purchase pixel finds it in the
|
|
90
|
+
// product's URL, and the widget loads the product's card from it.
|
|
91
|
+
const handle = typeof options.product?.handle === 'string' && options.product.handle !== '' ? options.product.handle : null;
|
|
92
|
+
const { shopCurrency } = options;
|
|
93
|
+
if (options.customerId) recapi.identify(String(options.customerId));
|
|
94
|
+
|
|
95
|
+
// What the shop's admin says the product is: recapi names the product from
|
|
96
|
+
// it when the shop sent no catalog (no products export, no webhook), so a
|
|
97
|
+
// shop that only pasted this snippet gets similar products by name. Only
|
|
98
|
+
// words: recapi never lets them overwrite what the shop sent itself. Sent
|
|
99
|
+
// once per product per browser, again when the shop changes them. They say
|
|
100
|
+
// nothing about the visitor, so they go with or without consent; what was
|
|
101
|
+
// sent is remembered only where recapi may store (else once per page view,
|
|
102
|
+
// which recapi writes only when the words changed).
|
|
103
|
+
const product = handle && { handle, title: options.product.title ?? null, type: options.product.type ?? null, tags: options.product.tags ?? null };
|
|
104
|
+
const describe = () => {
|
|
105
|
+
const body = JSON.stringify({ products: [product] });
|
|
106
|
+
// FNV-1a: a short fingerprint of the words, to tell a change.
|
|
107
|
+
let sum = 0x811c9dc5;
|
|
108
|
+
for (let i = 0; i < body.length; i++) sum = Math.imul(sum ^ body.charCodeAt(i), 0x01000193);
|
|
109
|
+
const hash = (sum >>> 0).toString(36);
|
|
110
|
+
const keep = recapi.getAnonId() !== null;
|
|
111
|
+
let sent = {};
|
|
112
|
+
try { if (keep) sent = JSON.parse(local.getItem(DESCRIBED) ?? '{}') ?? {}; } catch {}
|
|
113
|
+
if (sent[handle] === hash) return;
|
|
114
|
+
seen(body).then(async (response) => {
|
|
115
|
+
if (!response.ok) return;
|
|
116
|
+
const page = (await response.json().catch(() => null))?.list_page;
|
|
117
|
+
if (Number.isInteger(page) && page > 0) relay(page);
|
|
118
|
+
if (recapi.getAnonId() === null) return;
|
|
119
|
+
// The 100 products seen last: a visitor's storage stays small.
|
|
120
|
+
delete sent[handle];
|
|
121
|
+
sent[handle] = hash;
|
|
122
|
+
const handles = Object.keys(sent);
|
|
123
|
+
for (const old of handles.slice(0, -100)) delete sent[old];
|
|
124
|
+
local.setItem(DESCRIBED, JSON.stringify(sent));
|
|
125
|
+
}).catch(() => {});
|
|
126
|
+
};
|
|
127
|
+
// A product's words outlive the page (keepalive), as its view does. A
|
|
128
|
+
// relayed page doesn't: browsers refuse a keepalive body past 64 KiB, which
|
|
129
|
+
// 250 products with a few tags each reach, and recapi offers a page lost
|
|
130
|
+
// to navigation again once its 30 s hold ends.
|
|
131
|
+
const seen = (body, keepalive = true) => fetch(`${api.baseUrl}/v1/shopify/products:seen?key=${encodeURIComponent(api.apiKey)}&platform=${encodeURIComponent(api.platform)}`, {
|
|
132
|
+
method: 'POST',
|
|
133
|
+
// text/plain: no CORS preflight, one network trip.
|
|
134
|
+
headers: { 'Content-Type': 'text/plain' },
|
|
135
|
+
body,
|
|
136
|
+
keepalive
|
|
137
|
+
});
|
|
138
|
+
// While recapi has no catalog from the shop, it asks, in the answer above,
|
|
139
|
+
// for a page of the shop's own product list, which every Shopify storefront
|
|
140
|
+
// serves at /products.json to its visitors: a page of 250 products per page
|
|
141
|
+
// view, so a shop that only pasted this snippet has its whole catalog named
|
|
142
|
+
// after a few product views, its owner's own click-through included. recapi
|
|
143
|
+
// keeps the progress, so this needs nothing stored on the device, and hands
|
|
144
|
+
// each page to one browser at a time. Only once the browser is idle and the
|
|
145
|
+
// row (when it is being drawn) is on the page; a refused or failed read
|
|
146
|
+
// waits for the next page view, which gets the same page again.
|
|
147
|
+
let drawing = null;
|
|
148
|
+
const idle = (callback) => (window.requestIdleCallback ? window.requestIdleCallback(callback, { timeout: 10000 }) : setTimeout(callback, 2000));
|
|
149
|
+
const relay = async (page) => {
|
|
150
|
+
await new Promise(idle);
|
|
151
|
+
await drawing;
|
|
152
|
+
const response = await fetch(`${root}products.json?limit=250&page=${page}`).catch(() => null);
|
|
153
|
+
const list = response?.ok ? await response.json().catch(() => null) : null;
|
|
154
|
+
if (!Array.isArray(list?.products) || list.products.length > 250) return;
|
|
155
|
+
const words = (value, cut) => (typeof value === 'string' ? value.slice(0, cut) : '');
|
|
156
|
+
const products = [];
|
|
157
|
+
for (const p of list.products) {
|
|
158
|
+
// Any product without a handle: not the list recapi knows, so nothing goes.
|
|
159
|
+
if (typeof p?.handle !== 'string' || p.handle === '') return;
|
|
160
|
+
const tags = Array.isArray(p.tags) ? p.tags : typeof p.tags === 'string' ? p.tags.split(',') : [];
|
|
161
|
+
// recapi keeps 32 tags of 64 characters, and a title of 512 bytes.
|
|
162
|
+
products.push({ handle: p.handle, title: words(p.title, 512), type: words(p.product_type, 64), tags: tags.slice(0, 40).map((t) => words(t, 64).trim()).filter(Boolean) });
|
|
163
|
+
}
|
|
164
|
+
// The page's number tells recapi which page this is: an empty one ends the list.
|
|
165
|
+
await seen(JSON.stringify({ page, products }), false).catch(() => null);
|
|
166
|
+
};
|
|
167
|
+
if (product) describe();
|
|
168
|
+
// A card's link carries its recommendation: without consent nothing on the
|
|
169
|
+
// device remembers which list showed the product. In the fragment, which no
|
|
170
|
+
// server or crawler sees: each list's new ?rec= looks like another page.
|
|
171
|
+
// ?rec= is still read: links already out there, and the cards that can't use
|
|
172
|
+
// a fragment (below).
|
|
173
|
+
const inFragment = /^#rec_[0-9a-f]+$/;
|
|
174
|
+
const viewed = () => {
|
|
175
|
+
const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
|
|
176
|
+
const linked = fragment ?? new URLSearchParams(location.search).get('rec');
|
|
177
|
+
recapi.track(handle, 'view', { recommendationId: linked });
|
|
178
|
+
// recapi credits an explicit id to whoever brings it: drop it from the
|
|
179
|
+
// address so a copied or shared link doesn't credit strangers' visits.
|
|
180
|
+
// The other parameters (a variant) keep their exact text.
|
|
181
|
+
if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
|
|
182
|
+
else if (linked !== null) {
|
|
183
|
+
const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
184
|
+
history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
// A browser may preload the link under the pointer, and a page it prerenders
|
|
188
|
+
// runs this script though nobody may ever open it: a click nobody made must
|
|
189
|
+
// not be credited.
|
|
190
|
+
if (handle && document.prerendering) document.addEventListener('prerenderingchange', viewed);
|
|
191
|
+
else if (handle) viewed();
|
|
192
|
+
|
|
193
|
+
// Fills <div id="recapi-recommendations"> </div> wherever the theme has one.
|
|
194
|
+
const slot = document.getElementById('recapi-recommendations');
|
|
195
|
+
// A product row in the theme's colours and fonts. :where() weighs
|
|
196
|
+
// nothing, so any rule of the theme's restyles the cards.
|
|
197
|
+
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}` +
|
|
199
|
+
`:where(#${id} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
|
|
200
|
+
`:where(#${id} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
|
|
201
|
+
`:where(#${id} .recapi-price){font-weight:600}` +
|
|
202
|
+
'</style>';
|
|
203
|
+
const style = styleOf('recapi-recommendations');
|
|
204
|
+
// Dawn and the themes built on it hide every empty div (div:empty
|
|
205
|
+
// { display: none }): a slot pasted empty, as the quick start once
|
|
206
|
+
// printed it, has no box, never comes near the screen, and the row would
|
|
207
|
+
// never load. Its style, there at once, makes it not empty. A slot still
|
|
208
|
+
// without a box is hidden by the theme or a section around it: the row
|
|
209
|
+
// loads if that changes, and the shop's developer is told why it doesn't.
|
|
210
|
+
if (slot && !slot.getClientRects().length) {
|
|
211
|
+
slot.insertAdjacentHTML('afterbegin', style);
|
|
212
|
+
if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
|
|
213
|
+
}
|
|
214
|
+
// Not only [hidden]: any display rule of the theme's beats that one, and
|
|
215
|
+
// would leave a blank where the row should be.
|
|
216
|
+
const hide = () => {
|
|
217
|
+
slot.hidden = true;
|
|
218
|
+
slot.style.setProperty('display', 'none', 'important');
|
|
219
|
+
};
|
|
220
|
+
// Each row its own placement, so the dashboard and the lift test tell them
|
|
221
|
+
// apart. An unconfigured placement serves as the default one and joins its
|
|
222
|
+
// lift test, so a shop's settings carry over.
|
|
223
|
+
const { pageType } = options;
|
|
224
|
+
const placement = handle ? 'product' : pageType === 'cart' ? 'cart' : 'section';
|
|
225
|
+
// The row shows 4 cards. recapi counts every product of a list as shown,
|
|
226
|
+
// so a spare asked for would get an impression and could be credited a
|
|
227
|
+
// view it never caused: the row asks for 4. recapi learns products from
|
|
228
|
+
// events and may not know one sold out or was deleted; one more list,
|
|
229
|
+
// without the products already listed, then fills the gap.
|
|
230
|
+
const ROW = 4;
|
|
231
|
+
// A product page has a second row under the first: what shoppers bought
|
|
232
|
+
// with the product on screen, under its own placement, which recapi serves
|
|
233
|
+
// as bought together until the shop gives it settings of its own. The
|
|
234
|
+
// option is its title; false turns it off. Pieces pasted before it get the
|
|
235
|
+
// row too, with this title.
|
|
236
|
+
const together = handle && options.boughtTogether !== false
|
|
237
|
+
? (typeof options.boughtTogether === 'string' ? options.boughtTogether : 'Often bought together')
|
|
238
|
+
: null;
|
|
239
|
+
const rows = [{ placement, ...(handle ? { contextItemId: handle } : {}) }];
|
|
240
|
+
if (together !== null) rows.push({ placement: 'bought_together', contextItemId: handle });
|
|
241
|
+
// Through the call that takes all of a page's rows: billed as one, the
|
|
242
|
+
// history sent once, and no product on two rows, the first row's first.
|
|
243
|
+
// `counts` holds [row, count] pairs, the lists come back in their order.
|
|
244
|
+
const ask = (counts, exclude) => recapi.recommendLists({
|
|
245
|
+
lists: counts.map(([row, count]) => ({ count, ...rows[row] })),
|
|
246
|
+
...(exclude.length ? { exclude } : {})
|
|
247
|
+
});
|
|
248
|
+
const draw = async () => {
|
|
249
|
+
const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
250
|
+
// Prices are in the currency's subunit (100000 is ¥1,000), in the
|
|
251
|
+
// visitor's currency. A number and a symbol need no translation.
|
|
252
|
+
const currency = window.Shopify?.currency?.active;
|
|
253
|
+
const lang = document.documentElement?.lang;
|
|
254
|
+
let money = null;
|
|
255
|
+
try { if (currency && lang) money = new Intl.NumberFormat(lang, { style: 'currency', currency }); } catch {}
|
|
256
|
+
const tag = (amount) => `<span class="recapi-price">${escape(amount)}</span>`;
|
|
257
|
+
// Only http(s) addresses: metadata is the shop's, but a javascript: link
|
|
258
|
+
// must never reach the page.
|
|
259
|
+
const web = (address) => {
|
|
260
|
+
try {
|
|
261
|
+
const url = new URL(address, location.href);
|
|
262
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
|
|
263
|
+
} catch {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
// ?rec= only where a fragment can't carry the id: the address has its own
|
|
268
|
+
// (a theme's, not ours to overwrite), it's the page already open (a
|
|
269
|
+
// fragment wouldn't load it, so no view), or the page wouldn't read it back.
|
|
270
|
+
const carry = (url, recommendationId) => {
|
|
271
|
+
const open = url.href.split('#')[0] === location.href.split('#')[0];
|
|
272
|
+
if (recommendationId && (url.hash || open || !inFragment.test(`#${recommendationId}`))) url.searchParams.set('rec', recommendationId);
|
|
273
|
+
else if (recommendationId) url.hash = recommendationId;
|
|
274
|
+
return url;
|
|
275
|
+
};
|
|
276
|
+
// An item's metadata (sent with PUT /v1/items) draws its card when it has
|
|
277
|
+
// a name and a link, with no request to Shopify. Its price is text shown
|
|
278
|
+
// as it is, or a number in the shop's currency: a visitor browsing in
|
|
279
|
+
// another one gets Shopify's converted price from the lookup instead, as
|
|
280
|
+
// does a product Shopify's webhook marked "available": false: it may be
|
|
281
|
+
// sold out, or its stock untracked, and only the lookup knows which.
|
|
282
|
+
const fromMetadata = (metadata, recommendationId) => {
|
|
283
|
+
const link = metadata?.available !== false && typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? web(metadata.url) : null;
|
|
284
|
+
if (!link) return null;
|
|
285
|
+
let price = '';
|
|
286
|
+
if (typeof metadata.price === 'string') price = tag(metadata.price);
|
|
287
|
+
else if (typeof metadata.price === 'number') {
|
|
288
|
+
if (currency !== shopCurrency) return null;
|
|
289
|
+
if (money) price = tag(money.format(metadata.price));
|
|
290
|
+
}
|
|
291
|
+
carry(link, recommendationId);
|
|
292
|
+
const picture = typeof metadata.picture === 'string' ? web(metadata.picture) : null;
|
|
293
|
+
return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}<span>${escape(metadata.name)}</span>${price}</a>`;
|
|
294
|
+
};
|
|
295
|
+
// Shopify's CDN resizes on ?width=: a card needs no 2048 px original.
|
|
296
|
+
const image = (src) => (src ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
|
|
297
|
+
// Shopify gives a product's address as a path, and it stays one.
|
|
298
|
+
const path = (address, recommendationId) => {
|
|
299
|
+
const url = carry(new URL(address, location.href), recommendationId);
|
|
300
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
301
|
+
};
|
|
302
|
+
const fromProduct = (p, recommendationId) => (p?.available
|
|
303
|
+
? `<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>`
|
|
304
|
+
: null);
|
|
305
|
+
// A list's cards, in recapi's order. The others come from the product's
|
|
306
|
+
// own page data, one request each.
|
|
307
|
+
const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata }) => {
|
|
308
|
+
const card = fromMetadata(metadata, recommendationId);
|
|
309
|
+
if (card) return card;
|
|
310
|
+
const response = await fetch(`${root}products/${encodeURIComponent(itemId)}.js`).catch(() => null);
|
|
311
|
+
return fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId);
|
|
312
|
+
}))).filter(Boolean);
|
|
313
|
+
const lists = await ask(rows.map((_, row) => [row, ROW]), []);
|
|
314
|
+
const cards = await Promise.all(lists.map(cardsOf));
|
|
315
|
+
// Only a full list that couldn't fill its row: a shorter one means recapi
|
|
316
|
+
// has no more to give, and a fallback (recapi slow, down or at a limit)
|
|
317
|
+
// would only wait again. One more call for the short rows, without any
|
|
318
|
+
// product either row listed.
|
|
319
|
+
const short = lists.map((_, row) => row).filter((row) => cards[row].length < ROW && lists[row].items.length >= ROW && !lists[row].fallback);
|
|
320
|
+
if (short.length) {
|
|
321
|
+
// Refused (a key revoked mid-page): the rows keep the cards they have.
|
|
322
|
+
const more = await ask(short.map((row) => [row, ROW - cards[row].length]), lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)))
|
|
323
|
+
.catch((error) => { console.warn('recapi:', error); return []; });
|
|
324
|
+
await Promise.all(more.map(async (list, k) => { cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)]; }));
|
|
325
|
+
}
|
|
326
|
+
const [first, second = []] = cards.map((row) => row.slice(0, ROW));
|
|
327
|
+
if (first.length) slot.innerHTML = style + first.join('');
|
|
328
|
+
else hide();
|
|
329
|
+
// Each row shows or hides on its own. A popular fallback is not what was
|
|
330
|
+
// bought together, so that row then stays away. The theme's own h2 rule
|
|
331
|
+
// styles its title.
|
|
332
|
+
if (second.length && !lists[1].fallback) {
|
|
333
|
+
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>`);
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
// recommendLists() rejects only on a bad request: a page still loses no more than its rows.
|
|
338
|
+
const fill = () => (drawing = draw().catch((error) => {
|
|
339
|
+
hide();
|
|
340
|
+
console.warn('recapi:', error);
|
|
341
|
+
}));
|
|
342
|
+
// Only once the row comes within 400px of the screen, as Shopify's own
|
|
343
|
+
// themes load theirs: each list is billed and counted as shown, and a
|
|
344
|
+
// shopper who never scrolls down saw none. The div's min-height holds its
|
|
345
|
+
// place meanwhile. The view above went at once.
|
|
346
|
+
if (slot && typeof IntersectionObserver !== 'function') await fill();
|
|
347
|
+
else if (slot) {
|
|
348
|
+
const observer = new IntersectionObserver((entries) => {
|
|
349
|
+
if (!entries.some((entry) => entry.isIntersecting)) return undefined;
|
|
350
|
+
observer.disconnect();
|
|
351
|
+
return fill();
|
|
352
|
+
}, { rootMargin: '0px 0px 400px 0px' });
|
|
353
|
+
observer.observe(slot);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Product URLs end in /products/<handle>, the theme's item id.
|
|
358
|
+
const handleOf = (url) => {
|
|
359
|
+
const match = /\/products\/([^/?#]+)/.exec(url ?? '');
|
|
360
|
+
return match ? decodeURIComponent(match[1]) : null;
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
// Shopify doesn't promise that the checkout reads the storefront's storage:
|
|
364
|
+
// the theme's snippet also leaves the visitor and the recommendations they
|
|
365
|
+
// clicked in the cart. The SDK discards a state it can't read, so anything
|
|
366
|
+
// else there leaves the purchase without ids, as before.
|
|
367
|
+
const fromCart = (attributes) => {
|
|
368
|
+
try {
|
|
369
|
+
const { anonId, shown } = JSON.parse(attributes.find((a) => a.key === '_recapi').value);
|
|
370
|
+
return JSON.stringify({ anonId, userId: null, history: { top: [], recent: [], rejected: [], lastT: null }, shown });
|
|
371
|
+
} catch {
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
async function withRecapi({ apiKey, baseUrl, project, platform, browser }, track, attributes) {
|
|
377
|
+
// The pixel's own storage is not the shop's: read the snippet's state from
|
|
378
|
+
// the page (browser.localStorage is asynchronous, the SDK's storage
|
|
379
|
+
// synchronous) and write the events back to it.
|
|
380
|
+
const key = `recapi:v1:${project}`;
|
|
381
|
+
const read = await browser.localStorage.getItem(key);
|
|
382
|
+
let value = read ?? fromCart(attributes);
|
|
383
|
+
const storage = {
|
|
384
|
+
getItem: () => value,
|
|
385
|
+
setItem: (k, v) => { value = v; },
|
|
386
|
+
removeItem: () => { value = null; }
|
|
387
|
+
};
|
|
388
|
+
// Shopify runs this pixel only with the visitor's Analytics consent (its
|
|
389
|
+
// Customer privacy setting), and the theme's snippet stored the state under
|
|
390
|
+
// the same consent: without it there is nothing here to read.
|
|
391
|
+
const recapi = createClient({ apiKey, baseUrl, project, storage, consent: true, platform });
|
|
392
|
+
track(recapi);
|
|
393
|
+
const sent = recapi.destroy();
|
|
394
|
+
// On the storefront the theme's snippet writes the same state meanwhile
|
|
395
|
+
// (a recommendation it just showed): if it did, its copy is the newer one.
|
|
396
|
+
if (value !== read && (await browser.localStorage.getItem(key)) === read) {
|
|
397
|
+
await (value === null ? browser.localStorage.removeItem(key) : browser.localStorage.setItem(key, value));
|
|
398
|
+
}
|
|
399
|
+
await sent;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* The pixel's piece: one Shopify event (`checkout_completed` or
|
|
404
|
+
* `product_added_to_cart`) sent to recapi. Other events are ignored, so a
|
|
405
|
+
* later piece may pass more.
|
|
406
|
+
*
|
|
407
|
+
* @param {{ apiKey: string, baseUrl: string, project: string, platform: string, browser: object }} options
|
|
408
|
+
* @param {string} name the event's name
|
|
409
|
+
* @param {object} event Shopify's event
|
|
410
|
+
*/
|
|
411
|
+
export function shopifyPixel(options, name, event) {
|
|
412
|
+
if (name === 'checkout_completed') {
|
|
413
|
+
return withRecapi(options, (recapi) => {
|
|
414
|
+
for (const line of event.data.checkout.lineItems) {
|
|
415
|
+
const item = handleOf(line.variant?.product?.url);
|
|
416
|
+
if (item) recapi.track(item, 'purchase');
|
|
417
|
+
}
|
|
418
|
+
}, event.data.checkout.attributes);
|
|
419
|
+
}
|
|
420
|
+
if (name === 'product_added_to_cart') {
|
|
421
|
+
return withRecapi(options, (recapi) => {
|
|
422
|
+
const item = handleOf(event.data.cartLine?.merchandise?.product?.url);
|
|
423
|
+
if (item) recapi.track(item, 'cart');
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
return Promise.resolve();
|
|
427
|
+
}
|