@recapi/client 0.6.2 → 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.2/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.
@@ -327,6 +327,18 @@ repository root on any machine with Docker and python3:
327
327
  ./scripts/e2e_woocommerce.sh
328
328
  ```
329
329
 
330
+ The file's `Version:` header is that version, so a plugin fix an advisory has
331
+ to name needs a new SDK version (a change to the file alone doesn't move it).
332
+ Its `Update URI:` header, on your API's host, tells WordPress (5.8 or later;
333
+ the plugin needs 6.3) that its updates don't come from the WordPress.org
334
+ directory, so a same-named plugin listed there isn't offered as an update. The
335
+ last part is WordPress.org's documented behaviour, on its side of the update
336
+ check: the end-to-end test shows WordPress reading the header, sending it with
337
+ the check, asking the host's `update_plugins_{hostname}` filter and offering
338
+ nothing, and can't show what WordPress.org would do with a same-named listing.
339
+ Nothing answers that filter yet, so a shop gets no update notice. A snippet
340
+ install has neither header's effect: both are comments there.
341
+
330
342
  ### Magento
331
343
 
332
344
  The Magento 2 module ([`sdk/php/magento`](../php/magento/README.md)) prints
@@ -493,7 +505,7 @@ for (const item of items) {
493
505
  | `historyConfig` | spec defaults | `{ halfLifeSeconds, topK, recentSize }`; must match the server |
494
506
  | `consent` | `true` | storage consent, see [Consent](#consent-and-eprivacy) |
495
507
  | `respectDoNotTrack` | `true` | when DNT or Global Privacy Control is on: store nothing, send no events, see [Do Not Track](#do-not-track) |
496
- | `onError` | – | 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 |
497
509
  | `now`, `fetch`, `sleep` | `Date.now`, global `fetch`, `setTimeout` | for tests |
498
510
 
499
511
  ### Client methods
@@ -529,14 +541,16 @@ for (const item of items) {
529
541
  A public key goes in `?key=`, so the response can be cached by a CDN and
530
542
  the request needs no CORS preflight. A secret key (Node) goes in the
531
543
  `Authorization` header, because the API refuses a secret key in a URL.
532
- 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.
533
546
  - **`identify(userId, { history? })`**: see [Login and logout](#login-and-logout).
534
547
  - **`reset()`**: logout. Clears the user id, history and attribution data,
535
548
  and starts a new anonymous id. Events already queued keep the ids they
536
549
  were tracked with.
537
550
  - **`setConsent(boolean)`**: grants or withdraws storage consent.
538
551
  - **`flush()`**: sends queued events now. Never rejects. Errors go to
539
- `onError`, and batches that can still succeed stay queued.
552
+ `onError` ([without one](#event-delivery): lost events to `console.warn`), and
553
+ batches that can still succeed stay queued.
540
554
  - **`getHistory()`** returns `{ history, recent, rejected }` exactly as the
541
555
  next request would send it (`rejected` goes into `exclude`). Use it for
542
556
  debugging.
@@ -552,14 +566,15 @@ API error body supplies these when present. Client-side codes are
552
566
  `network`, `timeout`, `invalid_response`, `event_rejected` (some events in
553
567
  a 202 were rejected; see `details`) and `queue_overflow`. `status` is 0
554
568
  when no HTTP response was received. Use `error.retryable` to tell
555
- transient failures apart. `recommend()` resolves with popular items
556
- instead of rejecting on `network`, `timeout` and 5xx errors, and reports
557
- 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)).
558
572
 
559
573
  ### Fallback
560
574
 
561
575
  When recapi does not answer `recommend()` within 1.5 s, cannot be
562
- 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
563
578
  `tagsAny`, `tagsAll` and `count` (also within 1.5 s) and resolves with
564
579
  `{ recommendationId: null, fallback: true, items }`. The items have slot
565
580
  `backfill`. The items in `exclude` and the `contextItemId` item are left
@@ -568,18 +583,22 @@ the widget keeps its size. Nothing is recorded for attribution: events on these
568
583
  `recommendation_id`, so clicks and conversions on the dashboard count only
569
584
  real recommendations. The original error goes to `onError`.
570
585
 
571
- When `GET /v1/popular` fails too (recapi is down altogether), `recommend()`
572
- resolves with `{ recommendationId: null, fallback: true, items: [] }`, and
573
- both errors go to `onError`: hide the slot when `items` is empty. The page
574
- 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: [] }`.
592
+
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.
575
597
 
576
- `recommend()` still rejects, with no fallback, when:
598
+ `recommend()` and `popular()` still reject when:
577
599
 
