commerce-kit 0.0.31 → 0.0.32
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.d.ts +2 -1
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -658,9 +658,10 @@ type AddressSchema = TypeOf<ReturnType<typeof getAddressSchema>>;
|
|
|
658
658
|
/**
|
|
659
659
|
* @internal
|
|
660
660
|
*/
|
|
661
|
-
declare const updatePaymentIntent: ({ paymentIntentId, data, clearTaxCalculation, }: {
|
|
661
|
+
declare const updatePaymentIntent: ({ paymentIntentId, data, customerOverride, clearTaxCalculation, }: {
|
|
662
662
|
paymentIntentId: string;
|
|
663
663
|
data: Stripe.PaymentIntentUpdateParams;
|
|
664
|
+
customerOverride?: Stripe.Customer;
|
|
664
665
|
clearTaxCalculation?: boolean;
|
|
665
666
|
}) => Promise<Stripe.Response<Stripe.PaymentIntent>>;
|
|
666
667
|
declare const calculateCartTotalPossiblyWithTax: (cart: {
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{z as s}from"zod";function S(t,e){if(!t)throw new Error(e)}var X=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},U=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var ct=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),D=t=>Object.entries(t).map(([e,n])=>`${e}:"${ct(n)}"`).join(" AND ").trim();function G(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 ut=s.object({category:s.string().optional(),order:s.coerce.number().optional(),slug:s.string(),variant:s.string().optional(),stock:s.coerce.number().optional().transform(t=>t===void 0?1/0:t)});function q({default_price:t,marketing_features:e,...n}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:e.map(a=>a.name).filter(Boolean),metadata:ut.parse(n.metadata)}}function W(t){return t.data.map(q)}function H(t){return t}function Z(t){return t.data.map(H)}function Y(t){return t.filter((e,n,a)=>n===a.findIndex(o=>o.metadata.slug===e.metadata.slug))}var K=t=>!t.deleted&&t.active,O=s.object({shippingRateId:s.string().optional(),taxCalculationId:s.string().optional(),taxCalculationExp:s.string().optional(),taxId:s.string().optional(),couponCode:s.string().optional(),taxedAmount:s.string().optional(),"billingAddress.city":s.string().optional(),"billingAddress.country":s.string().optional(),"billingAddress.line1":s.string().optional(),"billingAddress.line2":s.string().optional(),"billingAddress.name":s.string().optional(),"billingAddress.postalCode":s.string().optional(),"billingAddress.state":s.string().optional(),netAmount:s.string().optional(),taxBreakdown0:s.string().optional(),taxBreakdown1:s.string().optional(),taxBreakdown2:s.string().optional(),taxBreakdown3:s.string().optional(),taxBreakdown4:s.string().optional(),taxBreakdown5:s.string().optional()}).and(s.record(s.string())),tt=s.object({taxType:s.string(),taxPercentage:s.string(),taxAmount:s.number()});function Q(t){let e=t.payment_method;S(typeof e!="string","Payment method should not be a string");let n=t.customer;S(typeof n!="string"&&!n?.deleted,"Customer should not be a string");let a=O.parse(t.metadata),o=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let d=tt.safeParse(U(String(i)));return d.success?d.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:e,taxBreakdown:o}}function et({payment_method:t,latest_charge:e,...n}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let a=O.parse(n.metadata),o=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let d=tt.safeParse(U(String(i)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:a}}import{revalidateTag as E}from"next/cache";import b from"stripe";import{z as C}from"zod";var m=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t};import rt from"stripe";var dt=process.env.STRIPE_SECRET_KEY,pt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:dt,StripeCurrency:pt};var lt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],f=({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=lt(t,a);return new rt(r,{typescript:!0,apiVersion:"2024-09-30.acacia",httpClient:rt.createFetchHttpClient((p,u)=>fetch(p,{...u,cache:n??u?.cache,next:{tags:i??u?.next?.tags,revalidate:e??u?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var v={DEBUG:0,LOG:1,WARN:2,ERROR:3},mt="LOG",ft=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in v?process.env.LOG_LEVEL:mt,T=v[ft],c={time(t){T>v.DEBUG||console.time(t)},timeEnd(t){T>v.DEBUG||console.timeEnd(t)},log(...t){T>v.LOG||console.log(...t)},dir(t,e){T>v.LOG||console.dir(t,e)},warn(...t){T>v.WARN||console.warn(...t)},error(...t){T>v.ERROR||console.error(...t)}};var w=t=>t.filter(Boolean),x={accountGetById:{tags:({accountId:t})=>w(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>w(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>w(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>w(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>w(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>w(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>w(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>w(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>w(["tax-settings"]),revalidate:()=>{}}};import{neon as gt}from"@neondatabase/serverless";var B;process.env.DATABASE_URL&&(B=gt(process.env.DATABASE_URL));var F=1e3;function ne({productId:t,cartId:e}){return e?yt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):ht({productId:t})}async function yt({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([k(t),it(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??{},u=L(i[t])+(n==="INCREASE"?1:-1);u<=0?i[t]="":i[t]=u.toString();let _=_t(r)+(o.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:i,amount:_||F},clearTaxCalculation:a})}catch(l){c.error(l)}finally{E(`cart-${e}`)}}async function $(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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(at.includes(r.status)){let i=Q(r);if(!i)return null;let d=await z(i.metadata),{metadata:{shippingRateId:p}}=i,u=p&&await N(p);return{cart:i,lines:d.map(({product:_,quantity:l})=>_?{product:_,quantity:l}:null).filter(Boolean),shippingRate:u||null}}}catch(r){if(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ht({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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||F,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw c.error(r),r}}async function ae({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return c.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?j(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:o}}async function oe({cartId:t,productId:e,quantity:n}){let[a,o]=await Promise.all([V(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=j(o)+(a.default_price.unit_amount??0);try{return await I({paymentIntentId:t,data:{metadata:r,amount:i||F}})}catch(d){c.error(d)}finally{E(`cart-${t}`)}}async function V(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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 q(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),r=await f({secretKey:a,tagPrefix:n,tags:x.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:D({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.all(r.data.map(i=>V(i.id))),G(W(r).filter(K))}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m();if(t.filter?.category){let o=t.filter?.category,i=await f({secretKey:a,tagPrefix:n,tags:x.productBrowse.tags({category:o}),cache:"force-cache"}).products.search({limit:100,query:D({active:!0,'metadata["category"]':o}),expand:["data.default_price"]},{stripeAccount:e});return G(Y(W(i)).filter(K).slice(t.offset,t.first))}else{let r=await f({secretKey:a,tagPrefix:n,tags:x.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return G(Y(W(r)).filter(K).slice(t.offset,t.first))}}async function se(){let{stripeAccount:t,storeId:e,secretKey:n}=await m(),o=await f({secretKey:n,tagPrefix:e,tags:x.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return Z(o)}async function N(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce(){let e=(await xt({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function ue(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function de(){let{stripeAccount:t,storeId:e,secretKey:n}=await m(),a=f({secretKey:n,tagPrefix:e,tags:x.accountGetById.tags({}),cache:"force-cache"});try{let[o,r]=await X(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(c.error(o),o instanceof b.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function wt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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 et(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function pe(t){let e=await wt(t);if(!e)return null;let n=ot(e.metadata),a=await Promise.all(n.map(async([i,d])=>({product:await k(i),quantity:d}))),{metadata:{shippingRateId:o}}=e,r=o&&await N(o);return{order:e,lines:a.map(({product:i,quantity:d})=>i?{product:i,quantity:d}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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 q(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}},at=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],ot=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),Ct=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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(at.includes(r.status))return Q(r)}catch(r){if(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function z(t){let e=ot(t);return await Promise.all(e.map(async([a,o])=>({product:await k(a),quantity:o})))}var it=async t=>{let e=await Ct(t);if(!e)return null;let n=await z(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}},_t=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,St=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];function bt({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,d=e.amount,p=St.some(h=>!n[h]&&!t.cart.metadata[h]?!1:n[h]!==t.cart.metadata[h]),u=a.length!==t.lines.length||a.some(h=>{let P=t.lines.find(A=>A.product.id===h.product?.id);return h.product?.default_price.unit_amount!==P?.product.default_price.unit_amount||h.quantity!==P?.quantity});return d&&i!==d||p||u}var le=t=>C.object({name:C.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:C.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:C.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:C.string({required_error:t.line1Required}).min(1,t.line1Required),line2:C.string().optional().nullable().default(""),postalCode:C.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:C.string().optional().nullable().default(""),phone:C.string().optional().nullable().default(""),taxId:C.string().optional().nullable().default(""),email:C.string().optional().nullable().default("")}),Rt=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:d}=await m(),p=f({secretKey:d,tagPrefix:i,tags:x.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let u=a?await N(a):null,_=typeof u?.tax_code=="string"?u.tax_code:u?.tax_code?.id,l=await It(),h=y.StripeCurrency==="usd"||y.StripeCurrency==="cad"?"exclusive":"inclusive",P=l.defaults.tax_behavior==="inferred_by_currency"?h:l.defaults.tax_behavior??h;l.defaults.tax_behavior||c.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y.StripeCurrency}: ${h}.`),c.time("createTaxCalculation ${cartId}");let A=await p.tax.calculations.create({expand:["line_items"],line_items:t.map(R=>({...R,tax_behavior:R.tax_behavior??P})),currency:y.StripeCurrency,shipping_cost:u?.active&&u?.fixed_amount?{amount:u.fixed_amount.amount,tax_behavior:u.tax_behavior==="inclusive"?"inclusive":u.tax_behavior==="exclusive"?"exclusive":P,tax_code:_??l.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 c.timeEnd("createTaxCalculation ${cartId}"),console.log(JSON.stringify(A).length),A},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};async function vt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await m(),o=f({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(c.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}function Pt(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 I=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:o,secretKey:r}=await m(),i=await it(t);S(i,`Cart not found: ${t}`);let d=e.amount?e.amount.toString():null,p=O.parse({...i.cart.metadata,...e.metadata});c.time("getProductsFromMetadata");let u=await z(p);c.timeEnd("getProductsFromMetadata");let l=!n&&bt({oldCart:i,data:e,mergedMetadata:p,lines:u})?await Rt({cartId:t,taxId:p.taxId??null,shippingRateId:p.shippingRateId??null,billingAddress:{country:p["billingAddress.country"]??"",city:p["billingAddress.city"]??"",line1:p["billingAddress.line1"]??"",line2:p["billingAddress.line2"]??"",name:p["billingAddress.name"]??"",postalCode:p["billingAddress.postalCode"]??"",state:p["billingAddress.state"]??""},lineItems:u.map(({product:g,quantity:M})=>{if(g?.default_price.unit_amount)return{product:g.id,reference:[g.metadata.slug,g.metadata.variant].filter(Boolean).join("-"),quantity:M,amount:g.default_price.unit_amount*M,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,h=e.customer?await vt(e.customer):i.cart.customer,P=f({secretKey:r,tagPrefix:o,cache:"no-cache"});c.time(`paymentIntents.update ${t}`);let A=l&&Object.fromEntries(l.tax_breakdown.map(g=>({taxType:g.tax_rate_details.tax_type,taxPercentage:g.tax_rate_details.percentage_decimal,taxAmount:g.amount})).map((g,M)=>[`taxBreakdown${M}`,JSON.stringify(g)])),R=l?l.amount_total:e.amount,J=R&&h?.discount?.coupon.valid?Pt(R,h.discount):R,st=await P.paymentIntents.update(t,{...e,...J&&{amount:J},metadata:{...p,...d&&{netAmount:d},...R&&{taxedAmount:R},...l?{...nt,...A,taxCalculationId:l.id,taxCalculationExp:l?.expires_at}:{...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:a});return c.timeEnd(`paymentIntents.update ${t}`),st},j=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Et(t):0,Et=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function me({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([V(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??{},u=L(i[t])+(n==="INCREASE"?1:-1);u<=0?i[t]="":i[t]=u.toString();let _=j(r)+(o.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:i,amount:_||F},clearTaxCalculation:a})}catch(l){c.error(l)}finally{E(`cart-${e}`)}}var fe=async({cartId:t,email:e})=>{let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){c.error(a)}finally{E(`cart-${t}`)}},ge=async({cartId:t,taxId:e})=>{let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){c.error(a)}finally{E(`cart-${t}`)}};async function ye({cartId:t,shippingRateId:e}){let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);c.time(`cartSaveShipping ${t}`);let a=await N(e);if(c.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{c.time(`updatePaymentIntent ${t}`);let o=await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:j({...n,shippingRate:a})}});return c.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){c.error(o)}finally{E(`cart-${t}`)}}async function he({cartId:t,billingAddress:e}){if(!await $(t))throw new Error(`Cart not found: ${t}`);try{return await I({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){c.error(a)}finally{E(`cart-${t}`)}}async function It(){let{stripeAccount:t,storeId:e,secretKey:n}=await m();return await f({secretKey:n,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function xe(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 we(t){if(!B)return null;let{storeId:e}=await m();return await B`
|
|
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 dt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Q=t=>Object.entries(t).map(([e,n])=>`${e}:"${dt(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 pt=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)});function W({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:pt.parse(n.metadata)}}function O(t){return t.data.map(W)}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 K=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())),et=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=et.safeParse(Y(String(i)));return u.success?u.data:null}).filter(Boolean);return{...t,metadata:a,customer:n,payment_method:e,taxBreakdown:o}}function rt({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=et.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 nt from"stripe";var lt=process.env.STRIPE_SECRET_KEY,mt=process.env.STRIPE_CURRENCY,g={StripeSecretKey:lt,StripeCurrency:mt};var ft=(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??g.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let i=ft(t,a);return new nt(r,{typescript:!0,apiVersion:"2024-09-30.acacia",httpClient:nt.createFetchHttpClient((h,s)=>fetch(h,{...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},gt="LOG",yt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in R?process.env.LOG_LEVEL:gt,T=R[yt],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 _=t=>t.filter(Boolean),x={accountGetById:{tags:({accountId:t})=>_(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>_(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>_(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>_(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>_(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>_(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>_(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>_(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>_(["tax-settings"]),revalidate:()=>{}}};import{neon as ht}from"@neondatabase/serverless";var B;process.env.DATABASE_URL&&(B=ht(process.env.DATABASE_URL));var j=1e3;function ae({productId:t,cartId:e}){return e?xt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):wt({productId:t})}async function xt({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([k(t),st(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(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(g.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let i=r.cart.metadata??{},s=L(i[t])+(n==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let w=bt(r)+(o.default_price.unit_amount??0);try{return await E({paymentIntentId:e,data:{metadata:i,amount:w||j},clearTaxCalculation:a})}catch(y){d.error(y)}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(ot.includes(r.status)){let i=z(r);if(!i)return null;let u=await X(i.metadata),{metadata:{shippingRateId:h}}=i,s=h&&await N(h);return{cart:i,lines:u.map(({product:w,quantity:y})=>w?{product:w,quantity:y}: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 wt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,cache:"no-cache"});if(!g.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:g.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 oe({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 ie({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(g.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${g.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 W(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function se({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.all(r.data.map(i=>J(i.id))),q(O(r).filter(K))}async function Ct(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l();if(t.filter?.category){let o=t.filter?.category,i=await m({secretKey:a,tagPrefix:n,tags:x.productBrowse.tags({category:o}),cache:"force-cache"}).products.search({limit:100,query:Q({active:!0,'metadata["category"]':o}),expand:["data.default_price"]},{stripeAccount:e});return q(V(O(i)).filter(K).slice(t.offset,t.first))}else{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(O(r)).filter(K).slice(t.offset,t.first))}}async function ce(){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 ue(){let e=(await Ct({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function de(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 pe(){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 _t(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 rt(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function le(t){let e=await _t(t);if(!e)return null;let n=it(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 W(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}},ot=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],it=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),St=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 ct(r.customer):null;if(ot.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=it(t);return await Promise.all(e.map(async([a,o])=>({product:await k(a),quantity:o})))}var st=async t=>{let e=await St(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}},bt=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,vt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];function Rt({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,h=vt.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 C=t.lines.find(I=>I.product.id===p.product?.id);return p.product?.default_price.unit_amount!==C?.product.default_price.unit_amount||p.quantity!==C?.quantity});return u&&i!==u||h||s}var me=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("")}),Pt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:i,secretKey:u}=await l(),h=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,y=await At(),p=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",C=y.defaults.tax_behavior==="inferred_by_currency"?p:y.defaults.tax_behavior??p;y.defaults.tax_behavior||d.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${p}.`),d.time("createTaxCalculation ${cartId}");let I=await h.tax.calculations.create({expand:["line_items"],line_items:t.map(M=>({...M,tax_behavior:M.tax_behavior??C})),currency:g.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":C,tax_code:w??y.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(I).length),I},at={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};async function ct(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 Et(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 st(t);b(u,`Cart not found: ${t}`);let h=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 y=!a&&Rt({oldCart:u,data:e,mergedMetadata:s,lines:w});console.log({shouldRecalculateTax:y});let p=y?await Pt({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:f,quantity:G})=>{if(f?.default_price.unit_amount)return{product:f.id,reference:[f.metadata.slug,f.metadata.variant].filter(Boolean).join("-"),quantity:G,amount:f.default_price.unit_amount*G,tax_behavior:f.default_price.tax_behavior==="exclusive"?"exclusive":f.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:f.tax_code?typeof f.tax_code=="string"?f.tax_code:f.tax_code.id:void 0}}).filter(Boolean)}):null,C=n??(e.customer?await ct(e.customer):u.cart.customer);console.log({customer:C});let I=m({secretKey:i,tagPrefix:r,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let M=p&&Object.fromEntries(p.tax_breakdown.map(f=>({taxType:f.tax_rate_details.tax_type,taxPercentage:f.tax_rate_details.percentage_decimal,taxAmount:f.amount})).map((f,G)=>[`taxBreakdown${G}`,JSON.stringify(f)])),A=p?p.amount_total:e.amount,D=A&&C?.discount?.coupon.valid?Et(A,C.discount):A;console.log({"discount.coupon.amount_off":C?.discount?.coupon.amount_off,"discount.coupon.percent_off":C?.discount?.coupon.percent_off,discountedAmount:D,taxedAmount:A,"taxCalculation.amount_total":p?.amount_total,"data.amount":e.amount,netAmount:h});let ut=await I.paymentIntents.update(t,{...e,...D&&{amount:D},metadata:{...s,...h&&{netAmount:h},...A&&{taxedAmount:A},...p?{...at,...M,taxCalculationId:p.id,taxCalculationExp:p?.expires_at}:{...a&&{...at,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:o});return d.timeEnd(`paymentIntents.update ${t}`),ut},U=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+It(t):0,It=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function fe({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(g.StripeCurrency?.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${g.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(y){d.error(y)}finally{P(`cart-${e}`)}}var ge=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}`)}},ye=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 he({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 xe({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 At(){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 we(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 Ce(t){if(!B)return null;let{storeId:e}=await l();return await B`
|
|
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
|
|
7
|
+
`}async function _e(t){if(!B)return null;let{storeId:e}=await l();return await B`
|
|
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
|
|
10
|
+
`}var Se=l;export{pe as accountGet,bt as calculateCartTotalNet,It as calculateCartTotalNetWithoutShipping,U as calculateCartTotalPossiblyWithTax,ae as cartAdd,oe as cartAddOptimistic,fe as cartChangeQuantity,we as cartCount,wt as cartCreate,$ as cartGet,xe as cartSaveBillingAddress,ge as cartSaveEmail,he as cartSaveShipping,ye as cartSaveTax,ie as cartSetQuantity,xt as cartUpdateQuantity,ue as categoryBrowse,Se as contextGet,de as fileGet,me as getAddressSchema,st as getCartWithProductsById,it as getProductsFromCart,X as getProductsFromMetadata,le as orderGet,Ct as productBrowse,se as productGet,J as productGetById,_e as productReviewAdd,Ce as productReviewBrowse,m as provider,ce as shippingBrowse,N as shippingGet,At as taxDefaultGet,E as updatePaymentIntent};
|