@recapi/client 0.6.3 → 0.6.5

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 for a year:
35
35
 
36
36
  ```html
37
37
  <script type="module">
38
- import { createClient } from 'https://api.example.com/sdk/0.6.3/index.js';
38
+ import { createClient } from 'https://api.example.com/sdk/0.6.5/index.js';
39
39
 
40
40
  const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com' });
41
41
  recapi.track('item-42', 'view'); // and the calls of the quick start below
@@ -72,9 +72,9 @@ const recapi = createClient({
72
72
  // The user opened an item: a product, an article, a video… (level 3).
73
73
  recapi.track('item-42', 'view');
74
74
 
75
- // Show recommendations. If recapi is slow or failing, recommend()
76
- // resolves with popular items instead, and with an empty list if recapi is
77
- // down altogether (hide the slot): no try/catch needed. Give the widget's
75
+ // Show recommendations. If recapi is slow, failing or at your plan's limit,
76
+ // recommend() resolves with popular items instead, and with an empty list if
77
+ // those fail too or your key is refused (hide the slot): no try/catch needed. Give the widget's
78
78
  // container a CSS min-height so the page doesn't jump when the items arrive.
79
79
  // Below the fold, ask only once it nears the screen: each list is billed
80
80
  // and counted as shown, and many visitors never scroll that far.
@@ -505,7 +505,7 @@ for (const item of items) {
505
505
  | `historyConfig` | spec defaults | `{ halfLifeSeconds, topK, recentSize }`; must match the server |
506
506
  | `consent` | `true` | storage consent, see [Consent](#consent-and-eprivacy) |
507
507
  | `respectDoNotTrack` | `true` | when DNT or Global Privacy Control is on: store nothing, send no events, see [Do Not Track](#do-not-track) |
508
- | `onError` | `console.warn` for lost events only | gets errors from background work (flushes, storage, rejected events) and those `recommend()` fell back from |
508
+ | `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 |
509
509
  | `now`, `fetch`, `sleep` | `Date.now`, global `fetch`, `setTimeout` | for tests |
510
510
 
511
511
  ### Client methods
