@kachingappz/bundles-js 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -200,4 +200,4 @@
200
200
  }
201
201
  }
202
202
  }
203
- `,{variables:{productGID:e.id,cursor:p,reverse:s,...l}}),{nodes:i,pageInfo:u}=d.product.variants;for(const r of i){if(a.has(r.id)){m=!1;break}a.add(r.id),s?o.push(r):n.push(r)}u.hasNextPage||(m=!1),p=u.endCursor}};return await Promise.all([c(!1),c(!0)]),e.variants.nodes=[...n,...o.reverse()],e},U=t=>{var c,s,m,p,d,i;const e=t.variants.nodes.map(({unitPriceMeasurement:u,...r})=>{var f,h;return{id:Number(r.id.split("/").pop()),availableForSale:r.availableForSale,price:Math.round(Number(r.price.amount)*100),compareAtPrice:r.compareAtPrice?Math.round(Number(r.compareAtPrice.amount)*100):null,options:r.selectedOptions.map(g=>g.value),imageId:r.image?Number(r.image.id.split("/").pop()):null,image:((f=r.image)==null?void 0:f.url)||null,sellingPlans:((h=r.sellingPlanAllocations)==null?void 0:h.nodes.map(g=>({id:Number(g.sellingPlan.id.split("/").pop()),price:g.priceAdjustments.length>0?Math.round(Number(g.priceAdjustments[0].price.amount)*100):Math.round(Number(r.price.amount)*100)})))||[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:r.quantityAvailable??null,unitPriceMeasurement:u!=null&&u.quantityUnit&&(u!=null&&u.referenceUnit)?{quantityValue:u.quantityValue,quantityUnit:u.quantityUnit.toLowerCase(),referenceValue:u.referenceValue,referenceUnit:u.referenceUnit.toLowerCase()}:null}}),l=t.options.map((u,r)=>{const f=u.optionValues.map(h=>{var g,y,I,v;return{id:Number(h.id.split("/").pop()),defaultName:h.name,name:h.name,swatch:{color:((g=h.swatch)==null?void 0:g.color)||null,image:((v=(I=(y=h.swatch)==null?void 0:y.image)==null?void 0:I.previewImage)==null?void 0:v.url)||null}}});return{defaultName:u.name,name:u.name,position:r+1,optionValues:V(f,r,e)}}),a=u=>{const r=u.priceAdjustments[0];if(!r)return null;const f=r.adjustmentValue;switch(f.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:f.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"fixed_amount",value:Number(f.adjustmentAmount.amount)*100};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:Number(f.price.amount)*100};default:throw new Error(`Unknown price adjustment type: ${f.__typename}`)}},n=((c=t.sellingPlanGroups)==null?void 0:c.nodes.flatMap(u=>u.sellingPlans.nodes.map(r=>({id:Number(r.id.split("/").pop()),name:r.name,priceAdjustment:a(r)}))))||[],o=t.variants.nodes.some(u=>u.requiresComponents);return{id:Number(t.id.split("/").pop()),handle:t.handle,url:t.onlineStoreUrl,availableForSale:t.availableForSale,createdAt:t.createdAt,title:t.title,image:((s=t.featuredImage)==null?void 0:s.url)||null,collectionIds:t.collections.nodes.map(u=>Number(u.id.split("/").pop())),options:l,selectedVariantId:Number(t.variants.nodes[0].id.split("/").pop()),variants:e,requiresSellingPlan:t.requiresSellingPlan,sellingPlans:n,isNativeBundle:o,metafields:{text:((m=t.metafield)==null?void 0:m.value)||null,text2:((p=t.metafield2)==null?void 0:p.value)||null,text3:((d=t.metafield3)==null?void 0:d.value)||null,text4:((i=t.metafield4)==null?void 0:i.value)||null}}},V=(t,e,l)=>t.filter(a=>l.filter(n=>n.options[e]===a.name).length>0),F=(t,e)=>{const l=[],a=t.filter(s=>s.blockVisibility==="selected-products");for(const s of a)s.selectedProductIds.map(Number).includes(e.id)&&l.push(s);const n=t.filter(s=>s.blockVisibility==="selected-collections");for(const s of n)e.collectionIds.some(m=>s.selectedCollectionIds.map(Number).includes(m))&&l.push(s);const o=t.filter(s=>s.blockVisibility==="excluded-products");for(const s of o)!s.excludedProductIds.map(Number).includes(e.id)&&!(s.excludedCollectionIds||[]).some(m=>e.collectionIds.includes(m))&&l.push(s);const c=t.filter(s=>s.blockVisibility==="all-products");for(const s of c)l.push(s);return l},j=t=>[...z(t),...R(t),...H(t),...J(t),...Q(t),...X(t),...K(t),...W(t),...Y(t),...Z(t)].filter(e=>e!=null&&!e.includes("placeholder")),z=t=>t.dealBars.flatMap(e=>[e.mediaImageGID,e.badgeImageGID]).filter(e=>e!=null),R=t=>t.dealBars.map(({freeGifts:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),H=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>(e||[]).map(l=>l.mediaImageGID)).filter(e=>e!=null),J=t=>t.dealBars.map(({upsells:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),Q=t=>t.swatchOptions?t.swatchOptions.reduce((e,l)=>{const a=l.images.map(n=>n.mediaImageGID).filter(n=>n!=null);return[...e,...a]},[]):[],X=t=>{if(!t.collectionBreaksEnabled||!t.collectionBreaks)return[];const e=t.collectionBreaks.mediaImageGID;return e?[e]:[]},K=t=>{var e,l,a;return t.progressiveGifts?[...((e=t.progressiveGifts.gifts)==null?void 0:e.map(n=>n.mediaImageGID))||[],(l=t.progressiveGifts.style)==null?void 0:l.lockedMediaImageGID,(a=t.progressiveGifts.dealBarStyle)==null?void 0:a.lockedMediaImageGID].filter(n=>n!=null):[]},W=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.mediaImageGID).filter(e=>e!=null),Y=t=>t.dealBars.map(e=>{var l;return(l=e.productPersonalisation)==null?void 0:l.mediaImageGID}).filter(e=>e!=null),Z=t=>t.dealBars.map(e=>{var l;return(l=e.highlights)==null?void 0:l.customIconGID}).filter(e=>e!=null),ee=t=>{const e=[...te(t),...le(t),...se(t),...ae(t),...ne(t),...ie(t),...re(t)];return Array.from(new Set(e.filter(l=>l!=null)))},te=t=>t.dealBars.flatMap(({freeGifts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),le=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>e?e.flatMap(l=>l.products?l.products.map(a=>a.id):[]):[]).filter(e=>e!=null),se=t=>{var e;return t.progressiveGiftsEnabled?((e=t.progressiveGifts)==null?void 0:e.gifts.map(l=>l.productGID).filter(l=>l!=null))||[]:[]},ae=t=>t.dealBars.flatMap(({upsells:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),ne=t=>t.dealBars.filter(e=>e.dealBarType==="bundle").flatMap(({bundleProducts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null).filter(e=>e!=="default"),ie=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.productGID).filter(e=>e!=null),re=t=>t.dealBars.filter(e=>e.dealBarType==="sku").flatMap(({productGID:e})=>e?[e]:[]);class D{constructor(e,l){this.storefrontApiVersion="2025-10",this.storefrontAccessToken=l,this.shopifyDomain=e}async query(e,l){var s;const a=(l==null?void 0:l.variables)??{};let n=`https://${this.shopifyDomain}/api/${this.storefrontApiVersion}/graphql.json`;const o=(s=e.match(/query\s+(\w+)/))==null?void 0:s[1];o&&(n+=`?operation_name=${o}`);const c=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:e,variables:a})})).text();if(!c)throw new Error("Empty graphql response");return JSON.parse(c).data}}const oe=async(t,e,{country:l,language:a})=>{const n=e.collectionBreaks;if(!e.collectionBreaksEnabled||!n)return;let o;n.visibility==="deal-products"?o=await A(t,{country:l,language:a,blockVisibility:e.blockVisibility,excludedProductGIDs:(e.excludedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedProductGIDs:(e.selectedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedCollectionGIDs:(e.selectedCollectionIds||[]).map(s=>`gid://shopify/Collection/${s}`)}):o=await A(t,{country:l,language:a,blockVisibility:n.visibility,excludedProductGIDs:(n.excludedProducts||[]).map(({id:s})=>s),selectedProductGIDs:(n.selectedProducts||[]).map(({id:s})=>s),selectedCollectionGIDs:(n.selectedCollections||[]).map(({id:s})=>s)}),o=o.slice(0,250);let c=await _(t,{country:l,language:a,productIds:o.map(s=>Number(s.split("/").pop())),useExternalMetafieldNamespace:!0});return c=c.filter(s=>s.availableForSale),c},ce=()=>({"system.out_of_stock":"There's not enough items in our stock, please select smaller bundle.","system.invalid_variant":"Sorry, this is not currently available.","system.unavailable_option_value":"Unavailable","system.confirm":"Confirm","system.cancel":"Cancel","system.free":"FREE","system.search":"Search","system.sort_by":"Sort by","system.sort_relevance":"Relevance","system.sort_newest_first":"Newest first","system.sort_price_low_to_high":"Price: Low → High","system.sort_price_high_to_low":"Price: High → Low","system.no_results_found":"No results found","system.no_results_description":"We can't find any item matching your search.","system.clear_search":"Clear search","system.no_products_available":"No products available"}),ue=async(t,{productId:e,dealBlockId:l,country:a,language:n})=>{try{const o=[Number(e.split("/").pop())],c=new D(t.shopifyDomain,t.storefrontAccessToken),s=await q(c,{language:n,country:a,useExternalMetafieldNamespace:!0}),m=s.storefrontAccessToken?new D(s.shopifyDomain,s.storefrontAccessToken):c,[p,d]=await Promise.all([_(m,{country:a,language:n,productIds:o,useExternalMetafieldNamespace:!0}),x(m,{useExternalMetafieldNamespace:!0,useMetaobjects:s.featureFlags.storefront_metaobjects})]),i=p[0];if(!i)return null;const u=F(d,i);let r;if(l?(r=u.find($=>$.id===l||$.nanoId===l),r||(r=u[0])):r=u[0],!r)return null;const f=j(r),h=ee(r),[g,y,I,v]=await Promise.all([_(m,{country:a,language:n,productIds:h,useExternalMetafieldNamespace:!0}),L(m,f,300),oe(m,r,{country:a,language:n}),ce()]);return{product:i,dealBlock:r,config:s,otherProducts:g,mediaImages:y,collectionBreaksProducts:I??[],translations:v}}catch(o){return console.error(o),null}},b="kaching-bundles-block",C=1e4,de="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",me="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",k=new WeakSet,G=async t=>{const e=t.document;if(!t.customElements.get(b)){if(k.has(e))return S(t,b);k.add(e);try{await he(t)}catch(l){throw k.delete(e),l}}},pe=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",fe=()=>pe()?de:me,he=t=>{const e=t.document;return new Promise((l,a)=>{const n=fe();if(e.querySelector(`script[src="${n}"]`)){S(t,b).then(l).catch(a);return}const c=e.createElement("script");c.src=n,c.onload=()=>S(t,b).then(l).catch(a),c.onerror=()=>a(new Error("Failed to load script")),e.head.appendChild(c)})},S=(t,e)=>new Promise((l,a)=>{if(t.customElements.get(e)){l();return}Promise.race([t.customElements.whenDefined(e),new Promise((n,o)=>setTimeout(()=>o(new Error(`Custom element "${e}" failed to register within ${C}ms`)),C))]).then(()=>l()).catch(a)});class ge extends HTMLElement{constructor(){super(...arguments),this.innerElement=null,this.handleItemsChanged=null,this.initializeId=0}static get observedAttributes(){return["selected-variant-id","product-id"]}async connectedCallback(){await this.initialize()}async initialize(){var c,s;const e=++this.initializeId;if(this.cleanup(),this.hasAttribute("demo")){if(await G(window),e!==this.initializeId)return;this.renderInnerElement(N);return}const l=this.getAttribute("shop-domain"),a=this.getAttribute("storefront-token"),n=this.getAttribute("product-id");if(!l||!a||!n)return;const[o]=await Promise.all([ue({shopifyDomain:l,storefrontAccessToken:a},{productId:n,dealBlockId:this.getAttribute("deal-block-id")??void 0,country:((c=this.getAttribute("country"))==null?void 0:c.toUpperCase())??void 0,language:((s=this.getAttribute("language"))==null?void 0:s.toUpperCase())??void 0}),G(window)]);!o||e!==this.initializeId||this.renderInnerElement(o)}renderInnerElement(e){const{config:l,dealBlock:a,product:n,otherProducts:o,mediaImages:c,collectionBreaksProducts:s,translations:m}=e;this.innerElement=document.createElement("kaching-bundles-block"),this.innerElement.setAttribute("deal-block-id",a.id),this.innerElement.setAttribute("config",JSON.stringify(l)),this.innerElement.setAttribute("deal-block",JSON.stringify(a)),this.innerElement.setAttribute("media-images",JSON.stringify(c??[])),this.innerElement.setAttribute("product",JSON.stringify(n)),this.innerElement.setAttribute("other-products",JSON.stringify(o??[])),this.innerElement.setAttribute("collection-breaks-products",JSON.stringify(s??[])),this.innerElement.setAttribute("translations",JSON.stringify(m??{}));const p=this.getAttribute("selected-variant-id");this.innerElement.setAttribute("current-variant-id",String(p?p.split("/").pop():n.variants[0].id)),this.hasAttribute("deal-bars-only")&&this.innerElement.setAttribute("deal-bars-only","");const d=this.innerElement,i=()=>{if(this.innerElement!==d)return;const r=d.items();r&&this.dispatchEvent(new CustomEvent("items-changed",{detail:{items:r},bubbles:!0}))};this.handleItemsChanged=r=>{r.stopPropagation(),i()};const u=this.handleItemsChanged;d.addEventListener("kaching-bundles-block-loaded",()=>{this.innerElement===d&&(d.addEventListener("items-changed",u),i(),this.dispatchEvent(new CustomEvent("loaded",{bubbles:!0})))},{once:!0}),this.appendChild(this.innerElement)}cleanup(){this.handleItemsChanged&&this.innerElement&&(this.innerElement.removeEventListener("items-changed",this.handleItemsChanged),this.handleItemsChanged=null),this.innerElement&&(this.innerElement.remove(),this.innerElement=null)}attributeChangedCallback(e,l,a){l!==a&&this.isConnected&&(e==="product-id"?this.initialize():e==="selected-variant-id"&&this.innerElement&&a&&this.innerElement.setAttribute("current-variant-id",a.includes("/")?String(a.split("/").pop()):a))}items(){return this.innerElement?this.innerElement.items():[]}disconnectedCallback(){this.cleanup(),this.initializeId++}}customElements.define("kaching-bundle-component",ge)})();
203
+ `,{variables:{productGID:e.id,cursor:p,reverse:s,...l}}),{nodes:i,pageInfo:u}=d.product.variants;for(const r of i){if(a.has(r.id)){m=!1;break}a.add(r.id),s?o.push(r):n.push(r)}u.hasNextPage||(m=!1),p=u.endCursor}};return await Promise.all([c(!1),c(!0)]),e.variants.nodes=[...n,...o.reverse()],e},U=t=>{var c,s,m,p,d,i;const e=t.variants.nodes.map(({unitPriceMeasurement:u,...r})=>{var f,h;return{id:Number(r.id.split("/").pop()),availableForSale:r.availableForSale,price:Math.round(Number(r.price.amount)*100),compareAtPrice:r.compareAtPrice?Math.round(Number(r.compareAtPrice.amount)*100):null,options:r.selectedOptions.map(g=>g.value),imageId:r.image?Number(r.image.id.split("/").pop()):null,image:((f=r.image)==null?void 0:f.url)||null,sellingPlans:((h=r.sellingPlanAllocations)==null?void 0:h.nodes.map(g=>({id:Number(g.sellingPlan.id.split("/").pop()),price:g.priceAdjustments.length>0?Math.round(Number(g.priceAdjustments[0].price.amount)*100):Math.round(Number(r.price.amount)*100)})))||[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:r.quantityAvailable??null,unitPriceMeasurement:u!=null&&u.quantityUnit&&(u!=null&&u.referenceUnit)?{quantityValue:u.quantityValue,quantityUnit:u.quantityUnit.toLowerCase(),referenceValue:u.referenceValue,referenceUnit:u.referenceUnit.toLowerCase()}:null}}),l=t.options.map((u,r)=>{const f=u.optionValues.map(h=>{var g,y,I,v;return{id:Number(h.id.split("/").pop()),defaultName:h.name,name:h.name,swatch:{color:((g=h.swatch)==null?void 0:g.color)||null,image:((v=(I=(y=h.swatch)==null?void 0:y.image)==null?void 0:I.previewImage)==null?void 0:v.url)||null}}});return{defaultName:u.name,name:u.name,position:r+1,optionValues:V(f,r,e)}}),a=u=>{const r=u.priceAdjustments[0];if(!r)return null;const f=r.adjustmentValue;switch(f.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:f.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"fixed_amount",value:Number(f.adjustmentAmount.amount)*100};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:Number(f.price.amount)*100};default:throw new Error(`Unknown price adjustment type: ${f.__typename}`)}},n=((c=t.sellingPlanGroups)==null?void 0:c.nodes.flatMap(u=>u.sellingPlans.nodes.map(r=>({id:Number(r.id.split("/").pop()),name:r.name,priceAdjustment:a(r)}))))||[],o=t.variants.nodes.some(u=>u.requiresComponents);return{id:Number(t.id.split("/").pop()),handle:t.handle,url:t.onlineStoreUrl,availableForSale:t.availableForSale,createdAt:t.createdAt,title:t.title,image:((s=t.featuredImage)==null?void 0:s.url)||null,collectionIds:t.collections.nodes.map(u=>Number(u.id.split("/").pop())),options:l,selectedVariantId:Number(t.variants.nodes[0].id.split("/").pop()),variants:e,requiresSellingPlan:t.requiresSellingPlan,sellingPlans:n,isNativeBundle:o,metafields:{text:((m=t.metafield)==null?void 0:m.value)||null,text2:((p=t.metafield2)==null?void 0:p.value)||null,text3:((d=t.metafield3)==null?void 0:d.value)||null,text4:((i=t.metafield4)==null?void 0:i.value)||null}}},V=(t,e,l)=>t.filter(a=>l.filter(n=>n.options[e]===a.name).length>0),F=(t,e)=>{const l=[],a=t.filter(s=>s.blockVisibility==="selected-products");for(const s of a)s.selectedProductIds.map(Number).includes(e.id)&&l.push(s);const n=t.filter(s=>s.blockVisibility==="selected-collections");for(const s of n)e.collectionIds.some(m=>s.selectedCollectionIds.map(Number).includes(m))&&l.push(s);const o=t.filter(s=>s.blockVisibility==="excluded-products");for(const s of o)!s.excludedProductIds.map(Number).includes(e.id)&&!(s.excludedCollectionIds||[]).some(m=>e.collectionIds.includes(m))&&l.push(s);const c=t.filter(s=>s.blockVisibility==="all-products");for(const s of c)l.push(s);return l},j=t=>[...z(t),...R(t),...H(t),...J(t),...Q(t),...X(t),...K(t),...W(t),...Y(t),...Z(t)].filter(e=>e!=null&&!e.includes("placeholder")),z=t=>t.dealBars.flatMap(e=>[e.mediaImageGID,e.badgeImageGID]).filter(e=>e!=null),R=t=>t.dealBars.map(({freeGifts:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),H=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>(e||[]).map(l=>l.mediaImageGID)).filter(e=>e!=null),J=t=>t.dealBars.map(({upsells:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),Q=t=>t.swatchOptions?t.swatchOptions.reduce((e,l)=>{const a=l.images.map(n=>n.mediaImageGID).filter(n=>n!=null);return[...e,...a]},[]):[],X=t=>{if(!t.collectionBreaksEnabled||!t.collectionBreaks)return[];const e=t.collectionBreaks.mediaImageGID;return e?[e]:[]},K=t=>{var e,l,a;return t.progressiveGifts?[...((e=t.progressiveGifts.gifts)==null?void 0:e.map(n=>n.mediaImageGID))||[],(l=t.progressiveGifts.style)==null?void 0:l.lockedMediaImageGID,(a=t.progressiveGifts.dealBarStyle)==null?void 0:a.lockedMediaImageGID].filter(n=>n!=null):[]},W=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.mediaImageGID).filter(e=>e!=null),Y=t=>t.dealBars.map(e=>{var l;return(l=e.productPersonalisation)==null?void 0:l.mediaImageGID}).filter(e=>e!=null),Z=t=>t.dealBars.map(e=>{var l;return(l=e.highlights)==null?void 0:l.customIconGID}).filter(e=>e!=null),ee=t=>{const e=[...te(t),...le(t),...se(t),...ae(t),...ne(t),...ie(t),...re(t)];return Array.from(new Set(e.filter(l=>l!=null)))},te=t=>t.dealBars.flatMap(({freeGifts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),le=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>e?e.flatMap(l=>l.products?l.products.map(a=>a.id):[]):[]).filter(e=>e!=null),se=t=>{var e;return t.progressiveGiftsEnabled?((e=t.progressiveGifts)==null?void 0:e.gifts.map(l=>l.productGID).filter(l=>l!=null))||[]:[]},ae=t=>t.dealBars.flatMap(({upsells:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),ne=t=>t.dealBars.filter(e=>e.dealBarType==="bundle").flatMap(({bundleProducts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null).filter(e=>e!=="default"),ie=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.productGID).filter(e=>e!=null),re=t=>t.dealBars.filter(e=>e.dealBarType==="sku").flatMap(({productGID:e})=>e?[e]:[]);class D{constructor(e,l){this.storefrontApiVersion="2025-10",this.storefrontAccessToken=l,this.shopifyDomain=e}async query(e,l){var s;const a=(l==null?void 0:l.variables)??{};let n=`https://${this.shopifyDomain}/api/${this.storefrontApiVersion}/graphql.json`;const o=(s=e.match(/query\s+(\w+)/))==null?void 0:s[1];o&&(n+=`?operation_name=${o}`);const c=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:e,variables:a})})).text();if(!c)throw new Error("Empty graphql response");return JSON.parse(c).data}}const oe=async(t,e,{country:l,language:a})=>{const n=e.collectionBreaks;if(!e.collectionBreaksEnabled||!n)return;let o;n.visibility==="deal-products"?o=await A(t,{country:l,language:a,blockVisibility:e.blockVisibility,excludedProductGIDs:(e.excludedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedProductGIDs:(e.selectedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedCollectionGIDs:(e.selectedCollectionIds||[]).map(s=>`gid://shopify/Collection/${s}`)}):o=await A(t,{country:l,language:a,blockVisibility:n.visibility,excludedProductGIDs:(n.excludedProducts||[]).map(({id:s})=>s),selectedProductGIDs:(n.selectedProducts||[]).map(({id:s})=>s),selectedCollectionGIDs:(n.selectedCollections||[]).map(({id:s})=>s)}),o=o.slice(0,250);let c=await _(t,{country:l,language:a,productIds:o.map(s=>Number(s.split("/").pop())),useExternalMetafieldNamespace:!0});return c=c.filter(s=>s.availableForSale),c},ce=()=>({"system.out_of_stock":"There's not enough items in our stock, please select smaller bundle.","system.invalid_variant":"Sorry, this is not currently available.","system.unavailable_option_value":"Unavailable","system.confirm":"Confirm","system.cancel":"Cancel","system.free":"FREE","system.search":"Search","system.sort_by":"Sort by","system.sort_relevance":"Relevance","system.sort_newest_first":"Newest first","system.sort_price_low_to_high":"Price: Low → High","system.sort_price_high_to_low":"Price: High → Low","system.no_results_found":"No results found","system.no_results_description":"We can't find any item matching your search.","system.clear_search":"Clear search","system.no_products_available":"No products available"}),ue=async(t,{productId:e,dealBlockId:l,country:a,language:n})=>{try{const o=[Number(e.split("/").pop())],c=new D(t.shopifyDomain,t.storefrontAccessToken),s=await q(c,{language:n,country:a,useExternalMetafieldNamespace:!0}),m=s.storefrontAccessToken?new D(s.shopifyDomain,s.storefrontAccessToken):c,[p,d]=await Promise.all([_(m,{country:a,language:n,productIds:o,useExternalMetafieldNamespace:!0}),x(m,{useExternalMetafieldNamespace:!0,useMetaobjects:s.featureFlags.storefront_metaobjects})]),i=p[0];if(!i)return null;const u=F(d,i);let r;if(l?(r=u.find($=>$.id===l||$.nanoId===l),r||(r=u[0])):r=u[0],!r)return null;const f=j(r),h=ee(r),[g,y,I,v]=await Promise.all([_(m,{country:a,language:n,productIds:h,useExternalMetafieldNamespace:!0}),L(m,f,300),oe(m,r,{country:a,language:n}),ce()]);return{product:i,dealBlock:r,config:s,otherProducts:g,mediaImages:y,collectionBreaksProducts:I??[],translations:v}}catch(o){return console.error(o),null}},b="kaching-bundles-block",C=1e4,de="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",me="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",k=new WeakSet,G=async t=>{const e=t.document;if(!t.customElements.get(b)){if(k.has(e))return S(t,b);k.add(e);try{await he(t)}catch(l){throw k.delete(e),l}}},pe=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",fe=()=>pe()?de:me,he=t=>{const e=t.document;return new Promise((l,a)=>{const n=fe();if(e.querySelector(`script[src="${n}"]`)){S(t,b).then(l).catch(a);return}const c=e.createElement("script");c.src=n,c.onload=()=>S(t,b).then(l).catch(a),c.onerror=()=>a(new Error("Failed to load script")),e.head.appendChild(c)})},S=(t,e)=>new Promise((l,a)=>{if(t.customElements.get(e)){l();return}Promise.race([t.customElements.whenDefined(e),new Promise((n,o)=>setTimeout(()=>o(new Error(`Custom element "${e}" failed to register within ${C}ms`)),C))]).then(()=>l()).catch(a)});class ge extends HTMLElement{constructor(){super(...arguments),this.innerElement=null,this.handleItemsChanged=null,this.initializeId=0}static get observedAttributes(){return["selected-variant-id","product-id"]}async connectedCallback(){await this.initialize()}async initialize(){var c,s;const e=++this.initializeId;if(this.cleanup(),this.hasAttribute("demo")){if(await G(window),e!==this.initializeId)return;this.renderInnerElement(N);return}const l=this.getAttribute("shop-domain"),a=this.getAttribute("storefront-token"),n=this.getAttribute("product-id");if(!l||!a||!n)return;const[o]=await Promise.all([ue({shopifyDomain:l,storefrontAccessToken:a},{productId:n,dealBlockId:this.getAttribute("deal-block-id")??void 0,country:((c=this.getAttribute("country"))==null?void 0:c.toUpperCase())??void 0,language:((s=this.getAttribute("language"))==null?void 0:s.toUpperCase())??void 0}),G(window)]);!o||e!==this.initializeId||this.renderInnerElement(o)}renderInnerElement(e){const{config:l,dealBlock:a,product:n,otherProducts:o,mediaImages:c,collectionBreaksProducts:s,translations:m}=e;this.innerElement=document.createElement("kaching-bundles-block"),this.innerElement.setAttribute("deal-block-id",a.id),this.innerElement.setAttribute("config",JSON.stringify(l)),this.innerElement.setAttribute("deal-block",JSON.stringify(a)),this.innerElement.setAttribute("media-images",JSON.stringify(c??[])),this.innerElement.setAttribute("product",JSON.stringify(n)),this.innerElement.setAttribute("other-products",JSON.stringify(o??[])),this.innerElement.setAttribute("collection-breaks-products",JSON.stringify(s??[])),this.innerElement.setAttribute("translations",JSON.stringify(m??{}));const p=this.getAttribute("selected-variant-id");this.innerElement.setAttribute("current-variant-id",String(p?p.split("/").pop():n.variants[0].id)),this.hasAttribute("compact")&&this.innerElement.setAttribute("compact","");const d=this.innerElement,i=()=>{if(this.innerElement!==d)return;const r=d.items();r&&this.dispatchEvent(new CustomEvent("items-changed",{detail:{items:r},bubbles:!0}))};this.handleItemsChanged=r=>{r.stopPropagation(),i()};const u=this.handleItemsChanged;d.addEventListener("kaching-bundles-block-loaded",()=>{this.innerElement===d&&(d.addEventListener("items-changed",u),this.dispatchEvent(new CustomEvent("loaded",{bubbles:!0})))},{once:!0}),this.appendChild(this.innerElement)}cleanup(){this.handleItemsChanged&&this.innerElement&&(this.innerElement.removeEventListener("items-changed",this.handleItemsChanged),this.handleItemsChanged=null),this.innerElement&&(this.innerElement.remove(),this.innerElement=null)}attributeChangedCallback(e,l,a){l!==a&&this.isConnected&&(e==="product-id"?this.initialize():e==="selected-variant-id"&&this.innerElement&&a&&this.innerElement.setAttribute("current-variant-id",a.includes("/")?String(a.split("/").pop()):a))}items(){return this.innerElement?this.innerElement.items():[]}disconnectedCallback(){this.cleanup(),this.initializeId++}}customElements.define("kaching-bundle-component",ge)})();
@@ -1137,7 +1137,7 @@ class Ie extends HTMLElement {
1137
1137
  this.innerElement.setAttribute(
1138
1138
  "current-variant-id",
1139
1139
  String(p ? p.split("/").pop() : n.variants[0].id)
1140
- ), this.hasAttribute("deal-bars-only") && this.innerElement.setAttribute("deal-bars-only", "");
1140
+ ), this.hasAttribute("compact") && this.innerElement.setAttribute("compact", "");
1141
1141
  const d = this.innerElement, i = () => {
1142
1142
  if (this.innerElement !== d) return;
1143
1143
  const r = d.items();
@@ -1155,7 +1155,7 @@ class Ie extends HTMLElement {
1155
1155
  d.addEventListener(
1156
1156
  "kaching-bundles-block-loaded",
1157
1157
  () => {
1158
- this.innerElement === d && (d.addEventListener("items-changed", u), i(), this.dispatchEvent(new CustomEvent("loaded", { bubbles: !0 })));
1158
+ this.innerElement === d && (d.addEventListener("items-changed", u), this.dispatchEvent(new CustomEvent("loaded", { bubbles: !0 })));
1159
1159
  },
1160
1160
  { once: !0 }
1161
1161
  ), this.appendChild(this.innerElement);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kachingappz/bundles-js",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "main": "./dist/bundles-js.js",
6
6
  "module": "./dist/bundles-js.js",
@@ -13,7 +13,8 @@
13
13
  }
14
14
  },
15
15
  "files": [
16
- "dist"
16
+ "dist",
17
+ "README.md"
17
18
  ],
18
19
  "scripts": {
19
20
  "dev": "vite",