578
- - the request is wrong or the key is not allowed: 400, 401, 403 (a
579
- suspended tenant) and 404. These are integration bugs, so they stay
580
- visible;
581
- - the tenant hit its limits: 429 `rate_limited` and 429 `quota_exceeded`.
582
- These are limits to raise, not outages, and a fallback would hide them;
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;
583
602
  - the response is malformed (`invalid_response`), for example a `baseUrl`
584
603
  that points at your own site.
585
604
 
@@ -654,6 +673,13 @@ event quota or spend cap is reached, events are lost until it resets or
654
673
  the plan changes. A 202 with some `rejected` events keeps the accepted
655
674
  ones, and the rejected ones are reported as `event_rejected`.
656
675
 
676
+ Without an `onError`, events lost for good (a batch refused as above,
677
+ `event_rejected`, `queue_overflow`) print one `console.warn` line per error
678
+ code per client, so a wrong key shows in the console without flooding a
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.
682
+
657
683
  When the page is hidden (`visibilitychange` → `hidden`, or `pagehide`),
658
684
  the SDK sends the queue at once using `fetch` with `keepalive: true`.
659
685
  It does not use `navigator.sendBeacon`, because a beacon cannot send the
@@ -794,14 +820,23 @@ key on a format change makes old data invisible.
794
820
  ## Size budget
795
821
 
796
822
  Budget: **6 KB gzip** after minification. The sources ship unminified with
797
- full JSDoc: 53 KB raw in five files, 18 KB as the API serves them (gzip -9),
823
+ full JSDoc: 58 KB raw in five files, 20 KB as the API serves them (gzip -9),
798
824
  and the browser caches them for a year. With comments stripped and no
799
- minification they are 7.2 KB gzip. A bundler's minifier should bring
825
+ minification they are 8.5 KB gzip. A bundler's minifier should bring
800
826
  that under the budget, but this has not been measured: the repo has no
801
827
  minifier, to keep zero dev dependencies.
802
828
 
803
829
  ## Changes
804
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)).
837
+ - 2026-11-04: version 0.6.3. Without an `onError`, events lost for good (a
838
+ batch refused for good, `event_rejected`, `queue_overflow`) print one
839
+ `console.warn` line per error code per client ([Event delivery](#event-delivery)).
805
840
  - 2026-11-03: version 0.6.2. `popular()` and the fallback list of
806
841
  `recommend()` no longer throw on React Native below 0.80, whose
807
842
  `URLSearchParams.set` is not implemented. Query strings are unchanged
package/index.d.ts CHANGED
@@ -83,7 +83,11 @@ export interface ClientOptions {
83
83
  * nothing, send no events and no visitor ids; recommendations still work.
84
84
  */
85
85
  respectDoNotTrack?: boolean;
86
- /** Receives errors from background work (flushes, storage) and those `recommend()` fell back from. */
86
+ /**
87
+ * Receives errors from background work (flushes, storage) and those
88
+ * `recommend()` fell back from. Without it, events lost for good print one
89
+ * `console.warn` line per error code.
90
+ */
87
91
  onError?: (error: unknown) => void;
88
92
  /** Clock in unix ms. */
89
93
  now?: () => number;
@@ -151,8 +155,9 @@ export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
151
155
 
152
156
  export interface RecapiClient {
153
157
  track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null }): void;
154
- /** 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. */
155
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. */
156
161
  popular(params?: PopularParams): Promise<PopularResult>;
157
162
  identify(userId: string, options?: { history?: ServerSnapshot }): void;
158
163
  reset(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.6.2",
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,7 +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.
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.
88
93
  * @property {() => number} [now] Clock in unix ms.
89
94
  * @property {typeof fetch} [fetch]
90
95
  * @property {(ms: number) => Promise<void>} [sleep] Backoff sleep (tests).
@@ -115,13 +120,38 @@ export function createClient(options) {
115
120
  const maxBatch = Math.min(Math.max(1, options.maxBatch ?? 100), MAX_EVENTS_PER_REQUEST);
116
121
  const maxQueue = Math.max(MAX_EVENTS_PER_REQUEST, maxBatch);
117
122
  const config = resolveConfig(options.historyConfig);
118
- const report = (error) => {
123
+ const warned = new Set();
124
+ // `lost`: events are gone for good. Without an onError nothing else would
125
+ // say so; once per code, or a visitor's console fills up.
126
+ const report = (error, lost) => {
119
127
  try {
120
- options.onError?.(error);
128
+ if (options.onError) options.onError(error);
129
+ else if (lost && !warned.has(error.code)) {
130
+ warned.add(error.code);
131
+ globalThis.console?.warn(`recapi: events lost: ${error.code}: ${error.message}`);
132
+ }
121
133
  } catch {
122
134
  // A faulty error handler must not break tracking.
123
135
  }
124
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
+ };
125
155
  const transport = createTransport({ baseUrl, apiKey, fetch: fetchImpl, timeoutMs });
126
156
  const popularCache = serverCacheMode();
127
157
  // The default adapter probes localStorage with a write, so it is picked at
@@ -242,7 +272,7 @@ export function createClient(options) {
242
272
 
243
273
  function dropOverflow() {
244
274
  const dropped = queue.splice(0, queue.length - maxQueue).length;
245
- report(new RecapiError('queue_overflow', `dropped ${dropped} oldest events`));
275
+ report(new RecapiError('queue_overflow', `dropped ${dropped} oldest events`), true);
246
276
  }
247
277
 
248
278
  function schedule() {
@@ -266,13 +296,13 @@ export function createClient(options) {
266
296
  report(new RecapiError('event_rejected', `${response.rejected.length} event(s) rejected`, {
267
297
  status: 202,
268
298
  details: response.rejected.map((r) => ({ ...r, event: events[r.index] }))
269
- }));
299
+ }), true);
270
300
  }
271
301
  }
272
302
 
273
303
  /** Puts a failed batch back at the head of the queue if it may succeed later. */
274
304
  function handleSendError(error, events) {
275
- report(error);
305
+ report(error, !error.retryable);
276
306
  if (error instanceof RecapiError && error.retryable) {
277
307
  queue.unshift(...events);
278
308
  if (queue.length > maxQueue) dropOverflow();
@@ -314,8 +344,9 @@ export function createClient(options) {
314
344
  }
315
345
 
316
346
  /**
317
- * Sends all queued events. Never rejects: failures go to `onError`, and
318
- * retryable batches stay queued for the next automatic flush.
347
+ * Sends all queued events. Never rejects: failures go to `onError` (without
348
+ * one, events lost for good to `console.warn`), and retryable batches stay
349
+ * queued for the next automatic flush.
319
350
  *
320
351
  * @returns {Promise<void>}
321
352
  */
@@ -471,12 +502,13 @@ export function createClient(options) {
471
502
 
472
503
  /**
473
504
  * Fetches personalised recommendations. Fails fast (no retry, at most
474
- * 1.5 s). When recapi is unreachable, slow or failing (network error,
475
- * timeout, 5xx), resolves with popular items instead, with `fallback:
476
- * true` and no recommendation id, and reports the error to `onError`.
477
- * When the popular request fails too (recapi is down), the list is
478
- * empty: hide the slot. Other errors still reject: a 4xx is an
479
- * 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.
480
512
  *
481
513
  * @param {{ count?: number, tagsAny?: string[], tagsAll?: string[], exclude?: string[],
482
514
  * contextItemId?: string, placement?: string, discovery?: number }} [params]
@@ -489,16 +521,19 @@ export function createClient(options) {
489
521
  try {
490
522
  return await personalised(params, deadline);
491
523
  } catch (error) {
492
- if (!outage(error)) throw error;
493
- report(error);
524
+ if (!sparesThePage(error)) throw error;
525
+ reportList(error);
494
526
  let items = [];
495
- try {
496
- items = await popularFallback(params, deadline);
497
- } catch (fallbackError) {
498
- // recapi is down altogether. The page awaits recommend() without a
499
- // catch (the README says it may), so an empty list it can hide
500
- // beats a rejection that breaks it.
501
- 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
+ }
502
537
  }
503
538
  return { recommendationId: null, fallback: true, items };
504
539
  }
@@ -507,13 +542,22 @@ export function createClient(options) {
507
542
  /**
508
543
  * Non-personalised popular items. A public key goes in the query string
509
544
  * so the response is CDN-cacheable and the request needs no CORS
510
- * 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.
511
548
  *
512
549
  * @param {{ tagsAny?: string[], tagsAll?: string[], count?: number }} [params]
513
550
  * @returns {Promise<{ items: Array<{ itemId: string, score: number, why?: string, metadata?: object }> }>}
514
551
  */
515
552
  async popular(params = {}) {
516
- 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
+ }
517
561
  return { items: items.map((item) => toItem(item)) };
518
562
  },
519
563
 
@@ -658,14 +702,26 @@ function toItem({ item_id: itemId, score, why, metadata }, slot) {
658
702
  }
659
703
 
660
704
  /**
661
- * Whether `recommend()` should fall back to popular items: recapi could not
662
- * answer in time or failed on its side. A 429 is the tenant's own limit
663
- * (`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.
664
710
  *
665
711
  * @param {unknown} error
666
712
  */
667
- function outage(error) {
668
- 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;
669
725
  }
670
726
 
671
727
  /**