commerce-kit 0.0.40 → 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.
package/dist/index.js CHANGED
@@ -1,10 +1,247 @@
1
- import{z as c}from"zod";function b(t,e){if(!t)throw new Error(e)}var H=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},L=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},Y=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var pt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Q=t=>Object.entries(t).map(([e,n])=>`${e}:"${pt(n)}"`).join(" AND ").trim();function q(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var lt=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional(),stock:c.coerce.number().optional().transform(t=>t===void 0?1/0:t),digitalAsset:c.string().optional(),preview:c.string().optional()});function O({default_price:t,marketing_features:e,...n}){return b(t,"Product must have a default price"),b(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:e.map(a=>a.name).filter(Boolean),metadata:lt.parse(n.metadata)}}function mt(t){return!!(t.active&&!t.deleted&&t.default_price)}function W(t){return{...t,data:t.data.filter(mt)}}function K(t){return t.data.map(O)}function Z(t){return t}function tt(t){return t.data.map(Z)}function V(t){return t.filter((e,n,a)=>n===a.findIndex(o=>o.metadata.slug===e.metadata.slug))}var et=t=>!t.deleted&&t.active,F=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),couponCode:c.string().optional(),taxedAmount:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string())),rt=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function z(t){let e=t.payment_method;b(typeof e!="string","Payment method should not be a string");let n=t.customer;b(typeof n!="string"&&!n?.deleted,"Customer should not be a string");let a=F.parse(t.metadata),o=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let u=rt.safeParse(Y(String(i)));return u.success?u.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:e,taxBreakdown:o}}function nt({payment_method:t,latest_charge:e,...n}){b(typeof t=="object","Payment method is missing from order"),b(typeof e=="object","Latest charge is missing from order");let a=F.parse(n.metadata),o=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let u=rt.safeParse(Y(String(i)));return u.success?u.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:a}}import{revalidateTag as P}from"next/cache";import v from"stripe";import{z as S}from"zod";var l=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t};import at from"stripe";var ft=process.env.STRIPE_SECRET_KEY,gt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:ft,StripeCurrency:gt};var yt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],m=({tags:t,revalidate:e,cache:n,tagPrefix:a,secretKey:o})=>{let r=o??y.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let i=yt(t,a);return new at(r,{typescript:!0,apiVersion:"2025-01-27.acacia",httpClient:at.createFetchHttpClient((f,s)=>fetch(f,{...s,cache:n??s?.cache,next:{tags:i??s?.next?.tags,revalidate:e??s?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var R={DEBUG:0,LOG:1,WARN:2,ERROR:3},ht="LOG",xt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in R?process.env.LOG_LEVEL:ht,T=R[xt],d={time(t){T>R.DEBUG||console.time(t)},timeEnd(t){T>R.DEBUG||console.timeEnd(t)},log(...t){T>R.LOG||console.log(...t)},dir(t,e){T>R.LOG||console.dir(t,e)},warn(...t){T>R.WARN||console.warn(...t)},error(...t){T>R.ERROR||console.error(...t)}};var C=t=>t.filter(Boolean),x={accountGetById:{tags:({accountId:t})=>C(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>C(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>C(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>C(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>C(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>C(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>C(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>C(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>C(["tax-settings"]),revalidate:()=>{}}};import{neon as wt}from"@neondatabase/serverless";var B;process.env.DATABASE_URL&&(B=wt(process.env.DATABASE_URL));var j=1e3;function ie({productId:t,cartId:e}){return e?_t({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):Ct({productId:t})}async function _t({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([k(t),ct(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(o.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(y.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let i=r.cart.metadata??{},s=L(i[t])+(n==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let w=Rt(r)+(o.default_price.unit_amount??0);try{return await E({paymentIntentId:e,data:{metadata:i,amount:w||j},clearTaxCalculation:a})}catch(h){d.error(h)}finally{P(`cart-${e}`)}}async function $(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(it.includes(r.status)){let i=z(r);if(!i)return null;let u=await X(i.metadata),{metadata:{shippingRateId:f}}=i,s=f&&await N(f);return{cart:i,lines:u.map(({product:w,quantity:h})=>w?{product:w,quantity:h}:null).filter(Boolean),shippingRate:s||null}}}catch(r){if(d.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Ct({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await k(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await o.paymentIntents.create({currency:y.StripeCurrency,amount:r?.default_price.unit_amount||j,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw d.error(r),r}}async function se({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return d.warn(`Product not found: ${e}`),t;let o=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),r=t?U(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:o}}async function ce({cartId:t,productId:e,quantity:n}){let[a,o]=await Promise.all([J(e),$(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!o)throw new Error(`Cart not found: ${t}`);if(y.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let r=o.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let i=U(o)+(a.default_price.unit_amount??0);try{return await E({paymentIntentId:t,data:{metadata:r,amount:i||j}})}catch(u){d.error(u)}finally{P(`cart-${t}`)}}async function J(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return O(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ue({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),r=await m({secretKey:a,tagPrefix:n,tags:x.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:Q({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.allSettled(r.data.map(i=>J(i.id))),q(K(W(r)))}async function St(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l();if(t.filter?.category){let i=t.filter?.category,f=await m({secretKey:a,tagPrefix:n,tags:x.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:Q({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return q(V(K(W(f)))).slice(t.offset||0,t.first)}let r=await m({secretKey:a,tagPrefix:n,tags:x.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return q(V(K(W(r))).filter(et)).slice(t.offset||0,t.first)}async function de(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),o=await m({secretKey:n,tagPrefix:e,tags:x.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return tt(o)}async function N(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:x.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(d.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function pe(){let e=(await St({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function le(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:x.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await o.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(d.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function me(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),a=m({secretKey:n,tagPrefix:e,tags:x.accountGetById.tags({}),cache:"force-cache"});try{let[o,r]=await H(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(o){if(d.error(o),o instanceof v.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function bt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:x.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge","customer"]},{stripeAccount:e});return nt(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function fe(t){let e=await bt(t);if(!e)return null;let n=st(e.metadata),a=await Promise.all(n.map(async([i,u])=>({product:await k(i),quantity:u}))),{metadata:{shippingRateId:o}}=e,r=o&&await N(o);return{order:e,lines:a.map(({product:i,quantity:u})=>i?{product:i,quantity:u}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return O(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}},it=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],st=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),vt=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e}),i=typeof r.customer=="string"?await ut(r.customer):null;if(it.includes(r.status))return z({...r,customer:i})}catch(r){if(d.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function X(t){let e=st(t);return await Promise.all(e.map(async([a,o])=>({product:await k(a),quantity:o})))}var ct=async t=>{let e=await vt(t);if(!e)return null;let n=await X(e.metadata),{metadata:{shippingRateId:a}}=e,o=a&&await N(a);return{cart:e,lines:n.map(({product:r,quantity:i})=>r?{product:r,quantity:i}:null).filter(Boolean),shippingRate:o||null}},Rt=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0,Pt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];function Et({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||o>=r)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,u=e.amount,f=Pt.some(p=>!n[p]&&!t.cart.metadata[p]?!1:n[p]!==t.cart.metadata[p]),s=a.length!==t.lines.length||a.some(p=>{let _=t.lines.find(A=>A.product.id===p.product?.id);return p.product?.default_price.unit_amount!==_?.product.default_price.unit_amount||p.quantity!==_?.quantity});return u&&i!==u||f||s}var ge=t=>S.object({name:S.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:S.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:S.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:S.string({required_error:t.line1Required}).min(1,t.line1Required),line2:S.string().optional().nullable().default(""),postalCode:S.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:S.string().optional().nullable().default(""),phone:S.string().optional().nullable().default(""),taxId:S.string().optional().nullable().default(""),email:S.string().optional().nullable().default("")}),At=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:i,secretKey:u}=await l(),f=m({secretKey:u,tagPrefix:i,tags:x.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let s=a?await N(a):null,w=typeof s?.tax_code=="string"?s.tax_code:s?.tax_code?.id,h=await Bt(),p=y.StripeCurrency==="usd"||y.StripeCurrency==="cad"?"exclusive":"inclusive",_=h.defaults.tax_behavior==="inferred_by_currency"?p:h.defaults.tax_behavior??p;h.defaults.tax_behavior||d.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y.StripeCurrency}: ${p}.`),d.time("createTaxCalculation ${cartId}");let A=await f.tax.calculations.create({expand:["line_items"],line_items:t.map(M=>({...M,tax_behavior:M.tax_behavior??_})),currency:y.StripeCurrency,shipping_cost:s?.active&&s?.fixed_amount?{amount:s.fixed_amount.amount,tax_behavior:s.tax_behavior==="inclusive"?"inclusive":s.tax_behavior==="exclusive"?"exclusive":_,tax_code:w??h.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return d.timeEnd("createTaxCalculation ${cartId}"),console.log(JSON.stringify(A).length),A},ot={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};async function ut(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:["customers",`customers-${t}`],cache:"force-cache"});try{let r=await o.customers.retrieve(t,{},{stripeAccount:e});return r.deleted?null:r}catch(r){if(d.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}function It(t,e){return e.coupon.amount_off?Math.max(t-e.coupon.amount_off,0):e.coupon.percent_off?Math.floor(t*(1-e.coupon.percent_off/100)):t}var E=async({paymentIntentId:t,data:e,customerOverride:n,clearTaxCalculation:a})=>{let{stripeAccount:o,storeId:r,secretKey:i}=await l(),u=await ct(t);b(u,`Cart not found: ${t}`);let f=e.amount?e.amount.toString():null,s=F.parse({...u.cart.metadata,...e.metadata});d.time("getProductsFromMetadata");let w=await X(s);d.timeEnd("getProductsFromMetadata");let h=!a&&Et({oldCart:u,data:e,mergedMetadata:s,lines:w});console.log({shouldRecalculateTax:h});let p=h?await At({cartId:t,taxId:s.taxId??null,shippingRateId:s.shippingRateId??null,billingAddress:{country:s["billingAddress.country"]??"",city:s["billingAddress.city"]??"",line1:s["billingAddress.line1"]??"",line2:s["billingAddress.line2"]??"",name:s["billingAddress.name"]??"",postalCode:s["billingAddress.postalCode"]??"",state:s["billingAddress.state"]??""},lineItems:w.map(({product:g,quantity:G})=>{if(g?.default_price.unit_amount)return{product:g.id,reference:[g.metadata.slug,g.metadata.variant].filter(Boolean).join("-"),quantity:G,amount:g.default_price.unit_amount*G,tax_behavior:g.default_price.tax_behavior==="exclusive"?"exclusive":g.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:g.tax_code?typeof g.tax_code=="string"?g.tax_code:g.tax_code.id:void 0}}).filter(Boolean)}):null,_=n??(e.customer?await ut(e.customer):u.cart.customer);console.log({customer:_});let A=m({secretKey:i,tagPrefix:r,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let M=p&&Object.fromEntries(p.tax_breakdown.map(g=>({taxType:g.tax_rate_details.tax_type,taxPercentage:g.tax_rate_details.percentage_decimal,taxAmount:g.amount})).map((g,G)=>[`taxBreakdown${G}`,JSON.stringify(g)])),I=p?p.amount_total:e.amount,D=I&&_?.discount?.coupon.valid?It(I,_.discount):I;console.log({"discount.coupon.amount_off":_?.discount?.coupon.amount_off,"discount.coupon.percent_off":_?.discount?.coupon.percent_off,discountedAmount:D,taxedAmount:I,"taxCalculation.amount_total":p?.amount_total,"data.amount":e.amount,netAmount:f});let dt=await A.paymentIntents.update(t,{...e,...D&&{amount:D},metadata:{...s,...f&&{netAmount:f},...I&&{taxedAmount:I},...p?{...ot,...M,taxCalculationId:p.id,taxCalculationExp:p?.expires_at}:{...a&&{...ot,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:o});return d.timeEnd(`paymentIntents.update ${t}`),dt},U=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Tt(t):0,Tt=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function ye({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([J(t),$(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(y.StripeCurrency?.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let i=r.cart.metadata??{},s=L(i[t])+(n==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let w=U(r)+(o.default_price.unit_amount??0);try{return await E({paymentIntentId:e,data:{metadata:i,amount:w||j},clearTaxCalculation:a})}catch(h){d.error(h)}finally{P(`cart-${e}`)}}var he=async({cartId:t,email:e})=>{let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await E({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){d.error(a)}finally{P(`cart-${t}`)}},xe=async({cartId:t,taxId:e})=>{let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await E({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){d.error(a)}finally{P(`cart-${t}`)}};async function we({cartId:t,shippingRateId:e}){let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);d.time(`cartSaveShipping ${t}`);let a=await N(e);if(d.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{d.time(`updatePaymentIntent ${t}`);let o=await E({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:U({...n,shippingRate:a})}});return d.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){d.error(o)}finally{P(`cart-${t}`)}}async function _e({cartId:t,billingAddress:e}){if(!await $(t))throw new Error(`Cart not found: ${t}`);try{return await E({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??"","billingAddress.email":e.email??""}}})}catch(a){d.error(a)}finally{P(`cart-${t}`)}}async function Bt(){let{stripeAccount:t,storeId:e,secretKey:n}=await l();return await m({secretKey:n,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function Ce(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function Se(t){if(!B)return null;let{storeId:e}=await l();return await B`
1
+ var Wt=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var mt=(t,e)=>{for(var r in e)Wt(t,r,{get:e[r],enumerable:!0})};import{neon as Kt}from"@neondatabase/serverless";var G,ft=P(()=>{"use strict";process.env.DATABASE_URL&&(G=Kt(process.env.DATABASE_URL))});var Qt,Vt,h,H=P(()=>{"use strict";Qt=process.env.STRIPE_SECRET_KEY,Vt=process.env.STRIPE_CURRENCY,h={StripeSecretKey:Qt,StripeCurrency:Vt}});function v(t,e){if(!t)throw new Error(e)}var gt,yt,q,Z,F=P(()=>{"use strict";gt=t=>{v(Number.isInteger(t),"Value must be an integer")},yt=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},q=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},Z=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}}});var jt,tt,et=P(()=>{"use strict";jt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),tt=t=>Object.entries(t).map(([e,r])=>`${e}:"${jt(r)}"`).join(" AND ").trim()});import{z as c}from"zod";function U(t){return t.toSorted((e,r)=>{let n=Number(e.metadata.order),o=Number(r.metadata.order);return Number.isNaN(n)&&Number.isNaN(o)||n===o?r.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(o)?-1:n-o})}function Y({default_price:t,marketing_features:e,...r}){return v(t,"Product must have a default price"),v(typeof t=="object","Product default price must be an object"),{...r,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:Jt.parse(r.metadata)}}function zt(t){return!!(t.active&&!t.deleted&&t.default_price)}function W(t){return{...t,data:t.data.filter(zt)}}function K(t){return t.data.map(Y)}function ht(t){return t}function wt(t){return t.data.map(ht)}function rt(t){return t.filter((e,r,n)=>r===n.findIndex(o=>o.metadata.slug===e.metadata.slug))}function at(t){let e=t.payment_method;v(typeof e!="string","Payment method should not be a string");let r=t.customer;v(typeof r!="string"&&!r?.deleted,"Customer should not be a string");let n=Q.parse(t.metadata),o=Object.entries(n).filter(([a])=>a.startsWith("taxBreakdown")).map(([a,i])=>{let u=Pt.safeParse(Z(String(i)));return u.success?u.data:null}).filter(Boolean);return{...t,metadata:n,customer:r,payment_method:e,taxBreakdown:o}}function Ct({payment_method:t,latest_charge:e,...r}){v(typeof t=="object","Payment method is missing from order"),v(typeof e=="object","Latest charge is missing from order");let n=Q.parse(r.metadata),o=Object.entries(n).filter(([a])=>a.startsWith("taxBreakdown")).map(([a,i])=>{let u=Pt.safeParse(Z(String(i)));return u.success?u.data:null}).filter(Boolean);return{...r,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:n}}var Jt,xt,Q,Pt,vt=P(()=>{"use strict";F();et();Jt=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional(),stock:c.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:c.string().optional(),preview:c.string().optional()});xt=t=>!t.deleted&&t.active,Q=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),couponCode:c.string().optional(),taxedAmount:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string(),c.string())),Pt=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()})});var R,Xt,Ht,N,d,St=P(()=>{"use strict";R={DEBUG:0,LOG:1,WARN:2,ERROR:3},Xt="LOG",Ht=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in R?process.env.LOG_LEVEL:Xt,N=R[Ht],d={time(t){N>R.DEBUG||console.time(t)},timeEnd(t){N>R.DEBUG||console.timeEnd(t)},log(...t){N>R.LOG||console.log(...t)},dir(t,e){N>R.LOG||console.dir(t,e)},warn(...t){N>R.WARN||console.warn(...t)},error(...t){N>R.ERROR||console.error(...t)}}});var I,x,It=P(()=>{"use strict";I=t=>t.filter(Boolean),x={accountGetById:{tags:({accountId:t})=>I(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>I(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>I(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>I(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>I(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>I(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>I(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>I(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>I(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>I(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>I(["tax-settings"]),revalidate:()=>{}}}});import _t from"stripe";var Zt,f,nt=P(()=>{"use strict";H();Zt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(r=>`${e}-${r}`)],f=({tags:t,revalidate:e,cache:r,tagPrefix:n,secretKey:o})=>{let a=o??h.StripeSecretKey;if(!a)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let i=Zt(t,n);return new _t(a,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:_t.createFetchHttpClient(((g,s)=>fetch(g,{...s,cache:r??s?.cache,next:{tags:i??s?.next?.tags,revalidate:e??s?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var m,bt=P(()=>{"use strict";m=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t}});import{revalidateTag as A}from"next/cache";import b from"stripe";import{z as _}from"zod";function Et({productId:t,cartId:e}){return e?ot({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):te({productId:t})}async function ot({productId:t,cartId:e,operation:r,clearTaxCalculation:n}){let[o,a]=await Promise.all([k(t),Tt(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!a)throw new Error(`Cart not found: ${e}`);if(o.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!h.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(h.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let i=a.cart.metadata??{},s=q(i[t])+(r==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let C=ae(a)+(o.default_price.unit_amount??0);try{return await B({paymentIntentId:e,data:{metadata:i,amount:C||V},clearTaxCalculation:n})}catch(w){d.error(w)}finally{A(`cart-${e}`)}}async function E(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let a=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(Bt.includes(a.status)){let i=at(a);if(!i)return null;let u=await st(i.metadata),{metadata:{shippingRateId:g}}=i,s=g&&await O(g);return{cart:i,lines:u.map(({product:C,quantity:w})=>C?{product:C,quantity:w}:null).filter(Boolean),shippingRate:s||null}}}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function te({productId:t}={}){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,cache:"no-cache"});if(!h.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let a=t?await k(t):null;if(a&&a.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await o.paymentIntents.create({currency:h.StripeCurrency,amount:a?.default_price.unit_amount||V,automatic_payment_methods:{enabled:!0},metadata:{...a&&{[a.id]:"1"}}},{stripeAccount:e})}catch(a){throw d.error(a),a}}async function Ze({cart:t,add:e}){if(!e)return t;let r=await k(e);if(!r)return d.warn(`Product not found: ${e}`),t;let o=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:r,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),a=t?j(t)+(r.default_price.unit_amount??0):r.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:a},lines:o}}async function tr({cartId:t,productId:e,quantity:r}){let[n,o]=await Promise.all([L(e),E(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!o)throw new Error(`Cart not found: ${t}`);if(h.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let a=o.cart.metadata??{};r<=0?a[e]="":a[e]=r.toString();let i=j(o)+(n.default_price.unit_amount??0);try{return await B({paymentIntentId:t,data:{metadata:a,amount:i||V}})}catch(u){d.error(u)}finally{A(`cart-${t}`)}}async function L(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let a=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return Y(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function At({slug:t}){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),a=await f({secretKey:n,tagPrefix:r,tags:x.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:tt({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(a.data.length>1&&a.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.allSettled(a.data.map(i=>L(i.id))),U(K(W(a)))}async function it(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m();if(t.filter?.category){let i=t.filter?.category,g=await f({secretKey:n,tagPrefix:r,tags:x.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:tt({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return U(rt(K(W(g)))).slice(t.offset||0,t.first)}let a=await f({secretKey:n,tagPrefix:r,tags:x.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return U(rt(K(W(a))).filter(xt)).slice(t.offset||0,t.first)}async function er(){let{stripeAccount:t,storeId:e,secretKey:r}=await m(),o=await f({secretKey:r,tagPrefix:e,tags:x.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return wt(o)}async function O(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let a=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return a}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function rr(){let e=(await it({first:100})).map(n=>n.metadata.category).filter(Boolean),r=new Set(e);return Array.from(r)}async function ar(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await o.fileLinks.create({file:t},{stripeAccount:e})}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function nr(){let{stripeAccount:t,storeId:e,secretKey:r}=await m(),n=f({secretKey:r,tagPrefix:e,tags:x.accountGetById.tags({}),cache:"force-cache"});try{let[o,a]=await yt(n.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=a?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:a,logo:null}:{account:a,logo:i}}catch(o){if(d.error(o),o instanceof b.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function ee(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let a=await o.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge","customer"]},{stripeAccount:e});return Ct(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function or(t){let e=await ee(t);if(!e)return null;let r=$t(e.metadata),n=await Promise.all(r.map(async([i,u])=>({product:await k(i),quantity:u}))),{metadata:{shippingRateId:o}}=e,a=o&&await O(o);return{order:e,lines:n.map(({product:i,quantity:u})=>i?{product:i,quantity:u}:null).filter(Boolean),shippingRate:a||null}}async function st(t){let e=$t(t);return await Promise.all(e.map(async([n,o])=>({product:await k(n),quantity:o})))}function oe({oldCart:t,data:e,mergedMetadata:r,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),a=r.taxCalculationExp?Number.parseInt(r.taxCalculationExp,10)*1e3:null;if(!a||o>=a)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,u=e.amount,g=ne.some(l=>!r[l]&&!t.cart.metadata[l]?!1:r[l]!==t.cart.metadata[l]),s=n.length!==t.lines.length||n.some(l=>{let S=t.lines.find($=>$.product.id===l.product?.id);return l.product?.default_price.unit_amount!==S?.product.default_price.unit_amount||l.quantity!==S?.quantity});return u&&i!==u||g||s}async function Gt(t){let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:["customers",`customers-${t}`],cache:"force-cache"});try{let a=await o.customers.retrieve(t,{},{stripeAccount:e});return a.deleted?null:a}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}function se(t,e){return e.coupon.amount_off?Math.max(t-e.coupon.amount_off,0):e.coupon.percent_off?Math.floor(t*(1-e.coupon.percent_off/100)):t}async function sr({productId:t,cartId:e,operation:r,clearTaxCalculation:n}){let[o,a]=await Promise.all([L(t),E(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!a)throw new Error(`Cart not found: ${e}`);if(h.StripeCurrency?.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let i=a.cart.metadata??{},s=q(i[t])+(r==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let C=j(a)+(o.default_price.unit_amount??0);try{return await B({paymentIntentId:e,data:{metadata:i,amount:C||V},clearTaxCalculation:n})}catch(w){d.error(w)}finally{A(`cart-${e}`)}}async function dr({cartId:t,shippingRateId:e}){let r=await E(t);if(!r)throw new Error(`Cart not found: ${t}`);d.time(`cartSaveShipping ${t}`);let n=await O(e);if(d.timeEnd(`cartSaveShipping ${t}`),!n)throw new Error(`Shipping rate not found: ${e}`);try{d.time(`updatePaymentIntent ${t}`);let o=await B({paymentIntentId:t,data:{metadata:{...r.cart.metadata,shippingRateId:e},amount:j({...r,shippingRate:n})}});return d.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){d.error(o)}finally{A(`cart-${t}`)}}async function pr({cartId:t,billingAddress:e}){if(!await E(t))throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??"","billingAddress.email":e.email??""}}})}catch(n){d.error(n)}finally{A(`cart-${t}`)}}async function ue(){let{stripeAccount:t,storeId:e,secretKey:r}=await m();return await f({secretKey:r,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function lr(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,r])=>[e,q(r)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function mr(t){if(!G)return null;let{storeId:e}=await m();return await G`
2
2
  select * from reviews
3
3
  where product_id = ${t.productId} and store_id = ${e}
4
4
  order by created_at desc
5
5
  limit ${t.first??100}
6
6
  offset ${t.offset??0}
7
- `}async function be(t){if(!B)return null;let{storeId:e}=await l();return await B`
7
+ `}async function fr(t){if(!G)return null;let{storeId:e}=await m();return await G`
8
8
  insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
9
9
  values (${e}, ${t.productId}, ${t.author}, ${t.email}, ${t.content}, ${t.rating}, now(), now())
10
- `}var ve=l;export{me as accountGet,Rt as calculateCartTotalNet,Tt as calculateCartTotalNetWithoutShipping,U as calculateCartTotalPossiblyWithTax,ie as cartAdd,se as cartAddOptimistic,ye as cartChangeQuantity,Ce as cartCount,Ct as cartCreate,$ as cartGet,_e as cartSaveBillingAddress,he as cartSaveEmail,we as cartSaveShipping,xe as cartSaveTax,ce as cartSetQuantity,_t as cartUpdateQuantity,pe as categoryBrowse,ve as contextGet,le as fileGet,ge as getAddressSchema,ct as getCartWithProductsById,st as getProductsFromCart,X as getProductsFromMetadata,fe as orderGet,St as productBrowse,ue as productGet,J as productGetById,be as productReviewAdd,Se as productReviewBrowse,m as provider,de as shippingBrowse,N as shippingGet,Bt as taxDefaultGet,E as updatePaymentIntent};
10
+ `}var V,k,Bt,$t,re,Tt,ae,ne,ir,ie,Rt,B,j,ce,cr,ur,gr,ct=P(()=>{"use strict";ft();H();vt();St();It();nt();et();F();bt();V=1e3;k=async t=>{let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.productGetById.tags({productId:t}),cache:"force-cache"});try{let a=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return Y(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}},Bt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],$t=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,r])=>[e,q(r)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),re=async t=>{let{stripeAccount:e,storeId:r,secretKey:n}=await m(),o=f({secretKey:n,tagPrefix:r,tags:x.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let a=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e}),i=typeof a.customer=="string"?await Gt(a.customer):null;if(Bt.includes(a.status))return at({...a,customer:i})}catch(a){if(d.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}};Tt=async t=>{let e=await re(t);if(!e)return null;let r=await st(e.metadata),{metadata:{shippingRateId:n}}=e,o=n&&await O(n);return{cart:e,lines:r.map(({product:a,quantity:i})=>a?{product:a,quantity:i}:null).filter(Boolean),shippingRate:o||null}},ae=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:r,quantity:n})=>e+(r.default_price?.unit_amount??0)*n,0):0,ne=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];ir=t=>_.object({name:_.string({message:t.nameRequired}).min(1,t.nameRequired),city:_.string({message:t.cityRequired}).min(1,t.cityRequired),country:_.string({message:t.countryRequired}).min(1,t.countryRequired),line1:_.string({message:t.line1Required}).min(1,t.line1Required),line2:_.string().optional().nullable().default(""),postalCode:_.string({message:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:_.string().optional().nullable().default(""),phone:_.string().optional().nullable().default(""),taxId:_.string().optional().nullable().default(""),email:_.string().optional().nullable().default("")}),ie=async({lineItems:t,billingAddress:e,cartId:r,shippingRateId:n,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!h.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:a,storeId:i,secretKey:u}=await m(),g=f({secretKey:u,tagPrefix:i,tags:x.createTaxCalculation.tags({cartId:r}),cache:"force-cache"});if(!e?.country)return null;let s=n?await O(n):null,C=typeof s?.tax_code=="string"?s.tax_code:s?.tax_code?.id,w=await ue(),l=h.StripeCurrency==="usd"||h.StripeCurrency==="cad"?"exclusive":"inclusive",S=w.defaults.tax_behavior==="inferred_by_currency"?l:w.defaults.tax_behavior??l;w.defaults.tax_behavior||d.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${h.StripeCurrency}: ${l}.`),d.time(`createTaxCalculation ${r}`);let $=await g.tax.calculations.create({expand:["line_items"],line_items:t.map(M=>({...M,tax_behavior:M.tax_behavior??S})),currency:h.StripeCurrency,shipping_cost:s?.active&&s?.fixed_amount?{amount:s.fixed_amount.amount,tax_behavior:s.tax_behavior==="inclusive"?"inclusive":s.tax_behavior==="exclusive"?"exclusive":S,tax_code:C??w.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:a});return d.timeEnd(`createTaxCalculation ${r}`),console.log(JSON.stringify($).length),$},Rt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};B=async({paymentIntentId:t,data:e,customerOverride:r,clearTaxCalculation:n})=>{let{stripeAccount:o,storeId:a,secretKey:i}=await m(),u=await Tt(t);v(u,`Cart not found: ${t}`);let g=e.amount?e.amount.toString():null,s=Q.parse({...u.cart.metadata,...e.metadata});d.time("getProductsFromMetadata");let C=await st(s);d.timeEnd("getProductsFromMetadata");let w=!n&&oe({oldCart:u,data:e,mergedMetadata:s,lines:C});console.log({shouldRecalculateTax:w});let l=w?await ie({cartId:t,taxId:s.taxId??null,shippingRateId:s.shippingRateId??null,billingAddress:{country:s["billingAddress.country"]??"",city:s["billingAddress.city"]??"",line1:s["billingAddress.line1"]??"",line2:s["billingAddress.line2"]??"",name:s["billingAddress.name"]??"",postalCode:s["billingAddress.postalCode"]??"",state:s["billingAddress.state"]??""},lineItems:C.map(({product:y,quantity:D})=>{if(y?.default_price.unit_amount)return{product:y.id,reference:[y.metadata.slug,y.metadata.variant].filter(Boolean).join("-"),quantity:D,amount:y.default_price.unit_amount*D,tax_behavior:y.default_price.tax_behavior==="exclusive"?"exclusive":y.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:y.tax_code?typeof y.tax_code=="string"?y.tax_code:y.tax_code.id:void 0}}).filter(Boolean)}):null,S=r??(e.customer?await Gt(e.customer):u.cart.customer);console.log({customer:S});let $=f({secretKey:i,tagPrefix:a,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let M=l&&Object.fromEntries(l.tax_breakdown.map(y=>({taxType:y.tax_rate_details.tax_type,taxPercentage:y.tax_rate_details.percentage_decimal,taxAmount:y.amount})).map((y,D)=>[`taxBreakdown${D}`,JSON.stringify(y)])),T=l?l.amount_total:e.amount,X=T&&S?.discount?.coupon.valid?se(T,S.discount):T;console.log({"discount.coupon.amount_off":S?.discount?.coupon.amount_off,"discount.coupon.percent_off":S?.discount?.coupon.percent_off,discountedAmount:X,taxedAmount:T,"taxCalculation.amount_total":l?.amount_total,"data.amount":e.amount,netAmount:g});let Yt=await $.paymentIntents.update(t,{...e,...X&&{amount:X},metadata:{...s,...g&&{netAmount:g},...T&&{taxedAmount:T},...l?{...Rt,...M,taxCalculationId:l.id,taxCalculationExp:l?.expires_at}:{...n&&{...Rt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:o});return d.timeEnd(`paymentIntents.update ${t}`),Yt},j=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+ce(t):0,ce=t=>t?t.lines.reduce((e,{product:r,quantity:n})=>e+(r.default_price?.unit_amount??0)*n,0):0;cr=async({cartId:t,email:e})=>{let r=await E(t);if(!r)throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{...r.cart.metadata,email:e}}})}catch(n){d.error(n)}finally{A(`cart-${t}`)}},ur=async({cartId:t,taxId:e})=>{let r=await E(t);if(!r)throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{...r.cart.metadata,taxId:e}}})}catch(n){d.error(n)}finally{A(`cart-${t}`)}};gr=m});var Nt={};mt(Nt,{StripeProvider:()=>J,createStripeProvider:()=>pe});function pe(t){return new J(t)}var J,qt=P(()=>{"use strict";ct();J=class{constructor(e){this.config=e}mapStripeProduct(e){let r=e.default_price?.unit_amount||0,n=e.default_price?.currency||"usd";return{id:e.id,name:e.name,slug:e.metadata?.slug,summary:e.description,images:e.images||[],active:e.active,price:r/100,currency:n.toUpperCase(),stock:Number.parseInt(e.metadata?.stock||"0",10),stripeId:e.id,metadata:e.metadata||{}}}async productBrowse(e){let r=await it({first:e.first||10,...e}),n=r.data.map(o=>this.mapStripeProduct(o));return{data:n,meta:{count:r.totalCount||n.length,offset:e.offset||0,limit:e.first||10,hasMore:n.length===(e.first||10)}}}async productGet(e){if(e.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),e.slug){let r=await At({slug:e.slug});return r?this.mapStripeProduct(r):null}if(e.id){let r=await L(e.id);return r?this.mapStripeProduct(r):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(e){return{cartId:(await Et({productId:e.variantId,cartId:e.cartId}))?.id||e.cartId||""}}async cartUpdate(e){let r=e.quantity>0?"INCREASE":"DECREASE";return{cartId:(await ot({cartId:e.cartId,productId:e.variantId,operation:r}))?.id||e.cartId}}async cartClear(e){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartGet(e){let r=await E(e.cartId);if(!r)return null;let n=r.lines.map(a=>({id:a.product?.id||"",productId:a.product?.id||"",variantId:a.product?.id,quantity:a.quantity,price:(a.product?.default_price?.unit_amount||0)/100})),o=n.reduce((a,i)=>a+i.price*i.quantity,0);return{id:r.cart.id,customerId:r.cart.customer,items:n,total:o,currency:r.cart.currency?.toUpperCase()||"USD",createdAt:new Date(r.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}}});function kt(t){return!t||t.length===0?dt:`
11
+ query ProductQuery($slug: String!) {
12
+ product(slug: $slug) {
13
+ ${t.join(`
14
+ `)}
15
+ }
16
+ }
17
+ `}function Mt(t){return!t||t.length===0?ut:`
18
+ query ProductsQuery(
19
+ $offset: Int
20
+ $limit: Int
21
+ $category: String
22
+ $query: String
23
+ $active: Boolean
24
+ $excludeBundles: Boolean
25
+ $orderBy: String
26
+ $orderDirection: String
27
+ ) {
28
+ products(
29
+ offset: $offset
30
+ limit: $limit
31
+ category: $category
32
+ query: $query
33
+ active: $active
34
+ excludeBundles: $excludeBundles
35
+ orderBy: $orderBy
36
+ orderDirection: $orderDirection
37
+ ) {
38
+ data {
39
+ ${t.join(`
40
+ `)}
41
+ }
42
+ meta {
43
+ count
44
+ offset
45
+ limit
46
+ hasMore
47
+ }
48
+ }
49
+ }
50
+ `}var Lt,ut,dt,le,Ot,Dt=P(()=>{"use strict";Lt=`
51
+ fragment ProductFragment on Product {
52
+ id
53
+ name
54
+ slug
55
+ summary
56
+ images
57
+ active
58
+ type
59
+ createdAt
60
+ updatedAt
61
+ category {
62
+ id
63
+ name
64
+ slug
65
+ description
66
+ image
67
+ }
68
+ variants {
69
+ id
70
+ price
71
+ originalPrice
72
+ prePromotionPrice
73
+ stock
74
+ shippable
75
+ attributes
76
+ combinations {
77
+ id
78
+ variantValue {
79
+ id
80
+ value
81
+ colorValue
82
+ variantType {
83
+ id
84
+ label
85
+ type
86
+ }
87
+ }
88
+ }
89
+ }
90
+ collections {
91
+ id
92
+ name
93
+ slug
94
+ description
95
+ image
96
+ active
97
+ }
98
+ bundleProducts {
99
+ id
100
+ quantity
101
+ position
102
+ variant {
103
+ id
104
+ price
105
+ originalPrice
106
+ stock
107
+ }
108
+ }
109
+ bundleDiscountPercentage
110
+ }
111
+ `,ut=`
112
+ query ProductsQuery(
113
+ $offset: Int
114
+ $limit: Int
115
+ $category: String
116
+ $query: String
117
+ $active: Boolean
118
+ $excludeBundles: Boolean
119
+ $orderBy: String
120
+ $orderDirection: String
121
+ ) {
122
+ products(
123
+ offset: $offset
124
+ limit: $limit
125
+ category: $category
126
+ query: $query
127
+ active: $active
128
+ excludeBundles: $excludeBundles
129
+ orderBy: $orderBy
130
+ orderDirection: $orderDirection
131
+ ) {
132
+ data {
133
+ ...ProductFragment
134
+ }
135
+ meta {
136
+ count
137
+ offset
138
+ limit
139
+ hasMore
140
+ }
141
+ }
142
+ }
143
+ ${Lt}
144
+ `,dt=`
145
+ query ProductQuery($slug: String!) {
146
+ product(slug: $slug) {
147
+ ...ProductFragment
148
+ }
149
+ }
150
+ ${Lt}
151
+ `,le=`
152
+ fragment CartFragment on Cart {
153
+ id
154
+ customerId
155
+ storeId
156
+ shippingId
157
+ couponId
158
+ billingAddressId
159
+ shippingAddressId
160
+ stripePaymentIntentId
161
+ checkoutSessionId
162
+ addonData
163
+ createdAt
164
+ updatedAt
165
+ customer {
166
+ id
167
+ email
168
+ userId
169
+ user {
170
+ id
171
+ email
172
+ name
173
+ }
174
+ }
175
+ coupon {
176
+ code
177
+ type
178
+ value
179
+ startDate
180
+ endDate
181
+ }
182
+ lineItems {
183
+ id
184
+ cartId
185
+ productVariantId
186
+ subscriptionId
187
+ quantity
188
+ createdAt
189
+ updatedAt
190
+ productVariant {
191
+ id
192
+ price
193
+ originalPrice
194
+ stock
195
+ shippable
196
+ attributes
197
+ }
198
+ subscription {
199
+ id
200
+ name
201
+ price
202
+ interval
203
+ intervalCount
204
+ }
205
+ }
206
+ billingAddress {
207
+ id
208
+ name
209
+ company
210
+ line1
211
+ line2
212
+ city
213
+ state
214
+ postalCode
215
+ country
216
+ phone
217
+ type
218
+ }
219
+ shippingAddress {
220
+ id
221
+ name
222
+ company
223
+ line1
224
+ line2
225
+ city
226
+ state
227
+ postalCode
228
+ country
229
+ phone
230
+ type
231
+ }
232
+ shipping {
233
+ id
234
+ name
235
+ price
236
+ minValue
237
+ maxValue
238
+ }
239
+ }
240
+ `,Ot=`
241
+ query CartQuery($id: String!) {
242
+ cart(id: $id) {
243
+ ...CartFragment
244
+ }
245
+ }
246
+ ${le}
247
+ `});var Ft={};mt(Ft,{YnsProvider:()=>z,createYnsProvider:()=>me});function me(t){return new z(t)}var z,Ut=P(()=>{"use strict";Dt();z=class{config;constructor(e){this.config=e}async graphqlRequest(e,r){let n=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:e,variables:r})});if(!n.ok)throw new Error(`YNS GraphQL request failed: ${n.status} ${n.statusText}`);let o=await n.json();if(o.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(o.errors)}`);return o.data}async restRequest(e,r="GET",n){let o=await fetch(`${this.config.endpoint}/api${e}`,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:n?JSON.stringify(n):void 0});if(!o.ok)throw new Error(`YNS REST request failed: ${o.status} ${o.statusText}`);return o.json()}mapYnsProduct(e){return{id:e.id,name:e.name,slug:e.slug,summary:e.summary,images:e.images||[],active:e.active,price:e.variants?.[0]?.price?Number.parseFloat(e.variants[0].price):0,currency:"USD",stock:e.variants?.[0]?.stock,category:e.category,variants:e.variants?.map(r=>({id:r.id,price:Number.parseFloat(r.price),stock:r.stock,attributes:r.attributes}))||[]}}mapYnsCart(e){let r=e.lineItems?.map(o=>({id:o.id,productId:o.productVariant?.id||"",variantId:o.productVariantId,quantity:o.quantity,price:Number.parseFloat(o.productVariant?.price||"0")}))||[],n=r.reduce((o,a)=>o+a.price*a.quantity,0);return{id:e.id,customerId:e.customerId,items:r,total:n,currency:"USD",createdAt:e.createdAt,updatedAt:e.updatedAt}}async productBrowse(e){let r=e.fields?Mt(e.fields):ut,n={offset:e.offset||0,limit:e.first||e.offset||10,category:e.category,query:e.query,active:e.active,excludeBundles:!1,orderBy:e.orderBy,orderDirection:e.orderDirection},o=await this.graphqlRequest(r,n);return{data:o.products.data.map(a=>this.mapYnsProduct(a)),meta:o.products.meta}}async productGet(e){if(!e.slug&&!e.id)throw new Error("Either slug or id is required for productGet");let r=e.fields?kt(e.fields):dt,n={slug:e.slug},o=await this.graphqlRequest(r,n);return o.product?this.mapYnsProduct(o.product):null}async cartAdd(e){let r={variantId:e.variantId,cartId:e.cartId,subscriptionId:e.subscriptionId};return await this.restRequest("/cart","POST",r)}async cartUpdate(e){let r={variantId:e.variantId,quantity:e.quantity};return await this.restRequest(`/cart/${e.cartId}`,"PUT",r)}async cartClear(e){return await this.restRequest(`/cart/${e.cartId}`,"DELETE")}async cartGet(e){let r=await this.graphqlRequest(Ot,{id:e.cartId});return r.cart?this.mapYnsCart(r.cart):null}}});ct();var pt=null,lt=new Map;function fe(t){pt=t,lt.clear()}function ge(){if(!pt)throw new Error("Commerce SDK not configured. Call Commerce.configure() with your provider settings first.");return pt}async function ye(t){let e=ge(),r=t||e.provider,n=lt.get(r);if(n)return n;let o;switch(r){case"stripe":{let{createStripeProvider:a}=await Promise.resolve().then(()=>(qt(),Nt));o=a(e.stripe||{});break}case"yns":{if(!e.yns)throw new Error("YNS provider configuration is required when using YNS provider");let{createYnsProvider:a}=await Promise.resolve().then(()=>(Ut(),Ft));o=a(e.yns);break}default:throw new Error(`Unsupported provider: ${r}`)}return lt.set(r,o),o}async function p(t){return ye(t?._provider)}F();var he=t=>(v(t.length===3,"currency needs to be a 3-letter code"),Pe[t.toUpperCase()]??2);var we=({amount:t,currency:e})=>{gt(t);let r=he(e),n=10**r;return Number.parseFloat((t/n).toFixed(r))},xe=({amount:t,currency:e,locale:r="en-US"})=>{let n=we({amount:t,currency:e});return new Intl.NumberFormat(r,{style:"currency",currency:e}).format(n)},Pe={BIF:0,CLP:0,DJF:0,GNF:0,JPY:0,KMF:0,KRW:0,MGA:0,PYG:0,RWF:0,UGX:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};var Ce={async add(t){return(await p(t)).cartAdd(t)},async update(t){return(await p(t)).cartUpdate(t)},async clear(t){return(await p(t)).cartClear(t)},async get(t){return(await p(t)).cartGet(t)}};var ve={async get(t){let e=await p(t);if(!e.orderGet)throw new Error("Order retrieval is not supported by the current provider");return e.orderGet(t)},async list(t={}){let e=await p(t);if(!e.orderList)throw new Error("Order listing is not supported by the current provider");return e.orderList(t)}};var Se={async browse(t={}){return(await p(t)).productBrowse(t)},async get(t){return(await p(t)).productGet(t)},async search(t){let e=await p(t);if(!e.productSearch)throw new Error("Product search is not supported by the current provider");return e.productSearch(t)}};nt();function Ie(t){return{product:{async browse(e){return(await p({_provider:t})).productBrowse({...e,_provider:t})},async get(e){return(await p({_provider:t})).productGet({...e,_provider:t})},async search(e){let r=await p({_provider:t});if(!r.productSearch)throw new Error(`Product search is not supported by ${t} provider`);return r.productSearch({...e,_provider:t})}},cart:{async add(e){return(await p({_provider:t})).cartAdd({...e,_provider:t})},async update(e){return(await p({_provider:t})).cartUpdate({...e,_provider:t})},async clear(e){return(await p({_provider:t})).cartClear({...e,_provider:t})},async get(e){return(await p({_provider:t})).cartGet({...e,_provider:t})}},order:{async get(e){let r=await p({_provider:t});if(!r.orderGet)throw new Error(`Order retrieval is not supported by ${t} provider`);return r.orderGet({...e,_provider:t})},async list(e={}){let r=await p({_provider:t});if(!r.orderList)throw new Error(`Order listing is not supported by ${t} provider`);return r.orderList({...e,_provider:t})}}}}export{nr as accountGet,ae as calculateCartTotalNet,ce as calculateCartTotalNetWithoutShipping,j as calculateCartTotalPossiblyWithTax,Ce as cart,Et as cartAdd,Ze as cartAddOptimistic,sr as cartChangeQuantity,lr as cartCount,te as cartCreate,E as cartGet,pr as cartSaveBillingAddress,cr as cartSaveEmail,dr as cartSaveShipping,ur as cartSaveTax,tr as cartSetQuantity,ot as cartUpdateQuantity,rr as categoryBrowse,fe as configure,gr as contextGet,ar as fileGet,xe as formatMoney,ir as getAddressSchema,Tt as getCartWithProductsById,$t as getProductsFromCart,st as getProductsFromMetadata,ve as order,or as orderGet,Se as product,it as productBrowse,At as productGet,L as productGetById,fr as productReviewAdd,mr as productReviewBrowse,f as provider,er as shippingBrowse,O as shippingGet,ue as taxDefaultGet,B as updatePaymentIntent,Ie as withProvider};
@@ -40,29 +40,13 @@ declare function sortProducts(products: MappedProduct[]): {
40
40
  }[];
41
41
  declare const ProductMetadataSchema: z.ZodObject<{
42
42
  category: z.ZodOptional<z.ZodString>;
43
- order: z.ZodOptional<z.ZodNumber>;
43
+ order: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
44
44
  slug: z.ZodString;
45
45
  variant: z.ZodOptional<z.ZodString>;
46
- stock: z.ZodEffects<z.ZodOptional<z.ZodNumber>, number, number | undefined>;
46
+ stock: z.ZodPipe<z.ZodOptional<z.ZodCoercedNumber<unknown>>, z.ZodTransform<number, number | undefined>>;
47
47
  digitalAsset: z.ZodOptional<z.ZodString>;
48
48
  preview: z.ZodOptional<z.ZodString>;
49
- }, "strip", z.ZodTypeAny, {
50
- slug: string;
51
- stock: number;
52
- category?: string | undefined;
53
- order?: number | undefined;
54
- variant?: string | undefined;
55
- digitalAsset?: string | undefined;
56
- preview?: string | undefined;
57
- }, {
58
- slug: string;
59
- category?: string | undefined;
60
- order?: number | undefined;
61
- variant?: string | undefined;
62
- stock?: number | undefined;
63
- digitalAsset?: string | undefined;
64
- preview?: string | undefined;
65
- }>;
49
+ }, z.core.$strip>;
66
50
  type ProductMetadata = z.infer<typeof ProductMetadataSchema>;
67
51
  /**
68
52
  * @internal
@@ -240,49 +224,7 @@ declare const cartMetadataSchema: z.ZodIntersection<z.ZodObject<{
240
224
  taxBreakdown3: z.ZodOptional<z.ZodString>;
241
225
  taxBreakdown4: z.ZodOptional<z.ZodString>;
242
226
  taxBreakdown5: z.ZodOptional<z.ZodString>;
243
- }, "strip", z.ZodTypeAny, {
244
- shippingRateId?: string | undefined;
245
- taxCalculationId?: string | undefined;
246
- taxCalculationExp?: string | undefined;
247
- taxId?: string | undefined;
248
- couponCode?: string | undefined;
249
- taxedAmount?: string | undefined;
250
- "billingAddress.city"?: string | undefined;
251
- "billingAddress.country"?: string | undefined;
252
- "billingAddress.line1"?: string | undefined;
253
- "billingAddress.line2"?: string | undefined;
254
- "billingAddress.name"?: string | undefined;
255
- "billingAddress.postalCode"?: string | undefined;
256
- "billingAddress.state"?: string | undefined;
257
- netAmount?: string | undefined;
258
- taxBreakdown0?: string | undefined;
259
- taxBreakdown1?: string | undefined;
260
- taxBreakdown2?: string | undefined;
261
- taxBreakdown3?: string | undefined;
262
- taxBreakdown4?: string | undefined;
263
- taxBreakdown5?: string | undefined;
264
- }, {
265
- shippingRateId?: string | undefined;
266
- taxCalculationId?: string | undefined;
267
- taxCalculationExp?: string | undefined;
268
- taxId?: string | undefined;
269
- couponCode?: string | undefined;
270
- taxedAmount?: string | undefined;
271
- "billingAddress.city"?: string | undefined;
272
- "billingAddress.country"?: string | undefined;
273
- "billingAddress.line1"?: string | undefined;
274
- "billingAddress.line2"?: string | undefined;
275
- "billingAddress.name"?: string | undefined;
276
- "billingAddress.postalCode"?: string | undefined;
277
- "billingAddress.state"?: string | undefined;
278
- netAmount?: string | undefined;
279
- taxBreakdown0?: string | undefined;
280
- taxBreakdown1?: string | undefined;
281
- taxBreakdown2?: string | undefined;
282
- taxBreakdown3?: string | undefined;
283
- taxBreakdown4?: string | undefined;
284
- taxBreakdown5?: string | undefined;
285
- }>, z.ZodRecord<z.ZodString, z.ZodString>>;
227
+ }, z.core.$strip>, z.ZodRecord<z.ZodString, z.ZodString>>;
286
228
  type CartMetadata = z.infer<typeof cartMetadataSchema>;
287
229
  /**
288
230
  * @internal
@@ -291,15 +233,7 @@ declare const cartMetadataTaxBreakdownSchema: z.ZodObject<{
291
233
  taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
292
234
  taxPercentage: z.ZodString;
293
235
  taxAmount: z.ZodNumber;
294
- }, "strip", z.ZodTypeAny, {
295
- taxPercentage: string;
296
- taxAmount: number;
297
- taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
298
- }, {
299
- taxPercentage: string;
300
- taxAmount: number;
301
- taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
302
- }>;
236
+ }, z.core.$strip>;
303
237
  /**
304
238
  * @internal
305
239
  */
@@ -329,9 +263,9 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
329
263
  customer: Stripe.Customer | null;
330
264
  payment_method: Stripe.PaymentMethod | null;
331
265
  taxBreakdown: {
266
+ taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
332
267
  taxPercentage: string;
333
268
  taxAmount: number;
334
- taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
335
269
  }[];
336
270
  id: string;
337
271
  object: "payment_intent";
@@ -350,7 +284,7 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
350
284
  created: number;
351
285
  currency: string;
352
286
  description: string | null;
353
- invoice: string | Stripe.Invoice | null;
287
+ excluded_payment_method_types: Array<Stripe.PaymentIntent.ExcludedPaymentMethodType> | null;
354
288
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
355
289
  latest_charge: string | Stripe.Charge | null;
356
290
  livemode: boolean;
@@ -359,6 +293,7 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
359
293
  payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
360
294
  payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
361
295
  payment_method_types: Array<string>;
296
+ presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
362
297
  processing: Stripe.PaymentIntent.Processing | null;
363
298
  receipt_email: string | null;
364
299
  review: string | Stripe.Review | null;
@@ -379,9 +314,9 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
379
314
  payment_method: Stripe.PaymentMethod | null;
380
315
  latest_charge: Stripe.Charge | null;
381
316
  taxBreakdown: {
317
+ taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
382
318
  taxPercentage: string;
383
319
  taxAmount: number;
384
- taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
385
320
  }[];
386
321
  metadata: {
387
322
  shippingRateId?: string | undefined;
@@ -423,7 +358,7 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
423
358
  currency: string;
424
359
  customer: string | Stripe.Customer | Stripe.DeletedCustomer | null;
425
360
  description: string | null;
426
- invoice: string | Stripe.Invoice | null;
361
+ excluded_payment_method_types: Array<Stripe.PaymentIntent.ExcludedPaymentMethodType> | null;
427
362
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
428
363
  livemode: boolean;
429
364
  next_action: Stripe.PaymentIntent.NextAction | null;
@@ -431,6 +366,7 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
431
366
  payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
432
367
  payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
433
368
  payment_method_types: Array<string>;
369
+ presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
434
370
  processing: Stripe.PaymentIntent.Processing | null;
435
371
  receipt_email: string | null;
436
372
  review: string | Stripe.Review | null;
package/dist/internal.js CHANGED
@@ -1 +1 @@
1
- import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var d=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),S=t=>Object.entries(t).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function k(t){return t.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=e.object({category:e.string().optional(),order:e.coerce.number().optional(),slug:e.string(),variant:e.string().optional(),stock:e.coerce.number().optional().transform(t=>t===void 0?1/0:t),digitalAsset:e.string().optional(),preview:e.string().optional()});function f({default_price:t,marketing_features:r,...n}){return i(t,"Product must have a default price"),i(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function x(t){return!!(t.active&&!t.deleted&&t.default_price)}function N(t){return{...t,data:t.data.filter(x)}}function T(t){return t.data.map(f)}function b(t){return t}function A(t){return t.data.map(b)}function B(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var R=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId:e.string().optional(),couponCode:e.string().optional(),taxedAmount:e.string().optional(),"billingAddress.city":e.string().optional(),"billingAddress.country":e.string().optional(),"billingAddress.line1":e.string().optional(),"billingAddress.line2":e.string().optional(),"billingAddress.name":e.string().optional(),"billingAddress.postalCode":e.string().optional(),"billingAddress.state":e.string().optional(),netAmount:e.string().optional(),taxBreakdown0:e.string().optional(),taxBreakdown1:e.string().optional(),taxBreakdown2:e.string().optional(),taxBreakdown3:e.string().optional(),taxBreakdown4:e.string().optional(),taxBreakdown5:e.string().optional()}).and(e.record(e.string())),c=e.object({taxType:e.string(),taxPercentage:e.string(),taxAmount:e.number()});function M(t){let r=t.payment_method;i(typeof r!="string","Payment method should not be a string");let n=t.customer;i(typeof n!="string"&&!n?.deleted,"Customer should not be a string");let a=l.parse(t.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:r,taxBreakdown:o}}function j({payment_method:t,latest_charge:r,...n}){i(typeof t=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,x as filterValidProduct,N as filterValidProducts,B as getUniqueVariants,R as isProductAvailable,M as mapCart,j as mapOrder,f as mapProduct,T as mapProducts,b as mapShippingRate,A as mapShippingRates,S as objectToStripeQuery,m as sanitizeQueryValue,k as sortProducts};
1
+ import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var d=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),S=t=>Object.entries(t).map(([r,n])=>`${r}:"${m(n)}"`).join(" AND ").trim();function N(t){return t.toSorted((r,n)=>{let a=Number(r.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-r.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var g=e.object({category:e.string().optional(),order:e.coerce.number().optional(),slug:e.string(),variant:e.string().optional(),stock:e.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:e.string().optional(),preview:e.string().optional()});function f({default_price:t,marketing_features:r,...n}){return i(t,"Product must have a default price"),i(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:r.map(a=>a.name).filter(Boolean),metadata:g.parse(n.metadata)}}function x(t){return!!(t.active&&!t.deleted&&t.default_price)}function T(t){return{...t,data:t.data.filter(x)}}function k(t){return t.data.map(f)}function b(t){return t}function A(t){return t.data.map(b)}function B(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var R=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId:e.string().optional(),couponCode:e.string().optional(),taxedAmount:e.string().optional(),"billingAddress.city":e.string().optional(),"billingAddress.country":e.string().optional(),"billingAddress.line1":e.string().optional(),"billingAddress.line2":e.string().optional(),"billingAddress.name":e.string().optional(),"billingAddress.postalCode":e.string().optional(),"billingAddress.state":e.string().optional(),netAmount:e.string().optional(),taxBreakdown0:e.string().optional(),taxBreakdown1:e.string().optional(),taxBreakdown2:e.string().optional(),taxBreakdown3:e.string().optional(),taxBreakdown4:e.string().optional(),taxBreakdown5:e.string().optional()}).and(e.record(e.string(),e.string())),c=e.object({taxType:e.string(),taxPercentage:e.string(),taxAmount:e.number()});function I(t){let r=t.payment_method;i(typeof r!="string","Payment method should not be a string");let n=t.customer;i(typeof n!="string"&&!n?.deleted,"Customer should not be a string");let a=l.parse(t.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:r,taxBreakdown:o}}function M({payment_method:t,latest_charge:r,...n}){i(typeof t=="object","Payment method is missing from order"),i(typeof r=="object","Latest charge is missing from order");let a=l.parse(n.metadata),o=Object.entries(a).filter(([s])=>s.startsWith("taxBreakdown")).map(([s,u])=>{let p=c.safeParse(d(String(u)));return p.success?p.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,x as filterValidProduct,T as filterValidProducts,B as getUniqueVariants,R as isProductAvailable,I as mapCart,M as mapOrder,f as mapProduct,k as mapProducts,b as mapShippingRate,A as mapShippingRates,S as objectToStripeQuery,m as sanitizeQueryValue,N as sortProducts};