commerce-kit 0.6.0 → 0.6.1-experimental.2
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 +37 -6
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -0
- package/package.json +23 -44
- package/LICENSE.md +0 -650
- package/README.md +0 -234
- package/dist/currencies.d.ts +0 -11
- package/dist/currencies.js +0 -1
- package/dist/internal.d.ts +0 -383
- package/dist/internal.js +0 -1
- package/dist/provider-CeP9uHnB.d.ts +0 -166
- package/dist/stripe.d.ts +0 -75
- package/dist/stripe.js +0 -1
- package/dist/yns-context.d.ts +0 -22
- package/dist/yns-context.js +0 -1
- package/dist/yns.d.ts +0 -101
- package/dist/yns.js +0 -1
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
interface BaseProvider {
|
|
2
|
-
productBrowse(params: ProductBrowseParams): Promise<ProductBrowseResult>;
|
|
3
|
-
productGet(params: ProductGetParams): Promise<Product | null>;
|
|
4
|
-
productSearch?(params: ProductSearchParams): Promise<ProductSearchResult>;
|
|
5
|
-
cartAdd(params: CartAddParams): Promise<Cart>;
|
|
6
|
-
cartUpdate(params: CartUpdateParams): Promise<Cart>;
|
|
7
|
-
cartRemove(params: CartRemoveParams): Promise<Cart>;
|
|
8
|
-
cartClear(params: CartClearParams): Promise<Cart>;
|
|
9
|
-
cartGet(params: CartGetParams): Promise<Cart | null>;
|
|
10
|
-
orderGet?(params: OrderGetParams): Promise<Order | null>;
|
|
11
|
-
orderList?(params: OrderListParams): Promise<OrderListResult>;
|
|
12
|
-
}
|
|
13
|
-
interface StripeProviderConfig {
|
|
14
|
-
secretKey?: string;
|
|
15
|
-
tagPrefix?: string;
|
|
16
|
-
}
|
|
17
|
-
interface YnsProviderConfig {
|
|
18
|
-
endpoint: string;
|
|
19
|
-
token: string;
|
|
20
|
-
}
|
|
21
|
-
interface Product {
|
|
22
|
-
id: string;
|
|
23
|
-
name: string;
|
|
24
|
-
slug?: string;
|
|
25
|
-
summary?: string;
|
|
26
|
-
images: string[];
|
|
27
|
-
active: boolean;
|
|
28
|
-
price: number;
|
|
29
|
-
currency: string;
|
|
30
|
-
stock?: number;
|
|
31
|
-
}
|
|
32
|
-
interface Customer {
|
|
33
|
-
id: string;
|
|
34
|
-
email?: string;
|
|
35
|
-
}
|
|
36
|
-
interface ProductInfo {
|
|
37
|
-
id: string;
|
|
38
|
-
name?: string;
|
|
39
|
-
images?: string[];
|
|
40
|
-
}
|
|
41
|
-
interface Cart {
|
|
42
|
-
id: string;
|
|
43
|
-
customerId?: string;
|
|
44
|
-
storeId?: string;
|
|
45
|
-
customer?: Customer;
|
|
46
|
-
items: CartItem[];
|
|
47
|
-
total: number;
|
|
48
|
-
currency: string;
|
|
49
|
-
createdAt?: string;
|
|
50
|
-
updatedAt?: string;
|
|
51
|
-
}
|
|
52
|
-
interface CartItem {
|
|
53
|
-
id: string;
|
|
54
|
-
productId: string;
|
|
55
|
-
variantId?: string;
|
|
56
|
-
quantity: number;
|
|
57
|
-
price: number;
|
|
58
|
-
stock?: number;
|
|
59
|
-
product?: ProductInfo;
|
|
60
|
-
}
|
|
61
|
-
interface Order {
|
|
62
|
-
id: string;
|
|
63
|
-
customerId?: string;
|
|
64
|
-
items: CartItem[];
|
|
65
|
-
total: number;
|
|
66
|
-
currency: string;
|
|
67
|
-
status: string;
|
|
68
|
-
createdAt: string;
|
|
69
|
-
updatedAt: string;
|
|
70
|
-
}
|
|
71
|
-
interface ProductBrowseParams {
|
|
72
|
-
first?: number;
|
|
73
|
-
offset?: number;
|
|
74
|
-
category?: string;
|
|
75
|
-
query?: string;
|
|
76
|
-
active?: boolean;
|
|
77
|
-
orderBy?: string;
|
|
78
|
-
orderDirection?: "asc" | "desc";
|
|
79
|
-
graphql?: string;
|
|
80
|
-
_provider?: "stripe" | "yns";
|
|
81
|
-
}
|
|
82
|
-
interface ProductGetParams {
|
|
83
|
-
slug?: string;
|
|
84
|
-
id?: string;
|
|
85
|
-
graphql?: string;
|
|
86
|
-
_provider?: "stripe" | "yns";
|
|
87
|
-
}
|
|
88
|
-
interface ProductSearchParams {
|
|
89
|
-
query: string;
|
|
90
|
-
limit?: number;
|
|
91
|
-
fields?: string[];
|
|
92
|
-
_provider?: "stripe" | "yns";
|
|
93
|
-
}
|
|
94
|
-
interface CartAddParams {
|
|
95
|
-
variantId: string;
|
|
96
|
-
quantity: number;
|
|
97
|
-
cartId?: string;
|
|
98
|
-
subscriptionId?: string;
|
|
99
|
-
_provider?: "stripe" | "yns";
|
|
100
|
-
}
|
|
101
|
-
interface CartRemoveParams {
|
|
102
|
-
cartId: string;
|
|
103
|
-
variantId: string;
|
|
104
|
-
_provider?: "stripe" | "yns";
|
|
105
|
-
}
|
|
106
|
-
interface CartClearParams {
|
|
107
|
-
cartId: string;
|
|
108
|
-
_provider?: "stripe" | "yns";
|
|
109
|
-
}
|
|
110
|
-
interface CartGetParams {
|
|
111
|
-
cartId: string;
|
|
112
|
-
_provider?: "stripe" | "yns";
|
|
113
|
-
}
|
|
114
|
-
interface CartUpdateParams {
|
|
115
|
-
cartId: string;
|
|
116
|
-
variantId: string;
|
|
117
|
-
quantity: number;
|
|
118
|
-
_provider?: "stripe" | "yns";
|
|
119
|
-
}
|
|
120
|
-
interface OrderGetParams {
|
|
121
|
-
orderId: string;
|
|
122
|
-
_provider?: "stripe" | "yns";
|
|
123
|
-
}
|
|
124
|
-
interface OrderListParams {
|
|
125
|
-
customerId?: string;
|
|
126
|
-
limit?: number;
|
|
127
|
-
offset?: number;
|
|
128
|
-
_provider?: "stripe" | "yns";
|
|
129
|
-
}
|
|
130
|
-
interface ProductBrowseResult {
|
|
131
|
-
data: Product[];
|
|
132
|
-
meta: {
|
|
133
|
-
count: number;
|
|
134
|
-
offset: number;
|
|
135
|
-
limit: number;
|
|
136
|
-
hasMore: boolean;
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
interface ProductSearchResult {
|
|
140
|
-
data: Product[];
|
|
141
|
-
total: number;
|
|
142
|
-
}
|
|
143
|
-
interface OrderListResult {
|
|
144
|
-
data: Order[];
|
|
145
|
-
meta: {
|
|
146
|
-
count: number;
|
|
147
|
-
offset: number;
|
|
148
|
-
limit: number;
|
|
149
|
-
hasMore: boolean;
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
interface YnsProduct extends Product {
|
|
153
|
-
category?: {
|
|
154
|
-
id: string;
|
|
155
|
-
name: string;
|
|
156
|
-
slug: string;
|
|
157
|
-
};
|
|
158
|
-
variants: Array<{
|
|
159
|
-
id: string;
|
|
160
|
-
price: number;
|
|
161
|
-
stock?: number;
|
|
162
|
-
attributes?: string;
|
|
163
|
-
}>;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
export type { BaseProvider as B, Cart as C, Order as O, Product as P, StripeProviderConfig as S, YnsProduct as Y, CartAddParams as a, CartClearParams as b, CartGetParams as c, CartItem as d, CartRemoveParams as e, CartUpdateParams as f, Customer as g, OrderGetParams as h, OrderListParams as i, OrderListResult as j, ProductBrowseParams as k, ProductBrowseResult as l, ProductGetParams as m, ProductInfo as n, ProductSearchParams as o, ProductSearchResult as p, YnsProviderConfig as q };
|
package/dist/stripe.d.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { S as StripeProviderConfig, k as ProductBrowseParams, l as ProductBrowseResult, m as ProductGetParams, P as Product, a as CartAddParams, C as Cart, f as CartUpdateParams, e as CartRemoveParams, b as CartClearParams, c as CartGetParams } from './provider-CeP9uHnB.js';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Stripe Commerce client - zero-config constructor
|
|
5
|
-
* Reads configuration from environment variables by default
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* ```typescript
|
|
9
|
-
* import { Commerce } from "commerce-kit/stripe";
|
|
10
|
-
*
|
|
11
|
-
* // Zero config - uses STRIPE_SECRET_KEY from environment
|
|
12
|
-
* const commerce = new Commerce();
|
|
13
|
-
*
|
|
14
|
-
* const products = await commerce.product.browse({ first: 10 });
|
|
15
|
-
* const result = await commerce.cart.add({ variantId: "price_123", quantity: 1 });
|
|
16
|
-
* ```
|
|
17
|
-
*/
|
|
18
|
-
declare class Commerce {
|
|
19
|
-
private config;
|
|
20
|
-
private provider?;
|
|
21
|
-
private providerPromise?;
|
|
22
|
-
constructor(config?: StripeProviderConfig);
|
|
23
|
-
/**
|
|
24
|
-
* Detect Stripe configuration from environment variables
|
|
25
|
-
*/
|
|
26
|
-
private detectFromEnv;
|
|
27
|
-
/**
|
|
28
|
-
* Lazy-load and cache provider instance
|
|
29
|
-
*/
|
|
30
|
-
private getProvider;
|
|
31
|
-
/**
|
|
32
|
-
* Load Stripe provider
|
|
33
|
-
*/
|
|
34
|
-
private loadProvider;
|
|
35
|
-
/**
|
|
36
|
-
* Product operations - Stripe specific
|
|
37
|
-
*/
|
|
38
|
-
get product(): {
|
|
39
|
-
/**
|
|
40
|
-
* Browse/list products with Stripe-specific parameters
|
|
41
|
-
*/
|
|
42
|
-
browse: (params?: ProductBrowseParams) => Promise<ProductBrowseResult>;
|
|
43
|
-
/**
|
|
44
|
-
* Get single product by ID or slug
|
|
45
|
-
*/
|
|
46
|
-
get: (params: ProductGetParams) => Promise<Product | null>;
|
|
47
|
-
};
|
|
48
|
-
/**
|
|
49
|
-
* Cart operations - Stripe specific
|
|
50
|
-
*/
|
|
51
|
-
get cart(): {
|
|
52
|
-
/**
|
|
53
|
-
* Add item to cart (additive behavior)
|
|
54
|
-
*/
|
|
55
|
-
add: (params: CartAddParams) => Promise<Cart>;
|
|
56
|
-
/**
|
|
57
|
-
* Update item in cart (absolute behavior)
|
|
58
|
-
*/
|
|
59
|
-
update: (params: CartUpdateParams) => Promise<Cart>;
|
|
60
|
-
/**
|
|
61
|
-
* Remove item from cart
|
|
62
|
-
*/
|
|
63
|
-
remove: (params: CartRemoveParams) => Promise<Cart>;
|
|
64
|
-
/**
|
|
65
|
-
* Clear entire cart
|
|
66
|
-
*/
|
|
67
|
-
clear: (params: CartClearParams) => Promise<Cart>;
|
|
68
|
-
/**
|
|
69
|
-
* Get cart details
|
|
70
|
-
*/
|
|
71
|
-
get: (params: CartGetParams) => Promise<Cart | null>;
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export { Commerce };
|
package/dist/stripe.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var xt=Object.defineProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var wt=(e,t)=>{for(var r in t)xt(e,r,{get:t[r],enumerable:!0})};var Ct,vt,y,q=v(()=>{"use strict";Ct=process.env.STRIPE_SECRET_KEY,vt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:Ct,StripeCurrency:vt}});function _(e,t){if(!e)throw new Error(t)}var M,J,K=v(()=>{"use strict";M=e=>{if(e==null)return 0;if(typeof e=="number")return e;let t=Number.parseInt(e,10);return Number.isNaN(t)?0:t},J=e=>{if(e==null)return null;try{return JSON.parse(e)}catch{return null}}});var Pt,O,W=v(()=>{"use strict";Pt=e=>e.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=e=>Object.entries(e).map(([t,r])=>`${t}:"${Pt(r)}"`).join(" AND ").trim()});import{z as o}from"zod";function B(e){return e.toSorted((t,r)=>{let n=Number(t.metadata.order),i=Number(r.metadata.order);return Number.isNaN(n)&&Number.isNaN(i)||n===i?r.updated-t.updated:Number.isNaN(n)?1:Number.isNaN(i)?-1:n-i})}function $({default_price:e,marketing_features:t,...r}){return _(e,"Product must have a default price"),_(typeof e=="object","Product default price must be an object"),{...r,default_price:e,marketing_features:t.map(n=>n.name).filter(Boolean),metadata:St.parse(r.metadata)}}function _t(e){return!!(e.active&&!e.deleted&&e.default_price)}function N(e){return{...e,data:e.data.filter(_t)}}function G(e){return e.data.map($)}function F(e){return e.filter((t,r,n)=>r===n.findIndex(i=>i.metadata.slug===t.metadata.slug))}function Y(e){let t=e.payment_method;_(typeof t!="string","Payment method should not be a string");let r=e.customer;_(typeof r!="string"&&!r?.deleted,"Customer should not be a string");let n=U.parse(e.metadata),i=Object.entries(n).filter(([a])=>a.startsWith("taxBreakdown")).map(([a,s])=>{let d=It.safeParse(J(String(s)));return d.success?d.data:null}).filter(Boolean);return{...e,metadata:n,customer:r,payment_method:t,taxBreakdown:i}}var St,X,U,It,H=v(()=>{"use strict";K();W();St=o.object({category:o.string().optional(),order:o.coerce.number().optional(),slug:o.string(),variant:o.string().optional(),stock:o.coerce.number().optional().transform(e=>e===void 0?Number.POSITIVE_INFINITY:e),digitalAsset:o.string().optional(),preview:o.string().optional()});X=e=>!e.deleted&&e.active,U=o.object({shippingRateId:o.string().optional(),taxCalculationId:o.string().optional(),taxCalculationExp:o.string().optional(),taxId:o.string().optional(),couponCode:o.string().optional(),taxedAmount:o.string().optional(),"billingAddress.city":o.string().optional(),"billingAddress.country":o.string().optional(),"billingAddress.line1":o.string().optional(),"billingAddress.line2":o.string().optional(),"billingAddress.name":o.string().optional(),"billingAddress.postalCode":o.string().optional(),"billingAddress.state":o.string().optional(),netAmount:o.string().optional(),taxBreakdown0:o.string().optional(),taxBreakdown1:o.string().optional(),taxBreakdown2:o.string().optional(),taxBreakdown3:o.string().optional(),taxBreakdown4:o.string().optional(),taxBreakdown5:o.string().optional()}).and(o.record(o.string(),o.string())),It=o.object({taxType:o.string(),taxPercentage:o.string(),taxAmount:o.number()})});var S,Rt,Et,E,m,Z=v(()=>{"use strict";S={DEBUG:0,LOG:1,WARN:2,ERROR:3},Rt="LOG",Et=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in S?process.env.LOG_LEVEL:Rt,E=S[Et],m={time(e){E>S.DEBUG||console.time(e)},timeEnd(e){E>S.DEBUG||console.timeEnd(e)},log(...e){E>S.LOG||console.log(...e)},dir(e,t){E>S.LOG||console.dir(e,t)},warn(...e){E>S.WARN||console.warn(...e)},error(...e){E>S.ERROR||console.error(...e)}}});var w,P,tt=v(()=>{"use strict";w=e=>e.filter(Boolean),P={accountGetById:{tags:({accountId:e})=>w(["account",e&&`account-${e}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:e})=>w(["cart",`cart-${e}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:e})=>w(["tax-calculations",`tax-calculations-${e}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:e})=>w(["files",`file-${e}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:e})=>w(["order",`order-${e}`]),revalidate:()=>{}},productBrowse:{tags:({category:e})=>w(["product",e&&`category-${e}`]),revalidate:()=>{}},productGetById:{tags:({productId:e})=>w(["product",`product-${e}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:e})=>w(["product",`product-${e}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>w(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:e})=>w(["shipping",`shipping-${e}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>w(["tax-settings"]),revalidate:()=>{}}}});import et from"stripe";var bt,f,rt=v(()=>{"use strict";q();bt=(e,t)=>!e||!t?e:[...e,`prefix-${t}`,...e.map(r=>`${t}-${r}`)],f=({tags:e,revalidate:t,cache:r,tagPrefix:n,secretKey:i})=>{let a=i??y.StripeSecretKey;if(!a)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let s=bt(e,n);return new et(a,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:et.createFetchHttpClient(((p,c)=>fetch(p,{...c,cache:r??c?.cache,next:{tags:s??c?.next?.tags,revalidate:t??c?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var h,at=v(()=>{"use strict";h=async()=>{let e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??e}});import{revalidateTag as At}from"next/cache";import b from"stripe";import{z as ue}from"zod";function ot({productId:e,cartId:t}){return t?j({cartId:t,productId:e,operation:"INCREASE",clearTaxCalculation:!0}):Tt({productId:e})}async function j({productId:e,cartId:t,operation:r,clearTaxCalculation:n}){let[i,a]=await Promise.all([V(e),pt(t)]);if(!i)throw new Error(`Product not found: ${e}`);if(!a)throw new Error(`Cart not found: ${t}`);if(i.metadata.stock<=0)throw Error(`Product ${e} is out of stock`);if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(y.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let s=a.cart.metadata??{},c=M(s[e])+(r==="INCREASE"?1:-1);c<=0?s[e]="":s[e]=c.toString();let C=Nt(a)+(i.default_price.unit_amount??0);try{return await Mt({paymentIntentId:t,data:{metadata:s,amount:C||it},clearTaxCalculation:n})}catch(g){m.error(g)}finally{At(`cart-${t}`)}}async function st(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.cartGetById.tags({cartId:e}),cache:"force-cache"});try{let a=await i.paymentIntents.retrieve(e,{expand:["payment_method","customer"]},{stripeAccount:t});if(dt.includes(a.status)){let s=Y(a);if(!s)return null;let d=await z(s.metadata),{metadata:{shippingRateId:p}}=s,c=p&&await Q(p);return{cart:s,lines:d.map(({product:C,quantity:g})=>C?{product:C,quantity:g}:null).filter(Boolean),shippingRate:c||null}}}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function Tt({productId:e}={}){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let a=e?await V(e):null;if(a&&a.metadata.stock<=0)throw Error(`Product ${e} is out of stock`);return await i.paymentIntents.create({currency:y.StripeCurrency,amount:a?.default_price.unit_amount||it,automatic_payment_methods:{enabled:!0},metadata:{...a&&{[a.id]:"1"}}},{stripeAccount:t})}catch(a){throw m.error(a),a}}async function D(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.productGetById.tags({productId:e}),cache:"force-cache"});try{let a=await i.products.retrieve(e,{expand:["default_price"]},{stripeAccount:t});return $(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function ct({slug:e}){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),a=await f({secretKey:n,tagPrefix:r,tags:P.productGetBySlug.tags({productSlug:e}),cache:"force-cache"}).products.search({query:O({active:!0,'metadata["slug"]':e}),expand:["data.default_price"]},{stripeAccount:t});if(a.data.length>1&&a.data.some(s=>!s.metadata.variant))throw new Error(`Multiple products found with the same slug (${e}) but no variant set.`);return await Promise.allSettled(a.data.map(s=>D(s.id))),B(G(N(a)))}async function ut(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h();if(e.filter?.category){let s=e.filter?.category,p=await f({secretKey:n,tagPrefix:r,tags:P.productBrowse.tags({category:s}),cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':s}),expand:["data.default_price"]},{stripeAccount:t});return B(F(G(N(p)))).slice(e.offset||0,e.first)}let a=await f({secretKey:n,tagPrefix:r,tags:P.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:t});return B(F(G(N(a))).filter(X)).slice(e.offset||0,e.first)}async function Q(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.shippingGetById.tags({shippingId:e}),cache:"force-cache"});try{let a=await i.shippingRates.retrieve(e,{},{stripeAccount:t});return a}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}async function z(e){let t=Bt(e);return await Promise.all(t.map(async([n,i])=>({product:await V(n),quantity:i})))}function Lt({oldCart:e,data:t,mergedMetadata:r,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),a=r.taxCalculationExp?Number.parseInt(r.taxCalculationExp,10)*1e3:null;if(!a||i>=a)return!0;let s=e.cart.metadata.netAmount||e.cart.amount,d=t.amount,p=Gt.some(u=>!r[u]&&!e.cart.metadata[u]?!1:r[u]!==e.cart.metadata[u]),c=n.length!==e.lines.length||n.some(u=>{let x=e.lines.find(I=>I.product.id===u.product?.id);return u.product?.default_price.unit_amount!==x?.product.default_price.unit_amount||u.quantity!==x?.quantity});return d&&s!==d||p||c}async function lt(e){let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:["customers",`customers-${e}`],cache:"force-cache"});try{let a=await i.customers.retrieve(e,{},{stripeAccount:t});return a.deleted?null:a}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}}function qt(e,t){return t.coupon.amount_off?Math.max(e-t.coupon.amount_off,0):t.coupon.percent_off?Math.floor(e*(1-t.coupon.percent_off/100)):e}async function Kt(){let{stripeAccount:e,storeId:t,secretKey:r}=await h();return await f({secretKey:r,tagPrefix:t,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:e})}var it,V,dt,Bt,$t,pt,Nt,Gt,kt,nt,Mt,mt=v(()=>{"use strict";q();H();Z();tt();rt();W();K();at();it=1e3;V=async e=>{let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.productGetById.tags({productId:e}),cache:"force-cache"});try{let a=await i.products.retrieve(e,{expand:["default_price"]},{stripeAccount:t});return $(a)}catch(a){if(a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}},dt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Bt=e=>Object.entries(e??{}).filter(([t])=>t.startsWith("prod_")).map(([t,r])=>[t,M(r)]).filter(([,t])=>t&&Number.isFinite(t)&&t>0),$t=async e=>{let{stripeAccount:t,storeId:r,secretKey:n}=await h(),i=f({secretKey:n,tagPrefix:r,tags:P.cartGetById.tags({cartId:e}),cache:"force-cache"});try{let a=await i.paymentIntents.retrieve(e,{expand:["payment_method"]},{stripeAccount:t}),s=typeof a.customer=="string"?await lt(a.customer):null;if(dt.includes(a.status))return Y({...a,customer:s})}catch(a){if(m.error(a),a instanceof b.errors.StripeError&&a.code==="resource_missing")return null;throw a}};pt=async e=>{let t=await $t(e);if(!t)return null;let r=await z(t.metadata),{metadata:{shippingRateId:n}}=t,i=n&&await Q(n);return{cart:t,lines:r.map(({product:a,quantity:s})=>a?{product:a,quantity:s}:null).filter(Boolean),shippingRate:i||null}},Nt=e=>e?e.cart.metadata?.taxCalculationId?e.cart.amount:(e.shippingRate?.fixed_amount?.amount??0)+e.lines.reduce((t,{product:r,quantity:n})=>t+(r.default_price?.unit_amount??0)*n,0):0,Gt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];kt=async({lineItems:e,billingAddress:t,cartId:r,shippingRateId:n,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:a,storeId:s,secretKey:d}=await h(),p=f({secretKey:d,tagPrefix:s,tags:P.createTaxCalculation.tags({cartId:r}),cache:"force-cache"});if(!t?.country)return null;let c=n?await Q(n):null,C=typeof c?.tax_code=="string"?c.tax_code:c?.tax_code?.id,g=await Kt(),u=y.StripeCurrency==="usd"||y.StripeCurrency==="cad"?"exclusive":"inclusive",x=g.defaults.tax_behavior==="inferred_by_currency"?u:g.defaults.tax_behavior??u;g.defaults.tax_behavior||m.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${y.StripeCurrency}: ${u}.`),m.time(`createTaxCalculation ${r}`);let I=await p.tax.calculations.create({expand:["line_items"],line_items:e.map(A=>({...A,tax_behavior:A.tax_behavior??x})),currency:y.StripeCurrency,shipping_cost:c?.active&&c?.fixed_amount?{amount:c.fixed_amount.amount,tax_behavior:c.tax_behavior==="inclusive"?"inclusive":c.tax_behavior==="exclusive"?"exclusive":x,tax_code:C??g.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:i?[{type:"eu_vat",value:i}]:void 0,address_source:"billing",address:{country:t.country,city:t?.city,line1:t?.line1,line2:t?.line2,postal_code:t?.postalCode,state:t?.state}}},{stripeAccount:a});return m.timeEnd(`createTaxCalculation ${r}`),console.log(JSON.stringify(I).length),I},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};Mt=async({paymentIntentId:e,data:t,customerOverride:r,clearTaxCalculation:n})=>{let{stripeAccount:i,storeId:a,secretKey:s}=await h(),d=await pt(e);_(d,`Cart not found: ${e}`);let p=t.amount?t.amount.toString():null,c=U.parse({...d.cart.metadata,...t.metadata});m.time("getProductsFromMetadata");let C=await z(c);m.timeEnd("getProductsFromMetadata");let g=!n&&Lt({oldCart:d,data:t,mergedMetadata:c,lines:C});console.log({shouldRecalculateTax:g});let u=g?await kt({cartId:e,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:C.map(({product:l,quantity:T})=>{if(l?.default_price.unit_amount)return{product:l.id,reference:[l.metadata.slug,l.metadata.variant].filter(Boolean).join("-"),quantity:T,amount:l.default_price.unit_amount*T,tax_behavior:l.default_price.tax_behavior==="exclusive"?"exclusive":l.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:l.tax_code?typeof l.tax_code=="string"?l.tax_code:l.tax_code.id:void 0}}).filter(Boolean)}):null,x=r??(t.customer?await lt(t.customer):d.cart.customer);console.log({customer:x});let I=f({secretKey:s,tagPrefix:a,cache:"no-cache"});m.time(`paymentIntents.update ${e}`);let A=u&&Object.fromEntries(u.tax_breakdown.map(l=>({taxType:l.tax_rate_details.tax_type,taxPercentage:l.tax_rate_details.percentage_decimal,taxAmount:l.amount})).map((l,T)=>[`taxBreakdown${T}`,JSON.stringify(l)])),R=u?u.amount_total:t.amount,k=R&&x?.discount?.coupon.valid?qt(R,x.discount):R;console.log({"discount.coupon.amount_off":x?.discount?.coupon.amount_off,"discount.coupon.percent_off":x?.discount?.coupon.percent_off,discountedAmount:k,taxedAmount:R,"taxCalculation.amount_total":u?.amount_total,"data.amount":t.amount,netAmount:p});let ht=await I.paymentIntents.update(e,{...t,...k&&{amount:k},metadata:{...c,...p&&{netAmount:p},...R&&{taxedAmount:R},...u?{...nt,...A,taxCalculationId:u.id,taxCalculationExp:u?.expires_at}:{...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:i});return m.timeEnd(`paymentIntents.update ${e}`),ht}});var ft={};wt(ft,{StripeProvider:()=>L,createStripeProvider:()=>Wt});function Wt(e){return new L(e)}var L,gt=v(()=>{"use strict";mt();L=class{constructor(t){this.config=t}mapStripeProduct(t){let r=t.default_price?.unit_amount||0,n=t.default_price?.currency||"usd";return{id:t.id,name:t.name,slug:t.metadata?.slug,summary:t.description,images:t.images||[],active:t.active,price:r/100,currency:n.toUpperCase(),stock:Number.parseInt(t.metadata?.stock||"0",10),stripeId:t.id,metadata:t.metadata||{}}}async productBrowse(t){let r=await ut({first:t.first||10,...t}),n=r.data.map(i=>this.mapStripeProduct(i));return{data:n,meta:{count:r.totalCount||n.length,offset:t.offset||0,limit:t.first||10,hasMore:n.length===(t.first||10)}}}async productGet(t){if(t.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),t.slug){let r=await ct({slug:t.slug});return r?this.mapStripeProduct(r):null}if(t.id){let r=await D(t.id);return r?this.mapStripeProduct(r):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(t){let r=t.quantity;if(t.cartId)try{let s=await this.cartGet({cartId:t.cartId});if(s){let d=s.items.find(p=>p.variantId===t.variantId);d&&(r=d.quantity+t.quantity)}}catch{}let i=(await ot({productId:t.variantId,cartId:t.cartId}))?.id||t.cartId||"",a=await this.cartGet({cartId:i});if(!a)throw new Error("Failed to retrieve cart after adding item");return a}async cartUpdate(t){let r=await j({cartId:t.cartId,productId:t.variantId,operation:"SET",quantity:t.quantity}),n=await this.cartGet({cartId:r?.id||t.cartId});if(!n)throw new Error("Failed to retrieve cart after update");return n}async cartClear(t){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartRemove(t){return await this.cartUpdate({cartId:t.cartId,variantId:t.variantId,quantity:0})}async cartGet(t){let r=await st(t.cartId);return r?this.mapCart(r):null}mapCart(t){let r=this.mapCartItems(t.lines);return{id:t.cart.id,customerId:this.mapCustomerId(t.cart.customer),storeId:void 0,customer:void 0,items:r,total:this.calculateTotal(r),currency:t.cart.currency?.toUpperCase()||"USD",createdAt:new Date(t.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}mapCartItems(t){return t?.map(r=>this.mapCartItem(r))||[]}mapCartItem(t){return{id:t.product?.id||"",productId:t.product?.id||"",variantId:t.product?.id,quantity:t.quantity,price:t.product?.default_price?.unit_amount||0,stock:void 0,product:void 0}}mapCustomerId(t){if(typeof t=="string")return t;if(t?.id)return t.id}calculateTotal(t){return t.reduce((r,n)=>r+n.price*n.quantity,0)}}});var yt=class{config;provider;providerPromise;constructor(t){if(this.config=t||this.detectFromEnv(),!this.config.secretKey&&!process.env.STRIPE_SECRET_KEY)throw new Error("Stripe configuration required. Provide secretKey in constructor or set STRIPE_SECRET_KEY environment variable.")}detectFromEnv(){return{secretKey:process.env.STRIPE_SECRET_KEY,tagPrefix:process.env.STRIPE_TAG_PREFIX}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createStripeProvider:t}=await Promise.resolve().then(()=>(gt(),ft));return t(this.config)}catch(t){throw new Error(`Failed to initialize Stripe provider: ${t instanceof Error?t.message:"Unknown error"}`)}}get product(){return{browse:async(t={})=>(await this.getProvider()).productBrowse(t),get:async t=>(await this.getProvider()).productGet(t)}}get cart(){return{add:async t=>(await this.getProvider()).cartAdd(t),update:async t=>(await this.getProvider()).cartUpdate(t),remove:async t=>(await this.getProvider()).cartRemove(t),clear:async t=>(await this.getProvider()).cartClear(t),get:async t=>(await this.getProvider()).cartGet(t)}}};export{yt as Commerce};
|
package/dist/yns-context.d.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
type YnsFindStripeAccountResult = {
|
|
2
|
-
stripeAccount: string | undefined;
|
|
3
|
-
storeId: string | undefined;
|
|
4
|
-
secretKey: string | undefined;
|
|
5
|
-
publishableKey: string | undefined;
|
|
6
|
-
};
|
|
7
|
-
type YnsContextResult = {
|
|
8
|
-
stripeAccount: string | undefined;
|
|
9
|
-
storeId: string | undefined;
|
|
10
|
-
secretKey: string | undefined;
|
|
11
|
-
publishableKey: string | undefined;
|
|
12
|
-
};
|
|
13
|
-
declare global {
|
|
14
|
-
/**
|
|
15
|
-
* ⚠️ Warning: This might be `undefined` but TypeScript doesn't have a syntax to express that.
|
|
16
|
-
* @see https://github.com/microsoft/TypeScript/issues/36057
|
|
17
|
-
*/
|
|
18
|
-
function __ynsFindStripeAccount(): YnsFindStripeAccountResult | undefined | Promise<YnsFindStripeAccountResult | undefined>;
|
|
19
|
-
}
|
|
20
|
-
declare const getYnsContext: () => Promise<YnsContextResult>;
|
|
21
|
-
|
|
22
|
-
export { getYnsContext };
|
package/dist/yns-context.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var t=async()=>{let e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??e};export{t as getYnsContext};
|
package/dist/yns.d.ts
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
import { q as YnsProviderConfig, k as ProductBrowseParams, l as ProductBrowseResult, m as ProductGetParams, P as Product, o as ProductSearchParams, p as ProductSearchResult, a as CartAddParams, C as Cart, f as CartUpdateParams, e as CartRemoveParams, b as CartClearParams, c as CartGetParams, h as OrderGetParams, O as Order, i as OrderListParams, j as OrderListResult } from './provider-CeP9uHnB.js';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* YNS Commerce client - zero-config constructor with GraphQL support
|
|
5
|
-
* Reads configuration from environment variables by default
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* ```typescript
|
|
9
|
-
* import { Commerce } from "commerce-kit/yns";
|
|
10
|
-
*
|
|
11
|
-
* // Zero config - uses YNS_ENDPOINT and YNS_TOKEN from environment
|
|
12
|
-
* const commerce = new Commerce();
|
|
13
|
-
*
|
|
14
|
-
* // GraphQL field selection supported
|
|
15
|
-
* const products = await commerce.product.browse({
|
|
16
|
-
* first: 10,
|
|
17
|
-
* fields: ["id", "name", "price", "category.name"]
|
|
18
|
-
* });
|
|
19
|
-
*
|
|
20
|
-
* const orders = await commerce.order.list({ first: 5 });
|
|
21
|
-
* ```
|
|
22
|
-
*/
|
|
23
|
-
declare class Commerce {
|
|
24
|
-
private config;
|
|
25
|
-
private provider?;
|
|
26
|
-
private providerPromise?;
|
|
27
|
-
constructor(config?: YnsProviderConfig);
|
|
28
|
-
/**
|
|
29
|
-
* Detect YNS configuration from environment variables
|
|
30
|
-
*/
|
|
31
|
-
private detectFromEnv;
|
|
32
|
-
/**
|
|
33
|
-
* Lazy-load and cache provider instance
|
|
34
|
-
*/
|
|
35
|
-
private getProvider;
|
|
36
|
-
/**
|
|
37
|
-
* Load YNS provider
|
|
38
|
-
*/
|
|
39
|
-
private loadProvider;
|
|
40
|
-
/**
|
|
41
|
-
* Product operations - YNS specific with GraphQL support
|
|
42
|
-
*/
|
|
43
|
-
get product(): {
|
|
44
|
-
/**
|
|
45
|
-
* Browse/list products with GraphQL field selection
|
|
46
|
-
*/
|
|
47
|
-
browse: (params?: ProductBrowseParams) => Promise<ProductBrowseResult>;
|
|
48
|
-
/**
|
|
49
|
-
* Get single product by ID or slug with field selection
|
|
50
|
-
*/
|
|
51
|
-
get: (params: ProductGetParams) => Promise<Product | null>;
|
|
52
|
-
/**
|
|
53
|
-
* Search products with GraphQL support
|
|
54
|
-
*/
|
|
55
|
-
search: (params: ProductSearchParams) => Promise<ProductSearchResult>;
|
|
56
|
-
};
|
|
57
|
-
/**
|
|
58
|
-
* Cart operations - Simplified API
|
|
59
|
-
*/
|
|
60
|
-
get cart(): {
|
|
61
|
-
/**
|
|
62
|
-
* Add items to cart (additive behavior)
|
|
63
|
-
* If cartId is provided, adds to existing quantity
|
|
64
|
-
* If no cartId, creates new cart
|
|
65
|
-
*/
|
|
66
|
-
add: (params: CartAddParams) => Promise<Cart>;
|
|
67
|
-
/**
|
|
68
|
-
* Update item in cart (absolute behavior)
|
|
69
|
-
* Sets quantity to exact number
|
|
70
|
-
* Requires cartId
|
|
71
|
-
*/
|
|
72
|
-
update: (params: CartUpdateParams) => Promise<Cart>;
|
|
73
|
-
/**
|
|
74
|
-
* Remove specific item from cart
|
|
75
|
-
*/
|
|
76
|
-
remove: (params: CartRemoveParams) => Promise<Cart>;
|
|
77
|
-
/**
|
|
78
|
-
* Clear entire cart
|
|
79
|
-
*/
|
|
80
|
-
clear: (params: CartClearParams) => Promise<Cart>;
|
|
81
|
-
/**
|
|
82
|
-
* Get cart details
|
|
83
|
-
*/
|
|
84
|
-
get: (params: CartGetParams) => Promise<Cart | null>;
|
|
85
|
-
};
|
|
86
|
-
/**
|
|
87
|
-
* Order operations - YNS specific
|
|
88
|
-
*/
|
|
89
|
-
get order(): {
|
|
90
|
-
/**
|
|
91
|
-
* Get single order
|
|
92
|
-
*/
|
|
93
|
-
get: (params: OrderGetParams) => Promise<Order | null>;
|
|
94
|
-
/**
|
|
95
|
-
* List orders with GraphQL field selection
|
|
96
|
-
*/
|
|
97
|
-
list: (params?: OrderListParams) => Promise<OrderListResult>;
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export { Commerce };
|
package/dist/yns.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var v=Object.defineProperty;var m=(a,r)=>()=>(a&&(r=a(a=0)),r);var l=(a,r)=>{for(var t in r)v(a,t,{get:r[t],enumerable:!0})};var u={};l(u,{YnsProvider:()=>d,createYnsProvider:()=>h});function h(a){return new d(a)}var d,p=m(()=>{"use strict";d=class{config;constructor(r){this.config=r}async graphqlRequest(r,t){let e=await fetch(`${this.config.endpoint}/api/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({query:r,variables:t})});if(!e.ok)throw new Error(`YNS GraphQL request failed: ${e.status} ${e.statusText}`);let i=await e.json();if(i.errors)throw new Error(`YNS GraphQL errors: ${JSON.stringify(i.errors)}`);return i.data}async restRequest(r,t="GET",e){let i=await fetch(`${this.config.endpoint}/api${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:e?JSON.stringify(e):void 0});if(!i.ok){let n=i.headers.get("content-type"),s=`YNS REST request failed: ${i.status} ${i.statusText}`;if(n?.includes("application/json"))try{let c=await i.json();s=c.error||c.message||s}catch{}throw new Error(s)}let o=i.headers.get("content-type");if(!o?.includes("application/json"))throw new Error(`YNS API returned ${o} instead of JSON for ${r}`);return i.json()}mapYnsProduct(r){return{id:r.id,name:r.name,slug:r.slug,summary:r.summary,images:r.images||[],active:r.active,price:r.variants?.[0]?.price?Number.parseFloat(r.variants[0].price):0,currency:"USD",stock:r.variants?.[0]?.stock,category:r.category,variants:r.variants?.map(t=>({id:t.id,price:Number.parseFloat(t.price),stock:t.stock,attributes:t.attributes}))||[]}}mapCart(r){let t=this.mapCartItems(r.lineItems);return{id:r.id,customerId:r.customerId,storeId:r.storeId,customer:this.mapCustomer(r.customer),items:t,total:this.calculateTotal(t),currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}mapCartItems(r){return r?.map(t=>this.mapCartItem(t))||[]}mapCartItem(r){let t=r.productVariant;return{id:r.id,productId:t?.product?.id||t?.id||"",variantId:t?.id,quantity:r.quantity,price:Number.parseFloat(t?.price||"0"),stock:t?.stock,product:this.mapProduct(t?.product)}}mapCustomer(r){if(r)return{id:r.id,email:r.email}}mapProduct(r){if(r)return{id:r.id,name:r.name,images:r.images||[]}}calculateTotal(r){return r.reduce((t,e)=>t+e.price*e.quantity,0)}async productBrowse(r){if(r.graphql){let t={offset:r.offset||0,limit:r.first||10,category:r.category,query:r.query,active:r.active,orderBy:r.orderBy,orderDirection:r.orderDirection},e=await this.graphqlRequest(r.graphql,t);return{data:e.products.data.map(i=>this.mapYnsProduct(i)),meta:e.products.meta}}else{let t=new URLSearchParams;r.first&&t.append("limit",r.first.toString()),r.offset&&t.append("offset",r.offset.toString()),r.category&&t.append("category",r.category),r.query&&t.append("q",r.query),r.active!==void 0&&t.append("active",r.active.toString()),r.orderBy&&t.append("orderBy",r.orderBy),r.orderDirection&&t.append("orderDirection",r.orderDirection);let e=`/products${t.toString()?`?${t.toString()}`:""}`,i=await this.restRequest(e);return{data:i.data.map(o=>this.mapYnsProduct(o)),meta:i.meta}}}async productGet(r){if(!r.slug&&!r.id)throw new Error("Either slug or id is required for productGet");if(r.graphql){let t={slug:r.slug,id:r.id},e=await this.graphqlRequest(r.graphql,t);return e.product?this.mapYnsProduct(e.product):null}else{let t=`/products/${r.id||r.slug}`,e=await this.restRequest(t);return e?this.mapYnsProduct(e):null}}async cartAdd(r){let t=r.quantity;if(r.cartId)try{let o=await this.cartGet({cartId:r.cartId});if(o){let n=o.items.find(s=>s.variantId===r.variantId);n&&(t=n.quantity+r.quantity)}}catch{}let e={variantId:r.variantId,cartId:r.cartId,quantity:t,subscriptionId:r.subscriptionId},i=await this.restRequest("/cart","POST",e);return this.mapCart(i)}async cartUpdate(r){let t={variantId:r.variantId,cartId:r.cartId,quantity:r.quantity},e=await this.restRequest("/cart","POST",t);return this.mapCart(e)}async cartRemove(r){let t=`/cart/${r.cartId}/items/${r.variantId}`,e=await this.restRequest(t,"DELETE");return this.mapCart(e)}async cartClear(r){let t=await this.restRequest(`/cart/${r.cartId}`,"DELETE");return this.mapCart(t)}async cartGet(r){let t=await this.restRequest(`/cart/${r.cartId}`);return t?this.mapCart(t):null}}});var P=class{config;provider;providerPromise;constructor(r){if(this.config=r||this.detectFromEnv(),!this.config.endpoint||!this.config.token)throw new Error("YNS configuration required. Provide endpoint and token in constructor or set YNS_ENDPOINT and YNS_TOKEN environment variables.")}detectFromEnv(){return{endpoint:process.env.YNS_ENDPOINT||"",token:process.env.YNS_TOKEN||""}}async getProvider(){return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.loadProvider()),this.provider=await this.providerPromise,this.provider)}async loadProvider(){try{let{createYnsProvider:r}=await Promise.resolve().then(()=>(p(),u));return r(this.config)}catch(r){throw new Error(`Failed to initialize YNS provider: ${r instanceof Error?r.message:"Unknown error"}`)}}get product(){return{browse:async(r={})=>(await this.getProvider()).productBrowse(r),get:async r=>(await this.getProvider()).productGet(r),search:async r=>{let t=await this.getProvider();if(!t.productSearch)throw new Error("Product search is not supported by YNS provider");return t.productSearch(r)}}}get cart(){return{add:async r=>(await this.getProvider()).cartAdd(r),update:async r=>(await this.getProvider()).cartUpdate(r),remove:async r=>(await this.getProvider()).cartRemove(r),clear:async r=>(await this.getProvider()).cartClear(r),get:async r=>(await this.getProvider()).cartGet(r)}}get order(){return{get:async r=>{let t=await this.getProvider();if(!t.orderGet)throw new Error("Order retrieval is not supported by YNS provider");return t.orderGet(r)},list:async(r={})=>{let t=await this.getProvider();if(!t.orderList)throw new Error("Order listing is not supported by YNS provider");return t.orderList(r)}}}};export{P as Commerce};
|