@recapi/client 0.33.1 → 0.34.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
@@ -54,7 +54,7 @@ are, gzipped, and browsers cache them:
54
54
 
55
55
  ```html
56
56
  <script type="module">
57
- import { createClient } from 'https://api.example.com/sdk/0.33.1/index.js';
57
+ import { createClient } from 'https://api.example.com/sdk/0.34.0/index.js';
58
58
 
59
59
  const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
60
60
  // From your cookie banner, once the visitor agrees: recapi.setConsent(true).
@@ -687,6 +687,32 @@ await recapi.destroy(); // flushes queued events before exit
687
687
  Timers do not keep a Node process alive. Call `await client.flush()` or
688
688
  `await client.destroy()` before exiting, or queued events are lost.
689
689
 
690
+ A web server makes a client per request, one visitor each (see below). Its
691
+ state, with the visitor's id, lives in their session, so a visitor who is not
692
+ logged in keeps one id from page to page:
693
+
694
+ ```js
695
+ // Express with express-session: a client per request
696
+ import { createClient } from '@recapi/client';
697
+
698
+ const options = { apiKey: process.env.RECAPI_KEY, baseUrl: 'https://api.example.com' };
699
+
700
+ app.get('/products/:id', async (req, res) => {
701
+ const visitor = createClient({ ...options, consent: true, storage: {
702
+ getItem: (key) => req.session[key] ?? null,
703
+ setItem: (key, value) => { req.session[key] = value; },
704
+ removeItem: (key) => { delete req.session[key]; }
705
+ } });
706
+ if (req.user) visitor.identify(req.user.id); // after login only
707
+ visitor.track(req.params.id, 'view');
708
+ const { items } = await visitor.recommend({ contextItemId: req.params.id, count: 4 });
709
+ res.on('finish', () => visitor.flush());
710
+ res.json(items);
711
+ });
712
+ ```
713
+
714
+ `make test` runs this block as it stands here, two pages of one visitor.
715
+
690
716
  ### Serverless and edge
691
717
 
692
718
  A request handler never exits: once the response is out, Cloudflare
@@ -826,6 +852,7 @@ for (const item of items) {
826
852
  | `historyConfig` | spec defaults | `{ halfLifeSeconds, topK, recentSize }`; must match the server |
827
853
  | `consent` | `false` | storage consent: `false` stores nothing until `setConsent(true)`, see [Consent](#consent-and-eprivacy) |
828
854
  | `describePages` | `true` | in a browser, a product's first view also sends its page's name, category and address (no query) to [`POST /v1/products:seen`](https://recapi.io/docs/api#post-v1productsseen--what-any-product-page-says), about 200 bytes, once per product per browser. It never renames a product you sent; never under Do Not Track. `false` turns it off |
855
+ | `own` | `false` | `true` marks every event and list as the shop's own, as a browser opened once with `?recapi_own=1` is: see [The shop's own browser](#the-shops-own-browser) |
829
856
  | `respectDoNotTrack` | `true` | when DNT or Global Privacy Control is on: store nothing, send no events, see [Do Not Track](#do-not-track) |
830
857
  | `onError` | `console.warn` for lost events and lists it answered with a fallback | gets errors from background work (flushes, storage, rejected events) and those `recommend()` and `popular()` fell back from |
831
858
  | `now`, `fetch`, `sleep` | `Date.now`, global `fetch`, `setTimeout` | for tests |
@@ -913,7 +940,7 @@ row, with nothing to set in the dashboard (`BOUGHT_TOGETHER` is the product
913
940
  page's second row).
914
941
 
915
942
  ```js
916
- import { RECENTLY_VIEWED } from 'https://api.example.com/sdk/0.33.1/index.js';
943
+ import { RECENTLY_VIEWED } from 'https://api.example.com/sdk/0.34.0/index.js';
917
944
 
