import { JSX, Accessor } from "solid-js"; export const version = "2.6.21"; export const is_debug: boolean; /** * Sets the prefix of dlog, dwarn, and derror messages in the browser console. Defaults to `[Depict]`. */ export const set_browser_prefix: (str: any) => void; export function dlog(...args: any[]): void; export function dwarn(...args: any[]): void; export function derror(...args: any[]): void; /** * Adds things to the object we send to backend in the query params to report the package versions used */ export const version_info: { [key: string]: string; }; export function add_to_version_info(package_name: string, version: string): void; /** * Adds the version info to the query params of a URL * @param url: a URL object or a string containing a relative or absolute URL * @returns the same type as the input but with added query params */ export function add_version_query_params(url: T): T; /** * 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. * 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 * queue is the queue of values that subscribers gets called with * last_processed_value is the last value that the subscribers were called with * push_value adds a new value to the queue and triggers the calling of the subscribers if they're done * 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 */ export class RawObservableInformation { subscribers_: ((val: T) => void)[]; waiting_for_update_: number; queue_: T[]; last_processed_value_: T | undefined; has_had_value_: boolean; push_value_: (value: T) => void; call_subscribers_: () => void; subscriber_done_: () => void; } /** * Makes an asyncIterable function out of a RawObservableInformation instance */ export function make_simple_async_iterable(state: RawObservableInformation): ((...values: T[]) => void) & { [Symbol.asyncIterator](): { next(): Promise<{ value: T; done: false; }>; return(): Promise<{ value: T; done: false; }>; }; }; /** * 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. * @param async_iterable The async iterable you want to make exitable * @return An array containing a function, the exit function, and a wrapped async iterable */ export function make_asyncIterable_exiter(async_iterable: AsyncIterable): [() => void, AsyncIterable]; export type IPNS = ((...values: T[]) => void) & AsyncIterable & { exit: () => void; state: T | undefined; latest_call_value: T | undefined; }; /** * 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 * # More about IPNS * It's a form of observable. Basically an infinite promise. * You await it by using for-await and you resolve it (as often as you like) by calling it. * List of random details: * 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 * 2. Giving it multiple arguments and calling it multiple times is the same thing * 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. * 4. You can use make_asyncIterable_exiter() to make individual for-await loop exit (stop awaiting the infinite promise) from the outside * 5. You can of course break and return any time from the for-await to stop awaiting * 6. IPNS.state gives you the value that's currently processed inside of the for-awaits from the outside * 7. IPNS.latest_call_value is the value that the IPNS was last called with (it doesn't have to have propagated everywhere yet) * @param exitable Whether the async iterator should return the currently resolving value on the first call or not * @param {state_obj} RawObservableInformation instance that contains the actual inner values of the IPNS * @return An IPNS. */ export function async_iterable_ipns(async_iterator_should_return_state_on_first_call?: boolean, state_obj?: RawObservableInformation): IPNS; /** * 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 * @param ipns IPNS to create "clone" of * @return A "cloned" ipns with the desired state-behavior. Keep in mind that exiting this one will not exit the one that was cloned. */ export function make_ipns_stateless(ipns: IPNS): IPNS; /** * 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 * @param ipns IPNS to create "clone" of * @return A "cloned" ipns with the desired state-behavior. Keep in mind that exiting this one will not exit the one that was cloned. */ export function make_ipns_stateful(ipns: IPNS): IPNS; export const Sentry: Hub | { captureException: (...args: any[]) => void; captureMessage: (...args: any[]) => void; withScope: (...args: any[]) => void; }; /** * @deprecated please use report instead and provide a severity */ export function err(exception: Error | any, error_for_stack?: Error): undefined; /** * 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. * The function uses getters and setters instead of polling which means it doesn't waste any resources. * If there are already getters or setters the function will proxy them, retaining their original functionality. * Only drawback is you can only wait for the variable being defined once, not for every change. * @param obj The base object to look in * @param property The property to wait for first * @param ...sub_objects_to_wait_for A list of further properties to wait for in the result of the last awaited thing * @return A promise containing the value of the variable that has been defined */ export function is_available_in(obj: Object, property: PropertyKey, ...sub_objects_to_wait_for: PropertyKey[]): any; export function find_descriptor(obj: Object, prop: PropertyKey): PropertyDescriptor | undefined; export function variable_setter_to_ipns(obj: Object, variable: PropertyKey, async_iterator_should_return_state_on_first_call?: boolean): IPNS; export const setOverrideSentryEnvironment: (env: string) => string; /** * Finds most frequent item in an array, written by chatGPT with some nudging. Returns `undefined` if the array is empty. * @param arr array to find the most frequent item in */ export function findMostFrequentItem(arr: T[]): T | undefined; /** * Encoding UTF8 ⇢ base64 */ export function base64_encode_unicode(str: any): string; /** * Decoding base64 ⇢ UTF8 */ export function base64_decode_unicode(str: any): string; /** * Severity level to send to sentry. * We can also send `log`, `info`, `debug`, `critical` and `fatal` but we haven't had a need for it yet. */ type Severity = "error" | "warning"; /** * Wraps a function in a try/catch that sends the error to sentry. * Also works for functions returning a promise/async functions. * If the function threw the wrapped function will return `undefined` * @param fn The function to wrap * @param message The message of the sentry error * @param severity The severity level to send to sentry */ export function catchify(fn: (...args: T) => X, message?: string, severity?: Severity): (...args: T) => X extends Promise ? Promise> : X | undefined; /** * Send error message with given severity and extra info to sentry * @param msg Error object to send to sentry or an array containing an error and a human-readable description for said error * @param severity How severe the error is. * - `"error"` - Things like not finding the market, unexpected product-id format. Even one of these errors is cause for concern. * - `"warning"` - Things that we expect to happen _sometimes_, like network errors. A couple of them is normal, * but if we suddenly get 1000s then that's an issue * @param input_data An object with extra information to sent to sentry. * * @example * report([err, "Got to few recs"], "warning", { * product_id, * }) */ export function report(msg: Error | [Error, string], severity: Severity, input_data?: { [key: string]: any; stack?: never; }): void; /** * Gives a random number between min and max (potentially including min and max). * @param min The minimum number. * @param max The maximum number. * @returns a random number */ export function rand(min: number, max: number): number; export type AsyncFunction = (...args: A) => Promise; /** * Wraps an async function and makes sure the returned wrapped function can only be "executing" once at the same time. * @param the_function an async function to wrap * @return The same function but wrapped so that it can only run once at once, no matter how often you call it */ export function deparallelize(the_function: AsyncFunction): (...args: A) => Promise | undefined>; /** * 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. */ export function deparallelize_no_drop(the_function: AsyncFunction): (...args: A) => Promise | undefined>; /** * @deprecated use async_iterable_ipns instead. It has a nicer API and more of an ecosystem. */ export class infinite_promise_no_skip { #private; promise: Promise; resolve: (value: T) => void; } type ws_event_callback = typeof WebSocket.prototype.onmessage; export interface AutoReconnectingWS { onclose: ws_event_callback; onerrror: ws_event_callback; onmessage: ws_event_callback; onopen: ws_event_callback; } export class AutoReconnectingWS extends EventTarget { #private; current_socket: WebSocket; restart_ws: (arg0?: any) => any; increase_fails(): void; send(...args: Parameters): Promise; constructor(url: string, protocols?: string | string[], options?: { max_backoff_ms?: number; }); } export class DepictAPIWS extends AutoReconnectingWS { #private; ensure_sent(payload: { id: string; event?: depict_body; [key: string]: any; }): Promise; constructor(...params: [url: ConstructorParameters[0], protocols?: ConstructorParameters[1], options?: ConstructorParameters[2] & Partial<{ initial_retry_ms: number; }>]); } export const base_url: string; /** * Returns a random string * @return A random string, containing a-z, 0-9 and occasionally a dot (`.`) */ export function random_string(): string; export function make_random_classname(): string; /** HTTP is the default; both also sends identical events over a canary socket. */ export type EventTransport = "http" | "both"; /** Configure before tracking starts; shared by users of this utilishared module. * Switching to http stops new socket sends but leaves an existing canary socket open. */ export function set_event_transport(value: EventTransport): void; export type event_types = "page_view" | "click" | "add_to_cart" | "purchase" | "element_visible"; declare const allowed_keys: readonly ["deduplication_id", "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"]; export type depict_body = Partial<{ [K in (typeof allowed_keys)[number]]: any }>; export type depict_payload = depict_body[]; type any_properties = { [key: string]: any; }; export type noisy_depict_payload = (depict_body & any_properties)[]; export const filter_depict_payload: (payload: noisy_depict_payload) => depict_payload | undefined; export const send_websocket: (bodies: depict_payload) => Promise; /** use_ws is retained for compatibility; transport is configured with set_event_transport. */ export const send_depict_unfiltered: (payload: depict_payload, use_ws?: any) => boolean | Promise | undefined; export const foolproof_send_beacon: (url: string, payload: { [key: string]: any; }) => boolean | undefined; export const send_depict: (payload: noisy_depict_payload, use_ws?: boolean | undefined) => boolean | Promise | undefined; export let get_session_id: () => string; export const set_session_id_fn: (newfn: () => string) => (() => string) | undefined; export type TrackingEventContextData = { session_id: string; url: string; document_width: number; document_referrer: string; }; export const get_tracking_event_context_data: () => TrackingEventContextData; /** * Sends a depict tracking event with prefilled data */ export const depict_prefilled: (vars: Partial<{ type: any; detail: any; url: any; currency: any; deduplication_id: any; tenant: any; market: any; session_id: any; product_id: any; entity_identifiers: any; entity_price: any; document_referrer: any; document_width: any; attribution_id: any; recommendation_id: any; click_location: any; ab_test_group: any; variant_ids: any; transaction_id: any; error_type: any; recommendation_type: any; search_result_id: any; product_listing_result_id: any; }> & { [key: string]: any; }, use_ws?: boolean | undefined) => boolean | Promise | undefined; export const depict_click: (vars: Partial<{ type: any; detail: any; url: any; currency: any; deduplication_id: any; tenant: any; market: any; session_id: any; product_id: any; entity_identifiers: any; entity_price: any; document_referrer: any; document_width: any; attribution_id: any; recommendation_id: any; click_location: any; ab_test_group: any; variant_ids: any; transaction_id: any; error_type: any; recommendation_type: any; search_result_id: any; product_listing_result_id: any; }> & { [key: string]: any; }) => boolean | Promise | undefined; export const depict_add_to_cart: (vars: Partial<{ type: any; detail: any; url: any; currency: any; deduplication_id: any; tenant: any; market: any; session_id: any; product_id: any; entity_identifiers: any; entity_price: any; document_referrer: any; document_width: any; attribution_id: any; recommendation_id: any; click_location: any; ab_test_group: any; variant_ids: any; transaction_id: any; error_type: any; recommendation_type: any; search_result_id: any; product_listing_result_id: any; }> & { [key: string]: any; }) => boolean | Promise | undefined; export function get_cookie(cookie_name: string): string | undefined; /** * Product properties that are used to render the product cards. Used until early 2023 */ export interface LegacyDisplay { /** * The URL of the product page. */ page_url: any; /** * The URL of the product image. */ image_url: string; /** The price of the product. */ sale_price: number; /** The original price of the product. */ original_price: number; /** The product ID of the product. */ product_id: string; /** The Google Analytics product ID */ ga_product_id?: string; /** The Google Analytics product IDs */ ga_product_ids?: string[]; /** The variation IDs */ variant_ids?: string[]; /** The title */ title: string; /** Unique recommendation result ID used by Depict */ recommendation_id?: string; /** Unique search result ID used by Depict */ search_result_id?: string; /** Unique product listing result ID used by Depict */ product_listing_result_id?: string; [key: string]: any; } interface ModernDisplay { /** * The index of the variant to be displayed. */ variant_index: number; /** * All variant displays (eg. different colors, sizes) of the product. */ variant_displays: any[]; /** Unique recommendation result ID used by Depict */ recommendation_id?: string; /** Unique search result ID used by Depict */ search_result_id?: string; /** Unique product listing result ID used by Depict */ product_listing_result_id?: string; /** Recommendation type logic used by Depict */ logic?: string; } interface BasicDisplay { product_id: string; /** Unique recommendation result ID used by Depict */ recommendation_id?: string; /** Unique search result ID used by Depict */ search_result_id?: string; /** Unique product listing result ID used by Depict */ product_listing_result_id?: string; /** Recommendation type logic used by Depict */ logic?: string; [key: string]: any; } export type Display = LegacyDisplay | ModernDisplay | BasicDisplay; export type Node_Iterable = HTMLCollection | NodeListOf | Node_Array; export type Node_Array = (Element | Text | Comment)[]; export type RecRendererResult = Record | { elements: Node_Array; displays: T[]; }; /** * Queues a task in the event queue without a timeout like setTimeout does, see https://www.youtube.com/watch?v=cCOL7MC4Pl0 * @param callback callback function that gets queued as a task */ export function queueMacroTask(callback: VoidFunction): void; interface SDKRenderingInfo { set_on_index_change: (fn: (index: number) => void) => void; } /** * Creates a handler for sending the "recommendations_inserted" event on new results. * Usage: call make_plp_recommendations_inserted_handler with options and then call the returned functions in your productCardTemplate */ export function make_plp_recommendations_inserted_handler(tenant: string, market: string, type: "search" | "category"): (display: T | null, info?: SDKRenderingInfo) => void; /** * @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 */ export function cache_args(fn: any, ...args: any[]): (...unimportant_args: any[]) => any; export const check_displays: (args_0: { recs: Display[] | { displays: Display[]; } | Promise; min_recs?: number | undefined; market: string; type: string; product_id: string | string[] | Promise | Promise | ((arg0?: string) => string | string[] | Promise | Promise) | undefined; tenant: string; }) => Promise; /** * @deprecated You should no longer need to use this. Use observer.onexists to add an event listener to an element once it exists. */ export function require_event_listener(element: Node, event: string, track_id: any, func: EventListenerOrEventListenerObject): void; /** * @deprecated use async_iterable_ipns instead. This can skip values which yields unexpected results. */ export function infinite_promise_creator(): { promise: Promise; internal_resolve: ((value: any) => void) | undefined; resolve: (argument?: any) => void; }; /** * @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. */ export function placeholder(...args: Parameters): accepted_input_that_resolves_to_elements; type accepted_element_types = Node_Array[0] | Node_Array; type accepted_input_that_resolves_to_elements = accepted_element_types | Promise | (() => accepted_element_types) | (() => Promise); 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 | Promise): Promise; export class ElementObserverEvent { constructor(opts: { element_: ElemType; selector_: SelectorType; disconnector_: Disconnector; mutation_record_?: MutationRecord; event_?: ListenerNames; }); } export interface ElementObserverEvent { element: ElemType; selector: SelectorType; disconnector: Disconnector; mutation_record?: MutationRecord; event?: ListenerNames; } /** * Element.querySelectorAll is broken in Chrome 37-latest, use this instead. * Related bug: https://bugs.chromium.org/p/chromium/issues/detail?id=1286047 * @param element Quite broadly anything you'd normaly call querySelectorAll on, including "null" * @param selector The selector to search for * @return Stock return value */ export function patched_querySelectorAll(element: Element | Document | DocumentFragment | null, selector: string): NodeListOf | T[] | undefined; export interface ElementObserver { /** * Immediately calls the callback with an ElementObserverEvent for nodes existing in the DOM that match the provided selector OR are the selector, * also calls the callback with an ElementObserverEvent whenever ANYTHING in the DOM occurs that makes an element match the provided selector. * @param selector Selector string or element to listen for * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry. */ onexists: EO_listener_also_taking_els; /** * Dispatches an ElementObserverEvent whenever a node is added to the DOM that matches the specified selector OR is the selector. * @param selector CSS selector or element to observe * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry. **/ oncreation: EO_listener_also_taking_els; /** * Dispatches an ElementObserverEvent whenever a node is removed from the DOM that matches the specified selector OR is the selector. * @param selector CSS selector or element to observe * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry. */ onremoved: EO_listener_also_taking_els; /** * Dispatches an ElementObserverEvent whenever a node that matches the specified selector or its children change in the DOM. * @param selector CSS selector or element to observe * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry. */ onchange: EO_listener; /** * Immediately calls the callback with an ElementObserverEvent on nodes that match the provided selector OR are the selector. * @param selector Selector string or element to look for in the DOM * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry. */ ifexists: EO_listener_also_taking_els; /** * 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. */ add_territory: (what: HTMLElement | Document | DocumentFragment) => void; /** * Removes a territory again. Useful for no longer observing shadow roots. */ remove_territory: (what: HTMLElement | Document | DocumentFragment) => void; /** * See docs for observer.onexists. Will return a Promise that resolves to the element out of the first call of an observer.onexists callback. * @param selector Selector string or element to wait for * @param timeout timeout to stop listening and resolve the Promise with `undefined` */ wait_for_element: (selector: string | ElemType, timeout?: number) => Promise; /** * See docs for observer.on. 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 * @param listener one of the possible functions on ElementObserver that start with "on", without the "on". So "creation", "change", "exists" or "removed" * @param selector String containing CSS selector * @param timeout timeout to stop listening and resolve the Promise with `undefined` */ wait_for_listener: (listener: SelectorType extends CallbackableNode ? "creation" | "removed" : "exists" | "creation" | "removed" | "change", selector: SelectorType, timeout?: number) => Promise; } export class ElementObserver { #private; constructor({ territory }?: { territory?: HTMLElement | Document | DocumentFragment | (HTMLElement | Document | DocumentFragment)[]; }); } type EO_listener = (selector: string, callback: ObserverCallbackFunction) => Disconnector; type EO_listener_also_taking_els = (selector: SelectorType, callback: ObserverCallbackFunction) => Disconnector; type ListenerNames = "exists" | "creation" | "removed" | "change"; type ObserverCallbackFunction = (event: ElementObserverEvent) => any; export type Disconnector = () => unknown; type CallbackableNode = Element | Text | Comment; /** * 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. */ export const observer: ElementObserver; /** * 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 * @param numSteps How many steps (notifications) there should be between 0 and 100% intersection * @return Stuff to give to IntersectionObserver */ export function buildThresholdList(numSteps: number): number[]; export function ensure_parameter_in_url(url: any, param: any, value: any): string; export function querySelectorUpwards(element: Element | HTMLElement, selector: string): Element | null; export function html2elems(html: string): NodeListOf; export function html2elem(html: string): Element | null; /** On demo domain: make all urls relative */ export function relativify(url: string | RegExp, also_onchange?: boolean, override_dev_url?: string, stfu?: boolean, also_in_all_shadow_roots?: boolean): void; export function querySelectorAllElements(elements: Node_Iterable, selector: string): T[]; export function standard_price_format(price: number, places_after_comma?: number | "auto", decimal_delimiter?: string, thousands_delimiter?: string): string; export function intl_number_format_with_fallback(bcp47_country_code: string, number: number, numberformat_options?: Parameters[1]): string; export function ensure_object_path(obj: object, step1: string, ...path: string[]): any; declare global { interface HTMLImageElementWithLoaded extends HTMLImageElement { loaded?: boolean; } interface HTMLSourceElementWithLoaded extends HTMLSourceElement { loaded?: boolean; } } export interface Lazyfier { t: {}; container: HTMLElement; selector: string; lazyfinder: lazyfinder; only_load_intersecting: boolean; ignore_data_urls?: boolean; } interface Lazyfier_Options { container?: HTMLElement; lazyfinder?: lazyfinder; selector?: string; wait_for_dominsertion?: boolean | Promise; only_load_intersecting?: boolean; verbose?: boolean; ignore_data_urls?: boolean; } export class Lazyfier { #private; intersection_observer: IntersectionObserver; start_observing_for_new_children_(override_container?: HTMLElement): void; constructor({ container, lazyfinder, selector, wait_for_dominsertion, only_load_intersecting, ignore_data_urls, verbose }: Lazyfier_Options); } interface lazyfinder { elements?: HTMLImageElementWithLoaded[]; unload?: (element: HTMLImageElementWithLoaded) => void | Promise; load?: (element: HTMLImageElementWithLoaded) => void | Promise; } export function test_array_proxy_support(): boolean; export interface Slider_Options { /** * Controls within what distance to hide the left slider button. * The distance is in pixels to the leftmost part of the slider container from the first element in the slider * * Defaults to `10` */ dist_to_hide_left?: number; /** * Controls within what distance to hide the right slider button. * The distance is in pixels to the rightmost part of the slider container from the last element in the slider * * Defaults to `10` */ dist_to_hide_right?: number; stepstoslide?: number; center_target?: boolean; constructor_plugins?: ((arg0: Slider_Options) => any)[]; mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record) => any)[]; correct_bs_targets?: boolean; button_contents?: { right: Node_Iterable; left: Node_Iterable; }; button_elems?: { right: HTMLElement; left: HTMLElement; }; autoinvalidate_cache?: boolean; } export class Amazing_Slider { #private; container: HTMLDivElement; elements_: { sliding_el_: HTMLDivElement; left_: HTMLElement; right_: HTMLElement; }; insert_here: HTMLDivElement; intersecting_items_object: { [key: string]: IntersectionObserverEntry; [key: number]: IntersectionObserverEntry; }; stepstoslide: number; dist_to_hide_left: number; dist_to_hide_right: number; center_target: boolean; correct_bs_targets: boolean; snap_style?: HTMLStyleElement; on_elements_changed: ((records: MutationRecord[]) => any)[]; observer: IntersectionObserver; observe: any; get_index_of_element(target: Element | HTMLElement): number | undefined; first_intersecting_index(min_ratio?: number): number; get first_intersecting(): IntersectionObserverEntry; get index_of_last_element(): number; get currently_selected(): number | undefined; get visible_sizes(): Map; get cards_fitting_in_viewport(): number; element_by_index(index: number): Element; invalidate_cache(): void; scroll_to_rel(offset: number, harsh?: boolean): void; scroll_to_abs(offset: number, harsh?: boolean): void; constructor({ dist_to_hide_left, dist_to_hide_right, stepstoslide, center_target, mutation_plugins, constructor_plugins, correct_bs_targets, button_contents, button_elems, autoinvalidate_cache }: Slider_Options); } /** * Make parts of a type optional * * From: https://github.com/Microsoft/TypeScript/issues/25760#issuecomment-614417742 */ type Optional = Omit & Partial; export interface Amazing_Lazy_Slider { lazyfier: Lazyfier; } export class Amazing_Lazy_Slider extends Amazing_Slider { constructor(options: Slider_Options, lazyfier_options?: Optional[0], "container">); } interface special_lazyfier_options extends Omit {} interface Deprecated_Slider_Options { dlog?: Function; catchify?: Function; dist_to_hide_left?: number; dist_to_hide_right?: number; stepstoslide?: number; arrow_image?: string; center_target?: boolean; constructor_plugins?: ((arg0: Deprecated_Slider_Options) => any)[]; mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record) => any)[]; correct_bs_targets?: boolean; } /** * @deprecated Please use Pro_Slider instead */ declare class Deprecated_Amazing_Slider extends Amazing_Lazy_Slider { constructor(static_options: Deprecated_Slider_Options, override_lazyfier_options?: special_lazyfier_options); } export function insert_styling_into_slider(slider: Deprecated_Amazing_Slider): void; /** * A function that attempts to "serialize" an object to a text representation that helps with debugging when using sentry * @param anything Something to try to serialize - this function is crappy and your mileage may vary * @param depth How deep to go when recursing * @return An object that is somehow closer to text (better serializable by sentry) or text */ export function serialize_object(anything: Object, depth?: number): Object; /** * @deprecated please use `fetch_retry()` instead * * 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 * (Note: this thing really should be rewritten with exponential backoff and a better API) * @param dlog logging function to use * @param error_log an array to which errors will be pushed * @return a windows proof fetch function */ export const wpff: (dlog: any, error_log?: any[]) => (url: RequestInfo, body: BodyInit, headers?: HeadersInit, decode_json?: boolean, fetch_options?: RequestInit, attempt?: number) => any; export const use_element: (callback: (element: E) => void, element: E) => E; export function use_listener(event: K, handler: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, element: E): E; export const classlist: (classes: (string | undefined)[]) => string; type Props = { children?: Elem[] | Elem; onClick?: (e: MouseEvent) => void; [key: string]: any; }; type Elem = Node | string; type Component = (props: Props, _unknown?: unknown) => HTMLElement; export const jsx: (tag: string | Component, { children, ...props }: Props, _unknown?: unknown) => JSX.Element; export const jsxs: (tag: string | Component, { children, ...props }: Props, _unknown?: unknown) => JSX.Element; export const Fragment: ({ children }: { children: Elem[] | Elem; }, _unknown?: unknown) => DocumentFragment; export const chevronRight: JSX.Element; export const chevronLeft: JSX.Element; export const expandingContainer: ({ duration }?: { duration?: number; }) => { expand: () => void; content: HTMLDivElement; container: HTMLDivElement; }; export const should_colorizeLogics: boolean; export function colorize_elements(elements: NodeListOf | Node_Array, display: Display): NodeListOf | Node_Array; /** * 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. * @param iterables Array of IPNS * @return IPNS that resolves with an array of the values of all provided IPNS when one of them resolves */ export function zip_async_iterables(iterables: IPNS[]): IPNS; /** Overrides that can specify a different amount of columns for certain rows * @param key The row (starts at 1) that you're "selecting" to override * @param value The amount of columns that your selected row should have */ type Override = { overrides: Record< /* Row: */number, /* Column: */number>; }; export type ColAtSize = /** [ , , , ] */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]; export type ColsAtSize = readonly ColAtSize[]; export type LayoutOptions = { container_element: Element; cols_at_size: ColsAtSize; grid_spacing: string; rows: { start_rows?: number; rows_per_click?: number; ipns?: IPNS; max_rows?: number; button?: HTMLElement; } | "all"; layout: "slider" | "grid"; disable_partial_rows?: boolean; override_vertical_spacing?: string; }; export const layout_media_query_header: (min: string, max?: string) => string; /** * Grid: Calculates CSS for a grid with a certain spacing and certain number of columns at certain screen sizes, including a view more button. * @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 * @param container_element container element of the elements that you want to style and hide * @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` * @param grid_spacing spacing to use if none is specified for the specific size in `cols_at_size` * @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". * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing */ export function Layout({ rows, container_element, cols_at_size, grid_spacing, layout, disable_partial_rows, override_vertical_spacing }: LayoutOptions): Promise; /** Getting how many recs should be displayed for a certain row (while taking override rules into account) * This returns number of recs for this row and all the previous ones * @param row The "index" of the row (counting from the top). Starts at 1. * @param options Your cols_at_size layout option */ export function layout_get_total_rec_amount_for_row(row: number, options: LayoutOptions["cols_at_size"][number]): number; /** * Same as `get_total_rec_amount_for_row` but caps the result to never exceed @param max_recs */ export function layout_get_visible_recs_without_partial_rows(rows: number, max_recs: number, options: LayoutOptions["cols_at_size"][number]): number; /** * basically equivalent of n_col_styling css mixin - generates distances for a flex grid with margins * @param selector_beginning Main selector targeting container classname to use in generated css * @param default_grid_spacing_text Spacing to use if not specified in cols_at_size for a specific size * @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 * @param layout "slider" or "grid" * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing * @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" * @return String of generated CSS */ 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; export function slider_autoscroll_factory(interval?: number): { constructor_plugin(this: Amazing_Slider): void; mutation_plugin: (this: Amazing_Slider, _intersections: IntersectionObserverEntry[], intersecting_mutations: Record) => void; }; export function make_button1(): { left: [HTMLImageElement]; right: [HTMLImageElement]; }; /** * Returns an object to put into `button_contents` for `Pro_Slider` containing the icon arrow images * @return An object with left and right being an array containing one image */ export function make_button2(): { left: HTMLImageElement[]; right: HTMLImageElement[]; }; export function slider_dots_factory({ navcont_insertion_fn, navdot, dontshowonedot, bitesize }: { navcont_insertion_fn?: (slider: Amazing_Slider, navcont: HTMLDivElement) => any; navdot: (unique_name: number, index: number) => Element; dontshowonedot?: boolean; bitesize?: number; }): { constructor_plugin: () => void; mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record) => void; }; export function navdot(unique_name: string | number): HTMLLabelElement; export function slider_draggable_factory(): { constructor_plugin: (slider_options: any) => void; mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record) => void; post_pro_plugin: { instant: (items: HTMLCollection) => void; }; }; export function slider_fading_factory({ fade_in_duration_, fade_out_duration_, visible_opacity_, faded_opacity_, easing_, threshold_ }?: { fade_in_duration_?: number; fade_out_duration_?: number; visible_opacity_?: number; faded_opacity_?: number; easing_?: string; threshold_?: number; }): { readonly mutation_plugin_: (this: Amazing_Slider, entries: IntersectionObserverEntry[], _intersecting_mutations: Record) => void; readonly constructor_plugin: (this: Amazing_Slider, _slider_options: Slider_Options) => void; }; export function slider_fractional_factory(_t?: any, fraction?: number, max_steps?: number, dont_enable_correct_bs_targets?: boolean, min_steps?: number): { constructor_plugin: (slider_options: Slider_Options) => void; mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record) => void; }; /** * * Plugin for rendering a scrollbar below the slider that follow the slider position. * * Scroll container class: `depict_slider_scroll` * * Scroll bar class: `depict_slider_scroll_bar` * @param options Options for the scrollbar. Add position styling and additional classes. */ export function slider_show_scroll(options: { add_position_styling: boolean; scroll_bar_classes?: string[]; scroll_container_classes?: string[]; }): { constructor_plugin: (_slider_options: Slider_Options) => void; mutation_plugin: (_intersections: IntersectionObserverEntry[], _intersecting_mutations: Record) => void; }; export function slider_snap_css(_t?: any, { snapEvery, align }?: { snapEvery?: number; align?: "center" | "start" | "end"; }): { constructor_plugin: (_slider_options: Slider_Options) => void; mutation_plugin: (_intersections: IntersectionObserverEntry[], intersecting_mutations: Record) => void; }; export function can_use_snapping_and_still_scroll(): Promise; export function slider_snapping_factory(options?: { stepsize?: number; threshold?: number; }): { constructor_plugin: (slider_options: any) => void | undefined; mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record) => void | undefined; }; type after_navig_fn = (arg0: Parameters, what_happened: "replaceState" | "pushState") => any; /** * AsyncIterable which resolves with the new href every time location.href changes */ export const stateless_href_change_ipns: IPNS; /** * AsyncIterable which resolves when you await it with the current href and then once every time it changes */ export const href_change_ipns: IPNS; /** * Functions to instantly (synchronously) call when a "popstate" event occurs, before the href_change_ipns' resolve * 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. */ export const instant_exec_on_suspect_history_change: Set<(what_happened?: "replaceState" | "pushState" | "popstate", args?: PopStateEvent | Parameters | Parameters) => void>; export function on_next_navigation(callback: (new_href: string) => void): Promise; /** * 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. * Please also consider adding a listener to the `popstate` event (`window.addEventListener("popstate", handler)`) to cover ALL navigation possibilities. * @param after_navigation Function to call after history.replaceState and history.pushState * @param replace_replaceState=true Whether to call the function also on history.replaceState. * @return Void */ export function history_replacer(after_navigation: after_navig_fn, replace_replaceState?: boolean): Promise; export type ReactiveTemplateValueContents = string | number | Node_Array[number] | undefined | (string | number | Node_Array[number])[]; export function reactive_template(initial_value?: ReactiveTemplateValueContents): readonly [Node_Array, () => ReactiveTemplateValueContents, (arg0: ReactiveTemplateValueContents) => void]; export const insert_styling: (css: string) => Promise; /** * Basically a RecRendererResult with less strict typing */ export interface Surface { elements?: Node_Array; displays?: T[]; should_stay_inserted?: Promise; } /** * Functions existing on ChildNode that are commonly used to insert recommendations into the DOM */ export type InsertionVerb = "after" | "before" | "replaceWith" | "append" | "prepend" | "replaceChildren"; /** * Tries to extract a product id from an url. * The method used to retrive product id used here is very narrow, probably better to use something else instead? * * @example normal_get_product_id("www.foo.com/bar/baz.html") // "baz" * * @param url The url to check, defaults to `window.location` * @returns */ export const normal_get_product_id: (url?: string) => string; declare global { interface Document { depictwashere: boolean; } } /** * If you need custom market logic that {@link depict_init_with_market_logic} doesn't support then use this function. * * Used to initialize an integration-script, this should always be the entrypoint of an integration. * * Makes sure that your script doesn't run twice */ export const depict_init: (callback: () => Promise) => void; /** * Initialize an integration-script like {@link depict_init}, but with automatic handling of unsupported and unknown markets. * * @param options.extract_market A function that extracts the current market, and if the market is supported, unsupported or unknown * @param options.callback If `extract_market` returned a supported market, calls `depict_init` with this callback. * @param options.supported_markets Markets where our script should run, in order to get the best typechecking you should add a `as const` * modifier to this type like so `["foo", "bar"] as const`. * @param options.unsupported_markets Markets we are aware of and where our script shouldn't run. * @param options.preferred_demo_market Market to use on .demo.depict.ai, if an override is needed for all users. * depict-override-market query parameter will override this behaviour. * * ### Behaviour * * - market is unsupported - log to console and exit * - market is unknown - report to sentry and exit * * ### Override market * * When running in debug mode the market can be overridden by setting a `depict-override-market` query param. * For example http://tenant.domain?depict-override-market=ez */ export function depict_init_with_market_logic(callback: (market: T[number]) => Promise, get_market: () => Promise | string | undefined, supported_markets: T, unsupported_markets: string[], preferred_demo_market?: string): void; /** * A wrapper around window.matchMedia, basically cross browser compatibly adds an event listener to a media query that triggers when it changes * @param query The media query (without `@media`) * @param catchified_handler The function to execute * @param initial_call If the handler should be called instantly with the current state of the media query * @return An object containing `remove`, a function which removes the event listener again */ export function javascript_media_query( // inspired by code in houdinisportswear modify script query: string, handler: (e: MediaQueryListEvent | MediaQueryList | { matches: false; }) => void, initial_call?: boolean): { remove(): void; }; type RenderingFunction = (...args: any[]) => Promise<{ surface_: Surface | void; cache_until_?: Promise; }>; /** * 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. * @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. * @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_. * @return a `Surface` object which, utilising a `reactive_template` always represents the currently chosen surface */ export function surface_mixer({ surface_rendering_functions_, current_surface_ }: { surface_rendering_functions_: RenderingFunction[]; current_surface_: IPNS; }): Promise>; /** * To be used in conjunction with surface_mixer. Makes it possible to switch Surface depending on screen size * @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. * @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). * @return An IPNS resolving with the number of the surface that should currently be shown */ export function sizes_to_surface(surface_per_size: [surface_index: number, min: string | null, max?: string][], cleanup_promise?: Promise): IPNS; /** * Returns a promise that resolve the next time the href is changed */ export function promise_until_next_navigation(): Promise; /** * 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 * @param {HTMLElement} a_element - The element to listen on the "click event" * @param {string} product_id - A unique identifier for the product which can be used to rerecognize it on the product page * @param {string} recommendation_id - The recommendation ID of the recommendation * @param {Function} additional_listener - An additional function to execute onclick */ export function bind_tracking_to_link(a_element: Element, product_id: string, recommendation_id: string, additional_listener?: Function): ((e: Event) => void) | undefined; export type A2CTrackingFunction = (product_id: string, recommendation_id: string, was_unmatching: boolean, event: Event) => any; /** * 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 * @param {HTMLElement} button - The element to listen on the "click event" * @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 * @param {A2CTrackingFunction} tracking_fn - A function which gets executed on click of button * @param {Boolean} [unmatching_tracking] - also call tracking_fn on products not found in localStorage. */ export function bind_to_a2c_button(button: Element, get_product_id: (url?: string, e?: Event) => string | Promise, tracking_fn: A2CTrackingFunction, unmatching_tracking?: boolean, event?: string): Promise; export function make_tracker_send_to_depict(ga_tracker: any, append_to_url?: string): void; export function create_ga_queue(): void; /** * A Post processor for Recommendation renderer to add impression tracking to all displays */ export const impression_tracking_post_processor: (items: any, display: any, info: any) => any; interface ImpressionTrackingOptions { /** The element to observe for impressions. */ element: HTMLElement; /** The impression data to send to the api (this is combined with context data) */ data: ExplicitImpressionEventData; /** When true the element will be observed by the IntersectionObserver only after it's inserted into the DOM. * Sometimes with a pollyfilled IntersectionObserver it ignores elements that are not in the DOM yet. * Defaults to true. * */ wait_for_dom_insertion?: boolean; } /** * Registers the passed element for impression tracking. * The element will be observed for intersection with the viewport. * Also handles sending the impression event. * * @return A function to stop observing the element for impressions */ export const impression_track_element: ({ element, data, wait_for_dom_insertion }: ImpressionTrackingOptions) => () => void; /** The start and end visibility threshold for an intersection to count as an impression */ export let impression_threshold: number[]; export const set_impression_threshold: (start: number, end: number) => number[]; /** The minimum duration the element has to be visible above the thresholds before it counts as an impression */ export const has_to_be_intersecting_for = 500; /** What explicit information is needed to form an ImpressionEvent */ export type ExplicitImpressionEventData = { recommendation_type?: string; entity_price?: number; market?: string; tenant?: string; product_id?: string; } & ({ recommendation_id: string; } | { search_result_id: string; } | { product_listing_result_id: string; } | { suggestions_result_id: string; }); /** What an impression event looks like when sent to the api */ export type ImpressionEvent = { /** The type for impression events should be element_visible */ type: "element_visible"; } & (ExplicitImpressionEventData | TrackingEventContextData); /** * Sends an impression event to the api. */ export const send_impression_event: (data: Optional) => void; export function Promise_Any(promises: (T | PromiseLike)[] | Iterable>): Promise; /** * Broadcasts the product id of the current page to a BroadcastChannel `right_click_attribution`. * 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. */ export function broadcast_product_id(product_id: string): Promise; /** * 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) * @param elements Elements that event listeners will be added on * @param display The display to take the product_id from * @param info InfoForProcessing to get Tenant instance out of * @return `elements` 1:1 */ export function add_new_tab_listener(elements: NodeListOf | Node_Array, display: Display, info?: any, get_event_listener_remover?: (remover: VoidFunction) => void): NodeListOf | Node_Array; /** * This is the event handler for the new tab tracking function (add_new_tab_listener) * @param e Click event * @param product_id product_id of clicked product * @return A promise resolving to void after 60s or when the product id was broadcasted */ export function contextmenu_callback(e: Event, product_id: string): Promise; interface TrackingData { /** The active market, if any */ market?: string; /** The merchant id */ tenant: string; } export interface PageViewEventData extends TrackingData { /** If the page is a pdp, include the product_id */ product_id?: string; } export interface PageViewTrackingData extends TrackingData { /** A function that returns the product_id of the product being displayed on href, * if the href points to a PDP */ get_product_id: (href: string) => string | undefined | Promise; } /** * Sends a page_view event to Depict tracking if it hasn't been sent yet for the current page url * 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 * @return A promise resolving to void */ export function send_page_view_if_needed(data: PageViewEventData): Promise; /** * Sends a page_view event to Depict tracking, and another one any time the page URL changes */ export function send_page_view_on_navigation(data: PageViewTrackingData): Promise; export interface ListenableSetEvent extends CustomEvent { detail: T; } /** * Set but you can listen for values being added or removed * i.e. my_set.addEventListener("add", ({detail}) => console.log(detail, "was added to", my_set)); */ export class ListenableSet extends Set { #private; addEventListener(event: "add" | "delete", callback: (ev: ListenableSetEvent) => unknown, options?: Parameters<(typeof EventTarget.prototype)["addEventListener"]>[2]): void; removeEventListener(event: "add" | "delete", callback: (ev: Event) => unknown): void; add(property: T): this; delete(property: T): any; } /** * 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. * @param element Element to start out at * @param selector Selector to search for * @param start_right=true In what direction to start: true = right, false = left * @return The found element or undefined */ export function chaotic_closest(element: Element, selector: string, start_right?: boolean): Element | undefined; type CompareMethod = (i1: T, i2: T) => boolean; export const deduplicate: (arr1: T[], arr2: T[], compareFunc: CompareMethod) => T[]; export const dedup_products: (arr1: T[], arr2: T[] | undefined) => T[]; /** * Attempt to navigate using nextjs's spa router. * Falls back to default browser navigation. * Docs: https://nextjs.org/docs/api-reference/next/router */ export function navigate_with_next_router(e: MouseEvent, url: string): false | undefined; /** * proxies window.fetch: * 1. Instead of window.fetch fetch_apply is called, target being the original fetch function * 2. fetch_proxy_handler is called and may read the request and return a (fake) response * 3. if fetch_proxy_handler fails the original target is called with the same this and arguments * We are meticulously preserving this, target and its arguments in case that someone replaces fetch with a function that does something else * 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 * Remember to return response, else it will make another request * @param fetch_proxy_handler Called instead of the original fetch function everytime someone does fetch. Has to return a response. * @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 * @return Nothing */ export function fetch_replacer(fetch_proxy_handler: (target: typeof window.fetch, this_arg: typeof window, arguments_list: Parameters) => Promise, unsafe_throw_up?: boolean): Promise; declare const FakeResponse_base: { new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response; prototype: Response; error(): Response; redirect(url: string | URL, status?: number | undefined): Response; }; /** * 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. * Useful when wanting to change the result of a `fetch request` * Please see repo for usage examples * @param response_string String to base Response object on * @param url URL to claim that the Response is from * @param headers Response headers * @param override_options More options to pass to the `Response` constructor */ export class FakeResponse extends FakeResponse_base { constructor(response_string: string, url: string, headers?: HeadersInit, override_options?: ResponseInit); } export type ShopifyItem = { id: number; handle: string; quantity: number; url: string; }; export type ShopifyError = { status: number; message: string; description: string; }; /** * Represents a Shopify cart "event", i.e. Whenever a Shopify API request is sucessfull. * - `type` represent the type of event * - `response` resolves to a shopify response */ export type ShopifyEvent = { type: "get_items"; response: Promise; body?: object; } | { type: "add_items"; response: Promise; body?: object; } | { type: "update_items"; response: Promise; body?: object; } | { type: "change_items"; response: Promise; body?: object; } | { type: "clear_items"; response: Promise<[] | ShopifyError>; body?: object; }; /** * Whenever any request to the shopify cart endpoint (this includes requests made by merchant code) is made {@link on_response} is called. * * ### Caveats * - This currently doesn't intercept XHR requests, only `fetch`. Interpecpting XHR should be implemented at some point! * * - Under the hood, this function works by proxying `window.fetch`. This isn't guaranted to work, and could even break merchant code. * Call this function early on in the execution for the best possibillity of success. * * - If the merchant performs a `window.fetch` to Shopify before `intercept` then that response wont be intercepted. * If you know that the merchant will make a request to Shopify early on then it might make sense to do something like: * ``` * const handle = setTimeout(catchify(() => get_items_in_cart()), 2000) * intercept(evt => { * canel_timeout(handle) * ... * }) * ``` * In order to get the cart contents at some point even if you miss the merchants innitialt Shopify request. * * - `intercept` intercepts all requests to Shopify, including requests made by you. * @param lenient: If true, also new style endpoints not ending on .js will be intercepted. */ export function intercept(on_request: (event: ShopifyEvent) => any, lenient?: boolean): void; export type AddToCartOptions = { quantity?: number; }; /** * Add an item to the Shopify cart. * * ### Caveats * Keep in mind that adding to the shopify cart wont neccesarily update the merchants UI, * it only means that when the merchant fetches the cart again then they'll get the item added by you. * Usually the merchant has it's own global add-to-cart function that can be used. While doing that can * take more developer time it means that you usually get the merchant UI to update correctly. * * @param shopify_id * @param options.quantity How many of an item to add, defaults to `1`. * @throws If the response JSON is in an unexpected format. */ export function add_item(shopify_id: string, options?: AddToCartOptions): Promise; /** * Fetch the items in the shoppify cart. * * This is probably not the right function for mose use-cases. * Want to get notified when merchant code adds new items to the cart through Shopify? * Use {@link intercept} to intercept all calls to Shopify (even ones made by merchant code). * * @returns All items currently in the cart. * @throws If the response JSON is in an unexpected format. */ export function get_items_in_cart(): Promise; declare global { interface Window { ShopifyAnalytics: { meta?: { product?: ShopifyMetaProduct; }; }; } } interface ShopifyMetaProduct { id?: string; vendor?: string; variants?: { id?: string; sku?: string; }[]; } /** Shopify sites often has an interesting meta object defined on window.ShopifyAnalytics.meta * The SKU that backend requires might only be found in the meta object. * This function gives you that object in a safe way that won't break Shopify. */ export const get_shopify_analytics_meta_product: () => Promise; export const wait: (delay: number) => Promise; /** * Fetch with retry and exponential back off. This is the 2.0 version of the previous Windows proof fetch. * * 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 * @param url Url to perform fetch towards * @param options Fetch options * @param max_retries Max number of retries, defaults to 10 * @param useFetch_ The fetch function to use, defaults to the global fetch * @param initialRetryDuration_ The start duration for the first retry, defaults to 100ms * @returns The fetch response */ export function fetch_retry(url: RequestInfo | URL, options?: RequestInit, max_retries?: number, { useFetch_, initialRetryDuration_ }?: { useFetch_?: typeof fetch; initialRetryDuration_?: number; }): Promise; /** * Ensures that the attribute value of an element is what an AsyncIterable resolves with * @param el Element to set attribute on * @param attribute_name Name of the attribute to set * @param async_iterable AsyncIterable to loop over * @param quit_after_navigation=true Whether to stop awaiting the AsyncIterable if the page navigates * @return [description] */ export function iterable_to_attribute(el: Element, attribute_name: string, async_iterable: AsyncIterable, quit_after_navigation?: boolean): Element; /** * Merges an IPNS with `reactive_template` - if the IPNS updates the reactive template's state is updated to what the IPNS returns * @param async_iterable The async iterable to use * @param quit_after_navigation Whether to stop listening for the IPNS when navigating away * @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. */ export function iterable_to_elems(async_iterable: AsyncIterable, quit_after_navigation?: boolean): Node_Array; /** * 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 * @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"; * @return A wrapped function that now executes in a context */ export const prevent_infinite_loop: (cb: (...args: A) => void | B) => (...args: A) => void | B; /** * Inserts one or multiple surfaces into the DOM. * 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 * @param surfaces Array with surfaces to insert * @param verb Verb on how to insert * @param target Selector for `observer.onexists` to find element to insert VERBto, alternatively an element * @param remove_after_navigation Whether to remove the elements from the DOM again if a navigation away occurs, defaults to true * @param try_forever Whether to try to insert the same surface even after the page has navigated away, defaults to false * @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 * @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 */ export function insert_surfaces({ surfaces: input_surfaces, verb, target, remove_after_navigation, try_forever, preserve_elements }: { verb: InsertionVerb; target: string | HTMLElement; remove_after_navigation?: boolean; try_forever?: boolean; surfaces: (Promise | void> | Surface | void)[]; preserve_elements?: boolean; }): Promise<{ surface: Surface; succeeded: boolean; }>[]; export const revertable_remove: (target: string | Element | Node_Array, should_stay_inserted: Promise) => Promise; /** * 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 * @return a WeakSet to add nodes to which you remove and want to ignore removal errors for */ export function removeChild_error_swallowing_factory(): WeakSet; /** * 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) * @return void */ export function replace_promise_with_native_if_exists_and_enforce(): void; /** * Creates a blank iframe inside and returns window.Promise out of it * @return a pristine, unpolyfilled window.Promise */ export function get_iframe_promise(): PromiseConstructor; /** * Proxies XMLHttpRequest.prototype.open to an open function which also calls the provided `fetch_handler` with useful information as parameter * @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 * @return void */ export function xhr_replace(fetch_handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, arg_array: Parameters) => void): void; /** * 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 * @param handler The function called on load of every XHR request. * @return void */ export function xhr_load(handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, event: ProgressEvent) => any): void; export function xhr_send_interceptor(send_callback: (request: XMLHttpRequest, open_args: Parameters, send_args: Parameters) => any): Promise; /** * Intercepts someone reading `response`, `responseText` and `responseXML` on an XMLHttpRequest * @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`. */ export function xhr_read_interceptor(read_callback: (request: XMLHttpRequest, open_args: Parameters, send_args: Parameters, orig_result: string | undefined, property_name: "responseText" | "response" | "responseXML") => string): Promise; export function default_rp_fixes(orig_url?: string | undefined): Promise; export function rp_relativify_history(orig_url_with_trailing_slash: string): void; export function rp_relativify_fetch(orig_url_with_trailing_slash: string): void; export function rp_relativify_xhr(orig_url_with_trailing_slash: string): void; /** * 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. */ export function sort_obj(maybe_obj: T): any; /** * Tries to figure out the tenant's market (`TwoLetterMarket` for new integrations) through various means. * * 1. Checks if there is a market in one of the url segments (www.tentant.se/foo/se/bar) * 2. Checks if the market is specified in the tenant's domain name (www.tenant-se.com) * 3. Checks the toplevel domain (www.tenant.se/foo/bar) * * @param allowed_markets An array the possible markets for the tenant. * Dont forget to specify the allowed market as const (`["se", "en"] as const`) to get the best typing * @param url Specify this to overide the url to check, defaults to the current url * @param tenant The tenant's name * @returns If a market specified in `allowed_markets`was found that is returned, `undefined` otherwise */ export function standard_get_market(allowed_markets: T, url?: string, tenant?: string): T[number] | undefined; /** * Listens to localstorage changes with `setItem` and direct assignment. * @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. */ export function listenToLocalStorage(listener: (key: string, value: string) => void): void; /** * Timeout a promise after `ms` milliseconds. * If the promise is timed out this function will return `undefined` and not throw. */ export function timeout_promise(promise: Promise, ms: number): Promise | undefined>; /** * Uses the default Voyado ID that is used in Voyado email recommendations. */ export const use_voyado_id: () => void | undefined; type ButtonProps = Omit, "type"> & { class?: string; }; export function DefaultViewMoreButton({ children, ...attributes }: ButtonProps): HTMLButtonElement; export function GeneralSideSlidein({ title_, children, CloseIcon }: { title_: IPNS; children: HTMLElement | HTMLElement[]; CloseIcon: () => HTMLElement | SVGElement; }): Promise<{ close_: VoidFunction; on_close_: (fn: VoidFunction) => number; }>; export function GeneralSizeSelector({ title_, items_, out_of_stock_text_, CloseIcon }: { title_: IPNS; out_of_stock_text_: IPNS; items_: { id_: string; size_name_: string; is_available_: boolean; }[]; CloseIcon: () => HTMLElement | SVGElement; }): Promise; type PlaceholderProps = Omit, "style"> & { /** Any extra classes togheter with the default `depict-placeholder` class */ class?: string; /** Convinence prop for setting element width */ width?: string; /** Convinence prop for setting element height */ height?: string; /** Will override the usage of width & height */ style?: string; }; type PlaceholderImageProps = Omit & { aspect_ratio: number; }; /** * A Placeholder with shimmering animation. * For text you can use `height="1em"`. * For specific number of characters use `ch`, ex: `width="7ch"` */ export const Placeholder: ({ width, height, class: extra_classes, style, ...attributes }: PlaceholderProps) => HTMLDivElement; /** * A wrapper of Placeholder with full width and maintained aspect ratio. * @see {@link Placeholder} */ export const ContainedPlaceholderImage: ({ aspect_ratio, ...attributes }: PlaceholderImageProps) => HTMLDivElement; export const RecommendationContainer: (title?: string | HTMLElement, surface_classes?: string[]) => HTMLDivElement; export const RightChevron: () => JSX.Element; export const LeftChevron: () => JSX.Element; export type ColorObj = { /** the value passed as a css color */ value: string; /** if specified, it's used as a title on hover */ label?: string; /** Allow for arbitrary data to be passed */ [key: string]: any; }; interface ColorPickerProps { /** An array of colors that can be selected */ colors: ColorObj[]; onSelect: (color: ColorObj) => unknown; /** * Called everytime a color is hovered */ onHoverUpdate?: (color: ColorObj, hovering: boolean) => unknown; /** * The color value to be initially selected. Can be omitted for no color to be selected. * If multiple colors use the same hex value, the label can also be specified (using a ColorObj) */ initialColor?: string | ColorObj; /** * Enabled hovering preview. When true `onSelect` will be called with a new color when it's hovered, * then reverts back to the last clicked color when hovering is stopped * */ selectOnHover?: boolean; /** * If set to true only `onSelect` will be called when an item is clicked */ dontSetActiveOnClick?: boolean; /** * If only circles should be returned and not the container element */ onlyCircles?: boolean; } /** * A color selector, that calls onSelect when a color is clicked and optionally on hover as well. */ export function createColorPicker({ colors, initialColor, onSelect, selectOnHover, onHoverUpdate, dontSetActiveOnClick, onlyCircles }: ColorPickerProps): { setActiveIndex: (index: number) => void | undefined; ColorPicker(): JSX.Element; }; /** * For example how to use, check /src/glitter/main.tsx * Warning: Don't use margins for the element you want to expand, since the animation will look janky * EDIT: above no longer applies if you only have one element that you want to expand */ export const useExpandingContainer: ({ duration, delay }?: { duration?: number; delay?: number; }) => { ExpandingContainer: ({ children }: { children?: Elem | Elem[] | undefined; }) => HTMLElement; expand: (expanding_delay?: any, time_to_expand?: any) => Promise; collapse: (collapsing_delay?: any, time_to_collapse?: any) => Promise; }; export const resize_base_url: string; export const is_safari: boolean; /** * 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 * @param what_to_watch Element to watch resizing of * @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 * @param resolution_factor a factor to multiply the target-to-display resolution with * @return A function that will set the `sizes` atribute of the provided element to the size of `what_to_watch`, continuously */ export function make_sizes_setter(what_to_watch: HTMLElement, sizes_communicator?: IPNS, resolution_factor?: number): (el_to_resize: HTMLSourceElement | HTMLImageElement) => Promise; /** * This function returns a function that can be used as JSX component. * It builds upon `make_sizes_setter` and uses it to set the `sizes` attribute of and a fallback tag that it creates. * @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. * @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. * @param formats An array of formats supported by the backends "ResizeImage" to allow the browser to use * @param resolutions An array of resolutions to generate a srcset for * @param sizes_communicator IPNS of which the resolution sets the `sizes` attribute on the images * @param sizes_setter_ a sizes setter returned by make_sizes_setter, you can provide one if you created it before creating the images * @param resolution_factor a factor to multiply the target-to-display resolution with * @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+) * * @example Per surface: * `const SourcesetComponent = make_sourceset_component(first_canvas, true, ["webp", "png", "tiff"]);` * and then instead of your tags: `` */ export function make_sourceset_component({ what_to_watch, set_dataset, formats, resolutions, sizes_communicator, resolution_factor, market_, sizes_setter_ }?: { what_to_watch?: HTMLElement; set_dataset?: boolean; formats?: string[]; resolutions?: number[]; sizes_communicator?: IPNS; resolution_factor?: number; market_?: string; sizes_setter_?: ReturnType; }): (image_options: Partial & { class?: string; }) => JSX.Element; /** * Adds query parameters from the `params` parameter to the `base` url. * Guaranteed to be correctly escaped and not doubled and perfectly formatted * @param base base url, can be relative * @param params an object like `{'param1': 'value'}` that will lead to `?param1=value` on the url * @return an absolute URL with the added query parameters */ export function make_url_with_query_params(base: string, params: { [key: string]: any; }): string; export interface ImageOptions extends Partial { aspect_ratio: number; class?: string; rendering_options?: Record; srcset_opts?: Parameters[0]; alt: string; remove_on_error?: boolean; /** * If true, inserts grey placeholder svg's before the image lazyloader and the sourceset component add the real source */ init_with_placeholder?: boolean; } /** * Contained image gives an image (a container with) intrinsic size of the given aspect ratio, filling out available space. * It means that images with different aspect ratios will all take the same amount of space * and the sides where it doesn't fit the aspect ratio will be filled with transparent. * It makes sure the images doesn't get squished like setting `width` and `height` would do. * @param aspect_ratio The aspect ratio of the image, i.e. 4/3 = 1,3̅ * @param alt Alt text of the image * @param remove_on_error Whether to remove the image if loading fails * @param rendering_options The rendering options. Please always provide this, it's only optional for compatibility reasons. * You should provide the `rendering_options` to the second argument, InfoForProcessing, provided to a template or preprocessor. * When provided to a postprocessor of a recommendation-renderer it will be the third argument * If you provide this, ContainedImage will automatically use `make_sourceset_component` * and the image resizing proxy to get you responsive images in a modern format (webp). * @param srcset_opts The options passed to `make_sourceset_component`, only used if `rendering_options` is set. * @param Everything else: attributes on the tag * @returns It depends on options and build target. But it's always one HTMLElement. */ export const ContainedImage: ({ init_with_placeholder, ...options }: ImageOptions) => HTMLElement; type HoverImageOptions = ImageOptions & { mobile_touch_hover?: boolean; extra_container_class?: string; main_extra_classes?: string; second_src?: string; second_srcset?: string; second_srcset_opts?: Parameters[0]; fade_length_seconds?: number; /** The minimum amount of time for a touch to be considered a link click */ navigation_minimum_ms?: number; }; export const ContainedHoverImage: ({ second_src, second_srcset, second_srcset_opts, fade_length_seconds, mobile_touch_hover, navigation_minimum_ms, ...options }: HoverImageOptions) => HTMLDivElement; /** * Shallowly converts all keys in an object from snake_case to camelCase. * Does not support symbol keys. * * @param obj the object. It will be cloned and not modified in-place. */ export function camelCasifyObject(obj: T): KeysToCamelCase; /** * Shallowly converts all keys in an object from camelCase to snake_case. * Does not support symbol keys. * @param obj the object. It will be cloned and not modified in-place. */ export function snakeCasifyObject(obj: T): KeysToSnakeCase; type CamelCase = S extends `${infer P1}_${infer P2}${infer P3}` ? `${Lowercase}${Uppercase}${CamelCase}` : Lowercase; type KeysToCamelCase = { [K in keyof T as CamelCase]: T[K] }; type CamelToSnakeCase = S extends `${infer T}${infer U}` ? `${T extends Capitalize ? "_" : ""}${Lowercase}${CamelToSnakeCase}` : S; type KeysToSnakeCase = { [K in keyof T as CamelToSnakeCase]: T[K] }; /** * Converts RGB to HSL * Source of function: https://www.30secondsofcode.org/js/s/rgb-to-hsl */ export function rgb_to_hsl(r: number, g: number, b: number): readonly [number, number, number]; /** * Converts HSL to RGB * Source of function: https://www.30secondsofcode.org/js/s/hsl-to-rgb */ export function hsl_to_rgb(h: number, s: number, l: number): readonly [number, number, number]; /** * Converts HSV (or HSB, it's the same) to RGB. * Source of function: https://www.30secondsofcode.org/js/s/hsb-to-rgb/ */ export function hsb_to_rgb(h: number, s: number, b: number): readonly [number, number, number]; /** * Calculates the relative luminance of a RGB color * Source: https://gist.github.com/jfsiii/5641126 */ export function relative_luminance_from_rgb(R8bit: number, G8bit: number, B8bit: number): number; /** * Converts a hex string to an RGB array * Source: https://stackoverflow.com/a/39077686 */ export function hex_to_rgb(hex: string): [number, number, number] | null; /** * Synchronizes an HTML element's content with a provided Solid.js accessor's value. You can decide what "content" means. * * By default, the function utilizes the `textContent` property of the provided element to * synchronize its text content. However, this behavior can be customized by providing optional * `getContent` and `setContent` functions. * * @param {string} selector - The CSS selector of the target HTML element. * @param {Accessor} data - Solid.js accessor that holds the text data to be synchronized. * @param {Object} [opts] - Optional configuration object. * @param {Function} [opts.getContent] - A function that retrieves the current content of a given HTML element. * If not provided, defaults to retrieving the `textContent` property of the element. * @param {Function} [opts.setContent] - A function that sets the content of a given HTML element based on the provided string. * If not provided, defaults to setting the `textContent` property of the element. */ export function sync_el_content_with_accessor(selector: string, data: Accessor, opts?: { getContent: (el: Element) => string | undefined | null; setContent: (el: Element, content: string) => void; }): void; /** * Returns an accessor that reactively returns the current href of the page */ export function use_href_accessor(): Accessor;