@kachingappz/bundles-js 1.1.1 → 1.1.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.
- package/dist/bundles-js.iife.js +2 -2
- package/dist/index.d.ts +3 -4
- package/dist/index.js +7 -8
- package/dist/kaching-bundle-component/index.d.ts +3 -4
- package/dist/kaching-bundle-component/index.js +158 -156
- package/dist/react/index.cjs +12 -12
- package/dist/react/index.d.ts +3 -4
- package/dist/react/index.js +114 -115
- package/package.json +1 -1
package/dist/bundles-js.iife.js
CHANGED
|
@@ -225,5 +225,5 @@ var BundlesJs=(function(A){"use strict";const z=(e,t)=>{const a=[],s=e.filter(r=
|
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
227
|
}
|
|
228
|
-
`,{variables:{mediaImageIds:i,size:a}})))).flatMap(i=>i.nodes).
|
|
229
|
-
`));return n.data}if("request"in this.storefront)return(await this.storefront.request(t,a)).data;if("shopifyDomain"in this.storefront&&"storefrontAccessToken"in this.storefront){const n=await fetch(`https://${this.storefront.shopifyDomain}/api/${Ce}/graphql.json`,{body:JSON.stringify({query:t,variables:a==null?void 0:a.variables}),headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefront.storefrontAccessToken},method:"POST"});if(!n.ok)throw new Error(n.statusText);return(await n.json()).data}else{const n=await fetch(this.storefront.getStorefrontApiUrl(),{body:JSON.stringify({query:t,variables:a==null?void 0:a.variables}),headers:this.storefront.getPublicTokenHeaders(),method:"POST"});if(!n.ok)throw new Error(n.statusText);return(await n.json()).data}}get i18n(){if("i18n"in this.storefront)return this.storefront.i18n}}const w="kaching-bundles-block",V=1e4,xe="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",Ge="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",D=new WeakSet,F=async e=>{const t=e.document;if(!e.customElements.get(w)){if(D.has(t))return C(e,w);D.add(t);try{await Me(e)}catch(a){throw D.delete(t),a}}},Te=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",Be=()=>Te()?xe:Ge,Me=e=>{const t=e.document;return new Promise((a,s)=>{const n=Be();if(t.querySelector(`script[src="${n}"]`)){C(e,w).then(a).catch(s);return}const o=t.createElement("script");o.src=n,o.onload=()=>C(e,w).then(a).catch(s),o.onerror=()=>s(new Error("Failed to load script")),t.head.appendChild(o)})},C=(e,t)=>new Promise((a,s)=>{if(e.customElements.get(t)){a();return}Promise.race([e.customElements.whenDefined(t),new Promise((n,i)=>setTimeout(()=>i(new Error(`Custom element "${t}" failed to register within ${V}ms`)),V))]).then(()=>a()).catch(s)});var E=(e=>(e.QuantityBreak="quantity-break",e.Bxgy="bxgy",e.Bundle="bundle",e.MixAndMatch="mix-and-match",e.Sku="sku",e))(E||{});const qe={id:1,handle:"example-product",url:null,availableForSale:!0,title:"Example product",image:null,collectionIds:[],options:[],selectedVariantId:1,variants:[{id:1,availableForSale:!0,price:8e3,compareAtPrice:null,options:["Default Title"],imageId:null,image:null,unitPriceMeasurement:null,sellingPlans:[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:50}],metafields:{text:null,text2:null,text3:null,text4:null},requiresSellingPlan:!1,sellingPlans:[],isNativeBundle:!1},Oe={id:"example",nanoId:"example",blockName:"Bundle",discountName:"",blockTitle:"BUNDLE & SAVE",blockLayout:"vertical",blockVisibility:"all-products",marketId:null,currency:null,excludeB2bCustomers:!1,excludePos:!1,startTimestamp:0,endTimestamp:null,differentVariantsEnabled:!0,hideVariantPicker:!0,disableVariantOptionSync:!1,hideUnavailableOptions:!1,showPricesPerItem:!1,showBothPrices:!1,unitLabel:"",useProductCompareAtPrice:!0,showPricesWithoutDecimals:!1,priceRounding:!1,priceRoundingPrecision:".00",updateNativePrice:!1,updateNativePriceType:"item",skipCart:!1,showVariantsForSingleQuantity:!1,preselectedDealBarId:"duo",cornerRadius:16,spacing:1,selectedProductIds:[],selectedCollectionIds:[],excludedProductIds:[],excludedCollectionIds:[],colors:{background:{red:245,green:245,blue:245,alpha:1},selectedBackground:{red:255,green:255,blue:255,alpha:1},border:{red:0,green:0,blue:0,alpha:1},blockTitle:{red:0,green:0,blue:0,alpha:1},title:{red:0,green:0,blue:0,alpha:1},subtitle:{red:85,green:85,blue:85,alpha:1},price:{red:0,green:0,blue:0,alpha:1},fullPrice:{red:85,green:85,blue:85,alpha:1},labelBackground:{red:171,green:239,blue:198,alpha:1},label:{red:0,green:0,blue:0,alpha:1},badgeBackground:{red:0,green:0,blue:0,alpha:1},badgeText:{red:255,green:255,blue:255,alpha:1},freeGiftBackground:{red:0,green:0,blue:0,alpha:.3},freeGiftText:{red:0,green:0,blue:0,alpha:1},freeGiftSelectedBackground:{red:0,green:0,blue:0,alpha:1},freeGiftSelectedText:{red:255,green:255,blue:255,alpha:1},upsellBackground:{red:0,green:0,blue:0,alpha:.2},upsellText:{red:0,green:0,blue:0,alpha:1},upsellSelectedBackground:{red:0,green:0,blue:0,alpha:.2},upsellSelectedText:{red:0,green:0,blue:0,alpha:1}},fonts:{blockTitle:{size:"14",style:"bold"},title:{size:"20",style:"bold"},subtitle:{size:"14",style:"regular"},label:{size:"12",style:"bold"},freeGift:{size:"13",style:"bold"},upsell:{size:"13",style:"bold"},unitLabel:{size:"14",style:"regular"}},dealBars:[{id:"single",dealBarType:E.QuantityBreak,quantitySelector:!1,title:"Single",subtitle:"Standard price",label:"",quantity:1,discountType:"default",discountValue:"",badgeStyle:"simple",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null,highlights:null,sellingPlanEnabled:!1,sellingPlanGid:null},{id:"duo",dealBarType:E.QuantityBreak,quantitySelector:!1,title:"Duo",subtitle:"You save 20%",label:"SAVE $32",quantity:2,discountType:"percentage",discountValue:"20",badgeStyle:"most-popular",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null,highlights:null,sellingPlanEnabled:!1,sellingPlanGid:null},{id:"trio",dealBarType:E.QuantityBreak,quantitySelector:!1,title:"Trio",subtitle:"You save 25%",label:"SAVE $60",quantity:3,discountType:"percentage",discountValue:"25",badgeStyle:"simple",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null,highlights:null,sellingPlanEnabled:!1,sellingPlanGid:null}],badgesEnabled:!0,badges:[{id:"bdg1",attachedTo:{type:"dealBar",dealBarId:"duo"},text:"MOST POPULAR",colors:null,badgeType:"most-popular",size:90}],swatchOptions:[],swatchSize:18,swatchShape:"circle",imageSize:48,imageCornerRadius:6,defaultVariantsV2:[],collectionBreaksEnabled:!1,collectionBreaks:null,chooseProductModal:null,timerEnabled:!1,timer:null,subscriptionsEnabled:!1,subscriptions:null,stickyAtcEnabled:!1,stickyAtc:null,progressiveGiftsEnabled:!1,progressiveGifts:null,checkboxUpsellsEnabled:!1,checkboxUpsells:null,customStylesEnabled:!1,shopCustomStyles:"",customStyles:"",lowStockAlertEnabled:!1,lowStockAlert:null},je={config:{shopifyDomain:"",moneyFormat:"${{amount}}",locale:"en",country:"US",currencyRate:1,marketId:0,productId:null,storefrontAccessToken:null,includeSellingPlans:!1,includeAvailableQuantity:!1,customApiHost:null,keepQuantityInput:!1,ignoreDeselect:!1,ignoreUnitPrice:!1,requireCustomerLogin:!1,abTestsRunning:!1,webPixel:!1,b2bCustomer:!1,isLoggedIn:!1,preview:!0,previewAlerts:!1,previewScratchOff:!1,defaultTranslations:{"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.quantity":"Quantity","system.subscription_plan":"Subscription plan","system.remove":"Remove","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","system.original_price":"Original price:","system.price":"Price:","system.letters_only":"Only letters are allowed.","system.numbers_only":"Only numbers are allowed."},customSelectors:{quantity:null,addToCartButton:null,variantPicker:null,price:null,priceCompare:null},featureFlags:{},shopCustomStyles:""},dealBlock:Oe,product:qe,otherProducts:[],mediaImages:[],collectionBreaksProducts:[],translations:{}};class Le extends HTMLElement{constructor(){super(...arguments),this.innerElement=null,this.handleItemsChanged=null,this.initializeId=0}static get observedAttributes(){return["selected-variant-id","product-id","country","language"]}async connectedCallback(){await this.initialize()}async initialize(){var o,r;const t=++this.initializeId;if(this.cleanup(),this.hasAttribute("demo")){if(await F(window),t!==this.initializeId)return;this.renderInnerElement(je);return}const a=this.getAttribute("shop-domain"),s=this.getAttribute("storefront-token"),n=this.getAttribute("product-id");if(!a||!s||!n)return;const[i]=await Promise.all([U({shopifyDomain:a,storefrontAccessToken:s},{productId:n,dealBlockId:this.getAttribute("deal-block-id")??void 0,country:((o=this.getAttribute("country"))==null?void 0:o.toUpperCase())??void 0,language:((r=this.getAttribute("language"))==null?void 0:r.toUpperCase())??void 0}),F(window)]);!i||t!==this.initializeId||this.renderInnerElement(i)}renderInnerElement(t){const{config:a,dealBlock:s,product:n,otherProducts:i,mediaImages:o,collectionBreaksProducts:r,translations:m}=t;this.innerElement=document.createElement("kaching-bundles-block"),this.innerElement.setAttribute("deal-block-id",s.id),this.innerElement.setAttribute("config",JSON.stringify(a)),this.innerElement.setAttribute("deal-block",JSON.stringify(s)),this.innerElement.setAttribute("media-images",JSON.stringify(o??[])),this.innerElement.setAttribute("product",JSON.stringify(n)),this.innerElement.setAttribute("other-products",JSON.stringify(i??[])),this.innerElement.setAttribute("collection-breaks-products",JSON.stringify(r??[])),this.innerElement.setAttribute("translations",JSON.stringify(m??{}));const c=this.getAttribute("selected-variant-id");this.innerElement.setAttribute("current-variant-id",String(c?c.split("/").pop():n.variants[0].id)),this.hasAttribute("compact")&&this.innerElement.setAttribute("compact","");const u=this.innerElement,h=()=>{if(this.innerElement!==u)return;const f=u.items();f&&this.dispatchEvent(new CustomEvent("items-changed",{detail:{items:f},bubbles:!0}))};this.handleItemsChanged=f=>{f.stopPropagation(),h()};const g=this.handleItemsChanged;u.addEventListener("kaching-bundles-block-loaded",()=>{this.innerElement===u&&(u.addEventListener("items-changed",g),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(t,a,s){a!==s&&this.isConnected&&(t==="product-id"||t==="country"||t==="language"?this.initialize():t==="selected-variant-id"&&this.innerElement&&s&&this.innerElement.setAttribute("current-variant-id",s.includes("/")?String(s.split("/").pop()):s))}items(){return this.innerElement?this.innerElement.items():[]}disconnectedCallback(){this.cleanup(),this.initializeId++}}return customElements.define("kaching-bundle-component",Le),A.fetchKachingBundlesData=U,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),A})({});
|
|
228
|
+
`,{variables:{mediaImageIds:i,size:a}})))).flatMap(i=>i.nodes).flatMap(i=>i!=null&&i.image?[{gid:i.id,url:i.image.url}]:[])};var S=(e=>(e.QuantityBreak="quantity-break",e.Bxgy="bxgy",e.Bundle="bundle",e.MixAndMatch="mix-and-match",e.Sku="sku",e))(S||{});const ae=e=>[...se(e),...ne(e),...le(e),...re(e),...ie(e),...oe(e),...ce(e),...ue(e),...de(e),...me(e),...pe(e),...fe(e),...he(e)].filter(t=>t!=null&&!t.includes("placeholder")),se=e=>e.dealBars.flatMap(t=>[t.mediaImageGID,t.badgeImageGID]).filter(t=>t!=null),ne=e=>e.dealBars.flatMap(t=>t.dealBarType===S.Bundle?t.bundleProducts.map(a=>a.mediaImageGID):[]).filter(t=>t!=null),le=e=>e.dealBars.map(({freeGifts:t})=>(t||[]).map(a=>a.mediaImageGID)).reduce((t,a)=>t.concat(a),[]).filter(t=>t!=null),re=e=>e.dealBars.flatMap(({multipleGiftsSelectors:t})=>(t||[]).map(a=>a.mediaImageGID)).filter(t=>t!=null),ie=e=>e.dealBars.map(({upsells:t})=>(t||[]).map(a=>a.mediaImageGID)).reduce((t,a)=>t.concat(a),[]).filter(t=>t!=null),oe=e=>e.swatchOptions?e.swatchOptions.reduce((t,a)=>{const s=a.images.map(n=>n.mediaImageGID).filter(n=>n!=null);return[...t,...s]},[]):[],ce=e=>{if(!e.collectionBreaksEnabled||!e.collectionBreaks)return[];const t=e.collectionBreaks.mediaImageGID;return t?[t]:[]},ue=e=>{var t,a,s;return e.progressiveGifts?[...((t=e.progressiveGifts.gifts)==null?void 0:t.map(n=>n.mediaImageGID))||[],(a=e.progressiveGifts.style)==null?void 0:a.lockedMediaImageGID,(s=e.progressiveGifts.dealBarStyle)==null?void 0:s.lockedMediaImageGID].filter(n=>n!=null):[]},de=e=>!e.checkboxUpsellsEnabled||!e.checkboxUpsells?[]:e.checkboxUpsells.upsells.flatMap(t=>[t.mediaImageGID,t.badgeImageGID]).filter(t=>t!=null),me=e=>e.dealBars.map(t=>{var a;return(a=t.productPersonalisation)==null?void 0:a.mediaImageGID}).filter(t=>t!=null),pe=e=>{var s,n;const t=e.dealBars.map(i=>{var o;return(o=i.highlights)==null?void 0:o.customIconGID}).filter(i=>i!=null),a=(n=(s=e.subscriptions)==null?void 0:s.highlights)==null?void 0:n.customIconGID;return a?[...t,a]:t},fe=e=>(e.badges||[]).flatMap(t=>t.badgeType==="custom"&&t.imageGID?[t.imageGID]:[]),he=e=>!e.savingsSummaryEnabled||!e.savingsSummary?[]:e.savingsSummary.customIconGID?[e.savingsSummary.customIconGID]:[],ge=e=>{const t=[...ye(e),...be(e),...ve(e),...Ie(e),..._e(e),...Pe(e),...Se(e),...ke(e)];return Array.from(new Set(t.filter(a=>a!=null)))},ye=e=>e.dealBars.flatMap(({freeGifts:t})=>t?t.map(a=>a.productGID):[]).filter(t=>t!=null),be=e=>e.dealBars.flatMap(({multipleGiftsSelectors:t})=>t?t.flatMap(a=>a.products?a.products.map(s=>s.id):[]):[]).filter(t=>t!=null),ve=e=>{var t;return e.progressiveGiftsEnabled?((t=e.progressiveGifts)==null?void 0:t.gifts.map(a=>a.productGID).filter(a=>a!=null))||[]:[]},Ie=e=>e.dealBars.flatMap(({upsells:t})=>t?t.map(a=>a.productGID):[]).filter(t=>t!=null),_e=e=>e.dealBars.filter(t=>t.dealBarType===S.Bundle).flatMap(({bundleProducts:t})=>t?t.map(a=>a.productGID):[]).filter(t=>t!=null).filter(t=>t!=="default"),Pe=e=>e.dealBars.filter(t=>t.dealBarType===S.MixAndMatch).flatMap(({bundleProducts:t})=>t?t.flatMap(a=>{var s;return[a.productGID,...((s=a.selectedProducts)==null?void 0:s.map(n=>n.id))??[]]}):[]).filter(t=>t!=null).filter(t=>t!=="default"),Se=e=>!e.checkboxUpsellsEnabled||!e.checkboxUpsells?[]:e.checkboxUpsells.upsells.map(t=>t.productGID).filter(t=>t!=null),ke=e=>e.dealBars.filter(t=>t.dealBarType===S.Sku).flatMap(({productGID:t})=>t?[t]:[]);class j extends Error{constructor({status:t,operationName:a,graphqlErrors:s}){const n=s.length?`: ${s.join("; ")}`:"";super(`Storefront API ${a??"query"} failed (HTTP ${t})${n}`),this.name="StorefrontApiError",this.status=t,this.operationName=a,this.graphqlErrors=s}}const we=async(e,t)=>{const a=await e.text();if(!a)throw new Error("Empty graphql response");let s;try{s=JSON.parse(a)}catch(n){throw e.ok?n:new j({status:e.status,operationName:t,graphqlErrors:[]})}if(!e.ok||s.data===null||s.data===void 0)throw new j({status:e.status,operationName:t,graphqlErrors:(s.errors??[]).map(({message:n})=>n).filter(Boolean)});return s.data};class Ee{constructor(t,a){this.storefrontApiVersion="2026-07",this.storefrontAccessToken=a,this.shopifyDomain=t}async query(t,a){var r;const s=(a==null?void 0:a.variables)??{};let n=`https://${this.shopifyDomain}/api/${this.storefrontApiVersion}/graphql.json`;const i=(r=t.match(/query\s+(\w+)/))==null?void 0:r[1];i&&(n+=`?operation_name=${i}`);const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:t,variables:s})});return we(o,i)}}const Ae=async(e,t,{country:a,language:s})=>{const n=t.collectionBreaks;if(!t.collectionBreaksEnabled||!n)return;let i;n.visibility==="deal-products"?i=await T(e,{country:a,language:s,blockVisibility:t.blockVisibility,excludedProductGIDs:(t.excludedProductIds||[]).map(r=>`gid://shopify/Product/${r}`),selectedProductGIDs:(t.selectedProductIds||[]).map(r=>`gid://shopify/Product/${r}`),selectedCollectionGIDs:(t.selectedCollectionIds||[]).map(r=>`gid://shopify/Collection/${r}`)}):i=await T(e,{country:a,language:s,blockVisibility:n.visibility,excludedProductGIDs:(n.excludedProducts||[]).map(({id:r})=>r),selectedProductGIDs:(n.selectedProducts||[]).map(({id:r})=>r),selectedCollectionGIDs:(n.selectedCollections||[]).map(({id:r})=>r)});let o=await $(e,{country:a,language:s,productIds:i.map(r=>Number(r.split("/").pop())),useExternalMetafieldNamespace:!0});return o=o.filter(r=>r.availableForSale),o},$e=({language:e,dealBlockId:t})=>{const a={"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.quantity":"Quantity","system.subscription_plan":"Subscription plan","system.remove":"Remove","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","system.original_price":"Original price:","system.price":"Price:","system.letters_only":"Only letters are allowed.","system.numbers_only":"Only numbers are allowed.","system.personalisation_required_alert":"Please add personalisation for every item to continue."},s=e?De(e):void 0;return{...a,...s==null?void 0:s.system,...s==null?void 0:s.dealBlocks[t]}},De=e=>{var n;if(typeof document>"u")return;const t=document.querySelector("script#kaching-bundles-translations");if(!(t!=null&&t.textContent))return;let a;try{a=JSON.parse(t.textContent)}catch{return}const s=L(e);return(n=a.find(i=>L(i.locale)===s))==null?void 0:n.translations},L=e=>e.toLowerCase().replace(/_/g,"-"),Ce="2026-07",U=async(e,{productId:t,dealBlockId:a,country:s=void 0,language:n=void 0})=>{var i,o;try{const r=[Number(t.split("/").pop())],m=new Ne(e);s=s||((i=m.i18n)==null?void 0:i.country),n=n||((o=m.i18n)==null?void 0:o.language);const c=await Z(m,{language:n,country:s,useExternalMetafieldNamespace:!0});m.shopifyDomain=c.shopifyDomain;const u=c.storefrontAccessToken?new Ee(c.shopifyDomain,c.storefrontAccessToken):m,[h,g]=await Promise.all([$(u,{country:s,language:n,productIds:r,useExternalMetafieldNamespace:!0}),X(u,{useExternalMetafieldNamespace:!0,useMetaobjects:c.featureFlags.storefront_metaobjects})]),f=h[0];if(!f)return null;const v=z(g,f);let l;if(a?(l=v.find(P=>P.id===a||P.nanoId===a),l||(l=v[0])):l=v[0],!l)return null;const d=ae(l),y=ge(l),[_,I,p,b]=await Promise.all([$(u,{country:s,language:n,productIds:y,useExternalMetafieldNamespace:!0}),te(u,d,300),Ae(u,l,{country:s,language:n}),$e({language:n,dealBlockId:l.id})]);return{product:f,dealBlock:l,config:c,otherProducts:_,mediaImages:I,collectionBreaksProducts:p??[],translations:b}}catch(r){return console.error(r),null}};class Ne{constructor(t){this.storefront=t,this.shopifyDomain=""}async query(t,a){var s;if("query"in this.storefront&&"i18n"in this.storefront)return await this.storefront.query(t,a);if("graphql"in this.storefront){const n=await this.storefront.graphql(t,a);if((s=n.errors)!=null&&s.length)throw new Error(n.errors.map(i=>i.message).join(`
|
|
229
|
+
`));return n.data}if("request"in this.storefront)return(await this.storefront.request(t,a)).data;if("shopifyDomain"in this.storefront&&"storefrontAccessToken"in this.storefront){const n=await fetch(`https://${this.storefront.shopifyDomain}/api/${Ce}/graphql.json`,{body:JSON.stringify({query:t,variables:a==null?void 0:a.variables}),headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefront.storefrontAccessToken},method:"POST"});if(!n.ok)throw new Error(n.statusText);return(await n.json()).data}else{const n=await fetch(this.storefront.getStorefrontApiUrl(),{body:JSON.stringify({query:t,variables:a==null?void 0:a.variables}),headers:this.storefront.getPublicTokenHeaders(),method:"POST"});if(!n.ok)throw new Error(n.statusText);return(await n.json()).data}}get i18n(){if("i18n"in this.storefront)return this.storefront.i18n}}const w="kaching-bundles-block",V=1e4,xe="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",Ge="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",D=new WeakSet,F=async e=>{const t=e.document;if(!e.customElements.get(w)){if(D.has(t))return C(e,w);D.add(t);try{await Me(e)}catch(a){throw D.delete(t),a}}},Te=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",Be=()=>Te()?xe:Ge,Me=e=>{const t=e.document;return new Promise((a,s)=>{const n=Be();if(t.querySelector(`script[src="${n}"]`)){C(e,w).then(a).catch(s);return}const o=t.createElement("script");o.src=n,o.onload=()=>C(e,w).then(a).catch(s),o.onerror=()=>s(new Error("Failed to load script")),t.head.appendChild(o)})},C=(e,t)=>new Promise((a,s)=>{if(e.customElements.get(t)){a();return}Promise.race([e.customElements.whenDefined(t),new Promise((n,i)=>setTimeout(()=>i(new Error(`Custom element "${t}" failed to register within ${V}ms`)),V))]).then(()=>a()).catch(s)});var E=(e=>(e.QuantityBreak="quantity-break",e.Bxgy="bxgy",e.Bundle="bundle",e.MixAndMatch="mix-and-match",e.Sku="sku",e))(E||{});const qe={id:1,handle:"example-product",url:null,availableForSale:!0,title:"Example product",image:null,collectionIds:[],options:[],selectedVariantId:1,variants:[{id:1,availableForSale:!0,price:8e3,compareAtPrice:null,options:["Default Title"],imageId:null,image:null,unitPriceMeasurement:null,sellingPlans:[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:50}],metafields:{text:null,text2:null,text3:null,text4:null},requiresSellingPlan:!1,sellingPlans:[],isNativeBundle:!1},Oe={id:"example",nanoId:"example",blockName:"Bundle",discountName:"",blockTitle:"BUNDLE & SAVE",blockLayout:"vertical",blockVisibility:"all-products",marketId:null,currency:null,excludeB2bCustomers:!1,excludePos:!1,startTimestamp:0,endTimestamp:null,differentVariantsEnabled:!0,hideVariantPicker:!0,disableVariantOptionSync:!1,hideUnavailableOptions:!1,showPricesPerItem:!1,showBothPrices:!1,unitLabel:"",useProductCompareAtPrice:!0,showPricesWithoutDecimals:!1,priceRounding:!1,priceRoundingPrecision:".00",updateNativePrice:!1,updateNativePriceType:"item",skipCart:!1,showVariantsForSingleQuantity:!1,preselectedDealBarId:"duo",cornerRadius:16,spacing:1,selectedProductIds:[],selectedCollectionIds:[],excludedProductIds:[],excludedCollectionIds:[],colors:{background:{red:245,green:245,blue:245,alpha:1},selectedBackground:{red:255,green:255,blue:255,alpha:1},border:{red:0,green:0,blue:0,alpha:1},blockTitle:{red:0,green:0,blue:0,alpha:1},title:{red:0,green:0,blue:0,alpha:1},subtitle:{red:85,green:85,blue:85,alpha:1},price:{red:0,green:0,blue:0,alpha:1},fullPrice:{red:85,green:85,blue:85,alpha:1},labelBackground:{red:171,green:239,blue:198,alpha:1},label:{red:0,green:0,blue:0,alpha:1},badgeBackground:{red:0,green:0,blue:0,alpha:1},badgeText:{red:255,green:255,blue:255,alpha:1},freeGiftBackground:{red:0,green:0,blue:0,alpha:.3},freeGiftText:{red:0,green:0,blue:0,alpha:1},freeGiftSelectedBackground:{red:0,green:0,blue:0,alpha:1},freeGiftSelectedText:{red:255,green:255,blue:255,alpha:1},upsellBackground:{red:0,green:0,blue:0,alpha:.2},upsellText:{red:0,green:0,blue:0,alpha:1},upsellSelectedBackground:{red:0,green:0,blue:0,alpha:.2},upsellSelectedText:{red:0,green:0,blue:0,alpha:1}},fonts:{blockTitle:{size:"14",style:"bold"},title:{size:"20",style:"bold"},subtitle:{size:"14",style:"regular"},label:{size:"12",style:"bold"},freeGift:{size:"13",style:"bold"},upsell:{size:"13",style:"bold"},unitLabel:{size:"14",style:"regular"}},dealBars:[{id:"single",dealBarType:E.QuantityBreak,quantitySelector:!1,title:"Single",subtitle:"Standard price",label:"",quantity:1,discountType:"default",discountValue:"",badgeStyle:"simple",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null,highlights:null,sellingPlanEnabled:!1,sellingPlanGid:null,subscriptionMode:"customer-choice"},{id:"duo",dealBarType:E.QuantityBreak,quantitySelector:!1,title:"Duo",subtitle:"You save 20%",label:"SAVE $32",quantity:2,discountType:"percentage",discountValue:"20",badgeStyle:"most-popular",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null,highlights:null,sellingPlanEnabled:!1,sellingPlanGid:null,subscriptionMode:"customer-choice"},{id:"trio",dealBarType:E.QuantityBreak,quantitySelector:!1,title:"Trio",subtitle:"You save 25%",label:"SAVE $60",quantity:3,discountType:"percentage",discountValue:"25",badgeStyle:"simple",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null,highlights:null,sellingPlanEnabled:!1,sellingPlanGid:null,subscriptionMode:"customer-choice"}],badgesEnabled:!0,badges:[{id:"bdg1",attachedTo:{type:"dealBar",dealBarId:"duo"},text:"MOST POPULAR",colors:null,badgeType:"most-popular",size:90}],swatchOptions:[],swatchSize:18,swatchShape:"circle",imageSize:48,imageCornerRadius:6,defaultVariantsV2:[],collectionBreaksEnabled:!1,collectionBreaks:null,chooseProductModal:null,timerEnabled:!1,timer:null,subscriptionsEnabled:!1,subscriptions:null,stickyAtcEnabled:!1,stickyAtc:null,progressiveGiftsEnabled:!1,progressiveGifts:null,checkboxUpsellsEnabled:!1,checkboxUpsells:null,customStylesEnabled:!1,shopCustomStyles:"",customStyles:"",lowStockAlertEnabled:!1,lowStockAlert:null},je={config:{shopifyDomain:"",moneyFormat:"${{amount}}",locale:"en",country:"US",currencyRate:1,marketId:0,productId:null,storefrontAccessToken:null,includeSellingPlans:!1,includeAvailableQuantity:!1,customApiHost:null,keepQuantityInput:!1,ignoreDeselect:!1,ignoreUnitPrice:!1,requireCustomerLogin:!1,abTestsRunning:!1,webPixel:!1,b2bCustomer:!1,isLoggedIn:!1,preview:!0,previewAlerts:!1,previewScratchOff:!1,defaultTranslations:{"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.quantity":"Quantity","system.subscription_plan":"Subscription plan","system.remove":"Remove","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","system.original_price":"Original price:","system.price":"Price:","system.letters_only":"Only letters are allowed.","system.numbers_only":"Only numbers are allowed."},customSelectors:{quantity:null,addToCartButton:null,variantPicker:null,price:null,priceCompare:null},featureFlags:{},shopCustomStyles:""},dealBlock:Oe,product:qe,otherProducts:[],mediaImages:[],collectionBreaksProducts:[],translations:{}};class Le extends HTMLElement{constructor(){super(...arguments),this.innerElement=null,this.handleItemsChanged=null,this.initializeId=0}static get observedAttributes(){return["selected-variant-id","product-id","country","language"]}async connectedCallback(){await this.initialize()}async initialize(){var o,r;const t=++this.initializeId;if(this.cleanup(),this.hasAttribute("demo")){if(await F(window),t!==this.initializeId)return;this.renderInnerElement(je);return}const a=this.getAttribute("shop-domain"),s=this.getAttribute("storefront-token"),n=this.getAttribute("product-id");if(!a||!s||!n)return;const[i]=await Promise.all([U({shopifyDomain:a,storefrontAccessToken:s},{productId:n,dealBlockId:this.getAttribute("deal-block-id")??void 0,country:((o=this.getAttribute("country"))==null?void 0:o.toUpperCase())??void 0,language:((r=this.getAttribute("language"))==null?void 0:r.toUpperCase())??void 0}),F(window)]);!i||t!==this.initializeId||this.renderInnerElement(i)}renderInnerElement(t){const{config:a,dealBlock:s,product:n,otherProducts:i,mediaImages:o,collectionBreaksProducts:r,translations:m}=t;this.innerElement=document.createElement("kaching-bundles-block"),this.innerElement.setAttribute("deal-block-id",s.id),this.innerElement.setAttribute("config",JSON.stringify(a)),this.innerElement.setAttribute("deal-block",JSON.stringify(s)),this.innerElement.setAttribute("media-images",JSON.stringify(o??[])),this.innerElement.setAttribute("product",JSON.stringify(n)),this.innerElement.setAttribute("other-products",JSON.stringify(i??[])),this.innerElement.setAttribute("collection-breaks-products",JSON.stringify(r??[])),this.innerElement.setAttribute("translations",JSON.stringify(m??{}));const c=this.getAttribute("selected-variant-id");this.innerElement.setAttribute("current-variant-id",String(c?c.split("/").pop():n.variants[0].id)),this.hasAttribute("compact")&&this.innerElement.setAttribute("compact","");const u=this.innerElement,h=()=>{if(this.innerElement!==u)return;const f=u.items();f&&this.dispatchEvent(new CustomEvent("items-changed",{detail:{items:f},bubbles:!0}))};this.handleItemsChanged=f=>{f.stopPropagation(),h()};const g=this.handleItemsChanged;u.addEventListener("kaching-bundles-block-loaded",()=>{this.innerElement===u&&(u.addEventListener("items-changed",g),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(t,a,s){a!==s&&this.isConnected&&(t==="product-id"||t==="country"||t==="language"?this.initialize():t==="selected-variant-id"&&this.innerElement&&s&&this.innerElement.setAttribute("current-variant-id",s.includes("/")?String(s.split("/").pop()):s))}items(){return this.innerElement?this.innerElement.items():[]}disconnectedCallback(){this.cleanup(),this.initializeId++}}return customElements.define("kaching-bundle-component",Le),A.fetchKachingBundlesData=U,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),A})({});
|
package/dist/index.d.ts
CHANGED
|
@@ -68,6 +68,7 @@ declare interface BaseDealBar {
|
|
|
68
68
|
highlights?: Highlights | null;
|
|
69
69
|
sellingPlanEnabled?: boolean;
|
|
70
70
|
sellingPlanGid?: string | null;
|
|
71
|
+
subscriptionMode?: SubscriptionMode;
|
|
71
72
|
hideBehindScratchOff?: boolean;
|
|
72
73
|
}
|
|
73
74
|
|
|
@@ -508,8 +509,6 @@ declare interface GlobalConfig {
|
|
|
508
509
|
"system.deal_page_items_few"?: string;
|
|
509
510
|
"system.deal_page_items_many"?: string;
|
|
510
511
|
"system.deal_page_percentage_off"?: string;
|
|
511
|
-
"system.deal_page_price_each"?: string;
|
|
512
|
-
"system.deal_page_quantity_for_price"?: string;
|
|
513
512
|
"system.deal_page_in_your_box"?: string;
|
|
514
513
|
"system.deal_page_in_your_box_count"?: string;
|
|
515
514
|
"system.deal_page_in_box_count"?: string;
|
|
@@ -571,7 +570,6 @@ declare interface GlobalConfig {
|
|
|
571
570
|
"system.deal_page_default_add_box_to_cart"?: string;
|
|
572
571
|
"system.deal_page_items_range"?: string;
|
|
573
572
|
"system.deal_page_tip_box_size"?: string;
|
|
574
|
-
"system.deal_page_tip_on_its_own"?: string;
|
|
575
573
|
"system.deal_page_about_this_price"?: string;
|
|
576
574
|
};
|
|
577
575
|
customSelectors: {
|
|
@@ -587,7 +585,6 @@ declare interface GlobalConfig {
|
|
|
587
585
|
atc_total_price?: boolean;
|
|
588
586
|
cart_change_response_rewrite?: boolean;
|
|
589
587
|
cart_interceptor_dedupe_disabled?: boolean;
|
|
590
|
-
cart_interceptor_json_encoding?: boolean;
|
|
591
588
|
debug_cart_add?: boolean;
|
|
592
589
|
disable_nested_cart_lines?: boolean;
|
|
593
590
|
early_fetch_override?: boolean;
|
|
@@ -973,6 +970,8 @@ export declare interface StorefrontCredentials {
|
|
|
973
970
|
storefrontAccessToken: string;
|
|
974
971
|
}
|
|
975
972
|
|
|
973
|
+
declare type SubscriptionMode = "customer-choice" | "always-subscription" | "one-time-only";
|
|
974
|
+
|
|
976
975
|
declare type Subscriptions = {
|
|
977
976
|
layout: SubscriptionsLayout;
|
|
978
977
|
position: "above" | "below";
|
package/dist/index.js
CHANGED
|
@@ -42,7 +42,7 @@ const T = (e, t) => {
|
|
|
42
42
|
d,
|
|
43
43
|
...s.slice(p + 1).map(D)
|
|
44
44
|
].join("");
|
|
45
|
-
}, D = (e) =>
|
|
45
|
+
}, D = (e) => C(e.value), C = (e) => e.replace(/\s/g, " "), N = (e) => e.type === "integer" || e.type === "group" || e.type === "decimal" || e.type === "fraction", O = (e, t) => e && t ? `${e}-${t.toUpperCase()}` : e || (t ? t.toUpperCase() : "en"), F = (e) => e === void 0 ? void 0 : C(e).replace(/’/g, "'"), U = (e, t, a) => t === "," && e === "." ? a ? "{{amount_with_comma_separator}}" : "{{amount_no_decimals_with_comma_separator}}" : t === "," && e === " " ? a ? "{{amount_with_space_separator}}" : "{{amount_no_decimals_with_space_separator}}" : t === "." && e === " " ? "{{amount_with_period_and_space_separator}}" : t === "." && e === "'" ? "{{amount_with_apostrophe_separator}}" : a ? "{{amount}}" : "{{amount_no_decimals}}", w = ({
|
|
46
46
|
country: e,
|
|
47
47
|
language: t
|
|
48
48
|
}) => {
|
|
@@ -707,10 +707,9 @@ const T = (e, t) => {
|
|
|
707
707
|
}
|
|
708
708
|
)
|
|
709
709
|
)
|
|
710
|
-
)).flatMap((l) => l.nodes).
|
|
711
|
-
gid: l.id,
|
|
712
|
-
|
|
713
|
-
}));
|
|
710
|
+
)).flatMap((l) => l.nodes).flatMap(
|
|
711
|
+
(l) => l != null && l.image ? [{ gid: l.id, url: l.image.url }] : []
|
|
712
|
+
);
|
|
714
713
|
};
|
|
715
714
|
var $ = /* @__PURE__ */ ((e) => (e.QuantityBreak = "quantity-break", e.Bxgy = "bxgy", e.Bundle = "bundle", e.MixAndMatch = "mix-and-match", e.Sku = "sku", e))($ || {});
|
|
716
715
|
const W = (e) => [
|
|
@@ -938,11 +937,11 @@ const Ie = async (e, t, { country: a, language: n }) => {
|
|
|
938
937
|
} catch {
|
|
939
938
|
return;
|
|
940
939
|
}
|
|
941
|
-
const n =
|
|
940
|
+
const n = M(e);
|
|
942
941
|
return (s = a.find(
|
|
943
|
-
(l) =>
|
|
942
|
+
(l) => M(l.locale) === n
|
|
944
943
|
)) == null ? void 0 : s.translations;
|
|
945
|
-
},
|
|
944
|
+
}, M = (e) => e.toLowerCase().replace(/_/g, "-"), $e = "2026-07", Se = async (e, {
|
|
946
945
|
productId: t,
|
|
947
946
|
dealBlockId: a,
|
|
948
947
|
country: n = void 0,
|
|
@@ -68,6 +68,7 @@ declare interface BaseDealBar {
|
|
|
68
68
|
highlights?: Highlights | null;
|
|
69
69
|
sellingPlanEnabled?: boolean;
|
|
70
70
|
sellingPlanGid?: string | null;
|
|
71
|
+
subscriptionMode?: SubscriptionMode;
|
|
71
72
|
hideBehindScratchOff?: boolean;
|
|
72
73
|
}
|
|
73
74
|
|
|
@@ -508,8 +509,6 @@ declare interface GlobalConfig {
|
|
|
508
509
|
"system.deal_page_items_few"?: string;
|
|
509
510
|
"system.deal_page_items_many"?: string;
|
|
510
511
|
"system.deal_page_percentage_off"?: string;
|
|
511
|
-
"system.deal_page_price_each"?: string;
|
|
512
|
-
"system.deal_page_quantity_for_price"?: string;
|
|
513
512
|
"system.deal_page_in_your_box"?: string;
|
|
514
513
|
"system.deal_page_in_your_box_count"?: string;
|
|
515
514
|
"system.deal_page_in_box_count"?: string;
|
|
@@ -571,7 +570,6 @@ declare interface GlobalConfig {
|
|
|
571
570
|
"system.deal_page_default_add_box_to_cart"?: string;
|
|
572
571
|
"system.deal_page_items_range"?: string;
|
|
573
572
|
"system.deal_page_tip_box_size"?: string;
|
|
574
|
-
"system.deal_page_tip_on_its_own"?: string;
|
|
575
573
|
"system.deal_page_about_this_price"?: string;
|
|
576
574
|
};
|
|
577
575
|
customSelectors: {
|
|
@@ -587,7 +585,6 @@ declare interface GlobalConfig {
|
|
|
587
585
|
atc_total_price?: boolean;
|
|
588
586
|
cart_change_response_rewrite?: boolean;
|
|
589
587
|
cart_interceptor_dedupe_disabled?: boolean;
|
|
590
|
-
cart_interceptor_json_encoding?: boolean;
|
|
591
588
|
debug_cart_add?: boolean;
|
|
592
589
|
disable_nested_cart_lines?: boolean;
|
|
593
590
|
early_fetch_override?: boolean;
|
|
@@ -973,6 +970,8 @@ export declare interface StorefrontCredentials {
|
|
|
973
970
|
storefrontAccessToken: string;
|
|
974
971
|
}
|
|
975
972
|
|
|
973
|
+
declare type SubscriptionMode = "customer-choice" | "always-subscription" | "one-time-only";
|
|
974
|
+
|
|
976
975
|
declare type Subscriptions = {
|
|
977
976
|
layout: SubscriptionsLayout;
|
|
978
977
|
position: "above" | "below";
|