@recapi/client 0.6.3 → 0.6.4

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.4/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
@@ -541,7 +541,8 @@ for (const item of items) {
541
541
  A public key goes in `?key=`, so the response can be cached by a CDN and
542
542
  the request needs no CORS preflight. A secret key (Node) goes in the
543
543
  `Authorization` header, because the API refuses a secret key in a URL.
544
- The [Fallback](#fallback) sends the key the same way.
544
+ The [Fallback](#fallback) sends the key the same way, and says when the list
545
+ is empty instead of rejecting.
545
546
  - **`identify(userId, { history? })`**: see [Login and logout](#login-and-logout).
546
547
  - **`reset()`**: logout. Clears the user id, history and attribution data,
547
548
  and starts a new anonymous id. Events already queued keep the ids they
@@ -565,14 +566,15 @@ API error body supplies these when present. Client-side codes are
565
566
  `network`, `timeout`, `invalid_response`, `event_rejected` (some events in
566
567
  a 202 were rejected; see `details`) and `queue_overflow`. `status` is 0
567
568
  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)).
569
+ transient failures apart. `recommend()` and `popular()` resolve with a
570
+ list instead of rejecting on `network`, `timeout`, 5xx, 429, 401 and 403
571
+ errors, and report the error to `onError` (see [Fallback](#fallback)).
571
572
 
572
573
  ### Fallback
573
574
 
574
575
  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
576
+ reached, fails with a 5xx or refuses the call for a limit (429 `rate_limited`
577
+ or `quota_exceeded`), the SDK asks `GET /v1/popular` once with the same
576
578
  `tagsAny`, `tagsAll` and `count` (also within 1.5 s) and resolves with
577
579
  `{ recommendationId: null, fallback: true, items }`. The items have slot
578
580
  `backfill`. The items in `exclude` and the `contextItemId` item are left
@@ -581,18 +583,22 @@ the widget keeps its size. Nothing is recorded for attribution: events on these
581
583
  `recommendation_id`, so clicks and conversions on the dashboard count only
582
584
  real recommendations. The original error goes to `onError`.
583
585
 
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.
586
+ When `GET /v1/popular` fails too (recapi is down altogether, or the limit
587
+ covers it), `recommend()` resolves with
588
+ `{ recommendationId: null, fallback: true, items: [] }`, and both errors go to
589
+ `onError`: hide the slot when `items` is empty. On a 401 or 403 (a revoked key,
590
+ a suspended shop) it resolves the same way at once: the popular request would
591
+ be refused too. On any of these, `popular()` resolves with `{ items: [] }`.
588
592
 
589
- `recommend()` still rejects, with no fallback, when:
593
+ The page never needs a `catch` for any of this, because each can start on a
594
+ live site with no deploy. Without an `onError`, they print one `console.warn`
595
+ line a minute per error code, with the API's message; the dashboard warns of a
596
+ limit as well.
590
597
 
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;
598
+ `recommend()` and `popular()` still reject when:
599
+
600
+ - the request is wrong: 400, 404, 413 and any other 3xx or 4xx. These are
601
+ integration bugs that a developer sees on the first run;
596
602
  - the response is malformed (`invalid_response`), for example a `baseUrl`
597
603
  that points at your own site.
598
604
 
@@ -670,9 +676,9 @@ ones, and the rejected ones are reported as `event_rejected`.
670
676
  Without an `onError`, events lost for good (a batch refused as above,
671
677
  `event_rejected`, `queue_overflow`) print one `console.warn` line per error
672
678
  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.
679
+ visitor's. Lists `recommend()` and `popular()` answered with a fallback print
680
+ one line a minute per error code ([Fallback](#fallback)). Events that can still
681
+ succeed and storage errors print nothing. With an `onError`, nothing is printed.
676
682
 
677
683
  When the page is hidden (`visibilitychange` → `hidden`, or `pagehide`),
678
684
  the SDK sends the queue at once using `fetch` with `keepalive: true`.
@@ -822,6 +828,12 @@ minifier, to keep zero dev dependencies.
822
828
 
823
829
  ## Changes
824
830
 
831
+ - 2026-11-04: version 0.6.4. `recommend()` no longer rejects on a limit
832
+ (429) or a refused key (401, 403), and `popular()` no longer rejects on an
833
+ outage, a limit or a refused key: the page gets popular items or an empty
834
+ list, and a catch you already have just runs less often. Without an
835
+ `onError`, these and outage fallbacks print one `console.warn` line a minute
836
+ per error code ([Fallback](#fallback)).
825
837
  - 2026-11-04: version 0.6.3. Without an `onError`, events lost for good (a
826
838
  batch refused for good, `event_rejected`, `queue_overflow`) print one
827
839
  `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.4",
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
@@ -480,12 +502,13 @@ export function createClient(options) {
480
502
 
481
503
  /**
482
504
  * 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.
505
+ * 1.5 s). When recapi is unreachable, slow, failing or at a limit (network
506
+ * error, timeout, 5xx, 429), resolves with popular items instead, with
507
+ * `fallback: true` and no recommendation id, and reports the error to
508
+ * `onError`. When the popular request fails too, the list is empty: hide
509
+ * the slot. On a 401 or 403 (a revoked key, a suspended shop) the list is
510
+ * empty at once. Other errors still reject: a bad request or a reply that
511
+ * isn't the API's can't start on a live site without a deploy.
489
512
  *
490
513
  * @param {{ count?: number, tagsAny?: string[], tagsAll?: string[], exclude?: string[],
491
514
  * contextItemId?: string, placement?: string, discovery?: number }} [params]
@@ -498,16 +521,19 @@ export function createClient(options) {
498
521
  try {
499
522
  return await personalised(params, deadline);
500
523
  } catch (error) {
501
- if (!outage(error)) throw error;
502
- report(error);
524
+ if (!sparesThePage(error)) throw error;
525
+ reportList(error);
503
526
  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);
527
+ // A refused key would be refused the popular list too.
528
+ if (!keyRefused(error)) {
529
+ try {
530
+ items = await popularFallback(params, deadline);
531
+ } catch (fallbackError) {
532
+ // Down altogether, or the limit covers popular too. The page
533
+ // awaits recommend() without a catch (the README says it may), so
534
+ // an empty list it can hide beats a rejection that breaks it.
535
+ reportList(fallbackError);
536
+ }
511
537
  }
512
538
  return { recommendationId: null, fallback: true, items };
513
539
  }
@@ -516,13 +542,22 @@ export function createClient(options) {
516
542
  /**
517
543
  * Non-personalised popular items. A public key goes in the query string
518
544
  * so the response is CDN-cacheable and the request needs no CORS
519
- * preflight; a secret key stays in the `Authorization` header.
545
+ * preflight; a secret key stays in the `Authorization` header. On a
546
+ * network error, timeout, 5xx, 429, 401 or 403 the list is empty (hide the
547
+ * slot) and the error goes to `onError`; other errors reject.
520
548
  *
521
549
  * @param {{ tagsAny?: string[], tagsAll?: string[], count?: number }} [params]
522
550
  * @returns {Promise<{ items: Array<{ itemId: string, score: number, why?: string, metadata?: object }> }>}
523
551
  */
524
552
  async popular(params = {}) {
525
- const items = await fetchPopular(params);
553
+ let items;
554
+ try {
555
+ items = await fetchPopular(params);
556
+ } catch (error) {
557
+ if (!sparesThePage(error)) throw error;
558
+ reportList(error);
559
+ items = [];
560
+ }
526
561
  return { items: items.map((item) => toItem(item)) };
527
562
  },
528
563
 
@@ -667,14 +702,26 @@ function toItem({ item_id: itemId, score, why, metadata }, slot) {
667
702
  }
668
703
 
669
704
  /**
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.
705
+ * Whether `recommend()` and `popular()` answer this failure with a list instead
706
+ * of rejecting. An outage, a limit or a refused key can start on a live site
707
+ * with no deploy, and a page must not pay for it: `onError`, the console and
708
+ * the dashboard show it. What's left (a bad request, a reply that isn't the
709
+ * API's) can't start without a deploy, and a developer sees it on the first run.
673
710
  *
674
711
  * @param {unknown} error
675
712
  */
676
- function outage(error) {
677
- return error instanceof RecapiError && (error.code === 'network' || error.code === 'timeout' || error.status >= 500);
713
+ function sparesThePage(error) {
714
+ return error instanceof RecapiError && (error.code === 'network' || error.code === 'timeout' ||
715
+ error.status >= 500 || error.status === 429 || keyRefused(error));
716
+ }
717
+
718
+ /**
719
+ * A key or shop recapi won't serve: any other call fails too.
720
+ *
721
+ * @param {RecapiError} error
722
+ */
723
+ function keyRefused(error) {
724
+ return error.status === 401 || error.status === 403;
678
725
  }
679
726
 
680
727
  /**