commerce-kit 0.0.20 → 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 +61 -46
- package/dist/index.js +4 -4
- package/dist/internal.d.ts +7 -0
- package/dist/internal.js +1 -1
- package/package.json +13 -13
package/dist/index.d.ts
CHANGED
|
@@ -88,6 +88,7 @@ declare function cartGet(cartId: string): Promise<{
|
|
|
88
88
|
marketing_features: string[];
|
|
89
89
|
metadata: {
|
|
90
90
|
slug: string;
|
|
91
|
+
stock: number;
|
|
91
92
|
category?: string | undefined;
|
|
92
93
|
order?: number | undefined;
|
|
93
94
|
variant?: string | undefined;
|
|
@@ -119,11 +120,12 @@ declare function cartCreate({ productId }?: {
|
|
|
119
120
|
cartId?: string;
|
|
120
121
|
}): Promise<Stripe.Response<Stripe.PaymentIntent>>;
|
|
121
122
|
declare function cartAddOptimistic({ cart, add }: {
|
|
122
|
-
cart
|
|
123
|
+
cart?: Cart | null;
|
|
123
124
|
add: string | undefined;
|
|
124
125
|
}): Promise<{
|
|
125
126
|
cart: {
|
|
126
|
-
|
|
127
|
+
amount: number;
|
|
128
|
+
metadata?: ({
|
|
127
129
|
shippingRateId?: string | undefined;
|
|
128
130
|
taxCalculationId?: string | undefined;
|
|
129
131
|
taxCalculationExp?: string | undefined;
|
|
@@ -142,51 +144,50 @@ declare function cartAddOptimistic({ cart, add }: {
|
|
|
142
144
|
taxBreakdown3?: string | undefined;
|
|
143
145
|
taxBreakdown4?: string | undefined;
|
|
144
146
|
taxBreakdown5?: string | undefined;
|
|
145
|
-
} & Record<string, string
|
|
146
|
-
payment_method
|
|
147
|
-
taxBreakdown
|
|
147
|
+
} & Record<string, string>) | undefined;
|
|
148
|
+
payment_method?: Stripe.PaymentMethod | null | undefined;
|
|
149
|
+
taxBreakdown?: {
|
|
148
150
|
taxPercentage: string;
|
|
149
151
|
taxAmount: number;
|
|
150
152
|
taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
|
|
151
|
-
}[];
|
|
152
|
-
id
|
|
153
|
-
object
|
|
154
|
-
|
|
155
|
-
amount_capturable: number;
|
|
153
|
+
}[] | undefined;
|
|
154
|
+
id?: string | undefined;
|
|
155
|
+
object?: "payment_intent" | undefined;
|
|
156
|
+
amount_capturable?: number | undefined;
|
|
156
157
|
amount_details?: Stripe.PaymentIntent.AmountDetails;
|
|
157
|
-
amount_received
|
|
158
|
-
application
|
|
159
|
-
application_fee_amount
|
|
160
|
-
automatic_payment_methods
|
|
161
|
-
canceled_at
|
|
162
|
-
cancellation_reason
|
|
163
|
-
capture_method
|
|
164
|
-
client_secret
|
|
165
|
-
confirmation_method
|
|
166
|
-
created
|
|
167
|
-
currency
|
|
168
|
-
customer
|
|
169
|
-
description
|
|
170
|
-
invoice
|
|
171
|
-
last_payment_error
|
|
172
|
-
latest_charge
|
|
173
|
-
livemode
|
|
174
|
-
next_action
|
|
175
|
-
on_behalf_of
|
|
176
|
-
payment_method_configuration_details
|
|
177
|
-
payment_method_options
|
|
178
|
-
payment_method_types
|
|
179
|
-
processing
|
|
180
|
-
receipt_email
|
|
181
|
-
review
|
|
182
|
-
setup_future_usage
|
|
183
|
-
shipping
|
|
184
|
-
source
|
|
185
|
-
statement_descriptor
|
|
186
|
-
statement_descriptor_suffix
|
|
187
|
-
status
|
|
188
|
-
transfer_data
|
|
189
|
-
transfer_group
|
|
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;
|
|
190
191
|
};
|
|
191
192
|
lines: {
|
|
192
193
|
product: {
|
|
@@ -194,6 +195,7 @@ declare function cartAddOptimistic({ cart, add }: {
|
|
|
194
195
|
marketing_features: string[];
|
|
195
196
|
metadata: {
|
|
196
197
|
slug: string;
|
|
198
|
+
stock: number;
|
|
197
199
|
category?: string | undefined;
|
|
198
200
|
order?: number | undefined;
|
|
199
201
|
variant?: string | undefined;
|
|
@@ -218,8 +220,8 @@ declare function cartAddOptimistic({ cart, add }: {
|
|
|
218
220
|
};
|
|
219
221
|
quantity: number;
|
|
220
222
|
}[];
|
|
221
|
-
shippingRate
|
|
222
|
-
}>;
|
|
223
|
+
shippingRate?: Stripe.ShippingRate | null | undefined;
|
|
224
|
+
} | null | undefined>;
|
|
223
225
|
declare function cartSetQuantity({ cartId, productId, quantity, }: {
|
|
224
226
|
cartId: string;
|
|
225
227
|
productId: string;
|
|
@@ -230,6 +232,7 @@ declare function productGetById(id: string): Promise<{
|
|
|
230
232
|
marketing_features: string[];
|
|
231
233
|
metadata: {
|
|
232
234
|
slug: string;
|
|
235
|
+
stock: number;
|
|
233
236
|
category?: string | undefined;
|
|
234
237
|
order?: number | undefined;
|
|
235
238
|
variant?: string | undefined;
|
|
@@ -259,6 +262,7 @@ declare function productGet({ slug }: {
|
|
|
259
262
|
marketing_features: string[];
|
|
260
263
|
metadata: {
|
|
261
264
|
slug: string;
|
|
265
|
+
stock: number;
|
|
262
266
|
category?: string | undefined;
|
|
263
267
|
order?: number | undefined;
|
|
264
268
|
variant?: string | undefined;
|
|
@@ -293,6 +297,7 @@ declare function productBrowse(params: {
|
|
|
293
297
|
marketing_features: string[];
|
|
294
298
|
metadata: {
|
|
295
299
|
slug: string;
|
|
300
|
+
stock: number;
|
|
296
301
|
category?: string | undefined;
|
|
297
302
|
order?: number | undefined;
|
|
298
303
|
variant?: string | undefined;
|
|
@@ -421,6 +426,7 @@ declare function orderGet(orderId: string): Promise<{
|
|
|
421
426
|
marketing_features: string[];
|
|
422
427
|
metadata: {
|
|
423
428
|
slug: string;
|
|
429
|
+
stock: number;
|
|
424
430
|
category?: string | undefined;
|
|
425
431
|
order?: number | undefined;
|
|
426
432
|
variant?: string | undefined;
|
|
@@ -454,6 +460,7 @@ declare function getProductsFromMetadata(metadata: MappedCart["metadata"]): Prom
|
|
|
454
460
|
marketing_features: string[];
|
|
455
461
|
metadata: {
|
|
456
462
|
slug: string;
|
|
463
|
+
stock: number;
|
|
457
464
|
category?: string | undefined;
|
|
458
465
|
order?: number | undefined;
|
|
459
466
|
variant?: string | undefined;
|
|
@@ -552,6 +559,7 @@ declare const getCartWithProductsById: (cartId: string) => Promise<{
|
|
|
552
559
|
marketing_features: string[];
|
|
553
560
|
metadata: {
|
|
554
561
|
slug: string;
|
|
562
|
+
stock: number;
|
|
555
563
|
category?: string | undefined;
|
|
556
564
|
order?: number | undefined;
|
|
557
565
|
variant?: string | undefined;
|
|
@@ -615,6 +623,7 @@ declare const getAddressSchema: (tr: {
|
|
|
615
623
|
state: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
|
|
616
624
|
phone: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
|
|
617
625
|
taxId: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
|
|
626
|
+
email: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
|
|
618
627
|
}, "strip", z.ZodTypeAny, {
|
|
619
628
|
name: string;
|
|
620
629
|
taxId: string | null;
|
|
@@ -625,6 +634,7 @@ declare const getAddressSchema: (tr: {
|
|
|
625
634
|
postalCode: string;
|
|
626
635
|
state: string | null;
|
|
627
636
|
phone: string | null;
|
|
637
|
+
email: string | null;
|
|
628
638
|
}, {
|
|
629
639
|
name: string;
|
|
630
640
|
city: string;
|
|
@@ -635,6 +645,7 @@ declare const getAddressSchema: (tr: {
|
|
|
635
645
|
line2?: string | null | undefined;
|
|
636
646
|
state?: string | null | undefined;
|
|
637
647
|
phone?: string | null | undefined;
|
|
648
|
+
email?: string | null | undefined;
|
|
638
649
|
}>;
|
|
639
650
|
type AddressSchema = TypeOf<ReturnType<typeof getAddressSchema>>;
|
|
640
651
|
declare const calculateCartTotalPossiblyWithTax: (cart: {
|
|
@@ -685,6 +696,10 @@ declare function cartChangeQuantity({ productId, cartId, operation, clearTaxCalc
|
|
|
685
696
|
operation: "INCREASE" | "DECREASE";
|
|
686
697
|
clearTaxCalculation?: boolean;
|
|
687
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>;
|
|
688
703
|
declare const cartSaveTax: ({ cartId, taxId }: {
|
|
689
704
|
cartId: string;
|
|
690
705
|
taxId: string;
|
|
@@ -740,4 +755,4 @@ declare const provider: ({ tags, revalidate, cache, tagPrefix, secretKey, }: {
|
|
|
740
755
|
secretKey: string | undefined;
|
|
741
756
|
}) => Stripe;
|
|
742
757
|
|
|
743
|
-
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, 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]}},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()});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,
|
|
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 se({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(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 T({paymentIntentId:e,data:{metadata:o,amount:g||K},clearTaxCalculation:a})}catch(l){u.error(l)}finally{I(`cart-${e}`)}}async function $(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;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 ce({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 ue({cartId:t,productId:e,quantity:n}){let[a,i]=await Promise.all([nt(e),$(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 de({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 pe(){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 le(){let e=(await xt({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function me(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 fe(){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 ge(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(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 he=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 ye({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([nt(t),$(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 T({paymentIntentId:e,data:{metadata:o,amount:g||K},clearTaxCalculation:a})}catch(l){u.error(l)}finally{I(`cart-${e}`)}}var xe=async({cartId:t,taxId:e})=>{let n=await $(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 we({cartId:t,shippingRateId:e}){let n=await $(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 Ce({cartId:t,billingAddress:e}){if(!await $(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 _e(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 Se(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
|
|
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
|
|
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/dist/internal.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ declare function sortProducts(products: MappedProduct[]): {
|
|
|
13
13
|
marketing_features: string[];
|
|
14
14
|
metadata: {
|
|
15
15
|
slug: string;
|
|
16
|
+
stock: number;
|
|
16
17
|
category?: string | undefined;
|
|
17
18
|
order?: number | undefined;
|
|
18
19
|
variant?: string | undefined;
|
|
@@ -40,8 +41,10 @@ declare const productMetadataSchema: z.ZodObject<{
|
|
|
40
41
|
order: z.ZodOptional<z.ZodNumber>;
|
|
41
42
|
slug: z.ZodString;
|
|
42
43
|
variant: z.ZodOptional<z.ZodString>;
|
|
44
|
+
stock: z.ZodEffects<z.ZodOptional<z.ZodNumber>, number, number | undefined>;
|
|
43
45
|
}, "strip", z.ZodTypeAny, {
|
|
44
46
|
slug: string;
|
|
47
|
+
stock: number;
|
|
45
48
|
category?: string | undefined;
|
|
46
49
|
order?: number | undefined;
|
|
47
50
|
variant?: string | undefined;
|
|
@@ -50,6 +53,7 @@ declare const productMetadataSchema: z.ZodObject<{
|
|
|
50
53
|
category?: string | undefined;
|
|
51
54
|
order?: number | undefined;
|
|
52
55
|
variant?: string | undefined;
|
|
56
|
+
stock?: number | undefined;
|
|
53
57
|
}>;
|
|
54
58
|
type ProductMetadata = z.infer<typeof productMetadataSchema>;
|
|
55
59
|
/**
|
|
@@ -60,6 +64,7 @@ declare function mapProduct({ default_price, marketing_features, ...product }: S
|
|
|
60
64
|
marketing_features: string[];
|
|
61
65
|
metadata: {
|
|
62
66
|
slug: string;
|
|
67
|
+
stock: number;
|
|
63
68
|
category?: string | undefined;
|
|
64
69
|
order?: number | undefined;
|
|
65
70
|
variant?: string | undefined;
|
|
@@ -90,6 +95,7 @@ declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<St
|
|
|
90
95
|
marketing_features: string[];
|
|
91
96
|
metadata: {
|
|
92
97
|
slug: string;
|
|
98
|
+
stock: number;
|
|
93
99
|
category?: string | undefined;
|
|
94
100
|
order?: number | undefined;
|
|
95
101
|
variant?: string | undefined;
|
|
@@ -129,6 +135,7 @@ declare function getUniqueVariants(products: MappedProduct[]): {
|
|
|
129
135
|
marketing_features: string[];
|
|
130
136
|
metadata: {
|
|
131
137
|
slug: string;
|
|
138
|
+
stock: number;
|
|
132
139
|
category?: string | undefined;
|
|
133
140
|
order?: number | undefined;
|
|
134
141
|
variant?: string | undefined;
|
package/dist/internal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"server-only";import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var u=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=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()});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 N(t){return t.data.map(f)}function x(t){return t}function T(t){return t.data.map(x)}function B(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var A=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId: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 R(t){let r=t.payment_method;i(typeof r!="string","Payment method is missing from cart");let n=l.parse(t.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,s])=>{let p=c.safeParse(u(String(s)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:r,taxBreakdown:a}}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,p])=>{let d=c.safeParse(u(String(p)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,B as getUniqueVariants,A as isProductAvailable,R as mapCart,M as mapOrder,f as mapProduct,N as mapProducts,x as mapShippingRate,T as mapShippingRates,y as objectToStripeQuery,m as sanitizeQueryValue,k as sortProducts};
|
|
1
|
+
import"server-only";import{z as e}from"zod";function i(t,r){if(!t)throw new Error(r)}var u=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var m=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=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)});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 N(t){return t.data.map(f)}function x(t){return t}function T(t){return t.data.map(x)}function B(t){return t.filter((r,n,a)=>n===a.findIndex(o=>o.metadata.slug===r.metadata.slug))}var A=t=>!t.deleted&&t.active,l=e.object({shippingRateId:e.string().optional(),taxCalculationId:e.string().optional(),taxCalculationExp:e.string().optional(),taxId: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 R(t){let r=t.payment_method;i(typeof r!="string","Payment method is missing from cart");let n=l.parse(t.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,s])=>{let p=c.safeParse(u(String(s)));return p.success?p.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:r,taxBreakdown:a}}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,p])=>{let d=c.safeParse(u(String(p)));return d.success?d.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:r,taxBreakdown:o,metadata:a}}export{l as cartMetadataSchema,c as cartMetadataTaxBreakdownSchema,B as getUniqueVariants,A as isProductAvailable,R as mapCart,M as mapOrder,f as mapProduct,N as mapProducts,x as mapShippingRate,T as mapShippingRates,y as objectToStripeQuery,m as sanitizeQueryValue,k 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.
|
|
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.
|
|
56
|
-
"@types/node": "^22.4
|
|
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.
|
|
59
|
+
"next": "15.0.0-canary.146",
|
|
60
60
|
"prettier": "3.3.3",
|
|
61
|
-
"react": "
|
|
62
|
-
"react-dom": "
|
|
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.
|
|
65
|
+
"stripe": "^16.10.0",
|
|
66
66
|
"tsup": "8.2.4",
|
|
67
|
-
"tsx": "^4.
|
|
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.
|
|
77
|
-
"react": "19.0.0-rc-
|
|
78
|
-
"react-dom": "19.0.0-rc-
|
|
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-
|
|
87
|
-
"react-dom": "19.0.0-rc-
|
|
86
|
+
"react": "19.0.0-rc-7771d3a7-20240827",
|
|
87
|
+
"react-dom": "19.0.0-rc-7771d3a7-20240827"
|
|
88
88
|
}
|
|
89
89
|
},
|
|
90
90
|
"scripts": {
|