New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@appmate/wishlist

Package Overview
Dependencies
Maintainers
1
Versions
214
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@appmate/wishlist - npm Package Compare versions

Comparing version 4.22.4 to 4.22.5

881

api.js

@@ -1,878 +0,7 @@

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from4, except, desc) => {
if (from4 && typeof from4 === "object" || typeof from4 === "function") {
for (let key of __getOwnPropNames(from4))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from4[key], enumerable: !(desc = __getOwnPropDesc(from4, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var B=Object.create;var M=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var J=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports);var $=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of H(i))!G.call(s,r)&&r!==e&&M(s,r,{get:()=>i[r],enumerable:!(t=K(i,r))||t.enumerable});return s};var Q=(s,i,e)=>(e=s!=null?B(z(s)):{},$(i||!s||!s.__esModule?M(e,"default",{value:s,enumerable:!0}):e,s));var q=J((Ce,j)=>{"use strict";var oe=function(){function s(e,t){if(typeof e!="function")throw new TypeError("DataLoader must be constructed with a function which accepts "+("Array<key> and returns Promise<Array<value>>, but got: "+e+"."));this._batchLoadFn=e,this._maxBatchSize=le(t),this._batchScheduleFn=ue(t),this._cacheKeyFn=de(t),this._cacheMap=me(t),this._batch=null,this.name=fe(t)}var i=s.prototype;return i.load=function(t){if(t==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(t)+"."));var r=he(this),n=this._cacheMap,a=this._cacheKeyFn(t);if(n){var o=n.get(a);if(o){var c=r.cacheHits||(r.cacheHits=[]);return new Promise(function(h){c.push(function(){h(o)})})}}r.keys.push(t);var p=new Promise(function(h,b){r.callbacks.push({resolve:h,reject:b})});return n&&n.set(a,p),p},i.loadMany=function(t){if(!O(t))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+t+"."));for(var r=[],n=0;n<t.length;n++)r.push(this.load(t[n]).catch(function(a){return a}));return Promise.all(r)},i.clear=function(t){var r=this._cacheMap;if(r){var n=this._cacheKeyFn(t);r.delete(n)}return this},i.clearAll=function(){var t=this._cacheMap;return t&&t.clear(),this},i.prime=function(t,r){var n=this._cacheMap;if(n){var a=this._cacheKeyFn(t);if(n.get(a)===void 0){var o;r instanceof Error?(o=Promise.reject(r),o.catch(function(){})):o=Promise.resolve(r),n.set(a,o)}}return this},s}(),ce=typeof process=="object"&&typeof process.nextTick=="function"?function(s){I||(I=Promise.resolve()),I.then(function(){process.nextTick(s)})}:typeof setImmediate=="function"?function(s){setImmediate(s)}:function(s){setTimeout(s)},I;function he(s){var i=s._batch;if(i!==null&&!i.hasDispatched&&i.keys.length<s._maxBatchSize)return i;var e={hasDispatched:!1,keys:[],callbacks:[]};return s._batch=e,s._batchScheduleFn(function(){pe(s,e)}),e}function pe(s,i){if(i.hasDispatched=!0,i.keys.length===0){k(i);return}var e;try{e=s._batchLoadFn(i.keys)}catch(t){return P(s,i,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function "+("errored synchronously: "+String(t)+".")))}if(!e||typeof e.then!="function")return P(s,i,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise: "+String(e)+".")));e.then(function(t){if(!O(t))throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise of an Array: "+String(t)+"."));if(t.length!==i.keys.length)throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys."+(`
// node_modules/dataloader/index.js
var require_dataloader = __commonJS({
"node_modules/dataloader/index.js"(exports, module) {
"use strict";
var DataLoader2 = /* @__PURE__ */ function() {
function DataLoader3(batchLoadFn, options) {
if (typeof batchLoadFn !== "function") {
throw new TypeError("DataLoader must be constructed with a function which accepts " + ("Array<key> and returns Promise<Array<value>>, but got: " + batchLoadFn + "."));
}
this._batchLoadFn = batchLoadFn;
this._maxBatchSize = getValidMaxBatchSize(options);
this._batchScheduleFn = getValidBatchScheduleFn(options);
this._cacheKeyFn = getValidCacheKeyFn(options);
this._cacheMap = getValidCacheMap(options);
this._batch = null;
this.name = getValidName(options);
}
var _proto = DataLoader3.prototype;
_proto.load = function load(key) {
if (key === null || key === void 0) {
throw new TypeError("The loader.load() function must be called with a value, " + ("but got: " + String(key) + "."));
}
var batch = getCurrentBatch(this);
var cacheMap = this._cacheMap;
var cacheKey = this._cacheKeyFn(key);
if (cacheMap) {
var cachedPromise = cacheMap.get(cacheKey);
if (cachedPromise) {
var cacheHits = batch.cacheHits || (batch.cacheHits = []);
return new Promise(function(resolve) {
cacheHits.push(function() {
resolve(cachedPromise);
});
});
}
}
batch.keys.push(key);
var promise = new Promise(function(resolve, reject) {
batch.callbacks.push({
resolve,
reject
});
});
if (cacheMap) {
cacheMap.set(cacheKey, promise);
}
return promise;
};
_proto.loadMany = function loadMany(keys) {
if (!isArrayLike(keys)) {
throw new TypeError("The loader.loadMany() function must be called with Array<key> " + ("but got: " + keys + "."));
}
var loadPromises = [];
for (var i = 0; i < keys.length; i++) {
loadPromises.push(this.load(keys[i])["catch"](function(error) {
return error;
}));
}
return Promise.all(loadPromises);
};
_proto.clear = function clear(key) {
var cacheMap = this._cacheMap;
if (cacheMap) {
var cacheKey = this._cacheKeyFn(key);
cacheMap["delete"](cacheKey);
}
return this;
};
_proto.clearAll = function clearAll() {
var cacheMap = this._cacheMap;
if (cacheMap) {
cacheMap.clear();
}
return this;
};
_proto.prime = function prime(key, value) {
var cacheMap = this._cacheMap;
if (cacheMap) {
var cacheKey = this._cacheKeyFn(key);
if (cacheMap.get(cacheKey) === void 0) {
var promise;
if (value instanceof Error) {
promise = Promise.reject(value);
promise["catch"](function() {
});
} else {
promise = Promise.resolve(value);
}
cacheMap.set(cacheKey, promise);
}
}
return this;
};
return DataLoader3;
}();
var enqueuePostPromiseJob = typeof process === "object" && typeof process.nextTick === "function" ? function(fn) {
if (!resolvedPromise) {
resolvedPromise = Promise.resolve();
}
resolvedPromise.then(function() {
process.nextTick(fn);
});
} : typeof setImmediate === "function" ? function(fn) {
setImmediate(fn);
} : function(fn) {
setTimeout(fn);
};
var resolvedPromise;
function getCurrentBatch(loader) {
var existingBatch = loader._batch;
if (existingBatch !== null && !existingBatch.hasDispatched && existingBatch.keys.length < loader._maxBatchSize) {
return existingBatch;
}
var newBatch = {
hasDispatched: false,
keys: [],
callbacks: []
};
loader._batch = newBatch;
loader._batchScheduleFn(function() {
dispatchBatch(loader, newBatch);
});
return newBatch;
}
function dispatchBatch(loader, batch) {
batch.hasDispatched = true;
if (batch.keys.length === 0) {
resolveCacheHits(batch);
return;
}
var batchPromise;
try {
batchPromise = loader._batchLoadFn(batch.keys);
} catch (e) {
return failedDispatch(loader, batch, new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function " + ("errored synchronously: " + String(e) + ".")));
}
if (!batchPromise || typeof batchPromise.then !== "function") {
return failedDispatch(loader, batch, new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did " + ("not return a Promise: " + String(batchPromise) + ".")));
}
batchPromise.then(function(values) {
if (!isArrayLike(values)) {
throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did " + ("not return a Promise of an Array: " + String(values) + "."));
}
if (values.length !== batch.keys.length) {
throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys." + ("\n\nKeys:\n" + String(batch.keys)) + ("\n\nValues:\n" + String(values)));
}
resolveCacheHits(batch);
for (var i = 0; i < batch.callbacks.length; i++) {
var value = values[i];
if (value instanceof Error) {
batch.callbacks[i].reject(value);
} else {
batch.callbacks[i].resolve(value);
}
}
})["catch"](function(error) {
failedDispatch(loader, batch, error);
});
}
function failedDispatch(loader, batch, error) {
resolveCacheHits(batch);
for (var i = 0; i < batch.keys.length; i++) {
loader.clear(batch.keys[i]);
batch.callbacks[i].reject(error);
}
}
function resolveCacheHits(batch) {
if (batch.cacheHits) {
for (var i = 0; i < batch.cacheHits.length; i++) {
batch.cacheHits[i]();
}
}
}
function getValidMaxBatchSize(options) {
var shouldBatch = !options || options.batch !== false;
if (!shouldBatch) {
return 1;
}
var maxBatchSize = options && options.maxBatchSize;
if (maxBatchSize === void 0) {
return Infinity;
}
if (typeof maxBatchSize !== "number" || maxBatchSize < 1) {
throw new TypeError("maxBatchSize must be a positive number: " + maxBatchSize);
}
return maxBatchSize;
}
function getValidBatchScheduleFn(options) {
var batchScheduleFn = options && options.batchScheduleFn;
if (batchScheduleFn === void 0) {
return enqueuePostPromiseJob;
}
if (typeof batchScheduleFn !== "function") {
throw new TypeError("batchScheduleFn must be a function: " + batchScheduleFn);
}
return batchScheduleFn;
}
function getValidCacheKeyFn(options) {
var cacheKeyFn = options && options.cacheKeyFn;
if (cacheKeyFn === void 0) {
return function(key) {
return key;
};
}
if (typeof cacheKeyFn !== "function") {
throw new TypeError("cacheKeyFn must be a function: " + cacheKeyFn);
}
return cacheKeyFn;
}
function getValidCacheMap(options) {
var shouldCache = !options || options.cache !== false;
if (!shouldCache) {
return null;
}
var cacheMap = options && options.cacheMap;
if (cacheMap === void 0) {
return /* @__PURE__ */ new Map();
}
if (cacheMap !== null) {
var cacheFunctions = ["get", "set", "delete", "clear"];
var missingFunctions = cacheFunctions.filter(function(fnName) {
return cacheMap && typeof cacheMap[fnName] !== "function";
});
if (missingFunctions.length !== 0) {
throw new TypeError("Custom cacheMap missing methods: " + missingFunctions.join(", "));
}
}
return cacheMap;
}
function getValidName(options) {
if (options && options.name) {
return options.name;
}
return null;
}
function isArrayLike(x) {
return typeof x === "object" && x !== null && typeof x.length === "number" && (x.length === 0 || x.length > 0 && Object.prototype.hasOwnProperty.call(x, x.length - 1));
}
module.exports = DataLoader2;
}
});
Keys:
`+String(i.keys))+(`
// src/api/GoogleAnalytics.ts
import { of } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var { gtag } = window;
var GoogleAnalytics = class {
constructor({ tracker }) {
this.tracker = tracker ? tracker : "t0";
this.eventNames = /* @__PURE__ */ new Map([
["addToWishlist", "add_to_wishlist"]
// ["removeFromWishlist", "WK Removed Product"],
// ["addToCart", "WK Added to Cart"],
// ["shareWishlist", "WK Shared Wishlist"],
// ["clearWishlist", "WK Cleared Wishlist"],
]);
}
track({ eventName, product, variant, quantity = 1 }) {
var _a, _b;
const eventAction = this.eventNames.get(eventName);
if (!eventAction || !gtag || !product) {
return of(false);
}
const itemPrice = (_a = variant == null ? void 0 : variant.price) != null ? _a : product.variants[0].price;
gtag("event", eventAction, {
currency: itemPrice,
value: variant == null ? void 0 : variant.price,
items: [
{
item_id: (_b = (variant == null ? void 0 : variant.sku) || (variant == null ? void 0 : variant.id)) != null ? _b : product.id,
item_name: product.title,
affiliation: "Wishlist King",
item_category: product.type,
item_brand: product.vendor,
item_variant: variant == null ? void 0 : variant.title,
item_quantity: quantity,
item_price: itemPrice
}
]
});
return of(true);
}
};
// src/api/KlaviyoTracking.ts
import { of as of2 } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var KlaviyoTracking = class {
constructor({
urlUtil,
moneyUtil
}) {
this.urlUtil = urlUtil;
this.moneyUtil = moneyUtil;
this.eventNames = /* @__PURE__ */ new Map([
["addToWishlist", "Added To Wishlist"],
["removeFromWishlist", "Removed From Wishlist"],
["clearWishlist", "Cleared Wishlist"]
]);
}
track({
eventName,
wishlist,
product,
variant,
quantity = 1
}) {
const eventAction = this.eventNames.get(eventName);
if (!eventAction || !wishlist || !product) {
return of2(false);
}
if (!window._learnq) {
window._learnq = [];
}
window._learnq.push([
"track",
eventAction,
{
URL: this.urlUtil.getVariantUrl(product.url, variant == null ? void 0 : variant.id),
Name: product.title,
ProductID: product.id,
VariantID: variant == null ? void 0 : variant.id,
SKU: variant == null ? void 0 : variant.sku,
Tags: product.tags,
Brand: product.vendor,
ImageURL: this.urlUtil.getImageUrl(product, { width: 1e3 }),
Price: variant == null ? void 0 : variant.price,
PriceFormatted: variant ? this.moneyUtil.formatMoney(variant.price) : null,
CompareAtPrice: variant == null ? void 0 : variant.compare_at_price,
CompareAtPriceFormatted: (variant == null ? void 0 : variant.compare_at_price) ? this.moneyUtil.formatMoney(variant.compare_at_price) : null,
Quantity: quantity,
WishlistUrl: this.urlUtil.getPublicWishlistUrl(wishlist.id)
// WishlistProductIDs: [] // 5 most recent product ids
}
]);
return of2(true);
}
};
// src/api/MetaPixel.ts
import { of as of3 } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var { fbq } = window;
var MetaPixel = class {
constructor({ currency }) {
this.currency = currency;
this.eventNames = /* @__PURE__ */ new Map([["addToWishlist", "AddToWishlist"]]);
}
track({ eventName, product, variant }) {
const eventAction = this.eventNames.get(eventName);
if (!eventAction || typeof fbq !== "function" || !product) {
return of3(false);
}
fbq("track", eventAction, {
value: variant == null ? void 0 : variant.price,
currency: this.currency,
content_ids: [product.id],
content_name: [product.title, variant == null ? void 0 : variant.title].filter((v) => !!v).join(" - "),
content_category: product.type,
content_type: "product_group",
num_items: 1
});
return of3(true);
}
};
// src/api/NotifyApi.ts
import { catchError, from, map, of as of4 } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var NotifyApi = class {
constructor({
host,
shop,
sessionId,
customerId
}) {
this.host = host;
this.shop = shop;
this.customerId = customerId;
this.sessionId = sessionId;
this.eventNames = /* @__PURE__ */ new Map([
["viewWishlist", "wishlist_viewed"],
["addToCart", "product_added_to_cart"],
["shareWishlist", "wishlist_shared"]
]);
}
setSessionId(sessionId) {
this.sessionId = sessionId;
}
track({
eventName,
wishlist,
product,
variant,
quantity,
source
}) {
var _a, _b;
if (!this.sessionId) {
return of4(false);
}
const eventAction = this.eventNames.get(eventName);
if (!eventAction || !wishlist) {
return of4(false);
}
return from(
window.fetch(this.host + `/notify`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-appmate-shp": this.shop,
"x-appmate-sid": (_a = this.sessionId) != null ? _a : "",
"x-appmate-cid": (_b = this.customerId) != null ? _b : ""
},
body: JSON.stringify({
event: eventAction,
wid: wishlist.publicId,
pid: product == null ? void 0 : product.id,
vid: variant == null ? void 0 : variant.id,
qty: quantity,
src: source
})
})
).pipe(
map(() => true),
catchError(() => of4(false))
);
}
getQuerystring(query) {
if (!query) {
return "";
}
const params = new URLSearchParams();
Object.entries(query).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((value2) => params.append(key, value2));
} else if (value) {
params.append(key, value);
}
});
return "?" + params.toString();
}
};
// src/api/RestApi.ts
import { from as from2, switchMap } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var RestApi = class {
constructor(params) {
this.host = params.host;
this.headers = {
"content-type": "application/json"
};
}
fetch({
path,
method = "GET",
query,
body,
headers = {}
}) {
return from2(
window.fetch(this.host + path + this.getQuerystring(query), {
method,
headers: {
...this.headers,
...headers
},
body
})
).pipe(
switchMap((response) => {
if (response.ok) {
return response.json();
} else {
throw Error(`Error ${response.status}`);
}
})
);
}
getQuerystring(query) {
if (!query) {
return "";
}
const params = new URLSearchParams();
Object.entries(query).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((value2) => params.append(key, value2));
} else if (value) {
params.append(key, value);
}
});
return "?" + params.toString();
}
get({ path, query, headers }) {
return this.fetch({
method: "GET",
path,
query,
headers
});
}
post({ path, query, body, headers }) {
return this.fetch({
method: "POST",
path,
query,
body: body ? JSON.stringify(body) : void 0,
headers
});
}
put({ path, query, body, headers }) {
return this.fetch({
method: "PUT",
path,
query,
body: body ? JSON.stringify(body) : void 0,
headers
});
}
delete({ path, query, body, headers }) {
return this.fetch({
method: "DELETE",
path,
query,
body: body ? JSON.stringify(body) : void 0,
headers
});
}
};
// src/api/ShopifyApi.ts
import { shareReplay, tap } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var ShopifyApi = class extends RestApi {
constructor() {
super(...arguments);
this.pendingProducts = /* @__PURE__ */ new Map();
}
loadProduct({ productHandle }) {
const path = `/products/${productHandle}.js`;
const pending = this.pendingProducts.get(path);
if (pending) {
return pending;
}
const product$ = this.get({
path
}).pipe(
tap(() => {
this.pendingProducts.delete(path);
}),
shareReplay()
);
this.pendingProducts.set(path, product$);
return product$;
}
addToCart(body) {
return this.post({
path: "/cart/add.js",
body
});
}
};
// src/api/TrackingApi.ts
import { forkJoin, lastValueFrom, of as of5 } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var TrackingApi = class {
constructor({
settings,
events,
notifyHost,
utils,
theme,
shop,
sessionId,
customerId
}) {
this.utils = utils;
this.theme = theme;
this.services = [];
if (settings.integrations.wishlistAnalytics.enabled) {
this.services.push(
new NotifyApi({
host: notifyHost,
shop,
customerId,
sessionId
})
);
}
if (settings.integrations.klaviyo.enabled) {
this.services.push(
new KlaviyoTracking({
urlUtil: this.utils.url,
moneyUtil: this.utils.money
})
);
}
if (settings.integrations.metaPixel.enabled) {
this.services.push(
new MetaPixel({
currency: window.Shopify.currency.active
})
);
}
if (settings.integrations.googleAnalytics.enabled) {
this.services.push(
new GoogleAnalytics({
tracker: settings.integrations.googleAnalytics.tracker
})
);
}
const source = this.theme.getPageType();
const trackStateEvent = (eventName) => (event) => {
var _a, _b, _c, _d;
return lastValueFrom(
this.track({
eventName,
source,
wishlist: (_a = event.data) == null ? void 0 : _a.wishlist,
product: (_b = event.data) == null ? void 0 : _b.product,
variant: (_c = event.data) == null ? void 0 : _c.variant,
quantity: (_d = event.data) == null ? void 0 : _d.quantity
})
);
};
events.subscribeMany({
"wk:wishlist:add-to-cart:success": trackStateEvent("addToCart"),
"wk:wishlist:add:success": trackStateEvent("addToWishlist"),
"wk:wishlist:change-variant:success": trackStateEvent("changeVariant"),
"wk:wishlist:clear:success": trackStateEvent("clearWishlist"),
"wk:wishlist:remove:success": trackStateEvent("removeFromWishlist"),
"wk:wishlist:share:success": trackStateEvent("shareWishlist"),
"wk:wishlist:page-view": trackStateEvent("viewWishlist")
});
}
track(event) {
if (!this.services.length) {
return of5([]);
}
return forkJoin(this.services.map((service) => service.track(event)));
}
setSessionId(sessionId) {
const notifyApi = this.services.find(
(service) => service instanceof NotifyApi
);
if (notifyApi) {
notifyApi.setSessionId(sessionId);
}
}
};
// src/api/WishlistApi.ts
var import_dataloader = __toESM(require_dataloader());
import {
defer,
from as from3,
lastValueFrom as lastValueFrom2,
shareReplay as shareReplay2,
switchMap as switchMap2,
tap as tap2
} from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var WishlistApi = class extends RestApi {
constructor(params) {
super(params);
this.productMetafields = false;
this.headers = {
"content-type": "application/json",
"x-appmate-api": "2022-11"
};
if (params.shop) {
this.headers["x-appmate-shp"] = params.shop;
}
if (params.sessionId) {
this.headers["x-appmate-sid"] = params.sessionId;
}
if (params.customerId) {
this.headers["x-appmate-cid"] = params.customerId.toString();
}
if (params.trackingSource) {
this.headers["x-appmate-src"] = params.trackingSource;
}
this.productMetafields = !!params.productMetafields;
this.wishlistLoader = this.createWishlistLoader();
this.wishlistItemLoader = this.createWishlistItemLoader();
}
get hasSession() {
return !!this.headers["x-appmate-sid"] || !!this.headers["x-appmate-cid"];
}
setSessionId(sessionId) {
this.headers["x-appmate-sid"] = sessionId;
}
createWishlistLoader() {
return new import_dataloader.default(
async (ids) => {
const wishlists = await Promise.all(
ids.map(
(wishlistId) => lastValueFrom2(
this.get({
path: `/wishlists/${wishlistId}`
})
)
)
).then((results) => results.map((result) => result.wishlist));
return ids.map((wishlistId) => {
var _a;
return (_a = wishlists.find((wishlist) => {
if (wishlistId === "mine") {
return wishlist.isMine;
}
return wishlist.publicId === wishlistId;
})) != null ? _a : new Error("Wishlist not found");
});
},
{
cache: true,
batchScheduleFn: (callback) => setTimeout(callback, 250)
}
);
}
createWishlistItemLoader() {
return new import_dataloader.default(
async (ids) => {
const dataMap = ids.map((id) => id.split("-")).reduce((map2, [wishlistId, wishlistItemId]) => {
if (!map2[wishlistId]) {
map2[wishlistId] = [];
}
map2[wishlistId].push(wishlistItemId);
return map2;
}, {});
const wishlistItems = await Promise.all(
Object.entries(dataMap).map(
([wishlistId, wishlistItemIds]) => lastValueFrom2(
this.get({
path: `/wishlists/${wishlistId}/items`,
headers: {
"x-appmate-ids": wishlistItemIds.join(","),
...this.productMetafields ? { "x-appmate-pmf": true } : {}
}
})
)
)
).then((results) => results.flatMap((result) => result.items));
return ids.map((id) => {
var _a;
const [, wishlistItemId] = id.split("-");
return (_a = wishlistItems.find((item) => item.id === wishlistItemId)) != null ? _a : new Error("Wishlist item not found");
});
},
{
cache: true,
batchScheduleFn: (callback) => setTimeout(callback, 250)
}
);
}
loadWishlist({ wishlistId }) {
return from3(
defer(
() => this.wishlistLoader.load(wishlistId).then((wishlist) => ({
wishlist
}))
)
);
}
loadWishlistItem({
wishlistId,
wishlistItemId
}) {
return from3(
defer(
() => this.wishlistItemLoader.load([wishlistId, wishlistItemId].join("-")).then(({ selectedVariantId, ...wishlistItem }) => ({
wishlistItem
}))
)
);
}
addItem({
productId,
variantId
}) {
if (typeof productId === "string") {
productId = parseInt(productId);
}
if (typeof variantId === "string") {
variantId = parseInt(variantId);
}
if (!this.hasSession && this._pendingSessionId) {
return this._pendingSessionId.pipe(
switchMap2(() => {
return this.addItem({
productId,
variantId
});
})
);
}
const request = this.post({
path: `/wishlists/mine/items`,
body: {
productId,
variantId
}
}).pipe(
tap2((result) => {
if (result.sessionId) {
this.setSessionId(result.sessionId);
this._pendingSessionId = void 0;
}
}),
shareReplay2()
);
if (!this.hasSession) {
this._pendingSessionId = request;
}
return request;
}
updateItem({
wishlistItemId,
changes
}) {
return this.put({
path: `/wishlists/mine/items`,
body: {
changes: {
...changes,
wishlistItemId
}
}
}).pipe(shareReplay2());
}
removeItem({
wishlistId,
wishlistItemId
}) {
return this.delete({
path: `/wishlists/${wishlistId}/items`,
body: {
wishlistItemId
}
}).pipe(shareReplay2());
}
clearWishlist() {
return this.delete({
path: `/wishlists/mine`
}).pipe(shareReplay2());
}
};
export {
GoogleAnalytics,
KlaviyoTracking,
MetaPixel,
NotifyApi,
RestApi,
ShopifyApi,
TrackingApi,
WishlistApi
};
//# sourceMappingURL=api.js.map
Values:
`+String(t)));k(i);for(var r=0;r<i.callbacks.length;r++){var n=t[r];n instanceof Error?i.callbacks[r].reject(n):i.callbacks[r].resolve(n)}}).catch(function(t){P(s,i,t)})}function P(s,i,e){k(i);for(var t=0;t<i.keys.length;t++)s.clear(i.keys[t]),i.callbacks[t].reject(e)}function k(s){if(s.cacheHits)for(var i=0;i<s.cacheHits.length;i++)s.cacheHits[i]()}function le(s){var i=!s||s.batch!==!1;if(!i)return 1;var e=s&&s.maxBatchSize;if(e===void 0)return 1/0;if(typeof e!="number"||e<1)throw new TypeError("maxBatchSize must be a positive number: "+e);return e}function ue(s){var i=s&&s.batchScheduleFn;if(i===void 0)return ce;if(typeof i!="function")throw new TypeError("batchScheduleFn must be a function: "+i);return i}function de(s){var i=s&&s.cacheKeyFn;if(i===void 0)return function(e){return e};if(typeof i!="function")throw new TypeError("cacheKeyFn must be a function: "+i);return i}function me(s){var i=!s||s.cache!==!1;if(!i)return null;var e=s&&s.cacheMap;if(e===void 0)return new Map;if(e!==null){var t=["get","set","delete","clear"],r=t.filter(function(n){return e&&typeof e[n]!="function"});if(r.length!==0)throw new TypeError("Custom cacheMap missing methods: "+r.join(", "))}return e}function fe(s){return s&&s.name?s.name:null}function O(s){return typeof s=="object"&&s!==null&&typeof s.length=="number"&&(s.length===0||s.length>0&&Object.prototype.hasOwnProperty.call(s,s.length-1))}j.exports=oe});import{of as U}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var{gtag:R}=window,d=class{constructor({tracker:i}){this.tracker=i||"t0",this.eventNames=new Map([["addToWishlist","add_to_wishlist"]])}track({eventName:i,product:e,variant:t,quantity:r=1}){var o,c;let n=this.eventNames.get(i);if(!n||!R||!e)return U(!1);let a=(o=t==null?void 0:t.price)!=null?o:e.variants[0].price;return R("event",n,{currency:a,value:t==null?void 0:t.price,items:[{item_id:(c=(t==null?void 0:t.sku)||(t==null?void 0:t.id))!=null?c:e.id,item_name:e.title,affiliation:"Wishlist King",item_category:e.type,item_brand:e.vendor,item_variant:t==null?void 0:t.title,item_quantity:r,item_price:a}]}),U(!0)}};import{of as N}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var m=class{constructor({urlUtil:i,moneyUtil:e}){this.urlUtil=i,this.moneyUtil=e,this.eventNames=new Map([["addToWishlist","Added To Wishlist"],["removeFromWishlist","Removed From Wishlist"],["clearWishlist","Cleared Wishlist"]])}track({eventName:i,wishlist:e,product:t,variant:r,quantity:n=1}){let a=this.eventNames.get(i);return!a||!e||!t?N(!1):(window._learnq||(window._learnq=[]),window._learnq.push(["track",a,{URL:this.urlUtil.getVariantUrl(t.url,r==null?void 0:r.id),Name:t.title,ProductID:t.id,VariantID:r==null?void 0:r.id,SKU:r==null?void 0:r.sku,Tags:t.tags,Brand:t.vendor,ImageURL:this.urlUtil.getImageUrl(t,{width:1e3}),Price:r==null?void 0:r.price,PriceFormatted:r?this.moneyUtil.formatMoney(r.price):null,CompareAtPrice:r==null?void 0:r.compare_at_price,CompareAtPriceFormatted:r!=null&&r.compare_at_price?this.moneyUtil.formatMoney(r.compare_at_price):null,Quantity:n,WishlistUrl:this.urlUtil.getPublicWishlistUrl(e.id)}]),N(!0))}};import{of as L}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var{fbq:F}=window,f=class{constructor({currency:i}){this.currency=i,this.eventNames=new Map([["addToWishlist","AddToWishlist"]])}track({eventName:i,product:e,variant:t}){let r=this.eventNames.get(i);return!r||typeof F!="function"||!e?L(!1):(F("track",r,{value:t==null?void 0:t.price,currency:this.currency,content_ids:[e.id],content_name:[e.title,t==null?void 0:t.title].filter(n=>!!n).join(" - "),content_category:e.type,content_type:"product_group",num_items:1}),L(!0))}};import{catchError as X,from as Y,map as Z,of as w}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var u=class{constructor({host:i,shop:e,sessionId:t,customerId:r}){this.host=i,this.shop=e,this.customerId=r,this.sessionId=t,this.eventNames=new Map([["viewWishlist","wishlist_viewed"],["addToCart","product_added_to_cart"],["shareWishlist","wishlist_shared"]])}setSessionId(i){this.sessionId=i}track({eventName:i,wishlist:e,product:t,variant:r,quantity:n,source:a}){var c,p;if(!this.sessionId)return w(!1);let o=this.eventNames.get(i);return!o||!e?w(!1):Y(window.fetch(this.host+"/notify",{method:"POST",headers:{"content-type":"application/json","x-appmate-shp":this.shop,"x-appmate-sid":(c=this.sessionId)!=null?c:"","x-appmate-cid":(p=this.customerId)!=null?p:""},body:JSON.stringify({event:o,wid:e.publicId,pid:t==null?void 0:t.id,vid:r==null?void 0:r.id,qty:n,src:a})})).pipe(Z(()=>!0),X(()=>w(!1)))}getQuerystring(i){if(!i)return"";let e=new URLSearchParams;return Object.entries(i).forEach(([t,r])=>{Array.isArray(r)?r.forEach(n=>e.append(t,n)):r&&e.append(t,r)}),"?"+e.toString()}};import{from as ee,switchMap as te}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var l=class{constructor(i){this.host=i.host,this.headers={"content-type":"application/json"}}fetch({path:i,method:e="GET",query:t,body:r,headers:n={}}){return ee(window.fetch(this.host+i+this.getQuerystring(t),{method:e,headers:{...this.headers,...n},body:r})).pipe(te(a=>{if(a.ok)return a.json();throw Error(`Error ${a.status}`)}))}getQuerystring(i){if(!i)return"";let e=new URLSearchParams;return Object.entries(i).forEach(([t,r])=>{Array.isArray(r)?r.forEach(n=>e.append(t,n)):r&&e.append(t,r)}),"?"+e.toString()}get({path:i,query:e,headers:t}){return this.fetch({method:"GET",path:i,query:e,headers:t})}post({path:i,query:e,body:t,headers:r}){return this.fetch({method:"POST",path:i,query:e,body:t?JSON.stringify(t):void 0,headers:r})}put({path:i,query:e,body:t,headers:r}){return this.fetch({method:"PUT",path:i,query:e,body:t?JSON.stringify(t):void 0,headers:r})}delete({path:i,query:e,body:t,headers:r}){return this.fetch({method:"DELETE",path:i,query:e,body:t?JSON.stringify(t):void 0,headers:r})}};import{shareReplay as ie,tap as re}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var _=class extends l{constructor(){super(...arguments);this.pendingProducts=new Map}loadProduct({productHandle:e}){let t=`/products/${e}.js`,r=this.pendingProducts.get(t);if(r)return r;let n=this.get({path:t}).pipe(re(()=>{this.pendingProducts.delete(t)}),ie());return this.pendingProducts.set(t,n),n}addToCart(e){return this.post({path:"/cart/add.js",body:e})}};import{forkJoin as se,lastValueFrom as ne,of as ae}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var T=class{constructor({settings:i,events:e,notifyHost:t,utils:r,theme:n,shop:a,sessionId:o,customerId:c}){this.utils=r,this.theme=n,this.services=[],i.integrations.wishlistAnalytics.enabled&&this.services.push(new u({host:t,shop:a,customerId:c,sessionId:o})),i.integrations.klaviyo.enabled&&this.services.push(new m({urlUtil:this.utils.url,moneyUtil:this.utils.money})),i.integrations.metaPixel.enabled&&this.services.push(new f({currency:window.Shopify.currency.active})),i.integrations.googleAnalytics.enabled&&this.services.push(new d({tracker:i.integrations.googleAnalytics.tracker}));let p=this.theme.getPageType(),h=b=>g=>{var A,x,W,E;return ne(this.track({eventName:b,source:p,wishlist:(A=g.data)==null?void 0:A.wishlist,product:(x=g.data)==null?void 0:x.product,variant:(W=g.data)==null?void 0:W.variant,quantity:(E=g.data)==null?void 0:E.quantity}))};e.subscribeMany({"wk:wishlist:add-to-cart:success":h("addToCart"),"wk:wishlist:add:success":h("addToWishlist"),"wk:wishlist:change-variant:success":h("changeVariant"),"wk:wishlist:clear:success":h("clearWishlist"),"wk:wishlist:remove:success":h("removeFromWishlist"),"wk:wishlist:share:success":h("shareWishlist"),"wk:wishlist:page-view":h("viewWishlist")})}track(i){return this.services.length?se(this.services.map(e=>e.track(i))):ae([])}setSessionId(i){let e=this.services.find(t=>t instanceof u);e&&e.setSessionId(i)}};var S=Q(q());import{defer as C,from as D,lastValueFrom as V,shareReplay as y,switchMap as ge,tap as ye}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var v=class extends l{constructor(e){super(e);this.productMetafields=!1;this.headers={"content-type":"application/json","x-appmate-api":"2022-11"},e.shop&&(this.headers["x-appmate-shp"]=e.shop),e.sessionId&&(this.headers["x-appmate-sid"]=e.sessionId),e.customerId&&(this.headers["x-appmate-cid"]=e.customerId.toString()),e.trackingSource&&(this.headers["x-appmate-src"]=e.trackingSource),this.productMetafields=!!e.productMetafields,this.wishlistLoader=this.createWishlistLoader(),this.wishlistItemLoader=this.createWishlistItemLoader()}get hasSession(){return!!this.headers["x-appmate-sid"]||!!this.headers["x-appmate-cid"]}setSessionId(e){this.headers["x-appmate-sid"]=e}createWishlistLoader(){return new S.default(async e=>{let t=await Promise.all(e.map(r=>V(this.get({path:`/wishlists/${r}`})))).then(r=>r.map(n=>n.wishlist));return e.map(r=>{var n;return(n=t.find(a=>r==="mine"?a.isMine:a.publicId===r))!=null?n:new Error("Wishlist not found")})},{cache:!0,batchScheduleFn:e=>setTimeout(e,250)})}createWishlistItemLoader(){return new S.default(async e=>{let t=e.map(n=>n.split("-")).reduce((n,[a,o])=>(n[a]||(n[a]=[]),n[a].push(o),n),{}),r=await Promise.all(Object.entries(t).map(([n,a])=>V(this.get({path:`/wishlists/${n}/items`,headers:{"x-appmate-ids":a.join(","),...this.productMetafields?{"x-appmate-pmf":!0}:{}}})))).then(n=>n.flatMap(a=>a.items));return e.map(n=>{var o;let[,a]=n.split("-");return(o=r.find(c=>c.id===a))!=null?o:new Error("Wishlist item not found")})},{cache:!0,batchScheduleFn:e=>setTimeout(e,250)})}loadWishlist({wishlistId:e}){return D(C(()=>this.wishlistLoader.load(e).then(t=>({wishlist:t}))))}loadWishlistItem({wishlistId:e,wishlistItemId:t}){return D(C(()=>this.wishlistItemLoader.load([e,t].join("-")).then(({selectedVariantId:r,...n})=>({wishlistItem:n}))))}addItem({productId:e,variantId:t}){if(typeof e=="string"&&(e=parseInt(e)),typeof t=="string"&&(t=parseInt(t)),!this.hasSession&&this._pendingSessionId)return this._pendingSessionId.pipe(ge(()=>this.addItem({productId:e,variantId:t})));let r=this.post({path:"/wishlists/mine/items",body:{productId:e,variantId:t}}).pipe(ye(n=>{n.sessionId&&(this.setSessionId(n.sessionId),this._pendingSessionId=void 0)}),y());return this.hasSession||(this._pendingSessionId=r),r}updateItem({wishlistItemId:e,changes:t}){return this.put({path:"/wishlists/mine/items",body:{changes:{...t,wishlistItemId:e}}}).pipe(y())}removeItem({wishlistId:e,wishlistItemId:t}){return this.delete({path:`/wishlists/${e}/items`,body:{wishlistItemId:t}}).pipe(y())}clearWishlist(){return this.delete({path:"/wishlists/mine"}).pipe(y())}};export{d as GoogleAnalytics,m as KlaviyoTracking,f as MetaPixel,u as NotifyApi,l as RestApi,_ as ShopifyApi,T as TrackingApi,v as WishlistApi};

