commerce-kit 0.0.13 → 0.0.15
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/README.md +9 -0
- package/dist/index.d.ts +62 -70
- package/dist/index.js +10 -1
- package/dist/internal.d.ts +11 -1
- package/dist/internal.js +1 -1
- package/dist/yns.d.ts +252 -2
- package/dist/yns.js +1 -1
- package/package.json +11 -5
package/README.md
CHANGED
|
@@ -61,6 +61,15 @@ export async function ProductList() {
|
|
|
61
61
|
}
|
|
62
62
|
```
|
|
63
63
|
|
|
64
|
+
## Debugging
|
|
65
|
+
|
|
66
|
+
This library uses a custom logger to output debug information. To control the debug output, use the `LOG_LEVEL` environment variable. The following levels are supported:
|
|
67
|
+
|
|
68
|
+
- **ERROR** – Critical issue for a specific request that needs immediate attention.
|
|
69
|
+
- **WARN** – Something that should be reviewed eventually.
|
|
70
|
+
- **LOG** – Details on regular operations.
|
|
71
|
+
- **DEBUG** – Debug information, including `time` and `timeEnd` function outputs.
|
|
72
|
+
|
|
64
73
|
## License
|
|
65
74
|
|
|
66
75
|
This project is licensed under the AGPL Version 3 license – see the LICENSE.md file for details.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,36 +1,20 @@
|
|
|
1
|
-
import { CartMetadata,
|
|
2
|
-
export { MappedProduct } from './internal.js';
|
|
1
|
+
import { CartMetadata, MappedCart } from './internal.js';
|
|
2
|
+
export { MappedProduct, MappedShippingRate } from './internal.js';
|
|
3
|
+
import { Config } from './yns.js';
|
|
3
4
|
import Stripe from 'stripe';
|
|
4
5
|
import { z, TypeOf } from 'zod';
|
|
5
6
|
|
|
6
|
-
type Entity = "Product" | "Category" | "Order";
|
|
7
|
-
type Provider = ({ tags, revalidate, cache, tagPrefix, }: {
|
|
8
|
-
tags?: NextFetchRequestConfig["tags"];
|
|
9
|
-
revalidate?: NextFetchRequestConfig["revalidate"];
|
|
10
|
-
cache?: RequestInit["cache"];
|
|
11
|
-
tagPrefix: string | undefined;
|
|
12
|
-
}) => Stripe;
|
|
13
|
-
type Filter<T extends Entity> = {
|
|
14
|
-
Product: {
|
|
15
|
-
category?: string;
|
|
16
|
-
};
|
|
17
|
-
Category: {};
|
|
18
|
-
Order: {};
|
|
19
|
-
}[T];
|
|
20
|
-
type BrowseParams<T extends Entity> = {
|
|
21
|
-
first?: number;
|
|
22
|
-
last?: number;
|
|
23
|
-
offset?: number;
|
|
24
|
-
filter?: Filter<T>;
|
|
25
|
-
};
|
|
26
|
-
type SearchParams<_T extends Entity> = {
|
|
27
|
-
query: string;
|
|
28
|
-
};
|
|
29
7
|
type Cart = NonNullable<Awaited<ReturnType<typeof cartGet>>>;
|
|
30
8
|
declare function cartAdd({ productId, cartId }: {
|
|
31
9
|
productId: string;
|
|
32
10
|
cartId?: string;
|
|
33
11
|
}): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
|
|
12
|
+
declare function cartUpdateQuantity({ productId, cartId, operation, clearTaxCalculation, }: {
|
|
13
|
+
productId: string;
|
|
14
|
+
cartId: string;
|
|
15
|
+
operation: "INCREASE" | "DECREASE";
|
|
16
|
+
clearTaxCalculation?: boolean;
|
|
17
|
+
}): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
|
|
34
18
|
declare function cartGet(cartId: string): Promise<{
|
|
35
19
|
cart: {
|
|
36
20
|
metadata: {
|
|
@@ -128,9 +112,12 @@ declare function cartGet(cartId: string): Promise<{
|
|
|
128
112
|
};
|
|
129
113
|
quantity: number;
|
|
130
114
|
}[];
|
|
131
|
-
shippingRate: Stripe.
|
|
115
|
+
shippingRate: Stripe.ShippingRate | null;
|
|
132
116
|
} | null | undefined>;
|
|
133
|
-
declare function cartCreate(
|
|
117
|
+
declare function cartCreate({ productId }?: {
|
|
118
|
+
productId?: string;
|
|
119
|
+
cartId?: string;
|
|
120
|
+
}): Promise<Stripe.Response<Stripe.PaymentIntent>>;
|
|
134
121
|
declare function cartAddOptimistic({ cart, add }: {
|
|
135
122
|
cart: Cart;
|
|
136
123
|
add: string | undefined;
|
|
@@ -231,7 +218,7 @@ declare function cartAddOptimistic({ cart, add }: {
|
|
|
231
218
|
};
|
|
232
219
|
quantity: number;
|
|
233
220
|
}[];
|
|
234
|
-
shippingRate: Stripe.
|
|
221
|
+
shippingRate: Stripe.ShippingRate | null;
|
|
235
222
|
}>;
|
|
236
223
|
declare function cartSetQuantity({ cartId, productId, quantity, }: {
|
|
237
224
|
cartId: string;
|
|
@@ -294,38 +281,14 @@ declare function productGet({ slug }: {
|
|
|
294
281
|
updated: number;
|
|
295
282
|
url: string | null;
|
|
296
283
|
}[]>;
|
|
297
|
-
declare function productBrowse(params:
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
category?: string
|
|
303
|
-
order?: number | undefined;
|
|
304
|
-
variant?: string | undefined;
|
|
284
|
+
declare function productBrowse(params: {
|
|
285
|
+
first?: number;
|
|
286
|
+
last?: number;
|
|
287
|
+
offset?: number;
|
|
288
|
+
filter?: {
|
|
289
|
+
category?: string;
|
|
305
290
|
};
|
|
306
|
-
|
|
307
|
-
object: "product";
|
|
308
|
-
active: boolean;
|
|
309
|
-
created: number;
|
|
310
|
-
deleted?: void | undefined;
|
|
311
|
-
description: string | null;
|
|
312
|
-
images: Array<string>;
|
|
313
|
-
livemode: boolean;
|
|
314
|
-
name: string;
|
|
315
|
-
package_dimensions: Stripe.Product.PackageDimensions | null;
|
|
316
|
-
shippable: boolean | null;
|
|
317
|
-
statement_descriptor?: string | null;
|
|
318
|
-
tax_code: string | Stripe.TaxCode | null;
|
|
319
|
-
type: Stripe.Product.Type;
|
|
320
|
-
unit_label?: string | null;
|
|
321
|
-
updated: number;
|
|
322
|
-
url: string | null;
|
|
323
|
-
}[]>;
|
|
324
|
-
type ShippingRate = Awaited<ReturnType<typeof shippingBrowse>>["data"][0];
|
|
325
|
-
declare function shippingBrowse(): Promise<Stripe.Response<Stripe.ApiList<Stripe.ShippingRate>>>;
|
|
326
|
-
declare function shippingGet(id: string): Promise<Stripe.Response<Stripe.ShippingRate> | null>;
|
|
327
|
-
declare function categoryBrowse(params: BrowseParams<"Category">): Promise<string[]>;
|
|
328
|
-
declare function productSearch(params: SearchParams<"Product">): Promise<{
|
|
291
|
+
}): Promise<{
|
|
329
292
|
default_price: Stripe.Price;
|
|
330
293
|
marketing_features: string[];
|
|
331
294
|
metadata: {
|
|
@@ -352,6 +315,9 @@ declare function productSearch(params: SearchParams<"Product">): Promise<{
|
|
|
352
315
|
updated: number;
|
|
353
316
|
url: string | null;
|
|
354
317
|
}[]>;
|
|
318
|
+
declare function shippingBrowse(): Promise<Stripe.ShippingRate[]>;
|
|
319
|
+
declare function shippingGet(id: string): Promise<Stripe.ShippingRate | null>;
|
|
320
|
+
declare function categoryBrowse(): Promise<string[]>;
|
|
355
321
|
declare function fileGet(id: string): Promise<Stripe.Response<Stripe.FileLink> | null>;
|
|
356
322
|
declare function accountGet(): Promise<{
|
|
357
323
|
account: (Stripe.Account & {
|
|
@@ -479,10 +445,9 @@ declare function orderGet(orderId: string): Promise<{
|
|
|
479
445
|
};
|
|
480
446
|
quantity: number;
|
|
481
447
|
}[];
|
|
482
|
-
shippingRate: Stripe.
|
|
448
|
+
shippingRate: Stripe.ShippingRate | null;
|
|
483
449
|
} | null>;
|
|
484
450
|
declare const getProductsFromCart: (metadata: CartMetadata) => (readonly [productId: string, quantity: number])[];
|
|
485
|
-
type MappedCart = ReturnType<typeof mapCart>;
|
|
486
451
|
declare function getProductsFromMetadata(metadata: MappedCart["metadata"]): Promise<{
|
|
487
452
|
product: {
|
|
488
453
|
default_price: Stripe.Price;
|
|
@@ -514,7 +479,7 @@ declare function getProductsFromMetadata(metadata: MappedCart["metadata"]): Prom
|
|
|
514
479
|
quantity: number;
|
|
515
480
|
}[]>;
|
|
516
481
|
type ProductsFromMetadata = Awaited<ReturnType<typeof getProductsFromMetadata>>;
|
|
517
|
-
declare const getCartWithProductsById: (
|
|
482
|
+
declare const getCartWithProductsById: (cartId: string) => Promise<{
|
|
518
483
|
cart: {
|
|
519
484
|
metadata: {
|
|
520
485
|
shippingRateId?: string | undefined;
|
|
@@ -611,7 +576,7 @@ declare const getCartWithProductsById: (provider: Provider, cartId: string) => P
|
|
|
611
576
|
};
|
|
612
577
|
quantity: number;
|
|
613
578
|
}[];
|
|
614
|
-
shippingRate: Stripe.
|
|
579
|
+
shippingRate: Stripe.ShippingRate | null;
|
|
615
580
|
} | null>;
|
|
616
581
|
declare const calculateCartTotalNet: (cart: {
|
|
617
582
|
cart: {
|
|
@@ -734,17 +699,44 @@ declare function cartSaveBillingAddress({ cartId, billingAddress, }: {
|
|
|
734
699
|
}): Promise<Stripe.Response<Stripe.PaymentIntent> | undefined>;
|
|
735
700
|
declare function taxDefaultGet(): Promise<Stripe.Response<Stripe.Tax.Settings>>;
|
|
736
701
|
declare function cartCount(metadata: CartMetadata): number;
|
|
702
|
+
type Review = {
|
|
703
|
+
id: string;
|
|
704
|
+
store_id: string;
|
|
705
|
+
product_id: string;
|
|
706
|
+
created_at: string;
|
|
707
|
+
updated_at: string;
|
|
708
|
+
author: string;
|
|
709
|
+
email: string;
|
|
710
|
+
content: string;
|
|
711
|
+
rating: number;
|
|
712
|
+
};
|
|
713
|
+
declare function productReviewBrowse(params: {
|
|
714
|
+
productId: string;
|
|
715
|
+
first?: number;
|
|
716
|
+
last?: number;
|
|
717
|
+
offset?: number;
|
|
718
|
+
filter?: {};
|
|
719
|
+
}): Promise<Review[]>;
|
|
720
|
+
declare function productReviewAdd(params: {
|
|
721
|
+
productId: string;
|
|
722
|
+
author: string;
|
|
723
|
+
email: string;
|
|
724
|
+
content: string;
|
|
725
|
+
rating: number;
|
|
726
|
+
}): Promise<Record<string, any>[]>;
|
|
727
|
+
declare const contextGet: () => Promise<{
|
|
728
|
+
stripeAccount: string | undefined;
|
|
729
|
+
storeId: string | undefined;
|
|
730
|
+
secretKey: string | undefined;
|
|
731
|
+
config: Config;
|
|
732
|
+
}>;
|
|
737
733
|
|
|
738
|
-
declare const
|
|
739
|
-
tags?: NextFetchRequestConfig["tags"];
|
|
740
|
-
revalidate?: NextFetchRequestConfig["revalidate"];
|
|
741
|
-
cache?: RequestInit["cache"];
|
|
742
|
-
}) => Stripe;
|
|
743
|
-
declare const provider: ({ tags, revalidate, cache, tagPrefix, }: {
|
|
734
|
+
declare const provider: ({ tags, revalidate, cache, tagPrefix, secretKey, }: {
|
|
744
735
|
tags?: NextFetchRequestConfig["tags"];
|
|
745
736
|
revalidate?: NextFetchRequestConfig["revalidate"];
|
|
746
737
|
cache?: RequestInit["cache"];
|
|
747
738
|
tagPrefix: string | undefined;
|
|
739
|
+
secretKey: string | undefined;
|
|
748
740
|
}) => Stripe;
|
|
749
741
|
|
|
750
|
-
export { type AddressSchema, type Cart,
|
|
742
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
import"server-only";import"server-only";import{z as c}from"zod";function C(t,e){if(!t)throw new Error(e)}var U=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},R=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},F=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var L=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${L(a)}"`).join(" AND ").trim();function A(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),r=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(r)||n===r?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(r)?-1:n-r})}var at=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional()});function $({default_price:t,marketing_features:e,...a}){return C(t,"Product must have a default price"),C(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:at.parse(a.metadata)}}function v(t){return t.data.map($)}function j(t){return t.filter((e,a,n)=>a===n.findIndex(r=>r.metadata.slug===e.metadata.slug))}var B=t=>!t.deleted&&t.active,q=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())),Y=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function Q(t){let e=t.payment_method;C(typeof e!="string","Payment method is missing from cart");let a=q.parse(t.metadata),n=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let o=Y.safeParse(F(String(i)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:n}}function V({payment_method:t,latest_charge:e,...a}){C(typeof t=="object","Payment method is missing from order"),C(typeof e=="object","Latest charge is missing from order");let n=q.parse(a.metadata),r=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,o])=>{let s=Y.safeParse(F(String(o)));return s.success?s.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:r,metadata:n}}import"server-only";import{revalidatePath as J,revalidateTag as P}from"next/cache";import _ from"stripe";import{z as w}from"zod";import"server-only";var f=async()=>{let t={stripeAccount:void 0,storeId:void 0};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};import"server-only";import K from"stripe";import"server-only";var z=process.env.STRIPE_SECRET_KEY;if(!z)throw new Error("Missing STRIPE_SECRET_KEY");var D=process.env.STRIPE_CURRENCY;if(!D)throw new Error("Missing STRIPE_CURRENCY");var h={StripeSecretKey:z,StripeCurrency:D};var nt=({tags:t,revalidate:e,cache:a})=>new K(h.StripeSecretKey,{typescript:!0,apiVersion:"2024-06-20",httpClient:K.createFetchHttpClient((r,i)=>fetch(r,{...i,cache:a??i?.cache,next:{tags:t??i?.next?.tags,revalidate:e??i?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}}),it=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],p=({tags:t,revalidate:e,cache:a,tagPrefix:n})=>nt({tags:it(t,n),revalidate:e,cache:a});var k=1e3;function Ot({productId:t,cartId:e}){return e?M.add(p,{productId:t,cartId:e}):M.create(p,{productId:t})}function T(t){return M.get(p,{cartId:t})}function jt(){return M.create(p,{})}async function Qt({cart:t,add:e}){if(!e)return t;let a=await E(e);if(!a)return console.warn(`Product not found: ${e}`),t;let r=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),i=t?W(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:i},lines:r}}async function Gt({cartId:t,productId:e,quantity:a}){let[n,r]=await Promise.all([H(e),T(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!r)throw new Error(`Cart not found: ${t}`);if(h.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let i=r.cart.metadata??{};a<=0?i[e]="":i[e]=a.toString();let o=W(r)+(n.default_price.unit_amount??0);try{return await S({paymentIntentId:t,data:{metadata:i,amount:o||k}})}catch(s){console.error(s)}finally{P(`cart-${t}`),J("/cart"),J("/cart-overlay")}}async function H(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Ut({slug:t}){let{stripeAccount:e,storeId:a}=await f(),r=await p({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"}).products.search({query:O({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return A(v(r).filter(B))}async function ot(t){let{stripeAccount:e,storeId:a}=await f();if(t.filter?.category){let n=t.filter?.category,i=await p({tagPrefix:a,tags:["product",`category-${n}`],cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':n}),expand:["data.default_price"]},{stripeAccount:e});return A(j(v(i)).filter(B).slice(t.offset,t.first))}else{let r=await p({tagPrefix:a,tags:["product"],cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return A(j(v(r)).filter(B).slice(t.offset,t.first))}}async function Yt(){let{stripeAccount:t,storeId:e}=await f();return await p({tagPrefix:e,tags:["shipping"],cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t})}async function I(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["shipping",`shipping-${t}`],cache:"force-cache"});try{return await n.shippingRates.retrieve(t,{},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Vt(t){let a=(await ot({first:100})).map(r=>r.metadata.category),n=new Set(a);return Array.from(n).filter(Boolean)}async function zt(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["products","search"],cache:"force-cache"}),r=L(t.query),i=await n.products.search({limit:100,query:`name~"${r}" OR description~"${r}" OR metadata["slug"]:"${r}" OR metadata["category"]:"${r}"`,expand:["data.default_price"]},{stripeAccount:e});return A(v(i).filter(o=>o.active&&!o.deleted))}async function Dt(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["files",`file-${t}`],cache:"force-cache"});try{return await n.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(console.error(r),r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Kt(){let{stripeAccount:t,storeId:e}=await f(),a=p({tagPrefix:e,tags:["account"],cache:"force-cache"});try{let[n,r]=await U(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(n){if(console.error(n),n instanceof _.errors.StripeError&&n.code==="resource_missing")return null;throw n}}async function ct(t){let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["order",`order-${t}`],cache:"force-cache"});try{let r=await n.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return V(r)}catch(r){if(r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Jt(t){let e=await ct(t);if(!e)return null;let a=tt(e.metadata),n=await Promise.all(a.map(async([o,s])=>({product:await E(o),quantity:s}))),{metadata:{shippingRateId:r}}=e,i=r&&await I(r);return{order:e,lines:n.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:i||null}}var E=async t=>{let{stripeAccount:e,storeId:a}=await f(),n=p({tagPrefix:a,tags:["product",`product-${t}`],cache:"force-cache"});try{let r=await n.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof _.errors.StripeError&&r.code==="resource_missing")return null;throw r}},Z=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],tt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),st=async(t,e)=>{let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status))return Q(i)}catch(i){if(console.error(i),i instanceof _.errors.StripeError&&i.code==="resource_missing")return null;throw i}};async function G(t){let e=tt(t);return await Promise.all(e.map(async([n,r])=>({product:await E(n),quantity:r})))}var et=async(t,e)=>{let a=await st(t,e);if(!a)return null;let n=await G(a.metadata),{metadata:{shippingRateId:r}}=a,i=r&&await I(r);return{cart:a,lines:n.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:i||null}},ut=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0,dt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function pt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let r=Date.now(),i=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!i||r>=i)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,u=dt.some(g=>!a[g]&&!t.cart.metadata[g]?!1:a[g]!==t.cart.metadata[g]),m=n.length!==t.lines.length||n.some(g=>{let d=t.lines.find(x=>x.product.id===g.product?.id);return g.product?.default_price.unit_amount!==d?.product.default_price.unit_amount||g.quantity!==d?.quantity});return s&&o!==s||u||m}var Xt=t=>w.object({name:w.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:w.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:w.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:w.string({required_error:t.line1Required}).min(1,t.line1Required),line2:w.string().optional().nullable().default(""),postalCode:w.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:w.string().optional().nullable().default(""),phone:w.string().optional().nullable().default(""),taxId:w.string().optional().nullable().default("")}),lt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:r})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:i,storeId:o}=await f(),s=p({tagPrefix:o,tags:["tax-calculations",`tax-calculations-${a}`],cache:"force-cache"});if(!e?.country)return null;let u=n?await I(n):null,m=typeof u?.tax_code=="string"?u.tax_code:u?.tax_code?.id,l=await ft(),y=h.StripeCurrency==="usd"||h.StripeCurrency==="cad"?"exclusive":"inclusive",g=l.defaults.tax_behavior==="inferred_by_currency"?y:l.defaults.tax_behavior??y;l.defaults.tax_behavior||console.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${h.StripeCurrency}: ${y}.`),console.time("createTaxCalculation ${cartId}");let d=await s.tax.calculations.create({expand:["line_items"],line_items:t.map(x=>({...x,tax_behavior:x.tax_behavior??g})),currency:h.StripeCurrency,shipping_cost:u?.active&&u?.fixed_amount?{amount:u.fixed_amount.amount,tax_behavior:u.tax_behavior==="inclusive"?"inclusive":u.tax_behavior==="exclusive"?"exclusive":g,tax_code:m??l.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:r?[{type:"eu_vat",value:r}]: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:i});return console.timeEnd("createTaxCalculation ${cartId}"),d},X={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},S=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let{stripeAccount:n,storeId:r}=await f(),i=await et(p,t);C(i,`Cart not found: ${t}`);let o=q.parse({...i.cart.metadata,...e.metadata}),s=await G(o),m=!a&&pt({oldCart:i,data:e,mergedMetadata:o,lines:s})?await lt({cartId:t,taxId:o.taxId??null,shippingRateId:o.shippingRateId??null,billingAddress:{country:o["billingAddress.country"]??"",city:o["billingAddress.city"]??"",line1:o["billingAddress.line1"]??"",line2:o["billingAddress.line2"]??"",name:o["billingAddress.name"]??"",postalCode:o["billingAddress.postalCode"]??"",state:o["billingAddress.state"]??""},lineItems:s.map(({product:d,quantity:x})=>{if(d?.default_price.unit_amount)return{product:d.id,reference:[d.metadata.slug,d.metadata.variant].filter(Boolean).join("-"),quantity:x,amount:d.default_price.unit_amount*x,tax_behavior:d.default_price.tax_behavior==="exclusive"?"exclusive":d.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:d.tax_code?typeof d.tax_code=="string"?d.tax_code:d.tax_code.id:void 0}}).filter(Boolean)}):null,l=e.amount?e.amount.toString():null;if(m){let d=Object.fromEntries(m.tax_breakdown.map(b=>({taxType:b.tax_rate_details.tax_type,taxPercentage:b.tax_rate_details.percentage_decimal,taxAmount:b.amount})).map((b,rt)=>[`taxBreakdown${rt}`,JSON.stringify(b)])),x=p({tagPrefix:r,tags:[],cache:"no-cache"});console.time(`updatePaymentIntent ${t}`);let N=await x.paymentIntents.update(t,{...e,amount:m.amount_total,metadata:{...o,...l&&{netAmount:l},...X,...d,taxCalculationId:m.id,taxCalculationExp:m?.expires_at}},{stripeAccount:n});return console.timeEnd(`updatePaymentIntent ${t}`),N}let y=p({tagPrefix:r,tags:[],cache:"no-cache"});console.time(`updatePaymentIntent ${t}`);let g=await y.paymentIntents.update(t,{...e,metadata:{...o,...l&&{netAmount:l},...a&&{...X,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:n});return console.timeEnd(`updatePaymentIntent ${t}`),g},M={async create(t,{productId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,cache:"no-cache"});try{let i=e?await E(e):null;return await r.paymentIntents.create({currency:h.StripeCurrency,amount:i?.default_price.unit_amount||k,automatic_payment_methods:{enabled:!0},metadata:{...i&&{[i.id]:"1"}}},{stripeAccount:a})}catch(i){throw console.error(i),i}},async get(t,{cartId:e}){let{stripeAccount:a,storeId:n}=await f(),r=t({tagPrefix:n,tags:["cart",`cart-${e}`],cache:"force-cache"});try{let i=await r.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:a});if(Z.includes(i.status)){let o=Q(i);if(!o)return null;let s=await G(o.metadata),{metadata:{shippingRateId:u}}=o,m=u&&await I(u);return{cart:o,lines:s.map(({product:l,quantity:y})=>l?{product:l,quantity:y}:null).filter(Boolean),shippingRate:m||null}}}catch(i){if(console.error(i),i instanceof _.errors.StripeError&&i.code==="resource_missing")return null;throw i}},async add(t,{cartId:e,productId:a}){return(async({productId:r,cartId:i,operation:o,clearTaxCalculation:s})=>{let[u,m]=await Promise.all([E(r),et(t,i)]);if(!u)throw new Error(`Product not found: ${r}`);if(!m)throw new Error(`Cart not found: ${i}`);if(h.StripeCurrency.toLowerCase()!==u.default_price.currency.toLowerCase())throw new Error(`Product currency ${u.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let l=m.cart.metadata??{},d=R(l[r])+(o==="INCREASE"?1:-1);d<=0?l[r]="":l[r]=d.toString();let x=ut(m)+(u.default_price.unit_amount??0);try{return await S({paymentIntentId:i,data:{metadata:l,amount:x||k},clearTaxCalculation:s})}catch(N){console.error(N)}finally{P(`cart-${i}`)}})({productId:a,cartId:e,operation:"INCREASE",clearTaxCalculation:!0})}},W=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+mt(t):0,mt=t=>t?t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0;async function Ht({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[r,i]=await Promise.all([H(t),T(e)]);if(!r)throw new Error(`Product not found: ${t}`);if(!i)throw new Error(`Cart not found: ${e}`);if(h.StripeCurrency?.toLowerCase()!==r.default_price.currency.toLowerCase())throw new Error(`Product currency ${r.default_price.currency} does not match cart currency ${h.StripeCurrency}`);let o=i.cart.metadata??{},m=R(o[t])+(a==="INCREASE"?1:-1);m<=0?o[t]="":o[t]=m.toString();let l=W(i)+(r.default_price.unit_amount??0);try{return await S({paymentIntentId:e,data:{metadata:o,amount:l||k},clearTaxCalculation:n})}catch(y){console.error(y)}finally{P(`cart-${e}`)}}var Zt=async({cartId:t,taxId:e})=>{let a=await T(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(n){console.error(n)}finally{P(`cart-${t}`)}};async function te({cartId:t,shippingRateId:e}){let a=await T(t);if(!a)throw new Error(`Cart not found: ${t}`);let n=await I(e);if(!n)throw new Error(`Shipping rate not found: ${e}`);try{return await S({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:W({...a,shippingRate:n})}})}catch(r){console.error(r)}finally{P(`cart-${t}`)}}async function ee({cartId:t,billingAddress:e}){if(!await T(t))throw new Error(`Cart not found: ${t}`);try{return await S({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(n){console.error(n)}finally{P(`cart-${t}`)}}async function ft(){let{stripeAccount:t,storeId:e}=await f();return await p({tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function re(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,R(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}export{nt as StripeClient,Kt as accountGet,ut as calculateCartTotalNet,mt as calculateCartTotalNetWithoutShipping,W as calculateCartTotalPossiblyWithTax,Ot as cartAdd,Qt as cartAddOptimistic,Ht as cartChangeQuantity,re as cartCount,jt as cartCreate,T as cartGet,ee as cartSaveBillingAddress,te as cartSaveShipping,Zt as cartSaveTax,Gt as cartSetQuantity,Vt as categoryBrowse,Dt as fileGet,Xt as getAddressSchema,et as getCartWithProductsById,tt as getProductsFromCart,Jt as orderGet,ot as productBrowse,Ut as productGet,H as productGetById,zt as productSearch,p as provider,Yt as shippingBrowse,I as shippingGet,ft as taxDefaultGet};
|
|
1
|
+
import"server-only";import"server-only";import{z as u}from"zod";function S(t,e){if(!t)throw new Error(e)}var z=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},K=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var dt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),U=t=>Object.entries(t).map(([e,a])=>`${e}:"${dt(a)}"`).join(" AND ").trim();function G(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),o=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(o)||n===o?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(o)?-1:n-o})}var pt=u.object({category:u.string().optional(),order:u.coerce.number().optional(),slug:u.string(),variant:u.string().optional()});function M({default_price:t,marketing_features:e,...a}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:pt.parse(a.metadata)}}function q(t){return t.data.map(M)}function H(t){return t}function J(t){return t.data.map(H)}function D(t){return t.filter((e,a,n)=>a===n.findIndex(o=>o.metadata.slug===e.metadata.slug))}var W=t=>!t.deleted&&t.active,j=u.object({shippingRateId:u.string().optional(),taxCalculationId:u.string().optional(),taxCalculationExp:u.string().optional(),taxId:u.string().optional(),"billingAddress.city":u.string().optional(),"billingAddress.country":u.string().optional(),"billingAddress.line1":u.string().optional(),"billingAddress.line2":u.string().optional(),"billingAddress.name":u.string().optional(),"billingAddress.postalCode":u.string().optional(),"billingAddress.state":u.string().optional(),netAmount:u.string().optional(),taxBreakdown0:u.string().optional(),taxBreakdown1:u.string().optional(),taxBreakdown2:u.string().optional(),taxBreakdown3:u.string().optional(),taxBreakdown4:u.string().optional(),taxBreakdown5:u.string().optional()}).and(u.record(u.string())),X=u.object({taxType:u.string(),taxPercentage:u.string(),taxAmount:u.number()});function Y(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let a=j.parse(t.metadata),n=Object.entries(a).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,r])=>{let i=X.safeParse(K(String(r)));return i.success?i.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:n}}function Z({payment_method:t,latest_charge:e,...a}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let n=j.parse(a.metadata),o=Object.entries(n).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let c=X.safeParse(K(String(i)));return c.success?c.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:n}}import"server-only";import{revalidatePath as rt,revalidateTag as E}from"next/cache";import R from"stripe";import{z as b}from"zod";import"server-only";import{z as s}from"zod";var Mt=s.object({hero:s.object({show:s.boolean(),title:s.string(),description:s.string(),button:s.object({label:s.string(),path:s.string()}),image:s.object({src:s.string(),alt:s.string()})}),categorySection:s.object({show:s.boolean()}),nav:s.object({title:s.string(),searchBar:s.object({show:s.boolean()}),links:s.array(s.object({label:s.string(),href:s.string()}))}),footer:s.object({name:s.string(),tagline:s.string(),newsletter:s.object({show:s.boolean()}),credits:s.boolean(),sections:s.array(s.object({header:s.string(),links:s.array(s.object({label:s.string(),href:s.string()}))}))})}),l=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,config:{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"}]}]}}};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};import"server-only";import et from"stripe";import"server-only";var lt=process.env.STRIPE_SECRET_KEY,tt=process.env.STRIPE_CURRENCY;if(!tt)throw new Error("Missing STRIPE_CURRENCY");var w={StripeSecretKey:lt,StripeCurrency:tt};var v={DEBUG:0,LOG:1,WARN:2,ERROR:3},mt="LOG",ft=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in v?process.env.LOG_LEVEL:mt,I=v[ft],d={time(t){I>v.DEBUG||console.time(t)},timeEnd(t){I>v.DEBUG||console.timeEnd(t)},log(...t){I>v.LOG||console.log(...t)},dir(t,e){I>v.LOG||console.dir(t,e)},warn(...t){I>v.WARN||console.warn(...t)},error(...t){I>v.ERROR||console.error(...t)}};var gt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],f=({tags:t,revalidate:e,cache:a,tagPrefix:n,secretKey:o})=>{let r=o??w.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");d.log(`Using Stripe secret key from ${o?"parameter":"env"}.`);let i=gt(t,n);return new et(r,{typescript:!0,apiVersion:"2024-06-20",httpClient:et.createFetchHttpClient((y,p)=>fetch(y,{...p,cache:a??p?.cache,next:{tags:i??p?.next?.tags,revalidate:e??p?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var _=t=>t.filter(Boolean),C={accountGetById:{tags:({accountId:t})=>_(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>_(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>_(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>_(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>_(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>_(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>_(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>_(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>_(["tax-settings"]),revalidate:()=>{}}};import{neon as ht}from"@neondatabase/serverless";var V=ht(process.env.DATABASE_URL);var O=1e3;function de({productId:t,cartId:e}){return e?yt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):xt({productId:t})}async function yt({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[o,r]=await Promise.all([k(t),st(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(w.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let i=r.cart.metadata??{},p=$(i[t])+(a==="INCREASE"?1:-1);p<=0?i[t]="":i[t]=p.toString();let h=bt(r)+(o.default_price.unit_amount??0);try{return await T({paymentIntentId:e,data:{metadata:i,amount:h||O},clearTaxCalculation:n})}catch(m){d.error(m)}finally{E(`cart-${e}`)}}async function N(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(ot.includes(r.status)){let i=Y(r);if(!i)return null;let c=await Q(i.metadata),{metadata:{shippingRateId:y}}=i,p=y&&await L(y);return{cart:i,lines:c.map(({product:h,quantity:m})=>h?{product:h,quantity:m}:null).filter(Boolean),shippingRate:p||null}}}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function xt({productId:t}={}){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,cache:"no-cache"});try{let r=t?await k(t):null;return await o.paymentIntents.create({currency:w.StripeCurrency,amount:r?.default_price.unit_amount||O,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw d.error(r),r}}async function pe({cart:t,add:e}){if(!e)return t;let a=await k(e);if(!a)return d.warn(`Product not found: ${e}`),t;let o=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),r=t?F(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:o}}async function le({cartId:t,productId:e,quantity:a}){let[n,o]=await Promise.all([nt(e),N(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!o)throw new Error(`Cart not found: ${t}`);if(w.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let r=o.cart.metadata??{};a<=0?r[e]="":r[e]=a.toString();let i=F(o)+(n.default_price.unit_amount??0);try{return await T({paymentIntentId:t,data:{metadata:r,amount:i||O}})}catch(c){d.error(c)}finally{E(`cart-${t}`),rt("/cart"),rt("/cart-overlay")}}async function nt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return M(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function me({slug:t}){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),r=await f({secretKey:n,tagPrefix:a,tags:C.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:U({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return G(q(r).filter(W))}async function wt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l();if(t.filter?.category){let o=t.filter?.category,i=await f({secretKey:n,tagPrefix:a,tags:C.productBrowse.tags({category:o}),cache:"force-cache"}).products.search({limit:100,query:U({active:!0,'metadata["category"]':o}),expand:["data.default_price"]},{stripeAccount:e});return G(D(q(i)).filter(W).slice(t.offset,t.first))}else{let r=await f({secretKey:n,tagPrefix:a,tags:C.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return G(D(q(r)).filter(W).slice(t.offset,t.first))}}async function fe(){let{stripeAccount:t,storeId:e,secretKey:a}=await l(),o=await f({secretKey:a,tagPrefix:e,tags:C.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return J(o)}async function L(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ge(){let e=(await wt({first:100})).map(n=>n.metadata.category).filter(Boolean),a=new Set(e);return Array.from(a)}async function he(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await o.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ye(){let{stripeAccount:t,storeId:e,secretKey:a}=await l(),n=f({secretKey:a,tagPrefix:e,tags:C.accountGetById.tags({}),cache:"force-cache"});try{let[o,r]=await z(n.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(o){if(d.error(o),o instanceof R.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function Ct(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return Z(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function xe(t){let e=await Ct(t);if(!e)return null;let a=it(e.metadata),n=await Promise.all(a.map(async([i,c])=>({product:await k(i),quantity:c}))),{metadata:{shippingRateId:o}}=e,r=o&&await L(o);return{order:e,lines:n.map(({product:i,quantity:c})=>i?{product:i,quantity:c}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return M(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}},ot=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],it=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,$(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),_t=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(ot.includes(r.status))return Y(r)}catch(r){if(d.error(r),r instanceof R.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([n,o])=>({product:await k(n),quantity:o})))}var st=async t=>{let e=await _t(t);if(!e)return null;let a=await Q(e.metadata),{metadata:{shippingRateId:n}}=e,o=n&&await L(n);return{cart:e,lines:a.map(({product:r,quantity:i})=>r?{product:r,quantity:i}:null).filter(Boolean),shippingRate:o||null}},bt=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0,St=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function vt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),r=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!r||o>=r)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,c=e.amount,y=St.some(x=>!a[x]&&!t.cart.metadata[x]?!1:a[x]!==t.cart.metadata[x]),p=n.length!==t.lines.length||n.some(x=>{let P=t.lines.find(g=>g.product.id===x.product?.id);return x.product?.default_price.unit_amount!==P?.product.default_price.unit_amount||x.quantity!==P?.quantity});return c&&i!==c||y||p}var we=t=>b.object({name:b.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:b.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:b.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:b.string({required_error:t.line1Required}).min(1,t.line1Required),line2:b.string().optional().nullable().default(""),postalCode:b.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:b.string().optional().nullable().default(""),phone:b.string().optional().nullable().default(""),taxId:b.string().optional().nullable().default("")}),Rt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:r,storeId:i,secretKey:c}=await l(),y=f({secretKey:c,tagPrefix:i,tags:C.createTaxCalculation.tags({cartId:a}),cache:"force-cache"});if(!e?.country)return null;let p=n?await L(n):null,h=typeof p?.tax_code=="string"?p.tax_code:p?.tax_code?.id,m=await At(),x=w.StripeCurrency==="usd"||w.StripeCurrency==="cad"?"exclusive":"inclusive",P=m.defaults.tax_behavior==="inferred_by_currency"?x:m.defaults.tax_behavior??x;m.defaults.tax_behavior||d.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${w.StripeCurrency}: ${x}.`),d.time("createTaxCalculation ${cartId}");let g=await y.tax.calculations.create({expand:["line_items"],line_items:t.map(A=>({...A,tax_behavior:A.tax_behavior??P})),currency:w.StripeCurrency,shipping_cost:p?.active&&p?.fixed_amount?{amount:p.fixed_amount.amount,tax_behavior:p.tax_behavior==="inclusive"?"inclusive":p.tax_behavior==="exclusive"?"exclusive":P,tax_code:h??m.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return d.timeEnd("createTaxCalculation ${cartId}"),g},at={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},T=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let{stripeAccount:n,storeId:o,secretKey:r}=await l(),i=await st(t);S(i,`Cart not found: ${t}`);let c=j.parse({...i.cart.metadata,...e.metadata});d.time("getProductsFromMetadata");let y=await Q(c);d.timeEnd("getProductsFromMetadata");let h=!a&&vt({oldCart:i,data:e,mergedMetadata:c,lines:y})?await Rt({cartId:t,taxId:c.taxId??null,shippingRateId:c.shippingRateId??null,billingAddress:{country:c["billingAddress.country"]??"",city:c["billingAddress.city"]??"",line1:c["billingAddress.line1"]??"",line2:c["billingAddress.line2"]??"",name:c["billingAddress.name"]??"",postalCode:c["billingAddress.postalCode"]??"",state:c["billingAddress.state"]??""},lineItems:y.map(({product:g,quantity:A})=>{if(g?.default_price.unit_amount)return{product:g.id,reference:[g.metadata.slug,g.metadata.variant].filter(Boolean).join("-"),quantity:A,amount:g.default_price.unit_amount*A,tax_behavior:g.default_price.tax_behavior==="exclusive"?"exclusive":g.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:g.tax_code?typeof g.tax_code=="string"?g.tax_code:g.tax_code.id:void 0}}).filter(Boolean)}):null,m=e.amount?e.amount.toString():null;if(h){let g=Object.fromEntries(h.tax_breakdown.map(B=>({taxType:B.tax_rate_details.tax_type,taxPercentage:B.tax_rate_details.percentage_decimal,taxAmount:B.amount})).map((B,ut)=>[`taxBreakdown${ut}`,JSON.stringify(B)])),A=f({secretKey:r,tagPrefix:o,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let ct=await A.paymentIntents.update(t,{...e,amount:h.amount_total,metadata:{...c,...m&&{netAmount:m},...at,...g,taxCalculationId:h.id,taxCalculationExp:h?.expires_at}},{stripeAccount:n});return d.timeEnd(`paymentIntents.update ${t}`),ct}let x=f({secretKey:r,tagPrefix:o,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let P=await x.paymentIntents.update(t,{...e,metadata:{...c,...m&&{netAmount:m},...a&&{...at,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:n});return d.timeEnd(`paymentIntents.update ${t}`),P},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Pt(t):0,Pt=t=>t?t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0;async function Ce({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[o,r]=await Promise.all([nt(t),N(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(w.StripeCurrency?.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let i=r.cart.metadata??{},p=$(i[t])+(a==="INCREASE"?1:-1);p<=0?i[t]="":i[t]=p.toString();let h=F(r)+(o.default_price.unit_amount??0);try{return await T({paymentIntentId:e,data:{metadata:i,amount:h||O},clearTaxCalculation:n})}catch(m){d.error(m)}finally{E(`cart-${e}`)}}var _e=async({cartId:t,taxId:e})=>{let a=await N(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await T({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(n){d.error(n)}finally{E(`cart-${t}`)}};async function be({cartId:t,shippingRateId:e}){let a=await N(t);if(!a)throw new Error(`Cart not found: ${t}`);d.time(`cartSaveShipping ${t}`);let n=await L(e);if(d.timeEnd(`cartSaveShipping ${t}`),!n)throw new Error(`Shipping rate not found: ${e}`);try{d.time(`updatePaymentIntent ${t}`);let o=await T({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:F({...a,shippingRate:n})}});return d.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){d.error(o)}finally{E(`cart-${t}`)}}async function Se({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(n){d.error(n)}finally{E(`cart-${t}`)}}async function At(){let{stripeAccount:t,storeId:e,secretKey:a}=await l();return await f({secretKey:a,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function ve(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,$(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function Re(t){let{storeId:e}=await l();return await V`
|
|
2
|
+
select * from reviews
|
|
3
|
+
where product_id = ${t.productId}
|
|
4
|
+
order by created_at desc
|
|
5
|
+
limit ${t.first??100}
|
|
6
|
+
offset ${t.offset??0}
|
|
7
|
+
`}async function Pe(t){let{storeId:e}=await l();return await V`
|
|
8
|
+
insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
|
|
9
|
+
values (${e}, ${t.productId}, ${t.author}, ${t.email}, ${t.content}, ${t.rating}, now(), now())
|
|
10
|
+
`}var Ae=l;export{ye as accountGet,bt as calculateCartTotalNet,Pt as calculateCartTotalNetWithoutShipping,F as calculateCartTotalPossiblyWithTax,de as cartAdd,pe as cartAddOptimistic,Ce as cartChangeQuantity,ve as cartCount,xt as cartCreate,N as cartGet,Se as cartSaveBillingAddress,be as cartSaveShipping,_e as cartSaveTax,le as cartSetQuantity,yt as cartUpdateQuantity,ge as categoryBrowse,Ae as contextGet,he as fileGet,we as getAddressSchema,st as getCartWithProductsById,it as getProductsFromCart,xe as orderGet,wt as productBrowse,me as productGet,nt as productGetById,Pe as productReviewAdd,Re as productReviewBrowse,f as provider,fe as shippingBrowse,L as shippingGet,At as taxDefaultGet};
|
package/dist/internal.d.ts
CHANGED
|
@@ -112,6 +112,15 @@ declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<St
|
|
|
112
112
|
updated: number;
|
|
113
113
|
url: string | null;
|
|
114
114
|
}[];
|
|
115
|
+
/**
|
|
116
|
+
* @internal
|
|
117
|
+
*/
|
|
118
|
+
declare function mapShippingRate(shippingRate: Stripe.ShippingRate): Stripe.ShippingRate;
|
|
119
|
+
type MappedShippingRate = ReturnType<typeof mapShippingRate>;
|
|
120
|
+
/**
|
|
121
|
+
* @internal
|
|
122
|
+
*/
|
|
123
|
+
declare function mapShippingRates(shippingRates: Stripe.ApiList<Stripe.ShippingRate>): Stripe.ShippingRate[];
|
|
115
124
|
/**
|
|
116
125
|
* @internal
|
|
117
126
|
*/
|
|
@@ -293,6 +302,7 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
|
|
|
293
302
|
transfer_data: Stripe.PaymentIntent.TransferData | null;
|
|
294
303
|
transfer_group: string | null;
|
|
295
304
|
};
|
|
305
|
+
type MappedCart = ReturnType<typeof mapCart>;
|
|
296
306
|
/**
|
|
297
307
|
* @internal
|
|
298
308
|
*/
|
|
@@ -363,4 +373,4 @@ declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.Pa
|
|
|
363
373
|
transfer_group: string | null;
|
|
364
374
|
};
|
|
365
375
|
|
|
366
|
-
export { type CartMetadata, type MappedProduct, type ProductMetadata, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, objectToStripeQuery, sanitizeQueryValue, sortProducts };
|
|
376
|
+
export { type CartMetadata, type MappedCart, type MappedProduct, type MappedShippingRate, type ProductMetadata, cartMetadataSchema, cartMetadataTaxBreakdownSchema, getUniqueVariants, isProductAvailable, mapCart, mapOrder, mapProduct, mapProducts, mapShippingRate, mapShippingRates, objectToStripeQuery, sanitizeQueryValue, sortProducts };
|
package/dist/internal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"server-only";import{z as
|
|
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};
|
package/dist/yns.d.ts
CHANGED
|
@@ -1,6 +1,256 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
declare const configSchema: z.ZodObject<{
|
|
4
|
+
hero: z.ZodObject<{
|
|
5
|
+
show: z.ZodBoolean;
|
|
6
|
+
title: z.ZodString;
|
|
7
|
+
description: z.ZodString;
|
|
8
|
+
button: z.ZodObject<{
|
|
9
|
+
label: z.ZodString;
|
|
10
|
+
path: z.ZodString;
|
|
11
|
+
}, "strip", z.ZodTypeAny, {
|
|
12
|
+
path: string;
|
|
13
|
+
label: string;
|
|
14
|
+
}, {
|
|
15
|
+
path: string;
|
|
16
|
+
label: string;
|
|
17
|
+
}>;
|
|
18
|
+
image: z.ZodObject<{
|
|
19
|
+
src: z.ZodString;
|
|
20
|
+
alt: z.ZodString;
|
|
21
|
+
}, "strip", z.ZodTypeAny, {
|
|
22
|
+
src: string;
|
|
23
|
+
alt: string;
|
|
24
|
+
}, {
|
|
25
|
+
src: string;
|
|
26
|
+
alt: string;
|
|
27
|
+
}>;
|
|
28
|
+
}, "strip", z.ZodTypeAny, {
|
|
29
|
+
description: string;
|
|
30
|
+
show: boolean;
|
|
31
|
+
title: string;
|
|
32
|
+
button: {
|
|
33
|
+
path: string;
|
|
34
|
+
label: string;
|
|
35
|
+
};
|
|
36
|
+
image: {
|
|
37
|
+
src: string;
|
|
38
|
+
alt: string;
|
|
39
|
+
};
|
|
40
|
+
}, {
|
|
41
|
+
description: string;
|
|
42
|
+
show: boolean;
|
|
43
|
+
title: string;
|
|
44
|
+
button: {
|
|
45
|
+
path: string;
|
|
46
|
+
label: string;
|
|
47
|
+
};
|
|
48
|
+
image: {
|
|
49
|
+
src: string;
|
|
50
|
+
alt: string;
|
|
51
|
+
};
|
|
52
|
+
}>;
|
|
53
|
+
categorySection: z.ZodObject<{
|
|
54
|
+
show: z.ZodBoolean;
|
|
55
|
+
}, "strip", z.ZodTypeAny, {
|
|
56
|
+
show: boolean;
|
|
57
|
+
}, {
|
|
58
|
+
show: boolean;
|
|
59
|
+
}>;
|
|
60
|
+
nav: z.ZodObject<{
|
|
61
|
+
title: z.ZodString;
|
|
62
|
+
searchBar: z.ZodObject<{
|
|
63
|
+
show: z.ZodBoolean;
|
|
64
|
+
}, "strip", z.ZodTypeAny, {
|
|
65
|
+
show: boolean;
|
|
66
|
+
}, {
|
|
67
|
+
show: boolean;
|
|
68
|
+
}>;
|
|
69
|
+
links: z.ZodArray<z.ZodObject<{
|
|
70
|
+
label: z.ZodString;
|
|
71
|
+
href: z.ZodString;
|
|
72
|
+
}, "strip", z.ZodTypeAny, {
|
|
73
|
+
label: string;
|
|
74
|
+
href: string;
|
|
75
|
+
}, {
|
|
76
|
+
label: string;
|
|
77
|
+
href: string;
|
|
78
|
+
}>, "many">;
|
|
79
|
+
}, "strip", z.ZodTypeAny, {
|
|
80
|
+
title: string;
|
|
81
|
+
searchBar: {
|
|
82
|
+
show: boolean;
|
|
83
|
+
};
|
|
84
|
+
links: {
|
|
85
|
+
label: string;
|
|
86
|
+
href: string;
|
|
87
|
+
}[];
|
|
88
|
+
}, {
|
|
89
|
+
title: string;
|
|
90
|
+
searchBar: {
|
|
91
|
+
show: boolean;
|
|
92
|
+
};
|
|
93
|
+
links: {
|
|
94
|
+
label: string;
|
|
95
|
+
href: string;
|
|
96
|
+
}[];
|
|
97
|
+
}>;
|
|
98
|
+
footer: z.ZodObject<{
|
|
99
|
+
name: z.ZodString;
|
|
100
|
+
tagline: z.ZodString;
|
|
101
|
+
newsletter: z.ZodObject<{
|
|
102
|
+
show: z.ZodBoolean;
|
|
103
|
+
}, "strip", z.ZodTypeAny, {
|
|
104
|
+
show: boolean;
|
|
105
|
+
}, {
|
|
106
|
+
show: boolean;
|
|
107
|
+
}>;
|
|
108
|
+
credits: z.ZodBoolean;
|
|
109
|
+
sections: z.ZodArray<z.ZodObject<{
|
|
110
|
+
header: z.ZodString;
|
|
111
|
+
links: z.ZodArray<z.ZodObject<{
|
|
112
|
+
label: z.ZodString;
|
|
113
|
+
href: z.ZodString;
|
|
114
|
+
}, "strip", z.ZodTypeAny, {
|
|
115
|
+
label: string;
|
|
116
|
+
href: string;
|
|
117
|
+
}, {
|
|
118
|
+
label: string;
|
|
119
|
+
href: string;
|
|
120
|
+
}>, "many">;
|
|
121
|
+
}, "strip", z.ZodTypeAny, {
|
|
122
|
+
links: {
|
|
123
|
+
label: string;
|
|
124
|
+
href: string;
|
|
125
|
+
}[];
|
|
126
|
+
header: string;
|
|
127
|
+
}, {
|
|
128
|
+
links: {
|
|
129
|
+
label: string;
|
|
130
|
+
href: string;
|
|
131
|
+
}[];
|
|
132
|
+
header: string;
|
|
133
|
+
}>, "many">;
|
|
134
|
+
}, "strip", z.ZodTypeAny, {
|
|
135
|
+
name: string;
|
|
136
|
+
tagline: string;
|
|
137
|
+
newsletter: {
|
|
138
|
+
show: boolean;
|
|
139
|
+
};
|
|
140
|
+
credits: boolean;
|
|
141
|
+
sections: {
|
|
142
|
+
links: {
|
|
143
|
+
label: string;
|
|
144
|
+
href: string;
|
|
145
|
+
}[];
|
|
146
|
+
header: string;
|
|
147
|
+
}[];
|
|
148
|
+
}, {
|
|
149
|
+
name: string;
|
|
150
|
+
tagline: string;
|
|
151
|
+
newsletter: {
|
|
152
|
+
show: boolean;
|
|
153
|
+
};
|
|
154
|
+
credits: boolean;
|
|
155
|
+
sections: {
|
|
156
|
+
links: {
|
|
157
|
+
label: string;
|
|
158
|
+
href: string;
|
|
159
|
+
}[];
|
|
160
|
+
header: string;
|
|
161
|
+
}[];
|
|
162
|
+
}>;
|
|
163
|
+
}, "strip", z.ZodTypeAny, {
|
|
164
|
+
hero: {
|
|
165
|
+
description: string;
|
|
166
|
+
show: boolean;
|
|
167
|
+
title: string;
|
|
168
|
+
button: {
|
|
169
|
+
path: string;
|
|
170
|
+
label: string;
|
|
171
|
+
};
|
|
172
|
+
image: {
|
|
173
|
+
src: string;
|
|
174
|
+
alt: string;
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
categorySection: {
|
|
178
|
+
show: boolean;
|
|
179
|
+
};
|
|
180
|
+
nav: {
|
|
181
|
+
title: string;
|
|
182
|
+
searchBar: {
|
|
183
|
+
show: boolean;
|
|
184
|
+
};
|
|
185
|
+
links: {
|
|
186
|
+
label: string;
|
|
187
|
+
href: string;
|
|
188
|
+
}[];
|
|
189
|
+
};
|
|
190
|
+
footer: {
|
|
191
|
+
name: string;
|
|
192
|
+
tagline: string;
|
|
193
|
+
newsletter: {
|
|
194
|
+
show: boolean;
|
|
195
|
+
};
|
|
196
|
+
credits: boolean;
|
|
197
|
+
sections: {
|
|
198
|
+
links: {
|
|
199
|
+
label: string;
|
|
200
|
+
href: string;
|
|
201
|
+
}[];
|
|
202
|
+
header: string;
|
|
203
|
+
}[];
|
|
204
|
+
};
|
|
205
|
+
}, {
|
|
206
|
+
hero: {
|
|
207
|
+
description: string;
|
|
208
|
+
show: boolean;
|
|
209
|
+
title: string;
|
|
210
|
+
button: {
|
|
211
|
+
path: string;
|
|
212
|
+
label: string;
|
|
213
|
+
};
|
|
214
|
+
image: {
|
|
215
|
+
src: string;
|
|
216
|
+
alt: string;
|
|
217
|
+
};
|
|
218
|
+
};
|
|
219
|
+
categorySection: {
|
|
220
|
+
show: boolean;
|
|
221
|
+
};
|
|
222
|
+
nav: {
|
|
223
|
+
title: string;
|
|
224
|
+
searchBar: {
|
|
225
|
+
show: boolean;
|
|
226
|
+
};
|
|
227
|
+
links: {
|
|
228
|
+
label: string;
|
|
229
|
+
href: string;
|
|
230
|
+
}[];
|
|
231
|
+
};
|
|
232
|
+
footer: {
|
|
233
|
+
name: string;
|
|
234
|
+
tagline: string;
|
|
235
|
+
newsletter: {
|
|
236
|
+
show: boolean;
|
|
237
|
+
};
|
|
238
|
+
credits: boolean;
|
|
239
|
+
sections: {
|
|
240
|
+
links: {
|
|
241
|
+
label: string;
|
|
242
|
+
href: string;
|
|
243
|
+
}[];
|
|
244
|
+
header: string;
|
|
245
|
+
}[];
|
|
246
|
+
};
|
|
247
|
+
}>;
|
|
248
|
+
type Config = z.infer<typeof configSchema>;
|
|
1
249
|
type YnsFindStripeAccountResult = {
|
|
2
250
|
stripeAccount: string | undefined;
|
|
3
251
|
storeId: string | undefined;
|
|
252
|
+
secretKey: string | undefined;
|
|
253
|
+
config: Config;
|
|
4
254
|
};
|
|
5
255
|
declare global {
|
|
6
256
|
/**
|
|
@@ -9,6 +259,6 @@ declare global {
|
|
|
9
259
|
*/
|
|
10
260
|
function __ynsFindStripeAccount(): YnsFindStripeAccountResult | undefined | Promise<YnsFindStripeAccountResult | undefined>;
|
|
11
261
|
}
|
|
12
|
-
declare const
|
|
262
|
+
declare const getYnsContext: () => Promise<YnsFindStripeAccountResult>;
|
|
13
263
|
|
|
14
|
-
export {
|
|
264
|
+
export { type Config, configSchema, getYnsContext };
|
package/dist/yns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"server-only";var i=async()=>{let
|
|
1
|
+
import"server-only";import{z as e}from"zod";var s=e.object({hero:e.object({show:e.boolean(),title:e.string(),description:e.string(),button:e.object({label:e.string(),path:e.string()}),image:e.object({src:e.string(),alt:e.string()})}),categorySection:e.object({show:e.boolean()}),nav:e.object({title:e.string(),searchBar:e.object({show:e.boolean()}),links:e.array(e.object({label:e.string(),href:e.string()}))}),footer:e.object({name:e.string(),tagline:e.string(),newsletter:e.object({show:e.boolean()}),credits:e.boolean(),sections:e.array(e.object({header:e.string(),links:e.array(e.object({label:e.string(),href:e.string()}))}))})}),i=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,config:{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"}]}]}}};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};export{s as configSchema,i as getYnsContext};
|
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.15",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
|
7
7
|
"keywords": [
|
|
@@ -34,6 +34,10 @@
|
|
|
34
34
|
"./yns": {
|
|
35
35
|
"import": "./dist/yns.js",
|
|
36
36
|
"types": "./dist/yns.d.ts"
|
|
37
|
+
},
|
|
38
|
+
"./db": {
|
|
39
|
+
"import": "./dist/db.js",
|
|
40
|
+
"types": "./dist/db.d.ts"
|
|
37
41
|
}
|
|
38
42
|
},
|
|
39
43
|
"files": [
|
|
@@ -44,7 +48,8 @@
|
|
|
44
48
|
],
|
|
45
49
|
"sideEffects": false,
|
|
46
50
|
"devDependencies": {
|
|
47
|
-
"@
|
|
51
|
+
"@neondatabase/serverless": "^0.9.4",
|
|
52
|
+
"@types/node": "^22.4.2",
|
|
48
53
|
"@types/react": "npm:types-react@19.0.0-rc.1",
|
|
49
54
|
"@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
|
|
50
55
|
"next": "15.0.0-canary.96",
|
|
@@ -53,17 +58,18 @@
|
|
|
53
58
|
"react-dom": "^19.0.0-rc.1",
|
|
54
59
|
"rimraf": "6.0.1",
|
|
55
60
|
"server-only": "0.0.1",
|
|
56
|
-
"stripe": "^16.
|
|
61
|
+
"stripe": "^16.8.0",
|
|
57
62
|
"tsup": "8.2.4",
|
|
58
|
-
"tsx": "^4.
|
|
63
|
+
"tsx": "^4.17.0",
|
|
59
64
|
"vitest": "^2.0.5",
|
|
60
65
|
"zod": "^3.23.8"
|
|
61
66
|
},
|
|
62
67
|
"peerDependencies": {
|
|
68
|
+
"@neondatabase/serverless": "^0.9.4",
|
|
63
69
|
"@types/node": "^20.14.8",
|
|
64
70
|
"@types/react": "npm:types-react@19.0.0-rc.1",
|
|
65
71
|
"@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
|
|
66
|
-
"next": "15.0.0-canary.
|
|
72
|
+
"next": "15.0.0-canary.121",
|
|
67
73
|
"react": "19.0.0-rc-3208e73e-20240730",
|
|
68
74
|
"react-dom": "19.0.0-rc-3208e73e-20240730",
|
|
69
75
|
"server-only": "0.0.1",
|