commerce-kit 0.0.39 → 0.0.41

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.
@@ -4,7 +4,7 @@ type Money = {
4
4
  };
5
5
  declare const getStripeAmountFromDecimal: ({ amount: major, currency }: Money) => number;
6
6
  declare const getDecimalFromStripeAmount: ({ amount: minor, currency }: Money) => number;
7
- declare const formatMoney: ({ amount: minor, currency, locale, }: Money & {
7
+ declare const formatMoney: ({ amount: minor, currency, locale }: Money & {
8
8
  locale?: string;
9
9
  }) => string;
10
10
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { CartMetadata, MappedCart } from './internal.js';
2
- export { MappedProduct, MappedShippingRate } from './internal.js';
3
1
  import Stripe from 'stripe';
4
2
  import { z, TypeOf } from 'zod';
3
+ import { CartMetadata, MappedCart } from './internal.js';
4
+ export { MappedProduct, MappedShippingRate } from './internal.js';
5
5
 
6
6
  type Cart = NonNullable<Awaited<ReturnType<typeof cartGet>>>;
7
7
  type Order = NonNullable<Awaited<ReturnType<typeof orderGet>>>;
@@ -42,9 +42,9 @@ declare function cartGet(cartId: string): Promise<{
42
42
  customer: Stripe.Customer | null;
43
43
  payment_method: Stripe.PaymentMethod | null;
44
44
  taxBreakdown: {
45
+ taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
45
46
  taxPercentage: string;
46
47
  taxAmount: number;
47
- taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
48
48
  }[];
49
49
  id: string;
50
50
  object: "payment_intent";
@@ -63,7 +63,7 @@ declare function cartGet(cartId: string): Promise<{
63
63
  created: number;
64
64
  currency: string;
65
65
  description: string | null;
66
- invoice: string | Stripe.Invoice | null;
66
+ excluded_payment_method_types: Array<Stripe.PaymentIntent.ExcludedPaymentMethodType> | null;
67
67
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
68
68
  latest_charge: string | Stripe.Charge | null;
69
69
  livemode: boolean;
@@ -72,6 +72,7 @@ declare function cartGet(cartId: string): Promise<{
72
72
  payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
73
73
  payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
74
74
  payment_method_types: Array<string>;
75
+ presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
75
76
  processing: Stripe.PaymentIntent.Processing | null;
76
77
  receipt_email: string | null;
77
78
  review: string | Stripe.Review | null;
@@ -123,7 +124,7 @@ declare function cartCreate({ productId }?: {
123
124
  productId?: string;
124
125
  cartId?: string;
125
126
  }): Promise<Stripe.Response<Stripe.PaymentIntent>>;
126
- declare function cartAddOptimistic({ cart, add, }: {
127
+ declare function cartAddOptimistic({ cart, add }: {
127
128
  cart?: Cart | null;
128
129
  add: string | undefined;
129
130
  }): Promise<{
@@ -154,9 +155,9 @@ declare function cartAddOptimistic({ cart, add, }: {
154
155
  customer?: Stripe.Customer | null | undefined;
155
156
  payment_method?: Stripe.PaymentMethod | null | undefined;
156
157
  taxBreakdown?: {
158
+ taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
157
159
  taxPercentage: string;
158
160
  taxAmount: number;
159
- taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
160
161
  }[] | undefined;
161
162
  id?: string | undefined;
162
163
  object?: "payment_intent" | undefined;
@@ -174,7 +175,7 @@ declare function cartAddOptimistic({ cart, add, }: {
174
175
  created?: number | undefined;
175
176
  currency?: string | undefined;
176
177
  description?: string | null | undefined;
177
- invoice?: string | Stripe.Invoice | null | undefined;
178
+ excluded_payment_method_types?: Stripe.PaymentIntent.ExcludedPaymentMethodType[] | null | undefined;
178
179
  last_payment_error?: Stripe.PaymentIntent.LastPaymentError | null | undefined;
179
180
  latest_charge?: string | Stripe.Charge | null | undefined;
180
181
  livemode?: boolean | undefined;
@@ -183,6 +184,7 @@ declare function cartAddOptimistic({ cart, add, }: {
183
184
  payment_method_configuration_details?: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null | undefined;
184
185
  payment_method_options?: Stripe.PaymentIntent.PaymentMethodOptions | null | undefined;
185
186
  payment_method_types?: string[] | undefined;
187
+ presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
186
188
  processing?: Stripe.PaymentIntent.Processing | null | undefined;
187
189
  receipt_email?: string | null | undefined;
188
190
  review?: string | Stripe.Review | null | undefined;
@@ -372,9 +374,9 @@ declare function orderGet(orderId: string): Promise<{
372
374
  payment_method: Stripe.PaymentMethod | null;
373
375
  latest_charge: Stripe.Charge | null;
374
376
  taxBreakdown: {
377
+ taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
375
378
  taxPercentage: string;
376
379
  taxAmount: number;
377
- taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
378
380
  }[];
379
381
  metadata: {
380
382
  shippingRateId?: string | undefined;
@@ -416,7 +418,7 @@ declare function orderGet(orderId: string): Promise<{
416
418
  currency: string;
417
419
  customer: string | Stripe.Customer | Stripe.DeletedCustomer | null;
418
420
  description: string | null;
419
- invoice: string | Stripe.Invoice | null;
421
+ excluded_payment_method_types: Array<Stripe.PaymentIntent.ExcludedPaymentMethodType> | null;
420
422
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
421
423
  livemode: boolean;
422
424
  next_action: Stripe.PaymentIntent.NextAction | null;
@@ -424,6 +426,7 @@ declare function orderGet(orderId: string): Promise<{
424
426
  payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
425
427
  payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
426
428
  payment_method_types: Array<string>;
429
+ presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
427
430
  processing: Stripe.PaymentIntent.Processing | null;
428
431
  receipt_email: string | null;
429
432
  review: string | Stripe.Review | null;
@@ -533,9 +536,9 @@ declare const getCartWithProductsById: (cartId: string) => Promise<{
533
536
  customer: Stripe.Customer | null;
534
537
  payment_method: Stripe.PaymentMethod | null;
535
538
  taxBreakdown: {
539
+ taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
536
540
  taxPercentage: string;
537
541
  taxAmount: number;
538
- taxType: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
539
542
  }[];
540
543
  id: string;
541
544
  object: "payment_intent";
@@ -554,7 +557,7 @@ declare const getCartWithProductsById: (cartId: string) => Promise<{
554
557
  created: number;
555
558
  currency: string;
556
559
  description: string | null;
557
- invoice: string | Stripe.Invoice | null;
560
+ excluded_payment_method_types: Array<Stripe.PaymentIntent.ExcludedPaymentMethodType> | null;
558
561
  last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
559
562
  latest_charge: string | Stripe.Charge | null;
560
563
  livemode: boolean;
@@ -563,6 +566,7 @@ declare const getCartWithProductsById: (cartId: string) => Promise<{
563
566
  payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
564
567
  payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
565
568
  payment_method_types: Array<string>;
569
+ presentment_details?: Stripe.PaymentIntent.PresentmentDetails;
566
570
  processing: Stripe.PaymentIntent.Processing | null;
567
571
  receipt_email: string | null;
568
572
  review: string | Stripe.Review | null;
@@ -648,29 +652,7 @@ declare const getAddressSchema: (tr: {
648
652
  phone: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
649
653
  taxId: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
650
654
  email: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
651
- }, "strip", z.ZodTypeAny, {
652
- name: string;
653
- taxId: string | null;
654
- city: string;
655
- country: string;
656
- line1: string;
657
- line2: string | null;
658
- postalCode: string;
659
- state: string | null;
660
- phone: string | null;
661
- email: string | null;
662
- }, {
663
- name: string;
664
- city: string;
665
- country: string;
666
- line1: string;
667
- postalCode: string;
668
- taxId?: string | null | undefined;
669
- line2?: string | null | undefined;
670
- state?: string | null | undefined;
671
- phone?: string | null | undefined;
672
- email?: string | null | undefined;
673
- }>;
655
+ }, z.core.$strip>;
674
656
  type AddressSchema = TypeOf<ReturnType<typeof getAddressSchema>>;
675
657
  /**
676
658
  * @internal
@@ -763,7 +745,7 @@ declare function productReviewBrowse(params: {
763
745
  first?: number;
764
746
  last?: number;
765
747
  offset?: number;
766
- filter?: {};
748
+ filter?: Record<string, never>;
767
749
  }): Promise<Review[] | null>;
768
750
  declare function productReviewAdd(params: {
769
751
  productId: string;
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
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:"2024-11-20.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
+ import{revalidateTag as P}from"next/cache";import R from"stripe";import{z as S}from"zod";import{neon as pt}from"@neondatabase/serverless";var T;process.env.DATABASE_URL&&(T=pt(process.env.DATABASE_URL));var lt=process.env.STRIPE_SECRET_KEY,mt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:lt,StripeCurrency:mt};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]}},N=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 ft=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),V=t=>Object.entries(t).map(([e,n])=>`${e}:"${ft(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 gt=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()});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:gt.parse(n.metadata)}}function yt(t){return!!(t.active&&!t.deleted&&t.default_price)}function W(t){return{...t,data:t.data.filter(yt)}}function K(t){return t.data.map(O)}function Z(t){return t}function tt(t){return t.data.map(Z)}function Q(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(),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}}var v={DEBUG:0,LOG:1,WARN:2,ERROR:3},ht="LOG",xt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in v?process.env.LOG_LEVEL:ht,B=v[xt],d={time(t){B>v.DEBUG||console.time(t)},timeEnd(t){B>v.DEBUG||console.timeEnd(t)},log(...t){B>v.LOG||console.log(...t)},dir(t,e){B>v.LOG||console.dir(t,e)},warn(...t){B>v.WARN||console.warn(...t)},error(...t){B>v.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 at from"stripe";var wt=(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=wt(t,a);return new at(r,{typescript:!0,apiVersion:"2025-08-27.basil",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 l=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t};var j=1e3;function oe({productId:t,cartId:e}){return e?Ct({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):_t({productId:t})}async function Ct({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=N(i[t])+(n==="INCREASE"?1:-1);s<=0?i[t]="":i[t]=s.toString();let w=vt(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 L(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 R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function _t({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 ie({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 se({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 R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce({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:V({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:V({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return q(Q(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(Q(K(W(r))).filter(et)).slice(t.offset||0,t.first)}async function ue(){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 L(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 R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function de(){let e=(await St({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function pe(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 R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function le(){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 R.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 R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function me(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 L(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 R.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,N(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),Rt=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 R.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 Rt(t);if(!e)return null;let n=await X(e.metadata),{metadata:{shippingRateId:a}}=e,o=a&&await L(a);return{cart:e,lines:n.map(({product:r,quantity:i})=>r?{product:r,quantity:i}:null).filter(Boolean),shippingRate:o||null}},vt=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,10)*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 C=t.lines.find(A=>A.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||f||s}var fe=t=>S.object({name:S.string({message:t.nameRequired}).min(1,t.nameRequired),city:S.string({message:t.cityRequired}).min(1,t.cityRequired),country:S.string({message:t.countryRequired}).min(1,t.countryRequired),line1:S.string({message:t.line1Required}).min(1,t.line1Required),line2:S.string().optional().nullable().default(""),postalCode:S.string({message: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 L(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",C=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 ${n}`);let A=await f.tax.calculations.create({expand:["line_items"],line_items:t.map(M=>({...M,tax_behavior:M.tax_behavior??C})),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":C,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 ${n}`),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 R.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,C=n??(e.customer?await ut(e.customer):u.cart.customer);console.log({customer:C});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&&C?.discount?.coupon.valid?It(I,C.discount):I;console.log({"discount.coupon.amount_off":C?.discount?.coupon.amount_off,"discount.coupon.percent_off":C?.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 ge({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=N(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 ye=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}`)}},he=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 xe({cartId:t,shippingRateId:e}){let n=await $(t);if(!n)throw new Error(`Cart not found: ${t}`);d.time(`cartSaveShipping ${t}`);let a=await L(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 we({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,N(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function _e(t){if(!T)return null;let{storeId:e}=await l();return await T`
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 Se(t){if(!T)return null;let{storeId:e}=await l();return await T`
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 be=l;export{le as accountGet,vt as calculateCartTotalNet,Tt as calculateCartTotalNetWithoutShipping,U as calculateCartTotalPossiblyWithTax,oe as cartAdd,ie as cartAddOptimistic,ge as cartChangeQuantity,Ce as cartCount,_t as cartCreate,$ as cartGet,we as cartSaveBillingAddress,ye as cartSaveEmail,xe as cartSaveShipping,he as cartSaveTax,se as cartSetQuantity,Ct as cartUpdateQuantity,de as categoryBrowse,be as contextGet,pe as fileGet,fe as getAddressSchema,ct as getCartWithProductsById,st as getProductsFromCart,X as getProductsFromMetadata,me as orderGet,St as productBrowse,ce as productGet,J as productGetById,Se as productReviewAdd,_e as productReviewBrowse,m as provider,ue as shippingBrowse,L as shippingGet,Bt as taxDefaultGet,E as updatePaymentIntent};
@@ -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: z.ZodLiteral<Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {})>;
298
- }, {
299
- taxPercentage: string;
300
- taxAmount: number;
301
- taxType: z.ZodLiteral<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: z.ZodLiteral<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: z.ZodLiteral<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};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "commerce-kit",
4
- "version": "0.0.39",
4
+ "version": "0.0.41",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [
@@ -48,45 +48,46 @@
48
48
  ],
49
49
  "sideEffects": false,
50
50
  "scripts": {
51
- "build": "rimraf dist/* && tsup --config tsup.config.ts",
52
- "prepublishOnly": "pnpm build",
53
- "dev": "tsup --config tsup.config.ts --watch"
51
+ "build": "biome check && rimraf dist/* && tsup --config tsup.config.ts",
52
+ "prepublishOnly": "bun run build",
53
+ "dev": "tsup --config tsup.config.ts --watch",
54
+ "lint": "biome check --write --unsafe"
54
55
  },
55
56
  "devDependencies": {
56
- "@neondatabase/serverless": "^0.10.4",
57
- "@types/node": "^22.10.1",
58
- "@types/react": "npm:types-react@19.0.0-rc.1",
59
- "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
60
- "next": "15.0.4-canary.45",
61
- "prettier": "3.4.1",
62
- "react": "19.0.0-rc.1",
63
- "react-dom": "19.0.0-rc.1",
57
+ "@biomejs/biome": "2.2.2",
58
+ "@neondatabase/serverless": "^1.0.1",
59
+ "@types/node": "^24.3.0",
60
+ "@types/react": "^19.1.12",
61
+ "@types/react-dom": "^19.1.9",
62
+ "next": "15.5.2",
63
+ "react": "19.1.1",
64
+ "react-dom": "19.1.1",
64
65
  "rimraf": "6.0.1",
65
66
  "server-only": "0.0.1",
66
- "stripe": "^17.4.0",
67
- "tsup": "8.3.5",
68
- "tsx": "^4.19.2",
69
- "vitest": "^2.1.6",
70
- "zod": "^3.23.8"
67
+ "stripe": "^18.5.0",
68
+ "tsup": "8.5.0",
69
+ "tsx": "^4.20.5",
70
+ "vitest": "^3.2.4",
71
+ "zod": "^4.1.5"
71
72
  },
72
73
  "peerDependencies": {
73
- "@neondatabase/serverless": "^0.9.4",
74
- "@types/node": "^20 || ^22",
75
- "@types/react": "npm:types-react@19.0.0-rc.1",
76
- "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
77
- "next": "15.0.4-canary.45",
78
- "react": "19.0.0-rc.1",
79
- "react-dom": "19.0.0-rc.1",
74
+ "@neondatabase/serverless": "^0.9.5",
75
+ "@types/node": "^24.3.0",
76
+ "@types/react": "^19.0.8",
77
+ "@types/react-dom": "^19.0.3",
78
+ "next": "15.5.2",
79
+ "react": "^19.1.1",
80
+ "react-dom": "19.1.1",
80
81
  "server-only": "0.0.1",
81
- "stripe": "^16.5.0 || ^17.0.0",
82
- "typescript": "^5.5.4",
83
- "zod": "^3.23.8"
82
+ "stripe": "^18.5.0",
83
+ "typescript": "^5.9.2",
84
+ "zod": "^4.1.5"
84
85
  },
85
86
  "peerDependencyRules": {
86
87
  "allowedVersions": {
87
- "react": "19.0.0-rc.1",
88
- "react-dom": "19.0.0-rc.1"
88
+ "react": "^19",
89
+ "react-dom": "^19"
89
90
  }
90
91
  },
91
- "packageManager": "pnpm@9.14.2"
92
+ "packageManager": "bun@1.2.21"
92
93
  }