@depict-ai/utilishared 2.0.4 → 2.0.5

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.
@@ -0,0 +1,2578 @@
1
+ import { JSX, Accessor } from "solid-js";
2
+ export const version = "2.0.5";
3
+ export const is_debug: boolean;
4
+ /**
5
+ * Sets the prefix of dlog, dwarn, and derror messages in the browser console. Defaults to `[Depict]`.
6
+ */
7
+ export const set_browser_prefix: (str: any) => void;
8
+ export function dlog(...args: any[]): void;
9
+ export function dwarn(...args: any[]): void;
10
+ export function derror(...args: any[]): void;
11
+ /**
12
+ * Adds things to the object we send to backend in the query params to report the package versions used
13
+ */
14
+ export const version_info: {
15
+ [key: string]: string;
16
+ };
17
+ export function add_to_version_info(package_name: string, version: string): void;
18
+ /**
19
+ * Adds the version info to the query params of a URL
20
+ * @param url: a URL object or a string containing a relative or absolute URL
21
+ * @returns the same type as the input but with added query params
22
+ */
23
+ export function add_version_query_params<T extends string | URL>(url: T): T;
24
+ /**
25
+ * Encoding UTF8 ⇢ base64
26
+ */
27
+ export function base64_encode_unicode(str: any): string;
28
+ /**
29
+ * Decoding base64 ⇢ UTF8
30
+ */
31
+ export function base64_decode_unicode(str: any): string;
32
+ /**
33
+ * Class containing state that an IPNS operates on. It's only exported for type info and in case that you want to use it for instanceof checks.
34
+ * subscribers is an array of functions that get called every time push_value is called with a new value AND all previous subscribers are done
35
+ * queue is the queue of values that subscribers gets called with
36
+ * last_processed_value is the last value that the subscribers were called with
37
+ * push_value adds a new value to the queue and triggers the calling of the subscribers if they're done
38
+ * subscriber_done decrements the number of subscribers we are waiting for, if this isn't called call_subscribers will get stuck. It also triggers a new call to call_subscribers
39
+ */
40
+ export class RawObservableInformation<T> {
41
+ subscribers_: ((val: T) => void)[];
42
+ waiting_for_update_: number;
43
+ queue_: T[];
44
+ last_processed_value_: T | undefined;
45
+ has_had_value_: boolean;
46
+ push_value_: (value: T) => void;
47
+ call_subscribers_: () => void;
48
+ subscriber_done_: () => void;
49
+ }
50
+ /**
51
+ * Makes an asyncIterable function out of a RawObservableInformation instance
52
+ */
53
+ export function make_simple_async_iterable<T>(state: RawObservableInformation<T>): ((...values: T[]) => void) & {
54
+ [Symbol.asyncIterator](): {
55
+ next(): Promise<{
56
+ value: T;
57
+ done: false;
58
+ }>;
59
+ return(): Promise<{
60
+ value: T;
61
+ done: false;
62
+ }>;
63
+ };
64
+ };
65
+ /**
66
+ * You know how you can write `break` inside of a `for await` loop to exit it? Well, this lets you break the loop from outside. Pass any async iterable that never throws and you will get back a function and a specially proxied async iterable. Whenever you call the function all for await loops iterating the returned iterable will break. Note: This will add some extra ticks because awaiting thenable objects takes more ticks than awaiting promises.
67
+ * @param async_iterable The async iterable you want to make exitable
68
+ * @return An array containing a function, the exit function, and a wrapped async iterable
69
+ */
70
+ export function make_asyncIterable_exiter<T>(async_iterable: AsyncIterable<T>): [() => void, AsyncIterable<T>];
71
+ export type IPNS<T> = ((...values: T[]) => void) & AsyncIterable<T> & {
72
+ exit: () => void;
73
+ state: T | undefined;
74
+ latest_call_value: T | undefined;
75
+ };
76
+ /**
77
+ * Creates an async iterable IPNS with "the old" API (we should maybe create a new one? idk). BUT which is resistant against things taking more than one tick. Meaning you can use `await` in the `for await` body without missing values
78
+ * # More about IPNS
79
+ * It's a form of observable. Basically an infinite promise.
80
+ * You await it by using for-await and you resolve it (as often as you like) by calling it.
81
+ * List of random details:
82
+ * 1. You can call it as fast as you like, the values will propagate into the for-awaits once all for-awaits have finished processing the value
83
+ * 2. Giving it multiple arguments and calling it multiple times is the same thing
84
+ * 3. IPNS.exit(); is going to make all for-await loops currently awaiting it exit EXCEPT for ones with currently executing loop bodies. Means if you do `IPNS.exit()` it won't exit the current loop - for that you need to use `break`. It does not change the IPNS in any other way so you can continue using it afterwards.
85
+ * 4. You can use make_asyncIterable_exiter() to make individual for-await loop exit (stop awaiting the infinite promise) from the outside
86
+ * 5. You can of course break and return any time from the for-await to stop awaiting
87
+ * 6. IPNS.state gives you the value that's currently processed inside of the for-awaits from the outside
88
+ * 7. IPNS.latest_call_value is the value that the IPNS was last called with (it doesn't have to have propagated everywhere yet)
89
+ * @param exitable Whether the async iterator should return the currently resolving value on the first call or not
90
+ * @param {state_obj} RawObservableInformation instance that contains the actual inner values of the IPNS
91
+ * @return An IPNS.
92
+ */
93
+ export function async_iterable_ipns<T>(async_iterator_should_return_state_on_first_call?: boolean, state_obj?: RawObservableInformation<T>): IPNS<T>;
94
+ /**
95
+ * Takes an IPNS that always resolves with state on first await and returns one that's in sync with the first one and doesn't
96
+ * @param ipns IPNS to create "clone" of
97
+ * @return A "cloned" ipns with the desired state-behavior. Keep in mind that exiting this one will not exit the one that was cloned.
98
+ */
99
+ export function make_ipns_stateless<T>(ipns: IPNS<T>): IPNS<any>;
100
+ /**
101
+ * Takes an IPNS that doesn't resolve with state on first await and returns one that's in sync with the first one and does
102
+ * @param ipns IPNS to create "clone" of
103
+ * @return A "cloned" ipns with the desired state-behavior. Keep in mind that exiting this one will not exit the one that was cloned.
104
+ */
105
+ export function make_ipns_stateful<T>(ipns: IPNS<T>): IPNS<any>;
106
+ /**
107
+ * @deprecated please use report instead and provide a severity
108
+ */
109
+ export function err(exception: Error | any, error_for_stack?: Error): undefined;
110
+ /**
111
+ * is_available_in: this function returns a promise that resolves once a variable has been defined inside of an object - or instantly, if it's already defined.
112
+ * The function uses getters and setters instead of polling which means it doesn't waste any resources.
113
+ * If there are already getters or setters the function will proxy them, retaining their original functionality.
114
+ * Only drawback is you can only wait for the variable being defined once, not for every change.
115
+ * @param obj The base object to look in
116
+ * @param property The property to wait for first
117
+ * @param ...sub_objects_to_wait_for A list of further properties to wait for in the result of the last awaited thing
118
+ * @return A promise containing the value of the variable that has been defined
119
+ */
120
+ export function is_available_in(obj: Object, property: PropertyKey, ...sub_objects_to_wait_for: PropertyKey[]): any;
121
+ export function find_descriptor(obj: Object, prop: PropertyKey): PropertyDescriptor | undefined;
122
+ export function variable_setter_to_ipns<T>(obj: Object, variable: PropertyKey, async_iterator_should_return_state_on_first_call?: boolean): IPNS<T>;
123
+ export const Sentry: Hub | {
124
+ captureException: (...args: any[]) => void;
125
+ captureMessage: (...args: any[]) => void;
126
+ withScope: (...args: any[]) => void;
127
+ };
128
+ /**
129
+ * Severity level to send to sentry.
130
+ * We can also send `log`, `info`, `debug`, `critical` and `fatal` but we haven't had a need for it yet.
131
+ */
132
+ type Severity = "error" | "warning";
133
+ /**
134
+ * Wraps a function in a try/catch that sends the error to sentry.
135
+ * Also works for functions returning a promise/async functions.
136
+ * If the function threw the wrapped function will return `undefined`
137
+ * @param fn The function to wrap
138
+ * @param message The message of the sentry error
139
+ * @param severity The severity level to send to sentry
140
+ */
141
+ export function catchify<T extends any[], X>(fn: (...args: T) => X, message?: string, severity?: Severity): (...args: T) => X extends Promise<any> ? Promise<undefined | Awaited<X>> : X | undefined;
142
+ /**
143
+ * Send error message with given severity and extra info to sentry
144
+ * @param msg Error object to send to sentry or an array containing an error and a human-readable description for said error
145
+ * @param severity How severe the error is.
146
+ * - `"error"` - Things like not finding the market, unexpected product-id format. Even one of these errors is cause for concern.
147
+ * - `"warning"` - Things that we expect to happen _sometimes_, like network errors. A couple of them is normal,
148
+ * but if we suddenly get 1000s then that's an issue
149
+ * @param input_data An object with extra information to sent to sentry.
150
+ *
151
+ * @example
152
+ * report([err, "Got to few recs"], "warning", {
153
+ * product_id,
154
+ * })
155
+ */
156
+ export function report(msg: Error | [Error, string], severity: Severity, input_data?: {
157
+ [key: string]: any;
158
+ stack?: never;
159
+ }): void;
160
+ /**
161
+ * Gives a random number between min and max (potentially including min and max).
162
+ * @param min The minimum number.
163
+ * @param max The maximum number.
164
+ * @returns a random number
165
+ */
166
+ export function rand(min: number, max: number): number;
167
+ export type AsyncFunction<A extends any[], O> = (...args: A) => Promise<O>;
168
+ /**
169
+ * Wraps an async function and makes sure the returned wrapped function can only be "executing" once at the same time.
170
+ * @param the_function an async function to wrap
171
+ * @return The same function but wrapped so that it can only run once at once, no matter how often you call it
172
+ */
173
+ export function deparallelize<A extends any[], O>(the_function: AsyncFunction<A, O>): (...args: A) => Promise<Awaited<O> | undefined>;
174
+ /**
175
+ * Like deparallelize but it makes sure that the last call of the function, while it's busy, will be executed after it's no longer busy.
176
+ */
177
+ export function deparallelize_no_drop<A extends any[], O>(the_function: AsyncFunction<A, O>): (...args: A) => Promise<Awaited<O> | undefined>;
178
+ /**
179
+ * @deprecated use async_iterable_ipns instead. It has a nicer API and more of an ecosystem.
180
+ */
181
+ export class infinite_promise_no_skip<T> {
182
+ #private;
183
+ promise: Promise<T>;
184
+ resolve: (value: T) => void;
185
+ }
186
+ type ws_event_callback = typeof WebSocket.prototype.onmessage;
187
+ export interface AutoReconnectingWS {
188
+ onclose: ws_event_callback;
189
+ onerrror: ws_event_callback;
190
+ onmessage: ws_event_callback;
191
+ onopen: ws_event_callback;
192
+ }
193
+ export class AutoReconnectingWS extends EventTarget {
194
+ #private;
195
+ current_socket: WebSocket;
196
+ restart_ws: (arg0?: any) => any;
197
+ increase_fails(): void;
198
+ send(...args: Parameters<typeof WebSocket.prototype.send>): Promise<void>;
199
+ constructor(url: string, protocols?: string | string[], options?: {
200
+ max_backoff_ms?: number;
201
+ });
202
+ }
203
+ export class DepictAPIWS extends AutoReconnectingWS {
204
+ #private;
205
+ ensure_sent(payload: {
206
+ id: string;
207
+ event?: depict_body;
208
+ [key: string]: any;
209
+ }): Promise<any[]>;
210
+ constructor(...params: [url: ConstructorParameters<typeof AutoReconnectingWS>[0], protocols?: ConstructorParameters<typeof AutoReconnectingWS>[1], options?: ConstructorParameters<typeof AutoReconnectingWS>[2] & Partial<{
211
+ initial_retry_ms: number;
212
+ }>]);
213
+ }
214
+ /**
215
+ * Returns a random string
216
+ * @return A random string, containing a-z, 0-9 and occasionally a dot (`.`)
217
+ */
218
+ export function random_string(): string;
219
+ export function make_random_classname(): string;
220
+ export const base_url: string;
221
+ export type event_types = "page_view" | "click" | "add_to_cart" | "purchase" | "element_visible";
222
+ declare const allowed_keys: readonly ["tenant", "market", "type", "session_id", "product_id", "entity_identifiers", "url", "entity_price", "currency", "document_referrer", "document_width", "attribution_id", "recommendation_id", "click_location", "ab_test_group", "variant_ids", "transaction_id", "error_type", "detail", "recommendation_type", "search_result_id", "product_listing_result_id"];
223
+ export type depict_body = Partial<{ [K in (typeof allowed_keys)[number]]: any }>;
224
+ export type depict_payload = depict_body[];
225
+ type any_properties = {
226
+ [key: string]: any;
227
+ };
228
+ export type noisy_depict_payload = (depict_body & any_properties)[];
229
+ export const filter_depict_payload: (payload: noisy_depict_payload) => depict_payload | undefined;
230
+ export const send_websocket: (bodies: depict_payload) => Promise<void | undefined>;
231
+ export const send_depict_unfiltered: (payload: depict_payload, use_ws?: any) => boolean | Promise<void | undefined> | undefined;
232
+ export const foolproof_send_beacon: (url: string, payload: {
233
+ [key: string]: any;
234
+ }) => boolean | undefined;
235
+ export const send_depict: (payload: noisy_depict_payload, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
236
+ export let get_session_id: () => string;
237
+ export const set_session_id_fn: (newfn: () => string) => (() => string) | undefined;
238
+ export type TrackingEventContextData = {
239
+ session_id: string;
240
+ url: string;
241
+ document_width: number;
242
+ document_referrer: string;
243
+ };
244
+ export const get_tracking_event_context_data: () => TrackingEventContextData;
245
+ /**
246
+ * Sends a depict tracking event with prefilled data
247
+ */
248
+ export const depict_prefilled: (vars: Partial<{
249
+ type: any;
250
+ detail: any;
251
+ url: any;
252
+ currency: any;
253
+ tenant: any;
254
+ market: any;
255
+ session_id: any;
256
+ product_id: any;
257
+ entity_identifiers: any;
258
+ entity_price: any;
259
+ document_referrer: any;
260
+ document_width: any;
261
+ attribution_id: any;
262
+ recommendation_id: any;
263
+ click_location: any;
264
+ ab_test_group: any;
265
+ variant_ids: any;
266
+ transaction_id: any;
267
+ error_type: any;
268
+ recommendation_type: any;
269
+ search_result_id: any;
270
+ product_listing_result_id: any;
271
+ }> & {
272
+ [key: string]: any;
273
+ }, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
274
+ export const depict_click: (vars: Partial<{
275
+ type: any;
276
+ detail: any;
277
+ url: any;
278
+ currency: any;
279
+ tenant: any;
280
+ market: any;
281
+ session_id: any;
282
+ product_id: any;
283
+ entity_identifiers: any;
284
+ entity_price: any;
285
+ document_referrer: any;
286
+ document_width: any;
287
+ attribution_id: any;
288
+ recommendation_id: any;
289
+ click_location: any;
290
+ ab_test_group: any;
291
+ variant_ids: any;
292
+ transaction_id: any;
293
+ error_type: any;
294
+ recommendation_type: any;
295
+ search_result_id: any;
296
+ product_listing_result_id: any;
297
+ }> & {
298
+ [key: string]: any;
299
+ }) => boolean | Promise<void | undefined> | undefined;
300
+ export const depict_add_to_cart: (vars: Partial<{
301
+ type: any;
302
+ detail: any;
303
+ url: any;
304
+ currency: any;
305
+ tenant: any;
306
+ market: any;
307
+ session_id: any;
308
+ product_id: any;
309
+ entity_identifiers: any;
310
+ entity_price: any;
311
+ document_referrer: any;
312
+ document_width: any;
313
+ attribution_id: any;
314
+ recommendation_id: any;
315
+ click_location: any;
316
+ ab_test_group: any;
317
+ variant_ids: any;
318
+ transaction_id: any;
319
+ error_type: any;
320
+ recommendation_type: any;
321
+ search_result_id: any;
322
+ product_listing_result_id: any;
323
+ }> & {
324
+ [key: string]: any;
325
+ }) => boolean | Promise<void | undefined> | undefined;
326
+ export type ConsentObj = {
327
+ marketing: boolean;
328
+ necessary: boolean;
329
+ preferences: boolean;
330
+ statistics: boolean;
331
+ };
332
+ export function get_cookie(cookie_name: string): string | undefined;
333
+ export function Promise_Any<T>(promises: (T | PromiseLike<T>)[] | Iterable<T | PromiseLike<T>>): Promise<T>;
334
+ /**
335
+ * Broadcasts the product id of the current page to a BroadcastChannel `right_click_attribution`.
336
+ * This enables a page in another tab where right-clicking on a recommendation yielded to the opening of this page to send click tracking events.
337
+ */
338
+ export function broadcast_product_id(product_id: string): Promise<void>;
339
+ /**
340
+ * This function is a post processor for recommendation renderer which adds a "new tab listener" to the recommendations. That means that it will listen for right-and wheel clicks on the elements and if a tab opens (=broadcasts the product id) of the clicked product it emulates a click event (using contextmenu_callback)
341
+ * @param elements Elements that event listeners will be added on
342
+ * @param display The display to take the product_id from
343
+ * @param info InfoForProcessing to get Tenant instance out of
344
+ * @return `elements` 1:1
345
+ */
346
+ export function add_new_tab_listener(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info?: any, get_event_listener_remover?: (remover: VoidFunction) => void): NodeListOf<ChildNode> | Node_Array;
347
+ /**
348
+ * This is the event handler for the new tab tracking function (add_new_tab_listener)
349
+ * @param e Click event
350
+ * @param product_id product_id of clicked product
351
+ * @return A promise resolving to void after 60s or when the product id was broadcasted
352
+ */
353
+ export function contextmenu_callback(e: Event, product_id: string): Promise<void>;
354
+ /**
355
+ * Make parts of a type optional
356
+ *
357
+ * From: https://github.com/Microsoft/TypeScript/issues/25760#issuecomment-614417742
358
+ */
359
+ type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>;
360
+ export class ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
361
+ constructor(opts: {
362
+ element_: ElemType;
363
+ selector_: SelectorType;
364
+ disconnector_: Disconnector;
365
+ mutation_record_?: MutationRecord;
366
+ event_?: ListenerNames;
367
+ });
368
+ }
369
+ export interface ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
370
+ element: ElemType;
371
+ selector: SelectorType;
372
+ disconnector: Disconnector;
373
+ mutation_record?: MutationRecord;
374
+ event?: ListenerNames;
375
+ }
376
+ /**
377
+ * Element.querySelectorAll is broken in Chrome 37-latest, use this instead.
378
+ * Related bug: https://bugs.chromium.org/p/chromium/issues/detail?id=1286047
379
+ * @param element Quite broadly anything you'd normaly call querySelectorAll on, including "null"
380
+ * @param selector The selector to search for
381
+ * @return Stock return value
382
+ */
383
+ export function patched_querySelectorAll<T extends Element>(element: Element | Document | DocumentFragment | null, selector: string): NodeListOf<T> | T[] | undefined;
384
+ export interface ElementObserver {
385
+ /**
386
+ * Immediately calls the callback with an ElementObserverEvent for nodes existing in the DOM that match the provided selector OR are the selector,
387
+ * also calls the callback with an ElementObserverEvent whenever ANYTHING in the DOM occurs that makes an element match the provided selector.
388
+ * @param selector Selector string or element to listen for
389
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
390
+ */
391
+ onexists: EO_listener_also_taking_els;
392
+ /**
393
+ * Dispatches an ElementObserverEvent whenever a node is added to the DOM that matches the specified selector OR is the selector.
394
+ * @param selector CSS selector or element to observe
395
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
396
+ **/
397
+ oncreation: EO_listener_also_taking_els;
398
+ /**
399
+ * Dispatches an ElementObserverEvent whenever a node is removed from the DOM that matches the specified selector OR is the selector.
400
+ * @param selector CSS selector or element to observe
401
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
402
+ */
403
+ onremoved: EO_listener_also_taking_els;
404
+ /**
405
+ * Dispatches an ElementObserverEvent whenever a node that matches the specified selector or its children change in the DOM.
406
+ * @param selector CSS selector or element to observe
407
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
408
+ */
409
+ onchange: EO_listener;
410
+ /**
411
+ * Immediately calls the callback with an ElementObserverEvent on nodes that match the provided selector OR are the selector.
412
+ * @param selector Selector string or element to look for in the DOM
413
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
414
+ */
415
+ ifexists: EO_listener_also_taking_els;
416
+ /**
417
+ * Adds a territory to the observer. The observer will observe all elements in the new territory and the one it observed before. `ifexists` checks made in the past won't be made again. Add your shadow roots here on creation and `observer` will finds elements in them.
418
+ */
419
+ add_territory: (what: HTMLElement | Document | DocumentFragment) => void;
420
+ /**
421
+ * Removes a territory again. Useful for no longer observing shadow roots.
422
+ */
423
+ remove_territory: (what: HTMLElement | Document | DocumentFragment) => void;
424
+ /**
425
+ * See docs for observer.onexists. Will return a Promise that resolves to the element out of the first call of an observer.onexists callback.
426
+ * @param selector Selector string or element to wait for
427
+ * @param timeout timeout to stop listening and resolve the Promise with `undefined`
428
+ */
429
+ wait_for_element: <ElemType extends HTMLElement = HTMLElement>(selector: string | ElemType, timeout?: number) => Promise<ElemType>;
430
+ /**
431
+ * See docs for observer.on<listener>. Will return a Promise that resolves to the first element that matches the given listener and selector. I.e. `wait_for_listener("removed", ".old-recs");` will resolve to the first element matching `.old-recs` that is removed from the DOM
432
+ * @param listener one of the possible functions on ElementObserver that start with "on", without the "on". So "creation", "change", "exists" or "removed"
433
+ * @param selector String containing CSS selector
434
+ * @param timeout timeout to stop listening and resolve the Promise with `undefined`
435
+ */
436
+ wait_for_listener: <ElemType extends HTMLElement = HTMLElement, SelectorType = string | CallbackableNode>(listener: SelectorType extends CallbackableNode ? "creation" | "removed" : "exists" | "creation" | "removed" | "change", selector: SelectorType, timeout?: number) => Promise<ElemType>;
437
+ }
438
+ export class ElementObserver {
439
+ #private;
440
+ constructor({
441
+ territory
442
+ }?: {
443
+ territory?: HTMLElement | Document | DocumentFragment | (HTMLElement | Document | DocumentFragment)[];
444
+ });
445
+ }
446
+ type EO_listener = <ElemType extends HTMLElement = HTMLElement>(selector: string, callback: ObserverCallbackFunction<ElemType>) => Disconnector;
447
+ type EO_listener_also_taking_els = <ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode>(selector: SelectorType, callback: ObserverCallbackFunction<ElemType, SelectorType>) => Disconnector;
448
+ type ListenerNames = "exists" | "creation" | "removed" | "change";
449
+ type ObserverCallbackFunction<ElemType extends CallbackableNode, SelectorType extends string | CallbackableNode = string | CallbackableNode> = (event: ElementObserverEvent<ElemType, SelectorType>) => any;
450
+ export type Disconnector = () => unknown;
451
+ type CallbackableNode = Element | Text | Comment;
452
+ /**
453
+ * Epic alien tech that categorizes DOM mutations, allowing one to listen and quickly (+2 ticks in the microtask queue, all before paint) react to DOM mutations such as elements (matching a selector) being added, deleted or changed.
454
+ */
455
+ export const observer: ElementObserver;
456
+ /**
457
+ * Useful for the `thresholds` option of IntersectionObserver - if you want to be notified at a 10% change, call this and set num_steps to 10. Pls see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/thresholds
458
+ * @param numSteps How many steps (notifications) there should be between 0 and 100% intersection
459
+ * @return Stuff to give to IntersectionObserver
460
+ */
461
+ export function buildThresholdList(numSteps: number): number[];
462
+ /**
463
+ * A Post processor for Recommendation renderer to add impression tracking to all displays
464
+ */
465
+ export const impression_tracking_post_processor: RR_PostProcessor<any>;
466
+ interface ImpressionTrackingOptions {
467
+ /** The element to observe for impressions. */
468
+ element: HTMLElement;
469
+ /** The impression data to send to the api (this is combined with context data) */
470
+ data: ExplicitImpressionEventData;
471
+ /** When true the element will be observed by the IntersectionObserver only after it's inserted into the DOM.
472
+ * Sometimes with a pollyfilled IntersectionObserver it ignores elements that are not in the DOM yet.
473
+ * Defaults to true.
474
+ * */
475
+ wait_for_dom_insertion?: boolean;
476
+ }
477
+ /**
478
+ * Registers the passed element for impression tracking.
479
+ * The element will be observed for intersection with the viewport.
480
+ * Also handles sending the impression event.
481
+ *
482
+ * @return A function to stop observing the element for impressions
483
+ */
484
+ export const impression_track_element: ({
485
+ element,
486
+ data,
487
+ wait_for_dom_insertion
488
+ }: ImpressionTrackingOptions) => () => void;
489
+ /** The start and end visibility threshold for an intersection to count as an impression */
490
+ export let impression_threshold: number[];
491
+ export const set_impression_threshold: (start: number, end: number) => number[];
492
+ /** The minimum duration the element has to be visible above the thresholds before it counts as an impression */
493
+ export const has_to_be_intersecting_for = 500;
494
+ /** What explicit information is needed to form an ImpressionEvent */
495
+ export type ExplicitImpressionEventData = {
496
+ recommendation_type?: string;
497
+ entity_price?: number;
498
+ market?: string;
499
+ tenant?: string;
500
+ product_id?: string;
501
+ } & ({
502
+ recommendation_id: string;
503
+ } | {
504
+ search_result_id: string;
505
+ } | {
506
+ product_listing_result_id: string;
507
+ } | {
508
+ suggestions_result_id: string;
509
+ });
510
+ /** What an impression event looks like when sent to the api */
511
+ export type ImpressionEvent = {
512
+ /** The type for impression events should be element_visible */
513
+ type: "element_visible";
514
+ } & (ExplicitImpressionEventData | TrackingEventContextData);
515
+ /**
516
+ * Sends an impression event to the api.
517
+ *
518
+ * Impression events always use websockets.
519
+ */
520
+ export const send_impression_event: (data: Optional<ImpressionEvent, "type">) => void;
521
+ /**
522
+ * Adds an event listener to a given element (example: recommendation link) which adds the provided product_id and recommendation_id to the 'depict' localStorage object
523
+ * @param {HTMLElement} a_element - The element to listen on the "click event"
524
+ * @param {string} product_id - A unique identifier for the product which can be used to rerecognize it on the product page
525
+ * @param {string} recommendation_id - The recommendation ID of the recommendation
526
+ * @param {Function} additional_listener - An additional function to execute onclick
527
+ */
528
+ export function bind_tracking_to_link(a_element: Element, product_id: string, recommendation_id: string, additional_listener?: Function): ((e: Event) => void) | undefined;
529
+ export type A2CTrackingFunction = (product_id: string, recommendation_id: string, was_unmatching: boolean, event: Event) => any;
530
+ /**
531
+ * Adds an event listener to a given element (example: the purchase button) which calls `tracking_fn(product_id,recommendation_id)` if the product_id exists in the 'depict' localStorage object
532
+ * @param {HTMLElement} button - The element to listen on the "click event"
533
+ * @param {Function} get_product_id - A function to get the product_id of the current page/the product associated with the add to cart button
534
+ * @param {A2CTrackingFunction} tracking_fn - A function which gets executed on click of button
535
+ * @param {Boolean} [unmatching_tracking] - also call tracking_fn on products not found in localStorage.
536
+ */
537
+ export function bind_to_a2c_button(button: Element, get_product_id: (url?: string, e?: Event) => string | Promise<string>, tracking_fn: A2CTrackingFunction, unmatching_tracking?: boolean, event?: string): Promise<void>;
538
+ type after_navig_fn = (arg0: Parameters<typeof history.replaceState | typeof history.pushState>, what_happened: "replaceState" | "pushState") => any;
539
+ /**
540
+ * AsyncIterable which resolves with the new href every time location.href changes
541
+ */
542
+ export const stateless_href_change_ipns: IPNS<string>;
543
+ /**
544
+ * AsyncIterable which resolves when you await it with the current href and then once every time it changes
545
+ */
546
+ export const href_change_ipns: IPNS<string>;
547
+ /**
548
+ * Functions to instantly (synchronously) call when a "popstate" event occurs, before the href_change_ipns' resolve
549
+ * This kind of bypasses the IPNS' point, and I'm sorry for that inconsistency, but I'm working on a feature that's not in the roadmap and am encountering issues due to the 1 tick delay of the IPNS. IPNS were a mistake, I'm sorry for them.
550
+ */
551
+ export const instant_exec_on_suspect_history_change: Set<(what_happened?: "replaceState" | "pushState" | "popstate", args?: PopStateEvent | Parameters<typeof history.replaceState> | Parameters<typeof history.pushState>) => void>;
552
+ export function on_next_navigation(callback: (new_href: string) => void): Promise<void>;
553
+ /**
554
+ * Proxies history.pushState, and, if the second argument is true, history.replaceState so that it executes the provided `after_navigation` function after the navigation (calling the original function) but before returning to what called it.
555
+ * Please also consider adding a listener to the `popstate` event (`window.addEventListener("popstate", handler)`) to cover ALL navigation possibilities.
556
+ * @param after_navigation Function to call after history.replaceState and history.pushState
557
+ * @param replace_replaceState=true Whether to call the function also on history.replaceState.
558
+ * @return Void
559
+ */
560
+ export function history_replacer(after_navigation: after_navig_fn, replace_replaceState?: boolean): Promise<void>;
561
+ interface TrackingData {
562
+ /** The active market, if any */
563
+ market?: string;
564
+ /** The merchant id */
565
+ tenant: string;
566
+ }
567
+ export interface PageViewEventData extends TrackingData {
568
+ /** If the page is a pdp, include the product_id */
569
+ product_id?: string;
570
+ }
571
+ export interface PageViewTrackingData extends TrackingData {
572
+ /** A function that returns the product_id of the product being displayed on href,
573
+ * if the href points to a PDP */
574
+ get_product_id: (href: string) => string | undefined | Promise<string | undefined>;
575
+ }
576
+ /**
577
+ * Sends a page_view event to Depict tracking if it hasn't been sent yet for the current page url
578
+ * It also broadcasts the current URL to a BroadcastChannel using the function `broadcast_url`, this is used for right click + open in new tab tracking
579
+ * @return A promise resolving to void
580
+ */
581
+ export function send_page_view_if_needed(data: PageViewEventData): Promise<void>;
582
+ /**
583
+ * Sends a page_view event to Depict tracking, and another one any time the page URL changes
584
+ */
585
+ export function send_page_view_on_navigation(data: PageViewTrackingData): Promise<void>;
586
+ export function make_tracker_send_to_depict(ga_tracker: any, append_to_url?: string): void;
587
+ export function create_ga_queue(): void;
588
+ /**
589
+ * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
590
+ * @return Current consent status, whether selected or not
591
+ */
592
+ export const cookiebot_get_consent: () => any;
593
+ /**
594
+ * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
595
+ * @return Consent status, once selected
596
+ */
597
+ export function cookiebot_wait_for_consent(): Promise<boolean>;
598
+ /**
599
+ * Returns an IPNS that resolves with initial consent when Cookiebot has loaded, or immediately if a consent cookie already exists.
600
+ * As well as a new consent object every time the consent status has changed
601
+ * @return An IPNS resolving to the consent object
602
+ */
603
+ export function cookiebot_get_cookie_ipns(): IPNS<ConsentObj>;
604
+ /**
605
+ * Anonymize Depict id until required consent level has been given through Cookiebot.
606
+ *
607
+ * This can be used for tenants using Cookiebot for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
608
+ * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
609
+ * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
610
+ *
611
+ * NOTE that this uses {@link set_depict_id_fn} to set {@link get_depict_id} and shouldn't be mixed with other uses of {@link set_depict_id_fn}.
612
+ */
613
+ export const init_cookiebot_tracking: (anon_id?: any) => Promise<void | undefined>;
614
+ declare global {
615
+ interface Window {
616
+ Cookiebot?: {
617
+ name: string;
618
+ consented: boolean;
619
+ declined: boolean;
620
+ changed: boolean;
621
+ hasResponse: boolean;
622
+ consentID: string;
623
+ consent: Consent;
624
+ isOutsideEU: boolean;
625
+ isOutOfRegion: boolean;
626
+ host: string;
627
+ domain: string;
628
+ currentPath: string;
629
+ doNotTrack: boolean;
630
+ consentLevel: string;
631
+ isRenewal: boolean;
632
+ forceShow: boolean;
633
+ dialog: null;
634
+ responseMode: string;
635
+ serial: string;
636
+ scriptId: string;
637
+ scriptElement: ScriptElement;
638
+ whitelist: any[];
639
+ cookieList: CookieList;
640
+ pathlist: any[];
641
+ userIsInPath: boolean;
642
+ cookieEnabled: boolean;
643
+ versionChecked: boolean;
644
+ versionRequested: boolean;
645
+ version: number;
646
+ latestVersion: number;
647
+ isNewVersion: boolean;
648
+ CDN: string;
649
+ source: string;
650
+ retryCounter: number;
651
+ frameRetryCounter: number;
652
+ bulkConsentFrameRetryCounter: number;
653
+ setOnloadFrameRetryCounter: number;
654
+ optOutLifetime: number;
655
+ consentLifetime: null;
656
+ framework: string;
657
+ hasFramework: boolean;
658
+ frameworkBlocked: boolean;
659
+ frameworkLoaded: boolean;
660
+ iframeReady: boolean;
661
+ iframe: Iframe;
662
+ bulkconsent: null;
663
+ bulkresetdomains: any[];
664
+ bulkconsentsubmitted: boolean;
665
+ isbulkrenewal: boolean;
666
+ wipe: Wipe;
667
+ consentUTC: Date;
668
+ IABConsentString: string;
669
+ GACMConsentString: string;
670
+ dataLayerName: string;
671
+ loaded: boolean;
672
+ autoblock: boolean;
673
+ mutationObserver: null;
674
+ mutationCounter: number;
675
+ mutationFallback: boolean;
676
+ mutationFallbackDocAttributes: any[];
677
+ mutationHandlerFallbackCharsetLoaded: boolean;
678
+ mutationAppName: string;
679
+ mutationEventListeners: any[];
680
+ mutationOnloadEventListeners: any[];
681
+ mutateEventListeners: boolean;
682
+ mutationHandlerFirstScript: null;
683
+ postPonedMutations: any[];
684
+ nonAsyncMutations: any[];
685
+ deferMutations: any[];
686
+ geoRegions: any[];
687
+ userCountry: string;
688
+ userCulture: string;
689
+ windowOnloadTriggered: boolean;
690
+ botDetectionDisabled: boolean;
691
+ regulations: Regulations;
692
+ regulationRegions: RegulationRegions;
693
+ commonTrackers: CommonTrackers;
694
+ configuration: Configuration;
695
+ inlineConfiguration: null;
696
+ processLinkClickCounter: number;
697
+ performanceEntriesCounter: number;
698
+ OverrideEventListenersOnloadFired: any[];
699
+ OverrideEventListenersOnloadToFire: any[];
700
+ fallbackScriptNodes: any[];
701
+ fallbackDeferNodes: any[];
702
+ };
703
+ }
704
+ }
705
+ export interface CommonTrackers {
706
+ domains: Domain[];
707
+ }
708
+ export interface Domain {
709
+ d: string;
710
+ c: number[];
711
+ }
712
+ export interface Configuration {
713
+ loaded: boolean;
714
+ loadRetry: number;
715
+ tags: any[];
716
+ trackingDomains: any[];
717
+ }
718
+ export interface Consent {
719
+ stamp: string;
720
+ necessary: boolean;
721
+ preferences: boolean;
722
+ statistics: boolean;
723
+ marketing: boolean;
724
+ }
725
+ export interface CookieList {
726
+ cookieTablePreference: any[];
727
+ cookieTableStatistics: any[];
728
+ cookieTableAdvertising: any[];
729
+ cookieTableUnclassified: any[];
730
+ }
731
+ export interface Iframe {
732
+ cookieconsentDataStyleDisplay: string;
733
+ mtjQuery171028673205955022363: number;
734
+ }
735
+ export interface RegulationRegions {
736
+ gdpr: string[];
737
+ ccpa: string[];
738
+ lgpd: string[];
739
+ }
740
+ export interface Regulations {
741
+ gdprApplies: boolean;
742
+ ccpaApplies: boolean;
743
+ lgpdApplies: boolean;
744
+ }
745
+ export interface ScriptElement {}
746
+ export interface Wipe {
747
+ preferences: boolean;
748
+ statistics: boolean;
749
+ marketing: boolean;
750
+ }
751
+ /**
752
+ * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
753
+ * @return Current consent status, whether selected or not
754
+ */
755
+ export const optanon_get_consent: () => any;
756
+ /**
757
+ * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
758
+ * @return Consent status
759
+ */
760
+ export function optanon_wait_for_consent(): Promise<boolean>;
761
+ /**
762
+ * Returns an IPNS that resolves with initial consent when Optanon has loaded, or immediately if a consent cookie already exists.
763
+ * As well as a new consent object every time the consent status has changed
764
+ * @return An IPNS resolving to the consent object
765
+ */
766
+ export function optanon_get_cookie_ipns(): IPNS<ConsentObj>;
767
+ /**
768
+ * Anonymize Depict id until required consent level has been given through OneTrust's Optanon.
769
+ *
770
+ * This can be used for tenants using OneTrust for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
771
+ * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
772
+ * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
773
+ *
774
+ * NOTE that this uses {@link set_depict_id_fn} to set {@link get_depict_id} and shouldn't be mixed with other uses of {@link set_depict_id_fn}.
775
+ */
776
+ export const init_optanon_tracking: (anon_id?: any) => Promise<void | undefined>;
777
+ export const load_gtag: (GA_ID: string, strict?: boolean | undefined) => Promise<void | undefined>;
778
+ export const setup_gtag: (GA_ID: string) => void | undefined;
779
+ export const gtag_view: <T extends Display>(raw_displays: T[], get_product_id: (url?: string | T | undefined) => string | Promise<string>, more?: {
780
+ [key: string]: any;
781
+ list_name?: string | undefined;
782
+ } | ((display: T) => {
783
+ [key: string]: any;
784
+ }) | undefined) => Promise<void | undefined>;
785
+ export const gtag_click: (product_id: string | number, index: number, more?: object | undefined) => Promise<any>;
786
+ export const send_ga: (action: string) => any;
787
+ export const setup_ga: (GAID: string) => void | undefined;
788
+ export const ga_rec_click: () => any;
789
+ export const ga_purchase_click: () => any;
790
+ export const insert_styling: (css: string) => Promise<void | undefined>;
791
+ /**
792
+ * A function meant to use to track the main add to cart button on the product page of an integration.
793
+ * * @param tenant instance of `Tenant` class
794
+ * @param selector The selector to use to find the button
795
+ * @param validator A function that can invalidate the click event before tracking is sent
796
+ * @return A `Disconnector` to stop looking for more add to cart buttons to track
797
+ */
798
+ export const track_a2c: (tenant: Tenant, selector: string, validator?: ((e: Event) => boolean) | undefined) => Disconnector;
799
+ /**
800
+ * Basically a RecRendererResult with less strict typing
801
+ */
802
+ export interface Surface<T extends Display> {
803
+ elements?: Node_Array;
804
+ displays?: T[];
805
+ should_stay_inserted?: Promise<boolean>;
806
+ }
807
+ /**
808
+ * Functions existing on ChildNode that are commonly used to insert recommendations into the DOM
809
+ */
810
+ export type InsertionVerb = "after" | "before" | "replaceWith" | "append" | "prepend" | "replaceChildren";
811
+ /**
812
+ * Tries to extract a product id from an url.
813
+ * The method used to retrive product id used here is very narrow, probably better to use something else instead?
814
+ *
815
+ * @example normal_get_product_id("www.foo.com/bar/baz.html") // "baz"
816
+ *
817
+ * @param url The url to check, defaults to `window.location`
818
+ * @returns
819
+ */
820
+ export const normal_get_product_id: (url?: string) => string;
821
+ declare global {
822
+ interface Document {
823
+ depictwashere: boolean;
824
+ }
825
+ }
826
+ /**
827
+ * If you need custom market logic that {@link depict_init_with_market_logic} doesn't support then use this function.
828
+ *
829
+ * Used to initialize an integration-script, this should always be the entrypoint of an integration.
830
+ *
831
+ * Makes sure that your script doesn't run twice
832
+ */
833
+ export const depict_init: (callback: () => Promise<void>) => void;
834
+ /**
835
+ * Initialize an integration-script like {@link depict_init}, but with automatic handling of unsupported and unknown markets.
836
+ *
837
+ * @param options.extract_market A function that extracts the current market, and if the market is supported, unsupported or unknown
838
+ * @param options.callback If `extract_market` returned a supported market, calls `depict_init` with this callback.
839
+ * @param options.supported_markets Markets where our script should run, in order to get the best typechecking you should add a `as const`
840
+ * modifier to this type like so `["foo", "bar"] as const`.
841
+ * @param options.unsupported_markets Markets we are aware of and where our script shouldn't run.
842
+ * @param options.preferred_demo_market Market to use on .demo.depict.ai, if an override is needed for all users.
843
+ * depict-override-market query parameter will override this behaviour.
844
+ *
845
+ * ### Behaviour
846
+ *
847
+ * - market is unsupported - log to console and exit
848
+ * - market is unknown - report to sentry and exit
849
+ *
850
+ * ### Override market
851
+ *
852
+ * When running in debug mode the market can be overridden by setting a `depict-override-market` query param.
853
+ * For example http://tenant.domain?depict-override-market=ez
854
+ */
855
+ export function depict_init_with_market_logic<T extends readonly string[]>(callback: (market: T[number]) => Promise<void>, get_market: () => Promise<string | undefined> | string | undefined, supported_markets: T, unsupported_markets: string[], preferred_demo_market?: string): void;
856
+ type IdType = string | undefined | Promise<string | undefined>;
857
+ export interface Tenant<ProductId extends IdType> {
858
+ TENANT: string;
859
+ tenant: string;
860
+ MARKET: TwoLetterMarket;
861
+ market: TwoLetterMarket;
862
+ TYPE: string;
863
+ type: string;
864
+ GA_ID: string;
865
+ gaid: string;
866
+ get_product_id: (url?: string) => ProductId extends string | undefined ? string : Promise<string>;
867
+ product_id: (url?: string) => string | Promise<string>;
868
+ dataset: DOMStringMap;
869
+ modify: boolean;
870
+ is_debug: boolean;
871
+ debug: boolean;
872
+ dlog: typeof dlog;
873
+ Sentry: typeof Sentry;
874
+ catchify: typeof catchify;
875
+ err: (...errors: any[]) => undefined;
876
+ }
877
+ /**
878
+ * Tenant class. This describes which site/customer one is on, in which market, and some more information. It also sends the page_view event if not already done and highlights elements with a `.depict` class if `localStorage['highlight-depict']` is `"true"`
879
+ * @param options A object with constructor options
880
+ */
881
+ export class Tenant<ProductId extends IdType = IdType> {
882
+ constructor(options: {
883
+ TENANT?: string;
884
+ TYPE?: string;
885
+ MARKET: TwoLetterMarket;
886
+ GA_ID: string;
887
+ get_product_id: (url?: string) => ProductId;
888
+ current_script_override?: HTMLScriptElement;
889
+ pageview_tracking?: boolean;
890
+ });
891
+ }
892
+ /**
893
+ * This is a list of alpha-2 country codes plus some two letter combinations commonly used to describe markets
894
+ */
895
+ export type TwoLetterMarket = "af" | "al" | "dz" | "as" | "ad" | "ao" | "ai" | "aq" | "ag" | "ar" | "am" | "aw" | "au" | "at" | "az" | "bs" | "bh" | "bd" | "bb" | "by" | "be" | "bz" | "bj" | "bm" | "bt" | "bo" | "bq" | "ba" | "bw" | "bv" | "br" | "io" | "bn" | "bg" | "bf" | "bi" | "cv" | "kh" | "cm" | "ca" | "ky" | "cf" | "td" | "cl" | "cn" | "cx" | "cc" | "co" | "km" | "cd" | "cg" | "ck" | "cr" | "hr" | "cu" | "cw" | "cy" | "cz" | "ci" | "dk" | "dj" | "dm" | "do" | "ec" | "eg" | "sv" | "gq" | "er" | "ee" | "sz" | "et" | "fk" | "fo" | "fj" | "fi" | "fr" | "gf" | "pf" | "tf" | "ga" | "gm" | "ge" | "de" | "gh" | "gi" | "gr" | "gl" | "gd" | "gp" | "gu" | "gt" | "gg" | "gn" | "gw" | "gy" | "ht" | "hm" | "va" | "hn" | "hk" | "hu" | "is" | "in" | "id" | "ir" | "iq" | "ie" | "im" | "il" | "it" | "jm" | "jp" | "je" | "jo" | "kz" | "ke" | "ki" | "kp" | "kr" | "kw" | "kg" | "la" | "lv" | "lb" | "ls" | "lr" | "ly" | "li" | "lt" | "lu" | "mo" | "mg" | "mw" | "my" | "mv" | "ml" | "mt" | "mh" | "mq" | "mr" | "mu" | "yt" | "mx" | "fm" | "md" | "mc" | "mn" | "me" | "ms" | "ma" | "mz" | "mm" | "na" | "nr" | "np" | "nl" | "nc" | "nz" | "ni" | "ne" | "ng" | "nu" | "nf" | "mp" | "no" | "om" | "pk" | "pw" | "ps" | "pa" | "pg" | "py" | "pe" | "ph" | "pn" | "pl" | "pt" | "pr" | "qa" | "mk" | "ro" | "ru" | "rw" | "re" | "bl" | "sh" | "kn" | "lc" | "mf" | "pm" | "vc" | "ws" | "sm" | "st" | "sa" | "sn" | "rs" | "sc" | "sl" | "sg" | "sx" | "sk" | "si" | "sb" | "so" | "za" | "gs" | "ss" | "es" | "lk" | "sd" | "sr" | "sj" | "se" | "ch" | "sy" | "tw" | "tj" | "tz" | "th" | "tl" | "tg" | "tk" | "to" | "tt" | "tn" | "tr" | "tm" | "tc" | "tv" | "ug" | "ua" | "ae" | "gb" | "um" | "us" | "uy" | "uz" | "vu" | "ve" | "vn" | "vg" | "vi" | "wf" | "eh" | "ye" | "zm" | "zw" | "ax" | "uk" | "en" | "da" | "eu" | "sv" | "oc" | "nb" | "sq";
896
+ type ImpressionTrackOptions = {
897
+ t?: Tenant;
898
+ impression_tracking?: false;
899
+ } | {
900
+ impression_tracking: true;
901
+ t: Tenant;
902
+ };
903
+ type TenantSpecificationOptions = {
904
+ t?: Tenant;
905
+ tenant: string;
906
+ market: string;
907
+ get_product_id: (url?: string) => string | Promise<string>;
908
+ } | {
909
+ t: Tenant;
910
+ tenant?: string;
911
+ market?: string;
912
+ get_product_id?: (url?: string) => string | Promise<string>;
913
+ };
914
+ type ElementDiscoveryOptions = {
915
+ product_selector: string;
916
+ product_elements?: null | void | undefined;
917
+ } | {
918
+ product_selector?: null | void | undefined;
919
+ product_elements: HTMLElement[];
920
+ };
921
+ type A2CButtonDiscoveryOptions = {
922
+ a2c_selector: string;
923
+ a2c_elements?: null | void | undefined;
924
+ } | {
925
+ a2c_selector?: null | void | undefined;
926
+ a2c_elements: HTMLElement[];
927
+ };
928
+ /**
929
+ * @deprecated Please use DPC instead.
930
+ * Does not support ModernDisplays.
931
+ */
932
+ export const AIO: (options: {
933
+ attempt_gtag_view_tracking?: boolean | undefined;
934
+ no_gtag?: boolean | undefined;
935
+ shade?: boolean | undefined;
936
+ always_track_a2c?: boolean | undefined;
937
+ get_rec_id?: ((elem: HTMLElement) => string | undefined) | undefined;
938
+ get_prod_id?: ((elem: HTMLElement) => (string | undefined) | Promise<string | undefined>) | undefined;
939
+ get_ga_prod_id?: ((elem: HTMLElement) => string | undefined | Promise<string | undefined>) | undefined;
940
+ click_location_prefix?: ((elem: HTMLElement) => string | undefined) | undefined;
941
+ rec_a2c_selector?: string | undefined;
942
+ rec_a2c_unbubbled?: boolean | undefined;
943
+ get_display?: ((elem: HTMLElement) => Partial<LegacyDisplay> | undefined) | undefined;
944
+ } & ImpressionTrackOptions & TenantSpecificationOptions & ElementDiscoveryOptions & A2CButtonDiscoveryOptions, gtag_options?: {
945
+ [key: string]: any;
946
+ list_name?: string | undefined;
947
+ } | undefined) => Promise<{
948
+ add_a2c_element: (element: HTMLElement) => void;
949
+ add_product_element: (element: HTMLElement) => Promise<void | undefined>;
950
+ } | undefined>;
951
+ export const paint_red: (element: HTMLElement) => void | undefined;
952
+ /**
953
+ * A function that attempts to "serialize" an object to a text representation that helps with debugging when using sentry
954
+ * @param anything Something to try to serialize - this function is crappy and your mileage may vary
955
+ * @param depth How deep to go when recursing
956
+ * @return An object that is somehow closer to text (better serializable by sentry) or text
957
+ */
958
+ export function serialize_object(anything: Object, depth?: number): Object;
959
+ export const wait: (delay: number) => Promise<unknown>;
960
+ /**
961
+ * Fetch with retry and exponetial back off. This is the 2.0 version of the previous Windows proof fetch.
962
+ *
963
+ * Windows proof fetch is a utility which retries fetch requests 10 times when they fail. Reason for this is a certain windows 10 build where the network stack randomly breaks 20% of https connections
964
+ * @param url Url to perform fetch towards
965
+ * @param options Fetch options
966
+ * @param max_retries Max number of retries, defaults to 10
967
+ * @returns The fetch response
968
+ */
969
+ export function fetch_retry(url: RequestInfo | URL, options?: RequestInit, max_retries?: number): Promise<false | Response>;
970
+ type PossibleEndpoint = "general" | "product" | "products" | "category";
971
+ type ExclusiveId = {
972
+ category_id: string;
973
+ product_id?: undefined;
974
+ product_ids?: undefined;
975
+ } | {
976
+ category_id?: undefined;
977
+ product_id: string;
978
+ product_ids?: undefined;
979
+ } | {
980
+ category_id?: undefined;
981
+ product_id?: undefined;
982
+ product_ids: string[];
983
+ } | {
984
+ category_id?: undefined;
985
+ product_id?: undefined;
986
+ product_ids?: undefined;
987
+ };
988
+ type FetchRecsOptions = {
989
+ type: string;
990
+ user_id?: string;
991
+ session_id?: string;
992
+ metadata?: Record<string, any>;
993
+ } & ExclusiveId;
994
+ /**
995
+ * @deprecated, use fetchDepictRecommendations instead
996
+ * Fetches recommendations from the depict v2 recommendation api.
997
+ * Will select the endpoint after which id property is given.
998
+ *
999
+ * API Docs: https://api.depict.ai/docs
1000
+ *
1001
+ * Formerly called get_displays
1002
+ */
1003
+ export function fetch_recs<T extends Display = Display>(t: Tenant | {
1004
+ market: string;
1005
+ tenant: string;
1006
+ }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<T[]>;
1007
+ export function fetch_recs_whole_response<R extends {
1008
+ displays: any[];
1009
+ }>(t: Tenant | {
1010
+ market: string;
1011
+ tenant: string;
1012
+ }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<R>;
1013
+ declare function default_get_fetch_url(type: PossibleEndpoint): string;
1014
+ export function ensure_parameter_in_url(url: any, param: any, value: any): string;
1015
+ export function querySelectorUpwards(element: Element | HTMLElement, selector: string): Element | null;
1016
+ export function html2elems(html: string): NodeListOf<ChildNode>;
1017
+ export function html2elem(html: string): Element | null;
1018
+ /** On demo domain: make all urls relative */
1019
+ export function relativify(url: string | RegExp, also_onchange?: boolean, override_dev_url?: string, stfu?: boolean, also_in_all_shadow_roots?: boolean): void;
1020
+ export function querySelectorAllElements<T extends Element>(elements: Node_Iterable, selector: string): T[];
1021
+ export function standard_price_format(price: number, places_after_comma?: number | "auto", decimal_delimiter?: string, thousands_delimiter?: string): string;
1022
+ export function intl_number_format_with_fallback(bcp47_country_code: string, number: number, numberformat_options?: Parameters<typeof Intl.NumberFormat>[1]): string;
1023
+ export function ensure_object_path(obj: object, step1: string, ...path: string[]): any;
1024
+ export function Rec_Renderer<T extends Display>(t: Tenant | null, rendering_options: RR_Options<T>): Promise<RecRendererResult<T>>;
1025
+ export function regex_templating(template: string, display?: Display | {
1026
+ [key: string]: any;
1027
+ }): string;
1028
+ export function clone_deep<T>(obj: T): T;
1029
+ export class InfoForProcessing<T extends Display> {
1030
+ constructor(t: Tenant | null, rendering_options: RR_Options<T>, displays: T[], index?: number, remove_display?: () => void, event_listeners?: [type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions][]);
1031
+ }
1032
+ type RegisterEventListener = (type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions) => void;
1033
+ export interface InfoForProcessing<T extends Display> {
1034
+ t: Tenant;
1035
+ rendering_options: RR_Options<T>;
1036
+ displays: T[];
1037
+ index: number;
1038
+ remove_display?: () => void;
1039
+ register_event_listener: RegisterEventListener;
1040
+ event_listeners?: [type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions][];
1041
+ extras?: {
1042
+ [key: string]: any;
1043
+ };
1044
+ }
1045
+ export type RR_PreProcessor<T extends Display> = (display: T, info: InfoForProcessing<T>) => Promise<T> | T;
1046
+ export type RR_PostProcessor<T extends Display> = (elements: NodeListOf<ChildNode> | Node_Array, display: T, info: InfoForProcessing<T>) => Promise<NodeListOf<ChildNode> | Node_Array> | NodeListOf<ChildNode> | Node_Array;
1047
+ export type RR_Options<T extends Display> = {
1048
+ template: string | ((arg0: T, info: InfoForProcessing<T>) => Promise<string | Node_Array> | string | Node_Array);
1049
+ recs?: T[] | undefined | Promise<T[] | undefined>;
1050
+ type: string;
1051
+ min_items_to_report?: number;
1052
+ min_items_to_run?: number;
1053
+ max_items?: number;
1054
+ extra_api_options?: {
1055
+ [key: string]: any;
1056
+ };
1057
+ pre_processors?: RR_PreProcessor<T>[];
1058
+ post_processors?: RR_PostProcessor<T>[];
1059
+ headers?: HeadersInit;
1060
+ } & FetchRecsOptions;
1061
+ /**
1062
+ * Product properties that are used to render the product cards. Used until early 2023
1063
+ */
1064
+ export interface LegacyDisplay {
1065
+ /**
1066
+ * The URL of the product page.
1067
+ */
1068
+ page_url: any;
1069
+ /**
1070
+ * The URL of the product image.
1071
+ */
1072
+ image_url: string;
1073
+ /** The price of the product. */
1074
+ sale_price: number;
1075
+ /** The original price of the product. */
1076
+ original_price: number;
1077
+ /** The product ID of the product. */
1078
+ product_id: string;
1079
+ /** The Google Analytics product ID */
1080
+ ga_product_id?: string;
1081
+ /** The Google Analytics product IDs */
1082
+ ga_product_ids?: string[];
1083
+ /** The variation IDs */
1084
+ variant_ids?: string[];
1085
+ /** The title */
1086
+ title: string;
1087
+ /** Unique recommendation result ID used by Depict */
1088
+ recommendation_id?: string;
1089
+ /** Unique search result ID used by Depict */
1090
+ search_result_id?: string;
1091
+ /** Unique product listing result ID used by Depict */
1092
+ product_listing_result_id?: string;
1093
+ [key: string]: any;
1094
+ }
1095
+ interface ModernDisplay {
1096
+ /**
1097
+ * The index of the variant to be displayed.
1098
+ */
1099
+ variant_index: number;
1100
+ /**
1101
+ * All variant displays (eg. different colors, sizes) of the product.
1102
+ */
1103
+ variant_displays: any[];
1104
+ /** SKUs of the different variants */
1105
+ variant_skus: string[];
1106
+ /** Product of the different variants */
1107
+ variant_product_ids: string[];
1108
+ /** Unique recommendation result ID used by Depict */
1109
+ recommendation_id?: string;
1110
+ /** Unique search result ID used by Depict */
1111
+ search_result_id?: string;
1112
+ /** Unique product listing result ID used by Depict */
1113
+ product_listing_result_id?: string;
1114
+ /** Recommendation type logic used by Depict */
1115
+ logic?: string;
1116
+ }
1117
+ interface BasicDisplay {
1118
+ product_id: string;
1119
+ /** Unique recommendation result ID used by Depict */
1120
+ recommendation_id?: string;
1121
+ /** Unique search result ID used by Depict */
1122
+ search_result_id?: string;
1123
+ /** Unique product listing result ID used by Depict */
1124
+ product_listing_result_id?: string;
1125
+ /** Recommendation type logic used by Depict */
1126
+ logic?: string;
1127
+ [key: string]: any;
1128
+ }
1129
+ export type Display = LegacyDisplay | ModernDisplay | BasicDisplay;
1130
+ export type Node_Iterable = HTMLCollection | NodeListOf<ChildNode> | Node_Array;
1131
+ export type Node_Array = (Element | Text | Comment)[];
1132
+ export type RecRendererResult<T extends Display> = Record<string, never> | {
1133
+ elements: Node_Array;
1134
+ displays: T[];
1135
+ };
1136
+ /**
1137
+ * Queues a task in the event queue without a timeout like setTimeout does, see https://www.youtube.com/watch?v=cCOL7MC4Pl0
1138
+ * @param callback callback function that gets queued as a task
1139
+ */
1140
+ export function queueMacroTask(callback: VoidFunction): void;
1141
+ interface SDKRenderingInfo {
1142
+ set_on_index_change: (fn: (index: number) => void) => void;
1143
+ }
1144
+ /**
1145
+ * Creates a handler for sending the "recommendations_inserted" event on new results.
1146
+ * Usage: call make_plp_recommendations_inserted_handler with options and then call the returned functions in your productCardTemplate
1147
+ */
1148
+ export function make_plp_recommendations_inserted_handler(tenant: string, market: string, type: "search" | "category"): <T extends Display>(display: T | null, info?: SDKRenderingInfo) => void;
1149
+ /**
1150
+ * @deprecated this was a stupid idea, it's much easier to read if one just does a quick arrow function that provides the wanted arguments
1151
+ */
1152
+ export function cache_args(fn: any, ...args: any[]): (...unimportant_args: any[]) => any;
1153
+ export const check_displays: (args_0: {
1154
+ recs: Display[] | {
1155
+ displays: Display[];
1156
+ } | Promise<Display[] | {
1157
+ displays: Display[];
1158
+ }>;
1159
+ min_recs?: number | undefined;
1160
+ market: string;
1161
+ type: string;
1162
+ product_id: string | string[] | Promise<string> | Promise<string[]> | ((arg0?: string) => string | string[] | Promise<string> | Promise<string[]>) | undefined;
1163
+ tenant: string;
1164
+ }) => Promise<boolean | undefined>;
1165
+ /**
1166
+ * @deprecated You should no longer need to use this. Use observer.onexists to add an event listener to an element once it exists.
1167
+ */
1168
+ export function require_event_listener(element: Node, event: string, track_id: any, func: EventListenerOrEventListenerObject): void;
1169
+ export const default_view_tracking: (RR_PostProcessor<any> | typeof depict_page_view)[];
1170
+ export const default_click_tracking: (typeof depict_click_tracking_post_processor | typeof add_new_tab_listener)[];
1171
+ export function recs_inserted_tracking<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1172
+ export function gtag_view_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1173
+ export function depict_page_view<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1174
+ export function gtag_click_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1175
+ export function depict_click_tracking_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1176
+ export function add_to_localstorage<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1177
+ export function ga_click<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1178
+ export const should_colorizeLogics: boolean;
1179
+ export function colorize_elements(elements: NodeListOf<ChildNode> | Node_Array, display: Display): NodeListOf<ChildNode> | Node_Array;
1180
+ type Extended_RR_Options<T extends Display> = {
1181
+ view_tracking?: RR_PostProcessor<T>[];
1182
+ click_tracking?: RR_PostProcessor<T>[];
1183
+ } & RR_Options<T>;
1184
+ export function default_rr<T extends Display>(t: Tenant | null, rendering_options: Extended_RR_Options<T>): Promise<RecRendererResult<T>>;
1185
+ type GWVM_Options = {
1186
+ container_selector?: string;
1187
+ start_rows?: number;
1188
+ rows_per_click?: number;
1189
+ recs_per_row?: number | ((showing: number) => number);
1190
+ button?: string | HTMLElement;
1191
+ override_rec_renderer?: typeof Rec_Renderer;
1192
+ title_selector?: string;
1193
+ title?: string | HTMLElement;
1194
+ container_template: string | Node_Array;
1195
+ only_full_rows?: boolean;
1196
+ should_preload?: boolean;
1197
+ };
1198
+ interface GWVM_InfoForProcessing<T extends Display> extends InfoForProcessing<T> {
1199
+ extras: {
1200
+ [key: string]: any;
1201
+ load_more_currently_showing: number;
1202
+ load_more: (num?: number | Event) => void;
1203
+ load_more_ipo: {
1204
+ promise: Promise<number>;
1205
+ resolve: (argument?: number) => void;
1206
+ };
1207
+ };
1208
+ }
1209
+ type GWVM_RR_Post_Pro = (elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: GWVM_InfoForProcessing) => Promise<NodeListOf<ChildNode> | Node_Array> | NodeListOf<ChildNode> | Node_Array;
1210
+ type GWVM_RR_Options = Extended_RR_Options & {
1211
+ post_processors?: GWVM_RR_Post_Pro[];
1212
+ };
1213
+ /**
1214
+ * @deprecated please use RecommendationGrid instead
1215
+ */
1216
+ export function GWVM_Renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: GWVM_Options): Promise<{
1217
+ elements?: ChildNode[] | undefined;
1218
+ load_more?: ((num?: number | Event) => void) | undefined;
1219
+ displays?: Display[] | undefined;
1220
+ }>;
1221
+ /**
1222
+ * Used auto generate recommendations with view more button.
1223
+ * @param t The tenant used for recommendations
1224
+ * @param options Rendering options for recommendations such as total number of recommendations and template.
1225
+ * `GWVM_RR_Options` extends the same typing used for options in `default_rr and` `recommendation-renderer`
1226
+ * @param GWVM_opts Grid options, starting row, rows per view more click, container templates
1227
+ * @param rec_selector The selector used to find the rendered recs (by recommendation renderer
1228
+ * for which the first options object was used) for the width calculation. Default: ".rec_outer".
1229
+ * @deprecated please use RecommendationGrid instead
1230
+ */
1231
+ export function Auto_GWVM(t: Tenant, options: GWVM_RR_Options, GWVM_opts: Omit<GWVM_Options, "recs_per_row">, {
1232
+ rec_selector
1233
+ }?: {
1234
+ rec_selector?: string;
1235
+ }): Promise<{
1236
+ elements?: Node_Array | undefined;
1237
+ load_more?: ((num?: number | Event) => void) | undefined;
1238
+ displays?: Display[] | undefined;
1239
+ }>;
1240
+ /**
1241
+ * @deprecated use async_iterable_ipns instead. This can skip values which yields unexpected results.
1242
+ */
1243
+ export function infinite_promise_creator(): {
1244
+ promise: Promise<unknown>;
1245
+ internal_resolve: ((value: any) => void) | undefined;
1246
+ resolve: (argument?: any) => void;
1247
+ };
1248
+ interface trimmed_GWVM_opts extends Omit<GWVM_Options, "start_rows" | "rows_per_click" | "recs_per_row"> {}
1249
+ /**
1250
+ * @deprecated please rewrite this, basing on RecommendationGrid and its `rows.ipns` option, next time you need infinite scroll
1251
+ */
1252
+ export function infinite_renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: trimmed_GWVM_opts, {
1253
+ rec_selector
1254
+ }?: {
1255
+ rec_selector?: string;
1256
+ }): Promise<{
1257
+ elements?: Node_Array | undefined;
1258
+ load_more?: ((num?: number | Event | undefined) => void) | undefined;
1259
+ displays?: Display[] | undefined;
1260
+ }>;
1261
+ /**
1262
+ * @deprecated Emil's utility in integration.ts is better because it doesn't cause multiply <style> tags and doesn't require a tenant class
1263
+ */
1264
+ export function deprecated_insert_styling(t: Tenant, css: string, extra_html?: string): Promise<void>;
1265
+ /**
1266
+ * @deprecated This is a predecessor to reactive_template which is much more limited (can only have two states) plus it's much more cumbersome to use, which is why I'm deprecating it.
1267
+ */
1268
+ export function placeholder(...args: Parameters<typeof placeholder_worker>): accepted_input_that_resolves_to_elements;
1269
+ type accepted_element_types = Node_Array[0] | Node_Array;
1270
+ type accepted_input_that_resolves_to_elements = accepted_element_types | Promise<accepted_element_types> | (() => accepted_element_types) | (() => Promise<accepted_element_types>);
1271
+ declare function placeholder_worker(placeholder_elements: accepted_input_that_resolves_to_elements, final_elements: accepted_input_that_resolves_to_elements, switching_trigger?: infinite_promise_no_skip<boolean> | Promise<boolean>): Promise<void>;
1272
+ declare global {
1273
+ interface HTMLImageElementWithLoaded extends HTMLImageElement {
1274
+ loaded?: boolean;
1275
+ }
1276
+ interface HTMLSourceElementWithLoaded extends HTMLSourceElement {
1277
+ loaded?: boolean;
1278
+ }
1279
+ }
1280
+ export interface Lazyfier {
1281
+ t: Tenant;
1282
+ container: HTMLElement;
1283
+ selector: string;
1284
+ lazyfinder: lazyfinder;
1285
+ only_load_intersecting: boolean;
1286
+ ignore_data_urls?: boolean;
1287
+ }
1288
+ interface Lazyfier_Options {
1289
+ container?: HTMLElement;
1290
+ lazyfinder?: lazyfinder;
1291
+ selector?: string;
1292
+ wait_for_dominsertion?: boolean | Promise<any>;
1293
+ only_load_intersecting?: boolean;
1294
+ verbose?: boolean;
1295
+ ignore_data_urls?: boolean;
1296
+ }
1297
+ export class Lazyfier {
1298
+ #private;
1299
+ intersection_observer: IntersectionObserver;
1300
+ start_observing_for_new_children_(override_container?: HTMLElement): void;
1301
+ constructor({
1302
+ container,
1303
+ lazyfinder,
1304
+ selector,
1305
+ wait_for_dominsertion,
1306
+ only_load_intersecting,
1307
+ ignore_data_urls,
1308
+ verbose
1309
+ }: Lazyfier_Options);
1310
+ }
1311
+ interface lazyfinder {
1312
+ elements?: HTMLImageElementWithLoaded[];
1313
+ unload?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1314
+ load?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1315
+ }
1316
+ export function test_array_proxy_support(): boolean;
1317
+ export interface Slider_Options {
1318
+ /**
1319
+ * Controls within what distance to hide the left slider button.
1320
+ * The distance is in pixels to the leftmost part of the slider container from the first element in the slider
1321
+ *
1322
+ * Defaults to `10`
1323
+ */
1324
+ dist_to_hide_left?: number;
1325
+ /**
1326
+ * Controls within what distance to hide the right slider button.
1327
+ * The distance is in pixels to the rightmost part of the slider container from the last element in the slider
1328
+ *
1329
+ * Defaults to `10`
1330
+ */
1331
+ dist_to_hide_right?: number;
1332
+ stepstoslide?: number;
1333
+ center_target?: boolean;
1334
+ constructor_plugins?: ((arg0: Slider_Options) => any)[];
1335
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1336
+ correct_bs_targets?: boolean;
1337
+ button_contents?: {
1338
+ right: Node_Iterable;
1339
+ left: Node_Iterable;
1340
+ };
1341
+ button_elems?: {
1342
+ right: HTMLElement;
1343
+ left: HTMLElement;
1344
+ };
1345
+ autoinvalidate_cache?: boolean;
1346
+ }
1347
+ export class Amazing_Slider {
1348
+ #private;
1349
+ container: HTMLDivElement;
1350
+ insert_here: HTMLDivElement;
1351
+ intersecting_items_object: {
1352
+ [key: string]: IntersectionObserverEntry;
1353
+ [key: number]: IntersectionObserverEntry;
1354
+ };
1355
+ stepstoslide: number;
1356
+ dist_to_hide_left: number;
1357
+ dist_to_hide_right: number;
1358
+ center_target: boolean;
1359
+ correct_bs_targets: boolean;
1360
+ snap_style?: HTMLStyleElement;
1361
+ on_elements_changed: ((records: MutationRecord[]) => any)[];
1362
+ observer: IntersectionObserver;
1363
+ observe: any;
1364
+ get_index_of_element(target: Element | HTMLElement): number | undefined;
1365
+ first_intersecting_index(min_ratio?: number): number;
1366
+ get first_intersecting(): IntersectionObserverEntry;
1367
+ get index_of_last_element(): number;
1368
+ get currently_selected(): number | undefined;
1369
+ get visible_sizes(): Map<Element, {
1370
+ total_visible: number;
1371
+ ratio_visible: number;
1372
+ margin_left: number;
1373
+ margin_right: number;
1374
+ rect: DOMRect;
1375
+ }>;
1376
+ get cards_fitting_in_viewport(): number;
1377
+ element_by_index(index: number): Element;
1378
+ invalidate_cache(): void;
1379
+ scroll_to_rel(offset: number, harsh?: boolean): void;
1380
+ scroll_to_abs(offset: number, harsh?: boolean): void;
1381
+ constructor({
1382
+ dist_to_hide_left,
1383
+ dist_to_hide_right,
1384
+ stepstoslide,
1385
+ center_target,
1386
+ mutation_plugins,
1387
+ constructor_plugins,
1388
+ correct_bs_targets,
1389
+ button_contents,
1390
+ button_elems,
1391
+ autoinvalidate_cache
1392
+ }: Slider_Options);
1393
+ }
1394
+ export interface Amazing_Lazy_Slider {
1395
+ lazyfier: Lazyfier;
1396
+ }
1397
+ export class Amazing_Lazy_Slider extends Amazing_Slider {
1398
+ constructor(options: Slider_Options, lazyfier_options?: Optional<ConstructorParameters<typeof Lazyfier>[0], "container">);
1399
+ }
1400
+ interface Pro_Slider_Options {
1401
+ container?: string | Node_Iterable;
1402
+ root_selector?: string;
1403
+ override_rec_renderer?: typeof Rec_Renderer;
1404
+ insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1405
+ lazyfier_options?: ConstructorParameters<typeof Amazing_Lazy_Slider>[1];
1406
+ }
1407
+ /**
1408
+ * @deprecated please use RecommendationSlider instead
1409
+ */
1410
+ export function Pro_Slider<T extends Display>(t: Tenant, rendering_options: Extended_RR_Options<T>, options_for_us?: Pro_Slider_Options, slider_options?: Slider_Options): ReturnType<typeof Rec_Renderer<T>>;
1411
+ /**
1412
+ * @deprecated Please use recommendation renderer instead
1413
+ */
1414
+ export class Depict {
1415
+ #private;
1416
+ settings: any;
1417
+ data: any;
1418
+ tracker: void;
1419
+ constructor(settings: any);
1420
+ init(callback: Function, existingDisplays?: object[]): void;
1421
+ loadRecommendations(callback: any): void;
1422
+ trackGAEvent(action: any, index: any, product_id: any, ga_product_ids?: string[]): void;
1423
+ trackPageView(): void;
1424
+ trackClick(index: any): boolean | Promise<void | undefined> | undefined;
1425
+ trackAddToCart(pId: any): boolean | Promise<void | undefined> | undefined;
1426
+ createContainer(root: any, container: any, prepend?: boolean): void;
1427
+ renderTemplate({
1428
+ prep,
1429
+ root,
1430
+ template,
1431
+ itemPreprocessor,
1432
+ itemPostprocessor
1433
+ }?: any): void;
1434
+ }
1435
+ declare global {
1436
+ interface Document {
1437
+ _depict_modify: boolean | undefined;
1438
+ }
1439
+ }
1440
+ interface TemplateToolOptions {
1441
+ max_items?: number;
1442
+ min_items?: number;
1443
+ DNT?: boolean;
1444
+ debug?: boolean;
1445
+ type?: string;
1446
+ product_id?: Function | ((url?: string) => string);
1447
+ sendGa?: boolean;
1448
+ loadHack?: boolean;
1449
+ shade?: boolean;
1450
+ gaid?: string;
1451
+ tenant?: string;
1452
+ market?: string;
1453
+ }
1454
+ /**
1455
+ * @deprecated Please use RecommendationRenderer instead
1456
+ */
1457
+ export const simplified_template_tool: (options: {
1458
+ options: TemplateToolOptions;
1459
+ recs?: object[] | undefined;
1460
+ root: Element;
1461
+ template: string;
1462
+ postProcessor?: Function | undefined;
1463
+ preProcessor?: Function | undefined;
1464
+ }) => Promise<Depict>;
1465
+ interface special_lazyfier_options extends Omit<Lazyfier_Options, "t"> {}
1466
+ interface Deprecated_Slider_Options {
1467
+ dlog?: Function;
1468
+ catchify?: Function;
1469
+ dist_to_hide_left?: number;
1470
+ dist_to_hide_right?: number;
1471
+ stepstoslide?: number;
1472
+ arrow_image?: string;
1473
+ center_target?: boolean;
1474
+ constructor_plugins?: ((arg0: Deprecated_Slider_Options) => any)[];
1475
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1476
+ correct_bs_targets?: boolean;
1477
+ }
1478
+ /**
1479
+ * @deprecated Please use Pro_Slider instead
1480
+ */
1481
+ declare class Deprecated_Amazing_Slider extends Amazing_Lazy_Slider {
1482
+ constructor(static_options: Deprecated_Slider_Options, override_lazyfier_options?: special_lazyfier_options);
1483
+ }
1484
+ export function insert_styling_into_slider(slider: Deprecated_Amazing_Slider): void;
1485
+ interface RR_Slider_Options {
1486
+ container?: string | Node_Iterable;
1487
+ root_selector?: string;
1488
+ Rec_Renderer?: typeof Rec_Renderer;
1489
+ insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1490
+ }
1491
+ /**
1492
+ * @deprecated please use Pro_Slider instead
1493
+ */
1494
+ export function RR_Slider<T extends Display>(t: Tenant, rendering_options: Extended_RR_Options<T>, options_for_us?: RR_Slider_Options, slider_options?: Deprecated_Slider_Options, override_lazyfier_options?: special_lazyfier_options): ReturnType<typeof Rec_Renderer>;
1495
+ type PreProcessor = (tenant: Tenant, display: any, i?: number, with_loadmore?: boolean, with_slider?: boolean, infinite_scroll?: boolean) => any;
1496
+ type PostProcessor = (tenant: Tenant, items: HTMLCollection, display: any, slider?: Deprecated_Amazing_Slider) => HTMLCollection;
1497
+ /**
1498
+ * @deprecated this uses template-tool-v1 which is long surpassed, please use RecommendationGrid or Pro_Slider (based on Recommendation-Renderer) instead
1499
+ */
1500
+ export function get_recs_with_template({
1501
+ t,
1502
+ recs,
1503
+ title,
1504
+ infinite_scroll,
1505
+ with_slider,
1506
+ with_loadmore,
1507
+ template_tool_options,
1508
+ slider_options,
1509
+ pre_processors,
1510
+ post_processors,
1511
+ container_template,
1512
+ // container template
1513
+ template,
1514
+ // recommendation template
1515
+ chunk_size_for_load_more,
1516
+ insertion_promise,
1517
+ view_more_text
1518
+ }: {
1519
+ t: Tenant;
1520
+ recs?: any[];
1521
+ with_loadmore?: boolean;
1522
+ title?: string | Node[] | NodeList;
1523
+ infinite_scroll?: boolean;
1524
+ template_tool_options?: TemplateToolOptions;
1525
+ with_slider?: boolean;
1526
+ slider_options?: Deprecated_Slider_Options;
1527
+ pre_processors?: PreProcessor[];
1528
+ post_processors?: PostProcessor[];
1529
+ container_template: string;
1530
+ template: string;
1531
+ chunk_size_for_load_more?: number;
1532
+ insertion_promise?: Promise<void | unknown>;
1533
+ view_more_text?: string;
1534
+ }): Promise<ChildNode[] | void>;
1535
+ export function default_pre_processor(_t: any, d: any, i: number, with_loadmore: boolean, with_slider: boolean, infinite_scroll: boolean): any;
1536
+ export function default_post_processor(_t: any, itms: HTMLCollection, d: any, slider: Deprecated_Amazing_Slider | null): HTMLCollection;
1537
+ /**
1538
+ * @deprecated please use `fetch_retry()` instead
1539
+ *
1540
+ * Windows proof fetch factory: windows proof fetch is a utility which retries fetch requests 10 times when they fail. Reason for this is a certain windows 10 build where the network stack randomly breaks 20% of https connections
1541
+ * (Note: this thing really should be rewritten with exponential backoff and a better API)
1542
+ * @param dlog logging function to use
1543
+ * @param error_log an array to which errors will be pushed
1544
+ * @return a windows proof fetch function
1545
+ */
1546
+ export const wpff: (dlog: any, error_log?: any[]) => (url: RequestInfo, body: BodyInit, headers?: HeadersInit, decode_json?: boolean, fetch_options?: RequestInit, attempt?: number) => any;
1547
+ export const use_element: <E extends HTMLOrSVGElement = HTMLElement>(callback: (element: E) => void, element: E) => E;
1548
+ export function use_listener<K extends keyof GlobalEventHandlersEventMap, E extends HTMLElement = HTMLElement>(event: K, handler: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, element: E): E;
1549
+ export const classlist: (classes: (string | undefined)[]) => string;
1550
+ type Props = {
1551
+ children?: Elem[] | Elem;
1552
+ onClick?: (e: MouseEvent) => void;
1553
+ [key: string]: any;
1554
+ };
1555
+ type Elem = Node | string;
1556
+ type Component = (props: Props, _unknown?: unknown) => HTMLElement;
1557
+ export const jsx: (tag: string | Component, {
1558
+ children,
1559
+ ...props
1560
+ }: Props, _unknown?: unknown) => JSX.Element;
1561
+ export const jsxs: (tag: string | Component, {
1562
+ children,
1563
+ ...props
1564
+ }: Props, _unknown?: unknown) => JSX.Element;
1565
+ export const Fragment: ({
1566
+ children
1567
+ }: {
1568
+ children: Elem[] | Elem;
1569
+ }, _unknown?: unknown) => DocumentFragment;
1570
+ export const chevronRight: JSX.Element;
1571
+ export const chevronLeft: JSX.Element;
1572
+ export const expandingContainer: ({
1573
+ duration
1574
+ }?: {
1575
+ duration?: number;
1576
+ }) => {
1577
+ expand: () => void;
1578
+ content: HTMLDivElement;
1579
+ container: HTMLDivElement;
1580
+ };
1581
+ /**
1582
+ * Like Promise.any but for async iterable infinite promises (object that have `.state` and a [Symbol.asyncIterator]). Returns an array of all current values when one value udpates.
1583
+ * @param iterables Array of IPNS
1584
+ * @return IPNS that resolves with an array of the values of all provided IPNS when one of them resolves
1585
+ */
1586
+ export function zip_async_iterables<T extends any[]>(iterables: IPNS<T[keyof T]>[]): IPNS<T>;
1587
+ /** Overrides that can specify a different amount of columns for certain rows
1588
+ * @param key The row (starts at 1) that you're "selecting" to override
1589
+ * @param value The amount of columns that your selected row should have
1590
+ */
1591
+ type Override = {
1592
+ overrides: Record< /* Row: */number, /* Column: */number>;
1593
+ };
1594
+ export type ColAtSize = /** [ <number of columns>, <min-width>, <max-width>, <spacing> ] */readonly [number, null, string, string | null] | readonly [number, string, string, null, Override] | readonly [number, string, null, string | null] | readonly [number, string, string, string | null] | readonly [number, string, null] | readonly [number, string, string] | readonly [number, null, string] | readonly [number, string];
1595
+ export type ColsAtSize = readonly ColAtSize[];
1596
+ export type LayoutOptions = {
1597
+ container_element: Element;
1598
+ cols_at_size: ColsAtSize;
1599
+ grid_spacing: string;
1600
+ rows: {
1601
+ start_rows?: number;
1602
+ rows_per_click?: number;
1603
+ ipns?: IPNS<number>;
1604
+ max_rows?: number;
1605
+ button?: HTMLElement;
1606
+ } | "all";
1607
+ layout: "slider" | "grid";
1608
+ disable_partial_rows?: boolean;
1609
+ override_vertical_spacing?: string;
1610
+ };
1611
+ export const layout_media_query_header: (min: string, max?: string) => string;
1612
+ /**
1613
+ * Grid: Calculates CSS for a grid with a certain spacing and certain number of columns at certain screen sizes, including a view more button.
1614
+ * @param rows if set to 'all': Just generate grid styling without any viewing/hiding functionality. If an object: start_rows is the number of rows at the beginning. rows_per_click is the amount of rows to view on each view more buttonn click. button is the view more button to display. ipns is an async iterable infinite promise that you can use to get and set the number of currently viewed rows
1615
+ * @param container_element container element of the elements that you want to style and hide
1616
+ * @param cols_at_size An array with sub arrays looking like this: `[n_cols, min_width_media_query, max_width_media_query, grid_spacing_for_size]`, everything after `[n_cols, min_width]` is optional. falsey value for `min_width = no min_width`
1617
+ * @param grid_spacing spacing to use if none is specified for the specific size in `cols_at_size`
1618
+ * @param disable_partial_rows If set to `true`, will not let user press "show more" if next row is a partial row. Example of partial row: `cols_at_size` says we should have 4 recs in the next row but we only have 2 left, so the row just gets 2 instead of 4, meaning it doesn't "fill out".
1619
+ * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1620
+ */
1621
+ export function Layout({
1622
+ rows,
1623
+ container_element,
1624
+ cols_at_size,
1625
+ grid_spacing,
1626
+ layout,
1627
+ disable_partial_rows,
1628
+ override_vertical_spacing
1629
+ }: LayoutOptions): Promise<void>;
1630
+ /** Getting how many recs should be displayed for a certain row (while taking override rules into account)
1631
+ * This returns number of recs for this row and all the previous ones
1632
+ * @param row The "index" of the row (counting from the top). Starts at 1.
1633
+ * @param options Your cols_at_size layout option
1634
+ */
1635
+ export function layout_get_total_rec_amount_for_row(row: number, options: LayoutOptions["cols_at_size"][number]): number;
1636
+ /**
1637
+ * Same as `get_total_rec_amount_for_row` but caps the result to never exceed @param max_recs
1638
+ */
1639
+ export function layout_get_visible_recs_without_partial_rows(rows: number, max_recs: number, options: LayoutOptions["cols_at_size"][number]): number;
1640
+ /**
1641
+ * basically equivalent of n_col_styling css mixin - generates distances for a flex grid with margins
1642
+ * @param selector_beginning Main selector targeting container classname to use in generated css
1643
+ * @param default_grid_spacing_text Spacing to use if not specified in cols_at_size for a specific size
1644
+ * @param cols_at_size An array with sub arrays looking like this: [n_cols, min_width_media_query, max_width_media_query, grid_spacing_for_size], everything after [n_cols, min_width] is optional. falsey value for min_width = no min_width
1645
+ * @param layout "slider" or "grid"
1646
+ * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1647
+ * @param only_generate_top_margins if a number, only generates top margins, not widths or side margins (this is used by the content block code to allow still having relative gap's). The provided number subtracts from the top row (makes us pretend it's shorter, for content blocks). Only works for layout = "grid"
1648
+ * @return String of generated CSS
1649
+ */
1650
+ export function n_col_styling_with_dist(selector_beginning: string, default_grid_spacing_text: string, cols_at_size: ColsAtSize, layout: "slider" | "grid", override_vertical_spacing?: string, only_generate_top_margins?: number): string;
1651
+ export interface RecommendationGridOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "layout"> {
1652
+ container_elements: Node_Array;
1653
+ container_selector?: string;
1654
+ override_rec_renderer?: typeof default_rr<T>;
1655
+ lazyfier_options?: Omit<Lazyfier_Options, "t">;
1656
+ eager_images?: boolean;
1657
+ }
1658
+ /**
1659
+ * RecommendationGrid: Searches your container_elements for ".grid" or `container_selector`, runs default_rr or `override_rec_renderer` and puts the recs into the found element. Then runs `Grid` on it.
1660
+ * @param t Instance of Tenant
1661
+ * @param recommendation_renderer_options Options for default_rr or override_rec_renderer
1662
+ * @param container_elements The elements from your container template.
1663
+ * @param container_selector Selector for finding the element in container_elements that should be the recommendations' immediate parents. A.k.a the selector for the "insertion point"
1664
+ * @param override_rec_renderer Other recommendation renderer to use apart from default_rr (i.e. placeholder_rr)
1665
+ * @param lazyfier_options Options for Lazyfier which does lazyloading of the images. Optional. Keys with the same name as the options passed by RecommendationGrid will override them.
1666
+ * @param eager_images Don't lazyload images
1667
+ * @param ...options_for_grid Options for Grid. See documentation of Grid.
1668
+ * @constructor
1669
+ */
1670
+ export function RecommendationGrid<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, {
1671
+ container_elements,
1672
+ container_selector,
1673
+ override_rec_renderer,
1674
+ lazyfier_options,
1675
+ eager_images,
1676
+ ...options_for_grid
1677
+ }: RecommendationGridOptions<T>): Promise<RecRendererResult<T>>;
1678
+ export interface EasySliderOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "rows" | "layout"> {
1679
+ rows?: {
1680
+ start_rows?: number;
1681
+ ipns?: IPNS<number>;
1682
+ } | "all";
1683
+ container_elements: Node_Array;
1684
+ container_selector?: string;
1685
+ override_rec_renderer?: typeof default_rr<T>;
1686
+ lazyfier_options?: Omit<Lazyfier_Options, "t">;
1687
+ eager_images?: boolean;
1688
+ dist_to_hide_left?: number;
1689
+ dist_to_hide_right?: number;
1690
+ stepstoslide?: number;
1691
+ center_target?: boolean;
1692
+ constructor_plugins?: ((arg0: Slider_Options) => any)[];
1693
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1694
+ button_contents?: {
1695
+ right: Node_Iterable;
1696
+ left: Node_Iterable;
1697
+ };
1698
+ button_elems?: {
1699
+ right: HTMLElement;
1700
+ left: HTMLElement;
1701
+ };
1702
+ override_vertical_spacing?: string;
1703
+ }
1704
+ export type RecommendationSliderSurface<T extends Display> = Record<string, never> | {
1705
+ elements: Node_Array;
1706
+ slider: Amazing_Slider | Amazing_Lazy_Slider;
1707
+ displays: T[];
1708
+ };
1709
+ /**
1710
+ *
1711
+ * The most epic RecommendationSlider todate
1712
+ * @param t Instance of tenant class
1713
+ * @param recommendation_renderer_options Options for Recommendation Renderer
1714
+ * @param RecommendationGrid_options Similar options object to RecommendationGrid except that it also contains options to Amazing_Slider
1715
+ * @return a Surface (object) that contains displays, elements and the instance of the slider class (as `slider`)
1716
+ */
1717
+ export function RecommendationSlider<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, {
1718
+ container_elements,
1719
+ container_selector,
1720
+ override_rec_renderer,
1721
+ lazyfier_options,
1722
+ eager_images,
1723
+ grid_spacing,
1724
+ cols_at_size,
1725
+ override_vertical_spacing,
1726
+ rows,
1727
+ ...slider_options
1728
+ }: EasySliderOptions<T>): Promise<RecommendationSliderSurface<T> | RecRendererResult<T> | Surface<T>>;
1729
+ export function slider_autoscroll_factory(interval?: number): {
1730
+ constructor_plugin(this: Amazing_Slider): void;
1731
+ mutation_plugin: (this: Amazing_Slider, _intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1732
+ };
1733
+ export function make_button1(): {
1734
+ left: [HTMLImageElement];
1735
+ right: [HTMLImageElement];
1736
+ };
1737
+ /**
1738
+ * Returns an object to put into `button_contents` for `Pro_Slider` containing the icon arrow images
1739
+ * @return An object with left and right being an array containing one image
1740
+ */
1741
+ export function make_button2(): {
1742
+ left: HTMLImageElement[];
1743
+ right: HTMLImageElement[];
1744
+ };
1745
+ export function slider_dots_factory({
1746
+ t,
1747
+ navcont_insertion_fn,
1748
+ navdot,
1749
+ dontshowonedot,
1750
+ bitesize
1751
+ }: {
1752
+ t: Tenant;
1753
+ navcont_insertion_fn?: (slider: Amazing_Slider, navcont: HTMLDivElement) => any;
1754
+ navdot: (unique_name: number, index: number) => Element;
1755
+ dontshowonedot?: boolean;
1756
+ bitesize?: number;
1757
+ }): {
1758
+ constructor_plugin: () => void;
1759
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1760
+ };
1761
+ export function navdot(unique_name: string | number): HTMLLabelElement;
1762
+ export function slider_draggable_factory(t: Tenant): {
1763
+ constructor_plugin: (slider_options: any) => void;
1764
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1765
+ post_pro_plugin: {
1766
+ instant: (items: HTMLCollection) => void;
1767
+ };
1768
+ };
1769
+ export function slider_fading_factory({
1770
+ fade_in_duration_,
1771
+ fade_out_duration_,
1772
+ visible_opacity_,
1773
+ faded_opacity_,
1774
+ easing_,
1775
+ threshold_
1776
+ }?: {
1777
+ fade_in_duration_?: number;
1778
+ fade_out_duration_?: number;
1779
+ visible_opacity_?: number;
1780
+ faded_opacity_?: number;
1781
+ easing_?: string;
1782
+ threshold_?: number;
1783
+ }): {
1784
+ readonly mutation_plugin_: (this: Amazing_Slider, entries: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1785
+ };
1786
+ export function slider_fractional_factory(_t?: any, fraction?: number, max_steps?: number, dont_enable_correct_bs_targets?: boolean, min_steps?: number): {
1787
+ constructor_plugin: (slider_options: Slider_Options) => void;
1788
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1789
+ };
1790
+ /**
1791
+ * * Plugin for rendering a scrollbar below the slider that follow the slider position.
1792
+ * * Scroll container class: `depict_slider_scroll`
1793
+ * * Scroll bar class: `depict_slider_scroll_bar`
1794
+ * @param options Options for the scrollbar. Add position styling and additional classes.
1795
+ */
1796
+ export function slider_show_scroll(options: {
1797
+ add_position_styling: boolean;
1798
+ scroll_bar_classes?: string[];
1799
+ scroll_container_classes?: string[];
1800
+ }): {
1801
+ constructor_plugin: (_slider_options: Slider_Options) => void;
1802
+ mutation_plugin: (_intersections: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1803
+ };
1804
+ export function slider_snap_css(_t?: any, {
1805
+ snapEvery,
1806
+ align
1807
+ }?: {
1808
+ snapEvery?: number;
1809
+ align?: "center" | "start" | "end";
1810
+ }): {
1811
+ constructor_plugin: (_slider_options: Slider_Options) => void;
1812
+ mutation_plugin: (_intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1813
+ };
1814
+ export function can_use_snapping_and_still_scroll(): Promise<boolean>;
1815
+ export function slider_snapping_factory(options?: {
1816
+ stepsize?: number;
1817
+ threshold?: number;
1818
+ }): {
1819
+ constructor_plugin: (slider_options: any) => void | undefined;
1820
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void | undefined;
1821
+ };
1822
+ export function slider_wraparound_factory({
1823
+ clones_per_side
1824
+ }?: {
1825
+ clones_per_side?: number | undefined;
1826
+ }): {
1827
+ constructor_plugin: (this: Amazing_Slider) => void;
1828
+ mutation_plugin: (this: Amazing_Slider, intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1829
+ post_processor: <T extends Display>(elements: Node_Array | NodeListOf<ChildNode>, _display: Display, info: InfoForProcessing<T>) => Promise<NodeListOf<ChildNode> | Node_Array>;
1830
+ };
1831
+ export type ReactiveTemplateValueContents = string | number | Node_Array[number] | undefined | (string | number | Node_Array[number])[];
1832
+ export function reactive_template(initial_value?: ReactiveTemplateValueContents): readonly [Node_Array, () => ReactiveTemplateValueContents, (arg0: ReactiveTemplateValueContents) => void];
1833
+ /**
1834
+ * A wrapper around window.matchMedia, basically cross browser compatibly adds an event listener to a media query that triggers when it changes
1835
+ * @param query The media query (without `@media`)
1836
+ * @param catchified_handler The function to execute
1837
+ * @param initial_call If the handler should be called instantly with the current state of the media query
1838
+ * @return An object containing `remove`, a function which removes the event listener again
1839
+ */
1840
+ export function javascript_media_query(
1841
+ // inspired by code in houdinisportswear modify script
1842
+ query: string, handler: (e: MediaQueryListEvent | MediaQueryList | {
1843
+ matches: false;
1844
+ }) => void, initial_call?: boolean): {
1845
+ remove(): void;
1846
+ };
1847
+ type RenderingFunction<T extends Display> = (...args: any[]) => Promise<{
1848
+ surface_: Surface<T> | void;
1849
+ cache_until_?: Promise<any>;
1850
+ }>;
1851
+ /**
1852
+ * Makes it possible to have "multiple surfaces" in one surface. So you provide multiple functions that return a `Surface` and get one `Surface` which will switch between the `Surface`s returned by the different functions depending on which one is selected by an IPNS.
1853
+ * @param surface_rendering_functions_ An array of functions returning an object that contains a Surface and a Promise until which's resolvement the Surface will be cached and re-used without calling the rendering function again.
1854
+ * @param current_surface_ An IPNS representing which Surface should currently be chosen. It has to resolve with a number corresponding with the index of a function in surface_rendering_functions_.
1855
+ * @return a `Surface` object which, utilising a `reactive_template` always represents the currently chosen surface
1856
+ */
1857
+ export function surface_mixer<T extends Display>({
1858
+ surface_rendering_functions_,
1859
+ current_surface_
1860
+ }: {
1861
+ surface_rendering_functions_: RenderingFunction<T>[];
1862
+ current_surface_: IPNS<number>;
1863
+ }): Promise<Surface<T>>;
1864
+ /**
1865
+ * To be used in conjunction with surface_mixer. Makes it possible to switch Surface depending on screen size
1866
+ * @param surface_per_size An array of arrays which represent which surface to show at which screen width. The arrays in the array can have up to three entries, the first one being: an index in the surface_rendering_functions_ array passed to `surface_mixer`, the second one: min screen width to switch to this surface, the third one: max screen width at which this surface should still be shown.
1867
+ * @param cleanup_promise Optional. A promise after which sizes_to_surface stops listening for media query changes. If none is provided we automatically stop listening on navigation away (if the href changes).
1868
+ * @return An IPNS resolving with the number of the surface that should currently be shown
1869
+ */
1870
+ export function sizes_to_surface(surface_per_size: [surface_index: number, min: string | null, max?: string][], cleanup_promise?: Promise<any>): IPNS<number>;
1871
+ /**
1872
+ * Returns a promise that resolve the next time the href is changed
1873
+ */
1874
+ export function promise_until_next_navigation(): Promise<string | undefined>;
1875
+ export function orderpage_transaction_id_extractor(t: Tenant, selector: string, filter?: (text: string) => string | undefined): void;
1876
+ /**
1877
+ * Looks at all entries in window.dataLayer, past present and future, and attempts to find transaction IDs in them.
1878
+ * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1879
+ * @param tenant The tenant we are tracking.
1880
+ * @param id_extractor Maps an entry to a transaction ID string, or something falsy if no transaction ID is found.
1881
+ * For example: entry => entry?.event?.purchase?.orderId
1882
+ */
1883
+ export function datalayer_transaction_id_extractor(tenant: Tenant, id_extractor: (layer_entry: any) => any): void;
1884
+ /**
1885
+ * Looks at all entries in window.dataLayer, past present and future, and executes the given callback on them.
1886
+ * @param interception_callback A callback that will be called on each entry pushed to dataLayer.
1887
+ */
1888
+ export function datalayer_interceptor(interception_callback: (layer_entry: any) => void): void;
1889
+ /**
1890
+ * Looks at all URL changes, including the current URL, and attempts to find transaction IDs in them.
1891
+ * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1892
+ * @param tenant The tenant we are tracking.
1893
+ * @param id_extractor Maps an URL to a transaction ID string, or something falsy if no transaction ID is found.
1894
+ * For example: url => url.searchParams.get("orderId")
1895
+ */
1896
+ export function url_transaction_id_extractor(tenant: Tenant, id_extractor: (url: URL) => unknown): void;
1897
+ export function send_transaction_id_to_depict(t: Tenant, input_id: string, session_id?: string, filter?: (text: string) => string | undefined): void;
1898
+ /**
1899
+ * Intercepts google analytics events for transactions (e.g when payment is made) and also sends it to depict.
1900
+ * */
1901
+ export function ga_to_transaction_api(t: Tenant, filter?: (text: string) => string | undefined): void;
1902
+ export interface ListenableSetEvent<T> extends CustomEvent {
1903
+ detail: T;
1904
+ }
1905
+ /**
1906
+ * Set but you can listen for values being added or removed
1907
+ * i.e. my_set.addEventListener("add", ({detail}) => console.log(detail, "was added to", my_set));
1908
+ */
1909
+ export class ListenableSet<T> extends Set<T> {
1910
+ #private;
1911
+ addEventListener(event: "add" | "delete", callback: (ev: ListenableSetEvent<T>) => unknown, options?: Parameters<(typeof EventTarget.prototype)["addEventListener"]>[2]): void;
1912
+ removeEventListener(event: "add" | "delete", callback: (ev: Event) => unknown): void;
1913
+ add(property: T): this;
1914
+ delete(property: T): any;
1915
+ }
1916
+ /**
1917
+ * This does what you'd think Element.closest does. It finds the closest node in the DOM tree matching a selector. So it starts out with the siblings and then goes upwards in the DOM and checks the siblings and their children of the parent until there's no parent anymore.
1918
+ * @param element Element to start out at
1919
+ * @param selector Selector to search for
1920
+ * @param start_right=true In what direction to start: true = right, false = left
1921
+ * @return The found element or undefined
1922
+ */
1923
+ export function chaotic_closest(element: Element, selector: string, start_right?: boolean): Element | undefined;
1924
+ type CompareMethod<T> = (i1: T, i2: T) => boolean;
1925
+ export const deduplicate: <T>(arr1: T[], arr2: T[], compareFunc: CompareMethod<T>) => T[];
1926
+ export const dedup_products: <T extends LegacyDisplay>(arr1: T[], arr2: T[] | undefined) => T[];
1927
+ /**
1928
+ * Attempt to navigate using nextjs's spa router.
1929
+ * Falls back to default browser navigation.
1930
+ * Docs: https://nextjs.org/docs/api-reference/next/router
1931
+ */
1932
+ export function navigate_with_next_router(e: MouseEvent, url: string): false | undefined;
1933
+ /**
1934
+ * proxies window.fetch:
1935
+ * 1. Instead of window.fetch fetch_apply is called, target being the original fetch function
1936
+ * 2. fetch_proxy_handler is called and may read the request and return a (fake) response
1937
+ * 3. if fetch_proxy_handler fails the original target is called with the same this and arguments
1938
+ * We are meticulously preserving this, target and its arguments in case that someone replaces fetch with a function that does something else
1939
+ * I recognise that I could hardcode window and fetch but I DO NOT want any cases where this may break anything if I can avoid it
1940
+ * Remember to return response, else it will make another request
1941
+ * @param fetch_proxy_handler Called instead of the original fetch function everytime someone does fetch. Has to return a response.
1942
+ * @param unsafe_throw_up Whether to ignore above described safety features and just pass on precisely what the fetch_proxy_handler does. If you do this, make sure to CATCH ALL ERRORS of your logic in the fetch_proxy_handler and only throw if the original fetch throws
1943
+ * @return Nothing
1944
+ */
1945
+ export function fetch_replacer(fetch_proxy_handler: (target: typeof window.fetch, this_arg: typeof window, arguments_list: Parameters<typeof window.fetch>) => Promise<Response | FakeResponse>, unsafe_throw_up?: boolean): Promise<void>;
1946
+ declare const FakeResponse_base: {
1947
+ new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response;
1948
+ prototype: Response;
1949
+ error(): Response;
1950
+ redirect(url: string | URL, status?: number | undefined): Response;
1951
+ };
1952
+ /**
1953
+ * This class extends and models the `Response` class as close as possible. Basically the only thing not being identical would be `instance_of_fake_response.constructor` and some other stuff, but nothing connected to how you're usually using a `Response` object.
1954
+ * Useful when wanting to change the result of a `fetch request`
1955
+ * Please see repo for usage examples
1956
+ * @param response_string String to base Response object on
1957
+ * @param url URL to claim that the Response is from
1958
+ * @param headers Response headers
1959
+ * @param override_options More options to pass to the `Response` constructor
1960
+ */
1961
+ export class FakeResponse extends FakeResponse_base {
1962
+ constructor(response_string: string, url: string, headers?: HeadersInit, override_options?: ResponseInit);
1963
+ }
1964
+ export type ShopifyItem = {
1965
+ id: number;
1966
+ handle: string;
1967
+ quantity: number;
1968
+ url: string;
1969
+ };
1970
+ export type ShopifyError = {
1971
+ status: number;
1972
+ message: string;
1973
+ description: string;
1974
+ };
1975
+ /**
1976
+ * Represents a Shopify cart "event", i.e. Whenever a Shopify API request is sucessfull.
1977
+ * - `type` represent the type of event
1978
+ * - `response` resolves to a shopify response
1979
+ */
1980
+ export type ShopifyEvent = {
1981
+ type: "get_items";
1982
+ response: Promise<ShopifyItem[] | ShopifyError>;
1983
+ body?: object;
1984
+ } | {
1985
+ type: "add_items";
1986
+ response: Promise<ShopifyItem[] | ShopifyError>;
1987
+ body?: object;
1988
+ } | {
1989
+ type: "update_items";
1990
+ response: Promise<ShopifyItem[] | ShopifyError>;
1991
+ body?: object;
1992
+ } | {
1993
+ type: "change_items";
1994
+ response: Promise<ShopifyItem[] | ShopifyError>;
1995
+ body?: object;
1996
+ } | {
1997
+ type: "clear_items";
1998
+ response: Promise<[] | ShopifyError>;
1999
+ body?: object;
2000
+ };
2001
+ /**
2002
+ * Whenever any request to the shopify cart endpoint (this includes requests made by merchant code) is made {@link on_response} is called.
2003
+ *
2004
+ * ### Caveats
2005
+ * - This currently doesn't intercept XHR requests, only `fetch`. Interpecpting XHR should be implemented at some point!
2006
+ *
2007
+ * - Under the hood, this function works by proxying `window.fetch`. This isn't guaranted to work, and could even break merchant code.
2008
+ * Call this function early on in the execution for the best possibillity of success.
2009
+ *
2010
+ * - If the merchant performs a `window.fetch` to Shopify before `intercept` then that response wont be intercepted.
2011
+ * If you know that the merchant will make a request to Shopify early on then it might make sense to do something like:
2012
+ * ```
2013
+ * const handle = setTimeout(catchify(() => get_items_in_cart()), 2000)
2014
+ * intercept(evt => {
2015
+ * canel_timeout(handle)
2016
+ * ...
2017
+ * })
2018
+ * ```
2019
+ * In order to get the cart contents at some point even if you miss the merchants innitialt Shopify request.
2020
+ *
2021
+ * - `intercept` intercepts all requests to Shopify, including requests made by you.
2022
+ * @param lenient: If true, also new style endpoints not ending on .js will be intercepted.
2023
+ */
2024
+ export function intercept(on_request: (event: ShopifyEvent) => any, lenient?: boolean): void;
2025
+ export type AddToCartOptions = {
2026
+ quantity?: number;
2027
+ };
2028
+ /**
2029
+ * Add an item to the Shopify cart.
2030
+ *
2031
+ * ### Caveats
2032
+ * Keep in mind that adding to the shopify cart wont neccesarily update the merchants UI,
2033
+ * it only means that when the merchant fetches the cart again then they'll get the item added by you.
2034
+ * Usually the merchant has it's own global add-to-cart function that can be used. While doing that can
2035
+ * take more developer time it means that you usually get the merchant UI to update correctly.
2036
+ *
2037
+ * @param shopify_id
2038
+ * @param options.quantity How many of an item to add, defaults to `1`.
2039
+ * @throws If the response JSON is in an unexpected format.
2040
+ */
2041
+ export function add_item(shopify_id: string, options?: AddToCartOptions): Promise<ShopifyItem[] | ShopifyError>;
2042
+ /**
2043
+ * Fetch the items in the shoppify cart.
2044
+ *
2045
+ * This is probably not the right function for mose use-cases.
2046
+ * Want to get notified when merchant code adds new items to the cart through Shopify?
2047
+ * Use {@link intercept} to intercept all calls to Shopify (even ones made by merchant code).
2048
+ *
2049
+ * @returns All items currently in the cart.
2050
+ * @throws If the response JSON is in an unexpected format.
2051
+ */
2052
+ export function get_items_in_cart(): Promise<ShopifyItem[] | ShopifyError>;
2053
+ declare global {
2054
+ interface Window {
2055
+ ShopifyAnalytics: {
2056
+ meta?: {
2057
+ product?: ShopifyMetaProduct;
2058
+ };
2059
+ };
2060
+ }
2061
+ }
2062
+ interface ShopifyMetaProduct {
2063
+ id?: string;
2064
+ vendor?: string;
2065
+ variants?: {
2066
+ id?: string;
2067
+ sku?: string;
2068
+ }[];
2069
+ }
2070
+ /** Shopify sites often has an interesting meta object defined on window.ShopifyAnalytics.meta
2071
+ * The SKU that backend requires might only be found in the meta object.
2072
+ * This function gives you that object in a safe way that won't break Shopify.
2073
+ */
2074
+ export const get_shopify_analytics_meta_product: () => Promise<ShopifyMetaProduct | undefined>;
2075
+ /**
2076
+ * Waits for google optimize and then gets the variant of a specified experiment id from it. Try not to use this when setting up A/B tests as it causes huge delays. Consider doing a server side optimize A/B test instead and use `get_and_track_variant` to get the same variant as the backend, or, if backend is not involved, use `client_side_server_side_a_b_test`
2077
+ * @param t Instance of `Tenant class`
2078
+ * @param experiment_id Optimize experiment id of running A/B test
2079
+ * @param functions_to_variants An array having a function to execute for each variant. The index of the function in the array specifies its variant.
2080
+ * @param functions_to_variants [description]
2081
+ * @return The return value of the called function
2082
+ */
2083
+ export function get_optimize_variant({
2084
+ t,
2085
+ experiment_id,
2086
+ functions_to_variants
2087
+ }: {
2088
+ t: Tenant;
2089
+ experiment_id: string;
2090
+ functions_to_variants: Function[];
2091
+ }): Promise<any>;
2092
+ /**
2093
+ * Ensures that the attribute value of an element is what an AsyncIterable resolves with
2094
+ * @param el Element to set attribute on
2095
+ * @param attribute_name Name of the attribute to set
2096
+ * @param async_iterable AsyncIterable to loop over
2097
+ * @param quit_after_navigation=true Whether to stop awaiting the AsyncIterable if the page navigates
2098
+ * @return [description]
2099
+ */
2100
+ export function iterable_to_attribute(el: Element, attribute_name: string, async_iterable: AsyncIterable<string>, quit_after_navigation?: boolean): Element;
2101
+ /**
2102
+ * Merges an IPNS with `reactive_template` - if the IPNS updates the reactive template's state is updated to what the IPNS returns
2103
+ * @param async_iterable The async iterable to use
2104
+ * @param quit_after_navigation Whether to stop listening for the IPNS when navigating away
2105
+ * @return An array of elements. Keep a reference to this since its content will update. This is because it's possible that the nodes are not yet in the DOM, meaning replaceWith won't work.
2106
+ */
2107
+ export function iterable_to_elems(async_iterable: AsyncIterable<ReactiveTemplateValueContents>, quit_after_navigation?: boolean): Node_Array;
2108
+ /**
2109
+ * Creates a context for every a function that could cause an `insert_surface` infinite loop (by restoring to old els on no recs which then again triggers an insertion) and hinders any further execution of the function of that "context" if the `insert_surface` call it contains fails
2110
+ * @param ...args Any arguments that will also be passed on to the wrapped function. If the wrapped function takes an ElementObserverEvent the disconnector on it will also be called if a context should be "stopped";
2111
+ * @return A wrapped function that now executes in a context
2112
+ */
2113
+ export const prevent_infinite_loop: <A extends any[], B>(cb: (...args: A) => void | B) => (...args: A) => void | B;
2114
+ /**
2115
+ * Inserts one or multiple surfaces into the DOM.
2116
+ * Will also revert (if verb is `replaceWith`) or remove the inserted elements again if placeholder rendering fails. This happens by a promise inside of the `Surface`s
2117
+ * @param surfaces Array with surfaces to insert
2118
+ * @param verb Verb on how to insert
2119
+ * @param target Selector for `observer.onexists` to find element to insert VERBto, alternatively an element
2120
+ * @param remove_after_navigation Whether to remove the elements from the DOM again if a navigation away occurs, defaults to true
2121
+ * @param try_forever Whether to try to insert the same surface even after the page has navigated away, defaults to false
2122
+ * @param preserve_elements Whether to reinsert elements into it's container if they are removed, useful for sites using VDOM diffing such as react where nodes that aren't in the VDOM are removed when rerendering
2123
+ * @return An array of promises, corresponding to the provided surfaces, where each promise will resolve with an object containing the surface and whether it failed or succeded
2124
+ */
2125
+ export function insert_surfaces<T extends Display>({
2126
+ surfaces: input_surfaces,
2127
+ verb,
2128
+ target,
2129
+ remove_after_navigation,
2130
+ try_forever,
2131
+ preserve_elements
2132
+ }: {
2133
+ verb: InsertionVerb;
2134
+ target: string | HTMLElement;
2135
+ remove_after_navigation?: boolean;
2136
+ try_forever?: boolean;
2137
+ surfaces: (Promise<Surface<T> | void> | Surface<T> | void)[];
2138
+ preserve_elements?: boolean;
2139
+ }): Promise<{
2140
+ surface: Surface<T>;
2141
+ succeeded: boolean;
2142
+ }>[];
2143
+ export const revertable_remove: (target: string | Element | Node_Array, should_stay_inserted: Promise<boolean>) => Promise<void | undefined>;
2144
+ type MakePlaceholderRROption<T extends Display> = {
2145
+ override_rec_renderer?: (t: Tenant | null, rendering_options: Extended_RR_Options<T>) => Promise<RecRendererResult<T>>;
2146
+ image_width?: number;
2147
+ image_height?: number;
2148
+ color?: string;
2149
+ num_items?: number;
2150
+ on_no_rendering_result?: (result?: RecRendererResult<T>) => any;
2151
+ post_rendering?: (surface?: RecRendererResult<T>) => Promise<void> | void;
2152
+ };
2153
+ /**
2154
+ * We want to deprecate this
2155
+ */
2156
+ export type PlaceholderRenderingDisplay = {
2157
+ sale_price: number;
2158
+ page_url: "#" | string;
2159
+ image_url: string;
2160
+ original_price: number;
2161
+ product_id: "placeholder" | string;
2162
+ recommendation_id: "placeholder" | string;
2163
+ title: string;
2164
+ brand: string;
2165
+ };
2166
+ export const random_text_placeholder: () => string;
2167
+ export const placeholder_svg: (image_width: number, image_height: number, color?: string) => string;
2168
+ /**
2169
+ * Wraps default_rr or provided override_rec_renderer in two rendering passes where the first one will render placeholders and the second one what actually is asked for. As soon as the second pass completes the result of the first one is replaced with it.
2170
+ * @param [override_rec_renderer=default_rr] The recommendation renderer to use
2171
+ * @param [image_width=2000] Width of placeholder image svg (use to set aspect ratio)
2172
+ * @param [image_height=2000] Height of placeholder image svg (use to set aspect ratio)
2173
+ * @param [num_items=10] Number of placeholders to render
2174
+ * @param [color="#d9d9d9"] Color of placeholder image svg
2175
+ * @param [on_no_rendering_result] If rendering of actual recommendations fails (doesn't yield any `elements`) this function will be called with the rendering result as first argument
2176
+ * @param [post_rendering] Will be called and awaited after rendering of actual recommendations, has a chance to change them before they get inserted into the DOM
2177
+ * @return It returns the same as a normal recommenation renderer would, meaning an object that might contain `displays` and `elements`
2178
+ */
2179
+ export function make_placeholder_rr<T extends Display>({
2180
+ override_rec_renderer,
2181
+ image_width,
2182
+ image_height,
2183
+ num_items,
2184
+ color,
2185
+ on_no_rendering_result,
2186
+ post_rendering
2187
+ }?: MakePlaceholderRROption<T>): Promise<(t: Tenant | null, rendering_options: Extended_RR_Options<T | PlaceholderRenderingDisplay>) => Promise<Record<string, never> | {
2188
+ elements: Node_Array;
2189
+ displays: T[];
2190
+ }>>;
2191
+ /**
2192
+ * Makes Node.prototype.removeChild not throw and emulate correct removal when a node is being removed by React's VDOM diffing that we have already removed before
2193
+ * @return a WeakSet to add nodes to which you remove and want to ignore removal errors for
2194
+ */
2195
+ export function removeChild_error_swallowing_factory(): WeakSet<Node>;
2196
+ /**
2197
+ * restore (if no allSettled and prototype.finally) native Promise and cement Promise - some customers force polyfill promise with flawed implementations of .all and .allSettled that randomly throw (see usage examples)
2198
+ * @return void
2199
+ */
2200
+ export function replace_promise_with_native_if_exists_and_enforce(): void;
2201
+ /**
2202
+ * Creates a blank iframe inside <head> and returns window.Promise out of it
2203
+ * @return a pristine, unpolyfilled window.Promise
2204
+ */
2205
+ export function get_iframe_promise(): PromiseConstructor;
2206
+ /**
2207
+ * Proxies XMLHttpRequest.prototype.open to an open function which also calls the provided `fetch_handler` with useful information as parameter
2208
+ * @param fetch_handler A function which is catchified and which's return value is ignored. It gets called every time an XHR request gets opened
2209
+ * @return void
2210
+ */
2211
+ export function xhr_replace(fetch_handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, arg_array: Parameters<typeof XMLHttpRequest.prototype.open>) => void): void;
2212
+ /**
2213
+ * xhr_load uses xhr_replace but adds the provided handler as a "load" event listener to every XHR request instead of calling it on open
2214
+ * @param handler The function called on load of every XHR request.
2215
+ * @return void
2216
+ */
2217
+ export function xhr_load(handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, event: ProgressEvent<XMLHttpRequestEventTarget>) => any): void;
2218
+ export function xhr_send_interceptor(send_callback: (request: XMLHttpRequest, open_args: Parameters<typeof XMLHttpRequest.prototype.open>, send_args: Parameters<typeof XMLHttpRequest.prototype.send>) => any): Promise<void>;
2219
+ /**
2220
+ * Intercepts someone reading `response`, `responseText` and `responseXML` on an XMLHttpRequest
2221
+ * @param read_callback Called everytime a response is read from an XMLHttpRequest which has been opened and sent - it doesn't have to have received a response yet so please keep in mind that you might have to pass through `undefined` if `orig_result` is `undefined`.
2222
+ */
2223
+ export function xhr_read_interceptor(read_callback: (request: XMLHttpRequest, open_args: Parameters<typeof XMLHttpRequest.prototype.open>, send_args: Parameters<typeof XMLHttpRequest.prototype.send>, orig_result: string | undefined, property_name: "responseText" | "response" | "responseXML") => string): Promise<void>;
2224
+ export function default_rp_fixes(orig_url?: string | undefined): Promise<void>;
2225
+ export function rp_relativify_history(orig_url_with_trailing_slash: string): void;
2226
+ export function rp_relativify_fetch(orig_url_with_trailing_slash: string): void;
2227
+ export function rp_relativify_xhr(orig_url_with_trailing_slash: string): void;
2228
+ /**
2229
+ * Recursively sorts the keys in an object (NOT in-place, returns a new object). Do not provide objects containing anything other than primitives or other objects. Do not provide objects that have cyclical values.
2230
+ */
2231
+ export function sort_obj<T>(maybe_obj: T): any;
2232
+ /**
2233
+ * Tries to figure out the tenant's market (`TwoLetterMarket` for new integrations) through various means.
2234
+ *
2235
+ * 1. Checks if there is a market in one of the url segments (www.tentant.se/foo/se/bar)
2236
+ * 2. Checks if the market is specified in the tenant's domain name (www.tenant-se.com)
2237
+ * 3. Checks the toplevel domain (www.tenant.se/foo/bar)
2238
+ *
2239
+ * @param allowed_markets An array the possible markets for the tenant.
2240
+ * Dont forget to specify the allowed market as const (`["se", "en"] as const`) to get the best typing
2241
+ * @param url Specify this to overide the url to check, defaults to the current url
2242
+ * @param tenant The tenant's name
2243
+ * @returns If a market specified in `allowed_markets`was found that is returned, `undefined` otherwise
2244
+ */
2245
+ export function standard_get_market<T extends readonly string[]>(allowed_markets: T, url?: string, tenant?: string): T[number] | undefined;
2246
+ /**
2247
+ * Listens to localstorage changes with `setItem` and direct assignment.
2248
+ * @param listener a function to invoke every time something in the localStorage changes. It gets two arguments: key and value, key being the key of the item set and value being the value of the item set.
2249
+ */
2250
+ export function listenToLocalStorage(listener: (key: string, value: string) => void): void;
2251
+ /**
2252
+ * Timeout a promise after `ms` milliseconds.
2253
+ * If the promise is timed out this function will return `undefined` and not throw.
2254
+ */
2255
+ export function timeout_promise<T>(promise: Promise<T>, ms: number): Promise<Awaited<T> | undefined>;
2256
+ /**
2257
+ * Uses the default Voyado ID that is used in Voyado email recommendations.
2258
+ */
2259
+ export const use_voyado_id: () => void | undefined;
2260
+ type ButtonProps = Omit<Partial<JSX.IntrinsicElements["button"]>, "type"> & {
2261
+ class?: string;
2262
+ };
2263
+ export function DefaultViewMoreButton({
2264
+ children,
2265
+ ...attributes
2266
+ }: ButtonProps): HTMLButtonElement;
2267
+ export function GeneralSideSlidein({
2268
+ title_,
2269
+ children,
2270
+ CloseIcon
2271
+ }: {
2272
+ title_: IPNS<string>;
2273
+ children: HTMLElement | HTMLElement[];
2274
+ CloseIcon: () => HTMLElement | SVGElement;
2275
+ }): Promise<{
2276
+ close_: VoidFunction;
2277
+ on_close_: (fn: VoidFunction) => number;
2278
+ }>;
2279
+ export function GeneralSizeSelector({
2280
+ title_,
2281
+ items_,
2282
+ out_of_stock_text_,
2283
+ CloseIcon
2284
+ }: {
2285
+ title_: IPNS<string>;
2286
+ out_of_stock_text_: IPNS<string>;
2287
+ items_: {
2288
+ id_: string;
2289
+ size_name_: string;
2290
+ is_available_: boolean;
2291
+ }[];
2292
+ CloseIcon: () => HTMLElement | SVGElement;
2293
+ }): Promise<string | void>;
2294
+ type PlaceholderProps = Omit<Partial<JSX.IntrinsicElements["div"]>, "style"> & {
2295
+ /** Any extra classes togheter with the default `depict-placeholder` class */
2296
+ class?: string;
2297
+ /** Convinence prop for setting element width */
2298
+ width?: string;
2299
+ /** Convinence prop for setting element height */
2300
+ height?: string;
2301
+ /** Will override the usage of width & height */
2302
+ style?: string;
2303
+ };
2304
+ type PlaceholderImageProps = Omit<PlaceholderProps, "width" | "height" | "style"> & {
2305
+ aspect_ratio: number;
2306
+ };
2307
+ /**
2308
+ * A Placeholder with shimmering animation.
2309
+ * For text you can use `height="1em"`.
2310
+ * For specific number of characters use `ch`, ex: `width="7ch"`
2311
+ */
2312
+ export const Placeholder: ({
2313
+ width,
2314
+ height,
2315
+ class: extra_classes,
2316
+ style,
2317
+ ...attributes
2318
+ }: PlaceholderProps) => HTMLDivElement;
2319
+ /**
2320
+ * A wrapper of Placeholder with full width and maintained aspect ratio.
2321
+ * @see {@link Placeholder}
2322
+ */
2323
+ export const ContainedPlaceholderImage: ({
2324
+ aspect_ratio,
2325
+ ...attributes
2326
+ }: PlaceholderImageProps) => HTMLDivElement;
2327
+ export const RecommendationContainer: (title?: string | HTMLElement, surface_classes?: string[]) => HTMLDivElement;
2328
+ export const RightChevron: () => JSX.Element;
2329
+ export const LeftChevron: () => JSX.Element;
2330
+ export type ColorObj = {
2331
+ /** the value passed as a css color */
2332
+ value: string;
2333
+ /** if specified, it's used as a title on hover */
2334
+ label?: string;
2335
+ /** Allow for arbitrary data to be passed */
2336
+ [key: string]: any;
2337
+ };
2338
+ interface ColorPickerProps {
2339
+ /** An array of colors that can be selected */
2340
+ colors: ColorObj[];
2341
+ onSelect: (color: ColorObj) => unknown;
2342
+ /**
2343
+ * Called everytime a color is hovered
2344
+ */
2345
+ onHoverUpdate?: (color: ColorObj, hovering: boolean) => unknown;
2346
+ /**
2347
+ * The color value to be initially selected. Can be omitted for no color to be selected.
2348
+ * If multiple colors use the same hex value, the label can also be specified (using a ColorObj)
2349
+ */
2350
+ initialColor?: string | ColorObj;
2351
+ /**
2352
+ * Enabled hovering preview. When true `onSelect` will be called with a new color when it's hovered,
2353
+ * then reverts back to the last clicked color when hovering is stopped
2354
+ * */
2355
+ selectOnHover?: boolean;
2356
+ /**
2357
+ * If set to true only `onSelect` will be called when an item is clicked
2358
+ */
2359
+ dontSetActiveOnClick?: boolean;
2360
+ /**
2361
+ * If only circles should be returned and not the container element
2362
+ */
2363
+ onlyCircles?: boolean;
2364
+ }
2365
+ /**
2366
+ * A color selector, that calls onSelect when a color is clicked and optionally on hover as well.
2367
+ */
2368
+ export function createColorPicker({
2369
+ colors,
2370
+ initialColor,
2371
+ onSelect,
2372
+ selectOnHover,
2373
+ onHoverUpdate,
2374
+ dontSetActiveOnClick,
2375
+ onlyCircles
2376
+ }: ColorPickerProps): {
2377
+ setActiveIndex: (index: number) => void | undefined;
2378
+ ColorPicker(): JSX.Element;
2379
+ };
2380
+ /**
2381
+ * For example how to use, check /src/glitter/main.tsx
2382
+ * Warning: Don't use margins for the element you want to expand, since the animation will look janky
2383
+ * EDIT: above no longer applies if you only have one element that you want to expand
2384
+ */
2385
+ export const useExpandingContainer: ({
2386
+ duration,
2387
+ delay
2388
+ }?: {
2389
+ duration?: number;
2390
+ delay?: number;
2391
+ }) => {
2392
+ ExpandingContainer: ({
2393
+ children
2394
+ }: {
2395
+ children?: Elem | Elem[] | undefined;
2396
+ }) => HTMLElement;
2397
+ expand: (expanding_delay?: any, time_to_expand?: any) => Promise<Animation | undefined>;
2398
+ collapse: (collapsing_delay?: any, time_to_collapse?: any) => Promise<Animation | undefined>;
2399
+ };
2400
+ export const resize_base_url: string;
2401
+ export const is_safari: boolean;
2402
+ /**
2403
+ * make_sizes_setter attaches a ResizeObserver to what_to_watch and returns a function to call to set the `sizes` attribute of the provided el_to_resize attribute to the width of `what_to_watch` on every ResizeObserver callback
2404
+ * @param what_to_watch Element to watch resizing of
2405
+ * @param sizes_communicator the IPNS which communicates the sizes. You can provide your own to get access to the watched sizes. This is usable i.e.to set "width" and "height" attributes to satisfy lighthouse flawed anti layout shift suggestions
2406
+ * @param resolution_factor a factor to multiply the target-to-display resolution with
2407
+ * @return A function that will set the `sizes` atribute of the provided element to the size of `what_to_watch`, continuously
2408
+ */
2409
+ export function make_sizes_setter(what_to_watch: HTMLElement, sizes_communicator?: IPNS<number>, resolution_factor?: number): (el_to_resize: HTMLSourceElement | HTMLImageElement) => Promise<void>;
2410
+ /**
2411
+ * This function returns a function that can be used as JSX component.
2412
+ * It builds upon `make_sizes_setter` and uses it to set the `sizes` attribute of <source> and a fallback <img> tag that it creates.
2413
+ * @param what_to_watch The Element representative of all other images which size will be used to determine the required image sizes for the other images.
2414
+ * @param set_dataset Whether to set `img.src` or `img.dataset.src`. If you're using Lazyfier (builtin to Pro_Slider) the latter is better. Defaults to true.
2415
+ * @param formats An array of formats supported by the backends "ResizeImage" to allow the browser to use
2416
+ * @param resolutions An array of resolutions to generate a srcset for
2417
+ * @param sizes_communicator IPNS of which the resolution sets the `sizes` attribute on the images
2418
+ * @param sizes_setter_ a sizes setter returned by make_sizes_setter, you can provide one if you created it before creating the images
2419
+ * @param resolution_factor a factor to multiply the target-to-display resolution with
2420
+ * @param market_ market to append to ResizeImage proxy, see discussion here: https://depictaiworkspace.slack.com/archives/C02KVDZ8YHZ/p1649162060750759?thread_ts=1649152089.815529&cid=C02KVDZ8YHZ. It's opt-in but should always be set for integrations that have very many images (like a million+)
2421
+ *
2422
+ * @example Per surface:
2423
+ * `const SourcesetComponent = make_sourceset_component(first_canvas, true, ["webp", "png", "tiff"]);`
2424
+ * and then instead of your <img> tags: `<SourcesetComponent data-src={d.image_url} class="image" />`
2425
+ */
2426
+ export function make_sourceset_component({
2427
+ what_to_watch,
2428
+ set_dataset,
2429
+ formats,
2430
+ resolutions,
2431
+ sizes_communicator,
2432
+ resolution_factor,
2433
+ market_,
2434
+ sizes_setter_
2435
+ }?: {
2436
+ what_to_watch?: HTMLElement;
2437
+ set_dataset?: boolean;
2438
+ formats?: string[];
2439
+ resolutions?: number[];
2440
+ sizes_communicator?: IPNS<number>;
2441
+ resolution_factor?: number;
2442
+ market_?: string;
2443
+ sizes_setter_?: ReturnType<typeof make_sizes_setter>;
2444
+ }): (image_options: Partial<JSX.IntrinsicElements["img"]> & {
2445
+ class?: string;
2446
+ }) => JSX.Element;
2447
+ /**
2448
+ * Adds query parameters from the `params` parameter to the `base` url.
2449
+ * Guaranteed to be correctly escaped and not doubled and perfectly formatted
2450
+ * @param base base url, can be relative
2451
+ * @param params an object like `{'param1': 'value'}` that will lead to `?param1=value` on the url
2452
+ * @return an absolute URL with the added query parameters
2453
+ */
2454
+ export function make_url_with_query_params(base: string, params: {
2455
+ [key: string]: any;
2456
+ }): string;
2457
+ export interface ImageOptions extends Partial<HTMLImageElement> {
2458
+ aspect_ratio: number;
2459
+ class?: string;
2460
+ rendering_options?: RR_Options<any>;
2461
+ srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2462
+ alt: string;
2463
+ remove_on_error?: boolean;
2464
+ /**
2465
+ * If true, inserts grey placeholder svg's before the image lazyloader and the sourceset component add the real source
2466
+ */
2467
+ init_with_placeholder?: boolean;
2468
+ }
2469
+ /**
2470
+ * Contained image gives an image (a container with) intrinsic size of the given aspect ratio, filling out available space.
2471
+ * It means that images with different aspect ratios will all take the same amount of space
2472
+ * and the sides where it doesn't fit the aspect ratio will be filled with transparent.
2473
+ * It makes sure the images doesn't get squished like setting `width` and `height` would do.
2474
+ * @param aspect_ratio The aspect ratio of the image, i.e. 4/3 = 1,3̅
2475
+ * @param alt Alt text of the image
2476
+ * @param remove_on_error Whether to remove the image if loading fails
2477
+ * @param rendering_options The rendering options. Please always provide this, it's only optional for compatibility reasons.
2478
+ * You should provide the `rendering_options` to the second argument, InfoForProcessing, provided to a template or preprocessor.
2479
+ * When provided to a postprocessor of a recommendation-renderer it will be the third argument
2480
+ * If you provide this, ContainedImage will automatically use `make_sourceset_component`
2481
+ * and the image resizing proxy to get you responsive images in a modern format (webp).
2482
+ * @param srcset_opts The options passed to `make_sourceset_component`, only used if `rendering_options` is set.
2483
+ * @param Everything else: attributes on the <img> tag
2484
+ * @returns It depends on options and build target. But it's always one HTMLElement.
2485
+ */
2486
+ export const ContainedImage: ({
2487
+ init_with_placeholder,
2488
+ ...options
2489
+ }: ImageOptions) => HTMLElement;
2490
+ type HoverImageOptions = ImageOptions & {
2491
+ mobile_touch_hover?: boolean;
2492
+ extra_container_class?: string;
2493
+ main_extra_classes?: string;
2494
+ second_src?: string;
2495
+ second_srcset?: string;
2496
+ second_srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2497
+ fade_length_seconds?: number;
2498
+ /** The minimum amount of time for a touch to be considered a link click */
2499
+ navigation_minimum_ms?: number;
2500
+ };
2501
+ export const ContainedHoverImage: ({
2502
+ second_src,
2503
+ second_srcset,
2504
+ second_srcset_opts,
2505
+ fade_length_seconds,
2506
+ mobile_touch_hover,
2507
+ navigation_minimum_ms,
2508
+ ...options
2509
+ }: HoverImageOptions) => HTMLDivElement;
2510
+ /**
2511
+ * Shallowly converts all keys in an object from snake_case to camelCase.
2512
+ * Does not support symbol keys.
2513
+ *
2514
+ * @param obj the object. It will be cloned and not modified in-place.
2515
+ */
2516
+ export function camelCasifyObject<T extends {
2517
+ [key: string]: any;
2518
+ }>(obj: T): KeysToCamelCase<T>;
2519
+ /**
2520
+ * Shallowly converts all keys in an object from camelCase to snake_case.
2521
+ * Does not support symbol keys.
2522
+ * @param obj the object. It will be cloned and not modified in-place.
2523
+ */
2524
+ export function snakeCasifyObject<T extends {
2525
+ [key: string]: any;
2526
+ }>(obj: T): KeysToSnakeCase<T>;
2527
+ type CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}` ? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}` : Lowercase<S>;
2528
+ type KeysToCamelCase<T> = { [K in keyof T as CamelCase<string & K>]: T[K] };
2529
+ type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelToSnakeCase<U>}` : S;
2530
+ type KeysToSnakeCase<T> = { [K in keyof T as CamelToSnakeCase<string & K>]: T[K] };
2531
+ /**
2532
+ * Converts RGB to HSL
2533
+ * Source of function: https://www.30secondsofcode.org/js/s/rgb-to-hsl
2534
+ */
2535
+ export function rgb_to_hsl(r: number, g: number, b: number): readonly [number, number, number];
2536
+ /**
2537
+ * Converts HSL to RGB
2538
+ * Source of function: https://www.30secondsofcode.org/js/s/hsl-to-rgb
2539
+ */
2540
+ export function hsl_to_rgb(h: number, s: number, l: number): readonly [number, number, number];
2541
+ /**
2542
+ * Converts HSV (or HSB, it's the same) to RGB.
2543
+ * Source of function: https://www.30secondsofcode.org/js/s/hsb-to-rgb/
2544
+ */
2545
+ export function hsb_to_rgb(h: number, s: number, b: number): readonly [number, number, number];
2546
+ /**
2547
+ * Calculates the relative luminance of a RGB color
2548
+ * Source: https://gist.github.com/jfsiii/5641126
2549
+ */
2550
+ export function relative_luminance_from_rgb(R8bit: number, G8bit: number, B8bit: number): number;
2551
+ /**
2552
+ * Converts a hex string to an RGB array
2553
+ * Source: https://stackoverflow.com/a/39077686
2554
+ */
2555
+ export function hex_to_rgb(hex: string): [number, number, number] | null;
2556
+ /**
2557
+ * Synchronizes an HTML element's content with a provided Solid.js accessor's value. You can decide what "content" means.
2558
+ *
2559
+ * By default, the function utilizes the `textContent` property of the provided element to
2560
+ * synchronize its text content. However, this behavior can be customized by providing optional
2561
+ * `getContent` and `setContent` functions.
2562
+ *
2563
+ * @param {string} selector - The CSS selector of the target HTML element.
2564
+ * @param {Accessor<string | undefined>} data - Solid.js accessor that holds the text data to be synchronized.
2565
+ * @param {Object} [opts] - Optional configuration object.
2566
+ * @param {Function} [opts.getContent] - A function that retrieves the current content of a given HTML element.
2567
+ * If not provided, defaults to retrieving the `textContent` property of the element.
2568
+ * @param {Function} [opts.setContent] - A function that sets the content of a given HTML element based on the provided string.
2569
+ * If not provided, defaults to setting the `textContent` property of the element.
2570
+ */
2571
+ export function sync_el_content_with_accessor(selector: string, data: Accessor<string | undefined>, opts?: {
2572
+ getContent: (el: Element) => string | undefined | null;
2573
+ setContent: (el: Element, content: string) => void;
2574
+ }): void;
2575
+ /**
2576
+ * Returns an accessor that reactively returns the current href of the page
2577
+ */
2578
+ export function use_href_accessor(): Accessor<string>;