918
945
  const [home, recent] = await recapi.recommendLists({
919
946
  lists: [{ placement: 'home', count: 4 }, { placement: RECENTLY_VIEWED, count: 4 }]
@@ -1264,6 +1291,20 @@ server and still sends the purchase). A site with its own legal basis for tracki
1264
1291
  passes `respectDoNotTrack: false` and gets the behaviour of 0.4.0 and
1265
1292
  earlier.
1266
1293
 
1294
+ ### The shop's own browser
1295
+
1296
+ A page opened with `?recapi_own=1` (the quick start's link) marks the
1297
+ browser as the shop's own: the SDK takes the parameter out of the address,
1298
+ keeps `recapi:own` in `localStorage` (the owner's click is the consent),
1299
+ and sends `own: true` with every event and list from that browser, so no
1300
+ dashboard number counts the owner's visits or test orders
1301
+ ([what recapi stores](https://recapi.io/docs/concepts#cookie-banners)).
1302
+ Under the first row it draws, a marked browser shows "This browser is
1303
+ yours: its visits are not counted." and a "Count them again" button that
1304
+ clears the mark. Shoppers never see it. `?recapi_own=0` clears it too.
1305
+ Shopify's theme editor marks its lists, and a checkout started in a marked
1306
+ browser marks its purchase.
1307
+
1267
1308
  ## Custom storage
1268
1309
 
1269
1310
  Any synchronous `{ getItem, setItem, removeItem }` works. Every call is
@@ -1297,16 +1338,16 @@ key on a format change makes old data invisible.
1297
1338
  ## Size budget
1298
1339
 
1299
1340
  What a first visit downloads before the library runs: each entry is one
1300
- file, joined and gzipped as the API serves it (library 0.33.1). A test fails
1341
+ file, joined and gzipped as the API serves it (library 0.34.0). A test fails
1301
1342
  when an entry passes its budget (`go test ./internal/jssdk -run SizeBudget -v`
1302
1343
  in `server/` prints these):
1303
1344
 
1304
1345
  | Entry | Bytes | Gzipped | Budget | Its files as they are |
1305
1346
  |---|--:|--:|--:|--:|
1306
- | `index.js` (the pasted tag) | 41,811 | 16,843 | 18,000 | 6 files, 38,228 |
1307
- | `woocommerce.js` | 51,482 | 20,315 | 20,500 | 9 files, 54,242 |
1308
- | `shopify.js` | 54,207 | 21,363 | 21,500 | 9 files, 57,147 |
1309
- | `magento.js` | 50,781 | 20,074 | 20,250 | 9 files, 53,874 |
1347
+ | `index.js` (the pasted tag) | 42,753 | 17,181 | 18,000 | 6 files, 38,709 |
1348
+ | `woocommerce.js` | 52,427 | 20,642 | 20,850 | 9 files, 55,102 |
1349
+ | `shopify.js` | 55,286 | 21,741 | 21,950 | 9 files, 58,134 |
1350
+ | `magento.js` | 51,737 | 20,389 | 20,600 | 9 files, 54,739 |
1310
1351
 
1311
1352
  `index.js` holds the row too, which it used to fetch at the first `row()`.
1312
1353
 
@@ -1324,6 +1365,12 @@ in `server/` writes the files as served, for `scripts/e2e/chain.mjs /tmp/served`
1324
1365
 
1325
1366
  ## Changes
1326
1367
 
1368
+ - 2026-12-03: version 0.34.0. A browser opened once with `?recapi_own=1`
1369
+ is the shop's own: its events and lists carry `own: true`, which no
1370
+ dashboard number counts, and a line under its row undoes it. The
1371
+ `own` option marks a client's calls. Shopify's theme editor marks its
1372
+ lists, and the checkout a marked browser's purchase.
1373
+
1327
1374
  - 2026-12-02: version 0.33.1. A product name too long for two lines ends
1328
1375
  with an ellipsis, so a card never grows past its held place. The Shopify
1329
1376
  box to paste holds the page's width from the first paint: paste it again
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.33.1",
3
+ "version": "0.34.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/cards.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * @module cards
7
7
  */
8
8
 
9
- import { REC_ID } from './client.js';
9
+ import { REC_ID, ownBrowser } from './client.js';
10
10
 
11
11
  /** recapi counts every item of a list as shown: a spare could be credited a view it never caused. */
12
12
  export const ROW = 4;
@@ -252,3 +252,26 @@ export function near(elements, then) {
252
252
  for (const el of elements) observer.observe(el);
253
253
  return undefined;
254
254
  }
255
+
256
+ /**
257
+ * Under the first row drawn in the shop's own browser (marked by the quick
258
+ * start's link), the line that says its visits are left out, and undoes it:
259
+ * a shared computer marked by mistake is seen and fixed in one click. After
260
+ * the row, not in it: the row keeps its height. Shoppers never see it.
261
+ */
262
+ export function ownLine(el) {
263
+ if (!ownBrowser() || document.querySelector('.recapi-own')) return;
264
+ addStyle('.recapi-own{font-size:.8125rem}.recapi-own>*{font:inherit;color:inherit;background:none;border:0;padding:0;text-decoration:underline}');
265
+ const line = document.createElement('p');
266
+ const button = document.createElement('button');
267
+ line.className = 'recapi-own';
268
+ line.textContent = 'This browser is yours: its visits are not counted. ';
269
+ button.type = 'button';
270
+ button.textContent = 'Count them again';
271
+ button.addEventListener('click', () => {
272
+ ownBrowser(false);
273
+ line.remove();
274
+ });
275
+ line.append(button);
276
+ el.insertAdjacentElement('afterend', line);
277
+ }
package/src/client.js CHANGED
@@ -91,6 +91,8 @@ const PUBLIC_KEY_PREFIX = 'rk_pub_';
91
91
  * @property {number} [timeoutMs] Per-request timeout.
92
92
  * @property {Partial<HistoryConfig>} [historyConfig]
93
93
  * @property {boolean} [consent] Initial storage consent (default `false`).
94
+ * @property {boolean} [own] Marks every event and list as the shop's own
95
+ * (a staff preview), as a browser opened once with `?recapi_own=1` is.
94
96
  * @property {boolean} [describePages] In a browser, a product's first view
95
97
  * sends the name and category the page gives search engines (default
96
98
  * `true`), so a site that sent no catalog gets similar products by name.
@@ -196,6 +198,12 @@ export function createClient(options) {
196
198
  // Without an answer from the site's banner the client stores nothing, so a
197
199
  // snippet pasted as is keeps the homepage's promise (ePrivacy art. 5(3)).
198
200
  let consent = !quiet && (options.consent ?? false);
201
+ // The shop's own browser: read at each send, so "Count them again" under
202
+ // a row stops the marks of every copy of the script on the page.
203
+ const own = () => (options.own === true || ownBrowser()) || undefined;
204
+ // The quick start's link may open a page with no product and no row: its
205
+ // mark is kept at once, before the owner moves on.
206
+ ownBrowser();
199
207
 
200
208
  /** @type {HistoryState} */
201
209
  let history = emptyHistory();
@@ -409,7 +417,8 @@ export function createClient(options) {
409
417
  ...shared,
410
418
  history: wire.history,
411
419
  recent: wire.recent,
412
- discovery: call === undefined ? rows[0].discovery : undefined
420
+ discovery: call === undefined ? rows[0].discovery : undefined,
421
+ own: own()
413
422
  })
414
423
  });
415
424
  const lists = call === undefined ? [response] : response?.lists;
@@ -823,7 +832,8 @@ export function createClient(options) {
823
832
  value,
824
833
  currency,
825
834
  timestamp: new Date(t).toISOString(),
826
- event_id: uuid()
835
+ event_id: uuid(),
836
+ own: own()
827
837
  }));
828
838
  if (level === LEVEL_NAMES.view && describing) describePage(itemId);
829
839
  },
