@blotoutio/providers-evo-search-sdk 1.64.2 → 1.65.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/core.cjs.js +234 -49
- package/core.js +234 -49
- package/core.mjs +234 -49
- package/hooks.d.ts +2 -1
- package/index.cjs.js +281 -136
- package/index.js +281 -136
- package/index.mjs +281 -136
- package/package.json +1 -1
package/core.cjs.js
CHANGED
|
@@ -634,6 +634,95 @@ const notifyReady = () => {
|
|
|
634
634
|
notifySubscribers(registry.subscribers, 'notifyReady');
|
|
635
635
|
};
|
|
636
636
|
|
|
637
|
+
// Resilience wrapper for /search requests. A transient network failure or a
|
|
638
|
+
// hung request must not wedge the UI: add a per-attempt timeout (a hang becomes
|
|
639
|
+
// a rejection), retry transient failures with backoff, and never retry a
|
|
640
|
+
// caller-superseded (aborted) request. Shared by the widget and the headless
|
|
641
|
+
// hook. See callers: search-widget.ts (performAutocomplete) and
|
|
642
|
+
// hooks/use-evo-search.ts.
|
|
643
|
+
const DEFAULTS = {
|
|
644
|
+
timeoutMs: 7000,
|
|
645
|
+
retries: 2,
|
|
646
|
+
backoffMs: [400, 1200],
|
|
647
|
+
};
|
|
648
|
+
// Deterministic HTTP errors (4xx other than 429) will never succeed on
|
|
649
|
+
// retry — only retry timeouts, network errors, 429, and 5xx. Errors without
|
|
650
|
+
// an attached `status` (network/timeout failures) are always retryable.
|
|
651
|
+
const isRetryable = (error) => {
|
|
652
|
+
const status = error === null || error === void 0 ? void 0 : error.status;
|
|
653
|
+
return status == null || status === 429 || status >= 500;
|
|
654
|
+
};
|
|
655
|
+
const delay = (ms, signal) => new Promise((resolve, reject) => {
|
|
656
|
+
if (signal.aborted)
|
|
657
|
+
return reject(new DOMException('Aborted', 'AbortError'));
|
|
658
|
+
const t = setTimeout(resolve, ms);
|
|
659
|
+
signal.addEventListener('abort', () => {
|
|
660
|
+
clearTimeout(t);
|
|
661
|
+
reject(new DOMException('Aborted', 'AbortError'));
|
|
662
|
+
}, { once: true });
|
|
663
|
+
});
|
|
664
|
+
/**
|
|
665
|
+
* Run `attempt` with a timeout, retrying transient failures. `callerSignal`
|
|
666
|
+
* supersedes everything: if it aborts, we stop immediately without retrying
|
|
667
|
+
* (the query changed / the widget cleaned up). A timeout or network error is
|
|
668
|
+
* retried up to `retries` times; anything left over is rethrown.
|
|
669
|
+
*/
|
|
670
|
+
async function withSearchResilience(attempt, callerSignal, options = {}) {
|
|
671
|
+
var _a, _b;
|
|
672
|
+
const { timeoutMs, retries, backoffMs } = { ...DEFAULTS, ...options };
|
|
673
|
+
let lastError;
|
|
674
|
+
for (let i = 0; i <= retries; i++) {
|
|
675
|
+
if (callerSignal.aborted)
|
|
676
|
+
throw new DOMException('Aborted', 'AbortError');
|
|
677
|
+
const local = new AbortController();
|
|
678
|
+
const onCallerAbort = () => local.abort();
|
|
679
|
+
callerSignal.addEventListener('abort', onCallerAbort, { once: true });
|
|
680
|
+
// Race the attempt against an explicit timeout that REJECTS. Aborting the
|
|
681
|
+
// signal alone isn't enough — an attempt that ignores its signal would
|
|
682
|
+
// otherwise hang forever and never retry. Reject with a TimeoutError (not
|
|
683
|
+
// an AbortError) so callers surface it instead of treating it as a
|
|
684
|
+
// caller-cancellation.
|
|
685
|
+
let timer;
|
|
686
|
+
const timeout = new Promise((_, reject) => {
|
|
687
|
+
timer = setTimeout(() => {
|
|
688
|
+
local.abort(); // still cancel the in-flight request to free the socket
|
|
689
|
+
reject(new DOMException('Search request timed out', 'TimeoutError'));
|
|
690
|
+
}, timeoutMs);
|
|
691
|
+
});
|
|
692
|
+
try {
|
|
693
|
+
return await Promise.race([attempt(local.signal), timeout]);
|
|
694
|
+
}
|
|
695
|
+
catch (error) {
|
|
696
|
+
lastError = error;
|
|
697
|
+
// The caller superseded this request — do not retry, propagate the abort.
|
|
698
|
+
if (callerSignal.aborted)
|
|
699
|
+
throw error;
|
|
700
|
+
// Otherwise it was a timeout or a transient network error: retry if budget remains.
|
|
701
|
+
if (i < retries && isRetryable(error)) {
|
|
702
|
+
const wait = (_b = (_a = backoffMs[i]) !== null && _a !== void 0 ? _a : backoffMs[backoffMs.length - 1]) !== null && _b !== void 0 ? _b : 0;
|
|
703
|
+
// Rejects with an AbortError if the caller aborts mid-backoff —
|
|
704
|
+
// propagate that cancellation instead of the transient `error` above.
|
|
705
|
+
await delay(wait, callerSignal);
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
throw error;
|
|
709
|
+
}
|
|
710
|
+
finally {
|
|
711
|
+
clearTimeout(timer);
|
|
712
|
+
callerSignal.removeEventListener('abort', onCallerAbort);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
throw lastError;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// Client-side deadlines for the Ask SSE path. `/search` already gets these via
|
|
719
|
+
// withSearchResilience; Ask is the streaming counterpart. The request timeout
|
|
720
|
+
// matches the resilience wrapper's per-attempt budget; the idle timeout catches
|
|
721
|
+
// a stream that stalls mid-flight without a terminal frame and resets on every
|
|
722
|
+
// chunk. Both surface a TimeoutError (not an AbortError) so submitAsk routes
|
|
723
|
+
// them to the search fallback instead of treating them as caller-cancellation.
|
|
724
|
+
const ASK_REQUEST_TIMEOUT_MS = 7000;
|
|
725
|
+
const ASK_SSE_IDLE_TIMEOUT_MS = 10000;
|
|
637
726
|
// Always defer to what the storefront itself is rendering — same source
|
|
638
727
|
// shop-gpt reads from. Two widgets on the same page would otherwise drift:
|
|
639
728
|
// shop-gpt picks Shopify, evo-search would pick its own override and show
|
|
@@ -661,15 +750,28 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
|
|
|
661
750
|
if (!sendTag) {
|
|
662
751
|
throw new Error('sendTag missing');
|
|
663
752
|
}
|
|
753
|
+
const getChannel = () => { var _a; return (((_a = window[registryKey]) === null || _a === void 0 ? void 0 : _a.ui) ? 'widget' : 'headless'); };
|
|
664
754
|
const getHeaders = () => {
|
|
665
|
-
var _a;
|
|
666
755
|
const headers = new Headers({ EdgeTagUserId: userId });
|
|
667
756
|
if (sessionId) {
|
|
668
757
|
headers.set('EdgeTagSessionId', sessionId);
|
|
669
758
|
}
|
|
670
|
-
headers.set('X-EvoSearch-Channel', (
|
|
759
|
+
headers.set('X-EvoSearch-Channel', getChannel());
|
|
671
760
|
return headers;
|
|
672
761
|
};
|
|
762
|
+
// Identity for the public read endpoints travels as query params instead of
|
|
763
|
+
// headers so the GET stays a CORS-simple request — no OPTIONS preflight,
|
|
764
|
+
// one connection attempt per keystroke instead of two (a hung transport
|
|
765
|
+
// path then wedges half as often, and withSearchResilience's retry isn't
|
|
766
|
+
// preceded by a second preflight). /user/* keeps the header form: the
|
|
767
|
+
// worker's cookie-HMAC auth binds to it, and those routes preflight anyway.
|
|
768
|
+
const setIdentityParams = (url) => {
|
|
769
|
+
url.searchParams.set('uid', userId);
|
|
770
|
+
if (sessionId) {
|
|
771
|
+
url.searchParams.set('sid', sessionId);
|
|
772
|
+
}
|
|
773
|
+
url.searchParams.set('channel', getChannel());
|
|
774
|
+
};
|
|
673
775
|
// Parsing `baseURL` once at API construction avoids re-parsing the host on
|
|
674
776
|
// every keystroke when `getURL` runs inside the autocomplete hot path.
|
|
675
777
|
const baseOrigin = new URL(baseURL).origin;
|
|
@@ -692,10 +794,14 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
|
|
|
692
794
|
for (const [key, value] of Object.entries(params !== null && params !== void 0 ? params : {})) {
|
|
693
795
|
url.searchParams.set(key, value);
|
|
694
796
|
}
|
|
797
|
+
const credentialed = needsCredentials(path);
|
|
798
|
+
if (!credentialed) {
|
|
799
|
+
setIdentityParams(url);
|
|
800
|
+
}
|
|
695
801
|
const response = await fetchImpl(url, {
|
|
696
802
|
method: 'GET',
|
|
697
|
-
headers: getHeaders(),
|
|
698
|
-
credentials:
|
|
803
|
+
...(credentialed ? { headers: getHeaders() } : {}),
|
|
804
|
+
credentials: credentialed ? 'include' : 'omit',
|
|
699
805
|
signal,
|
|
700
806
|
});
|
|
701
807
|
if (!response.ok) {
|
|
@@ -715,17 +821,38 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
|
|
|
715
821
|
logger.info('EvoSearch API: Fetching ask config');
|
|
716
822
|
return getJSON('/config', 'Config', undefined, signal);
|
|
717
823
|
};
|
|
718
|
-
//
|
|
719
|
-
// index off the request path
|
|
720
|
-
//
|
|
721
|
-
//
|
|
824
|
+
// Isolate warmer doubling as connection establisher: primes the worker's
|
|
825
|
+
// search index off the request path AND opens the h2/h3 connection before
|
|
826
|
+
// the first real keystroke needs it. Runs under the resilience wrapper so a
|
|
827
|
+
// black-holed connection attempt (hung QUIC/IPv6 path) is aborted and
|
|
828
|
+
// retried — the retry is what lets the browser fall back to a working
|
|
829
|
+
// transport while the shopper is still reaching for the search box. Any
|
|
830
|
+
// HTTP response counts as success: even an error status proves the
|
|
831
|
+
// connection is established. Never rejects; concurrent triggers (open,
|
|
832
|
+
// focus, first keystroke, keep-warm tick) coalesce into one attempt.
|
|
833
|
+
let warmInFlight = null;
|
|
834
|
+
let warmAbort = null;
|
|
722
835
|
const warm = () => {
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
836
|
+
if (warmInFlight) {
|
|
837
|
+
return warmInFlight;
|
|
838
|
+
}
|
|
839
|
+
const url = getURL('/warm');
|
|
840
|
+
setIdentityParams(url);
|
|
841
|
+
warmAbort = new AbortController();
|
|
842
|
+
warmInFlight = withSearchResilience((signal) => fetchImpl(url, { method: 'GET', credentials: 'omit', signal }), warmAbort.signal)
|
|
843
|
+
.then(() => undefined)
|
|
844
|
+
.catch(() => undefined)
|
|
845
|
+
.finally(() => {
|
|
846
|
+
warmInFlight = null;
|
|
847
|
+
warmAbort = null;
|
|
848
|
+
});
|
|
849
|
+
return warmInFlight;
|
|
728
850
|
};
|
|
851
|
+
// Closing the widget must kill the chain: a black-holed attempt would
|
|
852
|
+
// otherwise keep re-establishing connections for the wrapper's full budget
|
|
853
|
+
// (~23s) after the overlay is gone — exactly the churn warm() exists to
|
|
854
|
+
// avoid. The next warm() mints a fresh controller.
|
|
855
|
+
const cancelWarm = () => warmAbort === null || warmAbort === void 0 ? void 0 : warmAbort.abort();
|
|
729
856
|
const recents = (signal) => {
|
|
730
857
|
logger.info('EvoSearch API: Fetching recent searches');
|
|
731
858
|
return getJSON('/user/recents', 'Recents', undefined, signal);
|
|
@@ -766,50 +893,107 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
|
|
|
766
893
|
// reader, the for-await loop drops out, and the iterator returns.
|
|
767
894
|
async function* askStream(query, signal) {
|
|
768
895
|
const url = getURL('/ask');
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
signal,
|
|
779
|
-
});
|
|
780
|
-
if (!response.ok || !response.body) {
|
|
781
|
-
throw new Error(`Ask failed - ${response.status}`);
|
|
896
|
+
// One controller drives teardown for the whole stream: the caller's signal,
|
|
897
|
+
// the initial-request deadline, and the SSE idle timeout all abort through
|
|
898
|
+
// it, so a stall closes the fetch instead of hanging. `timedOut` lets us
|
|
899
|
+
// rethrow a TimeoutError rather than the AbortError the abort would raise.
|
|
900
|
+
const controller = new AbortController();
|
|
901
|
+
const onCallerAbort = () => controller.abort();
|
|
902
|
+
signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', onCallerAbort, { once: true });
|
|
903
|
+
if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
|
|
904
|
+
controller.abort();
|
|
782
905
|
}
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
906
|
+
let timedOut = false;
|
|
907
|
+
const initialTimer = setTimeout(() => {
|
|
908
|
+
timedOut = true;
|
|
909
|
+
controller.abort();
|
|
910
|
+
}, ASK_REQUEST_TIMEOUT_MS);
|
|
911
|
+
// Outer try guarantees the caller-signal listener is removed on EVERY exit
|
|
912
|
+
// path. It's `{ once: true }`, so a caller abort auto-removes it — but the
|
|
913
|
+
// initial-timeout, network-error, and non-ok paths never fire the abort
|
|
914
|
+
// event, so without this they'd leak a listener on a long-lived shared
|
|
915
|
+
// signal (one per Ask query).
|
|
787
916
|
try {
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
917
|
+
let response;
|
|
918
|
+
try {
|
|
919
|
+
response = await fetchImpl(url, {
|
|
920
|
+
method: 'POST',
|
|
921
|
+
headers: (() => {
|
|
922
|
+
const h = getHeaders();
|
|
923
|
+
h.set('Content-Type', 'application/json');
|
|
924
|
+
return h;
|
|
925
|
+
})(),
|
|
926
|
+
body: JSON.stringify({ query }),
|
|
927
|
+
credentials: 'omit',
|
|
928
|
+
signal: controller.signal,
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
catch (error) {
|
|
932
|
+
if (timedOut) {
|
|
933
|
+
throw new DOMException('Ask request timed out', 'TimeoutError');
|
|
792
934
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
935
|
+
throw error;
|
|
936
|
+
}
|
|
937
|
+
finally {
|
|
938
|
+
// The idle timeout takes over once the response resolves.
|
|
939
|
+
clearTimeout(initialTimer);
|
|
940
|
+
}
|
|
941
|
+
if (!response.ok || !response.body) {
|
|
942
|
+
throw new Error(`Ask failed - ${response.status}`);
|
|
943
|
+
}
|
|
944
|
+
const reader = response.body
|
|
945
|
+
.pipeThrough(new TextDecoderStream())
|
|
946
|
+
.getReader();
|
|
947
|
+
let buffer = '';
|
|
948
|
+
try {
|
|
949
|
+
while (true) {
|
|
950
|
+
// Idle timeout, reset every chunk: a stream that stalls mid-flight
|
|
951
|
+
// (no terminal frame) rejects here instead of freezing the skeleton.
|
|
952
|
+
let idleTimer;
|
|
953
|
+
const idle = new Promise((_, reject) => {
|
|
954
|
+
idleTimer = setTimeout(() => {
|
|
955
|
+
timedOut = true;
|
|
956
|
+
controller.abort();
|
|
957
|
+
reject(new DOMException('Ask stream stalled', 'TimeoutError'));
|
|
958
|
+
}, ASK_SSE_IDLE_TIMEOUT_MS);
|
|
959
|
+
});
|
|
960
|
+
let result;
|
|
961
|
+
try {
|
|
962
|
+
result = await Promise.race([reader.read(), idle]);
|
|
963
|
+
}
|
|
964
|
+
finally {
|
|
965
|
+
clearTimeout(idleTimer);
|
|
966
|
+
}
|
|
967
|
+
const { done, value } = result;
|
|
968
|
+
if (done) {
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
buffer += value;
|
|
972
|
+
let boundary = buffer.indexOf('\n\n');
|
|
973
|
+
while (boundary !== -1) {
|
|
974
|
+
const frame = buffer.slice(0, boundary);
|
|
975
|
+
buffer = buffer.slice(boundary + 2);
|
|
976
|
+
const event = parseSseFrame(frame);
|
|
977
|
+
if (event) {
|
|
978
|
+
yield event;
|
|
979
|
+
}
|
|
980
|
+
boundary = buffer.indexOf('\n\n');
|
|
801
981
|
}
|
|
802
|
-
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
finally {
|
|
985
|
+
try {
|
|
986
|
+
// cancel (not releaseLock) — safe with an outstanding read and tears
|
|
987
|
+
// down the upstream fetch on a caller-abort or idle timeout.
|
|
988
|
+
await reader.cancel();
|
|
989
|
+
}
|
|
990
|
+
catch {
|
|
991
|
+
// ignore — already closed
|
|
803
992
|
}
|
|
804
993
|
}
|
|
805
994
|
}
|
|
806
995
|
finally {
|
|
807
|
-
|
|
808
|
-
reader.releaseLock();
|
|
809
|
-
}
|
|
810
|
-
catch {
|
|
811
|
-
// ignore
|
|
812
|
-
}
|
|
996
|
+
signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onCallerAbort);
|
|
813
997
|
}
|
|
814
998
|
}
|
|
815
999
|
const sendEvent = (action, currency, actionData, clickData, beacon) => {
|
|
@@ -861,6 +1045,7 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
|
|
|
861
1045
|
trending,
|
|
862
1046
|
config,
|
|
863
1047
|
warm,
|
|
1048
|
+
cancelWarm,
|
|
864
1049
|
user: {
|
|
865
1050
|
recents,
|
|
866
1051
|
deleteRecent,
|