@findlane/browser 0.27.1 → 0.28.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/dist/images.d.ts CHANGED
@@ -8,6 +8,20 @@ export declare function imageWidth(width: number): 48 | 64 | 96 | 128 | 160 | 19
8
8
  export declare const imageHostsHeader = "x-findlane-images";
9
9
  /** The hosts an `x-findlane-images` header names; empty without one. */
10
10
  export declare function imageHostsOf(header: string | null | undefined): Set<string>;
11
+ /** The header naming where the index's optimized images load from (0.28.0), such as https://images.findlane.dev.
12
+ * Without it they load from the API's own origin. */
13
+ export declare const imageOriginHeader = "x-findlane-image-origin";
14
+ /** The origin an `x-findlane-image-origin` header names, or null for none or one that isn't an http(s) origin. */
15
+ export declare function imageOriginOf(header: string | null | undefined): string | null;
16
+ /** Where an index's images loaded from on an earlier page, kept in this browser (localStorage), so the next page
17
+ * can open that connection before its first answer says; null when unknown or without storage. */
18
+ export declare function rememberedImageOrigin(id: string): string | null;
19
+ /** Keeps where an index's images load from for later pages, or forgets it (null) once the index has none. */
20
+ export declare function rememberImageOrigin(id: string, origin: string | null): void;
21
+ /** Opens a connection to `origin` before a request needs it, as a preconnect hint in the page would: once per page,
22
+ * nothing outside a browser. Without credentials, as searches and optimized images are sent, so they use it. */
23
+ export declare function preconnect(origin: string): void;
11
24
  /** An image's optimized address: `src` resized to `width` (rounded up to a made width) by the image Worker
12
- * at `apiOrigin`, or null when `src` isn't an http(s) address on one of `hosts`. */
13
- export declare function optimizedImageUrl(apiOrigin: string, publicId: string, hosts: Set<string>, src: unknown, width: number): string | null;
25
+ * at `origin` (the one the API names, else the API's own), or null when `src` isn't an http(s) address on one of
26
+ * `hosts`. */
27
+ export declare function optimizedImageUrl(origin: string, publicId: string, hosts: Set<string>, src: unknown, width: number): string | null;
package/dist/images.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Optimized images (0.27.0): an index's record images, resized and re-encoded at the edge
2
2
  // (workers/images), from the hosts its owner allows. Shared by the client, the React Image component,
3
- // the search widget and the image Worker, so all of them ask for the same few widths.
3
+ // the search widget and the image Worker, so all of them ask for the same few widths. Since 0.28.0 they load
4
+ // from the address the API names (images.findlane.dev), whose connection is opened ahead of need.
4
5
  /** The widths the image Worker makes, in pixels. Any other width is rounded up to one of these, so a
5
6
  * page's images share cached copies, and asking for odd widths can't make endless new ones. */
6
7
  export const imageWidths = [48, 64, 96, 128, 160, 192, 256, 320, 384, 480, 640, 768, 960, 1280, 1600];
@@ -15,9 +16,62 @@ export const imageHostsHeader = "x-findlane-images";
15
16
  export function imageHostsOf(header) {
16
17
  return new Set((header ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(Boolean));
17
18
  }
19
+ /** The header naming where the index's optimized images load from (0.28.0), such as https://images.findlane.dev.
20
+ * Without it they load from the API's own origin. */
21
+ export const imageOriginHeader = "x-findlane-image-origin";
22
+ /** The origin an `x-findlane-image-origin` header names, or null for none or one that isn't an http(s) origin. */
23
+ export function imageOriginOf(header) {
24
+ if (!header)
25
+ return null;
26
+ try {
27
+ const url = new URL(header.trim());
28
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ const originKey = (id) => `findlane:image-origin:${id}`;
35
+ /** Where an index's images loaded from on an earlier page, kept in this browser (localStorage), so the next page
36
+ * can open that connection before its first answer says; null when unknown or without storage. */
37
+ export function rememberedImageOrigin(id) {
38
+ try {
39
+ return imageOriginOf(localStorage.getItem(originKey(id)));
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** Keeps where an index's images load from for later pages, or forgets it (null) once the index has none. */
46
+ export function rememberImageOrigin(id, origin) {
47
+ try {
48
+ if (origin)
49
+ localStorage.setItem(originKey(id), origin);
50
+ else
51
+ localStorage.removeItem(originKey(id));
52
+ }
53
+ catch {
54
+ // Storage that can't be used (a private window, a sandboxed frame): the next page opens it when it learns it.
55
+ }
56
+ }
57
+ /** Origins this page has opened a connection to ahead of need. */
58
+ const opened = new Set();
59
+ /** Opens a connection to `origin` before a request needs it, as a preconnect hint in the page would: once per page,
60
+ * nothing outside a browser. Without credentials, as searches and optimized images are sent, so they use it. */
61
+ export function preconnect(origin) {
62
+ if (typeof document === "undefined" || opened.has(origin))
63
+ return;
64
+ opened.add(origin);
65
+ const link = document.createElement("link");
66
+ link.rel = "preconnect";
67
+ link.href = origin;
68
+ link.crossOrigin = "anonymous";
69
+ document.head.append(link);
70
+ }
18
71
  /** An image's optimized address: `src` resized to `width` (rounded up to a made width) by the image Worker
19
- * at `apiOrigin`, or null when `src` isn't an http(s) address on one of `hosts`. */
20
- export function optimizedImageUrl(apiOrigin, publicId, hosts, src, width) {
72
+ * at `origin` (the one the API names, else the API's own), or null when `src` isn't an http(s) address on one of
73
+ * `hosts`. */
74
+ export function optimizedImageUrl(origin, publicId, hosts, src, width) {
21
75
  if (typeof src !== "string" || !hosts.size)
22
76
  return null;
23
77
  let url;
@@ -29,5 +83,5 @@ export function optimizedImageUrl(apiOrigin, publicId, hosts, src, width) {
29
83
  }
30
84
  if ((url.protocol !== "https:" && url.protocol !== "http:") || !hosts.has(url.hostname.toLowerCase()))
31
85
  return null;
32
- return `${apiOrigin}/img/${publicId}?url=${encodeURIComponent(src)}&w=${imageWidth(width)}`;
86
+ return `${origin}/img/${publicId}?url=${encodeURIComponent(src)}&w=${imageWidth(width)}`;
33
87
  }
package/dist/index.d.ts CHANGED
@@ -422,22 +422,33 @@ export declare class SearchBrowserClient {
422
422
  private test;
423
423
  /** The hosts the index's images may be loaded from resized, from the API's last answer (x-findlane-images). */
424
424
  private imageHosts;
425
+ /** Where they load from (x-findlane-image-origin, 0.28.0); the API's own origin without one. */
426
+ private imageOrigin;
427
+ /** Where they loaded from on an earlier page in this browser, read once; undefined until read. */
428
+ private knownImageOrigin;
425
429
  constructor(options: BrowserClientOptions);
426
430
  /** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
427
431
  * expires, or at once when `fresh`. */
428
432
  private signedKey;
429
433
  private post;
430
434
  private get;
431
- /** Each answer says which hosts the index's images may be loaded from resized; refusals say nothing. */
435
+ /** Each answer says which hosts the index's images may be loaded from resized, and where from (0.28.0); refusals
436
+ * say nothing. Where from is kept for later pages, and its connection opened now, before the results' images ask. */
432
437
  private noteImages;
438
+ private rememberedOrigin;
439
+ /** Opens the connection to where the index's images loaded from on an earlier page, with the first request or
440
+ * when a search box gets focus, so the results' first image doesn't wait for it. Nothing for an index without. */
441
+ private warmImages;
433
442
  /** Optimized images (0.27.0): a record image's address, resized to `width` pixels (rounded up to one of
434
- * `imageWidths`) and sent as WebP from the API's own address, when the index has optimized images on and the
435
- * image is on a host it allows; otherwise `src` as it is. Known from the first answer on, so build image
436
- * addresses from results, not before the first search. Load them with `crossorigin="anonymous"`, which
437
- * shares the connection searches use. React's `Image` does all of this. */
443
+ * `imageWidths`) and sent as WebP from the address the API names (images.findlane.dev since 0.28.0; the API's own
444
+ * before), when the index has optimized images on and the image is on a host it allows; otherwise `src` as it is.
445
+ * Known from the first answer on, so build image addresses from results, not before the first search. Load them
446
+ * with `crossorigin="anonymous"`, which uses the connection opened for them ahead of need. React's `Image` does all
447
+ * of this. */
438
448
  imageUrl(src: string, width: number): string;
439
449
  /** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
440
- * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. */
450
+ * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. Since 0.28.0 it
451
+ * also opens the one to where the index's images loaded from on an earlier page. */
441
452
  warm(): void;
442
453
  search<T = Record<string, unknown>>(request: SearchRequest, options?: {
443
454
  signal?: AbortSignal;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { imageHostsHeader, imageHostsOf, optimizedImageUrl } from "./images.js";
1
+ import { imageHostsHeader, imageHostsOf, imageOriginHeader, imageOriginOf, optimizedImageUrl, preconnect, rememberedImageOrigin, rememberImageOrigin } from "./images.js";
2
2
  export { imageWidth, imageWidths } from "./images.js";
3
3
  export { placeholderCss, placeholderUrl, revealCss } from "./placeholder.js";
4
4
  /** A query suggestion's text in parts: what was typed (`typed: true`) and the rest. */
@@ -272,8 +272,6 @@ function eventSender(url, fetcher, mode, ids, test) {
272
272
  flush,
273
273
  };
274
274
  }
275
- /** Origins this page has opened a connection to ahead of a search (warm). */
276
- const warmed = new Set();
277
275
  export class SearchBrowserClient {
278
276
  url;
279
277
  origin;
@@ -290,6 +288,10 @@ export class SearchBrowserClient {
290
288
  test;
291
289
  /** The hosts the index's images may be loaded from resized, from the API's last answer (x-findlane-images). */
292
290
  imageHosts = new Set();
291
+ /** Where they load from (x-findlane-image-origin, 0.28.0); the API's own origin without one. */
292
+ imageOrigin = null;
293
+ /** Where they loaded from on an earlier page in this browser, read once; undefined until read. */
294
+ knownImageOrigin;
293
295
  constructor(options) {
294
296
  if (!/^pub_[a-f0-9]{32}$/.test(options.publicId))
295
297
  throw new Error("A valid public index ID (pub_…) is required");
@@ -321,6 +323,7 @@ export class SearchBrowserClient {
321
323
  async post(operation, request, signal, renewed = false) {
322
324
  // A signed key goes in the body, so the request needs no preflight.
323
325
  const signing = operation === "search" || operation === "suggest" ? this.signedKey(renewed) : undefined;
326
+ this.warmImages();
324
327
  const response = await this.fetcher(`${this.url}/${operation}`, {
325
328
  method: "POST",
326
329
  // JSON as text/plain: browsers send it without asking the API first (a CORS preflight), which
@@ -341,6 +344,7 @@ export class SearchBrowserClient {
341
344
  // Lists are read with GET, which browsers send without a preflight and may keep for 30 seconds.
342
345
  async get(path, params, signal) {
343
346
  const query = new URLSearchParams(params).toString();
347
+ this.warmImages();
344
348
  const response = await this.fetcher(`${this.url}/${path}${query ? `?${query}` : ""}`, { method: "GET", signal });
345
349
  this.noteImages(response);
346
350
  const data = await response.json();
@@ -348,31 +352,47 @@ export class SearchBrowserClient {
348
352
  throw new FindlaneError(response.status, data.error ?? `HTTP ${response.status}`);
349
353
  return data;
350
354
  }
351
- /** Each answer says which hosts the index's images may be loaded from resized; refusals say nothing. */
355
+ /** Each answer says which hosts the index's images may be loaded from resized, and where from (0.28.0); refusals
356
+ * say nothing. Where from is kept for later pages, and its connection opened now, before the results' images ask. */
352
357
  noteImages(response) {
353
- if (response.ok)
354
- this.imageHosts = imageHostsOf(response.headers?.get(imageHostsHeader));
358
+ if (!response.ok)
359
+ return;
360
+ this.imageHosts = imageHostsOf(response.headers?.get(imageHostsHeader));
361
+ this.imageOrigin = this.imageHosts.size ? imageOriginOf(response.headers?.get(imageOriginHeader)) : null;
362
+ if (this.imageOrigin)
363
+ preconnect(this.imageOrigin);
364
+ if (this.imageOrigin !== this.rememberedOrigin()) {
365
+ rememberImageOrigin(this.publicId, this.imageOrigin);
366
+ this.knownImageOrigin = this.imageOrigin;
367
+ }
368
+ }
369
+ rememberedOrigin() {
370
+ if (this.knownImageOrigin === undefined)
371
+ this.knownImageOrigin = rememberedImageOrigin(this.publicId);
372
+ return this.knownImageOrigin;
373
+ }
374
+ /** Opens the connection to where the index's images loaded from on an earlier page, with the first request or
375
+ * when a search box gets focus, so the results' first image doesn't wait for it. Nothing for an index without. */
376
+ warmImages() {
377
+ const origin = this.rememberedOrigin();
378
+ if (origin)
379
+ preconnect(origin);
355
380
  }
356
381
  /** Optimized images (0.27.0): a record image's address, resized to `width` pixels (rounded up to one of
357
- * `imageWidths`) and sent as WebP from the API's own address, when the index has optimized images on and the
358
- * image is on a host it allows; otherwise `src` as it is. Known from the first answer on, so build image
359
- * addresses from results, not before the first search. Load them with `crossorigin="anonymous"`, which
360
- * shares the connection searches use. React's `Image` does all of this. */
382
+ * `imageWidths`) and sent as WebP from the address the API names (images.findlane.dev since 0.28.0; the API's own
383
+ * before), when the index has optimized images on and the image is on a host it allows; otherwise `src` as it is.
384
+ * Known from the first answer on, so build image addresses from results, not before the first search. Load them
385
+ * with `crossorigin="anonymous"`, which uses the connection opened for them ahead of need. React's `Image` does all
386
+ * of this. */
361
387
  imageUrl(src, width) {
362
- return optimizedImageUrl(this.origin, this.publicId, this.imageHosts, src, width) ?? src;
388
+ return optimizedImageUrl(this.imageOrigin ?? this.origin, this.publicId, this.imageHosts, src, width) ?? src;
363
389
  }
364
390
  /** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
365
- * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. */
391
+ * would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. Since 0.28.0 it
392
+ * also opens the one to where the index's images loaded from on an earlier page. */
366
393
  warm() {
367
- if (typeof document === "undefined" || warmed.has(this.origin))
368
- return;
369
- warmed.add(this.origin);
370
- const link = document.createElement("link");
371
- link.rel = "preconnect";
372
- link.href = this.origin;
373
- // Searches are sent without credentials, so they use the connection a crossorigin hint opens.
374
- link.crossOrigin = "anonymous";
375
- document.head.append(link);
394
+ preconnect(this.origin);
395
+ this.warmImages();
376
396
  }
377
397
  async search(request, options = {}) {
378
398
  const response = await this.post("search", request, options.signal);
@@ -38,7 +38,7 @@ export function Image({ src, width, client: given, placeholder, alt = "", loadin
38
38
  const waiting = preview !== null && loaded !== one;
39
39
  const ours = waiting ? placeholderStyle(preview) : revealing ? revealStyle : undefined;
40
40
  return (_jsx("img", { ...rest, src: one, srcSet: two !== one ? `${one} 1x, ${two} 2x` : undefined, width: width, alt: alt, loading: loading, decoding: decoding, style: ours ? { ...ours, ...style } : style,
41
- // Searches are sent without credentials, so an image sent without them comes over the same connection.
41
+ // Without credentials, as the client opened the image host's connection ahead of need, so the image uses it.
42
42
  crossOrigin: optimized ? "anonymous" : undefined,
43
43
  // An image the browser had already shows at once, without its placeholder.
44
44
  ref: waiting ? (node) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@findlane/browser",
3
- "version": "0.27.1",
3
+ "version": "0.28.0",
4
4
  "description": "Findlane browser SDK: fast, typo-tolerant public search from the browser with an index's public ID, plus React hooks and components.",
5
5
  "keywords": ["findlane", "search", "full-text search", "typo tolerance", "instant search", "ecommerce search", "browser", "react", "autocomplete"],
6
6
  "license": "MIT",