@@ -1258,9 +1268,7 @@ function landed() {
1258
1268
  } else if (REC_ID.test(url.searchParams.get('rec') ?? '')) {
1259
1269
  // ?rec=1 or ?rec=newest is the site's own parameter: it stays, and isn't sent.
1260
1270
  rec = url.searchParams.get('rec');
1261
- // Not URLSearchParams.toString(): the site's other parameters keep their exact text.
1262
- const query = url.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
1263
- url.search = query;
1271
+ unparam(url, 'rec');
1264
1272
  }
1265
1273
  if (rec === null) return null;
1266
1274
  try {
@@ -1269,6 +1277,39 @@ function landed() {
1269
1277
  return rec;
1270
1278
  }
1271
1279
 
1280
+ /** Not URLSearchParams.toString(): the site's other parameters keep their exact text. */
1281
+ function unparam(url, name) {
1282
+ url.search = url.search.slice(1).split('&').filter((p) => p.split('=')[0] !== name).join('&');
1283
+ }
1284
+
1285
+ /**
1286
+ * The shop's own browser's mark: `value` sets it, else a `?recapi_own=1`
1287
+ * in the address does (taken out of it, as `landed()` takes `?rec=`), else
1288
+ * it is what storage holds. Only ever set by the owner: their click on the
1289
+ * quick start's link, or "Count them again". False outside a page (no
1290
+ * `location`) and where storage refuses it: the owner then sees no line.
1291
+ *
1292
+ * @param {boolean} [value]
1293
+ * @returns {boolean}
1294
+ */
1295
+ export function ownBrowser(value) {
1296
+ try {
1297
+ const url = new URL(location.href);
1298
+ const asked = url.searchParams.get('recapi_own');
1299
+ if (value === undefined && asked !== null) {
1300
+ value = asked !== '0';
1301
+ unparam(url, 'recapi_own');
1302
+ history.replaceState(history.state, '', url.href);
1303
+ }
1304
+ if (value === undefined) return localStorage.getItem('recapi:own') === '1';
1305
+ if (value) localStorage.setItem('recapi:own', '1');
1306
+ else localStorage.removeItem('recapi:own');
1307
+ return value;
1308
+ } catch {
1309
+ return false;
1310
+ }
1311
+ }
1312
+
1272
1313
  /**
1273
1314
  * An item of a list as the SDK returns it. `why` (the reason code) and
1274
1315
  * `metadata` (the shop's own object, set with the item) are there only when
package/src/magento.js CHANGED
@@ -16,7 +16,7 @@
16
16
  */
17
17
 
18
18
  import { createClient } from './index.js';
19
- import { GRID, addStyle, blankStyle, blanks, card, cardStyle, carry, escape, headingAbove, idOf, listOf, listStyle, nameOf, nameStyle, near, opened, paired, pictureOf, recentlyViewed, region, wasOf, wasStyle, web } from './cards.js';
19
+ import { GRID, addStyle, blankStyle, blanks, card, cardStyle, carry, escape, headingAbove, idOf, listOf, listStyle, nameOf, nameStyle, near, opened, ownLine, paired, pictureOf, recentlyViewed, region, wasOf, wasStyle, web } from './cards.js';
20
20
  import { bought, fillRows, followReturns, landing, onReturn, orderStorage } from './shops.js';
21
21
  import { storageKey } from './storage.js';
22
22
  // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
@@ -230,6 +230,7 @@ export async function magentoPage(page) {
230
230
  })), its);
