@recapi/client 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ are, gzipped, and browsers cache them:
35
35
 
36
36
  ```html
37
37
  <script type="module">
38
- import { createClient } from 'https://api.example.com/sdk/0.7.0/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.8.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).
@@ -247,7 +247,27 @@ every page from `wp_footer`. The product id is the item id. It tracks:
247
247
  checkout alike: `is_order_received_page()`), with the order key checked,
248
248
  nothing for a failed or cancelled payment, and the order marked
249
249
  (`_recapi_counted` meta) so a reload prints nothing. A logged-in buyer's
250
- customer id is passed to `identify()` there.
250
+ customer id is passed to `identify()` there, even once the order is
251
+ counted. With a secret key saved (see
252
+ below) the shop's server also sends the order once it is paid, so a buyer
253
+ who pays off-site and never comes back, or blocks scripts, still counts:
254
+ on `woocommerce_payment_complete` and the `processing` and `completed`
255
+ statuses (cash on delivery, a bank transfer received, an order the merchant
256
+ enters), one `POST /v1/events` once the response is out (one try of 2 s, a
257
+ failure logged), each line dated when the order was paid, with an
258
+ `event_id` per order line. Whichever path comes first marks the order, so
259
+ it counts once. The buyer is the customer id, and the visitor id and the
260
+ recommendation of each clicked product from the `recapi` cookie, which the
261
+ script keeps (a day, only with consent, as the Magento module does) while a
262
+ key is saved; a guest without it gets `woocommerce-order-<id>` as
263
+ `anon_id`. The cookie is read only in the buyer's own request (not the
264
+ admin, WP-Cron, or a shop manager's call for another customer), and a
265
+ buyer sending `DNT: 1` or `Sec-GPC: 1` is not sent (the order is marked,
266
+ so a later status change doesn't send it either). Only orders paid since
267
+ the key was saved, or since the first request with a key after the update
268
+ that brought this path (`recapi_orders_since` option), go from the server:
269
+ older ones are in the past-orders file, whose upload skips only purchases
270
+ already sent live, so completing one later would count it twice.
251
271
 
252
272
  The checkout is the shop's own origin, so the purchase reads the state the
253
273
  product pages stored and is credited to the recommendation clicked: no
@@ -279,19 +299,50 @@ The script inserts it as `<h2 class="recapi-heading">` before the div once
279
299
  the cards fill, as text, so a row that stays hidden leaves no title. The
280
300
  shortcode shows none unless given one: `[recapi heading="You may also like"]`.
281
301
 
302
+ Each row asks for its own placement: `product` on product pages (the
303
+ Related products spot, or `[recapi]` in a product template), `cart` for
304
+ `[recapi]` on the cart page, `shortcode` elsewhere, so the Overview's "By
305
+ placement" and a lift test tell them apart. A placement not configured in
306
+ the dashboard serves as `default`, with its settings and its running lift
307
+ test, so a shop that set `default` up keeps it.
308
+
282
309
  The widget fills it like the Shopify snippet's, once it nears the screen,
283
- loading the 6 recommended products in one request to WooCommerce's public Store API
310
+ asking for the 4 products it shows (recapi counts every product of a list
311
+ as shown, so a spare would get an impression and could be credited a view it
312
+ never caused), loading them in one request to WooCommerce's public Store API
284
313
  (`/wc/store/v1/products?include=…`) and skipping those not purchasable or
285
- out of stock. Items whose [metadata](../../docs/api.md#item-metadata)
314
+ out of stock. A full list that leaves a gap that way (without a secret key
315
+ recapi may not know a product sold out) is topped up once with a second
316
+ list of as many products, excluding the first's; a fallback list is not. Items whose [metadata](../../docs/api.md#item-metadata)
286
317
  has a `name` and an http(s) `url` are left out of that request and drawn
287
318
  from it, as in the Shopify snippet (a number `price` is in the shop's
288
319
  currency, `woocommerce_currency`, and shown only while the visitor browses
289
- in it), so a row whose items all carry metadata needs no Store API call. Consent comes from the
290
- [WP Consent API](https://wordpress.org/plugins/wp-consent-api/)
291
- (`wp_has_consent('statistics')`, `wp_listen_for_consent_change`), which
292
- banner plugins feed and which reports allowed where no banner manages
293
- consent; without the API the plugin stores nothing, as the Shopify snippet
294
- does when its consent API fails to load. It declares compatibility with
320
+ in it), so a row whose items all carry metadata needs no Store API call.
321
+
322
+ Consent: the plugin keeps a visitor id on the device only with the
323
+ visitor's consent, and events without one train nothing, so WooCommerce →
324
+ recapi asks the merchant "How does your shop ask for cookie consent?"
325
+ (option `recapi_consent`):
326
+
327
+ - **A banner that feeds the [WP Consent API](https://wordpress.org/plugins/wp-consent-api/)**
328
+ (`wp-consent-api`, the reading until the merchant answers): Complianz,
329
+ CookieYes and others. `wp_has_consent('statistics')` at load, then
330
+ `wp_listen_for_consent_change`; the API reports allowed where no banner
331
+ manages consent.
332
+ - **Another banner, which calls recapi** (`banner`): once the visitor
333
+ accepts statistics cookies it runs `recapi.setConsent(true)` on every
334
+ page, and `recapi.setConsent(false)` if they withdraw. The page's head
335
+ defines `window.recapi` first, so a banner answering before the plugin's
336
+ module loads is heard.
337
+ - **No cookie banner needed** (`no-banner`): consent from the first page,
338
+ the reading the WP Consent API and Shopify give where no consent is
339
+ required. Do Not Track and Global Privacy Control still keep a visitor
340
+ out.
341
+
342
+ Until the merchant answers, a shop without the WP Consent API stores
343
+ nothing and sends events without an id, as the Shopify snippet does when its
344
+ consent API fails to load; the plugin list and WooCommerce → recapi then
345
+ show a notice that the shop isn't learning yet. It declares compatibility with
295
346
  WooCommerce's order tables (HPOS) and checkout blocks when installed as a
296
347
  plugin, and registers with the WP Consent API.
297
348
 
@@ -330,7 +381,7 @@ so recapi never sees or can guess the email), or without an email
330
381
  `woocommerce-order-<id>`. Only shop managers (`manage_woocommerce`) with
331
382
  the page's nonce get the file, and it reads orders 200 at a time through
332
383
  `wc_get_orders` (HPOS or not). The import skips rows already uploaded and
333
- purchases the order-received page already sent.
384
+ purchases the plugin already sent.
334
385
 
335
386
  `test/woocommerce.test.js` prints pages through PHP (`test/wordpress.php`
336
387
  stands in for WordPress, run by `scripts/php.sh`) and runs the printed
@@ -339,7 +390,7 @@ your address (`jssdk.WooCommerce`).
339
390
 
340
391
  `scripts/e2e_woocommerce.sh` (CI job `woocommerce`) runs the plugin on a
341
392
  real, throwaway shop: WordPress and WooCommerce in Docker at pinned
342
- versions, twice: the newest (WordPress 7.1.4, WooCommerce 11.2.1, PHP 8.5)
393
+ versions, twice: the newest (WordPress 7.1.4, WooCommerce 11.3.0, PHP 8.5)
343
394
  and the oldest the plugin's header declares (WordPress 6.3, WooCommerce 8.3,
344
395
  PHP 7.4), the plugin taken from the quick start of a new recapi shop with
345
396
  its public key pasted, then a guest's browser (Playwright) on a product
@@ -567,6 +618,8 @@ for (const item of items) {
567
618
  happens when the call fails. The user's rejected items (the newest 200)
568
619
  are added to `exclude`, after yours, up to the API's limit of 500. The SDK does not send `explain`, which needs
569
620
  a secret key: call the API from your backend for that.
621
+ - **`recommendLists({ lists, exclude, allowRepeats })`**: several rows in
622
+ one call, see [below](#several-rows-in-one-call).
570
623
  - **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
571
624
  A public key goes in `?key=`, so the response can be cached by a CDN.
572
625
  [How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
@@ -588,6 +641,20 @@ for (const item of items) {
588
641
  [Login and logout](#login-and-logout).
589
642
  - **`destroy()`** removes listeners and timers, then flushes.
590
643
 
644
+ ### Several rows in one call
645
+
646
+ A page with several rows asks for them in one call: the history is sent once
647
+ and the call is billed as one recommendation. Each list takes `recommend()`'s
648
+ parameters and resolves to its own result, in order, with its own
649
+ `recommendationId`. An item appears on one list only unless `allowRepeats`;
650
+ `exclude` applies to every list. A failure falls back list by list.
651
+
652
+ ```js
653
+ const [similar, more] = await recapi.recommendLists({
654
+ lists: [{ placement: 'product', count: 4, contextItemId: 'item-42' }, { placement: 'more', count: 8 }]
655
+ });
656
+ ```
657
+
591
658
  ### Errors
592
659
 
593
660
  Every failure is a `RecapiError` with `code`, `status` and `message`. The
@@ -877,7 +944,7 @@ key on a format change makes old data invisible.
877
944
  ## Size budget
878
945
 
879
946
  Budget: **6 KB gzip** after minification. The sources ship unminified with
880
- full JSDoc: 61 KB raw in five files, 21 KB as the API serves them (gzip -9),
947
+ full JSDoc: 66 KB raw in five files, 21 KB as the API serves them (gzip -9),
881
948
  and the browser caches them. With comments stripped and no
882
949
  minification they are 9 KB gzip. A bundler's minifier should bring
883
950
  that under the budget, but this has not been measured: the repo has no
@@ -885,6 +952,8 @@ minifier, to keep zero dev dependencies.
885
952
 
886
953
  ## Changes
887
954
 
955
+ - 2026-11-14: version 0.8.0. `recommendLists()` asks for a page's rows in one
956
+ call, billed as one recommendation ([Several rows in one call](#several-rows-in-one-call)).
888
957
  - 2026-11-11: version 0.7.0. `consent` defaults to `false`: a client stores
889
958
  nothing on the device and sends no `anon_id` until `consent: true` or
890
959
  `setConsent(true)`, so a tag pasted as is keeps the promise that our script
package/index.d.ts CHANGED
@@ -106,6 +106,15 @@ export interface RecommendParams {
106
106
  discovery?: number;
107
107
  }
108
108
 
109
+ export interface RecommendListsParams {
110
+ /** One result per list, in order; each list's `exclude` applies to it alone. */
111
+ lists: RecommendParams[];
112
+ /** Applies to every list. */
113
+ exclude?: string[];
114
+ /** Lets an item appear on more than one list. */
115
+ allowRepeats?: boolean;
116
+ }
117
+
109
118
  /** An item's reason code: map the ones you want to your own label, show none for an unknown one. */
110
119
  export type ReasonCode =
111
120
  | 'for_you' | 'similar' | 'next' | 'bought_together' | 'trending' | 'popular' | 'new' | 'explore' | 'more'
@@ -157,6 +166,8 @@ export interface RecapiClient {
157
166
  track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null }): void;
158
167
  /** Falls back to popular items on a network error, a timeout, a 5xx or a 429 (an empty list if those fail too), to an empty list on a 401 or 403; rejects on a bad request or a reply that isn't the API's. */
159
168
  recommend(params?: RecommendParams): Promise<RecommendResult>;
169
+ /** Several lists in one call, billed as one recommendation; falls back as `recommend()` does, list by list. */
170
+ recommendLists(params: RecommendListsParams): Promise<RecommendResult[]>;
160
171
  /** An empty list on a network error, a timeout, a 5xx, a 429, a 401 or a 403; rejects on a bad request or a reply that isn't the API's. */
161
172
  popular(params?: PopularParams): Promise<PopularResult>;
162
173
  identify(userId: string, options?: { history?: ServerSnapshot }): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Browser and Node client for the recapi recommendation API: local decayed history, event batching, attribution.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/client.js CHANGED
@@ -360,11 +360,30 @@ export function createClient(options) {
360
360
  return chain;
361
361
  }
362
362
 
363
- /** `POST /v1/recommendations`; remembers the shown items for attribution. */
364
- async function personalised(params, deadline) {
363
+ /**
364
+ * `POST /v1/recommendations` for `recommend()` (`call` undefined: one list)
365
+ * or `recommendLists()` (its `exclude` and `allowRepeats`); remembers each
366
+ * shown item under its own list's recommendation for attribution.
367
+ */
368
+ async function personalised(rows, call, deadline) {
365
369
  if (consent) reload();
366
370
  const wire = toWire(history, now(), config);
367
371
  const sentEmpty = wire.history.length === 0;
372
+ const row = (params, exclude) => ({
373
+ placement: params.placement ?? defaultPlacement,
374
+ count: params.count,
375
+ tags_any: params.tagsAny,
376
+ tags_all: params.tagsAll,
377
+ exclude,
378
+ context_item_id: params.contextItemId
379
+ });
380
+ const shared = call === undefined
381
+ ? row(rows[0], withRejected(rows[0].exclude, wire.rejected))
382
+ : {
383
+ placements: rows.map((params) => compact({ ...row(params, params.exclude), discovery: params.discovery })),
384
+ exclude: withRejected(call.exclude, wire.rejected),
385
+ allow_repeats: call.allowRepeats ? true : undefined
386
+ };
368
387
  const response = await transport.request({
369
388
  method: 'POST',
370
389
  path: '/v1/recommendations',
@@ -373,28 +392,31 @@ export function createClient(options) {
373
392
  body: compact({
374
393
  user_id: userId ?? undefined,
375
394
  anon_id: anonId ?? undefined,
376
- placement: params.placement ?? defaultPlacement,
377
- count: params.count,
378
- tags_any: params.tagsAny,
379
- tags_all: params.tagsAll,
380
- exclude: withRejected(params.exclude, wire.rejected),
381
- context_item_id: params.contextItemId,
395
+ ...shared,
382
396
  history: wire.history,
383
397
  recent: wire.recent,
384
- discovery: params.discovery
398
+ discovery: call === undefined ? rows[0].discovery : undefined
385
399
  })
386
400
  });
387
- if (typeof response?.recommendation_id !== 'string' || !Array.isArray(response.items)) {
401
+ const lists = call === undefined ? [response] : response?.lists;
402
+ if (!Array.isArray(lists) || lists.length !== rows.length ||
403
+ !lists.every((list) => typeof list?.recommendation_id === 'string' && Array.isArray(list.items))) {
388
404
  throw new RecapiError('invalid_response', 'malformed recommendations response');
389
405
  }
390
406
 
391
- const recommendationId = response.recommendation_id;
392
- const items = response.items.map((item) => toItem(item, item.slot));
407
+ const results = lists.map((list) => ({
408
+ recommendationId: list.recommendation_id,
409
+ fallback: false,
410
+ items: list.items.map((item) => toItem(item, item.slot))
411
+ }));
393
412
  mutate(() => {
394
413
  const t = now();
395
- for (const { itemId } of items) {
396
- shown.delete(itemId);
397
- shown.set(itemId, [recommendationId, t]);
414
+ // An item on two lists (allowRepeats) is credited to the last one.
415
+ for (const { recommendationId, items } of results) {
416
+ for (const { itemId } of items) {
417
+ shown.delete(itemId);
418
+ shown.set(itemId, [recommendationId, t]);
419
+ }
398
420
  }
399
421
  while (shown.size > MAX_SHOWN_ITEMS) shown.delete(shown.keys().next().value);
400
422
  // A snapshot is only trusted when we sent nothing, and merged once: a
@@ -408,7 +430,7 @@ export function createClient(options) {
408
430
  restored = true;
409
431
  }
410
432
  });
411
- return { recommendationId, fallback: false, items };
433
+ return results;
412
434
  }
413
435
 
414
436
  /**
@@ -429,22 +451,54 @@ export function createClient(options) {
429
451
  .map((item) => toItem(item, 'backfill'));
430
452
  }
431
453
 
432
- /** What `recommend()` answers instead of a list of its own: popular items, or none. */
433
- async function listInstead(error, params, deadline) {
454
+ /**
455
+ * What `recommend()` and `recommendLists()` answer instead of lists of
456
+ * their own: popular items, a request per list skipping the call's
457
+ * `exclude` and, unless `allowRepeats`, the earlier lists' items; once
458
+ * popular fails, the lists after it are empty without asking.
459
+ */
460
+ async function listsInstead(error, rows, { exclude = [], allowRepeats = false } = {}, deadline) {
434
461
  reportList(error);
435
- let items = [];
436
462
  // A refused key would be refused the popular list too.
437
- if (!keyRefused(error)) {
438
- try {
439
- items = await popularFallback(params, deadline);
440
- } catch (fallbackError) {
441
- // Down altogether, or the limit covers popular too. The page awaits
442
- // recommend() without a catch (the README says it may), so an empty
443
- // list it can hide beats a rejection that breaks it.
444
- reportList(fallbackError);
463
+ let failed = keyRefused(error);
464
+ const listed = [];
465
+ const results = [];
466
+ for (const params of rows) {
467
+ let items = [];
468
+ if (!failed) {
469
+ try {
470
+ items = await popularFallback({ ...params, exclude: [...exclude, ...(params.exclude ?? []), ...listed] }, deadline);
471
+ } catch (fallbackError) {
472
+ // Down altogether, or the limit covers popular too. The page awaits
473
+ // recommend() without a catch (the README says it may), so an empty
474
+ // list it can hide beats a rejection that breaks it.
475
+ reportList(fallbackError);
476
+ failed = true;
477
+ }
445
478
  }
479
+ if (!allowRepeats) listed.push(...items.map(({ itemId }) => itemId));
480
+ results.push({ recommendationId: null, fallback: true, items });
481
+ }
482
+ return results;
483
+ }
484
+
485
+ /** `recommend()` for one list (`call` undefined) and `recommendLists()`. */
486
+ async function recommendRows(rows, call) {
487
+ start();
488
+ const deadline = Math.min(timeoutMs, RECOMMEND_TIMEOUT_MS);
489
+ if (!rows.every((params) => usableContext(params.contextItemId))) {
490
+ // Unlike a failed call, nothing has read the stored rejections yet.
491
+ if (consent) reload();
492
+ const error = new RecapiError('invalid_request', idRule('contextItemId'));
493
+ const usable = rows.map((params) => (usableContext(params.contextItemId) ? params : { ...params, contextItemId: undefined }));
494
+ return listsInstead(error, usable, call, deadline);
495
+ }
496
+ try {
497
+ return await personalised(rows, call, deadline);
498
+ } catch (error) {
499
+ if (!sparesThePage(error)) throw error;
500
+ return listsInstead(error, rows, call, deadline);
446
501
  }
447
- return { recommendationId: null, fallback: true, items };
448
502
  }
449
503
 
450
504
  /**
@@ -549,20 +603,28 @@ export function createClient(options) {
549
603
  * items: Array<{ itemId: string, score: number, slot: string, why?: string, metadata?: object }> }>}
550
604
  */
551
605
  async recommend(params = {}) {
552
- start();
553
- const deadline = Math.min(timeoutMs, RECOMMEND_TIMEOUT_MS);
554
- if (!usableContext(params.contextItemId)) {
555
- // Unlike a failed call, nothing has read the stored rejections yet.
556
- if (consent) reload();
557
- const error = new RecapiError('invalid_request', idRule('contextItemId'));
558
- return listInstead(error, { ...params, contextItemId: undefined }, deadline);
559
- }
560
- try {
561
- return await personalised(params, deadline);
562
- } catch (error) {
563
- if (!sparesThePage(error)) throw error;
564
- return listInstead(error, params, deadline);
606
+ return (await recommendRows([params]))[0];
607
+ },
608
+
609
+ /**
610
+ * Several lists (a page's rows) from one call, billed as one
611
+ * recommendation and sending the history once: one result per entry of
612
+ * `lists`, in order, each with its own `recommendationId`. A list holds
613
+ * none of the items of the lists before it unless `allowRepeats`.
614
+ * `exclude` applies to every list, a list's own `exclude` to it alone.
615
+ * Fails and falls back as `recommend()` does, list by list: once the
616
+ * popular request fails, the lists after it are empty.
617
+ *
618
+ * @param {{ lists: Array<{ count?: number, tagsAny?: string[], tagsAll?: string[], exclude?: string[],
619
+ * contextItemId?: string, placement?: string, discovery?: number }>, exclude?: string[], allowRepeats?: boolean }} params
620
+ * @returns {Promise<Array<{ recommendationId: string | null, fallback: boolean,
621
+ * items: Array<{ itemId: string, score: number, slot: string, why?: string, metadata?: object }> }>>}
622
+ */
623
+ async recommendLists({ lists, exclude, allowRepeats = false } = {}) {
624
+ if (!Array.isArray(lists) || lists.length === 0) {
625
+ throw new RecapiError('invalid_request', 'at least one list is required');
565
626
  }
627
+ return recommendRows(lists, { exclude, allowRepeats });
566
628
  },
567
629
 
568
630
  /**