@kachingappz/bundles-js 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,203 @@
1
+ (function(){"use strict";const $={config:{shopifyDomain:"",moneyFormat:"${{amount}}",locale:"en",country:"US",currencyRate:1,marketId:0,productId:null,storefrontAccessToken:null,accessScopes:[],customApiHost:null,keepQuantityInput:!1,ignoreDeselect:!1,ignoreUnitPrice:!1,requireCustomerLogin:!1,abTestsRunning:!1,webPixel:!1,b2bCustomer:!1,isLoggedIn:!1,preview:!0,previewAlerts:!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.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"},customSelectors:{quantity:null,addToCartButton:null,variantPicker:null,price:null,priceCompare:null},featureFlags:{},shopCustomStyles:""},dealBlock:{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:8,spacing:1,selectedProductIds:[],selectedCollectionIds:[],excludedProductIds:[],excludedCollectionIds:[],colors:{background:{red:255,green:255,blue:255,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:238,green:238,blue:238,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:"medium"},subtitle:{size:"14",style:"regular"},label:{size:"12",style:"regular"},freeGift:{size:"13",style:"bold"},upsell:{size:"13",style:"bold"},unitLabel:{size:"14",style:"regular"}},dealBars:[{id:"single",dealBarType:"quantity-break",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:"quantity-break",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:"quantity-break",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}],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},product:{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},otherProducts:[],mediaImages:[],collectionBreaksProducts:[],translations:{}},I=({country:t,language:e})=>{const s=[];return t&&s.push(`country: ${t}`),e&&s.push(`language: ${e}`),s.length>0?`@inContext(${s.join(", ")})`:""},G=async(t,{useExternalMetafieldNamespace:e,useMetaobjects:s})=>s?T(t):x(t),x=async(t,e)=>{var l;const s=(l=(await t.query(`
2
+ query FetchDealBlocks($metafieldNamespace: String!) {
3
+ shop {
4
+ metafield(namespace: $metafieldNamespace, key: "deal_blocks") {
5
+ value
6
+ }
7
+ }
8
+ }
9
+ `,{variables:{metafieldNamespace:"app--2935586817--kaching_bundles"}})).shop.metafield)==null?void 0:l.value;return s?JSON.parse(s):[]},T=async(t,e)=>{const s="app--2935586817--deal_block",l=[];let a=null;for(;;){const r=await t.query(`
10
+ query FetchDealBlockMetaobjects($type: String!, $cursor: String) {
11
+ metaobjects(type: $type, first: 250, after: $cursor) {
12
+ nodes {
13
+ fields {
14
+ key
15
+ value
16
+ }
17
+ }
18
+ pageInfo {
19
+ hasNextPage
20
+ endCursor
21
+ }
22
+ }
23
+ }
24
+ `,{variables:{type:s,cursor:a}});for(const c of r.metaobjects.nodes){const n=c.fields.find(m=>m.key==="settings");n!=null&&n.value&&l.push(JSON.parse(n.value))}if(!r.metaobjects.pageInfo.hasNextPage)break;a=r.metaobjects.pageInfo.endCursor}return l},k="app--2935586817",B=async(t,{language:e,country:s,useExternalMetafieldNamespace:l})=>{const a=`${k}--kaching_bundles`,r=k,{shop:{moneyFormat:c,currencyRateConstant:n,primaryDomain:m,settingsMetafield:p}}=await t.query(`
25
+ query config($metafieldNamespace: String!, $settingsNamespace: String!) {
26
+ shop {
27
+ moneyFormat
28
+ primaryDomain {
29
+ host
30
+ }
31
+ currencyRateConstant: metafield(namespace: $metafieldNamespace, key: "currency_rate_constant") {
32
+ value
33
+ }
34
+ settingsMetafield: metafield(namespace: $settingsNamespace, key: "config") {
35
+ value
36
+ }
37
+ }
38
+ }
39
+ `,{variables:{metafieldNamespace:a,settingsNamespace:r}}),u=n?q(n.value):1,i=p?JSON.parse(p.value):null,d=(i==null?void 0:i.feature_flags)??{},o=(i==null?void 0:i.custom_selectors)??{};return{shopifyDomain:m.host,moneyFormat:c,locale:(e==null?void 0:e.toLowerCase())||"en",liquidLocale:(e==null?void 0:e.toLowerCase())||"en",country:s??"US",currencyRate:u,marketId:0,productId:null,storefrontAccessToken:(i==null?void 0:i.storefront_access_token)??null,accessScopes:(i==null?void 0:i.access_scopes)??[],customApiHost:(i==null?void 0:i.custom_api_host)??null,keepQuantityInput:(i==null?void 0:i.keep_quantity_input)??!1,ignoreDeselect:(i==null?void 0:i.ignore_deselect)??!1,ignoreUnitPrice:(i==null?void 0:i.ignore_unit_price)??!1,requireCustomerLogin:(i==null?void 0:i.require_customer_login)??!1,abTestsRunning:(i==null?void 0:i.ab_tests_running)??!1,webPixel:(i==null?void 0:i.web_pixel)??!1,b2bCustomer:!1,isLoggedIn:!1,preview:!1,previewAlerts:!1,defaultTranslations:{"system.out_of_stock":"Out of stock","system.invalid_variant":"Invalid variant","system.unavailable_option_value":"Unavailable option value","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"},customSelectors:{quantity:o.quantity??null,addToCartButton:o.add_to_cart_button??null,variantPicker:o.variant_picker??null,price:o.price??null,priceCompare:o.price_compare??null},shopCustomStyles:(i==null?void 0:i.shop_custom_styles)??"",featureFlags:d}},q=t=>JSON.parse(t).amount/1e6,M=async(t,e,s=200)=>(e=e.filter(Boolean).filter(l=>!l.startsWith("placeholder")),e.length===0?[]:(await t.query(`
40
+ query FetchMediaImages($mediaImageIds: [ID!]!, $size: Int!) {
41
+ nodes(ids: $mediaImageIds) {
42
+ ... on MediaImage {
43
+ id
44
+ image {
45
+ url(transform: { maxWidth: $size, maxHeight: $size })
46
+ }
47
+ }
48
+ }
49
+ }
50
+ `,{variables:{mediaImageIds:e,size:s}})).nodes.filter(Boolean).map(l=>({gid:l.id,url:l.image.url}))),E=async(t,{country:e,language:s,blockVisibility:l,excludedProductGIDs:a,selectedProductGIDs:r,selectedCollectionGIDs:c,limit:n=250})=>{switch(l){case"selected-products":return r.slice(0,n);case"all-products":case"excluded-products":{const m=I({country:e,language:s});let p=(await t.query(`
51
+ query FetchProductGIDs($limit: Int!) ${m} {
52
+ products(first: $limit) {
53
+ nodes {
54
+ id
55
+ }
56
+ }
57
+ }
58
+ `,{variables:{limit:n}})).products.nodes.map(u=>u.id);return l==="excluded-products"&&(p=p.filter(u=>!a.includes(u))),p}case"selected-collections":{const m=I({country:e,language:s}),p=(await t.query(`
59
+ query FetchCollectionProductGIDs($collectionGIDs: [ID!]!, $limit: Int!) ${m} {
60
+ nodes(ids: $collectionGIDs) {
61
+ ... on Collection {
62
+ products(first: $limit) {
63
+ nodes {
64
+ id
65
+ }
66
+ }
67
+ }
68
+ }
69
+ }
70
+ `,{variables:{collectionGIDs:c,limit:n}})).nodes.filter(u=>u!==null).flatMap(u=>u.products.nodes.map(i=>i.id));return Array.from(new Set(p)).slice(0,n)}}},w=`
71
+ id
72
+ availableForSale
73
+ price {
74
+ amount
75
+ }
76
+ compareAtPrice {
77
+ amount
78
+ }
79
+ selectedOptions {
80
+ name
81
+ value
82
+ }
83
+ image {
84
+ id
85
+ url(transform: { maxWidth: 200, maxHeight: 200 })
86
+ }
87
+ unitPriceMeasurement {
88
+ quantityUnit
89
+ quantityValue
90
+ referenceUnit
91
+ referenceValue
92
+ }
93
+ requiresComponents
94
+ sellingPlanAllocations(first: 100) @include(if: $includeSellingPlans) {
95
+ nodes {
96
+ sellingPlan {
97
+ id
98
+ }
99
+ priceAdjustments {
100
+ price {
101
+ amount
102
+ }
103
+ }
104
+ }
105
+ }
106
+ quantityAvailable @include(if: $includeAvailableQuantity)
107
+ `,P=async(t,{country:e,language:s,productIds:l,includeSellingPlans:a=!0,includeAvailableQuantity:r=!0,useExternalMetafieldNamespace:c=!1})=>{if(!l.length)return[];const n=l.map(u=>typeof u=="string"&&u.startsWith("gid://")?u:`gid://shopify/Product/${u}`),m=I({country:e,language:s});let p=(await t.query(`
108
+ query FetchProducts($productGIDs: [ID!]!, $includeSellingPlans: Boolean!, $includeAvailableQuantity: Boolean!, $metafieldNamespace: String!) ${m} {
109
+ nodes(ids: $productGIDs) {
110
+ ... on Product {
111
+ id
112
+ handle
113
+ onlineStoreUrl
114
+ availableForSale
115
+ createdAt
116
+ title
117
+ featuredImage {
118
+ url
119
+ }
120
+ options {
121
+ name
122
+ optionValues {
123
+ id
124
+ name
125
+ swatch {
126
+ color
127
+ image {
128
+ previewImage {
129
+ url(transform: { maxWidth: 200, maxHeight: 200 })
130
+ }
131
+ }
132
+ }
133
+ }
134
+ }
135
+ variants(first: 250) {
136
+ nodes {
137
+ ${w}
138
+ }
139
+ }
140
+ collections(first: 50) {
141
+ nodes {
142
+ id
143
+ }
144
+ }
145
+ metafield: metafield(namespace: $metafieldNamespace, key: "text") {
146
+ value
147
+ }
148
+ metafield2: metafield(namespace: $metafieldNamespace, key: "text2") {
149
+ value
150
+ }
151
+ metafield3: metafield(namespace: $metafieldNamespace, key: "text3") {
152
+ value
153
+ }
154
+ metafield4: metafield(namespace: $metafieldNamespace, key: "text4") {
155
+ value
156
+ }
157
+ requiresSellingPlan
158
+ sellingPlanGroups(first: 100) @include(if: $includeSellingPlans) {
159
+ nodes {
160
+ sellingPlans(first: 100) {
161
+ nodes {
162
+ id
163
+ name
164
+ priceAdjustments {
165
+ adjustmentValue {
166
+ __typename
167
+ ... on SellingPlanPercentagePriceAdjustment {
168
+ adjustmentPercentage
169
+ }
170
+ ... on SellingPlanFixedAmountPriceAdjustment {
171
+ adjustmentAmount {
172
+ amount
173
+ }
174
+ }
175
+ ... on SellingPlanFixedPriceAdjustment {
176
+ price {
177
+ amount
178
+ }
179
+ }
180
+ }
181
+ }
182
+ }
183
+ }
184
+ }
185
+ }
186
+ }
187
+ }
188
+ }
189
+ `,{variables:{productGIDs:n,includeSellingPlans:a,includeAvailableQuantity:r,metafieldNamespace:c?"app--2935586817--kaching_bundles":"$app:kaching_bundles"}})).nodes.filter(u=>u!=null);return p=await Promise.all(p.map(u=>O(t,u,{includeSellingPlans:a,includeAvailableQuantity:r}))),p.map(j)},O=async(t,e,s)=>{if(e.variants.nodes.length<250)return e;const l=new Set,a=[],r=[],c=async n=>{let m=!0,p=null;for(;m;){const u=await t.query(`
190
+ query($productGID: ID!, $cursor: String, $reverse: Boolean, $includeSellingPlans: Boolean!, $includeAvailableQuantity: Boolean!) {
191
+ product(id: $productGID) {
192
+ variants(first: 250, after: $cursor, reverse: $reverse) {
193
+ nodes {
194
+ ${w}
195
+ }
196
+ pageInfo {
197
+ endCursor
198
+ hasNextPage
199
+ }
200
+ }
201
+ }
202
+ }
203
+ `,{variables:{productGID:e.id,cursor:p,reverse:n,...s}}),{nodes:i,pageInfo:d}=u.product.variants;for(const o of i){if(l.has(o.id)){m=!1;break}l.add(o.id),n?r.push(o):a.push(o)}d.hasNextPage||(m=!1),p=d.endCursor}};return await Promise.all([c(!1),c(!0)]),e.variants.nodes=[...a,...r.reverse()],e},j=t=>{var c,n,m,p,u,i;const e=t.variants.nodes.map(({unitPriceMeasurement:d,...o})=>{var h,f;return{id:Number(o.id.split("/").pop()),availableForSale:o.availableForSale,price:Math.round(Number(o.price.amount)*100),compareAtPrice:o.compareAtPrice?Math.round(Number(o.compareAtPrice.amount)*100):null,options:o.selectedOptions.map(g=>g.value),imageId:o.image?Number(o.image.id.split("/").pop()):null,image:((h=o.image)==null?void 0:h.url)||null,sellingPlans:((f=o.sellingPlanAllocations)==null?void 0:f.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(o.price.amount)*100)})))||[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:o.quantityAvailable??null,unitPriceMeasurement:d!=null&&d.quantityUnit&&(d!=null&&d.referenceUnit)?{quantityValue:d.quantityValue,quantityUnit:d.quantityUnit.toLowerCase(),referenceValue:d.referenceValue,referenceUnit:d.referenceUnit.toLowerCase()}:null}}),s=t.options.map((d,o)=>{const h=d.optionValues.map(f=>{var g,b,y,v;return{id:Number(f.id.split("/").pop()),defaultName:f.name,name:f.name,swatch:{color:((g=f.swatch)==null?void 0:g.color)||null,image:((v=(y=(b=f.swatch)==null?void 0:b.image)==null?void 0:y.previewImage)==null?void 0:v.url)||null}}});return{defaultName:d.name,name:d.name,position:o+1,optionValues:L(h,o,e)}}),l=d=>{const o=d.priceAdjustments[0];if(!o)return null;const h=o.adjustmentValue;switch(h.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:h.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"fixed_amount",value:Number(h.adjustmentAmount.amount)*100};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:Number(h.price.amount)*100};default:throw new Error(`Unknown price adjustment type: ${h.__typename}`)}},a=((c=t.sellingPlanGroups)==null?void 0:c.nodes.flatMap(d=>d.sellingPlans.nodes.map(o=>({id:Number(o.id.split("/").pop()),name:o.name,priceAdjustment:l(o)}))))||[],r=t.variants.nodes.some(d=>d.requiresComponents);return{id:Number(t.id.split("/").pop()),handle:t.handle,url:t.onlineStoreUrl,availableForSale:t.availableForSale,createdAt:t.createdAt,title:t.title,image:((n=t.featuredImage)==null?void 0:n.url)||null,collectionIds:t.collections.nodes.map(d=>Number(d.id.split("/").pop())),options:s,selectedVariantId:Number(t.variants.nodes[0].id.split("/").pop()),variants:e,requiresSellingPlan:t.requiresSellingPlan,sellingPlans:a,isNativeBundle:r,metafields:{text:((m=t.metafield)==null?void 0:m.value)||null,text2:((p=t.metafield2)==null?void 0:p.value)||null,text3:((u=t.metafield3)==null?void 0:u.value)||null,text4:((i=t.metafield4)==null?void 0:i.value)||null}}},L=(t,e,s)=>t.filter(l=>s.filter(a=>a.options[e]===l.name).length>0),U=(t,e)=>{const s=[],l=t.filter(n=>n.blockVisibility==="selected-products");for(const n of l)n.selectedProductIds.map(Number).includes(e.id)&&s.push(n);const a=t.filter(n=>n.blockVisibility==="selected-collections");for(const n of a)e.collectionIds.some(m=>n.selectedCollectionIds.map(Number).includes(m))&&s.push(n);const r=t.filter(n=>n.blockVisibility==="excluded-products");for(const n of r)!n.excludedProductIds.map(Number).includes(e.id)&&!(n.excludedCollectionIds||[]).some(m=>e.collectionIds.includes(m))&&s.push(n);const c=t.filter(n=>n.blockVisibility==="all-products");for(const n of c)s.push(n);return s},V=t=>[...F(t),...R(t),...z(t),...H(t),...J(t),...Q(t),...X(t),...W(t),...K(t),...Y(t)].filter(e=>e!=null&&!e.includes("placeholder")),F=t=>t.dealBars.flatMap(e=>[e.mediaImageGID,e.badgeImageGID]).filter(e=>e!=null),R=t=>t.dealBars.map(({freeGifts:e})=>(e||[]).map(s=>s.mediaImageGID)).reduce((e,s)=>e.concat(s),[]).filter(e=>e!=null),z=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>(e||[]).map(s=>s.mediaImageGID)).filter(e=>e!=null),H=t=>t.dealBars.map(({upsells:e})=>(e||[]).map(s=>s.mediaImageGID)).reduce((e,s)=>e.concat(s),[]).filter(e=>e!=null),J=t=>t.swatchOptions?t.swatchOptions.reduce((e,s)=>{const l=s.images.map(a=>a.mediaImageGID).filter(a=>a!=null);return[...e,...l]},[]):[],Q=t=>{if(!t.collectionBreaksEnabled||!t.collectionBreaks)return[];const e=t.collectionBreaks.mediaImageGID;return e?[e]:[]},X=t=>{var e,s,l;return t.progressiveGifts?[...((e=t.progressiveGifts.gifts)==null?void 0:e.map(a=>a.mediaImageGID))||[],(s=t.progressiveGifts.style)==null?void 0:s.lockedMediaImageGID,(l=t.progressiveGifts.dealBarStyle)==null?void 0:l.lockedMediaImageGID].filter(a=>a!=null):[]},W=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.mediaImageGID).filter(e=>e!=null),K=t=>t.dealBars.map(e=>{var s;return(s=e.productPersonalisation)==null?void 0:s.mediaImageGID}).filter(e=>e!=null),Y=t=>t.dealBars.map(e=>{var s;return(s=e.highlights)==null?void 0:s.customIconGID}).filter(e=>e!=null),Z=t=>{const e=[...ee(t),...te(t),...se(t),...le(t),...ne(t),...ae(t),...ie(t)];return Array.from(new Set(e.filter(s=>s!=null)))},ee=t=>t.dealBars.flatMap(({freeGifts:e})=>e?e.map(s=>s.productGID):[]).filter(e=>e!=null),te=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>e?e.flatMap(s=>s.products?s.products.map(l=>l.id):[]):[]).filter(e=>e!=null),se=t=>{var e;return t.progressiveGiftsEnabled?((e=t.progressiveGifts)==null?void 0:e.gifts.map(s=>s.productGID).filter(s=>s!=null))||[]:[]},le=t=>t.dealBars.flatMap(({upsells:e})=>e?e.map(s=>s.productGID):[]).filter(e=>e!=null),ne=t=>t.dealBars.filter(e=>e.dealBarType==="bundle").flatMap(({bundleProducts:e})=>e?e.map(s=>s.productGID):[]).filter(e=>e!=null).filter(e=>e!=="default"),ae=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.productGID).filter(e=>e!=null),ie=t=>t.dealBars.filter(e=>e.dealBarType==="sku").flatMap(({productGID:e})=>e?[e]:[]);class re{constructor(e,s){this.storefrontApiVersion="2025-10",this.storefrontAccessToken=s,this.shopifyDomain=e}async query(e,s){var n;const l=(s==null?void 0:s.variables)??{};let a=`https://${this.shopifyDomain}/api/${this.storefrontApiVersion}/graphql.json`;const r=(n=e.match(/query\s+(\w+)/))==null?void 0:n[1];r&&(a+=`?operation_name=${r}`);const c=await(await fetch(a,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:e,variables:l})})).text();if(!c)throw new Error("Empty graphql response");return JSON.parse(c).data}}const oe=async(t,e,{country:s,language:l})=>{const a=e.collectionBreaks;if(!e.collectionBreaksEnabled||!a)return;let r;a.visibility==="deal-products"?r=await E(t,{country:s,language:l,blockVisibility:e.blockVisibility,excludedProductGIDs:(e.excludedProductIds||[]).map(n=>`gid://shopify/Product/${n}`),selectedProductGIDs:(e.selectedProductIds||[]).map(n=>`gid://shopify/Product/${n}`),selectedCollectionGIDs:(e.selectedCollectionIds||[]).map(n=>`gid://shopify/Collection/${n}`)}):r=await E(t,{country:s,language:l,blockVisibility:a.visibility,excludedProductGIDs:(a.excludedProducts||[]).map(({id:n})=>n),selectedProductGIDs:(a.selectedProducts||[]).map(({id:n})=>n),selectedCollectionGIDs:(a.selectedCollections||[]).map(({id:n})=>n)}),r=r.slice(0,250);let c=await P(t,{country:s,language:l,productIds:r.map(n=>Number(n.split("/").pop())),useExternalMetafieldNamespace:!0});return c=c.filter(n=>n.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="2025-10",de=async(t,{productId:e,dealBlockId:s,country:l=void 0,language:a=void 0})=>{var r,c;try{const n=[Number(e.split("/").pop())],m=new me(t);l=l||((r=m.i18n)==null?void 0:r.country),a=a||((c=m.i18n)==null?void 0:c.language);const p=await B(m,{language:a,country:l,useExternalMetafieldNamespace:!0}),u=p.storefrontAccessToken?new re(p.shopifyDomain,p.storefrontAccessToken):m,[i,d]=await Promise.all([P(u,{country:l,language:a,productIds:n,useExternalMetafieldNamespace:!0}),G(u,{useExternalMetafieldNamespace:!0,useMetaobjects:p.featureFlags.storefront_metaobjects})]),o=i[0];if(!o)return null;const h=U(d,o);let f;if(s?(f=h.find(N=>N.id===s||N.nanoId===s),f||(f=h[0])):f=h[0],!f)return null;const g=V(f),b=Z(f),[y,v,ve,Ie]=await Promise.all([P(u,{country:l,language:a,productIds:b,useExternalMetafieldNamespace:!0}),M(u,g,300),oe(u,f,{country:l,language:a}),ce()]);return{product:o,dealBlock:f,config:p,otherProducts:y,mediaImages:v,collectionBreaksProducts:ve??[],translations:Ie}}catch(n){return console.error(n),null}};class me{constructor(e){this.storefront=e}async query(e,s){if("query"in this.storefront&&"i18n"in this.storefront)return await this.storefront.query(e,s);if("request"in this.storefront)return(await this.storefront.request(e,s)).data;if("shopifyDomain"in this.storefront&&"storefrontAccessToken"in this.storefront){const l=await fetch(`https://${this.storefront.shopifyDomain}/api/${ue}/graphql.json`,{body:JSON.stringify({query:e,variables:s==null?void 0:s.variables}),headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefront.storefrontAccessToken},method:"POST"});if(!l.ok)throw new Error(l.statusText);return(await l.json()).data}else{const l=await fetch(this.storefront.getStorefrontApiUrl(),{body:JSON.stringify({query:e,variables:s==null?void 0:s.variables}),headers:this.storefront.getPublicTokenHeaders(),method:"POST"});if(!l.ok)throw new Error(l.statusText);return(await l.json()).data}}get i18n(){if("i18n"in this.storefront)return this.storefront.i18n}}const _="kaching-bundles-block",A=1e4,pe="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",fe="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",S=new WeakSet,D=async t=>{const e=t.document;if(!t.customElements.get(_)){if(S.has(e))return C(t,_);S.add(e);try{await be(t)}catch(s){throw S.delete(e),s}}},he=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",ge=()=>he()?pe:fe,be=t=>{const e=t.document;return new Promise((s,l)=>{const a=ge();if(e.querySelector(`script[src="${a}"]`)){s();return}const c=e.createElement("script");c.src=a,c.onload=()=>C(t,_).then(s).catch(l),c.onerror=()=>l(new Error("Failed to load script")),e.head.appendChild(c)})},C=(t,e)=>new Promise((s,l)=>{if(t.customElements.get(e)){s();return}Promise.race([t.customElements.whenDefined(e),new Promise((a,r)=>setTimeout(()=>r(new Error(`Custom element "${e}" failed to register within ${A}ms`)),A))]).then(()=>s()).catch(l)});class ye extends HTMLElement{constructor(){super(...arguments),this.innerElement=null,this.handleItemsChanged=null,this.currentProductId=null}static get observedAttributes(){return["selected-variant-id","product-id"]}async connectedCallback(){await this.initialize()}async initialize(){var r,c;if(this.hasAttribute("demo")){this.cleanup(),await D(window),this.renderInnerElement($);return}const e=this.getAttribute("shop-domain"),s=this.getAttribute("storefront-token"),l=this.getAttribute("product-id");if(!e||!s||!l||l===this.currentProductId)return;this.currentProductId=l,this.cleanup();const[a]=await Promise.all([de({shopifyDomain:e,storefrontAccessToken:s},{productId:l,dealBlockId:this.getAttribute("deal-block-id")??void 0,country:((r=this.getAttribute("country"))==null?void 0:r.toUpperCase())??void 0,language:((c=this.getAttribute("language"))==null?void 0:c.toUpperCase())??void 0}),D(window)]);!a||l!==this.currentProductId||this.renderInnerElement(a)}renderInnerElement(e){const{config:s,dealBlock:l,product:a,otherProducts:r,mediaImages:c,collectionBreaksProducts:n,translations:m}=e;this.innerElement=document.createElement("kaching-bundles-block"),this.innerElement.setAttribute("deal-block-id",l.id),this.innerElement.setAttribute("config",JSON.stringify(s)),this.innerElement.setAttribute("deal-block",JSON.stringify(l)),this.innerElement.setAttribute("media-images",JSON.stringify(c??[])),this.innerElement.setAttribute("product",JSON.stringify(a)),this.innerElement.setAttribute("other-products",JSON.stringify(r??[])),this.innerElement.setAttribute("collection-breaks-products",JSON.stringify(n??[])),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():a.variants[0].id)),this.appendChild(this.innerElement);const u=()=>{const i=this.innerElement.items();i&&this.dispatchEvent(new CustomEvent("items-changed",{detail:{items:i},bubbles:!0}))};this.handleItemsChanged=i=>{i.stopPropagation(),u()},this.innerElement.addEventListener("kaching-bundles-block-loaded",()=>{this.innerElement.addEventListener("items-changed",this.handleItemsChanged),u(),this.dispatchEvent(new CustomEvent("loaded",{bubbles:!0}))},{once:!0})}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,s,l){s!==l&&(e==="product-id"?this.initialize():e==="selected-variant-id"&&this.innerElement&&l&&this.innerElement.setAttribute("current-variant-id",l.includes("/")?String(l.split("/").pop()):l))}items(){return this.innerElement?this.innerElement.items():[]}disconnectedCallback(){this.cleanup(),this.currentProductId=null}}customElements.define("kaching-bundle-component",ye)})();