231
231
  region(blockOf(row.slot), its);
232
232
  blockOf(row.slot).hidden = false;
233
+ ownLine(blockOf(row.slot));
233
234
  if (row.slot === recent) fit();
234
235
  };
235
236
  const styled = () => addStyle(rows.map((row) => listStyle(`#${row.slot.id}`) + wasStyle(`#${row.slot.id}`) + nameStyle(`#${row.slot.id}`)).join(''));
package/src/row.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * @module row
9
9
  */
10
10
 
11
- import { GRID, ROW, addStyle, blankStyle, blanks, card, cardLink, cardStyle, carry, headingAbove, hide, listOf, nameOf, near, opened, openedOf, paired, pictureOf, region, title, untitled, wasOf } from './cards.js';
11
+ import { GRID, ROW, addStyle, blankStyle, blanks, card, cardLink, cardStyle, carry, headingAbove, hide, listOf, nameOf, near, opened, openedOf, ownLine, paired, pictureOf, region, title, untitled, wasOf } from './cards.js';
12
12
  import { onReturn } from './page.js';
13
13
 
14
14
  const CSS = `:where(.recapi-row ul){${GRID}}:where(.recapi-row ul,.recapi-bare ul){list-style:none;margin:0;padding:0}${cardStyle('.recapi-row')}${blankStyle('.recapi-row')}`;
