commerce-kit 0.0.21 → 0.0.22

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 CHANGED
@@ -120,11 +120,12 @@ declare function cartCreate({ productId }?: {
120
120
  cartId?: string;
121
121
  }): Promise<Stripe.Response<Stripe.PaymentIntent>>;
122
122
  declare function cartAddOptimistic({ cart, add }: {
123
- cart: Cart;
123
+ cart?: Cart | null;
124
124
  add: string | undefined;
125
125
  }): Promise<{
126
126
  cart: {
127
- metadata: {
127
+ amount: number;
128
+ metadata?: ({
128
129
  shippingRateId?: string | undefined;
129
130
  taxCalculationId?: string | undefined;
130
131
  taxCalculationExp?: string | undefined;
@@ -143,51 +144,50 @@ declare function cartAddOptimistic({ cart, add }: {
143
144
  taxBreakdown3?: string | undefined;
144
145
  taxBreakdown4?: string | undefined;
145
146
  taxBreakdown5?: string | undefined;
146
- } & Record<string, string>;
147
- payment_method: Stripe.PaymentMethod | null;
148
- taxBreakdown: {
147
+ } & Record<string, string>) | undefined;
148
+ payment_method?: Stripe.PaymentMethod | null | undefined;
149
+ taxBreakdown?: {
149
150
  taxPercentage: string;
150
151
  taxAmount: number;
151
152
  taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
152
- }[];
153
- id: string;
154
- object: "payment_intent";
155
- amount: number;
156
- amount_capturable: number;
153
+ }[] | undefined;
154
+ id?: string | undefined;
155
+ object?: "payment_intent" | undefined;
156
+ amount_capturable?: number | undefined;
157
157
  amount_details?: Stripe.PaymentIntent.AmountDetails;
158
- amount_received: number;
159
- application: string | Stripe.Application | null;
160
- application_fee_amount: number | null;
161
- automatic_payment_methods: Stripe.PaymentIntent.AutomaticPaymentMethods | null;
162
- canceled_at: number | null;
163
- cancellation_reason: Stripe.PaymentIntent.CancellationReason | null;
164
- capture_method: Stripe.PaymentIntent.CaptureMethod;
165
- client_secret: string | null;
166
- confirmation_method: Stripe.PaymentIntent.ConfirmationMethod;
167
- created: number;
168
- currency: string;
169
- customer: string | Stripe.Customer | Stripe.DeletedCustomer | null;
170
- description: string | null;
171
- invoice: string | Stripe.Invoice | null;
172
- last_payment_error: Stripe.PaymentIntent.LastPaymentError | null;
173
- latest_charge: string | Stripe.Charge | null;
174
- livemode: boolean;
175
- next_action: Stripe.PaymentIntent.NextAction | null;
176
- on_behalf_of: string | Stripe.Account | null;
177
- payment_method_configuration_details: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null;
178
- payment_method_options: Stripe.PaymentIntent.PaymentMethodOptions | null;
179
- payment_method_types: Array<string>;
180
- processing: Stripe.PaymentIntent.Processing | null;
181
- receipt_email: string | null;
182
- review: string | Stripe.Review | null;
183
- setup_future_usage: Stripe.PaymentIntent.SetupFutureUsage | null;
184
- shipping: Stripe.PaymentIntent.Shipping | null;
185
- source: string | Stripe.CustomerSource | Stripe.DeletedCustomerSource | null;
186
- statement_descriptor: string | null;
187
- statement_descriptor_suffix: string | null;
188
- status: Stripe.PaymentIntent.Status;
189
- transfer_data: Stripe.PaymentIntent.TransferData | null;
190
- transfer_group: string | null;
158
+ amount_received?: number | undefined;
159
+ application?: string | Stripe.Application | null | undefined;
160
+ application_fee_amount?: number | null | undefined;
161
+ automatic_payment_methods?: Stripe.PaymentIntent.AutomaticPaymentMethods | null | undefined;
162
+ canceled_at?: number | null | undefined;
163
+ cancellation_reason?: Stripe.PaymentIntent.CancellationReason | null | undefined;
164
+ capture_method?: Stripe.PaymentIntent.CaptureMethod | undefined;
165
+ client_secret?: string | null | undefined;
166
+ confirmation_method?: Stripe.PaymentIntent.ConfirmationMethod | undefined;
167
+ created?: number | undefined;
168
+ currency?: string | undefined;
169
+ customer?: string | Stripe.Customer | Stripe.DeletedCustomer | null | undefined;
170
+ description?: string | null | undefined;
171
+ invoice?: string | Stripe.Invoice | null | undefined;
172
+ last_payment_error?: Stripe.PaymentIntent.LastPaymentError | null | undefined;
173
+ latest_charge?: string | Stripe.Charge | null | undefined;
174
+ livemode?: boolean | undefined;
175
+ next_action?: Stripe.PaymentIntent.NextAction | null | undefined;
176
+ on_behalf_of?: string | Stripe.Account | null | undefined;
177
+ payment_method_configuration_details?: Stripe.PaymentIntent.PaymentMethodConfigurationDetails | null | undefined;
178
+ payment_method_options?: Stripe.PaymentIntent.PaymentMethodOptions | null | undefined;
179
+ payment_method_types?: string[] | undefined;
180
+ processing?: Stripe.PaymentIntent.Processing | null | undefined;
181
+ receipt_email?: string | null | undefined;
182
+ review?: string | Stripe.Review | null | undefined;
183
+ setup_future_usage?: Stripe.PaymentIntent.SetupFutureUsage | null | undefined;
184
+ shipping?: Stripe.PaymentIntent.Shipping | null | undefined;
185
+ source?: string | Stripe.CustomerSource | Stripe.DeletedCustomerSource | null | undefined;
186
+ statement_descriptor?: string | null | undefined;
187
+ statement_descriptor_suffix?: string | null | undefined;
188
+ status?: Stripe.PaymentIntent.Status | undefined;
189
+ transfer_data?: Stripe.PaymentIntent.TransferData | null | undefined;
190
+ transfer_group?: string | null | undefined;
191
191
  };
192
192
  lines: {
193
193
  product: {
@@ -220,8 +220,8 @@ declare function cartAddOptimistic({ cart, add }: {
220
220
  };
221
221
  quantity: number;
222
222
  }[];
223
- shippingRate: Stripe.ShippingRate | null;
224
- }>;
223
+ shippingRate?: Stripe.ShippingRate | null | undefined;
224
+ } | null | undefined>;
225
225
  declare function cartSetQuantity({ cartId, productId, quantity, }: {
226
226
  cartId: string;
227
227
  productId: string;
@@ -623,6 +623,7 @@ declare const getAddressSchema: (tr: {
623
623
  state: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
624
624
  phone: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
625
625
  taxId: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
626
+ email: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
626
627
  }, "strip", z.ZodTypeAny, {
627
628
  name: string;
628
629
  taxId: string | null;
@@ -633,6 +634,7 @@ declare const getAddressSchema: (tr: {
633
634
  postalCode: string;
634
635
  state: string | null;
635
636
  phone: string | null;
637
+ email: string | null;
636
638
  }, {
637
639
  name: string;
638
640
  city: string;
@@ -643,6 +645,7 @@ declare const getAddressSchema: (tr: {
643
645
  line2?: string | null | undefined;
644
646
  state?: string | null | undefined;
645
647
  phone?: string | null | undefined;
648
+ email?: string | null | undefined;
646
649
  }>;
647
650
  type AddressSchema = TypeOf<ReturnType<typeof getAddressSchema>>;
648
651
  declare const calculateCartTotalPossiblyWithTax: (cart: {
@@ -693,6 +696,10 @@ declare function cartChangeQuantity({ productId, cartId, operation, clearTaxCalc
693
696
  operation: "INCREASE" | "DECREASE";
694
697
  clearTaxCalculation?: boolean;
695
698
  }): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
699
+ declare const cartSaveEmail: ({ cartId, email }: {
700
+ cartId: string;
701
+ email: string;
702
+ }) => Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
696
703
  declare const cartSaveTax: ({ cartId, taxId }: {
697
704
  cartId: string;
698
705
  taxId: string;
@@ -748,4 +755,4 @@ declare const provider: ({ tags, revalidate, cache, tagPrefix, secretKey, }: {
748
755
  secretKey: string | undefined;
749
756
  }) => Stripe;
750
757
 
751
- export { type AddressSchema, type Cart, MappedCart, type ProductsFromMetadata, accountGet, calculateCartTotalNet, calculateCartTotalNetWithoutShipping, calculateCartTotalPossiblyWithTax, cartAdd, cartAddOptimistic, cartChangeQuantity, cartCount, cartCreate, cartGet, cartSaveBillingAddress, cartSaveShipping, cartSaveTax, cartSetQuantity, cartUpdateQuantity, categoryBrowse, contextGet, fileGet, getAddressSchema, getCartWithProductsById, getProductsFromCart, getProductsFromMetadata, orderGet, productBrowse, productGet, productGetById, productReviewAdd, productReviewBrowse, provider, shippingBrowse, shippingGet, taxDefaultGet };
758
+ export { type AddressSchema, type Cart, MappedCart, type ProductsFromMetadata, accountGet, calculateCartTotalNet, calculateCartTotalNetWithoutShipping, calculateCartTotalPossiblyWithTax, cartAdd, cartAddOptimistic, cartChangeQuantity, cartCount, cartCreate, cartGet, cartSaveBillingAddress, cartSaveEmail, cartSaveShipping, cartSaveTax, cartSetQuantity, cartUpdateQuantity, categoryBrowse, contextGet, fileGet, getAddressSchema, getCartWithProductsById, getProductsFromCart, getProductsFromMetadata, orderGet, productBrowse, productGet, productGetById, productReviewAdd, productReviewBrowse, provider, shippingBrowse, shippingGet, taxDefaultGet };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import"server-only";import"server-only";import{z as c}from"zod";function S(t,e){if(!t)throw new Error(e)}var V=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},$=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 ut=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),j=t=>Object.entries(t).map(([e,n])=>`${e}:"${ut(n)}"`).join(" AND ").trim();function q(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),i=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(i)||a===i?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(i)?-1:a-i})}var dt=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 G({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:dt.parse(n.metadata)}}function M(t){return t.data.map(G)}function H(t){return t}function z(t){return t.data.map(H)}function D(t){return t.filter((e,n,a)=>n===a.findIndex(i=>i.metadata.slug===e.metadata.slug))}var W=t=>!t.deleted&&t.active,O=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId: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())),J=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Y(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let n=O.parse(t.metadata),a=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,r])=>{let o=J.safeParse(U(String(r)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:e,taxBreakdown:a}}function X({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),i=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,o])=>{let s=J.safeParse(U(String(o)));return s.success?s.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:a}}import"server-only";import{revalidatePath as et,revalidateTag as I}from"next/cache";import v from"stripe";import{z as _}from"zod";import"server-only";var p=async()=>{let t={hero:{show:!0,title:"Discover our Curated Collection",description:"Explore our carefully selected products for your home and lifestyle.",button:{label:"Shop Now",path:"/"},image:{src:"https://files.stripe.com/links/MDB8YWNjdF8xT3BaeG5GSmNWbVh6bURsfGZsX3Rlc3RfaDVvWXowdU9ZbWlobUIyaHpNc1hCeDM200NBzvUjqP",alt:"Cup of coffee"}},categorySection:{show:!0},nav:{title:"Your Next Store",searchBar:{show:!0},links:[{label:"Home",href:"/"},{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},footer:{name:"Your Next Store",tagline:"Handcrafted with passion in California",newsletter:{show:!0},credits:!0,sections:[{header:"Products",links:[{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},{header:"Support",links:[{label:"Features",href:"https://yournextstore.com/#features"},{label:"Pricing",href:"https://yournextstore.com/#pricing"},{label:"Contact Us",href:"mailto:hi@yournextstore.com"}]}]},pages:{"/about":{content:`# Header 1
1
+ import"server-only";import"server-only";import{z as c}from"zod";function S(t,e){if(!t)throw new Error(e)}var V=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},U=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var ut=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),j=t=>Object.entries(t).map(([e,n])=>`${e}:"${ut(n)}"`).join(" AND ").trim();function q(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),i=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(i)||a===i?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(i)?-1:a-i})}var dt=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 G({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:dt.parse(n.metadata)}}function M(t){return t.data.map(G)}function H(t){return t}function z(t){return t.data.map(H)}function D(t){return t.filter((e,n,a)=>n===a.findIndex(i=>i.metadata.slug===e.metadata.slug))}var W=t=>!t.deleted&&t.active,K=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId: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())),J=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Y(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let n=K.parse(t.metadata),a=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,r])=>{let o=J.safeParse(U(String(r)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:e,taxBreakdown:a}}function X({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=K.parse(n.metadata),i=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,o])=>{let s=J.safeParse(U(String(o)));return s.success?s.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:a}}import"server-only";import{revalidatePath as et,revalidateTag as E}from"next/cache";import v from"stripe";import{z as _}from"zod";import"server-only";var l=async()=>{let t={hero:{show:!0,title:"Discover our Curated Collection",description:"Explore our carefully selected products for your home and lifestyle.",button:{label:"Shop Now",path:"/"},image:{src:"https://files.stripe.com/links/MDB8YWNjdF8xT3BaeG5GSmNWbVh6bURsfGZsX3Rlc3RfaDVvWXowdU9ZbWlobUIyaHpNc1hCeDM200NBzvUjqP",alt:"Cup of coffee"}},categorySection:{show:!0},nav:{title:"Your Next Store",searchBar:{show:!0},links:[{label:"Home",href:"/"},{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},footer:{name:"Your Next Store",tagline:"Handcrafted with passion in California",newsletter:{show:!0},credits:!0,sections:[{header:"Products",links:[{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},{header:"Support",links:[{label:"Features",href:"https://yournextstore.com/#features"},{label:"Pricing",href:"https://yournextstore.com/#pricing"},{label:"Contact Us",href:"mailto:hi@yournextstore.com"}]}]},pages:{"/about":{content:`# Header 1
2
2
 
3
3
  ## Header 2
4
4
 
@@ -23,13 +23,13 @@ function hello() {
23
23
  console.log('Hello world!');
24
24
  }
25
25
  \`\`\`
26
- `}}},e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0,config:t},n=await global?.__ynsFindStripeAccount?.();return n?{...n,config:n.config??t}:e};import"server-only";import tt from"stripe";import"server-only";var pt=process.env.STRIPE_SECRET_KEY,Z=process.env.STRIPE_CURRENCY;if(!Z)throw new Error("Missing STRIPE_CURRENCY");var x={StripeSecretKey:pt,StripeCurrency:Z};var b={DEBUG:0,LOG:1,WARN:2,ERROR:3},lt="LOG",mt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in b?process.env.LOG_LEVEL:lt,A=b[mt],u={time(t){A>b.DEBUG||console.time(t)},timeEnd(t){A>b.DEBUG||console.timeEnd(t)},log(...t){A>b.LOG||console.log(...t)},dir(t,e){A>b.LOG||console.dir(t,e)},warn(...t){A>b.WARN||console.warn(...t)},error(...t){A>b.ERROR||console.error(...t)}};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:i})=>{let r=i??x.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");u.log(`Using Stripe secret key from ${i?"parameter":"env"}.`);let o=ft(t,a);return new tt(r,{typescript:!0,apiVersion:"2024-06-20",httpClient:tt.createFetchHttpClient((h,d)=>fetch(h,{...d,cache:n??d?.cache,next:{tags:o??d?.next?.tags,revalidate:e??d?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var C=t=>t.filter(Boolean),w={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 gt}from"@neondatabase/serverless";var E;process.env.DATABASE_URL&&(E=gt(process.env.DATABASE_URL));var K=1e3;function oe({productId:t,cartId:e}){return e?ht({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):yt({productId:t})}async function ht({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([k(t),ot(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(i.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(x.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let o=r.cart.metadata??{},d=$(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let g=_t(r)+(i.default_price.unit_amount??0);try{return await T({paymentIntentId:e,data:{metadata:o,amount:g||K},clearTaxCalculation:a})}catch(l){u.error(l)}finally{I(`cart-${e}`)}}async function N(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(at.includes(r.status)){let o=Y(r);if(!o)return null;let s=await Q(o.metadata),{metadata:{shippingRateId:h}}=o,d=h&&await L(h);return{cart:o,lines:s.map(({product:g,quantity:l})=>g?{product:g,quantity:l}:null).filter(Boolean),shippingRate:d||null}}}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function yt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,cache:"no-cache"});try{let r=t?await k(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await i.paymentIntents.create({currency:x.StripeCurrency,amount:r?.default_price.unit_amount||K,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw u.error(r),r}}async function se({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return u.warn(`Product not found: ${e}`),t;let i=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),r=t?F(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:i}}async function ce({cartId:t,productId:e,quantity:n}){let[a,i]=await Promise.all([nt(e),N(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!i)throw new Error(`Cart not found: ${t}`);if(x.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let r=i.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let o=F(i)+(a.default_price.unit_amount??0);try{return await T({paymentIntentId:t,data:{metadata:r,amount:o||K}})}catch(s){u.error(s)}finally{I(`cart-${t}`),et("/cart"),et("/cart-overlay")}}async function nt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return G(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 p(),r=await m({secretKey:a,tagPrefix:n,tags:w.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:j({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(o=>!o.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return q(M(r).filter(W))}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p();if(t.filter?.category){let i=t.filter?.category,o=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:j({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return q(D(M(o)).filter(W).slice(t.offset,t.first))}else{let r=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return q(D(M(r)).filter(W).slice(t.offset,t.first))}}async function de(){let{stripeAccount:t,storeId:e,secretKey:n}=await p(),i=await m({secretKey:n,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return z(i)}async function L(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await i.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function pe(){let e=(await xt({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 p(),i=m({secretKey:a,tagPrefix:n,tags:w.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await i.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(u.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 p(),a=m({secretKey:n,tagPrefix:e,tags:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await V(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),o=r?.settings?.branding.logo??null;return!o||typeof o=="string"?{account:r,logo:null}:{account:r,logo:o}}catch(i){if(u.error(i),i instanceof v.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function wt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return X(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function fe(t){let e=await wt(t);if(!e)return null;let n=it(e.metadata),a=await Promise.all(n.map(async([o,s])=>({product:await k(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await L(i);return{order:e,lines:a.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return G(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}},at=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],it=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,$(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),Ct=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(at.includes(r.status))return Y(r)}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function Q(t){let e=it(t);return await Promise.all(e.map(async([a,i])=>({product:await k(a),quantity:i})))}var ot=async t=>{let e=await Ct(t);if(!e)return null;let n=await Q(e.metadata),{metadata:{shippingRateId:a}}=e,i=a&&await L(a);return{cart:e,lines:n.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||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"];function bt({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||i>=r)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,h=St.some(y=>!n[y]&&!t.cart.metadata[y]?!1:n[y]!==t.cart.metadata[y]),d=a.length!==t.lines.length||a.some(y=>{let R=t.lines.find(f=>f.product.id===y.product?.id);return y.product?.default_price.unit_amount!==R?.product.default_price.unit_amount||y.quantity!==R?.quantity});return s&&o!==s||h||d}var ge=t=>_.object({name:_.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:_.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:_.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:_.string({required_error:t.line1Required}).min(1,t.line1Required),line2:_.string().optional().nullable().default(""),postalCode:_.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:_.string().optional().nullable().default(""),phone:_.string().optional().nullable().default(""),taxId:_.string().optional().nullable().default("")}),vt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:r,storeId:o,secretKey:s}=await p(),h=m({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let d=a?await L(a):null,g=typeof d?.tax_code=="string"?d.tax_code:d?.tax_code?.id,l=await Pt(),y=x.StripeCurrency==="usd"||x.StripeCurrency==="cad"?"exclusive":"inclusive",R=l.defaults.tax_behavior==="inferred_by_currency"?y:l.defaults.tax_behavior??y;l.defaults.tax_behavior||u.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${x.StripeCurrency}: ${y}.`),u.time("createTaxCalculation ${cartId}");let f=await h.tax.calculations.create({expand:["line_items"],line_items:t.map(P=>({...P,tax_behavior:P.tax_behavior??R})),currency:x.StripeCurrency,shipping_cost:d?.active&&d?.fixed_amount?{amount:d.fixed_amount.amount,tax_behavior:d.tax_behavior==="inclusive"?"inclusive":d.tax_behavior==="exclusive"?"exclusive":R,tax_code:g??l.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:i?[{type:"eu_vat",value:i}]: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 u.timeEnd("createTaxCalculation ${cartId}"),f},rt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},T=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:i,secretKey:r}=await p(),o=await ot(t);S(o,`Cart not found: ${t}`);let s=O.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let h=await Q(s);u.timeEnd("getProductsFromMetadata");let g=!n&&bt({oldCart:o,data:e,mergedMetadata:s,lines:h})?await vt({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:h.map(({product:f,quantity:P})=>{if(f?.default_price.unit_amount)return{product:f.id,reference:[f.metadata.slug,f.metadata.variant].filter(Boolean).join("-"),quantity:P,amount:f.default_price.unit_amount*P,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,l=e.amount?e.amount.toString():null;if(g){let f=Object.fromEntries(g.tax_breakdown.map(B=>({taxType:B.tax_rate_details.tax_type,taxPercentage:B.tax_rate_details.percentage_decimal,taxAmount:B.amount})).map((B,ct)=>[`taxBreakdown${ct}`,JSON.stringify(B)])),P=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let st=await P.paymentIntents.update(t,{...e,amount:g.amount_total,metadata:{...s,...l&&{netAmount:l},...rt,...f,taxCalculationId:g.id,taxCalculationExp:g?.expires_at}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),st}let y=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let R=await y.paymentIntents.update(t,{...e,metadata:{...s,...l&&{netAmount:l},...n&&{...rt,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),R},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Rt(t):0,Rt=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function he({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([nt(t),N(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(x.StripeCurrency?.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let o=r.cart.metadata??{},d=$(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let g=F(r)+(i.default_price.unit_amount??0);try{return await T({paymentIntentId:e,data:{metadata:o,amount:g||K},clearTaxCalculation:a})}catch(l){u.error(l)}finally{I(`cart-${e}`)}}var ye=async({cartId:t,taxId:e})=>{let n=await N(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await T({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){u.error(a)}finally{I(`cart-${t}`)}};async function xe({cartId:t,shippingRateId:e}){let n=await N(t);if(!n)throw new Error(`Cart not found: ${t}`);u.time(`cartSaveShipping ${t}`);let a=await L(e);if(u.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await T({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:F({...n,shippingRate:a})}});return u.timeEnd(`updatePaymentIntent ${t}`),i}catch(i){u.error(i)}finally{I(`cart-${t}`)}}async function we({cartId:t,billingAddress:e}){if(!await N(t))throw new Error(`Cart not found: ${t}`);try{return await T({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??""}}})}catch(a){u.error(a)}finally{I(`cart-${t}`)}}async function Pt(){let{stripeAccount:t,storeId:e,secretKey:n}=await p();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)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function _e(t){if(!E)return null;let{storeId:e}=await p();return await E`
26
+ `}}},e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0,config:t},n=await global?.__ynsFindStripeAccount?.();return n?{...n,config:n.config??t}:e};import"server-only";import tt from"stripe";import"server-only";var lt=process.env.STRIPE_SECRET_KEY,Z=process.env.STRIPE_CURRENCY;if(!Z)throw new Error("Missing STRIPE_CURRENCY");var x={StripeSecretKey:lt,StripeCurrency:Z};var pt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],m=({tags:t,revalidate:e,cache:n,tagPrefix:a,secretKey:i})=>{let r=i??x.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let o=pt(t,a);return new tt(r,{typescript:!0,apiVersion:"2024-06-20",httpClient:tt.createFetchHttpClient((h,d)=>fetch(h,{...d,cache:n??d?.cache,next:{tags:o??d?.next?.tags,revalidate:e??d?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var b={DEBUG:0,LOG:1,WARN:2,ERROR:3},mt="LOG",ft=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in b?process.env.LOG_LEVEL:mt,I=b[ft],u={time(t){I>b.DEBUG||console.time(t)},timeEnd(t){I>b.DEBUG||console.timeEnd(t)},log(...t){I>b.LOG||console.log(...t)},dir(t,e){I>b.LOG||console.dir(t,e)},warn(...t){I>b.WARN||console.warn(...t)},error(...t){I>b.ERROR||console.error(...t)}};var C=t=>t.filter(Boolean),w={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 gt}from"@neondatabase/serverless";var T;process.env.DATABASE_URL&&(T=gt(process.env.DATABASE_URL));var O=1e3;function ie({productId:t,cartId:e}){return e?ht({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):yt({productId:t})}async function ht({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([k(t),ot(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(i.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(x.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let o=r.cart.metadata??{},d=N(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let g=_t(r)+(i.default_price.unit_amount??0);try{return await A({paymentIntentId:e,data:{metadata:o,amount:g||O},clearTaxCalculation:a})}catch(p){u.error(p)}finally{E(`cart-${e}`)}}async function B(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(at.includes(r.status)){let o=Y(r);if(!o)return null;let s=await Q(o.metadata),{metadata:{shippingRateId:h}}=o,d=h&&await L(h);return{cart:o,lines:s.map(({product:g,quantity:p})=>g?{product:g,quantity:p}:null).filter(Boolean),shippingRate:d||null}}}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function yt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),i=m({secretKey:a,tagPrefix:n,cache:"no-cache"});try{let r=t?await k(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await i.paymentIntents.create({currency:x.StripeCurrency,amount:r?.default_price.unit_amount||O,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw u.error(r),r}}async function oe({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return u.warn(`Product not found: ${e}`),t;let i=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),r=t?F(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:i}}async function se({cartId:t,productId:e,quantity:n}){let[a,i]=await Promise.all([nt(e),B(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!i)throw new Error(`Cart not found: ${t}`);if(x.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let r=i.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let o=F(i)+(a.default_price.unit_amount??0);try{return await A({paymentIntentId:t,data:{metadata:r,amount:o||O}})}catch(s){u.error(s)}finally{E(`cart-${t}`),et("/cart"),et("/cart-overlay")}}async function nt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return G(r)}catch(r){if(r instanceof v.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:w.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:j({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(o=>!o.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return q(M(r).filter(W))}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l();if(t.filter?.category){let i=t.filter?.category,o=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:j({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return q(D(M(o)).filter(W).slice(t.offset,t.first))}else{let r=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return q(D(M(r)).filter(W).slice(t.offset,t.first))}}async function ue(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),i=await m({secretKey:n,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return z(i)}async function L(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),i=m({secretKey:a,tagPrefix:n,tags:w.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await i.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function de(){let e=(await xt({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(),i=m({secretKey:a,tagPrefix:n,tags:w.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await i.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(u.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:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await V(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),o=r?.settings?.branding.logo??null;return!o||typeof o=="string"?{account:r,logo:null}:{account:r,logo:o}}catch(i){if(u.error(i),i instanceof v.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function wt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),i=m({secretKey:a,tagPrefix:n,tags:w.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return X(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function me(t){let e=await wt(t);if(!e)return null;let n=it(e.metadata),a=await Promise.all(n.map(async([o,s])=>({product:await k(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await L(i);return{order:e,lines:a.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return G(r)}catch(r){if(r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}},at=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],it=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,N(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),Ct=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(at.includes(r.status))return Y(r)}catch(r){if(u.error(r),r instanceof v.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function Q(t){let e=it(t);return await Promise.all(e.map(async([a,i])=>({product:await k(a),quantity:i})))}var ot=async t=>{let e=await Ct(t);if(!e)return null;let n=await Q(e.metadata),{metadata:{shippingRateId:a}}=e,i=a&&await L(a);return{cart:e,lines:n.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||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"];function bt({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||i>=r)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,h=St.some(y=>!n[y]&&!t.cart.metadata[y]?!1:n[y]!==t.cart.metadata[y]),d=a.length!==t.lines.length||a.some(y=>{let R=t.lines.find(f=>f.product.id===y.product?.id);return y.product?.default_price.unit_amount!==R?.product.default_price.unit_amount||y.quantity!==R?.quantity});return s&&o!==s||h||d}var fe=t=>_.object({name:_.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:_.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:_.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:_.string({required_error:t.line1Required}).min(1,t.line1Required),line2:_.string().optional().nullable().default(""),postalCode:_.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:_.string().optional().nullable().default(""),phone:_.string().optional().nullable().default(""),taxId:_.string().optional().nullable().default(""),email:_.string().optional().nullable().default("")}),vt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:r,storeId:o,secretKey:s}=await l(),h=m({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let d=a?await L(a):null,g=typeof d?.tax_code=="string"?d.tax_code:d?.tax_code?.id,p=await Pt(),y=x.StripeCurrency==="usd"||x.StripeCurrency==="cad"?"exclusive":"inclusive",R=p.defaults.tax_behavior==="inferred_by_currency"?y:p.defaults.tax_behavior??y;p.defaults.tax_behavior||u.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${x.StripeCurrency}: ${y}.`),u.time("createTaxCalculation ${cartId}");let f=await h.tax.calculations.create({expand:["line_items"],line_items:t.map(P=>({...P,tax_behavior:P.tax_behavior??R})),currency:x.StripeCurrency,shipping_cost:d?.active&&d?.fixed_amount?{amount:d.fixed_amount.amount,tax_behavior:d.tax_behavior==="inclusive"?"inclusive":d.tax_behavior==="exclusive"?"exclusive":R,tax_code:g??p.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:i?[{type:"eu_vat",value:i}]: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 u.timeEnd("createTaxCalculation ${cartId}"),f},rt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},A=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:i,secretKey:r}=await l(),o=await ot(t);S(o,`Cart not found: ${t}`);let s=K.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let h=await Q(s);u.timeEnd("getProductsFromMetadata");let g=!n&&bt({oldCart:o,data:e,mergedMetadata:s,lines:h})?await vt({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:h.map(({product:f,quantity:P})=>{if(f?.default_price.unit_amount)return{product:f.id,reference:[f.metadata.slug,f.metadata.variant].filter(Boolean).join("-"),quantity:P,amount:f.default_price.unit_amount*P,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,p=e.amount?e.amount.toString():null;if(g){let f=Object.fromEntries(g.tax_breakdown.map($=>({taxType:$.tax_rate_details.tax_type,taxPercentage:$.tax_rate_details.percentage_decimal,taxAmount:$.amount})).map(($,ct)=>[`taxBreakdown${ct}`,JSON.stringify($)])),P=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let st=await P.paymentIntents.update(t,{...e,amount:g.amount_total,metadata:{...s,...p&&{netAmount:p},...rt,...f,taxCalculationId:g.id,taxCalculationExp:g?.expires_at}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),st}let y=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let R=await y.paymentIntents.update(t,{...e,metadata:{...s,...p&&{netAmount:p},...n&&{...rt,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),R},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Rt(t):0,Rt=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[i,r]=await Promise.all([nt(t),B(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(x.StripeCurrency?.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${x.StripeCurrency}`);let o=r.cart.metadata??{},d=N(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let g=F(r)+(i.default_price.unit_amount??0);try{return await A({paymentIntentId:e,data:{metadata:o,amount:g||O},clearTaxCalculation:a})}catch(p){u.error(p)}finally{E(`cart-${e}`)}}var he=async({cartId:t,email:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await A({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}},ye=async({cartId:t,taxId:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await A({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}};async function xe({cartId:t,shippingRateId:e}){let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);u.time(`cartSaveShipping ${t}`);let a=await L(e);if(u.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await A({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:F({...n,shippingRate:a})}});return u.timeEnd(`updatePaymentIntent ${t}`),i}catch(i){u.error(i)}finally{E(`cart-${t}`)}}async function we({cartId:t,billingAddress:e}){if(!await B(t))throw new Error(`Cart not found: ${t}`);try{return await A({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){u.error(a)}finally{E(`cart-${t}`)}}async function Pt(){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`
27
27
  select * from reviews
28
28
  where product_id = ${t.productId} and store_id = ${e}
29
29
  order by created_at desc
30
30
  limit ${t.first??100}
31
31
  offset ${t.offset??0}
32
- `}async function Se(t){if(!E)return null;let{storeId:e}=await p();return await E`
32
+ `}async function Se(t){if(!T)return null;let{storeId:e}=await l();return await T`
33
33
  insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
34
34
  values (${e}, ${t.productId}, ${t.author}, ${t.email}, ${t.content}, ${t.rating}, now(), now())
35
- `}var be=p;export{me as accountGet,_t as calculateCartTotalNet,Rt as calculateCartTotalNetWithoutShipping,F as calculateCartTotalPossiblyWithTax,oe as cartAdd,se as cartAddOptimistic,he as cartChangeQuantity,Ce as cartCount,yt as cartCreate,N as cartGet,we as cartSaveBillingAddress,xe as cartSaveShipping,ye as cartSaveTax,ce as cartSetQuantity,ht as cartUpdateQuantity,pe as categoryBrowse,be as contextGet,le as fileGet,ge as getAddressSchema,ot as getCartWithProductsById,it as getProductsFromCart,Q as getProductsFromMetadata,fe as orderGet,xt as productBrowse,ue as productGet,nt as productGetById,Se as productReviewAdd,_e as productReviewBrowse,m as provider,de as shippingBrowse,L as shippingGet,Pt as taxDefaultGet};
35
+ `}var be=l;export{pe as accountGet,_t as calculateCartTotalNet,Rt as calculateCartTotalNetWithoutShipping,F as calculateCartTotalPossiblyWithTax,ie as cartAdd,oe as cartAddOptimistic,ge as cartChangeQuantity,Ce as cartCount,yt as cartCreate,B as cartGet,we as cartSaveBillingAddress,he as cartSaveEmail,xe as cartSaveShipping,ye as cartSaveTax,se as cartSetQuantity,ht as cartUpdateQuantity,de as categoryBrowse,be as contextGet,le as fileGet,fe as getAddressSchema,ot as getCartWithProductsById,it as getProductsFromCart,Q as getProductsFromMetadata,me as orderGet,xt as productBrowse,ce as productGet,nt as productGetById,Se as productReviewAdd,_e as productReviewBrowse,m as provider,ue as shippingBrowse,L as shippingGet,Pt as taxDefaultGet};
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.21",
4
+ "version": "0.0.22",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [
@@ -52,19 +52,19 @@
52
52
  ],
53
53
  "sideEffects": false,
54
54
  "devDependencies": {
55
- "@neondatabase/serverless": "^0.9.4",
56
- "@types/node": "^22.4.2",
55
+ "@neondatabase/serverless": "^0.9.5",
56
+ "@types/node": "^22.5.4",
57
57
  "@types/react": "npm:types-react@19.0.0-rc.1",
58
58
  "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
59
- "next": "15.0.0-canary.96",
59
+ "next": "15.0.0-canary.146",
60
60
  "prettier": "3.3.3",
61
- "react": "^19.0.0-rc.1",
62
- "react-dom": "^19.0.0-rc.1",
61
+ "react": "19.0.0-rc-fb9a90fa48-20240614",
62
+ "react-dom": "19.0.0-rc-fb9a90fa48-20240614",
63
63
  "rimraf": "6.0.1",
64
64
  "server-only": "0.0.1",
65
- "stripe": "^16.8.0",
65
+ "stripe": "^16.10.0",
66
66
  "tsup": "8.2.4",
67
- "tsx": "^4.17.0",
67
+ "tsx": "^4.19.0",
68
68
  "vitest": "^2.0.5",
69
69
  "zod": "^3.23.8"
70
70
  },
@@ -73,9 +73,9 @@
73
73
  "@types/node": "^20.14.8",
74
74
  "@types/react": "npm:types-react@19.0.0-rc.1",
75
75
  "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
76
- "next": "15.0.0-canary.121",
77
- "react": "19.0.0-rc-3208e73e-20240730",
78
- "react-dom": "19.0.0-rc-3208e73e-20240730",
76
+ "next": "15.0.0-canary.146",
77
+ "react": "19.0.0-rc-7771d3a7-20240827",
78
+ "react-dom": "19.0.0-rc-7771d3a7-20240827",
79
79
  "server-only": "0.0.1",
80
80
  "stripe": "^16.5.0",
81
81
  "typescript": "^5.5.4",
@@ -83,8 +83,8 @@
83
83
  },
84
84
  "peerDependencyRules": {
85
85
  "allowedVersions": {
86
- "react": "19.0.0-rc-3208e73e-20240730",
87
- "react-dom": "19.0.0-rc-3208e73e-20240730"
86
+ "react": "19.0.0-rc-7771d3a7-20240827",
87
+ "react-dom": "19.0.0-rc-7771d3a7-20240827"
88
88
  }
89
89
  },
90
90
  "scripts": {