UNPKG

commerce-kit

Version:

2 lines (1 loc) 6.05 kB
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};