@@ -154,6 +154,7 @@ export function rows(client) {
154
154
  given.set(el, before.map(([attribute, was]) => [attribute, was, el.getAttribute(attribute)]));
155
155
  }
156
156
  el.removeAttribute('aria-busy');
157
+ ownLine(el);
157
158
  };
158
159
 
159
160
  const fill = async (members) => {
package/src/shopify.js CHANGED
@@ -13,10 +13,10 @@
13
13
  */
14
14
 
15
15
  import { createClient, localStorageAdapter, memoryStorage } from './index.js';
16
- import { GRID, blankStyle, blanks, card, cardLink, cardStyle, carry, drawable, headingAbove, heldRow, heldStyle, hide, inStock, listOf, listStyle, nameAttribute, nameOf, near, opened, paired, pictureOf, recentlyViewed, region, title, unheld, untitled, wasOf } from './cards.js';
16
+ import { GRID, blankStyle, blanks, card, cardLink, cardStyle, carry, drawable, headingAbove, heldRow, heldStyle, hide, inStock, listOf, listStyle, nameAttribute, nameOf, near, opened, ownLine, paired, pictureOf, recentlyViewed, region, title, unheld, untitled, wasOf } from './cards.js';
17
17
  import { fillRows, followReturns, landing } from './shops.js';
18
18
  // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
19
- import './client.js';
19
+ import { ownBrowser } from './client.js';
20
20
  import './history.js';
21
21
  import './page.js';
22
22
  import './storage.js';
@@ -49,8 +49,8 @@ export async function shopifyTheme(options) {
49
49
  (error) => done(error ? null : window.Shopify.customerPrivacy));
50
50
  });
51
51
  // The theme editor's preview is the shop's own staff placing the row: it
52
- // shows, but nothing is stored or sent about them (no view, cart or click).
53
- // Its lists still count as shown: the API has no way to ask without counting.
52
+ // shows, but nothing is stored or sent about them (no view, cart or click),
53
+ // and its lists are marked as the shop's own, which no number counts.
54
54
  const editor = window.Shopify?.designMode === true;
55
55
  const consent = !editor && privacy?.analyticsProcessingAllowed?.() === true;
56
56
 