@@ -1,57 +0,10 @@

// src/components/button.ts
import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
import { FloatingUiController } from "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/controllers.js";
import "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/components/counter.js";
import "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/components/icon.js";
var Button = class extends LitElement {
constructor() {
super(...arguments);
this.text = "";
this.hint = "";
this.selected = false;
this.disabled = false;
this.showIcon = false;
this.showText = false;
this.iconUnstyled = false;
this.fullWidth = false;
this.alignSelf = "center";
this.alignContent = "center";
this.floatingUi = new FloatingUiController(this);
this.getCounterFloating = () => {
var _a, _b, _c, _d;
if (!((_a = this.counter) == null ? void 0 : _a.floating))
return;
const reference = ((_c = (_b = this.counter) == null ? void 0 : _b.floating) == null ? void 0 : _c.reference) === "icon" ? (_d = this.iconElement) != null ? _d : this : this;
return {
...this.counter.floating,
reference
};
};
}
get iconElement() {
return this.querySelector(".wk-icon");
}
render() {
var _a, _b, _c, _d;
const alignSelf = (_a = this.alignSelf) != null ? _a : "center";
const alignContent = (_b = this.alignContent) != null ? _b : "center";
const classes = [
"wk-button",
`wk-align-${alignSelf}`,
`wk-align-content-${alignContent}`,
this.selected && "wk-selected",
this.fullWidth && "wk-full-width"
].filter((v) => !!v).join(" ");
if (this.href) {
return html`
<a href=${this.href} aria-label=${(_c = this.hint) != null ? _c : ""} class=${classes}>
import{LitElement as h,html as i}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";import{FloatingUiController as u}from"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/controllers.js";import"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/components/counter.js";import"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/components/icon.js";var s=class extends h{constructor(){super(...arguments);this.text="";this.hint="";this.selected=!1;this.disabled=!1;this.showIcon=!1;this.showText=!1;this.iconUnstyled=!1;this.fullWidth=!1;this.alignSelf="center";this.alignContent="center";this.floatingUi=new u(this);this.getCounterFloating=()=>{var r,e,n,o;if(!((r=this.counter)!=null&&r.floating))return;let t=((n=(e=this.counter)==null?void 0:e.floating)==null?void 0:n.reference)==="icon"?(o=this.iconElement)!=null?o:this:this;return{...this.counter.floating,reference:t}}}get iconElement(){return this.querySelector(".wk-icon")}render(){var n,o,l,a;let t=(n=this.alignSelf)!=null?n:"center",r=(o=this.alignContent)!=null?o:"center",e=["wk-button",`wk-align-${t}`,`wk-align-content-${r}`,this.selected&&"wk-selected",this.fullWidth&&"wk-full-width"].filter(c=>!!c).join(" ");return this.href?i`
<a href=${this.href} aria-label=${(l=this.hint)!=null?l:""} class=${e}>
${this.renderIcon()}${this.renderText()}${this.renderCounter()}
</a>
`;
}
return html`
`:i`
<button
type="button"
aria-label=${(_d = this.hint) != null ? _d : ""}
class=${classes}
aria-label=${(a=this.hint)!=null?a:""}
class=${e}
?disabled=${this.disabled}

@@ -61,9 +14,3 @@ >

</button>
`;
}
renderIcon() {
if (!this.showIcon || !this.icon) {
return;
}
return html`
`}renderIcon(){if(!(!this.showIcon||!this.icon))return i`
<wk-icon

@@ -74,21 +21,5 @@ class="wk-icon"

></wk-icon>
`;
}
renderText() {
if (!this.showText) {
return;
}
return html`<span class="wk-text">${this.text}</span>`;
}
renderCounter() {
var _a;
if (!this.counter) {
return;
}
if (this.counter.hideWhenZero && !this.counter.value) {
return;
}
return html`
`}renderText(){if(this.showText)return i`<span class="wk-text">${this.text}</span>`}renderCounter(){var t;if(this.counter&&!(this.counter.hideWhenZero&&!this.counter.value))return i`
<wk-counter
.value=${(_a = this.counter) == null ? void 0 : _a.value}
.value=${(t=this.counter)==null?void 0:t.value}
.floating=${this.counterFloating}

@@ -99,35 +30,2 @@ .showIcon=${this.counter.showIcon}

></wk-counter>
`;
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
this.counterFloating = this.getCounterFloating();
}
createRenderRoot() {
return this;
}
};
Button.properties = {
href: { type: String },
text: { type: String },
hint: { type: String },
selected: { type: Boolean },
disabled: { type: Boolean },
showIcon: { type: Boolean, attribute: "show-icon" },
showText: { type: Boolean, attribute: "show-text" },
icon: { type: String },
iconUnstyled: { type: Boolean, attribute: "icon-unstyled" },
fullWidth: { type: Boolean, attribute: "full-width" },
alignSelf: { type: String, attribute: "align-self" },
alignContent: { type: String, attribute: "align-content" },
floating: { type: Object },
counter: { type: Object },
counterFloating: { state: true }
};
if (!customElements.get("wk-button")) {
customElements.define("wk-button", Button);
}
export {
Button
};
//# sourceMappingURL=button.js.map
`}firstUpdated(t){super.firstUpdated(t),this.counterFloating=this.getCounterFloating()}createRenderRoot(){return this}};s.properties={href:{type:String},text:{type:String},hint:{type:String},selected:{type:Boolean},disabled:{type:Boolean},showIcon:{type:Boolean,attribute:"show-icon"},showText:{type:Boolean,attribute:"show-text"},icon:{type:String},iconUnstyled:{type:Boolean,attribute:"icon-unstyled"},fullWidth:{type:Boolean,attribute:"full-width"},alignSelf:{type:String,attribute:"align-self"},alignContent:{type:String,attribute:"align-content"},floating:{type:Object},counter:{type:Object},counterFloating:{state:!0}};customElements.get("wk-button")||customElements.define("wk-button",s);export{s as Button};

@@ -1,40 +0,1 @@

// src/components/counter.ts
import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
import { FloatingUiController } from "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/controllers.js";
var Counter = class extends LitElement {
constructor() {
super(...arguments);
this.value = 0;
this.showIcon = false;
this.showNumber = false;
this.showBrackets = false;
this.floatingUi = new FloatingUiController(this);
}
render() {
const text = this.showNumber ? this.value : "";
const classes = [
"wk-counter",
this.showBrackets && "wk-brackets",
this.floating && "wk-bubble",
this.floating && !this.showNumber && "wk-dot"
].filter((v) => !!v).join(" ");
return html`<span class=${classes}>${text}</span>`;
}
createRenderRoot() {
return this;
}
};
Counter.properties = {
value: { type: Number },
floating: { type: Object },
showIcon: { type: Boolean, attribute: "show-icon" },
showNumber: { type: Boolean, attribute: "show-number" },
showBrackets: { type: Boolean, attribute: "show-brackets" }
};
if (!customElements.get("wk-counter")) {
customElements.define("wk-counter", Counter);
}
export {
Counter
};
//# sourceMappingURL=counter.js.map
import{LitElement as s,html as a}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";import{FloatingUiController as n}from"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/controllers.js";var t=class extends s{constructor(){super(...arguments);this.value=0;this.showIcon=!1;this.showNumber=!1;this.showBrackets=!1;this.floatingUi=new n(this)}render(){let e=this.showNumber?this.value:"",o=["wk-counter",this.showBrackets&&"wk-brackets",this.floating&&"wk-bubble",this.floating&&!this.showNumber&&"wk-dot"].filter(r=>!!r).join(" ");return a`<span class=${o}>${e}</span>`}createRenderRoot(){return this}};t.properties={value:{type:Number},floating:{type:Object},showIcon:{type:Boolean,attribute:"show-icon"},showNumber:{type:Boolean,attribute:"show-number"},showBrackets:{type:Boolean,attribute:"show-brackets"}};customElements.get("wk-counter")||customElements.define("wk-counter",t);export{t as Counter};

@@ -1,49 +0,1 @@

// src/components/icon.ts
import { LitElement } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
import { unsafeHTML } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
var _Icon = class extends LitElement {
constructor() {
super();
this.icon = "";
this.unstyled = false;
this.classList.add("wk-icon");
}
static addIcons(icons) {
this.icons = {
...this.icons,
...icons
};
}
render() {
if (!this.icon) {
return unsafeHTML(`<svg><!-- icon not defined --></svg>`);
}
const iconSvg = _Icon.icons[this.icon];
if (!iconSvg) {
console.warn(`Icon "${this.icon}" not found`, { icons: _Icon.icons });
}
return unsafeHTML(iconSvg);
}
updated(_changedProperties) {
super.updated(_changedProperties);
if (_changedProperties.has("unstyled")) {
this.classList.toggle("wk-nostyle", this.unstyled);
}
}
createRenderRoot() {
return this;
}
};
var Icon = _Icon;
Icon.properties = {
icon: { type: String },
unstyled: { type: Boolean }
};
Icon.icons = {};
if (!customElements.get("wk-icon")) {
customElements.define("wk-icon", Icon);
}
export {
Icon
};
//# sourceMappingURL=icon.js.map
import{LitElement as o}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";import{unsafeHTML as s}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";var n=class extends o{constructor(){super();this.icon="";this.unstyled=!1;this.classList.add("wk-icon")}static addIcons(t){this.icons={...this.icons,...t}}render(){if(!this.icon)return s("<svg><!-- icon not defined --></svg>");let t=n.icons[this.icon];return t||console.warn(`Icon "${this.icon}" not found`,{icons:n.icons}),s(t)}updated(t){super.updated(t),t.has("unstyled")&&this.classList.toggle("wk-nostyle",this.unstyled)}createRenderRoot(){return this}},e=n;e.properties={icon:{type:String},unstyled:{type:Boolean}},e.icons={};customElements.get("wk-icon")||customElements.define("wk-icon",e);export{e as Icon};

@@ -1,41 +0,18 @@

// src/components/option-select.ts
import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
import { Icon } from "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/components/icon.js";
var OptionSelect = class extends LitElement {
constructor() {
super();
this.icon = "caret";
}
get app() {
if (!window.WishlistKing) {
throw new Error("Wishlist King SDK not initialized");
}
return window.WishlistKing;
}
render() {
if (!this.option) {
return;
}
const option = this.option;
const name = `options[${this.option.name}]`;
const inputId = `${this.app.utils.url.handlelize(this.id)}-select`;
return html`
import{LitElement as l,html as n}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";import{Icon as a}from"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/components/icon.js";var i=class extends l{constructor(){super();this.icon="caret"}get app(){if(!window.WishlistKing)throw new Error("Wishlist King SDK not initialized");return window.WishlistKing}render(){if(!this.option)return;let t=this.option,e=`options[${this.option.name}]`,s=`${this.app.utils.url.handlelize(this.id)}-select`;return n`
<div class="wk-option-select">
<label class="wk-label" for=${inputId}>${option.name}</label>
<label class="wk-label" for=${s}>${t.name}</label>
<div class="wk-control">
<select id=${inputId} class="wk-input" name=${name}>
${!option.selectedValue && this.defaultText ? html`<option disabled selected>${this.defaultText}</option>` : void 0}
${option.values.map(
(value) => html`
<select id=${s} class="wk-input" name=${e}>
${!t.selectedValue&&this.defaultText?n`<option disabled selected>${this.defaultText}</option>`:void 0}
${t.values.map(o=>n`
<option
value=${value}
?selected=${value === option.selectedValue}
value=${o}
?selected=${o===t.selectedValue}
>
${value}
${o}
</option>
`
)}
`)}
</select>
<div class="wk-content">
<div class="wk-text">${option.selectedValue || option.name}</div>
<div class="wk-text">${t.selectedValue||t.name}</div>
<wk-icon class="wk-icon" icon=${this.icon}></wk-icon>

@@ -45,36 +22,6 @@ </div>

</div>
`;
}
updated(_changedProperties) {
var _a;
super.updated(_changedProperties);
if (_changedProperties.has("option")) {
this.classList.toggle(
"wk-single-option",
((_a = this.option) == null ? void 0 : _a.values.length) === 1
);
}
}
createRenderRoot() {
return this;
}
};
OptionSelect.properties = {
icon: { type: String },
option: { type: Object },
defaultText: { type: String }
};
Icon.addIcons({
caret: `
`}updated(t){var e;super.updated(t),t.has("option")&&this.classList.toggle("wk-single-option",((e=this.option)==null?void 0:e.values.length)===1)}createRenderRoot(){return this}};i.properties={icon:{type:String},option:{type:Object},defaultText:{type:String}};a.addIcons({caret:`
<svg aria-hidden="true" focusable="false" role="presentation" viewBox="0 0 24 24">
<path d="M6 9l6 6 6-6" />
</svg>
`
});
if (!customElements.get("wk-option-select")) {
customElements.define("wk-option-select", OptionSelect);
}
export {
OptionSelect
};
//# sourceMappingURL=option-select.js.map
`});customElements.get("wk-option-select")||customElements.define("wk-option-select",i);export{i as OptionSelect};

@@ -1,98 +0,22 @@

// src/components/option-swatches.ts
import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
var OptionSwatches = class extends LitElement {
constructor() {
super();
}
get app() {
if (!window.WishlistKing) {
throw new Error("Wishlist King SDK not initialized");
}
return window.WishlistKing;
}
render() {
if (!this.option) {
return;
}
const name = `options[${this.option.name}]`;
const fieldsetId = `${this.id}-fieldset`;
return html`
import{LitElement as $,html as w}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";var s=class extends ${constructor(){super()}get app(){if(!window.WishlistKing)throw new Error("Wishlist King SDK not initialized");return window.WishlistKing}render(){if(!this.option)return;let t=`options[${this.option.name}]`,e=`${this.id}-fieldset`;return w`
<div class="wk-option-swatches">
<label class="wk-label" for=${fieldsetId}>${this.option.name}</label>
<fieldset id=${fieldsetId} class="wk-fieldset">
${this.option.values.map(
(value) => this.renderSwatch({ value, name })
)}
<label class="wk-label" for=${e}>${this.option.name}</label>
<fieldset id=${e} class="wk-fieldset">
${this.option.values.map(i=>this.renderSwatch({value:i,name:t}))}
</fieldset>
</div>
`;
}
renderSwatch({ value, name }) {
var _a, _b, _c, _d, _e;
const handle = this.app.utils.url.handlelize(value);
const inputId = `${this.app.utils.url.handlelize(this.id)}-${handle}-radio`;
const unavailable = (_b = (_a = this.option) == null ? void 0 : _a.unavailableValues) == null ? void 0 : _b.includes(value);
const soldout = (_d = (_c = this.option) == null ? void 0 : _c.soldoutValues) == null ? void 0 : _d.includes(value);
const selected = value === ((_e = this.option) == null ? void 0 : _e.selectedValue);
const { color, image } = this.getColorSettings(handle);
const styles = [
color ? `background-color: ${color}` : void 0,
image ? `background-image: url(${image})` : void 0
].filter((v) => !!v).join(";");
const classes = [
"wk-swatch",
soldout && "wk-soldout",
unavailable && "wk-unavailable",
selected && "wk-selected",
color && "wk-has-color",
image && "wk-has-image"
].filter((v) => !!v).join(" ");
return html`
<div class=${classes}>
<label class="wk-label" for=${inputId}>${value}</label>
<div class="wk-control" style=${styles}>
`}renderSwatch({value:t,name:e}){var d,c,p,u,h;let i=this.app.utils.url.handlelize(t),a=`${this.app.utils.url.handlelize(this.id)}-${i}-radio`,g=(c=(d=this.option)==null?void 0:d.unavailableValues)==null?void 0:c.includes(t),m=(u=(p=this.option)==null?void 0:p.soldoutValues)==null?void 0:u.includes(t),r=t===((h=this.option)==null?void 0:h.selectedValue),{color:o,image:n}=this.getColorSettings(i),f=[o?`background-color: ${o}`:void 0,n?`background-image: url(${n})`:void 0].filter(l=>!!l).join(";"),k=["wk-swatch",m&&"wk-soldout",g&&"wk-unavailable",r&&"wk-selected",o&&"wk-has-color",n&&"wk-has-image"].filter(l=>!!l).join(" ");return w`
<div class=${k}>
<label class="wk-label" for=${a}>${t}</label>
<div class="wk-control" style=${f}>
<input
id=${inputId}
id=${a}
class="wk-radio"
type="radio"
?checked=${selected}
value=${value}
name=${name}
?checked=${r}
value=${t}
name=${e}
/>
</div>
</div>
`;
}
getColorSettings(handle) {
if (!this.app.settings.colorMap[handle]) {
return {
color: void 0,
image: void 0
};
}
return this.app.settings.colorMap[handle];
}
updated(_changedProperties) {
var _a;
super.updated(_changedProperties);
if (_changedProperties.has("option")) {
this.classList.toggle(
"wk-single-option",
((_a = this.option) == null ? void 0 : _a.values.length) === 1
);
}
}
createRenderRoot() {
return this;
}
};
OptionSwatches.properties = {
option: { type: Object }
};
if (!customElements.get("wk-option-swatches")) {
customElements.define("wk-option-swatches", OptionSwatches);
}
export {
OptionSwatches
};
//# sourceMappingURL=option-swatches.js.map
`}getColorSettings(t){return this.app.settings.colorMap[t]?this.app.settings.colorMap[t]:{color:void 0,image:void 0}}updated(t){var e;super.updated(t),t.has("option")&&this.classList.toggle("wk-single-option",((e=this.option)==null?void 0:e.values.length)===1)}createRenderRoot(){return this}};s.properties={option:{type:Object}};customElements.get("wk-option-swatches")||customElements.define("wk-option-swatches",s);export{s as OptionSwatches};

@@ -1,109 +0,1 @@

// src/components/popover-util.ts
var showPopover = ({
text,
reference,
placement = "top",
arrow = true,
autoHide = true,
offset = 10
}) => {
const popover = document.createElement("wk-popover");
popover.text = text;
popover.autoHide = autoHide;
popover.floating = {
reference,
position: {
strategy: "fixed",
placement,
inset: false
},
arrow,
offset
};
popover.show();
return popover;
};
var notificationQueue = [];
var showNotification = ({
text,
placement = "bottom",
autoHide = true,
offset = 30
}) => {
if (notificationQueue.length > 2) {
return;
}
const popover = document.createElement("wk-popover");
popover.text = text;
popover.autoHide = autoHide;
popover.elementClass = "wk-notification";
popover.floating = {
reference: "viewport",
position: {
strategy: "fixed",
placement,
inset: true
},
offset
};
notificationQueue.push(popover);
popover.addEventListener("removed", () => {
notificationQueue.shift();
});
if (notificationQueue.length === 1) {
popover.show();
} else {
notificationQueue[notificationQueue.length - 2].addEventListener(
"removed",
() => requestAnimationFrame(() => {
var _a;
return (_a = notificationQueue[0]) == null ? void 0 : _a.show();
})
);
}
return popover;
};
var addTooltip = ({
text,
reference,
placement = "top",
arrow = true,
flip = true,
shift = true,
autoHide = false,
offset = 10
}) => {
const popover = document.createElement("wk-popover");
popover.text = text;
popover.autoHide = autoHide;
popover.elementClass = "wk-tooltip";
popover.floating = {
reference,
position: {
strategy: "fixed",
placement,
inset: false
},
arrow,
flip,
shift,
offset
};
const eventListener = [
["mouseenter", () => popover.show()],
["focus", () => popover.show()],
["mouseleave", () => popover.hide()],
["blur", () => popover.hide()],
["click", () => popover.hide()]
];
eventListener.forEach(([event, listener]) => {
reference.addEventListener(event, listener);
});
return popover;
};
export {
addTooltip,
showNotification,
showPopover
};
//# sourceMappingURL=popover-util.js.map
var f=({text:a,reference:r,placement:s="top",arrow:l=!0,autoHide:e=!0,offset:i=10})=>{let o=document.createElement("wk-popover");return o.text=a,o.autoHide=e,o.floating={reference:r,position:{strategy:"fixed",placement:s,inset:!1},arrow:l,offset:i},o.show(),o},n=[],d=({text:a,placement:r="bottom",autoHide:s=!0,offset:l=30})=>{if(n.length>2)return;let e=document.createElement("wk-popover");return e.text=a,e.autoHide=s,e.elementClass="wk-notification",e.floating={reference:"viewport",position:{strategy:"fixed",placement:r,inset:!0},offset:l},n.push(e),e.addEventListener("removed",()=>{n.shift()}),n.length===1?e.show():n[n.length-2].addEventListener("removed",()=>requestAnimationFrame(()=>{var i;return(i=n[0])==null?void 0:i.show()})),e},v=({text:a,reference:r,placement:s="top",arrow:l=!0,flip:e=!0,shift:i=!0,autoHide:o=!1,offset:p=10})=>{let t=document.createElement("wk-popover");return t.text=a,t.autoHide=o,t.elementClass="wk-tooltip",t.floating={reference:r,position:{strategy:"fixed",placement:s,inset:!1},arrow:l,flip:e,shift:i,offset:p},[["mouseenter",()=>t.show()],["focus",()=>t.show()],["mouseleave",()=>t.hide()],["blur",()=>t.hide()],["click",()=>t.hide()]].forEach(([c,m])=>{r.addEventListener(c,m)}),t};export{v as addTooltip,d as showNotification,f as showPopover};

@@ -1,135 +0,6 @@

// src/components/popover.ts
import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
import { FloatingUiController } from "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/controllers.js";
var Popover = class extends LitElement {
constructor() {
super(...arguments);
this.text = "";
this.autoShow = false;
this.autoHide = false;
this.floatingUi = new FloatingUiController(this);
}
get added() {
return !!this.parentElement;
}
get showing() {
return this.transition === "show";
}
get hiding() {
return this.transition === "hide";
}
render() {
var _a;
const classes = [
"wk-popover",
this.transition ? `wk-${this.transition}` : "",
this.elementClass
].filter((v) => !!v).join(" ");
return html`
<div class=${classes}>
import{LitElement as s,html as o}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";import{FloatingUiController as r}from"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/controllers.js";var n=class extends s{constructor(){super(...arguments);this.text="";this.autoShow=!1;this.autoHide=!1;this.floatingUi=new r(this)}get added(){return!!this.parentElement}get showing(){return this.transition==="show"}get hiding(){return this.transition==="hide"}render(){var e;let t=["wk-popover",this.transition?`wk-${this.transition}`:"",this.elementClass].filter(i=>!!i).join(" ");return o`
<div class=${t}>
<div class="wk-text">${this.getText()}</div>
${(_a = this.floatingUi) == null ? void 0 : _a.arrowEl}
${(e=this.floatingUi)==null?void 0:e.arrowEl}
</div>
`;
}
firstUpdated() {
if (this.autoShow !== false) {
this._autoShowTimer = setTimeout(
() => this.show(),
(this.autoShow === true ? 0 : this.autoShow) * 1e3
);
}
if (this.autoHide !== false) {
this._autoHideTimer = setTimeout(
() => this.hide(),
(this.autoHide === true ? 2 : this.autoHide) * 1e3
);
}
}
add(root = document.body) {
if (!this.added) {
root.appendChild(this);
}
}
show(callback) {
if (this.showing) {
return;
}
this.clearAllTimer();
if (!this.added) {
this.add();
}
requestAnimationFrame(() => {
this.transition = "show";
});
const onTransitionEnd = () => {
this.removeEventListener("transitionend", onTransitionEnd);
this.removeEventListener("transitioncancel", onTransitionCancel);
callback == null ? void 0 : callback();
};
const onTransitionCancel = () => {
this.removeEventListener("transitionend", onTransitionEnd);
this.removeEventListener("transitioncancel", onTransitionCancel);
};
this.addEventListener("transitionend", onTransitionEnd);
this.addEventListener("transitioncancel", onTransitionCancel);
}
hide() {
if (!this.showing) {
return;
}
this.clearAllTimer();
requestAnimationFrame(() => {
this.transition = "hide";
});
const onTransitionEnd = () => {
this.removeEventListener("transitionend", onTransitionEnd);
this.removeEventListener("transitioncancel", onTransitionCancel);
this.remove();
};
const onTransitionCancel = () => {
this.removeEventListener("transitionend", onTransitionEnd);
this.removeEventListener("transitioncancel", onTransitionCancel);
};
this.addEventListener("transitionend", onTransitionEnd);
this.addEventListener("transitioncancel", onTransitionCancel);
}
remove() {
if (this.parentElement) {
this.parentElement.removeChild(this);
}
this.transition = void 0;
this.dispatchEvent(new Event("removed"));
}
clearAllTimer() {
if (this._autoShowTimer) {
clearTimeout(this._autoShowTimer);
this._autoShowTimer = void 0;
}
if (this._autoHideTimer) {
clearTimeout(this._autoHideTimer);
this._autoHideTimer = void 0;
}
}
getText() {
if (typeof this.text === "function") {
return this.text();
}
return this.text;
}
createRenderRoot() {
return this;
}
};
Popover.properties = {
text: { attribute: false },
transition: { state: true },
floating: { type: Object }
};
if (!customElements.get("wk-popover")) {
customElements.define("wk-popover", Popover);
}
export {
Popover
};
//# sourceMappingURL=popover.js.map
`}firstUpdated(){this.autoShow!==!1&&(this._autoShowTimer=setTimeout(()=>this.show(),(this.autoShow===!0?0:this.autoShow)*1e3)),this.autoHide!==!1&&(this._autoHideTimer=setTimeout(()=>this.hide(),(this.autoHide===!0?2:this.autoHide)*1e3))}add(t=document.body){this.added||t.appendChild(this)}show(t){if(this.showing)return;this.clearAllTimer(),this.added||this.add(),requestAnimationFrame(()=>{this.transition="show"});let e=()=>{this.removeEventListener("transitionend",e),this.removeEventListener("transitioncancel",i),t==null||t()},i=()=>{this.removeEventListener("transitionend",e),this.removeEventListener("transitioncancel",i)};this.addEventListener("transitionend",e),this.addEventListener("transitioncancel",i)}hide(){if(!this.showing)return;this.clearAllTimer(),requestAnimationFrame(()=>{this.transition="hide"});let t=()=>{this.removeEventListener("transitionend",t),this.removeEventListener("transitioncancel",e),this.remove()},e=()=>{this.removeEventListener("transitionend",t),this.removeEventListener("transitioncancel",e)};this.addEventListener("transitionend",t),this.addEventListener("transitioncancel",e)}remove(){this.parentElement&&this.parentElement.removeChild(this),this.transition=void 0,this.dispatchEvent(new Event("removed"))}clearAllTimer(){this._autoShowTimer&&(clearTimeout(this._autoShowTimer),this._autoShowTimer=void 0),this._autoHideTimer&&(clearTimeout(this._autoHideTimer),this._autoHideTimer=void 0)}getText(){return typeof this.text=="function"?this.text():this.text}createRenderRoot(){return this}};n.properties={text:{attribute:!1},transition:{state:!0},floating:{type:Object}};customElements.get("wk-popover")||customElements.define("wk-popover",n);export{n as Popover};

@@ -1,978 +0,1 @@

// node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs
function t(t2) {
return t2.split("-")[1];
}
function e(t2) {
return "y" === t2 ? "height" : "width";
}
function n(t2) {
return t2.split("-")[0];
}
function o(t2) {
return ["top", "bottom"].includes(n(t2)) ? "x" : "y";
}
function i(i3, r3, a3) {
let { reference: l3, floating: s3 } = i3;
const c3 = l3.x + l3.width / 2 - s3.width / 2, f3 = l3.y + l3.height / 2 - s3.height / 2, m3 = o(r3), u3 = e(m3), g3 = l3[u3] / 2 - s3[u3] / 2, d3 = "x" === m3;
let p3;
switch (n(r3)) {
case "top":
p3 = { x: c3, y: l3.y - s3.height };
break;
case "bottom":
p3 = { x: c3, y: l3.y + l3.height };
break;
case "right":
p3 = { x: l3.x + l3.width, y: f3 };
break;
case "left":
p3 = { x: l3.x - s3.width, y: f3 };
break;
default:
p3 = { x: l3.x, y: l3.y };
}
switch (t(r3)) {
case "start":
p3[m3] -= g3 * (a3 && d3 ? -1 : 1);
break;
case "end":
p3[m3] += g3 * (a3 && d3 ? -1 : 1);
}
return p3;
}
var r = async (t2, e2, n3) => {
const { placement: o3 = "bottom", strategy: r3 = "absolute", middleware: a3 = [], platform: l3 } = n3, s3 = a3.filter(Boolean), c3 = await (null == l3.isRTL ? void 0 : l3.isRTL(e2));
let f3 = await l3.getElementRects({ reference: t2, floating: e2, strategy: r3 }), { x: m3, y: u3 } = i(f3, o3, c3), g3 = o3, d3 = {}, p3 = 0;
for (let n4 = 0; n4 < s3.length; n4++) {
const { name: a4, fn: h3 } = s3[n4], { x: y3, y: x3, data: w3, reset: v3 } = await h3({ x: m3, y: u3, initialPlacement: o3, placement: g3, strategy: r3, middlewareData: d3, rects: f3, platform: l3, elements: { reference: t2, floating: e2 } });
m3 = null != y3 ? y3 : m3, u3 = null != x3 ? x3 : u3, d3 = { ...d3, [a4]: { ...d3[a4], ...w3 } }, v3 && p3 <= 50 && (p3++, "object" == typeof v3 && (v3.placement && (g3 = v3.placement), v3.rects && (f3 = true === v3.rects ? await l3.getElementRects({ reference: t2, floating: e2, strategy: r3 }) : v3.rects), { x: m3, y: u3 } = i(f3, g3, c3)), n4 = -1);
}
return { x: m3, y: u3, placement: g3, strategy: r3, middlewareData: d3 };
};
function a(t2) {
return "number" != typeof t2 ? function(t3) {
return { top: 0, right: 0, bottom: 0, left: 0, ...t3 };
}(t2) : { top: t2, right: t2, bottom: t2, left: t2 };
}
function l(t2) {
return { ...t2, top: t2.y, left: t2.x, right: t2.x + t2.width, bottom: t2.y + t2.height };
}
async function s(t2, e2) {
var n3;
void 0 === e2 && (e2 = {});
const { x: o3, y: i3, platform: r3, rects: s3, elements: c3, strategy: f3 } = t2, { boundary: m3 = "clippingAncestors", rootBoundary: u3 = "viewport", elementContext: g3 = "floating", altBoundary: d3 = false, padding: p3 = 0 } = e2, h3 = a(p3), y3 = c3[d3 ? "floating" === g3 ? "reference" : "floating" : g3], x3 = l(await r3.getClippingRect({ element: null == (n3 = await (null == r3.isElement ? void 0 : r3.isElement(y3))) || n3 ? y3 : y3.contextElement || await (null == r3.getDocumentElement ? void 0 : r3.getDocumentElement(c3.floating)), boundary: m3, rootBoundary: u3, strategy: f3 })), w3 = "floating" === g3 ? { ...s3.floating, x: o3, y: i3 } : s3.reference, v3 = await (null == r3.getOffsetParent ? void 0 : r3.getOffsetParent(c3.floating)), b3 = await (null == r3.isElement ? void 0 : r3.isElement(v3)) && await (null == r3.getScale ? void 0 : r3.getScale(v3)) || { x: 1, y: 1 }, A2 = l(r3.convertOffsetParentRelativeRectToViewportRelativeRect ? await r3.convertOffsetParentRelativeRectToViewportRelativeRect({ rect: w3, offsetParent: v3, strategy: f3 }) : w3);
return { top: (x3.top - A2.top + h3.top) / b3.y, bottom: (A2.bottom - x3.bottom + h3.bottom) / b3.y, left: (x3.left - A2.left + h3.left) / b3.x, right: (A2.right - x3.right + h3.right) / b3.x };
}
var c = Math.min;
var f = Math.max;
function m(t2, e2, n3) {
return f(t2, c(e2, n3));
}
var u = (n3) => ({ name: "arrow", options: n3, async fn(i3) {
const { element: r3, padding: l3 = 0 } = n3 || {}, { x: s3, y: c3, placement: f3, rects: u3, platform: g3, elements: d3 } = i3;
if (null == r3)
return {};
const p3 = a(l3), h3 = { x: s3, y: c3 }, y3 = o(f3), x3 = e(y3), w3 = await g3.getDimensions(r3), v3 = "y" === y3, b3 = v3 ? "top" : "left", A2 = v3 ? "bottom" : "right", R2 = v3 ? "clientHeight" : "clientWidth", P3 = u3.reference[x3] + u3.reference[y3] - h3[y3] - u3.floating[x3], E2 = h3[y3] - u3.reference[y3], T3 = await (null == g3.getOffsetParent ? void 0 : g3.getOffsetParent(r3));
let D3 = T3 ? T3[R2] : 0;
D3 && await (null == g3.isElement ? void 0 : g3.isElement(T3)) || (D3 = d3.floating[R2] || u3.floating[x3]);
const L3 = P3 / 2 - E2 / 2, k2 = p3[b3], O3 = D3 - w3[x3] - p3[A2], B2 = D3 / 2 - w3[x3] / 2 + L3, C2 = m(k2, B2, O3), H2 = null != t(f3) && B2 != C2 && u3.reference[x3] / 2 - (B2 < k2 ? p3[b3] : p3[A2]) - w3[x3] / 2 < 0;
return { [y3]: h3[y3] - (H2 ? B2 < k2 ? k2 - B2 : O3 - B2 : 0), data: { [y3]: C2, centerOffset: B2 - C2 } };
} });
var g = ["top", "right", "bottom", "left"];
var d = g.reduce((t2, e2) => t2.concat(e2, e2 + "-start", e2 + "-end"), []);
var p = { left: "right", right: "left", bottom: "top", top: "bottom" };
function h(t2) {
return t2.replace(/left|right|bottom|top/g, (t3) => p[t3]);
}
function y(n3, i3, r3) {
void 0 === r3 && (r3 = false);
const a3 = t(n3), l3 = o(n3), s3 = e(l3);
let c3 = "x" === l3 ? a3 === (r3 ? "end" : "start") ? "right" : "left" : "start" === a3 ? "bottom" : "top";
return i3.reference[s3] > i3.floating[s3] && (c3 = h(c3)), { main: c3, cross: h(c3) };
}
var x = { start: "end", end: "start" };
function w(t2) {
return t2.replace(/start|end/g, (t3) => x[t3]);
}
var b = function(e2) {
return void 0 === e2 && (e2 = {}), { name: "flip", options: e2, async fn(o3) {
var i3;
const { placement: r3, middlewareData: a3, rects: l3, initialPlacement: c3, platform: f3, elements: m3 } = o3, { mainAxis: u3 = true, crossAxis: g3 = true, fallbackPlacements: d3, fallbackStrategy: p3 = "bestFit", fallbackAxisSideDirection: x3 = "none", flipAlignment: v3 = true, ...b3 } = e2, A2 = n(r3), R2 = n(c3) === c3, P3 = await (null == f3.isRTL ? void 0 : f3.isRTL(m3.floating)), E2 = d3 || (R2 || !v3 ? [h(c3)] : function(t2) {
const e3 = h(t2);
return [w(t2), e3, w(e3)];
}(c3));
d3 || "none" === x3 || E2.push(...function(e3, o4, i4, r4) {
const a4 = t(e3);
let l4 = function(t2, e4, n3) {
const o5 = ["left", "right"], i5 = ["right", "left"], r5 = ["top", "bottom"], a5 = ["bottom", "top"];
switch (t2) {
case "top":
case "bottom":
return n3 ? e4 ? i5 : o5 : e4 ? o5 : i5;
case "left":
case "right":
return e4 ? r5 : a5;
default:
return [];
}
}(n(e3), "start" === i4, r4);
return a4 && (l4 = l4.map((t2) => t2 + "-" + a4), o4 && (l4 = l4.concat(l4.map(w)))), l4;
}(c3, v3, x3, P3));
const T3 = [c3, ...E2], D3 = await s(o3, b3), L3 = [];
let k2 = (null == (i3 = a3.flip) ? void 0 : i3.overflows) || [];
if (u3 && L3.push(D3[A2]), g3) {
const { main: t2, cross: e3 } = y(r3, l3, P3);
L3.push(D3[t2], D3[e3]);
}
if (k2 = [...k2, { placement: r3, overflows: L3 }], !L3.every((t2) => t2 <= 0)) {
var O3, B2;
const t2 = ((null == (O3 = a3.flip) ? void 0 : O3.index) || 0) + 1, e3 = T3[t2];
if (e3)
return { data: { index: t2, overflows: k2 }, reset: { placement: e3 } };
let n3 = null == (B2 = k2.filter((t3) => t3.overflows[0] <= 0).sort((t3, e4) => t3.overflows[1] - e4.overflows[1])[0]) ? void 0 : B2.placement;
if (!n3)
switch (p3) {
case "bestFit": {
var C2;
const t3 = null == (C2 = k2.map((t4) => [t4.placement, t4.overflows.filter((t5) => t5 > 0).reduce((t5, e4) => t5 + e4, 0)]).sort((t4, e4) => t4[1] - e4[1])[0]) ? void 0 : C2[0];
t3 && (n3 = t3);
break;
}
case "initialPlacement":
n3 = c3;
}
if (r3 !== n3)
return { reset: { placement: n3 } };
}
return {};
} };
};
var D = function(e2) {
return void 0 === e2 && (e2 = 0), { name: "offset", options: e2, async fn(i3) {
const { x: r3, y: a3 } = i3, l3 = await async function(e3, i4) {
const { placement: r4, platform: a4, elements: l4 } = e3, s3 = await (null == a4.isRTL ? void 0 : a4.isRTL(l4.floating)), c3 = n(r4), f3 = t(r4), m3 = "x" === o(r4), u3 = ["left", "top"].includes(c3) ? -1 : 1, g3 = s3 && m3 ? -1 : 1, d3 = "function" == typeof i4 ? i4(e3) : i4;
let { mainAxis: p3, crossAxis: h3, alignmentAxis: y3 } = "number" == typeof d3 ? { mainAxis: d3, crossAxis: 0, alignmentAxis: null } : { mainAxis: 0, crossAxis: 0, alignmentAxis: null, ...d3 };
return f3 && "number" == typeof y3 && (h3 = "end" === f3 ? -1 * y3 : y3), m3 ? { x: h3 * g3, y: p3 * u3 } : { x: p3 * u3, y: h3 * g3 };
}(i3, e2);
return { x: r3 + l3.x, y: a3 + l3.y, data: l3 };
} };
};
function L(t2) {
return "x" === t2 ? "y" : "x";
}
var k = function(t2) {
return void 0 === t2 && (t2 = {}), { name: "shift", options: t2, async fn(e2) {
const { x: i3, y: r3, placement: a3 } = e2, { mainAxis: l3 = true, crossAxis: c3 = false, limiter: f3 = { fn: (t3) => {
let { x: e3, y: n3 } = t3;
return { x: e3, y: n3 };
} }, ...u3 } = t2, g3 = { x: i3, y: r3 }, d3 = await s(e2, u3), p3 = o(n(a3)), h3 = L(p3);
let y3 = g3[p3], x3 = g3[h3];
if (l3) {
const t3 = "y" === p3 ? "bottom" : "right";
y3 = m(y3 + d3["y" === p3 ? "top" : "left"], y3, y3 - d3[t3]);
}
if (c3) {
const t3 = "y" === h3 ? "bottom" : "right";
x3 = m(x3 + d3["y" === h3 ? "top" : "left"], x3, x3 - d3[t3]);
}
const w3 = f3.fn({ ...e2, [p3]: y3, [h3]: x3 });
return { ...w3, data: { x: w3.x - i3, y: w3.y - r3 } };
} };
};
// node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs
function n2(t2) {
var e2;
return (null == (e2 = t2.ownerDocument) ? void 0 : e2.defaultView) || window;
}
function o2(t2) {
return n2(t2).getComputedStyle(t2);
}
function i2(t2) {
return t2 instanceof n2(t2).Node;
}
function r2(t2) {
return i2(t2) ? (t2.nodeName || "").toLowerCase() : "";
}
var l2;
function c2() {
if (l2)
return l2;
const t2 = navigator.userAgentData;
return t2 && Array.isArray(t2.brands) ? (l2 = t2.brands.map((t3) => t3.brand + "/" + t3.version).join(" "), l2) : navigator.userAgent;
}
function s2(t2) {
return t2 instanceof n2(t2).HTMLElement;
}
function f2(t2) {
return t2 instanceof n2(t2).Element;
}
function u2(t2) {
if ("undefined" == typeof ShadowRoot)
return false;
return t2 instanceof n2(t2).ShadowRoot || t2 instanceof ShadowRoot;
}
function a2(t2) {
const { overflow: e2, overflowX: n3, overflowY: i3, display: r3 } = o2(t2);
return /auto|scroll|overlay|hidden|clip/.test(e2 + i3 + n3) && !["inline", "contents"].includes(r3);
}
function d2(t2) {
return ["table", "td", "th"].includes(r2(t2));
}
function h2(t2) {
const e2 = /firefox/i.test(c2()), n3 = o2(t2), i3 = n3.backdropFilter || n3.WebkitBackdropFilter;
return "none" !== n3.transform || "none" !== n3.perspective || !!i3 && "none" !== i3 || e2 && "filter" === n3.willChange || e2 && !!n3.filter && "none" !== n3.filter || ["transform", "perspective"].some((t3) => n3.willChange.includes(t3)) || ["paint", "layout", "strict", "content"].some((t3) => {
const e3 = n3.contain;
return null != e3 && e3.includes(t3);
});
}
function p2() {
return /^((?!chrome|android).)*safari/i.test(c2());
}
function g2(t2) {
return ["html", "body", "#document"].includes(r2(t2));
}
var m2 = Math.min;
var y2 = Math.max;
var x2 = Math.round;
function w2(t2) {
const e2 = o2(t2);
let n3 = parseFloat(e2.width), i3 = parseFloat(e2.height);
const r3 = s2(t2), l3 = r3 ? t2.offsetWidth : n3, c3 = r3 ? t2.offsetHeight : i3, f3 = x2(n3) !== l3 || x2(i3) !== c3;
return f3 && (n3 = l3, i3 = c3), { width: n3, height: i3, fallback: f3 };
}
function v2(t2) {
return f2(t2) ? t2 : t2.contextElement;
}
var b2 = { x: 1, y: 1 };
function L2(t2) {
const e2 = v2(t2);
if (!s2(e2))
return b2;
const n3 = e2.getBoundingClientRect(), { width: o3, height: i3, fallback: r3 } = w2(e2);
let l3 = (r3 ? x2(n3.width) : n3.width) / o3, c3 = (r3 ? x2(n3.height) : n3.height) / i3;
return l3 && Number.isFinite(l3) || (l3 = 1), c3 && Number.isFinite(c3) || (c3 = 1), { x: l3, y: c3 };
}
function E(e2, o3, i3, r3) {
var l3, c3;
void 0 === o3 && (o3 = false), void 0 === i3 && (i3 = false);
const s3 = e2.getBoundingClientRect(), u3 = v2(e2);
let a3 = b2;
o3 && (r3 ? f2(r3) && (a3 = L2(r3)) : a3 = L2(e2));
const d3 = u3 ? n2(u3) : window, h3 = p2() && i3;
let g3 = (s3.left + (h3 && (null == (l3 = d3.visualViewport) ? void 0 : l3.offsetLeft) || 0)) / a3.x, m3 = (s3.top + (h3 && (null == (c3 = d3.visualViewport) ? void 0 : c3.offsetTop) || 0)) / a3.y, y3 = s3.width / a3.x, x3 = s3.height / a3.y;
if (u3) {
const t2 = n2(u3), e3 = r3 && f2(r3) ? n2(r3) : r3;
let o4 = t2.frameElement;
for (; o4 && r3 && e3 !== t2; ) {
const t3 = L2(o4), e4 = o4.getBoundingClientRect(), i4 = getComputedStyle(o4);
e4.x += (o4.clientLeft + parseFloat(i4.paddingLeft)) * t3.x, e4.y += (o4.clientTop + parseFloat(i4.paddingTop)) * t3.y, g3 *= t3.x, m3 *= t3.y, y3 *= t3.x, x3 *= t3.y, g3 += e4.x, m3 += e4.y, o4 = n2(o4).frameElement;
}
}
return l({ width: y3, height: x3, x: g3, y: m3 });
}
function T2(t2) {
return ((i2(t2) ? t2.ownerDocument : t2.document) || window.document).documentElement;
}
function R(t2) {
return f2(t2) ? { scrollLeft: t2.scrollLeft, scrollTop: t2.scrollTop } : { scrollLeft: t2.pageXOffset, scrollTop: t2.pageYOffset };
}
function C(t2) {
return E(T2(t2)).left + R(t2).scrollLeft;
}
function F(t2) {
if ("html" === r2(t2))
return t2;
const e2 = t2.assignedSlot || t2.parentNode || u2(t2) && t2.host || T2(t2);
return u2(e2) ? e2.host : e2;
}
function W(t2) {
const e2 = F(t2);
return g2(e2) ? e2.ownerDocument.body : s2(e2) && a2(e2) ? e2 : W(e2);
}
function D2(t2, e2) {
var o3;
void 0 === e2 && (e2 = []);
const i3 = W(t2), r3 = i3 === (null == (o3 = t2.ownerDocument) ? void 0 : o3.body), l3 = n2(i3);
return r3 ? e2.concat(l3, l3.visualViewport || [], a2(i3) ? i3 : []) : e2.concat(i3, D2(i3));
}
function S(e2, i3, r3) {
let l3;
if ("viewport" === i3)
l3 = function(t2, e3) {
const o3 = n2(t2), i4 = T2(t2), r4 = o3.visualViewport;
let l4 = i4.clientWidth, c4 = i4.clientHeight, s3 = 0, f3 = 0;
if (r4) {
l4 = r4.width, c4 = r4.height;
const t3 = p2();
(!t3 || t3 && "fixed" === e3) && (s3 = r4.offsetLeft, f3 = r4.offsetTop);
}
return { width: l4, height: c4, x: s3, y: f3 };
}(e2, r3);
else if ("document" === i3)
l3 = function(t2) {
const e3 = T2(t2), n3 = R(t2), i4 = t2.ownerDocument.body, r4 = y2(e3.scrollWidth, e3.clientWidth, i4.scrollWidth, i4.clientWidth), l4 = y2(e3.scrollHeight, e3.clientHeight, i4.scrollHeight, i4.clientHeight);
let c4 = -n3.scrollLeft + C(t2);
const s3 = -n3.scrollTop;
return "rtl" === o2(i4).direction && (c4 += y2(e3.clientWidth, i4.clientWidth) - r4), { width: r4, height: l4, x: c4, y: s3 };
}(T2(e2));
else if (f2(i3))
l3 = function(t2, e3) {
const n3 = E(t2, true, "fixed" === e3), o3 = n3.top + t2.clientTop, i4 = n3.left + t2.clientLeft, r4 = s2(t2) ? L2(t2) : { x: 1, y: 1 };
return { width: t2.clientWidth * r4.x, height: t2.clientHeight * r4.y, x: i4 * r4.x, y: o3 * r4.y };
}(i3, r3);
else {
const t2 = { ...i3 };
if (p2()) {
var c3, u3;
const o3 = n2(e2);
t2.x -= (null == (c3 = o3.visualViewport) ? void 0 : c3.offsetLeft) || 0, t2.y -= (null == (u3 = o3.visualViewport) ? void 0 : u3.offsetTop) || 0;
}
l3 = t2;
}
return l(l3);
}
function A(t2, e2) {
return s2(t2) && "fixed" !== o2(t2).position ? e2 ? e2(t2) : t2.offsetParent : null;
}
function H(t2, e2) {
const i3 = n2(t2);
if (!s2(t2))
return i3;
let l3 = A(t2, e2);
for (; l3 && d2(l3) && "static" === o2(l3).position; )
l3 = A(l3, e2);
return l3 && ("html" === r2(l3) || "body" === r2(l3) && "static" === o2(l3).position && !h2(l3)) ? i3 : l3 || function(t3) {
let e3 = F(t3);
for (; s2(e3) && !g2(e3); ) {
if (h2(e3))
return e3;
e3 = F(e3);
}
return null;
}(t2) || i3;
}
function V(t2, e2, n3) {
const o3 = s2(e2), i3 = T2(e2), l3 = E(t2, true, "fixed" === n3, e2);
let c3 = { scrollLeft: 0, scrollTop: 0 };
const f3 = { x: 0, y: 0 };
if (o3 || !o3 && "fixed" !== n3)
if (("body" !== r2(e2) || a2(i3)) && (c3 = R(e2)), s2(e2)) {
const t3 = E(e2, true);
f3.x = t3.x + e2.clientLeft, f3.y = t3.y + e2.clientTop;
} else
i3 && (f3.x = C(i3));
return { x: l3.left + c3.scrollLeft - f3.x, y: l3.top + c3.scrollTop - f3.y, width: l3.width, height: l3.height };
}
var O2 = { getClippingRect: function(t2) {
let { element: e2, boundary: n3, rootBoundary: i3, strategy: l3 } = t2;
const c3 = "clippingAncestors" === n3 ? function(t3, e3) {
const n4 = e3.get(t3);
if (n4)
return n4;
let i4 = D2(t3).filter((t4) => f2(t4) && "body" !== r2(t4)), l4 = null;
const c4 = "fixed" === o2(t3).position;
let s4 = c4 ? F(t3) : t3;
for (; f2(s4) && !g2(s4); ) {
const t4 = o2(s4), e4 = h2(s4);
"fixed" === t4.position && (l4 = null), (c4 ? e4 || l4 : e4 || "static" !== t4.position || !l4 || !["absolute", "fixed"].includes(l4.position)) ? l4 = t4 : i4 = i4.filter((t5) => t5 !== s4), s4 = F(s4);
}
return e3.set(t3, i4), i4;
}(e2, this._c) : [].concat(n3), s3 = [...c3, i3], u3 = s3[0], a3 = s3.reduce((t3, n4) => {
const o3 = S(e2, n4, l3);
return t3.top = y2(o3.top, t3.top), t3.right = m2(o3.right, t3.right), t3.bottom = m2(o3.bottom, t3.bottom), t3.left = y2(o3.left, t3.left), t3;
}, S(e2, u3, l3));
return { width: a3.right - a3.left, height: a3.bottom - a3.top, x: a3.left, y: a3.top };
}, convertOffsetParentRelativeRectToViewportRelativeRect: function(t2) {
let { rect: e2, offsetParent: n3, strategy: o3 } = t2;
const i3 = s2(n3), l3 = T2(n3);
if (n3 === l3)
return e2;
let c3 = { scrollLeft: 0, scrollTop: 0 }, f3 = { x: 1, y: 1 };
const u3 = { x: 0, y: 0 };
if ((i3 || !i3 && "fixed" !== o3) && (("body" !== r2(n3) || a2(l3)) && (c3 = R(n3)), s2(n3))) {
const t3 = E(n3);
f3 = L2(n3), u3.x = t3.x + n3.clientLeft, u3.y = t3.y + n3.clientTop;
}
return { width: e2.width * f3.x, height: e2.height * f3.y, x: e2.x * f3.x - c3.scrollLeft * f3.x + u3.x, y: e2.y * f3.y - c3.scrollTop * f3.y + u3.y };
}, isElement: f2, getDimensions: function(t2) {
return w2(t2);
}, getOffsetParent: H, getDocumentElement: T2, getScale: L2, async getElementRects(t2) {
let { reference: e2, floating: n3, strategy: o3 } = t2;
const i3 = this.getOffsetParent || H, r3 = this.getDimensions;
return { reference: V(e2, await i3(n3), o3), floating: { x: 0, y: 0, ...await r3(n3) } };
}, getClientRects: (t2) => Array.from(t2.getClientRects()), isRTL: (t2) => "rtl" === o2(t2).direction };
function P2(t2, e2, n3, o3) {
void 0 === o3 && (o3 = {});
const { ancestorScroll: i3 = true, ancestorResize: r3 = true, elementResize: l3 = true, animationFrame: c3 = false } = o3, s3 = i3 && !c3, u3 = s3 || r3 ? [...f2(t2) ? D2(t2) : t2.contextElement ? D2(t2.contextElement) : [], ...D2(e2)] : [];
u3.forEach((t3) => {
s3 && t3.addEventListener("scroll", n3, { passive: true }), r3 && t3.addEventListener("resize", n3);
});
let a3, d3 = null;
l3 && (d3 = new ResizeObserver(() => {
n3();
}), f2(t2) && !c3 && d3.observe(t2), f2(t2) || !t2.contextElement || c3 || d3.observe(t2.contextElement), d3.observe(e2));
let h3 = c3 ? E(t2) : null;
return c3 && function e3() {
const o4 = E(t2);
!h3 || o4.x === h3.x && o4.y === h3.y && o4.width === h3.width && o4.height === h3.height || n3();
h3 = o4, a3 = requestAnimationFrame(e3);
}(), n3(), () => {
var t3;
u3.forEach((t4) => {
s3 && t4.removeEventListener("scroll", n3), r3 && t4.removeEventListener("resize", n3);
}), null == (t3 = d3) || t3.disconnect(), d3 = null, c3 && cancelAnimationFrame(a3);
};
}
var z = (t2, n3, o3) => {
const i3 = /* @__PURE__ */ new Map(), r3 = { platform: O2, ...o3 }, l3 = { ...r3.platform, _c: i3 };
return r(t2, n3, { ...r3, platform: l3 });
};
// src/controllers/FloatingUiController.ts
var FloatingUiController = class {
constructor(host) {
this._middleware = [];
this._floating = false;
(this.host = host).addController(this);
}
hostConnected() {
if (this.host.floating) {
this.float(this.host.floating);
}
}
hostDisconnected() {
this.destroy();
}
hostUpdated() {
if (this.host.floating && !this._floating) {
this.float(this.host.floating);
}
if (this._floating) {
this.updatePosition();
}
}
hostResized() {
if (this._floating) {
this.updatePosition();
}
}
float(settings) {
var _a;
if (this._floating) {
return;
}
this._floating = true;
this._settings = settings;
this._reference = this.getReference();
this._resizeObserver = new ResizeObserver(() => this.hostResized());
if (!this._settings) {
throw new Error("Floating settings are required");
}
if (!this._reference) {
throw new Error("Floating reference is required");
}
this.host.classList.add("wk-floating");
const {
position,
arrow: arrowSetting = false,
flip: flipSetting = false,
shift: shiftSetting = false
} = this._settings;
const offsetSetting = this.getOffsetSetting();
Object.assign(this.host.style, {
position: (_a = position.strategy) != null ? _a : "absolute",
top: "0",
left: "0",
transition: "none",
transform: "translate3d(0,0,0)"
});
if (position.inset && !arrowSetting) {
this._middleware.push(
D(({ rects, placement }) => {
var _a2, _b, _c, _d, _e, _f;
if (placement.includes("top") || placement.includes("bottom")) {
return {
mainAxis: -rects.floating.height - ((_a2 = offsetSetting == null ? void 0 : offsetSetting.mainAxis) != null ? _a2 : 0),
crossAxis: (_b = offsetSetting == null ? void 0 : offsetSetting.crossAxis) != null ? _b : 0,
alignmentAxis: (_c = offsetSetting == null ? void 0 : offsetSetting.alignmentAxis) != null ? _c : 0
};
} else {
return {
mainAxis: -rects.floating.width - ((_d = offsetSetting == null ? void 0 : offsetSetting.mainAxis) != null ? _d : 0),
crossAxis: (_e = offsetSetting == null ? void 0 : offsetSetting.crossAxis) != null ? _e : 0,
alignmentAxis: (_f = offsetSetting == null ? void 0 : offsetSetting.alignmentAxis) != null ? _f : 0
};
}
})
);
} else if (offsetSetting) {
this._middleware.push(D(offsetSetting));
}
if (flipSetting) {
this._middleware.push(b());
}
if (shiftSetting) {
this._middleware.push(k());
}
if (arrowSetting) {
this.arrowEl = document.createElement("div");
this.arrowEl.classList.add("wk-arrow");
this._middleware.push(u({ element: this.arrowEl }));
}
this.cleanupAutoUpdate = P2(this._reference, this.host, () => {
this.updatePosition();
});
this._resizeObserver.observe(this.host);
}
getOffsetSetting() {
var _a, _b;
const offset = (_a = this._settings) == null ? void 0 : _a.offset;
if (!offset || typeof offset === "boolean") {
return void 0;
}
if (typeof offset === "number") {
return {
mainAxis: offset,
alignmentAxis: ((_b = this._settings) == null ? void 0 : _b.position.inset) ? offset : null
};
}
return offset;
}
destroy() {
var _a, _b, _c, _d;
if (this._floating) {
Object.assign(this.host.style, {
position: "",
top: "",
left: "",
transition: "",
transform: ""
});
(_b = (_a = this.arrowEl) == null ? void 0 : _a.parentElement) == null ? void 0 : _b.removeChild(this.arrowEl);
this.arrowEl = void 0;
this._middleware = [];
this.host.classList.remove("wk-floating");
(_c = this.cleanupAutoUpdate) == null ? void 0 : _c.call(this);
(_d = this._resizeObserver) == null ? void 0 : _d.disconnect();
this._floating = false;
}
}
updatePosition() {
var _a;
if (!this._reference || !this._settings) {
return;
}
const { strategy = "absolute", placement = "top" } = (_a = this._settings.position) != null ? _a : {};
z(this._reference, this.host, {
middleware: this._middleware,
strategy,
placement
}).then(({ x: x3, y: y3, placement: placement2, middlewareData }) => {
if (middlewareData.arrow && this.arrowEl) {
const { x: arrowX, y: arrowY } = middlewareData.arrow;
const staticSide = {
top: "bottom",
right: "left",
bottom: "top",
left: "right"
}[placement2.split("-")[0]];
const arrowRotation = {
bottom: "0deg",
left: "90deg",
top: "180deg",
right: "270deg"
}[placement2.split("-")[0]];
Object.assign(this.arrowEl.style, {
left: arrowX != null ? `${arrowX}px` : "",
top: arrowY != null ? `${arrowY}px` : "",
right: "",
bottom: "",
[staticSide]: "-5px",
transform: `rotate(${arrowRotation})`
});
}
Object.assign(this.host.style, {
transform: `translate3d(${Math.round(x3)}px,${Math.round(y3)}px,0)`
});
});
}
getReference() {
if (!this._settings) {
return;
}
const reference = this._settings.reference;
if (typeof reference === "string") {
if (reference === "viewport") {
return this.createViewportReference();
}
const queryElement = document.querySelector(reference);
if (!queryElement) {
throw new Error(`Floating reference element (${reference}) not found`);
}
return queryElement;
}
if (reference.hasOwnProperty("element")) {
return reference.element;
}
return reference;
}
createViewportReference() {
return {
getBoundingClientRect() {
var _a, _b, _c, _d;
return {
x: 0,
y: 0,
top: 0,
left: 0,
bottom: 0,
right: 0,
width: (_b = (_a = window.visualViewport) == null ? void 0 : _a.width) != null ? _b : 0,
height: (_d = (_c = window.visualViewport) == null ? void 0 : _c.height) != null ? _d : 0
};
}
};
}
};
// src/controllers/ProductFormController.ts
var ProductFormController = class {
constructor(host) {
this.product = null;
this.selectedVariant = null;
this.selectedOptions = {};
this.hasSelection = false;
this.optionsWithValues = [];
this.hasOnlyDefaultVariant = false;
(this.host = host).addController(this);
}
set submitting(value) {
var _a;
(_a = this.host.querySelector("form")) == null ? void 0 : _a.classList.toggle("wk-submitting", value);
}
get submitting() {
var _a, _b;
return (_b = (_a = this.host.querySelector("form")) == null ? void 0 : _a.classList.contains("wk-submitting")) != null ? _b : false;
}
setProduct({
product,
selectedVariantId,
autoSelect = false
}) {
if (!(product == null ? void 0 : product.variants)) {
return;
}
this.product = product;
this.initFormState({
selectedVariantId,
autoSelect
});
}
initFormState({
selectedVariantId,
autoSelect
}) {
if (!this.product) {
throw new Error("Product not set");
}
const variant = this.initializedVariantId !== selectedVariantId ? this.product.variants.find(
(variant2) => variant2.id === selectedVariantId
) : this.selectedVariant;
this.initializedVariantId = selectedVariantId;
const options = this.host.app.utils.product.getVariantOptions({
variant
});
this.updateFormState({
options,
autoSelect
});
}
updateFormState({
options,
change,
autoSelect = false
}) {
if (!this.product) {
throw new Error("Product not set");
}
const {
hasSelection,
optionsWithValues,
selectedOptions,
selectedVariant,
hasOnlyDefaultVariant
} = this.host.app.utils.product.getFormState({
product: this.product,
options,
change,
autoSelect
});
this.hasSelection = hasSelection;
this.optionsWithValues = optionsWithValues;
this.selectedOptions = selectedOptions;
this.selectedVariant = selectedVariant;
this.hasOnlyDefaultVariant = hasOnlyDefaultVariant;
this.host.requestUpdate();
}
changeOption({
input,
autoSelect = false
}) {
if (!this.product) {
throw new Error("Product not set");
}
const change = this.getInputOption(input);
if (!change) {
throw new Error("Cannot parse options from input");
}
this.updateFormState({
options: this.selectedOptions,
change,
autoSelect
});
}
addToCart({
wishlistId,
wishlistItemId,
sectionsToRender,
sectionsUrl = "/"
}) {
if (!this.selectedVariant) {
throw new Error("No variant selected");
}
const formElement = this.host.querySelector("form");
if (!formElement) {
throw new Error("Form not found");
}
this.submitting = true;
return this.host.app.addToCart({
wishlistId,
wishlistItemId,
variantId: this.selectedVariant.id,
quantity: this.host.app.utils.product.getFormQuantity({
form: formElement
}),
sectionsToRender,
sectionsUrl
}).finally(() => {
this.submitting = false;
});
}
getInputOption(element) {
if (!this.product) {
throw new Error("Product not set");
}
return this.host.app.utils.product.getInputOption({
input: element,
product: this.product
});
}
hostConnected() {
}
hostDisconnected() {
}
hostUpdate() {
}
hostUpdated() {
}
};
// src/controllers/WishlistStateController.ts
import { combineLatest, distinctUntilChanged, map, of } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
var WishlistStateController = class {
constructor(host) {
this.stateConfig = { loading: "eager" };
(this.host = host).addController(this);
}
get app() {
if (!window.WishlistKing) {
throw new Error("Wishlist King SDK not initialized");
}
return window.WishlistKing;
}
get hostDataset() {
if (this.host.dataset) {
return this.host.dataset;
}
if (this.host.host) {
return this.host.host.dataset;
}
return {};
}
hostConnected() {
}
hostDisconnected() {
}
parseStateConfig(config) {
var _a;
return {
loading: (_a = config.loading) != null ? _a : "eager",
wishlist: this.parseWishlistStateConfig(config),
wishlistItem: this.parseWishlistItemStateConfig(config),
productInfo: this.parseProductInfoStateConfig(config)
};
}
parseWishlistStateConfig({
wishlist
}) {
var _a;
const wishlistId = (_a = this.hostDataset.wishlistId) != null ? _a : "mine";
if (!wishlist) {
return;
}
return {
params: {
wishlistId
}
};
}
parseWishlistItemStateConfig({
wishlistItem
}) {
const { wishlistId = "mine", wishlistItemId } = this.hostDataset;
if (!wishlistItem || !wishlistItemId) {
return;
}
return {
params: {
wishlistId,
wishlistItemId
}
};
}
parseProductInfoStateConfig({
productInfo
}) {
if (!productInfo) {
return;
}
const {
wishlistId = "mine",
productHandle = "",
productId,
variantId
} = this.hostDataset;
return {
params: {
wishlistId,
productHandle,
variantId: variantId ? parseInt(variantId) : void 0
}
};
}
observe() {
this.stateConfig = this.parseStateConfig(this.host.getStateConfig());
const observables = [];
if (this.stateConfig.wishlist) {
const { wishlistId = "mine" } = this.stateConfig.wishlist.params;
observables.push(
this.app.state.observeWishlist({
wishlistId
}).pipe(map((wishlist) => ({ wishlist })))
);
}
if (this.stateConfig.productInfo) {
const { productHandle, variantId } = this.stateConfig.productInfo.params;
if (!productHandle) {
throw new Error("Product handle is required");
}
observables.push(
this.app.state.observeProductInfo({
productHandle,
variantId
}).pipe(map((productInfo) => ({ productInfo })))
);
}
if (this.stateConfig.wishlistItem) {
const { wishlistId, wishlistItemId } = this.stateConfig.wishlistItem.params;
if (!wishlistId) {
throw new Error("Wishlist id is required");
}
if (!wishlistItemId) {
throw new Error("Wishlist item id is required");
}
observables.push(
this.app.state.observeWishlistItem({
wishlistId,
wishlistItemId
}).pipe(map((wishlistItem) => ({ wishlistItem })))
);
}
if (!observables.length) {
observables.push(of({}));
}
return combineLatest(observables).pipe(
map((results) => {
return results.reduce((state, result) => {
if (result.wishlist) {
return {
...state,
wishlist: result.wishlist
};
}
if (result.wishlistItem) {
return {
...state,
wishlistItem: result.wishlistItem
};
}
if (result.productInfo) {
return {
...state,
productInfo: result.productInfo
};
}
return state;
}, {});
}),
distinctUntilChanged((a3, b3) => JSON.stringify(a3) === JSON.stringify(b3))
);
}
getFallback() {
this.stateConfig = this.parseStateConfig(this.host.getStateConfig());
const fallbackState = {};
if (this.stateConfig.wishlist) {
const { wishlistId = "mine" } = this.stateConfig.wishlist.params;
fallbackState.wishlist = {
id: wishlistId,
isMine: wishlistId === "mine",
numItems: 0,
items: []
};
}
if (this.stateConfig.productInfo) {
const { variantId = 0, productHandle } = this.stateConfig.productInfo.params;
fallbackState.productInfo = {
productId: 0,
variantId,
productHandle,
inWishlist: false
};
}
if (this.stateConfig.wishlistItem) {
const { wishlistId, wishlistItemId } = this.stateConfig.wishlistItem.params;
if (!wishlistId) {
throw new Error("Wishlist id is required");
}
if (!wishlistItemId) {
throw new Error("Wishlist item id is required");
}
fallbackState.wishlistItem = {
id: wishlistItemId,
product: {
id: 0,
handle: "",
hidden: false
}
};
}
return fallbackState;
}
};
export {
FloatingUiController,
ProductFormController,
WishlistStateController
};
//# sourceMappingURL=controllers.js.map
function j(e){return e.split("-")[1]}function st(e){return e==="y"?"height":"width"}function k(e){return e.split("-")[0]}function N(e){return["top","bottom"].includes(k(e))?"x":"y"}function yt(e,t,i){let{reference:n,floating:s}=e,r=n.x+n.width/2-s.width/2,o=n.y+n.height/2-s.height/2,l=N(t),c=st(l),f=n[c]/2-s[c]/2,u=l==="x",a;switch(k(t)){case"top":a={x:r,y:n.y-s.height};break;case"bottom":a={x:r,y:n.y+n.height};break;case"right":a={x:n.x+n.width,y:o};break;case"left":a={x:n.x-s.width,y:o};break;default:a={x:n.x,y:n.y}}switch(j(t)){case"start":a[l]-=f*(i&&u?-1:1);break;case"end":a[l]+=f*(i&&u?-1:1)}return a}var xt=async(e,t,i)=>{let{placement:n="bottom",strategy:s="absolute",middleware:r=[],platform:o}=i,l=r.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(t)),f=await o.getElementRects({reference:e,floating:t,strategy:s}),{x:u,y:a}=yt(f,n,c),d=n,h={},p=0;for(let m=0;m<l.length;m++){let{name:g,fn:y}=l[m],{x:w,y:x,data:E,reset:b}=await y({x:u,y:a,initialPlacement:n,placement:d,strategy:s,middlewareData:h,rects:f,platform:o,elements:{reference:e,floating:t}});u=w!=null?w:u,a=x!=null?x:a,h={...h,[g]:{...h[g],...E}},b&&p<=50&&(p++,typeof b=="object"&&(b.placement&&(d=b.placement),b.rects&&(f=b.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:s}):b.rects),{x:u,y:a}=yt(f,d,c)),m=-1)}return{x:u,y:a,placement:d,strategy:s,middlewareData:h}};function vt(e){return typeof e!="number"?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(e):{top:e,right:e,bottom:e,left:e}}function U(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}async function rt(e,t){var i;t===void 0&&(t={});let{x:n,y:s,platform:r,rects:o,elements:l,strategy:c}=e,{boundary:f="clippingAncestors",rootBoundary:u="viewport",elementContext:a="floating",altBoundary:d=!1,padding:h=0}=t,p=vt(h),m=l[d?a==="floating"?"reference":"floating":a],g=U(await r.getClippingRect({element:(i=await(r.isElement==null?void 0:r.isElement(m)))==null||i?m:m.contextElement||await(r.getDocumentElement==null?void 0:r.getDocumentElement(l.floating)),boundary:f,rootBoundary:u,strategy:c})),y=a==="floating"?{...o.floating,x:n,y:s}:o.reference,w=await(r.getOffsetParent==null?void 0:r.getOffsetParent(l.floating)),x=await(r.isElement==null?void 0:r.isElement(w))&&await(r.getScale==null?void 0:r.getScale(w))||{x:1,y:1},E=U(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({rect:y,offsetParent:w,strategy:c}):y);return{top:(g.top-E.top+p.top)/x.y,bottom:(E.bottom-g.bottom+p.bottom)/x.y,left:(g.left-E.left+p.left)/x.x,right:(E.right-g.right+p.right)/x.x}}var kt=Math.min,zt=Math.max;function ot(e,t,i){return zt(e,kt(t,i))}var lt=e=>({name:"arrow",options:e,async fn(t){let{element:i,padding:n=0}=e||{},{x:s,y:r,placement:o,rects:l,platform:c,elements:f}=t;if(i==null)return{};let u=vt(n),a={x:s,y:r},d=N(o),h=st(d),p=await c.getDimensions(i),m=d==="y",g=m?"top":"left",y=m?"bottom":"right",w=m?"clientHeight":"clientWidth",x=l.reference[h]+l.reference[d]-a[d]-l.floating[h],E=a[d]-l.reference[d],b=await(c.getOffsetParent==null?void 0:c.getOffsetParent(i)),W=b?b[w]:0;W&&await(c.isElement==null?void 0:c.isElement(b))||(W=f.floating[w]||l.floating[h]);let D=x/2-E/2,H=u[g],q=W-p[h]-u[y],A=W/2-p[h]/2+D,v=ot(H,A,q),C=j(o)!=null&&A!=v&&l.reference[h]/2-(A<H?u[g]:u[y])-p[h]/2<0;return{[d]:a[d]-(C?A<H?H-A:q-A:0),data:{[d]:v,centerOffset:A-v}}}}),Mt=["top","right","bottom","left"],Qt=Mt.reduce((e,t)=>e.concat(t,t+"-start",t+"-end"),[]),qt={left:"right",right:"left",bottom:"top",top:"bottom"};function Y(e){return e.replace(/left|right|bottom|top/g,t=>qt[t])}function Bt(e,t,i){i===void 0&&(i=!1);let n=j(e),s=N(e),r=st(s),o=s==="x"?n===(i?"end":"start")?"right":"left":n==="start"?"bottom":"top";return t.reference[r]>t.floating[r]&&(o=Y(o)),{main:o,cross:Y(o)}}var Ut={start:"end",end:"start"};function nt(e){return e.replace(/start|end/g,t=>Ut[t])}var at=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var i;let{placement:n,middlewareData:s,rects:r,initialPlacement:o,platform:l,elements:c}=t,{mainAxis:f=!0,crossAxis:u=!0,fallbackPlacements:a,fallbackStrategy:d="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:p=!0,...m}=e,g=k(n),y=k(o)===o,w=await(l.isRTL==null?void 0:l.isRTL(c.floating)),x=a||(y||!p?[Y(o)]:function(v){let C=Y(v);return[nt(v),C,nt(C)]}(o));a||h==="none"||x.push(...function(v,C,V,L){let F=j(v),S=function(B,it,Dt){let gt=["left","right"],wt=["right","left"],Ht=["top","bottom"],Vt=["bottom","top"];switch(B){case"top":case"bottom":return Dt?it?wt:gt:it?gt:wt;case"left":case"right":return it?Ht:Vt;default:return[]}}(k(v),V==="start",L);return F&&(S=S.map(B=>B+"-"+F),C&&(S=S.concat(S.map(nt)))),S}(o,p,h,w));let E=[o,...x],b=await rt(t,m),W=[],D=((i=s.flip)==null?void 0:i.overflows)||[];if(f&&W.push(b[g]),u){let{main:v,cross:C}=Bt(n,r,w);W.push(b[v],b[C])}if(D=[...D,{placement:n,overflows:W}],!W.every(v=>v<=0)){var H,q;let v=(((H=s.flip)==null?void 0:H.index)||0)+1,C=E[v];if(C)return{data:{index:v,overflows:D},reset:{placement:C}};let V=(q=D.filter(L=>L.overflows[0]<=0).sort((L,F)=>L.overflows[1]-F.overflows[1])[0])==null?void 0:q.placement;if(!V)switch(d){case"bestFit":{var A;let L=(A=D.map(F=>[F.placement,F.overflows.filter(S=>S>0).reduce((S,B)=>S+B,0)]).sort((F,S)=>F[1]-S[1])[0])==null?void 0:A[0];L&&(V=L);break}case"initialPlacement":V=o}if(n!==V)return{reset:{placement:V}}}return{}}}};var J=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){let{x:i,y:n}=t,s=await async function(r,o){let{placement:l,platform:c,elements:f}=r,u=await(c.isRTL==null?void 0:c.isRTL(f.floating)),a=k(l),d=j(l),h=N(l)==="x",p=["left","top"].includes(a)?-1:1,m=u&&h?-1:1,g=typeof o=="function"?o(r):o,{mainAxis:y,crossAxis:w,alignmentAxis:x}=typeof g=="number"?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...g};return d&&typeof x=="number"&&(w=d==="end"?-1*x:x),h?{x:w*m,y:y*p}:{x:y*p,y:w*m}}(t,e);return{x:i+s.x,y:n+s.y,data:s}}}};function jt(e){return e==="x"?"y":"x"}var ct=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){let{x:i,y:n,placement:s}=t,{mainAxis:r=!0,crossAxis:o=!1,limiter:l={fn:g=>{let{x:y,y:w}=g;return{x:y,y:w}}},...c}=e,f={x:i,y:n},u=await rt(t,c),a=N(k(s)),d=jt(a),h=f[a],p=f[d];if(r){let g=a==="y"?"bottom":"right";h=ot(h+u[a==="y"?"top":"left"],h,h-u[g])}if(o){let g=d==="y"?"bottom":"right";p=ot(p+u[d==="y"?"top":"left"],p,p-u[g])}let m=l.fn({...t,[a]:h,[d]:p});return{...m,data:{x:m.x-i,y:m.y-n}}}}};function I(e){var t;return((t=e.ownerDocument)==null?void 0:t.defaultView)||window}function O(e){return I(e).getComputedStyle(e)}function Rt(e){return e instanceof I(e).Node}function _(e){return Rt(e)?(e.nodeName||"").toLowerCase():""}var Q;function Pt(){if(Q)return Q;let e=navigator.userAgentData;return e&&Array.isArray(e.brands)?(Q=e.brands.map(t=>t.brand+"/"+t.version).join(" "),Q):navigator.userAgent}function P(e){return e instanceof I(e).HTMLElement}function R(e){return e instanceof I(e).Element}function bt(e){return typeof ShadowRoot=="undefined"?!1:e instanceof I(e).ShadowRoot||e instanceof ShadowRoot}function Z(e){let{overflow:t,overflowX:i,overflowY:n,display:s}=O(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+i)&&!["inline","contents"].includes(s)}function Nt(e){return["table","td","th"].includes(_(e))}function ft(e){let t=/firefox/i.test(Pt()),i=O(e),n=i.backdropFilter||i.WebkitBackdropFilter;return i.transform!=="none"||i.perspective!=="none"||!!n&&n!=="none"||t&&i.willChange==="filter"||t&&!!i.filter&&i.filter!=="none"||["transform","perspective"].some(s=>i.willChange.includes(s))||["paint","layout","strict","content"].some(s=>{let r=i.contain;return r!=null&&r.includes(s)})}function ht(){return/^((?!chrome|android).)*safari/i.test(Pt())}function ut(e){return["html","body","#document"].includes(_(e))}var Et=Math.min,$=Math.max,G=Math.round;function At(e){let t=O(e),i=parseFloat(t.width),n=parseFloat(t.height),s=P(e),r=s?e.offsetWidth:i,o=s?e.offsetHeight:n,l=G(i)!==r||G(n)!==o;return l&&(i=r,n=o),{width:i,height:n,fallback:l}}function Ot(e){return R(e)?e:e.contextElement}var Wt={x:1,y:1};function M(e){let t=Ot(e);if(!P(t))return Wt;let i=t.getBoundingClientRect(),{width:n,height:s,fallback:r}=At(t),o=(r?G(i.width):i.width)/n,l=(r?G(i.height):i.height)/s;return o&&Number.isFinite(o)||(o=1),l&&Number.isFinite(l)||(l=1),{x:o,y:l}}function z(e,t,i,n){var s,r;t===void 0&&(t=!1),i===void 0&&(i=!1);let o=e.getBoundingClientRect(),l=Ot(e),c=Wt;t&&(n?R(n)&&(c=M(n)):c=M(e));let f=l?I(l):window,u=ht()&&i,a=(o.left+(u&&((s=f.visualViewport)==null?void 0:s.offsetLeft)||0))/c.x,d=(o.top+(u&&((r=f.visualViewport)==null?void 0:r.offsetTop)||0))/c.y,h=o.width/c.x,p=o.height/c.y;if(l){let m=I(l),g=n&&R(n)?I(n):n,y=m.frameElement;for(;y&&n&&g!==m;){let w=M(y),x=y.getBoundingClientRect(),E=getComputedStyle(y);x.x+=(y.clientLeft+parseFloat(E.paddingLeft))*w.x,x.y+=(y.clientTop+parseFloat(E.paddingTop))*w.y,a*=w.x,d*=w.y,h*=w.x,p*=w.y,a+=x.x,d+=x.y,y=I(y).frameElement}}return U({width:h,height:p,x:a,y:d})}function T(e){return((Rt(e)?e.ownerDocument:e.document)||window.document).documentElement}function tt(e){return R(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Ft(e){return z(T(e)).left+tt(e).scrollLeft}function X(e){if(_(e)==="html")return e;let t=e.assignedSlot||e.parentNode||bt(e)&&e.host||T(e);return bt(t)?t.host:t}function Lt(e){let t=X(e);return ut(t)?t.ownerDocument.body:P(t)&&Z(t)?t:Lt(t)}function K(e,t){var i;t===void 0&&(t=[]);let n=Lt(e),s=n===((i=e.ownerDocument)==null?void 0:i.body),r=I(n);return s?t.concat(r,r.visualViewport||[],Z(n)?n:[]):t.concat(n,K(n))}function It(e,t,i){let n;if(t==="viewport")n=function(o,l){let c=I(o),f=T(o),u=c.visualViewport,a=f.clientWidth,d=f.clientHeight,h=0,p=0;if(u){a=u.width,d=u.height;let m=ht();(!m||m&&l==="fixed")&&(h=u.offsetLeft,p=u.offsetTop)}return{width:a,height:d,x:h,y:p}}(e,i);else if(t==="document")n=function(o){let l=T(o),c=tt(o),f=o.ownerDocument.body,u=$(l.scrollWidth,l.clientWidth,f.scrollWidth,f.clientWidth),a=$(l.scrollHeight,l.clientHeight,f.scrollHeight,f.clientHeight),d=-c.scrollLeft+Ft(o),h=-c.scrollTop;return O(f).direction==="rtl"&&(d+=$(l.clientWidth,f.clientWidth)-u),{width:u,height:a,x:d,y:h}}(T(e));else if(R(t))n=function(o,l){let c=z(o,!0,l==="fixed"),f=c.top+o.clientTop,u=c.left+o.clientLeft,a=P(o)?M(o):{x:1,y:1};return{width:o.clientWidth*a.x,height:o.clientHeight*a.y,x:u*a.x,y:f*a.y}}(t,i);else{let o={...t};if(ht()){var s,r;let l=I(e);o.x-=((s=l.visualViewport)==null?void 0:s.offsetLeft)||0,o.y-=((r=l.visualViewport)==null?void 0:r.offsetTop)||0}n=o}return U(n)}function St(e,t){return P(e)&&O(e).position!=="fixed"?t?t(e):e.offsetParent:null}function Ct(e,t){let i=I(e);if(!P(e))return i;let n=St(e,t);for(;n&&Nt(n)&&O(n).position==="static";)n=St(n,t);return n&&(_(n)==="html"||_(n)==="body"&&O(n).position==="static"&&!ft(n))?i:n||function(s){let r=X(s);for(;P(r)&&!ut(r);){if(ft(r))return r;r=X(r)}return null}(e)||i}function $t(e,t,i){let n=P(t),s=T(t),r=z(e,!0,i==="fixed",t),o={scrollLeft:0,scrollTop:0},l={x:0,y:0};if(n||!n&&i!=="fixed")if((_(t)!=="body"||Z(s))&&(o=tt(t)),P(t)){let c=z(t,!0);l.x=c.x+t.clientLeft,l.y=c.y+t.clientTop}else s&&(l.x=Ft(s));return{x:r.left+o.scrollLeft-l.x,y:r.top+o.scrollTop-l.y,width:r.width,height:r.height}}var Kt={getClippingRect:function(e){let{element:t,boundary:i,rootBoundary:n,strategy:s}=e,r=i==="clippingAncestors"?function(f,u){let a=u.get(f);if(a)return a;let d=K(f).filter(g=>R(g)&&_(g)!=="body"),h=null,p=O(f).position==="fixed",m=p?X(f):f;for(;R(m)&&!ut(m);){let g=O(m),y=ft(m);g.position==="fixed"&&(h=null),(p?y||h:y||g.position!=="static"||!h||!["absolute","fixed"].includes(h.position))?h=g:d=d.filter(w=>w!==m),m=X(m)}return u.set(f,d),d}(t,this._c):[].concat(i),o=[...r,n],l=o[0],c=o.reduce((f,u)=>{let a=It(t,u,s);return f.top=$(a.top,f.top),f.right=Et(a.right,f.right),f.bottom=Et(a.bottom,f.bottom),f.left=$(a.left,f.left),f},It(t,l,s));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{rect:t,offsetParent:i,strategy:n}=e,s=P(i),r=T(i);if(i===r)return t;let o={scrollLeft:0,scrollTop:0},l={x:1,y:1},c={x:0,y:0};if((s||!s&&n!=="fixed")&&((_(i)!=="body"||Z(r))&&(o=tt(i)),P(i))){let f=z(i);l=M(i),c.x=f.x+i.clientLeft,c.y=f.y+i.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-o.scrollLeft*l.x+c.x,y:t.y*l.y-o.scrollTop*l.y+c.y}},isElement:R,getDimensions:function(e){return At(e)},getOffsetParent:Ct,getDocumentElement:T,getScale:M,async getElementRects(e){let{reference:t,floating:i,strategy:n}=e,s=this.getOffsetParent||Ct,r=this.getDimensions;return{reference:$t(t,await s(i),n),floating:{x:0,y:0,...await r(i)}}},getClientRects:e=>Array.from(e.getClientRects()),isRTL:e=>O(e).direction==="rtl"};function Tt(e,t,i,n){n===void 0&&(n={});let{ancestorScroll:s=!0,ancestorResize:r=!0,elementResize:o=!0,animationFrame:l=!1}=n,c=s&&!l,f=c||r?[...R(e)?K(e):e.contextElement?K(e.contextElement):[],...K(t)]:[];f.forEach(h=>{c&&h.addEventListener("scroll",i,{passive:!0}),r&&h.addEventListener("resize",i)});let u,a=null;o&&(a=new ResizeObserver(()=>{i()}),R(e)&&!l&&a.observe(e),R(e)||!e.contextElement||l||a.observe(e.contextElement),a.observe(t));let d=l?z(e):null;return l&&function h(){let p=z(e);!d||p.x===d.x&&p.y===d.y&&p.width===d.width&&p.height===d.height||i(),d=p,u=requestAnimationFrame(h)}(),i(),()=>{var h;f.forEach(p=>{c&&p.removeEventListener("scroll",i),r&&p.removeEventListener("resize",i)}),(h=a)==null||h.disconnect(),a=null,l&&cancelAnimationFrame(u)}}var _t=(e,t,i)=>{let n=new Map,s={platform:Kt,...i},r={...s.platform,_c:n};return xt(e,t,{...s,platform:r})};var dt=class{constructor(t){this._middleware=[];this._floating=!1;(this.host=t).addController(this)}hostConnected(){this.host.floating&&this.float(this.host.floating)}hostDisconnected(){this.destroy()}hostUpdated(){this.host.floating&&!this._floating&&this.float(this.host.floating),this._floating&&this.updatePosition()}hostResized(){this._floating&&this.updatePosition()}float(t){var l;if(this._floating)return;if(this._floating=!0,this._settings=t,this._reference=this.getReference(),this._resizeObserver=new ResizeObserver(()=>this.hostResized()),!this._settings)throw new Error("Floating settings are required");if(!this._reference)throw new Error("Floating reference is required");this.host.classList.add("wk-floating");let{position:i,arrow:n=!1,flip:s=!1,shift:r=!1}=this._settings,o=this.getOffsetSetting();Object.assign(this.host.style,{position:(l=i.strategy)!=null?l:"absolute",top:"0",left:"0",transition:"none",transform:"translate3d(0,0,0)"}),i.inset&&!n?this._middleware.push(J(({rects:c,placement:f})=>{var u,a,d,h,p,m;return f.includes("top")||f.includes("bottom")?{mainAxis:-c.floating.height-((u=o==null?void 0:o.mainAxis)!=null?u:0),crossAxis:(a=o==null?void 0:o.crossAxis)!=null?a:0,alignmentAxis:(d=o==null?void 0:o.alignmentAxis)!=null?d:0}:{mainAxis:-c.floating.width-((h=o==null?void 0:o.mainAxis)!=null?h:0),crossAxis:(p=o==null?void 0:o.crossAxis)!=null?p:0,alignmentAxis:(m=o==null?void 0:o.alignmentAxis)!=null?m:0}})):o&&this._middleware.push(J(o)),s&&this._middleware.push(at()),r&&this._middleware.push(ct()),n&&(this.arrowEl=document.createElement("div"),this.arrowEl.classList.add("wk-arrow"),this._middleware.push(lt({element:this.arrowEl}))),this.cleanupAutoUpdate=Tt(this._reference,this.host,()=>{this.updatePosition()}),this._resizeObserver.observe(this.host)}getOffsetSetting(){var i,n;let t=(i=this._settings)==null?void 0:i.offset;if(!(!t||typeof t=="boolean"))return typeof t=="number"?{mainAxis:t,alignmentAxis:(n=this._settings)!=null&&n.position.inset?t:null}:t}destroy(){var t,i,n,s;this._floating&&(Object.assign(this.host.style,{position:"",top:"",left:"",transition:"",transform:""}),(i=(t=this.arrowEl)==null?void 0:t.parentElement)==null||i.removeChild(this.arrowEl),this.arrowEl=void 0,this._middleware=[],this.host.classList.remove("wk-floating"),(n=this.cleanupAutoUpdate)==null||n.call(this),(s=this._resizeObserver)==null||s.disconnect(),this._floating=!1)}updatePosition(){var n;if(!this._reference||!this._settings)return;let{strategy:t="absolute",placement:i="top"}=(n=this._settings.position)!=null?n:{};_t(this._reference,this.host,{middleware:this._middleware,strategy:t,placement:i}).then(({x:s,y:r,placement:o,middlewareData:l})=>{if(l.arrow&&this.arrowEl){let{x:c,y:f}=l.arrow,u={top:"bottom",right:"left",bottom:"top",left:"right"}[o.split("-")[0]],a={bottom:"0deg",left:"90deg",top:"180deg",right:"270deg"}[o.split("-")[0]];Object.assign(this.arrowEl.style,{left:c!=null?`${c}px`:"",top:f!=null?`${f}px`:"",right:"",bottom:"",[u]:"-5px",transform:`rotate(${a})`})}Object.assign(this.host.style,{transform:`translate3d(${Math.round(s)}px,${Math.round(r)}px,0)`})})}getReference(){if(!this._settings)return;let t=this._settings.reference;if(typeof t=="string"){if(t==="viewport")return this.createViewportReference();let i=document.querySelector(t);if(!i)throw new Error(`Floating reference element (${t}) not found`);return i}return t.hasOwnProperty("element")?t.element:t}createViewportReference(){return{getBoundingClientRect(){var t,i,n,s;return{x:0,y:0,top:0,left:0,bottom:0,right:0,width:(i=(t=window.visualViewport)==null?void 0:t.width)!=null?i:0,height:(s=(n=window.visualViewport)==null?void 0:n.height)!=null?s:0}}}}};var pt=class{constructor(t){this.product=null;this.selectedVariant=null;this.selectedOptions={};this.hasSelection=!1;this.optionsWithValues=[];this.hasOnlyDefaultVariant=!1;(this.host=t).addController(this)}set submitting(t){var i;(i=this.host.querySelector("form"))==null||i.classList.toggle("wk-submitting",t)}get submitting(){var t,i;return(i=(t=this.host.querySelector("form"))==null?void 0:t.classList.contains("wk-submitting"))!=null?i:!1}setProduct({product:t,selectedVariantId:i,autoSelect:n=!1}){t!=null&&t.variants&&(this.product=t,this.initFormState({selectedVariantId:i,autoSelect:n}))}initFormState({selectedVariantId:t,autoSelect:i}){if(!this.product)throw new Error("Product not set");let n=this.initializedVariantId!==t?this.product.variants.find(r=>r.id===t):this.selectedVariant;this.initializedVariantId=t;let s=this.host.app.utils.product.getVariantOptions({variant:n});this.updateFormState({options:s,autoSelect:i})}updateFormState({options:t,change:i,autoSelect:n=!1}){if(!this.product)throw new Error("Product not set");let{hasSelection:s,optionsWithValues:r,selectedOptions:o,selectedVariant:l,hasOnlyDefaultVariant:c}=this.host.app.utils.product.getFormState({product:this.product,options:t,change:i,autoSelect:n});this.hasSelection=s,this.optionsWithValues=r,this.selectedOptions=o,this.selectedVariant=l,this.hasOnlyDefaultVariant=c,this.host.requestUpdate()}changeOption({input:t,autoSelect:i=!1}){if(!this.product)throw new Error("Product not set");let n=this.getInputOption(t);if(!n)throw new Error("Cannot parse options from input");this.updateFormState({options:this.selectedOptions,change:n,autoSelect:i})}addToCart({wishlistId:t,wishlistItemId:i,sectionsToRender:n,sectionsUrl:s="/"}){if(!this.selectedVariant)throw new Error("No variant selected");let r=this.host.querySelector("form");if(!r)throw new Error("Form not found");return this.submitting=!0,this.host.app.addToCart({wishlistId:t,wishlistItemId:i,variantId:this.selectedVariant.id,quantity:this.host.app.utils.product.getFormQuantity({form:r}),sectionsToRender:n,sectionsUrl:s}).finally(()=>{this.submitting=!1})}getInputOption(t){if(!this.product)throw new Error("Product not set");return this.host.app.utils.product.getInputOption({input:t,product:this.product})}hostConnected(){}hostDisconnected(){}hostUpdate(){}hostUpdated(){}};import{combineLatest as Xt,distinctUntilChanged as Yt,map as et,of as Jt}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";var mt=class{constructor(t){this.stateConfig={loading:"eager"};(this.host=t).addController(this)}get app(){if(!window.WishlistKing)throw new Error("Wishlist King SDK not initialized");return window.WishlistKing}get hostDataset(){return this.host.dataset?this.host.dataset:this.host.host?this.host.host.dataset:{}}hostConnected(){}hostDisconnected(){}parseStateConfig(t){var i;return{loading:(i=t.loading)!=null?i:"eager",wishlist:this.parseWishlistStateConfig(t),wishlistItem:this.parseWishlistItemStateConfig(t),productInfo:this.parseProductInfoStateConfig(t)}}parseWishlistStateConfig({wishlist:t}){var n;let i=(n=this.hostDataset.wishlistId)!=null?n:"mine";if(t)return{params:{wishlistId:i}}}parseWishlistItemStateConfig({wishlistItem:t}){let{wishlistId:i="mine",wishlistItemId:n}=this.hostDataset;if(!(!t||!n))return{params:{wishlistId:i,wishlistItemId:n}}}parseProductInfoStateConfig({productInfo:t}){if(!t)return;let{wishlistId:i="mine",productHandle:n="",productId:s,variantId:r}=this.hostDataset;return{params:{wishlistId:i,productHandle:n,variantId:r?parseInt(r):void 0}}}observe(){this.stateConfig=this.parseStateConfig(this.host.getStateConfig());let t=[];if(this.stateConfig.wishlist){let{wishlistId:i="mine"}=this.stateConfig.wishlist.params;t.push(this.app.state.observeWishlist({wishlistId:i}).pipe(et(n=>({wishlist:n}))))}if(this.stateConfig.productInfo){let{productHandle:i,variantId:n}=this.stateConfig.productInfo.params;if(!i)throw new Error("Product handle is required");t.push(this.app.state.observeProductInfo({productHandle:i,variantId:n}).pipe(et(s=>({productInfo:s}))))}if(this.stateConfig.wishlistItem){let{wishlistId:i,wishlistItemId:n}=this.stateConfig.wishlistItem.params;if(!i)throw new Error("Wishlist id is required");if(!n)throw new Error("Wishlist item id is required");t.push(this.app.state.observeWishlistItem({wishlistId:i,wishlistItemId:n}).pipe(et(s=>({wishlistItem:s}))))}return t.length||t.push(Jt({})),Xt(t).pipe(et(i=>i.reduce((n,s)=>s.wishlist?{...n,wishlist:s.wishlist}:s.wishlistItem?{...n,wishlistItem:s.wishlistItem}:s.productInfo?{...n,productInfo:s.productInfo}:n,{})),Yt((i,n)=>JSON.stringify(i)===JSON.stringify(n)))}getFallback(){this.stateConfig=this.parseStateConfig(this.host.getStateConfig());let t={};if(this.stateConfig.wishlist){let{wishlistId:i="mine"}=this.stateConfig.wishlist.params;t.wishlist={id:i,isMine:i==="mine",numItems:0,items:[]}}if(this.stateConfig.productInfo){let{variantId:i=0,productHandle:n}=this.stateConfig.productInfo.params;t.productInfo={productId:0,variantId:i,productHandle:n,inWishlist:!1}}if(this.stateConfig.wishlistItem){let{wishlistId:i,wishlistItemId:n}=this.stateConfig.wishlistItem.params;if(!i)throw new Error("Wishlist id is required");if(!n)throw new Error("Wishlist item id is required");t.wishlistItem={id:n,product:{id:0,handle:"",hidden:!1}}}return t}};export{dt as FloatingUiController,pt as ProductFormController,mt as WishlistStateController};

2

package.json
{
"name": "@appmate/wishlist",
"version": "4.22.4",
"version": "4.22.5",
"description": "Wishlist King SDK",

@@ -5,0 +5,0 @@ "main": "wishlist-app.js",

@@ -1,386 +0,1 @@

// src/theme-helper/ThemeInjector.ts
var ThemeInjector = class {
constructor(element) {
this.element = element;
}
replace(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.replaceWith(element);
return element;
}
append(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.append(element);
return element;
}
prepend(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.prepend(element);
return element;
}
insertBefore(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.before(element);
return element;
}
insertAfter(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.after(element);
return element;
}
closest(selector, depth = 5) {
if (!this.element) {
return new ThemeInjector();
}
if (typeof selector === "object") {
return this.searchByStyle(
selector,
this.element,
(element2) => element2.parentElement,
depth
);
}
const element = this.element.closest(selector);
if (element) {
return new ThemeInjector(element);
}
return new ThemeInjector();
}
find(selector) {
var _a;
const element = (_a = this.element) == null ? void 0 : _a.querySelector(selector);
if (element) {
return new ThemeInjector(element);
}
return new ThemeInjector();
}
searchByStyle(search, element, next, depth = 5) {
if (depth < 0 || !element) {
return null;
}
const computedStyle = getComputedStyle(element);
const isMatch = Object.entries(search).every(
([key, value]) => computedStyle.getPropertyValue(key) === value
);
if (isMatch) {
return new ThemeInjector(element);
}
const nextElement = next(element);
if (!nextElement) {
return null;
}
return this.searchByStyle(search, nextElement, next, depth - 1);
}
};
// src/theme-helper/ThemeObserver.ts
var ThemeObserver = class {
constructor({ routeUtil }) {
this.subscriber = [];
this.routeUtil = routeUtil;
this.observer = new MutationObserver((mutations) => {
mutations.reduce(
(acc, mutation) => acc.concat(Array.from(mutation.addedNodes)),
[]
).filter(
(node) => node instanceof Element && !node.hasAttribute("data-appmate")
).forEach((node) => {
if (node instanceof Element) {
this.scan(node);
}
});
});
this.observer.observe(document, {
subtree: true,
childList: true,
attributes: false
});
}
watch(target, callback) {
const subscriber = {
target,
callback
};
this.subscriber.push(subscriber);
if (isRouteSubscriber(
subscriber,
this.routeUtil.parse(window.location.pathname)
)) {
this.scan(document);
}
}
shouldSkip(element, { skipHidden }) {
if (!skipHidden) {
return false;
}
if (element instanceof HTMLElement) {
return element.offsetParent === null;
}
return false;
}
scan(rootElement) {
if (!rootElement) {
return;
}
this.subscriber.filter(
(subscriber) => isRouteSubscriber(
subscriber,
this.routeUtil.parse(window.location.pathname)
)
).forEach((subscriber) => {
const isRootMatch = rootElement instanceof Element && rootElement.matches(subscriber.target.selector) && !this.shouldSkip(rootElement, {
skipHidden: !!subscriber.target.skipHidden
});
if (isRootMatch) {
this.notify(subscriber, rootElement);
}
if (isRootMatch && subscriber.target.firstMatch) {
return;
}
const childMatches = rootElement.querySelectorAll(
subscriber.target.selector
);
for (const element of childMatches) {
if (!this.shouldSkip(element, {
skipHidden: !!subscriber.target.skipHidden
})) {
this.notify(subscriber, element);
if (subscriber.target.firstMatch) {
break;
}
}
}
});
}
notify(subscriber, element) {
if (!element.hasAttribute("data-appmate")) {
element.setAttribute("data-appmate", "");
const injector = new ThemeInjector(element);
subscriber.callback(injector);
}
}
};
function isRouteSubscriber({ target }, route) {
if (!target.pageType) {
return true;
}
if (!route.pageType) {
return false;
}
const pageTypes = Array.isArray(target.pageType) ? target.pageType : [target.pageType];
if (pageTypes.includes("all")) {
return true;
}
return pageTypes.includes(route.pageType);
}
// src/theme-helper/RouteUtil.ts
var tests = [
{
pageType: "product",
match: (path) => path.includes("/products/")
},
{
pageType: "collection",
match: (path) => path.includes("/collections/") && !path.includes("/products/")
},
{
pageType: "account",
match: (path) => path.includes("/account/") || path.endsWith("/account")
},
{
pageType: "blog",
match: (path) => path.includes("/blog/")
},
{
pageType: "cart",
match: (path) => path.includes("/cart/") || path.endsWith("/cart")
},
{
pageType: "wishlist",
match: (path, { wishlistUrl }) => path.includes(wishlistUrl)
},
{
pageType: "page",
match: (path) => path.includes("/pages/")
},
{
pageType: "home",
match: (path) => path.length < 4
}
];
var RouteUtil = class {
constructor({ wishlistUrl }) {
this.wishlistUrl = wishlistUrl;
}
parse(path) {
for (const test of tests) {
const match = test.match(path, { wishlistUrl: this.wishlistUrl });
if (match) {
return {
pageType: test.pageType
};
}
}
return {
pageType: void 0
};
}
};
// src/theme-helper/LocaleUtil.ts
var LocaleUtil = class {
constructor(params) {
this.locale = {};
var _a;
this.initLocale((_a = params == null ? void 0 : params.locale) != null ? _a : {});
}
initLocale(locale) {
this.locale = this.decodeLocale(locale);
}
decodeHtmlEntities(str) {
return str.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&#39;/g, "'");
}
decodeLocale(locale) {
const result = {};
for (const group in locale) {
result[group] = {};
for (const key in locale[group]) {
result[group][key] = this.decodeHtmlEntities(locale[group][key]);
}
}
return result;
}
translate(id, values) {
var _a;
const [group, key] = id.split(".");
const text = (_a = this.locale[group]) == null ? void 0 : _a[key];
if (!text) {
return `translation missing: ${id}`;
}
if (!values) {
return text;
}
return Object.entries(values).reduce(
(text2, [key2, value]) => text2.replace(new RegExp(`{{\\s*${key2}\\s*}}`, "g"), value),
text
);
}
};
// src/theme-helper/ThemeHelper.ts
var ThemeHelper = class {
constructor({
rootUrl,
wishlistUrl
}) {
this._rootUrl = rootUrl;
this.route = new RouteUtil({ wishlistUrl });
this.observer = new ThemeObserver({ routeUtil: this.route });
this.locale = new LocaleUtil();
this.watch = this.observer.watch.bind(this.observer);
}
getPageType(path = window.location.pathname) {
return this.route.parse(path).pageType;
}
getWishlistId(url) {
if (!url) {
return null;
}
if (url instanceof URL) {
url = url.pathname;
}
const parts = url.replace(this._rootUrl, "/").split("/");
return parts.length === 4 ? parts.pop() : "mine";
}
getProductHandle(url) {
var _a;
if (!url) {
return null;
}
if (url instanceof URL) {
url = url.pathname;
}
return (_a = url.split("/").pop()) == null ? void 0 : _a.split("?")[0];
}
getVariantId(url) {
if (!url) {
return null;
}
if (url instanceof URL) {
url = url.pathname;
}
const params = new URLSearchParams(url.split("?")[1]);
return params.get("variant");
}
translate(id, values) {
return this.locale.translate(id, values);
}
createComponent(name, config) {
var _a;
const element = document.createElement(name);
if (config == null ? void 0 : config.dataset) {
Object.entries(config == null ? void 0 : config.dataset).forEach(([key, value]) => {
if (!value) {
return;
}
if (typeof value === "boolean") {
element.dataset[key] = "";
} else if (typeof value === "object") {
element.dataset[key] = JSON.stringify(value);
} else {
element.dataset[key] = value;
}
});
}
if (config == null ? void 0 : config.props) {
Object.entries(config == null ? void 0 : config.props).forEach(([key, value]) => {
element[key] = value;
});
}
if ((_a = config == null ? void 0 : config.wrap) == null ? void 0 : _a.name) {
return this.createElement(config.wrap.name, config.wrap.props, element);
}
return element;
}
createHeadlessComponent(name, config) {
var _a;
const host = config.host.element ? config.host.element : config.host;
if (!host) {
throw new Error("Headless host is undefined");
}
if (config.dataset) {
Object.entries(config.dataset).forEach(([key, value]) => {
if (!value) {
return;
}
if (typeof value === "boolean") {
host.dataset[key] = "";
} else if (typeof value === "object") {
host.dataset[key] = JSON.stringify(value);
} else {
host.dataset[key] = value;
}
});
}
const ElementConstructor = (_a = window.headlessElements) == null ? void 0 : _a.store.get(name);
if (!ElementConstructor) {
throw new Error(`Headless element not found: ${name}`);
}
return new ElementConstructor(host);
}
createElement(name, props = {}, ...children) {
const element = Object.assign(
document.createElement(name),
props
);
if (children) {
element.append(...children);
}
return element;
}
};
export {
ThemeHelper
};
//# sourceMappingURL=theme-helper.js.map
var o=class{constructor(t){this.element=t}replace(t){var e;return(e=this.element)==null||e.replaceWith(t),t}append(t){var e;return(e=this.element)==null||e.append(t),t}prepend(t){var e;return(e=this.element)==null||e.prepend(t),t}insertBefore(t){var e;return(e=this.element)==null||e.before(t),t}insertAfter(t){var e;return(e=this.element)==null||e.after(t),t}closest(t,e=5){if(!this.element)return new o;if(typeof t=="object")return this.searchByStyle(t,this.element,a=>a.parentElement,e);let r=this.element.closest(t);return r?new o(r):new o}find(t){var r;let e=(r=this.element)==null?void 0:r.querySelector(t);return e?new o(e):new o}searchByStyle(t,e,r,a=5){if(a<0||!e)return null;let n=getComputedStyle(e);if(Object.entries(t).every(([h,d])=>n.getPropertyValue(h)===d))return new o(e);let c=r(e);return c?this.searchByStyle(t,c,r,a-1):null}};var l=class{constructor({routeUtil:t}){this.subscriber=[],this.routeUtil=t,this.observer=new MutationObserver(e=>{e.reduce((r,a)=>r.concat(Array.from(a.addedNodes)),[]).filter(r=>r instanceof Element&&!r.hasAttribute("data-appmate")).forEach(r=>{r instanceof Element&&this.scan(r)})}),this.observer.observe(document,{subtree:!0,childList:!0,attributes:!1})}watch(t,e){let r={target:t,callback:e};this.subscriber.push(r),g(r,this.routeUtil.parse(window.location.pathname))&&this.scan(document)}shouldSkip(t,{skipHidden:e}){return e&&t instanceof HTMLElement?t.offsetParent===null:!1}scan(t){t&&this.subscriber.filter(e=>g(e,this.routeUtil.parse(window.location.pathname))).forEach(e=>{let r=t instanceof Element&&t.matches(e.target.selector)&&!this.shouldSkip(t,{skipHidden:!!e.target.skipHidden});if(r&&this.notify(e,t),r&&e.target.firstMatch)return;let a=t.querySelectorAll(e.target.selector);for(let n of a)if(!this.shouldSkip(n,{skipHidden:!!e.target.skipHidden})&&(this.notify(e,n),e.target.firstMatch))break})}notify(t,e){if(!e.hasAttribute("data-appmate")){e.setAttribute("data-appmate","");let r=new o(e);t.callback(r)}}};function g({target:s},t){if(!s.pageType)return!0;if(!t.pageType)return!1;let e=Array.isArray(s.pageType)?s.pageType:[s.pageType];return e.includes("all")?!0:e.includes(t.pageType)}var f=[{pageType:"product",match:s=>s.includes("/products/")},{pageType:"collection",match:s=>s.includes("/collections/")&&!s.includes("/products/")},{pageType:"account",match:s=>s.includes("/account/")||s.endsWith("/account")},{pageType:"blog",match:s=>s.includes("/blog/")},{pageType:"cart",match:s=>s.includes("/cart/")||s.endsWith("/cart")},{pageType:"wishlist",match:(s,{wishlistUrl:t})=>s.includes(t)},{pageType:"page",match:s=>s.includes("/pages/")},{pageType:"home",match:s=>s.length<4}],p=class{constructor({wishlistUrl:t}){this.wishlistUrl=t}parse(t){for(let e of f)if(e.match(t,{wishlistUrl:this.wishlistUrl}))return{pageType:e.pageType};return{pageType:void 0}}};var u=class{constructor(t){this.locale={};var e;this.initLocale((e=t==null?void 0:t.locale)!=null?e:{})}initLocale(t){this.locale=this.decodeLocale(t)}decodeHtmlEntities(t){return t.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'")}decodeLocale(t){let e={};for(let r in t){e[r]={};for(let a in t[r])e[r][a]=this.decodeHtmlEntities(t[r][a])}return e}translate(t,e){var i;let[r,a]=t.split("."),n=(i=this.locale[r])==null?void 0:i[a];return n?e?Object.entries(e).reduce((c,[h,d])=>c.replace(new RegExp(`{{\\s*${h}\\s*}}`,"g"),d),n):n:`translation missing: ${t}`}};var m=class{constructor({rootUrl:t,wishlistUrl:e}){this._rootUrl=t,this.route=new p({wishlistUrl:e}),this.observer=new l({routeUtil:this.route}),this.locale=new u,this.watch=this.observer.watch.bind(this.observer)}getPageType(t=window.location.pathname){return this.route.parse(t).pageType}getWishlistId(t){if(!t)return null;t instanceof URL&&(t=t.pathname);let e=t.replace(this._rootUrl,"/").split("/");return e.length===4?e.pop():"mine"}getProductHandle(t){var e;return t?(t instanceof URL&&(t=t.pathname),(e=t.split("/").pop())==null?void 0:e.split("?")[0]):null}getVariantId(t){return t?(t instanceof URL&&(t=t.pathname),new URLSearchParams(t.split("?")[1]).get("variant")):null}translate(t,e){return this.locale.translate(t,e)}createComponent(t,e){var a;let r=document.createElement(t);return e!=null&&e.dataset&&Object.entries(e==null?void 0:e.dataset).forEach(([n,i])=>{i&&(typeof i=="boolean"?r.dataset[n]="":typeof i=="object"?r.dataset[n]=JSON.stringify(i):r.dataset[n]=i)}),e!=null&&e.props&&Object.entries(e==null?void 0:e.props).forEach(([n,i])=>{r[n]=i}),(a=e==null?void 0:e.wrap)!=null&&a.name?this.createElement(e.wrap.name,e.wrap.props,r):r}createHeadlessComponent(t,e){var n;let r=e.host.element?e.host.element:e.host;if(!r)throw new Error("Headless host is undefined");e.dataset&&Object.entries(e.dataset).forEach(([i,c])=>{c&&(typeof c=="boolean"?r.dataset[i]="":typeof c=="object"?r.dataset[i]=JSON.stringify(c):r.dataset[i]=c)});let a=(n=window.headlessElements)==null?void 0:n.store.get(t);if(!a)throw new Error(`Headless element not found: ${t}`);return new a(r)}createElement(t,e={},...r){let a=Object.assign(document.createElement(t),e);return r&&a.append(...r),a}};export{m as ThemeHelper};

@@ -1,412 +0,1 @@

// src/utils/MoneyUtil.ts
var MoneyUtil = class {
constructor(params) {
this.placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var _a, _b;
this.moneyFormat = (_a = params.moneyFormat) != null ? _a : "${{amount}}";
this.moneyFormatWithCurrency = (_b = params.moneyFormatWithCurrency) != null ? _b : "${{amount}} USD";
}
formatMoney(cents, options) {
var _a, _b;
const withCurrency = (_a = options == null ? void 0 : options.withCurrency) != null ? _a : false;
if (typeof cents === "string") {
cents = parseInt(cents.replace(".", ""));
}
return (withCurrency ? this.moneyFormatWithCurrency : this.moneyFormat).replace(
this.placeholderRegex,
this.formatCents(
cents,
(_b = this.moneyFormat.match(this.placeholderRegex)) == null ? void 0 : _b[1]
)
);
}
formatCents(cents, format) {
switch (format) {
case "amount_no_decimals":
return this.formatWithDelimiters(cents, 0);
case "amount_with_comma_separator":
return this.formatWithDelimiters(cents, 2, ".", ",");
case "amount_no_decimals_with_comma_separator":
return this.formatWithDelimiters(cents, 0, ".", ",");
case "amount":
default:
return this.formatWithDelimiters(cents, 2);
}
}
formatWithDelimiters(cents, precision = 2, thousands = ",", decimal = ".") {
if (isNaN(cents) || cents == null) {
return "0";
}
const amount = (cents / 100).toFixed(precision);
const parts = amount.split(".");
const dollarsAmount = parts[0].replace(
/(\d)(?=(\d\d\d)+(?!\d))/g,
`$1${thousands}`
);
const centsAmount = parts[1] ? decimal + parts[1] : "";
return dollarsAmount + centsAmount;
}
};
// src/utils/ProductUtil.ts
var ProductUtil = class {
constructor() {
}
getFormState({
product,
options,
autoSelect = false,
change
}) {
const selectedOptions = this.getSelectedOptions({
product,
options,
change,
autoSelect
});
const hasSelection = selectedOptions && Object.values(selectedOptions).every((value) => !!value);
const optionsWithValues = this.getOptionsWithValues({
product,
selectedOptions
});
const selectedVariant = this.getVariantByOptions({
product,
options: selectedOptions,
optionsWithValues
});
return {
selectedVariant,
selectedOptions,
hasSelection,
optionsWithValues,
hasOnlyDefaultVariant: product.variants.length === 1
};
}
getSelectedOptions({
product,
options,
autoSelect,
change = {}
}) {
const nextOptions = Object.fromEntries(
Object.entries({
...options,
...change
}).map(([optionKey, value], index) => {
var _a;
if (!value && ((_a = product.options[index]) == null ? void 0 : _a.values.length) === 1) {
return [optionKey, product.options[index].values[0]];
}
return [optionKey, value];
})
);
if (!autoSelect) {
return nextOptions;
}
const lastChangedKey = Object.keys(change).pop();
const fixedOptions = !lastChangedKey ? Object.fromEntries(
Object.entries(options).filter(([, value]) => !!value)
) : Object.fromEntries(
Object.entries(nextOptions).filter(([key]) => lastChangedKey > key)
);
const variableOptions = Object.fromEntries(
Object.entries(nextOptions).filter(([key]) => !(key in fixedOptions))
);
const autoSelectOptions = Object.keys(variableOptions).reduce(
(options2, optionKey) => {
var _a;
const variants = this.getAllVariantsByOptions({
product,
options: options2
});
if (!variants.length) {
return {
...options2,
[optionKey]: null
};
}
return {
...options2,
[optionKey]: ((_a = variants.find((variant) => variant.available)) != null ? _a : variants[0])[optionKey]
};
},
fixedOptions
);
return autoSelectOptions;
}
getVariantOptions({
variant
}) {
var _a, _b, _c;
return {
option1: (_a = variant == null ? void 0 : variant.option1) != null ? _a : null,
option2: (_b = variant == null ? void 0 : variant.option2) != null ? _b : null,
option3: (_c = variant == null ? void 0 : variant.option3) != null ? _c : null
};
}
getOptionsWithValues({
product,
selectedOptions = {}
}) {
return product.options.map((option) => {
var _a;
const optionKey = `option${option.position}`;
const unavailableValues = this.getUnavailableOptionValues({
product,
optionKey,
selectedOptions,
values: option.values
});
const soldoutValues = this.getSoldoutOptionValues({
product,
optionKey,
selectedOptions,
values: option.values
});
const selectedValue = (_a = selectedOptions == null ? void 0 : selectedOptions[optionKey]) != null ? _a : null;
return {
...option,
selectedValue,
soldoutValues,
unavailableValues
};
});
}
getSoldoutOptionValues({
product,
optionKey,
values,
selectedOptions = {}
}) {
const optionsFilter = Object.fromEntries(
Object.entries(selectedOptions).filter(([key]) => key < optionKey)
);
return values.filter((value) => {
const matchingVariants = product.variants.filter(
(variant) => this.matchesVariant({
variant,
options: {
...optionsFilter,
[optionKey]: value
}
})
);
if (!matchingVariants.length) {
return false;
}
return matchingVariants.every((variant) => !variant.available);
});
}
getUnavailableOptionValues({
product,
optionKey,
values,
selectedOptions = {}
}) {
const optionsFilter = Object.fromEntries(
Object.entries(selectedOptions).filter(([key]) => key < optionKey)
);
return values.filter(
(value) => product.variants.every(
(variant) => !this.matchesVariant({
variant,
options: {
...optionsFilter,
[optionKey]: value
}
})
)
);
}
getFirstAvailableVariant({ product }) {
var _a;
return (_a = product.variants.find((variant) => variant.available)) != null ? _a : null;
}
getSelectedVariant({
product,
variantId
}) {
var _a;
return (_a = product.variants.find((variant) => variant.id === variantId)) != null ? _a : null;
}
matchesVariant({
variant,
options
}) {
return (!(options == null ? void 0 : options.option1) || options.option1 === variant.option1) && (!(options == null ? void 0 : options.option2) || options.option2 === variant.option2) && (!(options == null ? void 0 : options.option3) || options.option3 === variant.option3);
}
getFormData({
form,
product
}) {
const formData = new FormData(form);
return {
quantity: this.getFormQuantity({ form }),
options: this.getFormOptions({
formData,
product
})
};
}
getFormQuantity({ form }) {
var _a;
const formData = new FormData(form);
const quantity = (_a = formData.get("quantity")) == null ? void 0 : _a.toString();
if (!quantity) {
return 1;
}
return parseInt(quantity);
}
getVariantByOptions({
product,
options,
optionsWithValues
}) {
var _a;
const optionList = Object.entries(options).reduce(
(options2, [, value], index) => {
options2[index] = value;
return options2;
},
new Array(3).fill(null)
);
return (_a = product.variants.find((variant) => {
return optionList.every((value, index) => {
if (!optionsWithValues.some((option) => option.position === index + 1)) {
return true;
}
return variant[`option${index + 1}`] === value;
});
})) != null ? _a : null;
}
getAllVariantsByOptions({
product,
options
}) {
var _a;
const optionList = Object.entries(options).reduce(
(options2, [, value], index) => {
options2[index] = value;
return options2;
},
new Array(3).fill(null)
);
return (_a = product.variants.filter((variant) => {
return optionList.every(
(value, index) => !value || variant[`option${index + 1}`] === value
);
})) != null ? _a : [];
}
getFormOptions({
formData,
product
}) {
return Array.from(formData.entries()).reduce((options, [key, data]) => {
var _a;
const name = (_a = key.match(/\[(.*?)\]/)) == null ? void 0 : _a[1];
if (!name) {
return options;
}
const optionIndex = product.options.findIndex((option) => option.name === name) + 1;
if (optionIndex > 0) {
const optionKey = `option${optionIndex}`;
options[optionKey] = data.toString() || null;
}
return options;
}, {});
}
getInputOption({
input,
product
}) {
var _a;
const name = (_a = input.name.match(/\[(.*?)\]/)) == null ? void 0 : _a[1];
if (!name) {
return null;
}
const optionIndex = product.options.findIndex((option) => option.name === name) + 1;
if (optionIndex > 0) {
const optionKey = `option${optionIndex}`;
return {
[optionKey]: input.value.toString()
};
}
return null;
}
};
// src/utils/UrlUtil.ts
var UrlUtil = class {
constructor(params) {
this.rootUrl = params.rootUrl;
this.shopDomain = params.shopDomain;
this.wishlistUrl = params.wishlistUrl;
this.placeholderImageUrl = params.placeholderImageUrl;
this.fileUrl = params.fileUrl;
}
getPublicWishlistUrl(wishlistId) {
return `https://${this.shopDomain}${this.wishlistUrl}/${wishlistId}`;
}
getFileUrl(file = "") {
return `https:${this.fileUrl.split("?")[0]}${file}`;
}
getImageUrl(media, size) {
var _a, _b;
if (!media) {
return (_a = this.placeholderImageUrl) != null ? _a : "";
}
const image = this.getImage(media);
if (!(image == null ? void 0 : image.src)) {
return (_b = this.placeholderImageUrl) != null ? _b : "";
}
return this.appendSize(image.src, size);
}
getImage(media) {
var _a, _b, _c, _d;
if (media.hasOwnProperty("sku")) {
const variant = media;
return {
src: (_b = (_a = variant.featured_image) == null ? void 0 : _a.src) != null ? _b : ""
};
} else if ((_c = media == null ? void 0 : media.images) == null ? void 0 : _c.length) {
const product = media;
return {
src: (_d = product.featured_image) != null ? _d : product.images[0]
};
} else if (media.hasOwnProperty("src")) {
const image = media;
return {
src: image.src
};
}
return null;
}
appendSize(url, size) {
const newUrl = new URL(url.startsWith("//") ? `https://${url}` : url);
if (size == null ? void 0 : size.width) {
newUrl.searchParams.set("width", size == null ? void 0 : size.width.toString());
}
if (size == null ? void 0 : size.height) {
newUrl.searchParams.set("height", size == null ? void 0 : size.height.toString());
}
return newUrl.href;
}
getVariantUrl(productUrl, variantId) {
if (!productUrl) {
return;
}
if (!variantId) {
return productUrl;
}
return productUrl + `?variant=${variantId}`;
}
handlelize(value) {
return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/([^\w]+|\s+)/g, "-").replace(/\-\-+/g, "-").replace(/(^-+|-+$)/g, "").toLowerCase();
}
};
export {
MoneyUtil,
ProductUtil,
UrlUtil
};
//# sourceMappingURL=utils.js.map
var m=class{constructor(t){this.placeholderRegex=/\{\{\s*(\w+)\s*\}\}/;var r,e;this.moneyFormat=(r=t.moneyFormat)!=null?r:"${{amount}}",this.moneyFormatWithCurrency=(e=t.moneyFormatWithCurrency)!=null?e:"${{amount}} USD"}formatMoney(t,r){var o,i;let e=(o=r==null?void 0:r.withCurrency)!=null?o:!1;return typeof t=="string"&&(t=parseInt(t.replace(".",""))),(e?this.moneyFormatWithCurrency:this.moneyFormat).replace(this.placeholderRegex,this.formatCents(t,(i=this.moneyFormat.match(this.placeholderRegex))==null?void 0:i[1]))}formatCents(t,r){switch(r){case"amount_no_decimals":return this.formatWithDelimiters(t,0);case"amount_with_comma_separator":return this.formatWithDelimiters(t,2,".",",");case"amount_no_decimals_with_comma_separator":return this.formatWithDelimiters(t,0,".",",");case"amount":default:return this.formatWithDelimiters(t,2)}}formatWithDelimiters(t,r=2,e=",",o="."){if(isNaN(t)||t==null)return"0";let n=(t/100).toFixed(r).split("."),a=n[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,`$1${e}`),s=n[1]?o+n[1]:"";return a+s}};var f=class{constructor(){}getFormState({product:t,options:r,autoSelect:e=!1,change:o}){let i=this.getSelectedOptions({product:t,options:r,change:o,autoSelect:e}),n=i&&Object.values(i).every(u=>!!u),a=this.getOptionsWithValues({product:t,selectedOptions:i});return{selectedVariant:this.getVariantByOptions({product:t,options:i,optionsWithValues:a}),selectedOptions:i,hasSelection:n,optionsWithValues:a,hasOnlyDefaultVariant:t.variants.length===1}}getSelectedOptions({product:t,options:r,autoSelect:e,change:o={}}){let i=Object.fromEntries(Object.entries({...r,...o}).map(([l,c],p)=>{var h;return!c&&((h=t.options[p])==null?void 0:h.values.length)===1?[l,t.options[p].values[0]]:[l,c]}));if(!e)return i;let n=Object.keys(o).pop(),a=Object.fromEntries(n?Object.entries(i).filter(([l])=>n>l):Object.entries(r).filter(([,l])=>!!l)),s=Object.fromEntries(Object.entries(i).filter(([l])=>!(l in a)));return Object.keys(s).reduce((l,c)=>{var h;let p=this.getAllVariantsByOptions({product:t,options:l});return p.length?{...l,[c]:((h=p.find(g=>g.available))!=null?h:p[0])[c]}:{...l,[c]:null}},a)}getVariantOptions({variant:t}){var r,e,o;return{option1:(r=t==null?void 0:t.option1)!=null?r:null,option2:(e=t==null?void 0:t.option2)!=null?e:null,option3:(o=t==null?void 0:t.option3)!=null?o:null}}getOptionsWithValues({product:t,selectedOptions:r={}}){return t.options.map(e=>{var s;let o=`option${e.position}`,i=this.getUnavailableOptionValues({product:t,optionKey:o,selectedOptions:r,values:e.values}),n=this.getSoldoutOptionValues({product:t,optionKey:o,selectedOptions:r,values:e.values}),a=(s=r==null?void 0:r[o])!=null?s:null;return{...e,selectedValue:a,soldoutValues:n,unavailableValues:i}})}getSoldoutOptionValues({product:t,optionKey:r,values:e,selectedOptions:o={}}){let i=Object.fromEntries(Object.entries(o).filter(([n])=>n<r));return e.filter(n=>{let a=t.variants.filter(s=>this.matchesVariant({variant:s,options:{...i,[r]:n}}));return a.length?a.every(s=>!s.available):!1})}getUnavailableOptionValues({product:t,optionKey:r,values:e,selectedOptions:o={}}){let i=Object.fromEntries(Object.entries(o).filter(([n])=>n<r));return e.filter(n=>t.variants.every(a=>!this.matchesVariant({variant:a,options:{...i,[r]:n}})))}getFirstAvailableVariant({product:t}){var r;return(r=t.variants.find(e=>e.available))!=null?r:null}getSelectedVariant({product:t,variantId:r}){var e;return(e=t.variants.find(o=>o.id===r))!=null?e:null}matchesVariant({variant:t,options:r}){return(!(r!=null&&r.option1)||r.option1===t.option1)&&(!(r!=null&&r.option2)||r.option2===t.option2)&&(!(r!=null&&r.option3)||r.option3===t.option3)}getFormData({form:t,product:r}){let e=new FormData(t);return{quantity:this.getFormQuantity({form:t}),options:this.getFormOptions({formData:e,product:r})}}getFormQuantity({form:t}){var o;let e=(o=new FormData(t).get("quantity"))==null?void 0:o.toString();return e?parseInt(e):1}getVariantByOptions({product:t,options:r,optionsWithValues:e}){var i;let o=Object.entries(r).reduce((n,[,a],s)=>(n[s]=a,n),new Array(3).fill(null));return(i=t.variants.find(n=>o.every((a,s)=>e.some(u=>u.position===s+1)?n[`option${s+1}`]===a:!0)))!=null?i:null}getAllVariantsByOptions({product:t,options:r}){var o;let e=Object.entries(r).reduce((i,[,n],a)=>(i[a]=n,i),new Array(3).fill(null));return(o=t.variants.filter(i=>e.every((n,a)=>!n||i[`option${a+1}`]===n)))!=null?o:[]}getFormOptions({formData:t,product:r}){return Array.from(t.entries()).reduce((e,[o,i])=>{var s;let n=(s=o.match(/\[(.*?)\]/))==null?void 0:s[1];if(!n)return e;let a=r.options.findIndex(u=>u.name===n)+1;if(a>0){let u=`option${a}`;e[u]=i.toString()||null}return e},{})}getInputOption({input:t,product:r}){var i;let e=(i=t.name.match(/\[(.*?)\]/))==null?void 0:i[1];if(!e)return null;let o=r.options.findIndex(n=>n.name===e)+1;return o>0?{[`option${o}`]:t.value.toString()}:null}};var d=class{constructor(t){this.rootUrl=t.rootUrl,this.shopDomain=t.shopDomain,this.wishlistUrl=t.wishlistUrl,this.placeholderImageUrl=t.placeholderImageUrl,this.fileUrl=t.fileUrl}getPublicWishlistUrl(t){return`https://${this.shopDomain}${this.wishlistUrl}/${t}`}getFileUrl(t=""){return`https:${this.fileUrl.split("?")[0]}${t}`}getImageUrl(t,r){var o,i;if(!t)return(o=this.placeholderImageUrl)!=null?o:"";let e=this.getImage(t);return e!=null&&e.src?this.appendSize(e.src,r):(i=this.placeholderImageUrl)!=null?i:""}getImage(t){var r,e,o,i;if(t.hasOwnProperty("sku"))return{src:(e=(r=t.featured_image)==null?void 0:r.src)!=null?e:""};if((o=t==null?void 0:t.images)!=null&&o.length){let n=t;return{src:(i=n.featured_image)!=null?i:n.images[0]}}else if(t.hasOwnProperty("src"))return{src:t.src};return null}appendSize(t,r){let e=new URL(t.startsWith("//")?`https://${t}`:t);return r!=null&&r.width&&e.searchParams.set("width",r==null?void 0:r.width.toString()),r!=null&&r.height&&e.searchParams.set("height",r==null?void 0:r.height.toString()),e.href}getVariantUrl(t,r){if(t)return r?t+`?variant=${r}`:t}handlelize(t){return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/([^\w]+|\s+)/g,"-").replace(/\-\-+/g,"-").replace(/(^-+|-+$)/g,"").toLowerCase()}};export{m as MoneyUtil,f as ProductUtil,d as UrlUtil};

@@ -1,866 +0,1 @@

// src/theme-helper/ThemeInjector.ts
var ThemeInjector = class {
constructor(element) {
this.element = element;
}
replace(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.replaceWith(element);
return element;
}
append(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.append(element);
return element;
}
prepend(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.prepend(element);
return element;
}
insertBefore(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.before(element);
return element;
}
insertAfter(element) {
var _a;
(_a = this.element) == null ? void 0 : _a.after(element);
return element;
}
closest(selector, depth = 5) {
if (!this.element) {
return new ThemeInjector();
}
if (typeof selector === "object") {
return this.searchByStyle(
selector,
this.element,
(element2) => element2.parentElement,
depth
);
}
const element = this.element.closest(selector);
if (element) {
return new ThemeInjector(element);
}
return new ThemeInjector();
}
find(selector) {
var _a;
const element = (_a = this.element) == null ? void 0 : _a.querySelector(selector);
if (element) {
return new ThemeInjector(element);
}
return new ThemeInjector();
}
searchByStyle(search, element, next, depth = 5) {
if (depth < 0 || !element) {
return null;
}
const computedStyle = getComputedStyle(element);
const isMatch = Object.entries(search).every(
([key, value]) => computedStyle.getPropertyValue(key) === value
);
if (isMatch) {
return new ThemeInjector(element);
}
const nextElement = next(element);
if (!nextElement) {
return null;
}
return this.searchByStyle(search, nextElement, next, depth - 1);
}
};
// src/theme-helper/ThemeObserver.ts
var ThemeObserver = class {
constructor({ routeUtil }) {
this.subscriber = [];
this.routeUtil = routeUtil;
this.observer = new MutationObserver((mutations) => {
mutations.reduce(
(acc, mutation) => acc.concat(Array.from(mutation.addedNodes)),
[]
).filter(
(node) => node instanceof Element && !node.hasAttribute("data-appmate")
).forEach((node) => {
if (node instanceof Element) {
this.scan(node);
}
});
});
this.observer.observe(document, {
subtree: true,
childList: true,
attributes: false
});
}
watch(target, callback) {
const subscriber = {
target,
callback
};
this.subscriber.push(subscriber);
if (isRouteSubscriber(
subscriber,
this.routeUtil.parse(window.location.pathname)
)) {
this.scan(document);
}
}
shouldSkip(element, { skipHidden }) {
if (!skipHidden) {
return false;
}
if (element instanceof HTMLElement) {
return element.offsetParent === null;
}
return false;
}
scan(rootElement) {
if (!rootElement) {
return;
}
this.subscriber.filter(
(subscriber) => isRouteSubscriber(
subscriber,
this.routeUtil.parse(window.location.pathname)
)
).forEach((subscriber) => {
const isRootMatch = rootElement instanceof Element && rootElement.matches(subscriber.target.selector) && !this.shouldSkip(rootElement, {
skipHidden: !!subscriber.target.skipHidden
});
if (isRootMatch) {
this.notify(subscriber, rootElement);
}
if (isRootMatch && subscriber.target.firstMatch) {
return;
}
const childMatches = rootElement.querySelectorAll(
subscriber.target.selector
);
for (const element of childMatches) {
if (!this.shouldSkip(element, {
skipHidden: !!subscriber.target.skipHidden
})) {
this.notify(subscriber, element);
if (subscriber.target.firstMatch) {
break;
}
}
}
});
}
notify(subscriber, element) {
if (!element.hasAttribute("data-appmate")) {
element.setAttribute("data-appmate", "");
const injector = new ThemeInjector(element);
subscriber.callback(injector);
}
}
};
function isRouteSubscriber({ target }, route) {
if (!target.pageType) {
return true;
}
if (!route.pageType) {
return false;
}
const pageTypes = Array.isArray(target.pageType) ? target.pageType : [target.pageType];
if (pageTypes.includes("all")) {
return true;
}
return pageTypes.includes(route.pageType);
}
// src/theme-helper/RouteUtil.ts
var tests = [
{
pageType: "product",
match: (path) => path.includes("/products/")
},
{
pageType: "collection",
match: (path) => path.includes("/collections/") && !path.includes("/products/")
},
{
pageType: "account",
match: (path) => path.includes("/account/") || path.endsWith("/account")
},
{
pageType: "blog",
match: (path) => path.includes("/blog/")
},
{
pageType: "cart",
match: (path) => path.includes("/cart/") || path.endsWith("/cart")
},
{
pageType: "wishlist",
match: (path, { wishlistUrl }) => path.includes(wishlistUrl)
},
{
pageType: "page",
match: (path) => path.includes("/pages/")
},
{
pageType: "home",
match: (path) => path.length < 4
}
];
var RouteUtil = class {
constructor({ wishlistUrl }) {
this.wishlistUrl = wishlistUrl;
}
parse(path) {
for (const test of tests) {
const match = test.match(path, { wishlistUrl: this.wishlistUrl });
if (match) {
return {
pageType: test.pageType
};
}
}
return {
pageType: void 0
};
}
};
// src/theme-helper/LocaleUtil.ts
var LocaleUtil = class {
constructor(params) {
this.locale = {};
var _a;
this.initLocale((_a = params == null ? void 0 : params.locale) != null ? _a : {});
}
initLocale(locale) {
this.locale = this.decodeLocale(locale);
}
decodeHtmlEntities(str) {
return str.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&#39;/g, "'");
}
decodeLocale(locale) {
const result = {};
for (const group in locale) {
result[group] = {};
for (const key in locale[group]) {
result[group][key] = this.decodeHtmlEntities(locale[group][key]);
}
}
return result;
}
translate(id, values) {
var _a;
const [group, key] = id.split(".");
const text = (_a = this.locale[group]) == null ? void 0 : _a[key];
if (!text) {
return `translation missing: ${id}`;
}
if (!values) {
return text;
}
return Object.entries(values).reduce(
(text2, [key2, value]) => text2.replace(new RegExp(`{{\\s*${key2}\\s*}}`, "g"), value),
text
);
}
};
// src/theme-helper/ThemeHelper.ts
var ThemeHelper = class {
constructor({
rootUrl,
wishlistUrl
}) {
this._rootUrl = rootUrl;
this.route = new RouteUtil({ wishlistUrl });
this.observer = new ThemeObserver({ routeUtil: this.route });
this.locale = new LocaleUtil();
this.watch = this.observer.watch.bind(this.observer);
}
getPageType(path = window.location.pathname) {
return this.route.parse(path).pageType;
}
getWishlistId(url) {
if (!url) {
return null;
}
if (url instanceof URL) {
url = url.pathname;
}
const parts = url.replace(this._rootUrl, "/").split("/");
return parts.length === 4 ? parts.pop() : "mine";
}
getProductHandle(url) {
var _a;
if (!url) {
return null;
}
if (url instanceof URL) {
url = url.pathname;
}
return (_a = url.split("/").pop()) == null ? void 0 : _a.split("?")[0];
}
getVariantId(url) {
if (!url) {
return null;
}
if (url instanceof URL) {
url = url.pathname;
}
const params = new URLSearchParams(url.split("?")[1]);
return params.get("variant");
}
translate(id, values) {
return this.locale.translate(id, values);
}
createComponent(name, config) {
var _a;
const element = document.createElement(name);
if (config == null ? void 0 : config.dataset) {
Object.entries(config == null ? void 0 : config.dataset).forEach(([key, value]) => {
if (!value) {
return;
}
if (typeof value === "boolean") {
element.dataset[key] = "";
} else if (typeof value === "object") {
element.dataset[key] = JSON.stringify(value);
} else {
element.dataset[key] = value;
}
});
}
if (config == null ? void 0 : config.props) {
Object.entries(config == null ? void 0 : config.props).forEach(([key, value]) => {
element[key] = value;
});
}
if ((_a = config == null ? void 0 : config.wrap) == null ? void 0 : _a.name) {
return this.createElement(config.wrap.name, config.wrap.props, element);
}
return element;
}
createHeadlessComponent(name, config) {
var _a;
const host = config.host.element ? config.host.element : config.host;
if (!host) {
throw new Error("Headless host is undefined");
}
if (config.dataset) {
Object.entries(config.dataset).forEach(([key, value]) => {
if (!value) {
return;
}
if (typeof value === "boolean") {
host.dataset[key] = "";
} else if (typeof value === "object") {
host.dataset[key] = JSON.stringify(value);
} else {
host.dataset[key] = value;
}
});
}
const ElementConstructor = (_a = window.headlessElements) == null ? void 0 : _a.store.get(name);
if (!ElementConstructor) {
throw new Error(`Headless element not found: ${name}`);
}
return new ElementConstructor(host);
}
createElement(name, props = {}, ...children) {
const element = Object.assign(
document.createElement(name),
props
);
if (children) {
element.append(...children);
}
return element;
}
};
// src/utils/WishlistEvents.ts
var WishlistEvents = class {
constructor() {
this.dispatcher = document;
}
publish(event) {
this.dispatcher.dispatchEvent(
new CustomEvent(event.name, {
detail: event,
bubbles: false,
cancelable: false
})
);
}
once(eventName, handler) {
const oneTimeHandler = (event) => {
this.dispatcher.removeEventListener(eventName, oneTimeHandler);
handler(event);
};
this.subscribe(eventName, oneTimeHandler);
}
subscribe(eventName, handler) {
this.dispatcher.addEventListener(eventName, (event) => {
const customEvent = event;
handler({
name: customEvent.type,
data: customEvent.detail.data
});
});
}
subscribeMany(events) {
return Object.entries(events).map(
([eventName, handler]) => this.subscribe(eventName, handler)
);
}
};
// src/WishlistApp.ts
if (!window.headlessElements) {
window.headlessElements = {
store: /* @__PURE__ */ new Map(),
define(name, element) {
var _a;
(_a = window.headlessElements) == null ? void 0 : _a.store.set(name, element);
}
};
}
var WishlistApp = class {
constructor({ dependencies = [], ...params }) {
this.stylesLoaded = false;
this._loaded = false;
this.addToCart = (args) => this.state.promise.addToCart(args);
this.addAllToCart = (args) => this.state.promise.addAllToCart(args);
this.addWishlistItem = (args) => this.state.promise.addWishlistItem(args);
this.clearWishlist = () => this.state.promise.clearWishlist();
this.loadProductInfo = (args) => this.state.promise.loadProductInfo(args);
this.loadShopifyProduct = (args) => this.state.promise.loadShopifyProduct(args);
this.loadWishlist = (args) => this.state.promise.loadWishlist(args);
this.loadWishlistItem = (args) => this.state.promise.loadWishlistItem(args);
// loadWishlistProduct: typeof this.state.promise.loadWishlistProduct = (args) =>
// this.state.promise.loadWishlistProduct(args);
this.publishWishlistEvent = (args) => this.state.promise.publishWishlistEvent(args);
this.publishWishlistProductEvent = (args) => this.state.promise.publishWishlistProductEvent(args);
this.removeWishlistItem = (args) => this.state.promise.removeWishlistItem(args);
this.shareWishlist = (args) => this.state.promise.shareWishlist(args);
this.updateWishlistItem = (args) => this.state.promise.updateWishlistItem(args);
this.config = this.parseConfig(params);
this.settings = this.parseSettings(params);
this.routes = this.parseRoutes();
this.customer = this.config.customer.id ? {
id: this.config.customer.id,
email: this.config.customer.email
} : null;
this.events = new WishlistEvents();
this.theme = new ThemeHelper({
rootUrl: this.routes.rootUrl,
wishlistUrl: this.routes.wishlistUrl
});
const { stylesheets, scripts, iconSetUrl, localeUrl } = dependencies.reduce(
({ stylesheets: stylesheets2, scripts: scripts2, iconSetUrl: iconSetUrl2, localeUrl: localeUrl2 }, source) => {
const [url] = source.split("?");
if (url.endsWith(".css")) {
stylesheets2.push(source);
} else if (url.endsWith("icons.js")) {
iconSetUrl2 = source;
} else if (url.endsWith(".js")) {
scripts2.push(source);
} else if (url.endsWith(".json")) {
localeUrl2 = source;
}
return { stylesheets: stylesheets2, scripts: scripts2, iconSetUrl: iconSetUrl2, localeUrl: localeUrl2 };
},
{
stylesheets: [],
scripts: [],
iconSetUrl: "",
localeUrl: ""
}
);
this.initStyles({
stylesheets,
iconSetUrl,
localeUrl
});
this.initScripts(scripts);
if (this.hasSession || this.settings.general.appLoading === "EAGER") {
this.load();
}
window.WishlistKing = this;
this.events.publish({
name: "wk:app:created"
});
}
get loaded() {
return this._loaded;
}
get state() {
return lazyLoaded(this._state);
}
get apis() {
return lazyLoaded(this._apis);
}
get utils() {
return lazyLoaded(this._utils);
}
get hasSession() {
return !!this.getSessionId() || !!this.customer;
}
get isLoggedIn() {
var _a;
return !!((_a = this.customer) == null ? void 0 : _a.id);
}
getSessionId() {
const sessionId = window.localStorage.getItem("wk_session_id");
if (sessionId) {
return sessionId;
}
const legacySession = window.localStorage.getItem("appmate-session");
if (legacySession) {
try {
const sessionId2 = JSON.parse(legacySession).state.sid;
return this.setSessionId(sessionId2);
} catch (error) {
console.error(error);
}
}
}
setSessionId(sessionId) {
var _a;
window.localStorage.setItem("wk_session_id", sessionId);
(_a = this._apis) == null ? void 0 : _a.tracking.setSessionId(sessionId);
return sessionId;
}
async load() {
if (this._loadPromise) {
return this._loadPromise;
}
return this._loadPromise = (async () => {
const [
{ WishlistState },
{ ShopifyApi, WishlistApi, TrackingApi },
{ MoneyUtil, UrlUtil, ProductUtil }
] = await Promise.all([
import("https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/state.js"),
import("https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/api.js"),
import("https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/utils.js")
]);
this.initUtils({
MoneyUtil,
UrlUtil,
ProductUtil
});
this.initApis({
WishlistApi,
ShopifyApi,
TrackingApi
});
this.initState({
WishlistState
});
this.initUrlChangeEvents();
this.trackCurrentPage();
if (!this.hasSession) {
await this.state.promise.clearCache();
this.events.once("wk:app:init-sid", (event) => {
var _a, _b;
if ((_a = event.data) == null ? void 0 : _a.sessionId) {
this.setSessionId((_b = event.data) == null ? void 0 : _b.sessionId);
}
});
}
this._loaded = true;
this.events.publish({
name: "wk:app:load:success"
});
})();
}
initUtils({
UrlUtil,
MoneyUtil,
ProductUtil
}) {
this._utils = {
url: new UrlUtil({
rootUrl: this.routes.rootUrl,
wishlistUrl: this.routes.wishlistUrl,
shopDomain: this.config.shop.domain,
placeholderImageUrl: this.config.products.fallbackImage,
fileUrl: this.routes.fileUrl
}),
money: new MoneyUtil({
moneyFormat: this.config.shop.moneyFormat,
moneyFormatWithCurrency: this.config.shop.moneyFormatWithCurrency
// currencyRate: parseFloat(window.Shopify.currency.rate),
// activeCurrency: window.Shopify.currency.active,
}),
product: new ProductUtil()
};
}
initApis({
WishlistApi,
ShopifyApi,
TrackingApi
}) {
var _a, _b;
this._apis = {
wishlist: new WishlistApi({
host: this.config.routes.apiHost,
shop: window.Shopify.shop,
customerId: (_a = this.config.customer.id) != null ? _a : void 0,
sessionId: this.getSessionId(),
trackingSource: this.theme.getPageType(),
productMetafields: this.config.products.metafields
}),
shopify: new ShopifyApi({
host: window.Shopify.routes.root.substring(
0,
window.Shopify.routes.root.length - 1
)
}),
tracking: new TrackingApi({
notifyHost: this.config.routes.apiHost,
events: this.events,
shop: window.Shopify.shop,
customerId: (_b = this.config.customer.id) != null ? _b : void 0,
sessionId: this.getSessionId(),
utils: this.utils,
theme: this.theme,
settings: this.settings
})
};
}
initState({
WishlistState
}) {
this._state = new WishlistState({
wishlistApi: this.apis.wishlist,
shopifyApi: this.apis.shopify,
settings: this.settings,
events: this.events,
utils: this.utils
});
}
async initStyles({
stylesheets,
iconSetUrl,
localeUrl
}) {
if (!(stylesheets == null ? void 0 : stylesheets.length) && !iconSetUrl) {
this.onStylesLoaded();
return;
}
try {
await Promise.all([
...(stylesheets != null ? stylesheets : []).map(
(url) => new Promise((resolve, reject) => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
})
),
iconSetUrl ? Promise.all([
import("https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/components/icon.js"),
import(iconSetUrl)
]).then(([{ Icon }, { icons }]) => {
if (typeof icons !== "object") {
throw new Error("Icon set must export icons object.");
}
Icon.addIcons(icons);
}) : Promise.resolve(),
localeUrl ? fetch(localeUrl).then((response) => response.json()).then((locale) => {
this.theme.locale.initLocale(locale);
}) : Promise.resolve()
]);
this.onStylesLoaded();
} catch (error) {
console.warn(error);
this.events.publish({
name: "wk:app:load-styles:error"
});
}
}
async initScripts(scripts) {
if (!(scripts == null ? void 0 : scripts.length)) {
this.events.publish({
name: "wk:app:load-scripts:success"
});
return;
}
try {
await Promise.all(scripts.map((url) => import(url)));
this.events.publish({
name: "wk:app:load-scripts:success"
});
} catch (error) {
console.warn(error);
this.events.publish({
name: "wk:app:load-scripts:error"
});
}
}
trackCurrentPage() {
const currentPage = this.theme.getPageType();
if (currentPage === "wishlist") {
const wishlistId = this.theme.getWishlistId(window.location.pathname);
if (wishlistId) {
this.publishWishlistEvent({
eventName: "wk:wishlist:page-view",
wishlistId
});
}
}
}
onStylesLoaded() {
this.stylesLoaded = true;
this.events.publish({
name: "wk:app:load-styles:success"
});
}
initUrlChangeEvents() {
const originalReplaceState = history.replaceState;
const publishVariantChange = ({
productHandle,
variantId
}) => {
this.events.publish({
name: "wk:product:change-variant:success",
data: {
productHandle,
variantId
}
});
};
history.replaceState = (...args) => {
const baseUrl = `${window.location.protocol}//${window.location.host}`;
const url = typeof args[2] === "string" ? new URL(args[2], baseUrl) : args[2];
const result = originalReplaceState.apply(history, args);
if (!url) {
return result;
}
const productHandle = this.theme.getProductHandle(url);
const variantId = url.searchParams.get("variant");
if (!productHandle || !variantId) {
return result;
}
publishVariantChange({
productHandle,
variantId: parseInt(variantId)
});
};
}
parseConfig({
config
}) {
var _a, _b, _c, _d, _e, _f, _g, _h;
return {
customer: {
id: config.customerId ? config.customerId : null,
email: (_a = config.customerEmail) != null ? _a : ""
},
shop: {
name: (_b = config.shopName) != null ? _b : "",
domain: (_c = config.shopDomain) != null ? _c : "",
permanentDomain: (_d = config.shopPermanentDomain) != null ? _d : "",
// currency: config.shopCurrency ?? "",
moneyFormat: (_e = config.shopMoneyFormat) != null ? _e : "",
moneyFormatWithCurrency: (_f = config.shopMoneyFormatWithCurrency) != null ? _f : "",
customerAccountsEnabled: config.shopCustomerAccountsEnabled ? config.shopCustomerAccountsEnabled === "true" : false
},
routes: {
apiHost: (_g = config.apiHost) != null ? _g : "https://api.appmate.io/v2",
rootUrl: window.Shopify.routes.root,
fileUrl: config.fileUrl
},
products: {
fallbackImage: (_h = config.productFallbackImage) != null ? _h : "//cdn.shopify.com/s/files/1/0533/2089/files/placeholder-images-image_large.png?format=webp&v=1530129081",
metafields: !!config.productMetafields
}
};
}
parseSettings({
settings
}) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A;
return {
general: {
appLoading: (_b = (_a = settings == null ? void 0 : settings.general) == null ? void 0 : _a.appLoading) != null ? _b : "LAZY",
wishlistAccessMode: this.config.customer.id ? "UNRESTRICTED" : (_d = (_c = settings == null ? void 0 : settings.general) == null ? void 0 : _c.wishlistAccessMode) != null ? _d : "UNRESTRICTED",
wishlistMode: (_f = (_e = settings == null ? void 0 : settings.general) == null ? void 0 : _e.wishlistMode) != null ? _f : "PRODUCT",
wishlistPath: (_h = (_g = settings == null ? void 0 : settings.general) == null ? void 0 : _g.wishlistPath) != null ? _h : "/apps/wishlist"
},
money: {
withCurrency: (_j = (_i = settings == null ? void 0 : settings.money) == null ? void 0 : _i.withCurrency) != null ? _j : false
},
integrations: {
googleAnalytics: {
enabled: (_m = (_l = (_k = settings.integrations) == null ? void 0 : _k.googleAnalytics) == null ? void 0 : _l.enabled) != null ? _m : false,
tracker: (_p = (_o = (_n = settings.integrations) == null ? void 0 : _n.googleAnalytics) == null ? void 0 : _o.tracker) != null ? _p : ""
},
klaviyo: {
enabled: (_s = (_r = (_q = settings.integrations) == null ? void 0 : _q.klaviyo) == null ? void 0 : _r.enabled) != null ? _s : false
},
metaPixel: {
enabled: (_v = (_u = (_t = settings.integrations) == null ? void 0 : _t.metaPixel) == null ? void 0 : _u.enabled) != null ? _v : false
},
wishlistAnalytics: {
enabled: (_y = (_x = (_w = settings.integrations) == null ? void 0 : _w.metaPixel) == null ? void 0 : _x.enabled) != null ? _y : true
}
},
cache: {
wishlist: {
ttl: 6e4
},
wishlistItem: {
ttl: 6e4
},
productInfo: {
ttl: 6e4
},
product: {
ttl: 3e4
}
},
colorMap: (_z = settings.colorMap) != null ? _z : {},
collectionButtons: (_A = settings.collectionButtons) != null ? _A : {}
};
}
parseRoutes() {
const rootUrl = this.config.routes.rootUrl;
return {
rootUrl,
fileUrl: this.config.routes.fileUrl,
wishlistUrl: rootUrl + this.settings.general.wishlistPath.split("/").filter((v) => !!v).join("/"),
accountUrl: rootUrl + "account",
accountLoginUrl: rootUrl + "account/login",
accountLogoutUrl: rootUrl + "account/logout",
accountRegisterUrl: rootUrl + "account/register",
accountAddressesUrl: rootUrl + "account/addresses",
collectionsUrl: rootUrl + "collections",
allProductsCollectionUrl: rootUrl + "collections/all",
searchUrl: rootUrl + "search",
predictiveSearchUrl: rootUrl + "search/suggest",
cartUrl: rootUrl + "cart",
cartAddUrl: rootUrl + "cart/add",
cartChangeUrl: rootUrl + "cart/change",
cartClearUrl: rootUrl + "cart/clear",
cartUpdateUrl: rootUrl + "cart/update",
productRecommendationsUrl: rootUrl + "recommendations/products"
};
}
};
var lazyLoaded = (value) => {
if (!value)
throw new Error("Wishlist app not loaded.");
return value;
};
export {
WishlistApp
};
//# sourceMappingURL=wishlist-app.js.map
var h=class{constructor(t){this.element=t}replace(t){var e;return(e=this.element)==null||e.replaceWith(t),t}append(t){var e;return(e=this.element)==null||e.append(t),t}prepend(t){var e;return(e=this.element)==null||e.prepend(t),t}insertBefore(t){var e;return(e=this.element)==null||e.before(t),t}insertAfter(t){var e;return(e=this.element)==null||e.after(t),t}closest(t,e=5){if(!this.element)return new h;if(typeof t=="object")return this.searchByStyle(t,this.element,i=>i.parentElement,e);let s=this.element.closest(t);return s?new h(s):new h}find(t){var s;let e=(s=this.element)==null?void 0:s.querySelector(t);return e?new h(e):new h}searchByStyle(t,e,s,i=5){if(i<0||!e)return null;let r=getComputedStyle(e);if(Object.entries(t).every(([l,c])=>r.getPropertyValue(l)===c))return new h(e);let n=s(e);return n?this.searchByStyle(t,n,s,i-1):null}};var g=class{constructor({routeUtil:t}){this.subscriber=[],this.routeUtil=t,this.observer=new MutationObserver(e=>{e.reduce((s,i)=>s.concat(Array.from(i.addedNodes)),[]).filter(s=>s instanceof Element&&!s.hasAttribute("data-appmate")).forEach(s=>{s instanceof Element&&this.scan(s)})}),this.observer.observe(document,{subtree:!0,childList:!0,attributes:!1})}watch(t,e){let s={target:t,callback:e};this.subscriber.push(s),_(s,this.routeUtil.parse(window.location.pathname))&&this.scan(document)}shouldSkip(t,{skipHidden:e}){return e&&t instanceof HTMLElement?t.offsetParent===null:!1}scan(t){t&&this.subscriber.filter(e=>_(e,this.routeUtil.parse(window.location.pathname))).forEach(e=>{let s=t instanceof Element&&t.matches(e.target.selector)&&!this.shouldSkip(t,{skipHidden:!!e.target.skipHidden});if(s&&this.notify(e,t),s&&e.target.firstMatch)return;let i=t.querySelectorAll(e.target.selector);for(let r of i)if(!this.shouldSkip(r,{skipHidden:!!e.target.skipHidden})&&(this.notify(e,r),e.target.firstMatch))break})}notify(t,e){if(!e.hasAttribute("data-appmate")){e.setAttribute("data-appmate","");let s=new h(e);t.callback(s)}}};function _({target:a},t){if(!a.pageType)return!0;if(!t.pageType)return!1;let e=Array.isArray(a.pageType)?a.pageType:[a.pageType];return e.includes("all")?!0:e.includes(t.pageType)}var N=[{pageType:"product",match:a=>a.includes("/products/")},{pageType:"collection",match:a=>a.includes("/collections/")&&!a.includes("/products/")},{pageType:"account",match:a=>a.includes("/account/")||a.endsWith("/account")},{pageType:"blog",match:a=>a.includes("/blog/")},{pageType:"cart",match:a=>a.includes("/cart/")||a.endsWith("/cart")},{pageType:"wishlist",match:(a,{wishlistUrl:t})=>a.includes(t)},{pageType:"page",match:a=>a.includes("/pages/")},{pageType:"home",match:a=>a.length<4}],f=class{constructor({wishlistUrl:t}){this.wishlistUrl=t}parse(t){for(let e of N)if(e.match(t,{wishlistUrl:this.wishlistUrl}))return{pageType:e.pageType};return{pageType:void 0}}};var w=class{constructor(t){this.locale={};var e;this.initLocale((e=t==null?void 0:t.locale)!=null?e:{})}initLocale(t){this.locale=this.decodeLocale(t)}decodeHtmlEntities(t){return t.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'")}decodeLocale(t){let e={};for(let s in t){e[s]={};for(let i in t[s])e[s][i]=this.decodeHtmlEntities(t[s][i])}return e}translate(t,e){var o;let[s,i]=t.split("."),r=(o=this.locale[s])==null?void 0:o[i];return r?e?Object.entries(e).reduce((n,[l,c])=>n.replace(new RegExp(`{{\\s*${l}\\s*}}`,"g"),c),r):r:`translation missing: ${t}`}};var u=class{constructor({rootUrl:t,wishlistUrl:e}){this._rootUrl=t,this.route=new f({wishlistUrl:e}),this.observer=new g({routeUtil:this.route}),this.locale=new w,this.watch=this.observer.watch.bind(this.observer)}getPageType(t=window.location.pathname){return this.route.parse(t).pageType}getWishlistId(t){if(!t)return null;t instanceof URL&&(t=t.pathname);let e=t.replace(this._rootUrl,"/").split("/");return e.length===4?e.pop():"mine"}getProductHandle(t){var e;return t?(t instanceof URL&&(t=t.pathname),(e=t.split("/").pop())==null?void 0:e.split("?")[0]):null}getVariantId(t){return t?(t instanceof URL&&(t=t.pathname),new URLSearchParams(t.split("?")[1]).get("variant")):null}translate(t,e){return this.locale.translate(t,e)}createComponent(t,e){var i;let s=document.createElement(t);return e!=null&&e.dataset&&Object.entries(e==null?void 0:e.dataset).forEach(([r,o])=>{o&&(typeof o=="boolean"?s.dataset[r]="":typeof o=="object"?s.dataset[r]=JSON.stringify(o):s.dataset[r]=o)}),e!=null&&e.props&&Object.entries(e==null?void 0:e.props).forEach(([r,o])=>{s[r]=o}),(i=e==null?void 0:e.wrap)!=null&&i.name?this.createElement(e.wrap.name,e.wrap.props,s):s}createHeadlessComponent(t,e){var r;let s=e.host.element?e.host.element:e.host;if(!s)throw new Error("Headless host is undefined");e.dataset&&Object.entries(e.dataset).forEach(([o,n])=>{n&&(typeof n=="boolean"?s.dataset[o]="":typeof n=="object"?s.dataset[o]=JSON.stringify(n):s.dataset[o]=n)});let i=(r=window.headlessElements)==null?void 0:r.store.get(t);if(!i)throw new Error(`Headless element not found: ${t}`);return new i(s)}createElement(t,e={},...s){let i=Object.assign(document.createElement(t),e);return s&&i.append(...s),i}};var y=class{constructor(){this.dispatcher=document}publish(t){this.dispatcher.dispatchEvent(new CustomEvent(t.name,{detail:t,bubbles:!1,cancelable:!1}))}once(t,e){let s=i=>{this.dispatcher.removeEventListener(t,s),e(i)};this.subscribe(t,s)}subscribe(t,e){this.dispatcher.addEventListener(t,s=>{let i=s;e({name:i.type,data:i.detail.data})})}subscribeMany(t){return Object.entries(t).map(([e,s])=>this.subscribe(e,s))}};window.headlessElements||(window.headlessElements={store:new Map,define(a,t){var e;(e=window.headlessElements)==null||e.store.set(a,t)}});var j=class{constructor({dependencies:t=[],...e}){this.stylesLoaded=!1;this._loaded=!1;this.addToCart=t=>this.state.promise.addToCart(t);this.addAllToCart=t=>this.state.promise.addAllToCart(t);this.addWishlistItem=t=>this.state.promise.addWishlistItem(t);this.clearWishlist=()=>this.state.promise.clearWishlist();this.loadProductInfo=t=>this.state.promise.loadProductInfo(t);this.loadShopifyProduct=t=>this.state.promise.loadShopifyProduct(t);this.loadWishlist=t=>this.state.promise.loadWishlist(t);this.loadWishlistItem=t=>this.state.promise.loadWishlistItem(t);this.publishWishlistEvent=t=>this.state.promise.publishWishlistEvent(t);this.publishWishlistProductEvent=t=>this.state.promise.publishWishlistProductEvent(t);this.removeWishlistItem=t=>this.state.promise.removeWishlistItem(t);this.shareWishlist=t=>this.state.promise.shareWishlist(t);this.updateWishlistItem=t=>this.state.promise.updateWishlistItem(t);this.config=this.parseConfig(e),this.settings=this.parseSettings(e),this.routes=this.parseRoutes(),this.customer=this.config.customer.id?{id:this.config.customer.id,email:this.config.customer.email}:null,this.events=new y,this.theme=new u({rootUrl:this.routes.rootUrl,wishlistUrl:this.routes.wishlistUrl});let{stylesheets:s,scripts:i,iconSetUrl:r,localeUrl:o}=t.reduce(({stylesheets:n,scripts:l,iconSetUrl:c,localeUrl:p},d)=>{let[m]=d.split("?");return m.endsWith(".css")?n.push(d):m.endsWith("icons.js")?c=d:m.endsWith(".js")?l.push(d):m.endsWith(".json")&&(p=d),{stylesheets:n,scripts:l,iconSetUrl:c,localeUrl:p}},{stylesheets:[],scripts:[],iconSetUrl:"",localeUrl:""});this.initStyles({stylesheets:s,iconSetUrl:r,localeUrl:o}),this.initScripts(i),(this.hasSession||this.settings.general.appLoading==="EAGER")&&this.load(),window.WishlistKing=this,this.events.publish({name:"wk:app:created"})}get loaded(){return this._loaded}get state(){return b(this._state)}get apis(){return b(this._apis)}get utils(){return b(this._utils)}get hasSession(){return!!this.getSessionId()||!!this.customer}get isLoggedIn(){var t;return!!((t=this.customer)!=null&&t.id)}getSessionId(){let t=window.localStorage.getItem("wk_session_id");if(t)return t;let e=window.localStorage.getItem("appmate-session");if(e)try{let s=JSON.parse(e).state.sid;return this.setSessionId(s)}catch(s){console.error(s)}}setSessionId(t){var e;return window.localStorage.setItem("wk_session_id",t),(e=this._apis)==null||e.tracking.setSessionId(t),t}async load(){return this._loadPromise?this._loadPromise:this._loadPromise=(async()=>{let[{WishlistState:t},{ShopifyApi:e,WishlistApi:s,TrackingApi:i},{MoneyUtil:r,UrlUtil:o,ProductUtil:n}]=await Promise.all([import("https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/state.js"),import("https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/api.js"),import("https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/utils.js")]);this.initUtils({MoneyUtil:r,UrlUtil:o,ProductUtil:n}),this.initApis({WishlistApi:s,ShopifyApi:e,TrackingApi:i}),this.initState({WishlistState:t}),this.initUrlChangeEvents(),this.trackCurrentPage(),this.hasSession||(await this.state.promise.clearCache(),this.events.once("wk:app:init-sid",l=>{var c,p;(c=l.data)!=null&&c.sessionId&&this.setSessionId((p=l.data)==null?void 0:p.sessionId)})),this._loaded=!0,this.events.publish({name:"wk:app:load:success"})})()}initUtils({UrlUtil:t,MoneyUtil:e,ProductUtil:s}){this._utils={url:new t({rootUrl:this.routes.rootUrl,wishlistUrl:this.routes.wishlistUrl,shopDomain:this.config.shop.domain,placeholderImageUrl:this.config.products.fallbackImage,fileUrl:this.routes.fileUrl}),money:new e({moneyFormat:this.config.shop.moneyFormat,moneyFormatWithCurrency:this.config.shop.moneyFormatWithCurrency}),product:new s}}initApis({WishlistApi:t,ShopifyApi:e,TrackingApi:s}){var i,r;this._apis={wishlist:new t({host:this.config.routes.apiHost,shop:window.Shopify.shop,customerId:(i=this.config.customer.id)!=null?i:void 0,sessionId:this.getSessionId(),trackingSource:this.theme.getPageType(),productMetafields:this.config.products.metafields}),shopify:new e({host:window.Shopify.routes.root.substring(0,window.Shopify.routes.root.length-1)}),tracking:new s({notifyHost:this.config.routes.apiHost,events:this.events,shop:window.Shopify.shop,customerId:(r=this.config.customer.id)!=null?r:void 0,sessionId:this.getSessionId(),utils:this.utils,theme:this.theme,settings:this.settings})}}initState({WishlistState:t}){this._state=new t({wishlistApi:this.apis.wishlist,shopifyApi:this.apis.shopify,settings:this.settings,events:this.events,utils:this.utils})}async initStyles({stylesheets:t,iconSetUrl:e,localeUrl:s}){if(!(t!=null&&t.length)&&!e){this.onStylesLoaded();return}try{await Promise.all([...(t!=null?t:[]).map(i=>new Promise((r,o)=>{let n=document.createElement("link");n.rel="stylesheet",n.href=i,n.onload=r,n.onerror=o,document.head.appendChild(n)})),e?Promise.all([import("https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/components/icon.js"),import(e)]).then(([{Icon:i},{icons:r}])=>{if(typeof r!="object")throw new Error("Icon set must export icons object.");i.addIcons(r)}):Promise.resolve(),s?fetch(s).then(i=>i.json()).then(i=>{this.theme.locale.initLocale(i)}):Promise.resolve()]),this.onStylesLoaded()}catch(i){console.warn(i),this.events.publish({name:"wk:app:load-styles:error"})}}async initScripts(t){if(!(t!=null&&t.length)){this.events.publish({name:"wk:app:load-scripts:success"});return}try{await Promise.all(t.map(e=>import(e))),this.events.publish({name:"wk:app:load-scripts:success"})}catch(e){console.warn(e),this.events.publish({name:"wk:app:load-scripts:error"})}}trackCurrentPage(){if(this.theme.getPageType()==="wishlist"){let e=this.theme.getWishlistId(window.location.pathname);e&&this.publishWishlistEvent({eventName:"wk:wishlist:page-view",wishlistId:e})}}onStylesLoaded(){this.stylesLoaded=!0,this.events.publish({name:"wk:app:load-styles:success"})}initUrlChangeEvents(){let t=history.replaceState,e=({productHandle:s,variantId:i})=>{this.events.publish({name:"wk:product:change-variant:success",data:{productHandle:s,variantId:i}})};history.replaceState=(...s)=>{let i=`${window.location.protocol}//${window.location.host}`,r=typeof s[2]=="string"?new URL(s[2],i):s[2],o=t.apply(history,s);if(!r)return o;let n=this.theme.getProductHandle(r),l=r.searchParams.get("variant");if(!n||!l)return o;e({productHandle:n,variantId:parseInt(l)})}}parseConfig({config:t}){var e,s,i,r,o,n,l,c;return{customer:{id:t.customerId?t.customerId:null,email:(e=t.customerEmail)!=null?e:""},shop:{name:(s=t.shopName)!=null?s:"",domain:(i=t.shopDomain)!=null?i:"",permanentDomain:(r=t.shopPermanentDomain)!=null?r:"",moneyFormat:(o=t.shopMoneyFormat)!=null?o:"",moneyFormatWithCurrency:(n=t.shopMoneyFormatWithCurrency)!=null?n:"",customerAccountsEnabled:t.shopCustomerAccountsEnabled?t.shopCustomerAccountsEnabled==="true":!1},routes:{apiHost:(l=t.apiHost)!=null?l:"https://api.appmate.io/v2",rootUrl:window.Shopify.routes.root,fileUrl:t.fileUrl},products:{fallbackImage:(c=t.productFallbackImage)!=null?c:"//cdn.shopify.com/s/files/1/0533/2089/files/placeholder-images-image_large.png?format=webp&v=1530129081",metafields:!!t.productMetafields}}}parseSettings({settings:t}){var e,s,i,r,o,n,l,c,p,d,m,U,W,v,E,P,S,T,k,I,A,R,L,C,M,H,x;return{general:{appLoading:(s=(e=t==null?void 0:t.general)==null?void 0:e.appLoading)!=null?s:"LAZY",wishlistAccessMode:this.config.customer.id?"UNRESTRICTED":(r=(i=t==null?void 0:t.general)==null?void 0:i.wishlistAccessMode)!=null?r:"UNRESTRICTED",wishlistMode:(n=(o=t==null?void 0:t.general)==null?void 0:o.wishlistMode)!=null?n:"PRODUCT",wishlistPath:(c=(l=t==null?void 0:t.general)==null?void 0:l.wishlistPath)!=null?c:"/apps/wishlist"},money:{withCurrency:(d=(p=t==null?void 0:t.money)==null?void 0:p.withCurrency)!=null?d:!1},integrations:{googleAnalytics:{enabled:(W=(U=(m=t.integrations)==null?void 0:m.googleAnalytics)==null?void 0:U.enabled)!=null?W:!1,tracker:(P=(E=(v=t.integrations)==null?void 0:v.googleAnalytics)==null?void 0:E.tracker)!=null?P:""},klaviyo:{enabled:(k=(T=(S=t.integrations)==null?void 0:S.klaviyo)==null?void 0:T.enabled)!=null?k:!1},metaPixel:{enabled:(R=(A=(I=t.integrations)==null?void 0:I.metaPixel)==null?void 0:A.enabled)!=null?R:!1},wishlistAnalytics:{enabled:(M=(C=(L=t.integrations)==null?void 0:L.metaPixel)==null?void 0:C.enabled)!=null?M:!0}},cache:{wishlist:{ttl:6e4},wishlistItem:{ttl:6e4},productInfo:{ttl:6e4},product:{ttl:3e4}},colorMap:(H=t.colorMap)!=null?H:{},collectionButtons:(x=t.collectionButtons)!=null?x:{}}}parseRoutes(){let t=this.config.routes.rootUrl;return{rootUrl:t,fileUrl:this.config.routes.fileUrl,wishlistUrl:t+this.settings.general.wishlistPath.split("/").filter(e=>!!e).join("/"),accountUrl:t+"account",accountLoginUrl:t+"account/login",accountLogoutUrl:t+"account/logout",accountRegisterUrl:t+"account/register",accountAddressesUrl:t+"account/addresses",collectionsUrl:t+"collections",allProductsCollectionUrl:t+"collections/all",searchUrl:t+"search",predictiveSearchUrl:t+"search/suggest",cartUrl:t+"cart",cartAddUrl:t+"cart/add",cartChangeUrl:t+"cart/change",cartClearUrl:t+"cart/clear",cartUpdateUrl:t+"cart/update",productRecommendationsUrl:t+"recommendations/products"}}},b=a=>{if(!a)throw new Error("Wishlist app not loaded.");return a};export{j as WishlistApp};

@@ -1,216 +0,1 @@

// src/WishlistElementHeadless.ts
import {
delayWhen,
from,
fromEvent,
isObservable,
map,
of
} from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
import { filter, first, switchMap, tap } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
import { WishlistStateController } from "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/controllers.js";
var WishlistElementHeadless = class {
constructor(host) {
this.connected = false;
this.cleanupMethods = [];
this.eventPending = false;
this.firstConnect = true;
this.host = host;
this.stateCtrl = new WishlistStateController(this);
if (this.host.hasAttribute("wk-headless")) {
throw new Error("Headless component already initialised");
}
this.host.setAttribute("wk-headless", "");
this.initEvents();
this.connect();
this.firstConnect = false;
}
get app() {
return this.stateCtrl.app;
}
static get observedAttributes() {
return [
"data-wishlist-id",
"data-wishlist-item-id",
"data-product-handle",
"data-product-id",
"data-variant-id"
];
}
addController(controller) {
}
appReadyCallback() {
if (!this.host.dataset.productHandle) {
return;
}
this.app.events.subscribe("wk:product:change-variant:success", (event) => {
var _a, _b, _c;
if (this.host.dataset.productHandle === ((_a = event.data) == null ? void 0 : _a.productHandle) && ((_b = event.data) == null ? void 0 : _b.variantId)) {
const wishlistItemId = this.productInfo ? this.productInfo.wishlistItemId : void 0;
const currentVariantId = this.productInfo ? this.productInfo.variantId : void 0;
if (wishlistItemId && !currentVariantId) {
this.app.updateWishlistItem({
wishlistItemId,
changes: {
variantId: (_c = event.data) == null ? void 0 : _c.variantId
}
});
}
this.host.dataset.variantId = event.data.variantId.toString();
if (this.connected) {
this.initState();
}
}
});
}
async connect() {
if (this.connected) {
return;
}
if (!this.app.stylesLoaded) {
fromEvent(document, "wk:app:load-styles:success").pipe(first()).subscribe(() => this.connect());
return;
}
this.connected = true;
if (this.app.loaded) {
this.init();
} else if (this.app.hasSession) {
await this.app.load();
this.init();
} else {
this.initFallbackState();
this.app.events.once("wk:app:load:success", () => {
this.init();
});
}
}
getStateConfig() {
return {};
}
init() {
const { loading } = this.getStateConfig();
if (loading === "lazy") {
this.initFallbackState();
this.initObserver();
} else {
this.initState();
this.appReadyCallback();
}
}
updated() {
}
setState(state) {
this.wishlist = state.wishlist;
this.wishlistItem = state.wishlistItem;
this.productInfo = state.productInfo;
this.updated();
}
createRenderRoot() {
return this;
}
initState() {
if (this.subscription) {
this.subscription.unsubscribe();
}
this.subscription = this.stateCtrl.observe().subscribe((state) => {
this.setState(state);
});
}
initFallbackState() {
const fallback = this.stateCtrl.getFallback();
if (fallback) {
this.setState(fallback);
}
}
initObserver() {
var _a;
(_a = this.observer) == null ? void 0 : _a.disconnect();
this.observer = new IntersectionObserver(
(entries) => this.handleIntersect(entries),
{
root: null,
rootMargin: "0px"
}
);
this.host.setAttribute("wk-lazy", "");
this.observer.observe(this.host);
}
handleIntersect([entry]) {
var _a;
if (entry.isIntersecting) {
this.host.removeAttribute("wk-lazy");
(_a = this.observer) == null ? void 0 : _a.disconnect();
this.initState();
this.appReadyCallback();
}
}
getEventConfig() {
return {};
}
initEvents() {
const eventConfig = this.getEventConfig();
if (!eventConfig) {
return;
}
const subscriptions = Object.entries(eventConfig).map(([key, handler]) => {
const [eventName, selector] = key.split(/ (.*)/s);
return this.subscribeToEvent({
eventName,
selector,
handler
});
});
this.cleanupMethods.push(
() => subscriptions.forEach((subscription) => subscription.unsubscribe())
);
}
subscribeToEvent({
eventName,
handler,
selector
}) {
return fromEvent(this.host, eventName).pipe(
tap((event) => {
if (this.eventPending) {
event.preventDefault();
}
}),
filter(() => !this.eventPending),
tap(() => {
this.eventPending = true;
}),
map((event) => {
if (!(event.target instanceof HTMLElement)) {
return { event, target: null };
}
return {
event,
target: selector ? event.target.closest(selector) : event.currentTarget
};
}),
filter(({ target }) => !!target),
delayWhen((input) => {
if (!this.app.hasSession) {
return from(this.app.load());
}
return of(input);
}),
switchMap(({ event, target }) => {
const result = handler.bind(this)(event, target);
if (isObservable(result)) {
return result;
}
if (typeof (result == null ? void 0 : result.then) === "function") {
return from(result);
}
return of(result);
})
).subscribe(() => {
this.eventPending = false;
});
}
};
export {
WishlistElementHeadless
};
//# sourceMappingURL=wishlist-element-headless.js.map
import{delayWhen as p,from as a,fromEvent as o,isObservable as u,map as f,of as h}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";import{filter as l,first as b,switchMap as v,tap as c}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";import{WishlistStateController as g}from"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/controllers.js";var d=class{constructor(t){this.connected=!1;this.cleanupMethods=[];this.eventPending=!1;this.firstConnect=!0;if(this.host=t,this.stateCtrl=new g(this),this.host.hasAttribute("wk-headless"))throw new Error("Headless component already initialised");this.host.setAttribute("wk-headless",""),this.initEvents(),this.connect(),this.firstConnect=!1}get app(){return this.stateCtrl.app}static get observedAttributes(){return["data-wishlist-id","data-wishlist-item-id","data-product-handle","data-product-id","data-variant-id"]}addController(t){}appReadyCallback(){this.host.dataset.productHandle&&this.app.events.subscribe("wk:product:change-variant:success",t=>{var i,n,e;if(this.host.dataset.productHandle===((i=t.data)==null?void 0:i.productHandle)&&((n=t.data)!=null&&n.variantId)){let r=this.productInfo?this.productInfo.wishlistItemId:void 0,s=this.productInfo?this.productInfo.variantId:void 0;r&&!s&&this.app.updateWishlistItem({wishlistItemId:r,changes:{variantId:(e=t.data)==null?void 0:e.variantId}}),this.host.dataset.variantId=t.data.variantId.toString(),this.connected&&this.initState()}})}async connect(){if(!this.connected){if(!this.app.stylesLoaded){o(document,"wk:app:load-styles:success").pipe(b()).subscribe(()=>this.connect());return}this.connected=!0,this.app.loaded?this.init():this.app.hasSession?(await this.app.load(),this.init()):(this.initFallbackState(),this.app.events.once("wk:app:load:success",()=>{this.init()}))}}getStateConfig(){return{}}init(){let{loading:t}=this.getStateConfig();t==="lazy"?(this.initFallbackState(),this.initObserver()):(this.initState(),this.appReadyCallback())}updated(){}setState(t){this.wishlist=t.wishlist,this.wishlistItem=t.wishlistItem,this.productInfo=t.productInfo,this.updated()}createRenderRoot(){return this}initState(){this.subscription&&this.subscription.unsubscribe(),this.subscription=this.stateCtrl.observe().subscribe(t=>{this.setState(t)})}initFallbackState(){let t=this.stateCtrl.getFallback();t&&this.setState(t)}initObserver(){var t;(t=this.observer)==null||t.disconnect(),this.observer=new IntersectionObserver(i=>this.handleIntersect(i),{root:null,rootMargin:"0px"}),this.host.setAttribute("wk-lazy",""),this.observer.observe(this.host)}handleIntersect([t]){var i;t.isIntersecting&&(this.host.removeAttribute("wk-lazy"),(i=this.observer)==null||i.disconnect(),this.initState(),this.appReadyCallback())}getEventConfig(){return{}}initEvents(){let t=this.getEventConfig();if(!t)return;let i=Object.entries(t).map(([n,e])=>{let[r,s]=n.split(/ (.*)/s);return this.subscribeToEvent({eventName:r,selector:s,handler:e})});this.cleanupMethods.push(()=>i.forEach(n=>n.unsubscribe()))}subscribeToEvent({eventName:t,handler:i,selector:n}){return o(this.host,t).pipe(c(e=>{this.eventPending&&e.preventDefault()}),l(()=>!this.eventPending),c(()=>{this.eventPending=!0}),f(e=>e.target instanceof HTMLElement?{event:e,target:n?e.target.closest(n):e.currentTarget}:{event:e,target:null}),l(({target:e})=>!!e),p(e=>this.app.hasSession?h(e):a(this.app.load())),v(({event:e,target:r})=>{let s=i.bind(this)(e,r);return u(s)?s:typeof(s==null?void 0:s.then)=="function"?a(s):h(s)})).subscribe(()=>{this.eventPending=!1})}};export{d as WishlistElementHeadless};

@@ -1,283 +0,1 @@

// src/WishlistElement.ts
import {
delayWhen,
from,
fromEvent,
isObservable,
map,
of
} from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
import { filter, first, switchMap, tap } from "https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";
import { LitElement } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
import { unsafeHTML } from "https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";
import { WishlistStateController } from "https://wishlist-king-sdk.eu.ngrok.io/npm/@appmate/wishlist@4.22.3/controllers.js";
var WishlistElement = class extends LitElement {
constructor() {
super();
this.connected = false;
this.cleanupMethods = [];
this.eventPending = false;
this.firstConnect = true;
this.stateCtrl = new WishlistStateController(this);
}
get app() {
return this.stateCtrl.app;
}
static get observedAttributes() {
return [
...super.observedAttributes,
"data-wishlist-id",
"data-wishlist-item-id",
"data-product-handle",
"data-product-id",
"data-variant-id"
];
}
attributeChangedCallback(name, oldValue, newValue) {
super.attributeChangedCallback(name, oldValue, newValue);
if (this.connected && this.app.loaded) {
this.initState();
}
}
appReadyCallback() {
if (!this.dataset.productHandle) {
return;
}
this.app.events.subscribe("wk:product:change-variant:success", (event) => {
var _a, _b, _c;
if (this.dataset.productHandle === ((_a = event.data) == null ? void 0 : _a.productHandle) && ((_b = event.data) == null ? void 0 : _b.variantId)) {
const wishlistItemId = this.productInfo ? this.productInfo.wishlistItemId : void 0;
const currentVariantId = this.productInfo ? this.productInfo.variantId : void 0;
if (wishlistItemId && !currentVariantId) {
this.app.updateWishlistItem({
wishlistItemId,
changes: {
variantId: (_c = event.data) == null ? void 0 : _c.variantId
}
});
}
this.dataset.variantId = event.data.variantId.toString();
}
});
}
async connect() {
if (this.connected) {
return;
}
if (!window.WishlistKing) {
window.document.addEventListener(
"wk:app:created",
() => {
this.connect();
},
{ once: true }
);
return;
}
if (!this.app.stylesLoaded) {
fromEvent(document, "wk:app:load-styles:success").pipe(first()).subscribe(() => this.connect());
return;
}
this.connected = true;
if (this.app.loaded) {
this.init();
} else if (this.app.hasSession) {
await this.app.load();
this.init();
} else {
this.initFallbackState();
this.app.events.once("wk:app:load:success", () => {
this.init();
});
}
}
getStateConfig() {
return {};
}
getTranslation(id, values) {
if (!this.app.theme) {
return id;
}
const text = this.app.theme.translate(id, values);
if (id.endsWith("_html")) {
return unsafeHTML(text);
}
return text;
}
formatMoney(value, options) {
var _a;
return this.app.utils.money.formatMoney(value, {
withCurrency: (_a = options == null ? void 0 : options.withCurrency) != null ? _a : this.app.settings.money.withCurrency
});
}
renderMoney(value, options) {
return unsafeHTML(this.formatMoney(value, options));
}
getProductUrl(product, variant) {
return this.app.utils.url.getVariantUrl(product.url, variant == null ? void 0 : variant.id);
}
getImageUrl(product, variant, size) {
var _a;
return this.app.utils.url.getImageUrl(
((_a = variant == null ? void 0 : variant.featured_image) == null ? void 0 : _a.src) ? variant : product,
size
);
}
init() {
const { loading } = this.getStateConfig();
if (loading === "lazy") {
this.initFallbackState();
this.initObserver();
} else {
this.initState();
this.appReadyCallback();
}
}
setState(state) {
if (state.wishlist) {
this.wishlist = state.wishlist;
}
if (state.wishlistItem) {
this.wishlistItem = state.wishlistItem;
}
if (state.productInfo) {
this.productInfo = state.productInfo;
}
}
createRenderRoot() {
return this;
}
connectedCallback() {
super.connectedCallback();
if (this.innerHTML && this.firstConnect) {
this.innerHTML = "";
}
this.initEvents();
this.connect();
this.firstConnect = false;
}
disconnectedCallback() {
var _a, _b;
super.disconnectedCallback();
this.cleanupMethods.forEach((cleanup) => cleanup());
this.connected = false;
(_a = this.subscription) == null ? void 0 : _a.unsubscribe();
(_b = this.observer) == null ? void 0 : _b.disconnect();
}
shouldUpdate(changedProperties) {
if (!this.connected) {
return false;
}
return super.shouldUpdate(changedProperties);
}
initState() {
if (this.subscription) {
this.subscription.unsubscribe();
}
this.subscription = this.stateCtrl.observe().subscribe((state) => {
this.setState(state);
});
}
initFallbackState() {
const fallback = this.stateCtrl.getFallback();
if (fallback) {
this.setState(fallback);
}
}
initObserver() {
var _a, _b;
(_a = this.observer) == null ? void 0 : _a.disconnect();
this.observer = new IntersectionObserver(
(entries) => this.handleIntersect(entries),
{
root: null,
rootMargin: "0px"
}
);
this.setAttribute("wk-lazy", "");
this.observer.observe((_b = this.firstElementChild) != null ? _b : this);
}
handleIntersect([entry]) {
var _a;
if (entry.isIntersecting) {
this.removeAttribute("wk-lazy");
(_a = this.observer) == null ? void 0 : _a.disconnect();
this.initState();
this.appReadyCallback();
}
}
getEventConfig() {
return {};
}
initEvents() {
const eventConfig = this.getEventConfig();
if (!eventConfig) {
return;
}
const subscriptions = Object.entries(eventConfig).map(([key, handler]) => {
const [eventName, selector] = key.split(/ (.*)/s);
return this.subscribeToEvent({
eventName,
selector,
handler
});
});
this.cleanupMethods.push(
() => subscriptions.forEach((subscription) => subscription.unsubscribe())
);
}
subscribeToEvent({
eventName,
handler,
selector
}) {
return fromEvent(this, eventName).pipe(
tap((event) => {
if (this.eventPending) {
event.preventDefault();
}
}),
filter(() => !this.eventPending),
tap(() => {
this.eventPending = true;
}),
map((event) => {
if (!(event.target instanceof HTMLElement)) {
return { event, target: null };
}
return {
event,
target: selector ? event.target.closest(selector) : event.currentTarget
};
}),
filter(({ target }) => !!target),
delayWhen((input) => {
if (!this.app.hasSession) {
return from(this.app.load());
}
return of(input);
}),
switchMap(({ event, target }) => {
const result = handler.bind(this)(event, target);
if (isObservable(result)) {
return result;
}
if (typeof (result == null ? void 0 : result.then) === "function") {
return from(result);
}
return of(result);
})
).subscribe(() => {
this.eventPending = false;
});
}
};
WishlistElement.properties = {
wishlist: { state: true },
productInfo: { state: true },
wishlistItem: { state: true }
};
export {
WishlistElement
};
//# sourceMappingURL=wishlist-element.js.map
import{delayWhen as p,from as o,fromEvent as c,isObservable as f,map as b,of as h}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";import{filter as l,first as g,switchMap as m,tap as d}from"https://cdn.jsdelivr.net/npm/rxjs@7.8.0/+esm";import{LitElement as y}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";import{unsafeHTML as u}from"https://cdn.jsdelivr.net/gh/lit/dist@2.7.2/all/lit-all.min.js";import{WishlistStateController as v}from"https://cdn.jsdelivr.net/npm/@appmate/wishlist@4.22.5/controllers.js";var a=class extends y{constructor(){super();this.connected=!1;this.cleanupMethods=[];this.eventPending=!1;this.firstConnect=!0;this.stateCtrl=new v(this)}get app(){return this.stateCtrl.app}static get observedAttributes(){return[...super.observedAttributes,"data-wishlist-id","data-wishlist-item-id","data-product-handle","data-product-id","data-variant-id"]}attributeChangedCallback(t,e,i){super.attributeChangedCallback(t,e,i),this.connected&&this.app.loaded&&this.initState()}appReadyCallback(){this.dataset.productHandle&&this.app.events.subscribe("wk:product:change-variant:success",t=>{var e,i,s;if(this.dataset.productHandle===((e=t.data)==null?void 0:e.productHandle)&&((i=t.data)!=null&&i.variantId)){let n=this.productInfo?this.productInfo.wishlistItemId:void 0,r=this.productInfo?this.productInfo.variantId:void 0;n&&!r&&this.app.updateWishlistItem({wishlistItemId:n,changes:{variantId:(s=t.data)==null?void 0:s.variantId}}),this.dataset.variantId=t.data.variantId.toString()}})}async connect(){if(!this.connected){if(!window.WishlistKing){window.document.addEventListener("wk:app:created",()=>{this.connect()},{once:!0});return}if(!this.app.stylesLoaded){c(document,"wk:app:load-styles:success").pipe(g()).subscribe(()=>this.connect());return}this.connected=!0,this.app.loaded?this.init():this.app.hasSession?(await this.app.load(),this.init()):(this.initFallbackState(),this.app.events.once("wk:app:load:success",()=>{this.init()}))}}getStateConfig(){return{}}getTranslation(t,e){if(!this.app.theme)return t;let i=this.app.theme.translate(t,e);return t.endsWith("_html")?u(i):i}formatMoney(t,e){var i;return this.app.utils.money.formatMoney(t,{withCurrency:(i=e==null?void 0:e.withCurrency)!=null?i:this.app.settings.money.withCurrency})}renderMoney(t,e){return u(this.formatMoney(t,e))}getProductUrl(t,e){return this.app.utils.url.getVariantUrl(t.url,e==null?void 0:e.id)}getImageUrl(t,e,i){var s;return this.app.utils.url.getImageUrl((s=e==null?void 0:e.featured_image)!=null&&s.src?e:t,i)}init(){let{loading:t}=this.getStateConfig();t==="lazy"?(this.initFallbackState(),this.initObserver()):(this.initState(),this.appReadyCallback())}setState(t){t.wishlist&&(this.wishlist=t.wishlist),t.wishlistItem&&(this.wishlistItem=t.wishlistItem),t.productInfo&&(this.productInfo=t.productInfo)}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.innerHTML&&this.firstConnect&&(this.innerHTML=""),this.initEvents(),this.connect(),this.firstConnect=!1}disconnectedCallback(){var t,e;super.disconnectedCallback(),this.cleanupMethods.forEach(i=>i()),this.connected=!1,(t=this.subscription)==null||t.unsubscribe(),(e=this.observer)==null||e.disconnect()}shouldUpdate(t){return this.connected?super.shouldUpdate(t):!1}initState(){this.subscription&&this.subscription.unsubscribe(),this.subscription=this.stateCtrl.observe().subscribe(t=>{this.setState(t)})}initFallbackState(){let t=this.stateCtrl.getFallback();t&&this.setState(t)}initObserver(){var t,e;(t=this.observer)==null||t.disconnect(),this.observer=new IntersectionObserver(i=>this.handleIntersect(i),{root:null,rootMargin:"0px"}),this.setAttribute("wk-lazy",""),this.observer.observe((e=this.firstElementChild)!=null?e:this)}handleIntersect([t]){var e;t.isIntersecting&&(this.removeAttribute("wk-lazy"),(e=this.observer)==null||e.disconnect(),this.initState(),this.appReadyCallback())}getEventConfig(){return{}}initEvents(){let t=this.getEventConfig();if(!t)return;let e=Object.entries(t).map(([i,s])=>{let[n,r]=i.split(/ (.*)/s);return this.subscribeToEvent({eventName:n,selector:r,handler:s})});this.cleanupMethods.push(()=>e.forEach(i=>i.unsubscribe()))}subscribeToEvent({eventName:t,handler:e,selector:i}){return c(this,t).pipe(d(s=>{this.eventPending&&s.preventDefault()}),l(()=>!this.eventPending),d(()=>{this.eventPending=!0}),b(s=>s.target instanceof HTMLElement?{event:s,target:i?s.target.closest(i):s.currentTarget}:{event:s,target:null}),l(({target:s})=>!!s),p(s=>this.app.hasSession?h(s):o(this.app.load())),m(({event:s,target:n})=>{let r=e.bind(this)(s,n);return f(r)?r:typeof(r==null?void 0:r.then)=="function"?o(r):h(r)})).subscribe(()=>{this.eventPending=!1})}};a.properties={wishlist:{state:!0},productInfo:{state:!0},wishlistItem:{state:!0}};export{a as WishlistElement};

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc