@recapi/client 0.6.4 → 0.6.6
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 +80 -24
- package/package.json +1 -1
- package/src/client.js +60 -21
- package/src/transport.js +14 -7
package/README.md
CHANGED
|
@@ -31,11 +31,11 @@ visit, private browsing) are not part of it.
|
|
|
31
31
|
|
|
32
32
|
On a site without a build step (a theme, plain HTML), load the SDK from
|
|
33
33
|
your recapi API with one tag. The API serves the files of `src/` as they
|
|
34
|
-
are, gzipped, and browsers cache them
|
|
34
|
+
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.6.
|
|
38
|
+
import { createClient } from 'https://api.example.com/sdk/0.6.6/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
|
|
@@ -47,8 +47,20 @@ dashboard's quick start shows this tag with your API's address. A site
|
|
|
47
47
|
with a Content-Security-Policy allows that address in `script-src` and
|
|
48
48
|
`connect-src`. Each version's files never change: a later version gets a
|
|
49
49
|
new path, and an older path redirects to it, so a pasted tag keeps
|
|
50
|
-
working.
|
|
51
|
-
|
|
50
|
+
working. You have no version to manage: new visitors get the new version at
|
|
51
|
+
once, and returning visitors move to it about a day after it ships. A browser
|
|
52
|
+
holding a copy over a day old may run that copy once more while it fetches
|
|
53
|
+
the new one.
|
|
54
|
+
|
|
55
|
+
Browsers keep `index.js`, the file the tag loads, for a day, and the other
|
|
56
|
+
files for a year: `index.js` is all it takes to reach a new version. The price
|
|
57
|
+
is in a long recapi outage: a returning visitor's copy over a day old runs at
|
|
58
|
+
most once more, and after that the library doesn't load until the API is back,
|
|
59
|
+
as for a first-time visitor. Your page isn't affected: its content and other
|
|
60
|
+
scripts keep working. Only the code in the same `<script>` block as the
|
|
61
|
+
`import` doesn't run, so keep anything that must run without recapi in another
|
|
62
|
+
block. A browser that got `index.js` before this header (November 2026) keeps
|
|
63
|
+
that copy for up to a year.
|
|
52
64
|
|
|
53
65
|
With a bundler (Vite, webpack…), install the package instead:
|
|
54
66
|
|
|
@@ -143,11 +155,19 @@ in two places, both shown with your address in the dashboard's quick start:
|
|
|
143
155
|
where no consent is required Shopify reports it allowed) and fails closed
|
|
144
156
|
if the API doesn't load within 2 s. Without consent it stores nothing and
|
|
145
157
|
sends events without `anon_id`, and each card links to its product with
|
|
146
|
-
|
|
147
|
-
click is still credited (see [Consent](#consent-and-eprivacy)).
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
158
|
+
`#<recommendation id>`, which the product page's view passes on, so a
|
|
159
|
+
click is still credited (see [Consent](#consent-and-eprivacy)). A fragment
|
|
160
|
+
never reaches a server, so a page cache serves the click its stored page and
|
|
161
|
+
a crawler sees no new address per list. The page then removes the id from its
|
|
162
|
+
address (`history.replaceState`, everything else kept): recapi credits an
|
|
163
|
+
explicit id to whoever sends it, so a copied or shared link would credit
|
|
164
|
+
strangers' visits and purchases to it. The page accepts only `#rec_` and hex
|
|
165
|
+
digits, and leaves any other fragment alone. A card uses `?rec=<recommendation
|
|
166
|
+
id>` instead when its address has a fragment of its own, or is the page
|
|
167
|
+
already open (a fragment wouldn't load it); the page still reads `?rec=`, for
|
|
168
|
+
those and for links already out there. A page the browser prerenders sends
|
|
169
|
+
its view only once it is shown (`prerenderingchange`), so a preload nobody
|
|
170
|
+
opened credits no click.
|
|
151
171
|
- [`shopify/pixel.js`](shopify/pixel.js), a custom pixel (Settings →
|
|
152
172
|
Customer events): on `product_added_to_cart` it tracks the product as a
|
|
153
173
|
`cart` (level 5, the default conversion level, so a pilot's conversion
|
|
@@ -208,8 +228,12 @@ version, your address and your project (`jssdk.Shopify`).
|
|
|
208
228
|
plugin (or a snippet for Code Snippets or WPCode) that prints the SDK on
|
|
209
229
|
every page from `wp_footer`. The product id is the item id. It tracks:
|
|
210
230
|
|
|
211
|
-
- a `view` on product pages, with
|
|
212
|
-
|
|
231
|
+
- a `view` on product pages, with `#<recommendation id>` from a card's link
|
|
232
|
+
(then removed from the address, and sent only once a prerendered page is
|
|
233
|
+
shown, as on Shopify). On a shop with a page cache a `?rec=` link missed the
|
|
234
|
+
cache on every click: on a test shop (Cache Enabler, WordPress Playground, so
|
|
235
|
+
only hit or miss carries over) 0 of 7 hits at about 1.8 s first byte, against
|
|
236
|
+
7 of 7 at about 50 ms with the fragment;
|
|
213
237
|
- a `cart` (level 5) once per add to cart: on the classic product page's
|
|
214
238
|
form submit (the page reloads, so it counts at once), or on jQuery's
|
|
215
239
|
`added_to_cart` (Ajax buttons) or the blocks' `wc-blocks_added_to_cart`
|
|
@@ -521,10 +545,11 @@ for (const item of items) {
|
|
|
521
545
|
local history at once and queues the event with `anon_id`, `user_id`, a
|
|
522
546
|
timestamp and a fresh `event_id` (the idempotency
|
|
523
547
|
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
|
-
|
|
548
|
+
not change the history. Throws `RecapiError('invalid_request')` on a bad
|
|
549
|
+
level. An item id follows the API's rules, 1–256 bytes of UTF-8
|
|
526
550
|
(128 characters of Cyrillic or accented Latin, 85 of CJK) without
|
|
527
|
-
control characters
|
|
551
|
+
control characters; any other drops the event and reports it instead of
|
|
552
|
+
throwing, as a visitor's URL can carry one (see [Fallback](#fallback)). A stored history entry whose id breaks the rule,
|
|
528
553
|
left by an earlier SDK version, is dropped when the page loads.
|
|
529
554
|
- **`recommend({ count, tagsAny, tagsAll, exclude, contextItemId, placement, discovery })`**
|
|
530
555
|
resolves to `{ recommendationId, fallback, items: [{ itemId, score, slot, why, metadata }] }`.
|
|
@@ -538,9 +563,8 @@ for (const item of items) {
|
|
|
538
563
|
are added to `exclude`, after yours, up to the API's limit of 500. The SDK does not send `explain`, which needs
|
|
539
564
|
a secret key: call the API from your backend for that.
|
|
540
565
|
- **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
|
|
541
|
-
A public key goes in `?key=`, so the response can be cached by a CDN
|
|
542
|
-
the
|
|
543
|
-
`Authorization` header, because the API refuses a secret key in a URL.
|
|
566
|
+
A public key goes in `?key=`, so the response can be cached by a CDN.
|
|
567
|
+
[How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
|
|
544
568
|
The [Fallback](#fallback) sends the key the same way, and says when the list
|
|
545
569
|
is empty instead of rejecting.
|
|
546
570
|
- **`identify(userId, { history? })`**: see [Login and logout](#login-and-logout).
|
|
@@ -595,9 +619,18 @@ live site with no deploy. Without an `onError`, they print one `console.warn`
|
|
|
595
619
|
line a minute per error code, with the API's message; the dashboard warns of a
|
|
596
620
|
limit as well.
|
|
597
621
|
|
|
622
|
+
A page often takes a product id from a visitor's URL, so a crafted link can
|
|
623
|
+
carry an id the API would refuse (over 256 bytes of UTF-8, a control
|
|
624
|
+
character, not a string at all). Such a `contextItemId` is never sent:
|
|
625
|
+
`recommend()` asks only for popular items and answers as above, with
|
|
626
|
+
`invalid_request` going to `onError` or the same line, which never quotes the id.
|
|
627
|
+
`track()` with such an `itemId` drops that event alone and reports it the same
|
|
628
|
+
way: it doesn't throw, and the history and the batch's other events are
|
|
629
|
+
untouched. An empty or `null` `contextItemId` just means none.
|
|
630
|
+
|
|
598
631
|
`recommend()` and `popular()` still reject when:
|
|
599
632
|
|
|
600
|
-
- the request is wrong: 400, 404, 413 and any other 3xx or 4xx. These are
|
|
633
|
+
- the request is wrong: another 400, 404, 413 and any other 3xx or 4xx. These are
|
|
601
634
|
integration bugs that a developer sees on the first run;
|
|
602
635
|
- the response is malformed (`invalid_response`), for example a `baseUrl`
|
|
603
636
|
that points at your own site.
|
|
@@ -656,6 +689,20 @@ the oldest are dropped first. An explicit `recommendationId` always wins;
|
|
|
656
689
|
when it is the id of the recommendation that showed the item, it is the
|
|
657
690
|
click on the item too.
|
|
658
691
|
|
|
692
|
+
### How the key is sent
|
|
693
|
+
|
|
694
|
+
A public key (`rk_pub_…`) goes in the URL as `?key=` on every call, and the JSON
|
|
695
|
+
body is labelled `Content-Type: text/plain`. So a browser sends the call at once,
|
|
696
|
+
without first asking permission with an `OPTIONS` request (the CORS preflight),
|
|
697
|
+
which would cost a network trip before a visit's first list and events. A public
|
|
698
|
+
key is public by design, as it is in the page's source, so seeing it in access logs
|
|
699
|
+
exposes nothing new.
|
|
700
|
+
|
|
701
|
+
A secret key (Node) goes in the `Authorization` header with
|
|
702
|
+
`Content-Type: application/json`, because the API refuses a secret key in a URL.
|
|
703
|
+
|
|
704
|
+
There is no option for this: the key's prefix decides.
|
|
705
|
+
|
|
659
706
|
### Event delivery
|
|
660
707
|
|
|
661
708
|
Events are sent in batches every `flushIntervalMs`, or as soon as
|
|
@@ -683,8 +730,7 @@ succeed and storage errors print nothing. With an `onError`, nothing is printed.
|
|
|
683
730
|
When the page is hidden (`visibilitychange` → `hidden`, or `pagehide`),
|
|
684
731
|
the SDK sends the queue at once using `fetch` with `keepalive: true`.
|
|
685
732
|
It does not use `navigator.sendBeacon`, because a beacon cannot send the
|
|
686
|
-
`Authorization` header
|
|
687
|
-
`GET /v1/popular`. A keepalive fetch also survives page unload, but the
|
|
733
|
+
`Authorization` header a secret key needs. A keepalive fetch also survives page unload, but the
|
|
688
734
|
browser allows at most 64 KiB of keepalive bodies in flight per page, all
|
|
689
735
|
requests together. The SDK marks a request keepalive only up to 60,000
|
|
690
736
|
bytes (about 250 typical events). A default batch of 100 events is about
|
|
@@ -751,7 +797,9 @@ Without consent, the SDK never reads or writes storage and creates no
|
|
|
751
797
|
anonymous id. The history and the attribution map live in memory for the
|
|
752
798
|
current page only. A single-page app keeps attribution. On a multi-page
|
|
753
799
|
site, a click that loads the item's page is not attributed unless you
|
|
754
|
-
pass the id yourself, for example in the link
|
|
800
|
+
pass the id yourself, for example in the link. A fragment (`#${recommendationId}`,
|
|
801
|
+
read from `location.hash`) avoids a page cache miss, as the shop rows above do;
|
|
802
|
+
a query also reaches pages that read the id on the server:
|
|
755
803
|
|
|
756
804
|
```js
|
|
757
805
|
// On the listing page: link each item with its recommendation id
|
|
@@ -821,13 +869,21 @@ key on a format change makes old data invisible.
|
|
|
821
869
|
|
|
822
870
|
Budget: **6 KB gzip** after minification. The sources ship unminified with
|
|
823
871
|
full JSDoc: 58 KB raw in five files, 20 KB as the API serves them (gzip -9),
|
|
824
|
-
and the browser caches them
|
|
872
|
+
and the browser caches them. With comments stripped and no
|
|
825
873
|
minification they are 8.5 KB gzip. A bundler's minifier should bring
|
|
826
874
|
that under the budget, but this has not been measured: the repo has no
|
|
827
875
|
minifier, to keep zero dev dependencies.
|
|
828
876
|
|
|
829
877
|
## Changes
|
|
830
878
|
|
|
879
|
+
- 2026-11-07: version 0.6.6. With a public key, `recommend()` and the event
|
|
880
|
+
batches go out with `?key=` and `Content-Type: text/plain`, no `Authorization`,
|
|
881
|
+
so a browser skips the permission request before them: a visit's first list
|
|
882
|
+
arrives one network trip sooner ([How the key is sent](#how-the-key-is-sent)).
|
|
883
|
+
Nothing changes in your code, and a secret key keeps the header.
|
|
884
|
+
- 2026-11-05: version 0.6.5. A visitor's URL can't make `recommend()` or
|
|
885
|
+
`track()` throw: a `contextItemId` the API would refuse gets popular items
|
|
886
|
+
with no recommendation request, and such an `itemId` drops only that event.
|
|
831
887
|
- 2026-11-04: version 0.6.4. `recommend()` no longer rejects on a limit
|
|
832
888
|
(429) or a refused key (401, 403), and `popular()` no longer rejects on an
|
|
833
889
|
outage, a limit or a refused key: the page gets popular items or an empty
|
|
@@ -905,8 +961,8 @@ The same steps in real browsers (Chromium, Firefox, WebKit): see
|
|
|
905
961
|
[Testing](../../docs/development.md#testing).
|
|
906
962
|
|
|
907
963
|
The API embeds `src/*.js` (module `recapi/sdkjs`, `embed.go`) and serves
|
|
908
|
-
them at `/sdk/<version>/`, where browsers cache
|
|
909
|
-
change to `src/` needs a new version: bump `version` in `package.json`,
|
|
964
|
+
them at `/sdk/<version>/`, where browsers cache every file but `index.js` for
|
|
965
|
+
a year. So a change to `src/` needs a new version: bump `version` in `package.json`,
|
|
910
966
|
add the entry the failing Go test `TestSDKChangesNeedANewVersion` prints
|
|
911
967
|
to `published.json` (the digest is `sha256sum src/*.js | sha256sum`, then
|
|
912
968
|
each file's exports), and change the `/sdk/<version>/` paths in this
|
package/package.json
CHANGED
package/src/client.js
CHANGED
|
@@ -153,6 +153,9 @@ export function createClient(options) {
|
|
|
153
153
|
}
|
|
154
154
|
};
|
|
155
155
|
const transport = createTransport({ baseUrl, apiKey, fetch: fetchImpl, timeoutMs });
|
|
156
|
+
// A public key goes in the URL (no CORS preflight; popular() is CDN-cacheable),
|
|
157
|
+
// any other key in the header (Node with a secret key).
|
|
158
|
+
const auth = apiKey.startsWith(PUBLIC_KEY_PREFIX) ? 'query' : 'header';
|
|
156
159
|
const popularCache = serverCacheMode();
|
|
157
160
|
// The default adapter probes localStorage with a write, so it is picked at
|
|
158
161
|
// the first storage access: never before consent, nor under Do Not Track.
|
|
@@ -290,7 +293,7 @@ export function createClient(options) {
|
|
|
290
293
|
* away still completes.
|
|
291
294
|
*/
|
|
292
295
|
async function sendBatch(events, { retry }) {
|
|
293
|
-
const send = () => transport.request({ method: 'POST', path: '/v1/events', body: { events }, keepalive: true });
|
|
296
|
+
const send = () => transport.request({ method: 'POST', path: '/v1/events', auth, body: { events }, keepalive: true });
|
|
294
297
|
const response = retry ? await withRetry(send, { sleep }) : await send();
|
|
295
298
|
if (response?.rejected?.length) {
|
|
296
299
|
report(new RecapiError('event_rejected', `${response.rejected.length} event(s) rejected`, {
|
|
@@ -363,6 +366,7 @@ export function createClient(options) {
|
|
|
363
366
|
const response = await transport.request({
|
|
364
367
|
method: 'POST',
|
|
365
368
|
path: '/v1/recommendations',
|
|
369
|
+
auth,
|
|
366
370
|
timeoutMs: deadline,
|
|
367
371
|
body: compact({
|
|
368
372
|
user_id: userId ?? undefined,
|
|
@@ -423,16 +427,33 @@ export function createClient(options) {
|
|
|
423
427
|
.map((item) => toItem(item, 'backfill'));
|
|
424
428
|
}
|
|
425
429
|
|
|
430
|
+
/** What `recommend()` answers instead of a list of its own: popular items, or none. */
|
|
431
|
+
async function listInstead(error, params, deadline) {
|
|
432
|
+
reportList(error);
|
|
433
|
+
let items = [];
|
|
434
|
+
// A refused key would be refused the popular list too.
|
|
435
|
+
if (!keyRefused(error)) {
|
|
436
|
+
try {
|
|
437
|
+
items = await popularFallback(params, deadline);
|
|
438
|
+
} catch (fallbackError) {
|
|
439
|
+
// Down altogether, or the limit covers popular too. The page awaits
|
|
440
|
+
// recommend() without a catch (the README says it may), so an empty
|
|
441
|
+
// list it can hide beats a rejection that breaks it.
|
|
442
|
+
reportList(fallbackError);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return { recommendationId: null, fallback: true, items };
|
|
446
|
+
}
|
|
447
|
+
|
|
426
448
|
/**
|
|
427
449
|
* `GET /v1/popular` for `popular()` and the fallback; `deadline` defaults
|
|
428
|
-
* to `timeoutMs`.
|
|
429
|
-
* CORS preflight); any other key in the header (Node with a secret key).
|
|
450
|
+
* to `timeoutMs`.
|
|
430
451
|
*/
|
|
431
452
|
async function fetchPopular({ tagsAny, tagsAll, count }, deadline) {
|
|
432
453
|
const response = await transport.request({
|
|
433
454
|
method: 'GET',
|
|
434
455
|
path: '/v1/popular',
|
|
435
|
-
auth
|
|
456
|
+
auth,
|
|
436
457
|
cache: popularCache,
|
|
437
458
|
timeoutMs: deadline,
|
|
438
459
|
query: { tags_any: tagsAny?.join(','), tags_all: tagsAll?.join(','), count }
|
|
@@ -462,6 +483,8 @@ export function createClient(options) {
|
|
|
462
483
|
* interested"): the item is never recommended to this user again until
|
|
463
484
|
* a positive event on it. Don't send skips or bounces as rejections.
|
|
464
485
|
* Does nothing under Do Not Track (see `respectDoNotTrack`).
|
|
486
|
+
* An `itemId` the API would refuse (a page often takes it from a
|
|
487
|
+
* visitor's URL) drops the event and goes to `onError`, without throwing.
|
|
465
488
|
* @param {{ recommendationId?: string | null }} [options] Overrides the
|
|
466
489
|
* automatic attribution. `null` (a fallback list's id) is no override.
|
|
467
490
|
*/
|
|
@@ -470,7 +493,6 @@ export function createClient(options) {
|
|
|
470
493
|
// A fallback list has a null id, and a page passing it on must not
|
|
471
494
|
// send `null` or lose the item's earlier, real attribution.
|
|
472
495
|
const recommendationId = explicit ?? undefined;
|
|
473
|
-
if (!isId(itemId)) throw new RecapiError('invalid_request', 'itemId must be 1-256 bytes of UTF-8 without control characters');
|
|
474
496
|
if (typeof level === 'string' && Object.hasOwn(LEVEL_NAMES, level)) level = LEVEL_NAMES[level];
|
|
475
497
|
if (!Number.isInteger(level) || level < -10 || level > 10) {
|
|
476
498
|
throw new RecapiError(
|
|
@@ -478,6 +500,13 @@ export function createClient(options) {
|
|
|
478
500
|
"level must be an integer between -10 and 10, or 'view', 'cart', 'purchase' or 'reject'"
|
|
479
501
|
);
|
|
480
502
|
}
|
|
503
|
+
// A page often takes this id from a visitor's URL, so a crafted link
|
|
504
|
+
// must not fail it. Nothing is kept: in the history it would make the
|
|
505
|
+
// API refuse every later list. The line never quotes the visitor's id.
|
|
506
|
+
if (!isId(itemId)) {
|
|
507
|
+
report(new RecapiError('invalid_request', idRule('itemId')), true);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
481
510
|
if (quiet) return;
|
|
482
511
|
const t = now();
|
|
483
512
|
let attributed = recommendationId;
|
|
@@ -507,8 +536,10 @@ export function createClient(options) {
|
|
|
507
536
|
* `fallback: true` and no recommendation id, and reports the error to
|
|
508
537
|
* `onError`. When the popular request fails too, the list is empty: hide
|
|
509
538
|
* the slot. On a 401 or 403 (a revoked key, a suspended shop) the list is
|
|
510
|
-
* empty at once.
|
|
511
|
-
*
|
|
539
|
+
* empty at once. A `contextItemId` the API would refuse (a page often takes
|
|
540
|
+
* it from a visitor's URL) is never sent: the answer is the same popular
|
|
541
|
+
* list. Other errors still reject: a bad request or a reply that isn't the
|
|
542
|
+
* API's can't start on a live site without a deploy.
|
|
512
543
|
*
|
|
513
544
|
* @param {{ count?: number, tagsAny?: string[], tagsAll?: string[], exclude?: string[],
|
|
514
545
|
* contextItemId?: string, placement?: string, discovery?: number }} [params]
|
|
@@ -518,24 +549,17 @@ export function createClient(options) {
|
|
|
518
549
|
async recommend(params = {}) {
|
|
519
550
|
start();
|
|
520
551
|
const deadline = Math.min(timeoutMs, RECOMMEND_TIMEOUT_MS);
|
|
552
|
+
if (!usableContext(params.contextItemId)) {
|
|
553
|
+
// Unlike a failed call, nothing has read the stored rejections yet.
|
|
554
|
+
if (consent) reload();
|
|
555
|
+
const error = new RecapiError('invalid_request', idRule('contextItemId'));
|
|
556
|
+
return listInstead(error, { ...params, contextItemId: undefined }, deadline);
|
|
557
|
+
}
|
|
521
558
|
try {
|
|
522
559
|
return await personalised(params, deadline);
|
|
523
560
|
} catch (error) {
|
|
524
561
|
if (!sparesThePage(error)) throw error;
|
|
525
|
-
|
|
526
|
-
let items = [];
|
|
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
|
-
}
|
|
537
|
-
}
|
|
538
|
-
return { recommendationId: null, fallback: true, items };
|
|
562
|
+
return listInstead(error, params, deadline);
|
|
539
563
|
}
|
|
540
564
|
},
|
|
541
565
|
|
|
@@ -701,6 +725,21 @@ function toItem({ item_id: itemId, score, why, metadata }, slot) {
|
|
|
701
725
|
return item;
|
|
702
726
|
}
|
|
703
727
|
|
|
728
|
+
/** The API's rule for ids, for messages that never quote the id: a visitor may have written it. */
|
|
729
|
+
function idRule(name) {
|
|
730
|
+
return `${name} must be 1-256 bytes of UTF-8 without control characters`;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Whether the API would take this as a context item: an id, or nothing (an
|
|
735
|
+
* empty string reads as no context item).
|
|
736
|
+
*
|
|
737
|
+
* @param {unknown} id
|
|
738
|
+
*/
|
|
739
|
+
function usableContext(id) {
|
|
740
|
+
return id === undefined || id === null || id === '' || isId(id);
|
|
741
|
+
}
|
|
742
|
+
|
|
704
743
|
/**
|
|
705
744
|
* Whether `recommend()` and `popular()` answer this failure with a list instead
|
|
706
745
|
* of rejecting. An outage, a limit or a refused key can start on a live site
|
package/src/transport.js
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* HTTP layer: fetch with timeout, JSON, error mapping and retry.
|
|
3
3
|
*
|
|
4
|
+
* A public key travels as `?key=` and a body as `text/plain`, because a browser
|
|
5
|
+
* sends such a call to another origin at once. `Authorization` or
|
|
6
|
+
* `Content-Type: application/json` would make it ask permission first (the CORS
|
|
7
|
+
* preflight), one more network trip before a visit's first list and events.
|
|
8
|
+
* The body is still JSON: the API doesn't read the `Content-Type`.
|
|
9
|
+
*
|
|
4
10
|
* Page-hide flushing uses `fetch(..., { keepalive: true })` rather than
|
|
5
|
-
* `navigator.sendBeacon`: a beacon cannot carry the `Authorization` header
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
11
|
+
* `navigator.sendBeacon`: a beacon cannot carry the `Authorization` header a
|
|
12
|
+
* secret key needs, and a keepalive fetch survives page unload like a beacon
|
|
13
|
+
* does, as long as in-flight keepalive bodies stay under the browser's 64 KiB
|
|
14
|
+
* budget.
|
|
9
15
|
*
|
|
10
16
|
* @module transport
|
|
11
17
|
*/
|
|
@@ -62,8 +68,9 @@ export class RecapiError extends Error {
|
|
|
62
68
|
* @property {string} path
|
|
63
69
|
* @property {Record<string, string | number | undefined>} [query]
|
|
64
70
|
* @property {unknown} [body]
|
|
65
|
-
* @property {'header' | 'query'} [auth] `query` sends `?key
|
|
66
|
-
*
|
|
71
|
+
* @property {'header' | 'query'} [auth] `query` sends `?key=`, and a body as
|
|
72
|
+
* `text/plain`, so the call needs no CORS preflight and a GET's response is
|
|
73
|
+
* CDN-cacheable. Only for a public key: the API refuses a secret key in a URL.
|
|
67
74
|
* @property {boolean} [keepalive] Let the request outlive the page.
|
|
68
75
|
* @property {RequestCache} [cache] fetch's cache mode; the runtime's default when unset.
|
|
69
76
|
* @property {number} [timeoutMs]
|
|
@@ -92,7 +99,7 @@ export function createTransport({ baseUrl, apiKey, fetch, timeoutMs: defaultTime
|
|
|
92
99
|
const init = { method, headers };
|
|
93
100
|
if (cache) init.cache = cache;
|
|
94
101
|
if (body !== undefined) {
|
|
95
|
-
headers['Content-Type'] = 'application/json';
|
|
102
|
+
headers['Content-Type'] = auth === 'query' ? 'text/plain' : 'application/json';
|
|
96
103
|
init.body = JSON.stringify(body);
|
|
97
104
|
if (keepalive && byteLength(init.body) <= KEEPALIVE_MAX_BYTES) init.keepalive = true;
|
|
98
105
|
}
|