@@ -68,7 +68,9 @@ export async function shopifyTheme(options) {
68
68
  try {
69
69
  const { anonId, shown } = JSON.parse(state);
70
70
  const clicked = shown.filter((entry) => entry.length > 3).slice(-10);
71
- if (clicked.length) value = JSON.stringify({ anonId, shown: clicked });
71
+ // The shop's own browser: its test order is marked too.
72
+ const own = ownBrowser() || undefined;
73
+ if (clicked.length || own) value = JSON.stringify({ anonId, shown: clicked, own });
72
74
  } catch {}
73
75
  const memo = `${key}:cart`;
74
76
  const sent = local.getItem(memo) ?? '';
@@ -90,7 +92,7 @@ export async function shopifyTheme(options) {
90
92
  // The pixel reads this state under the same project, whatever key it holds.
91
93
  const api = { apiKey: options.apiKey, baseUrl: options.baseUrl, platform: options.platform };
92
94
  // The theme sends Shopify's own words for the product (describe, below).
93
- const recapi = createClient({ ...api, project: options.project, consent, storage, describePages: false });
95
+ const recapi = createClient({ ...api, project: options.project, consent, storage, describePages: false, own: editor });
94
96
  // What the product pages sent (below) is remembered as recapi's history
95
97
  // is: withdrawing consent forgets it too.
96
98
  const DESCRIBED = 'recapi:described';
@@ -364,6 +366,7 @@ export async function shopifyTheme(options) {
364
366
  unheld();
365
367
  if (first.length) {
366
368
  region(slot, name);
369
+ ownLine(slot);
367
370
  slot.innerHTML = style + (own ? `${ownTitleStyle}${title(inStock(), own)}` : '') + listOf(first, name);
368
371
  } else {
369
372
  slot.innerHTML = '';
@@ -407,8 +410,8 @@ const handleOf = (url) => {
407
410
  // else there leaves the purchase without ids, as before.
408
411
  const fromCart = (attributes) => {
409
412
  try {
410
- const { anonId, shown } = JSON.parse(attributes.find((a) => a.key === '_recapi').value);
411
- return JSON.stringify({ anonId, userId: null, history: { top: [], recent: [], rejected: [], lastT: null }, shown });
413
+ const { anonId, shown, own } = JSON.parse(attributes.find((a) => a.key === '_recapi').value);
414
+ return JSON.stringify({ anonId, userId: null, history: { top: [], recent: [], rejected: [], lastT: null }, shown, own });
412
415
  } catch {
413
416
  return null;
414
417
  }
@@ -429,6 +432,9 @@ async function withRecapi({ apiKey, baseUrl, project, platform, browser }, track
429
432
  const key = `recapi:v1:${project}`;
430
433
  const read = await browser.localStorage.getItem(key);
431
434
  let value = read ?? fromCart(attributes);
435
+ // The shop's own browser (its test order): the page's mark, else the
436
+ // cart's when the page's storage is out of reach.
437
+ const own = (await browser.localStorage.getItem('recapi:own')) === '1' || (read === null && JSON.parse(value)?.own);
432
438
  const storage = {
433
439
  getItem: () => value,
434
440
  setItem: (k, v) => { value = v; },
@@ -437,7 +443,7 @@ async function withRecapi({ apiKey, baseUrl, project, platform, browser }, track
437
443
  // Shopify runs this pixel only with the visitor's Analytics consent (its
438
444
  // Customer privacy setting), and the theme's snippet stored the state under
439
445
  // the same consent: without it there is nothing here to read.
440
- const recapi = createClient({ apiKey, baseUrl, project, storage, consent: true, platform });
446
+ const recapi = createClient({ apiKey, baseUrl, project, storage, consent: true, platform, own });
441
447
  track(recapi);
442
448
  const sent = recapi.destroy();
443
449
  // On the storefront the theme's snippet writes the same state meanwhile
@@ -14,7 +14,7 @@
14
14
  */
15
15
 
16
16
  import { createClient } from './index.js';
17
- import { blankStyle, blanks, card, cardStyle, carry, headingAbove, heldRow, heldStyle, hide, listOf, listStyle, nameAttribute, nameOf, near, paired, opened, pictureOf, recentlyViewed, region, title, unheld, untitled, wasOf, web } from './cards.js';
17
+ import { blankStyle, blanks, card, cardStyle, carry, headingAbove, heldRow, heldStyle, hide, listOf, listStyle, nameAttribute, nameOf, near, paired, opened, ownLine, pictureOf, recentlyViewed, region, title, unheld, untitled, wasOf, web } from './cards.js';
18
18
  import { bought, fillRows, followReturns, landing, orderStorage } from './shops.js';
19
19
  // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
20
20
  import './client.js';
@@ -187,6 +187,7 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
187
187
  const name = nameOf(first.length && heading ? titleId : headingAbove(slot), heading);
188
188
  if (first.length) {
189
189
  region(slot, name);
190
+ ownLine(slot);
190
191
  slot.innerHTML = style + listOf(first, name);
191
192
  // Hidden by an empty draw before a Back, not by the theme.
192
193
  if (slot.hidden) {