@@ -521,10 +521,11 @@ for (const item of items) {
521
521
  local history at once and queues the event with `anon_id`, `user_id`, a
522
522
  timestamp and a fresh `event_id` (the idempotency
523
523
  key, reused on retries). Level 0 means an impression: it is sent but does
524
- not change the history. Throws `RecapiError('invalid_request')` on bad
525
- arguments, with the API's rules: an item id is 1–256 bytes of UTF-8
524
+ not change the history. Throws `RecapiError('invalid_request')` on a bad
525
+ level. An item id follows the API's rules, 1–256 bytes of UTF-8
526
526
  (128 characters of Cyrillic or accented Latin, 85 of CJK) without
527
- control characters. A stored history entry whose id breaks the rule,
527
+ control characters; any other drops the event and reports it instead of
528
+ throwing, as a visitor's URL can carry one (see [Fallback](#fallback)). A stored history entry whose id breaks the rule,
528
529
  left by an earlier SDK version, is dropped when the page loads.
529
530
  - **`recommend({ count, tagsAny, tagsAll, exclude, contextItemId, placement, discovery })`**
530
531
  resolves to `{ recommendationId, fallback, items: [{ itemId, score, slot, why, metadata }] }`.
@@ -541,7 +542,8 @@ for (const item of items) {
541
542
  A public key goes in `?key=`, so the response can be cached by a CDN and
542
543
  the request needs no CORS preflight. A secret key (Node) goes in the
543
544
  `Authorization` header, because the API refuses a secret key in a URL.
544
- The [Fallback](#fallback) sends the key the same way.
545
+ The [Fallback](#fallback) sends the key the same way, and says when the list
546
+ is empty instead of rejecting.
545
547
  - **`identify(userId, { history? })`**: see [Login and logout](#login-and-logout).
546
548
  - **`reset()`**: logout. Clears the user id, history and attribution data,
547
549
  and starts a new anonymous id. Events already queued keep the ids they
@@ -565,14 +567,15 @@ API error body supplies these when present. Client-side codes are
565
567
  `network`, `timeout`, `invalid_response`, `event_rejected` (some events in
566
568
  a 202 were rejected; see `details`) and `queue_overflow`. `status` is 0
567
569
  when no HTTP response was received. Use `error.retryable` to tell
568
- transient failures apart. `recommend()` resolves with popular items
569
- instead of rejecting on `network`, `timeout` and 5xx errors, and reports
570
- the error to `onError` (see [Fallback](#fallback)).
570
+ transient failures apart. `recommend()` and `popular()` resolve with a
571
+ list instead of rejecting on `network`, `timeout`, 5xx, 429, 401 and 403
572
+ errors, and report the error to `onError` (see [Fallback](#fallback)).
571
573
 
572
574
  ### Fallback
573
575
 
574
576
  When recapi does not answer `recommend()` within 1.5 s, cannot be
575
- reached, or fails with a 5xx, the SDK asks `GET /v1/popular` with the same
577
+ reached, fails with a 5xx or refuses the call for a limit (429 `rate_limited`
578
+ or `quota_exceeded`), the SDK asks `GET /v1/popular` once with the same
576
579
  `tagsAny`, `tagsAll` and `count` (also within 1.5 s) and resolves with
577
580
  `{ recommendationId: null, fallback: true, items }`. The items have slot
578
581
  `backfill`. The items in `exclude` and the `contextItemId` item are left
@@ -581,18 +584,31 @@ the widget keeps its size. Nothing is recorded for attribution: events on these
581
584
  `recommendation_id`, so clicks and conversions on the dashboard count only
582
585
  real recommendations. The original error goes to `onError`.
583
586
 
584
- When `GET /v1/popular` fails too (recapi is down altogether), `recommend()`
585
- resolves with `{ recommendationId: null, fallback: true, items: [] }`, and
586
- both errors go to `onError`: hide the slot when `items` is empty. The page
587
- never needs a `catch` for an outage.
588
-
589
- `recommend()` still rejects, with no fallback, when:
590
-
591
- - the request is wrong or the key is not allowed: 400, 401, 403 (a
592
- suspended tenant) and 404. These are integration bugs, so they stay
593
- visible;
594
- - the tenant hit its limits: 429 `rate_limited` and 429 `quota_exceeded`.
595
- These are limits to raise, not outages, and a fallback would hide them;
587
+ When `GET /v1/popular` fails too (recapi is down altogether, or the limit
588
+ covers it), `recommend()` resolves with
589
+ `{ recommendationId: null, fallback: true, items: [] }`, and both errors go to
590
+ `onError`: hide the slot when `items` is empty. On a 401 or 403 (a revoked key,
591
+ a suspended shop) it resolves the same way at once: the popular request would
592
+ be refused too. On any of these, `popular()` resolves with `{ items: [] }`.
593
+
594
+ The page never needs a `catch` for any of this, because each can start on a
595
+ live site with no deploy. Without an `onError`, they print one `console.warn`
596
+ line a minute per error code, with the API's message; the dashboard warns of a
597
+ limit as well.
598
+
599
+ A page often takes a product id from a visitor's URL, so a crafted link can
600
+ carry an id the API would refuse (over 256 bytes of UTF-8, a control
601
+ character, not a string at all). Such a `contextItemId` is never sent:
602
+ `recommend()` asks only for popular items and answers as above, with
603
+ `invalid_request` going to `onError` or the same line, which never quotes the id.
604
+ `track()` with such an `itemId` drops that event alone and reports it the same
605
+ way: it doesn't throw, and the history and the batch's other events are
606
+ untouched. An empty or `null` `contextItemId` just means none.
607
+
608
+ `recommend()` and `popular()` still reject when:
609
+
610
+ - the request is wrong: another 400, 404, 413 and any other 3xx or 4xx. These are
611
+ integration bugs that a developer sees on the first run;
596
612
  - the response is malformed (`invalid_response`), for example a `baseUrl`
597
613
  that points at your own site.
598
614
 
@@ -670,9 +686,9 @@ ones, and the rejected ones are reported as `event_rejected`.
670
686
  Without an `onError`, events lost for good (a batch refused as above,
671
687
  `event_rejected`, `queue_overflow`) print one `console.warn` line per error
672
688
  code per client, so a wrong key shows in the console without flooding a
673
- visitor's. Failures that can still succeed, storage errors and the errors
674
- `recommend()` falls back from print nothing. With an `onError`, nothing is
675
- printed.
689
+ visitor's. Lists `recommend()` and `popular()` answered with a fallback print
690
+ one line a minute per error code ([Fallback](#fallback)). Events that can still
691
+ succeed and storage errors print nothing. With an `onError`, nothing is printed.
676
692
 
677
693
  When the page is hidden (`visibilitychange` → `hidden`, or `pagehide`),
678
694
  the SDK sends the queue at once using `fetch` with `keepalive: true`.
@@ -822,6 +838,15 @@ minifier, to keep zero dev dependencies.
822
838
 
823
839
  ## Changes
824
840
 
841
+ - 2026-11-05: version 0.6.5. A visitor's URL can't make `recommend()` or
842
+ `track()` throw: a `contextItemId` the API would refuse gets popular items
843
+ with no recommendation request, and such an `itemId` drops only that event.
844
+ - 2026-11-04: version 0.6.4. `recommend()` no longer rejects on a limit
845
+ (429) or a refused key (401, 403), and `popular()` no longer rejects on an
846
+ outage, a limit or a refused key: the page gets popular items or an empty
847
+ list, and a catch you already have just runs less often. Without an
848
+ `onError`, these and outage fallbacks print one `console.warn` line a minute
849
+ per error code ([Fallback](#fallback)).
825
850
  - 2026-11-04: version 0.6.3. Without an `onError`, events lost for good (a
826
851
  batch refused for good, `event_rejected`, `queue_overflow`) print one
827
852
  `console.warn` line per error code per client ([Event delivery](#event-delivery)).
package/index.d.ts CHANGED
@@ -155,8 +155,9 @@ export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
155
155
 
156
156
  export interface RecapiClient {
157
157
  track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null }): void;
158
- /** Falls back to popular items on a network error, a timeout or a 5xx (an empty list if those fail too); rejects on 4xx and 429. */
158
+ /** 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
159
  recommend(params?: RecommendParams): Promise<RecommendResult>;
160
+ /** 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. */
160
161
  popular(params?: PopularParams): Promise<PopularResult>;
161
162
  identify(userId: string, options?: { history?: ServerSnapshot }): void;
162
163
  reset(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
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
@@ -36,6 +36,9 @@ const MAX_SHOWN_ITEMS = 500;
36
36
  const MAX_EVENTS_PER_REQUEST = 1000;
37
37
  /** Upper bound for the flush delay after repeated failures (e.g. offline). */
38
38
  const MAX_FLUSH_BACKOFF_MS = 60000;
39
+ /** At most one `console.warn` per error code this often, for lists recapi couldn't serve. */
40
+ const LIST_LINE_MS = 60 * 1000;
41
+
39
42
  /**
40
43
  * How long `recommend()` waits before it falls back to popular items, and
41
44
  * the fallback request after it. A widget above the fold that is still empty
@@ -84,8 +87,9 @@ const PUBLIC_KEY_PREFIX = 'rk_pub_';
84
87
  * Track or Global Privacy Control (default `true`): store nothing, send no
85
88
  * events and no visitor ids; recommendations are still asked for.
86
89
  * @property {(error: unknown) => void} [onError] Receives background errors,
87
- * and the errors `recommend()` fell back from. Without it, events lost for
88
- * good print one `console.warn` line per error code.
90
+ * and the errors `recommend()` and `popular()` answered with a fallback.
91
+ * Without it, events lost for good print one `console.warn` line per error
92
+ * code, and those lists one line a minute per error code.
89
93
  * @property {() => number} [now] Clock in unix ms.
90
94
  * @property {typeof fetch} [fetch]
91
95
  * @property {(ms: number) => Promise<void>} [sleep] Backoff sleep (tests).
@@ -130,6 +134,24 @@ export function createClient(options) {
130
134
  // A faulty error handler must not break tracking.
131
135
  }
132
136
  };
137
+ const listLines = new Map();
138
+ // A list recapi couldn't serve: on a busy back end, a line per call fills
139
+ // the log, and one line ever ages out of it during a weeks-long revocation.
140
+ const reportList = (error) => {
141
+ try {
142
+ if (options.onError) {
143
+ options.onError(error);
144
+ return;
145
+ }
146
+ const t = now();
147
+ const printed = listLines.get(error.code);
148
+ if (printed !== undefined && Math.abs(t - printed) < LIST_LINE_MS) return;
149
+ listLines.set(error.code, t);
150
+ globalThis.console?.warn(`recapi: list failed, showing popular items or none: ${error.code}: ${error.message}`);
151
+ } catch {
152
+ // A faulty error handler must not fail the page.
153
+ }
154
+ };
133
155
  const transport = createTransport({ baseUrl, apiKey, fetch: fetchImpl, timeoutMs });
134
156
  const popularCache = serverCacheMode();
135
157
  // The default adapter probes localStorage with a write, so it is picked at
@@ -401,6 +423,24 @@ export function createClient(options) {
401
423
  .map((item) => toItem(item, 'backfill'));
402
424
  }
403
425
 
426
+ /** What `recommend()` answers instead of a list of its own: popular items, or none. */
427
+ async function listInstead(error, params, deadline) {
428
+ reportList(error);
429
+ let items = [];
430
+ // A refused key would be refused the popular list too.
431
+ if (!keyRefused(error)) {
432
+ try {
433
+ items = await popularFallback(params, deadline);
434
+ } catch (fallbackError) {
435
+ // Down altogether, or the limit covers popular too. The page awaits
436
+ // recommend() without a catch (the README says it may), so an empty
437
+ // list it can hide beats a rejection that breaks it.
438
+ reportList(fallbackError);
439
+ }
440
+ }
441
+ return { recommendationId: null, fallback: true, items };
442
+ }
443
+
404
444
  /**
405
445
  * `GET /v1/popular` for `popular()` and the fallback; `deadline` defaults
406
446
  * to `timeoutMs`. A public key goes in the query string (CDN-cacheable, no
@@ -440,6 +480,8 @@ export function createClient(options) {
440
480
  * interested"): the item is never recommended to this user again until
441
481
  * a positive event on it. Don't send skips or bounces as rejections.
442
482
  * Does nothing under Do Not Track (see `respectDoNotTrack`).
483
+ * An `itemId` the API would refuse (a page often takes it from a
484
+ * visitor's URL) drops the event and goes to `onError`, without throwing.
443
485
  * @param {{ recommendationId?: string | null }} [options] Overrides the
444
486
  * automatic attribution. `null` (a fallback list's id) is no override.
445
487
  */
@@ -448,7 +490,6 @@ export function createClient(options) {
448
490
  // A fallback list has a null id, and a page passing it on must not
449
491
  // send `null` or lose the item's earlier, real attribution.
450
492
  const recommendationId = explicit ?? undefined;
451
- if (!isId(itemId)) throw new RecapiError('invalid_request', 'itemId must be 1-256 bytes of UTF-8 without control characters');
452
493
  if (typeof level === 'string' && Object.hasOwn(LEVEL_NAMES, level)) level = LEVEL_NAMES[level];
453
494
  if (!Number.isInteger(level) || level < -10 || level > 10) {
454
495
  throw new RecapiError(
@@ -456,6 +497,13 @@ export function createClient(options) {
456
497
  "level must be an integer between -10 and 10, or 'view', 'cart', 'purchase' or 'reject'"
457
498
  );
458
499
  }
500
+ // A page often takes this id from a visitor's URL, so a crafted link
501
+ // must not fail it. Nothing is kept: in the history it would make the
502
+ // API refuse every later list. The line never quotes the visitor's id.
503
+ if (!isId(itemId)) {
504
+ report(new RecapiError('invalid_request', idRule('itemId')), true);
505
+ return;
506
+ }
459
507
  if (quiet) return;
460
508
  const t = now();
461
509
  let attributed = recommendationId;
@@ -480,12 +528,15 @@ export function createClient(options) {
480
528
 
481
529
  /**
482
530
  * Fetches personalised recommendations. Fails fast (no retry, at most
483
- * 1.5 s). When recapi is unreachable, slow or failing (network error,
484
- * timeout, 5xx), resolves with popular items instead, with `fallback:
485
- * true` and no recommendation id, and reports the error to `onError`.
486
- * When the popular request fails too (recapi is down), the list is
487
- * empty: hide the slot. Other errors still reject: a 4xx is an
488
- * integration bug or a tenant limit (429), and a fallback would hide it.
531
+ * 1.5 s). When recapi is unreachable, slow, failing or at a limit (network
532
+ * error, timeout, 5xx, 429), resolves with popular items instead, with
533
+ * `fallback: true` and no recommendation id, and reports the error to
534
+ * `onError`. When the popular request fails too, the list is empty: hide
535
+ * the slot. On a 401 or 403 (a revoked key, a suspended shop) the list is
536
+ * empty at once. A `contextItemId` the API would refuse (a page often takes
537
+ * it from a visitor's URL) is never sent: the answer is the same popular
538
+ * list. Other errors still reject: a bad request or a reply that isn't the
539
+ * API's can't start on a live site without a deploy.
489
540
  *
490
541
  * @param {{ count?: number, tagsAny?: string[], tagsAll?: string[], exclude?: string[],
491
542
  * contextItemId?: string, placement?: string, discovery?: number }} [params]
@@ -495,34 +546,39 @@ export function createClient(options) {
495
546
  async recommend(params = {}) {
496
547
  start();
497
548
  const deadline = Math.min(timeoutMs, RECOMMEND_TIMEOUT_MS);
549
+ if (!usableContext(params.contextItemId)) {
550
+ // Unlike a failed call, nothing has read the stored rejections yet.
551
+ if (consent) reload();
552
+ const error = new RecapiError('invalid_request', idRule('contextItemId'));
553
+ return listInstead(error, { ...params, contextItemId: undefined }, deadline);
554
+ }
498
555
  try {
499
556
  return await personalised(params, deadline);
500
557
  } catch (error) {
501
- if (!outage(error)) throw error;
502
- report(error);
503
- let items = [];
504
- try {
505
- items = await popularFallback(params, deadline);
506
- } catch (fallbackError) {
507
- // recapi is down altogether. The page awaits recommend() without a
508
- // catch (the README says it may), so an empty list it can hide
509
- // beats a rejection that breaks it.
510
- report(fallbackError);
511
- }
512
- return { recommendationId: null, fallback: true, items };
558
+ if (!sparesThePage(error)) throw error;
559
+ return listInstead(error, params, deadline);
513
560
  }
514
561
  },
515
562
 
516
563
  /**
517
564
  * Non-personalised popular items. A public key goes in the query string
518
565
  * so the response is CDN-cacheable and the request needs no CORS
519
- * preflight; a secret key stays in the `Authorization` header.
566
+ * preflight; a secret key stays in the `Authorization` header. On a
567
+ * network error, timeout, 5xx, 429, 401 or 403 the list is empty (hide the
568
+ * slot) and the error goes to `onError`; other errors reject.
520
569
  *
521
570
  * @param {{ tagsAny?: string[], tagsAll?: string[], count?: number }} [params]
522
571
  * @returns {Promise<{ items: Array<{ itemId: string, score: number, why?: string, metadata?: object }> }>}
523
572
  */
524
573
  async popular(params = {}) {
525
- const items = await fetchPopular(params);
574
+ let items;
575
+ try {
576
+ items = await fetchPopular(params);
577
+ } catch (error) {
578
+ if (!sparesThePage(error)) throw error;
579
+ reportList(error);
580
+ items = [];
581
+ }
526
582
  return { items: items.map((item) => toItem(item)) };
527
583
  },
528
584
 
@@ -666,15 +722,42 @@ function toItem({ item_id: itemId, score, why, metadata }, slot) {
666
722
  return item;
667
723
  }
668
724
 
725
+ /** The API's rule for ids, for messages that never quote the id: a visitor may have written it. */
726
+ function idRule(name) {
727
+ return `${name} must be 1-256 bytes of UTF-8 without control characters`;
728
+ }
729
+
730
+ /**
731
+ * Whether the API would take this as a context item: an id, or nothing (an
732
+ * empty string reads as no context item).
733
+ *
734
+ * @param {unknown} id
735
+ */
736
+ function usableContext(id) {
737
+ return id === undefined || id === null || id === '' || isId(id);
738
+ }
739
+
669
740
  /**
670
- * Whether `recommend()` should fall back to popular items: recapi could not
671
- * answer in time or failed on its side. A 429 is the tenant's own limit
672
- * (`rate_limited` or `quota_exceeded`), not an outage, so it stays visible.
741
+ * Whether `recommend()` and `popular()` answer this failure with a list instead
742
+ * of rejecting. An outage, a limit or a refused key can start on a live site
743
+ * with no deploy, and a page must not pay for it: `onError`, the console and
744
+ * the dashboard show it. What's left (a bad request, a reply that isn't the
745
+ * API's) can't start without a deploy, and a developer sees it on the first run.
673
746
  *
674
747
  * @param {unknown} error
675
748
  */
676
- function outage(error) {
677
- return error instanceof RecapiError && (error.code === 'network' || error.code === 'timeout' || error.status >= 500);
749
+ function sparesThePage(error) {
750
+ return error instanceof RecapiError && (error.code === 'network' || error.code === 'timeout' ||
751
+ error.status >= 500 || error.status === 429 || keyRefused(error));
752
+ }
753
+
754
+ /**
755
+ * A key or shop recapi won't serve: any other call fails too.
756
+ *
757
+ * @param {RecapiError} error
758
+ */
759
+ function keyRefused(error) {
760
+ return error.status === 401 || error.status === 403;
678
761
  }
679
762
 
680
763
  /**