commerce-kit 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { formatMoney } from './currencies.js';
2
2
  export { MappedCart, MappedProduct, MappedShippingRate } from './internal.js';
3
- export { B as BaseProvider, C as Cart, a as CartAddParams, b as CartClearParams, c as CartGetParams, d as CartItem, e as CartUpdateParams, O as Order, f as OrderGetParams, g as OrderListParams, h as OrderListResult, P as Product, i as ProductBrowseParams, j as ProductBrowseResult, k as ProductGetParams, l as ProductSearchParams, m as ProductSearchResult, S as StripeProviderConfig, Y as YnsProviderConfig } from './provider-Co3VegT-.js';
3
+ export { B as BaseProvider, C as Cart, a as CartAddParams, b as CartClearParams, c as CartGetParams, d as CartItem, e as CartRemoveParams, f as CartUpdateParams, g as Customer, O as Order, h as OrderGetParams, i as OrderListParams, j as OrderListResult, P as Product, k as ProductBrowseParams, l as ProductBrowseResult, m as ProductGetParams, n as ProductInfo, o as ProductSearchParams, p as ProductSearchResult, S as StripeProviderConfig, Y as YnsProduct, q as YnsProviderConfig } from './provider-CeP9uHnB.js';
4
4
  export { Commerce } from './yns.js';
5
5
  import 'stripe';
6
6
  import 'zod';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var l=Object.defineProperty;var P=(o,r)=>()=>(o&&(r=o(o=0)),r);var m=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})};var u={};m(u,{YnsProvider:()=>a,createYnsProvider:()=>y});function y(o){return new a(o)}var a,p=P(()=>{"use strict";a=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)throw new Error(`YNS REST request failed: ${i.status} ${i.statusText}`);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}))||[]}}mapYnsCart(r){let t=r.lineItems?.map(i=>({id:i.id,productId:i.productVariant?.id||"",variantId:i.productVariantId,quantity:i.quantity,price:Number.parseFloat(i.productVariant?.price||"0")}))||[],e=t.reduce((i,s)=>i+s.price*s.quantity,0);return{id:r.id,customerId:r.customerId,items:t,total:e,currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}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(s=>this.mapYnsProduct(s)),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=r.id?`/products/${r.id}`:`/products/slug/${r.slug}`,e=await this.restRequest(t);return e?this.mapYnsProduct(e):null}}async cartAdd(r){let t={variantId:r.variantId,cartId:r.cartId,subscriptionId:r.subscriptionId};return await this.restRequest("/cart","POST",t)}async cartUpdate(r){let t={variantId:r.variantId,quantity:r.quantity};return await this.restRequest(`/cart/${r.cartId}`,"PUT",t)}async cartClear(r){return await this.restRequest(`/cart/${r.cartId}`,"DELETE")}async cartGet(r){let t=await this.restRequest(`/cart/${r.cartId}`);return t?this.mapYnsCart(t):null}}});function n(o,r){if(!o)throw new Error(r)}var c=o=>{n(Number.isInteger(o),"Value must be an integer")};var g=o=>(n(o.length===3,"currency needs to be a 3-letter code"),h[o.toUpperCase()]??2);var v=({amount:o,currency:r})=>{c(o);let t=g(r),e=10**t;return Number.parseFloat((o/e).toFixed(t))},f=({amount:o,currency:r,locale:t="en-US"})=>{let e=v({amount:o,currency:r});return new Intl.NumberFormat(t,{style:"currency",currency:r}).format(e)},h={BIF:0,CLP:0,DJF:0,GNF:0,JPY:0,KMF:0,KRW:0,MGA:0,PYG:0,RWF:0,UGX:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};var d=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),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{d as Commerce,f as formatMoney};
1
+ var v=Object.defineProperty;var f=(o,r)=>()=>(o&&(r=o(o=0)),r);var g=(o,r)=>{for(var t in r)v(o,t,{get:r[t],enumerable:!0})};var P={};g(P,{YnsProvider:()=>d,createYnsProvider:()=>I});function I(o){return new d(o)}var d,l=f(()=>{"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 s=i.headers.get("content-type"),n=`YNS REST request failed: ${i.status} ${i.statusText}`;if(s?.includes("application/json"))try{let p=await i.json();n=p.error||p.message||n}catch{}throw new Error(n)}let a=i.headers.get("content-type");if(!a?.includes("application/json"))throw new Error(`YNS API returned ${a} 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:this.parsePrice(t?.price),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||[]}}parsePrice(r){return Number.parseFloat(r||"0")/100}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(a=>this.mapYnsProduct(a)),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 a=await this.cartGet({cartId:r.cartId});if(a){let s=a.items.find(n=>n.variantId===r.variantId);s&&(t=s.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}}});function c(o,r){if(!o)throw new Error(r)}var m=o=>{c(Number.isInteger(o),"Value must be an integer")};var h=o=>(c(o.length===3,"currency needs to be a 3-letter code"),w[o.toUpperCase()]??2);var y=({amount:o,currency:r})=>{m(o);let t=h(r),e=10**t;return Number.parseFloat((o/e).toFixed(t))},C=({amount:o,currency:r,locale:t="en-US"})=>{let e=y({amount:o,currency:r});return new Intl.NumberFormat(t,{style:"currency",currency:r}).format(e)},w={BIF:0,CLP:0,DJF:0,GNF:0,JPY:0,KMF:0,KRW:0,MGA:0,PYG:0,RWF:0,UGX:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};var u=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(()=>(l(),P));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{u as Commerce,C as formatMoney};
@@ -10,7 +10,7 @@ type MappedProduct = ReturnType<typeof mapProduct>;
10
10
  */
11
11
  declare function sortProducts(products: MappedProduct[]): {
12
12
  default_price: Stripe.Price;
13
- marketing_features: string[];
13
+ marketing_features: (string | undefined)[];
14
14
  metadata: {
15
15
  slug: string;
16
16
  stock: number;
@@ -53,7 +53,7 @@ type ProductMetadata = z.infer<typeof ProductMetadataSchema>;
53
53
  */
54
54
  declare function mapProduct({ default_price, marketing_features, ...product }: Stripe.Product): {
55
55
  default_price: Stripe.Price;
56
- marketing_features: string[];
56
+ marketing_features: (string | undefined)[];
57
57
  metadata: {
58
58
  slug: string;
59
59
  stock: number;
@@ -126,7 +126,7 @@ declare function filterValidProducts(products: Stripe.Response<Stripe.ApiSearchR
126
126
  */
127
127
  declare function mapProducts(products: Stripe.Response<Stripe.ApiSearchResult<Stripe.Product> | Stripe.ApiList<Stripe.Product>>): {
128
128
  default_price: Stripe.Price;
129
- marketing_features: string[];
129
+ marketing_features: (string | undefined)[];
130
130
  metadata: {
131
131
  slug: string;
132
132
  stock: number;
@@ -168,7 +168,7 @@ declare function mapShippingRates(shippingRates: Stripe.ApiList<Stripe.ShippingR
168
168
  */
169
169
  declare function getUniqueVariants(products: MappedProduct[]): {
170
170
  default_price: Stripe.Price;
171
- marketing_features: string[];
171
+ marketing_features: (string | undefined)[];
172
172
  metadata: {
173
173
  slug: string;
174
174
  stock: number;
@@ -262,11 +262,11 @@ declare function mapCart(cart: Stripe.PaymentIntent): {
262
262
  } & Record<string, string>;
263
263
  customer: Stripe.Customer | null;
264
264
  payment_method: Stripe.PaymentMethod | null;
265
- taxBreakdown: {
265
+ taxBreakdown: ({
266
266
  taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
267
267
  taxPercentage: string;
268
268
  taxAmount: number;
269
- }[];
269
+ } | null)[];
270
270
  id: string;
271
271
  object: "payment_intent";
272
272
  amount: number;
@@ -313,11 +313,11 @@ type MappedCart = ReturnType<typeof mapCart>;
313
313
  declare function mapOrder({ payment_method, latest_charge, ...order }: Stripe.PaymentIntent): {
314
314
  payment_method: Stripe.PaymentMethod | null;
315
315
  latest_charge: Stripe.Charge | null;
316
- taxBreakdown: {
316
+ taxBreakdown: ({
317
317
  taxType: Stripe.Tax.Calculation.TaxBreakdown.TaxRateDetails.TaxType | (string & {});
318
318
  taxPercentage: string;
319
319
  taxAmount: number;
320
- }[];
320
+ } | null)[];
321
321
  metadata: {
322
322
  shippingRateId?: string | undefined;
323
323
  taxCalculationId?: string | undefined;
@@ -2,15 +2,10 @@ interface BaseProvider {
2
2
  productBrowse(params: ProductBrowseParams): Promise<ProductBrowseResult>;
3
3
  productGet(params: ProductGetParams): Promise<Product | null>;
4
4
  productSearch?(params: ProductSearchParams): Promise<ProductSearchResult>;
5
- cartAdd(params: CartAddParams): Promise<{
6
- cartId: string;
7
- }>;
8
- cartUpdate(params: CartUpdateParams): Promise<{
9
- cartId: string;
10
- }>;
11
- cartClear(params: CartClearParams): Promise<{
12
- cartId: string;
13
- }>;
5
+ cartAdd(params: CartAddParams): Promise<Cart>;
6
+ cartUpdate(params: CartUpdateParams): Promise<Cart>;
7
+ cartRemove(params: CartRemoveParams): Promise<Cart>;
8
+ cartClear(params: CartClearParams): Promise<Cart>;
14
9
  cartGet(params: CartGetParams): Promise<Cart | null>;
15
10
  orderGet?(params: OrderGetParams): Promise<Order | null>;
16
11
  orderList?(params: OrderListParams): Promise<OrderListResult>;
@@ -34,14 +29,25 @@ interface Product {
34
29
  currency: string;
35
30
  stock?: number;
36
31
  }
32
+ interface Customer {
33
+ id: string;
34
+ email?: string;
35
+ }
36
+ interface ProductInfo {
37
+ id: string;
38
+ name?: string;
39
+ images?: string[];
40
+ }
37
41
  interface Cart {
38
42
  id: string;
39
43
  customerId?: string;
44
+ storeId?: string;
45
+ customer?: Customer;
40
46
  items: CartItem[];
41
47
  total: number;
42
48
  currency: string;
43
- createdAt: string;
44
- updatedAt: string;
49
+ createdAt?: string;
50
+ updatedAt?: string;
45
51
  }
46
52
  interface CartItem {
47
53
  id: string;
@@ -49,6 +55,8 @@ interface CartItem {
49
55
  variantId?: string;
50
56
  quantity: number;
51
57
  price: number;
58
+ stock?: number;
59
+ product?: ProductInfo;
52
60
  }
53
61
  interface Order {
54
62
  id: string;
@@ -85,15 +93,14 @@ interface ProductSearchParams {
85
93
  }
86
94
  interface CartAddParams {
87
95
  variantId: string;
96
+ quantity: number;
88
97
  cartId?: string;
89
- quantity?: number;
90
98
  subscriptionId?: string;
91
99
  _provider?: "stripe" | "yns";
92
100
  }
93
- interface CartUpdateParams {
101
+ interface CartRemoveParams {
94
102
  cartId: string;
95
103
  variantId: string;
96
- quantity: number;
97
104
  _provider?: "stripe" | "yns";
98
105
  }
99
106
  interface CartClearParams {
@@ -104,6 +111,12 @@ interface CartGetParams {
104
111
  cartId: string;
105
112
  _provider?: "stripe" | "yns";
106
113
  }
114
+ interface CartUpdateParams {
115
+ cartId: string;
116
+ variantId: string;
117
+ quantity: number;
118
+ _provider?: "stripe" | "yns";
119
+ }
107
120
  interface OrderGetParams {
108
121
  orderId: string;
109
122
  _provider?: "stripe" | "yns";
@@ -136,5 +149,18 @@ interface OrderListResult {
136
149
  hasMore: boolean;
137
150
  };
138
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
+ }
139
165
 
140
- export type { BaseProvider as B, Cart as C, Order as O, Product as P, StripeProviderConfig as S, YnsProviderConfig as Y, CartAddParams as a, CartClearParams as b, CartGetParams as c, CartItem as d, CartUpdateParams as e, OrderGetParams as f, OrderListParams as g, OrderListResult as h, ProductBrowseParams as i, ProductBrowseResult as j, ProductGetParams as k, ProductSearchParams as l, ProductSearchResult as m };
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 CHANGED
@@ -1,4 +1,4 @@
1
- import { S as StripeProviderConfig, i as ProductBrowseParams, j as ProductBrowseResult, k as ProductGetParams, P as Product, a as CartAddParams, e as CartUpdateParams, b as CartClearParams, c as CartGetParams, C as Cart } from './provider-Co3VegT-.js';
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
2
 
3
3
  /**
4
4
  * Stripe Commerce client - zero-config constructor
@@ -50,23 +50,21 @@ declare class Commerce {
50
50
  */
51
51
  get cart(): {
52
52
  /**
53
- * Add item to cart
53
+ * Add item to cart (additive behavior)
54
54
  */
55
- add: (params: CartAddParams) => Promise<{
56
- cartId: string;
57
- }>;
55
+ add: (params: CartAddParams) => Promise<Cart>;
58
56
  /**
59
- * Update item in cart
57
+ * Update item in cart (absolute behavior)
60
58
  */
61
- update: (params: CartUpdateParams) => Promise<{
62
- cartId: string;
63
- }>;
59
+ update: (params: CartUpdateParams) => Promise<Cart>;
64
60
  /**
65
- * Clear cart
61
+ * Remove item from cart
66
62
  */
67
- clear: (params: CartClearParams) => Promise<{
68
- cartId: string;
69
- }>;
63
+ remove: (params: CartRemoveParams) => Promise<Cart>;
64
+ /**
65
+ * Clear entire cart
66
+ */
67
+ clear: (params: CartClearParams) => Promise<Cart>;
70
68
  /**
71
69
  * Get cart details
72
70
  */
package/dist/stripe.js CHANGED
@@ -1 +1 @@
1
- var xt=Object.defineProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var wt=(t,e)=>{for(var a in e)xt(t,a,{get:e[a],enumerable:!0})};var Ct,Pt,y,M=P(()=>{"use strict";Ct=process.env.STRIPE_SECRET_KEY,Pt=process.env.STRIPE_CURRENCY,y={StripeSecretKey:Ct,StripeCurrency:Pt}});function _(t,e){if(!t)throw new Error(e)}var q,J,K=P(()=>{"use strict";q=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},J=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}}});var vt,O,W=P(()=>{"use strict";vt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),O=t=>Object.entries(t).map(([e,a])=>`${e}:"${vt(a)}"`).join(" AND ").trim()});import{z as i}from"zod";function B(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})}function $({default_price:t,marketing_features:e,...a}){return _(t,"Product must have a default price"),_(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:St.parse(a.metadata)}}function _t(t){return!!(t.active&&!t.deleted&&t.default_price)}function N(t){return{...t,data:t.data.filter(_t)}}function L(t){return t.data.map($)}function U(t){return t.filter((e,a,n)=>a===n.findIndex(o=>o.metadata.slug===e.metadata.slug))}function Y(t){let e=t.payment_method;_(typeof e!="string","Payment method should not be a string");let a=t.customer;_(typeof a!="string"&&!a?.deleted,"Customer should not be a string");let n=F.parse(t.metadata),o=Object.entries(n).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,s])=>{let d=It.safeParse(J(String(s)));return d.success?d.data:null}).filter(Boolean);return{...t,metadata:n,customer:a,payment_method:e,taxBreakdown:o}}var St,X,F,It,H=P(()=>{"use strict";K();W();St=i.object({category:i.string().optional(),order:i.coerce.number().optional(),slug:i.string(),variant:i.string().optional(),stock:i.coerce.number().optional().transform(t=>t===void 0?Number.POSITIVE_INFINITY:t),digitalAsset:i.string().optional(),preview:i.string().optional()});X=t=>!t.deleted&&t.active,F=i.object({shippingRateId:i.string().optional(),taxCalculationId:i.string().optional(),taxCalculationExp:i.string().optional(),taxId:i.string().optional(),couponCode:i.string().optional(),taxedAmount:i.string().optional(),"billingAddress.city":i.string().optional(),"billingAddress.country":i.string().optional(),"billingAddress.line1":i.string().optional(),"billingAddress.line2":i.string().optional(),"billingAddress.name":i.string().optional(),"billingAddress.postalCode":i.string().optional(),"billingAddress.state":i.string().optional(),netAmount:i.string().optional(),taxBreakdown0:i.string().optional(),taxBreakdown1:i.string().optional(),taxBreakdown2:i.string().optional(),taxBreakdown3:i.string().optional(),taxBreakdown4:i.string().optional(),taxBreakdown5:i.string().optional()}).and(i.record(i.string(),i.string())),It=i.object({taxType:i.string(),taxPercentage:i.string(),taxAmount:i.number()})});var S,Et,Rt,R,m,Z=P(()=>{"use strict";S={DEBUG:0,LOG:1,WARN:2,ERROR:3},Et="LOG",Rt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in S?process.env.LOG_LEVEL:Et,R=S[Rt],m={time(t){R>S.DEBUG||console.time(t)},timeEnd(t){R>S.DEBUG||console.timeEnd(t)},log(...t){R>S.LOG||console.log(...t)},dir(t,e){R>S.LOG||console.dir(t,e)},warn(...t){R>S.WARN||console.warn(...t)},error(...t){R>S.ERROR||console.error(...t)}}});var w,v,tt=P(()=>{"use strict";w=t=>t.filter(Boolean),v={accountGetById:{tags:({accountId:t})=>w(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>w(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>w(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>w(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>w(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>w(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>w(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>w(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>w(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>w(["tax-settings"]),revalidate:()=>{}}}});import et from"stripe";var bt,f,rt=P(()=>{"use strict";M();bt=(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??y.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let s=bt(t,n);return new et(r,{typescript:!0,apiVersion:"2025-08-27.basil",httpClient:et.createFetchHttpClient(((l,c)=>fetch(l,{...c,cache:a??c?.cache,next:{tags:s??c?.next?.tags,revalidate:e??c?.next?.revalidate}}))),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})}});var h,at=P(()=>{"use strict";h=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t}});import{revalidateTag as At}from"next/cache";import b from"stripe";import{z as ue}from"zod";function it({productId:t,cartId:e}){return e?j({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):Tt({productId:t})}async function j({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[o,r]=await Promise.all([Q(t),pt(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(o.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(y.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${y.StripeCurrency}`);let s=r.cart.metadata??{},c=q(s[t])+(a==="INCREASE"?1:-1);c<=0?s[t]="":s[t]=c.toString();let C=Nt(r)+(o.default_price.unit_amount??0);try{return await qt({paymentIntentId:e,data:{metadata:s,amount:C||ot},clearTaxCalculation:n})}catch(g){m.error(g)}finally{At(`cart-${e}`)}}async function st(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(dt.includes(r.status)){let s=Y(r);if(!s)return null;let d=await z(s.metadata),{metadata:{shippingRateId:l}}=s,c=l&&await V(l);return{cart:s,lines:d.map(({product:C,quantity:g})=>C?{product:C,quantity:g}:null).filter(Boolean),shippingRate:c||null}}}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function Tt({productId:t}={}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,cache:"no-cache"});if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await Q(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await o.paymentIntents.create({currency:y.StripeCurrency,amount:r?.default_price.unit_amount||ot,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw m.error(r),r}}async function D(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ct({slug:t}){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),r=await f({secretKey:n,tagPrefix:a,tags:v.productGetBySlug.tags({productSlug: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(s=>!s.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.allSettled(r.data.map(s=>D(s.id))),B(L(N(r)))}async function ut(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h();if(t.filter?.category){let s=t.filter?.category,l=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({category:s}),cache:"force-cache"}).products.search({limit:100,query:O({active:!0,'metadata["category"]':s}),expand:["data.default_price"]},{stripeAccount:e});return B(U(L(N(l)))).slice(t.offset||0,t.first)}let r=await f({secretKey:n,tagPrefix:a,tags:v.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return B(U(L(N(r))).filter(X)).slice(t.offset||0,t.first)}async function V(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function z(t){let e=Bt(t);return await Promise.all(e.map(async([n,o])=>({product:await Q(n),quantity:o})))}function Gt({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,10)*1e3:null;if(!r||o>=r)return!0;let s=t.cart.metadata.netAmount||t.cart.amount,d=e.amount,l=Lt.some(u=>!a[u]&&!t.cart.metadata[u]?!1:a[u]!==t.cart.metadata[u]),c=n.length!==t.lines.length||n.some(u=>{let x=t.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||l||c}async function lt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:["customers",`customers-${t}`],cache:"force-cache"});try{let r=await o.customers.retrieve(t,{},{stripeAccount:e});return r.deleted?null:r}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}}function Mt(t,e){return e.coupon.amount_off?Math.max(t-e.coupon.amount_off,0):e.coupon.percent_off?Math.floor(t*(1-e.coupon.percent_off/100)):t}async function Kt(){let{stripeAccount:t,storeId:e,secretKey:a}=await h();return await f({secretKey:a,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}var ot,Q,dt,Bt,$t,pt,Nt,Lt,kt,nt,qt,mt=P(()=>{"use strict";M();H();Z();tt();rt();W();K();at();ot=1e3;Q=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return $(r)}catch(r){if(r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}},dt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],Bt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,q(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),$t=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await h(),o=f({secretKey:n,tagPrefix:a,tags:v.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e}),s=typeof r.customer=="string"?await lt(r.customer):null;if(dt.includes(r.status))return Y({...r,customer:s})}catch(r){if(m.error(r),r instanceof b.errors.StripeError&&r.code==="resource_missing")return null;throw r}};pt=async t=>{let e=await $t(t);if(!e)return null;let a=await z(e.metadata),{metadata:{shippingRateId:n}}=e,o=n&&await V(n);return{cart:e,lines:a.map(({product:r,quantity:s})=>r?{product:r,quantity:s}:null).filter(Boolean),shippingRate:o||null}},Nt=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,Lt=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId","couponCode"];kt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!y.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:s,secretKey:d}=await h(),l=f({secretKey:d,tagPrefix:s,tags:v.createTaxCalculation.tags({cartId:a}),cache:"force-cache"});if(!e?.country)return null;let c=n?await V(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 ${a}`);let I=await l.tax.calculations.create({expand:["line_items"],line_items:t.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: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 m.timeEnd(`createTaxCalculation ${a}`),console.log(JSON.stringify(I).length),I},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""};qt=async({paymentIntentId:t,data:e,customerOverride:a,clearTaxCalculation:n})=>{let{stripeAccount:o,storeId:r,secretKey:s}=await h(),d=await pt(t);_(d,`Cart not found: ${t}`);let l=e.amount?e.amount.toString():null,c=F.parse({...d.cart.metadata,...e.metadata});m.time("getProductsFromMetadata");let C=await z(c);m.timeEnd("getProductsFromMetadata");let g=!n&&Gt({oldCart:d,data:e,mergedMetadata:c,lines:C});console.log({shouldRecalculateTax:g});let u=g?await kt({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:C.map(({product:p,quantity:T})=>{if(p?.default_price.unit_amount)return{product:p.id,reference:[p.metadata.slug,p.metadata.variant].filter(Boolean).join("-"),quantity:T,amount:p.default_price.unit_amount*T,tax_behavior:p.default_price.tax_behavior==="exclusive"?"exclusive":p.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:p.tax_code?typeof p.tax_code=="string"?p.tax_code:p.tax_code.id:void 0}}).filter(Boolean)}):null,x=a??(e.customer?await lt(e.customer):d.cart.customer);console.log({customer:x});let I=f({secretKey:s,tagPrefix:r,cache:"no-cache"});m.time(`paymentIntents.update ${t}`);let A=u&&Object.fromEntries(u.tax_breakdown.map(p=>({taxType:p.tax_rate_details.tax_type,taxPercentage:p.tax_rate_details.percentage_decimal,taxAmount:p.amount})).map((p,T)=>[`taxBreakdown${T}`,JSON.stringify(p)])),E=u?u.amount_total:e.amount,k=E&&x?.discount?.coupon.valid?Mt(E,x.discount):E;console.log({"discount.coupon.amount_off":x?.discount?.coupon.amount_off,"discount.coupon.percent_off":x?.discount?.coupon.percent_off,discountedAmount:k,taxedAmount:E,"taxCalculation.amount_total":u?.amount_total,"data.amount":e.amount,netAmount:l});let ht=await I.paymentIntents.update(t,{...e,...k&&{amount:k},metadata:{...c,...l&&{netAmount:l},...E&&{taxedAmount:E},...u?{...nt,...A,taxCalculationId:u.id,taxCalculationExp:u?.expires_at}:{...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}}},{stripeAccount:o});return m.timeEnd(`paymentIntents.update ${t}`),ht}});var ft={};wt(ft,{StripeProvider:()=>G,createStripeProvider:()=>Wt});function Wt(t){return new G(t)}var G,gt=P(()=>{"use strict";mt();G=class{constructor(e){this.config=e}mapStripeProduct(e){let a=e.default_price?.unit_amount||0,n=e.default_price?.currency||"usd";return{id:e.id,name:e.name,slug:e.metadata?.slug,summary:e.description,images:e.images||[],active:e.active,price:a/100,currency:n.toUpperCase(),stock:Number.parseInt(e.metadata?.stock||"0",10),stripeId:e.id,metadata:e.metadata||{}}}async productBrowse(e){let a=await ut({first:e.first||10,...e}),n=a.data.map(o=>this.mapStripeProduct(o));return{data:n,meta:{count:a.totalCount||n.length,offset:e.offset||0,limit:e.first||10,hasMore:n.length===(e.first||10)}}}async productGet(e){if(e.fields&&console.warn("GraphQL field selection not supported for Stripe provider. Ignoring 'fields' parameter."),e.slug){let a=await ct({slug:e.slug});return a?this.mapStripeProduct(a):null}if(e.id){let a=await D(e.id);return a?this.mapStripeProduct(a):null}throw new Error("Either slug or id is required for productGet")}async cartAdd(e){return{cartId:(await it({productId:e.variantId,cartId:e.cartId}))?.id||e.cartId||""}}async cartUpdate(e){let a=e.quantity>0?"INCREASE":"DECREASE";return{cartId:(await j({cartId:e.cartId,productId:e.variantId,operation:a}))?.id||e.cartId}}async cartClear(e){throw new Error("Cart clear not yet implemented for Stripe provider")}async cartGet(e){let a=await st(e.cartId);if(!a)return null;let n=a.lines.map(r=>({id:r.product?.id||"",productId:r.product?.id||"",variantId:r.product?.id,quantity:r.quantity,price:(r.product?.default_price?.unit_amount||0)/100})),o=n.reduce((r,s)=>r+s.price*s.quantity,0);return{id:a.cart.id,customerId:a.cart.customer,items:n,total:o,currency:a.cart.currency?.toUpperCase()||"USD",createdAt:new Date(a.cart.created*1e3).toISOString(),updatedAt:new Date().toISOString()}}}});var yt=class{config;provider;providerPromise;constructor(e){if(this.config=e||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:e}=await Promise.resolve().then(()=>(gt(),ft));return e(this.config)}catch(e){throw new Error(`Failed to initialize Stripe provider: ${e instanceof Error?e.message:"Unknown error"}`)}}get product(){return{browse:async(e={})=>(await this.getProvider()).productBrowse(e),get:async e=>(await this.getProvider()).productGet(e)}}get cart(){return{add:async e=>(await this.getProvider()).cartAdd(e),update:async e=>(await this.getProvider()).cartUpdate(e),clear:async e=>(await this.getProvider()).cartClear(e),get:async e=>(await this.getProvider()).cartGet(e)}}};export{yt as Commerce};
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:this.parsePrice(t.product?.default_price?.unit_amount),stock:void 0,product:void 0}}mapCustomerId(t){if(typeof t=="string")return t;if(t?.id)return t.id}parsePrice(t){return(t||0)/100}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.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Y as YnsProviderConfig, i as ProductBrowseParams, j as ProductBrowseResult, k as ProductGetParams, P as Product, l as ProductSearchParams, m as ProductSearchResult, a as CartAddParams, e as CartUpdateParams, b as CartClearParams, c as CartGetParams, C as Cart, f as OrderGetParams, O as Order, g as OrderListParams, h as OrderListResult } from './provider-Co3VegT-.js';
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
2
 
3
3
  /**
4
4
  * YNS Commerce client - zero-config constructor with GraphQL support
@@ -55,27 +55,29 @@ declare class Commerce {
55
55
  search: (params: ProductSearchParams) => Promise<ProductSearchResult>;
56
56
  };
57
57
  /**
58
- * Cart operations - YNS specific
58
+ * Cart operations - Simplified API
59
59
  */
60
60
  get cart(): {
61
61
  /**
62
- * Add item to cart
62
+ * Add items to cart (additive behavior)
63
+ * If cartId is provided, adds to existing quantity
64
+ * If no cartId, creates new cart
63
65
  */
64
- add: (params: CartAddParams) => Promise<{
65
- cartId: string;
66
- }>;
66
+ add: (params: CartAddParams) => Promise<Cart>;
67
67
  /**
68
- * Update item in cart
68
+ * Update item in cart (absolute behavior)
69
+ * Sets quantity to exact number
70
+ * Requires cartId
69
71
  */
70
- update: (params: CartUpdateParams) => Promise<{
71
- cartId: string;
72
- }>;
72
+ update: (params: CartUpdateParams) => Promise<Cart>;
73
73
  /**
74
- * Clear cart
74
+ * Remove specific item from cart
75
75
  */
76
- clear: (params: CartClearParams) => Promise<{
77
- cartId: string;
78
- }>;
76
+ remove: (params: CartRemoveParams) => Promise<Cart>;
77
+ /**
78
+ * Clear entire cart
79
+ */
80
+ clear: (params: CartClearParams) => Promise<Cart>;
79
81
  /**
80
82
  * Get cart details
81
83
  */
package/dist/yns.js CHANGED
@@ -1 +1 @@
1
- var u=Object.defineProperty;var p=(o,r)=>()=>(o&&(r=o(o=0)),r);var P=(o,r)=>{for(var t in r)u(o,t,{get:r[t],enumerable:!0})};var n={};P(n,{YnsProvider:()=>a,createYnsProvider:()=>v});function v(o){return new a(o)}var a,d=p(()=>{"use strict";a=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)throw new Error(`YNS REST request failed: ${i.status} ${i.statusText}`);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}))||[]}}mapYnsCart(r){let t=r.lineItems?.map(i=>({id:i.id,productId:i.productVariant?.id||"",variantId:i.productVariantId,quantity:i.quantity,price:Number.parseFloat(i.productVariant?.price||"0")}))||[],e=t.reduce((i,s)=>i+s.price*s.quantity,0);return{id:r.id,customerId:r.customerId,items:t,total:e,currency:"USD",createdAt:r.createdAt,updatedAt:r.updatedAt}}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(s=>this.mapYnsProduct(s)),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=r.id?`/products/${r.id}`:`/products/slug/${r.slug}`,e=await this.restRequest(t);return e?this.mapYnsProduct(e):null}}async cartAdd(r){let t={variantId:r.variantId,cartId:r.cartId,subscriptionId:r.subscriptionId};return await this.restRequest("/cart","POST",t)}async cartUpdate(r){let t={variantId:r.variantId,quantity:r.quantity};return await this.restRequest(`/cart/${r.cartId}`,"PUT",t)}async cartClear(r){return await this.restRequest(`/cart/${r.cartId}`,"DELETE")}async cartGet(r){let t=await this.restRequest(`/cart/${r.cartId}`);return t?this.mapYnsCart(t):null}}});var c=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(()=>(d(),n));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),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{c as Commerce};
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:this.parsePrice(t?.price),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||[]}}parsePrice(r){return Number.parseFloat(r||"0")/100}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};
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.3.0",
4
+ "version": "0.5.0",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [