commerce-kit 0.0.29 → 0.0.30
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.js +5 -5
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{z as c}from"zod";function S(t,e){if(!t)throw new Error(e)}var z=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},L=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 st=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),U=t=>Object.entries(t).map(([e,n])=>`${e}:"${st(n)}"`).join(" AND ").trim();function M(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),i=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(i)||a===i?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(i)?-1:a-i})}var ct=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional(),stock:c.coerce.number().optional().transform(t=>t===void 0?1/0:t)});function q({default_price:t,marketing_features:e,...n}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:e.map(a=>a.name).filter(Boolean),metadata:ct.parse(n.metadata)}}function G(t){return t.data.map(q)}function J(t){return t}function X(t){return t.data.map(J)}function Y(t){return t.filter((e,n,a)=>n===a.findIndex(i=>i.metadata.slug===e.metadata.slug))}var W=t=>!t.deleted&&t.active,K=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string())),H=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function D(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let n=K.parse(t.metadata),a=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,r])=>{let o=H.safeParse(j(String(r)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:e,taxBreakdown:a}}function Z({payment_method:t,latest_charge:e,...n}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let a=K.parse(n.metadata),i=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,o])=>{let s=H.safeParse(j(String(o)));return s.success?s.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:a}}import{revalidateTag as E}from"next/cache";import R from"stripe";import{z as _}from"zod";var p=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t};import tt from"stripe";var ut=process.env.STRIPE_SECRET_KEY,dt=process.env.STRIPE_CURRENCY,g={StripeSecretKey:ut,StripeCurrency:dt};var pt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],m=({tags:t,revalidate:e,cache:n,tagPrefix:a,secretKey:i})=>{let r=i??g.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let o=pt(t,a);return new tt(r,{typescript:!0,apiVersion:"2024-09-30.acacia",httpClient:tt.createFetchHttpClient((h,d)=>fetch(h,{...d,cache:n??d?.cache,next:{tags:o??d?.next?.tags,revalidate:e??d?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var b={DEBUG:0,LOG:1,WARN:2,ERROR:3},lt="LOG",mt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in b?process.env.LOG_LEVEL:lt,A=b[mt],u={time(t){A>b.DEBUG||console.time(t)},timeEnd(t){A>b.DEBUG||console.timeEnd(t)},log(...t){A>b.LOG||console.log(...t)},dir(t,e){A>b.LOG||console.dir(t,e)},warn(...t){A>b.WARN||console.warn(...t)},error(...t){A>b.ERROR||console.error(...t)}};var C=t=>t.filter(Boolean),w={accountGetById:{tags:({accountId:t})=>C(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>C(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>C(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>C(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>C(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>C(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>C(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>C(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>C(["tax-settings"]),revalidate:()=>{}}};import{neon as ft}from"@neondatabase/serverless";var T;process.env.DATABASE_URL&&(T=ft(process.env.DATABASE_URL));var O=1e3;function te({productId:t,cartId:e}){return e?gt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):yt({productId:t})}async function gt({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([k(t),at(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(i.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(g.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=r.cart.metadata??{},d=L(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let y=Ct(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:y||O},clearTaxCalculation:a})}catch(l){u.error(l)}finally{E(`cart-${e}`)}}async function B(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(rt.includes(r.status)){let o=D(r);if(!o)return null;let s=await V(o.metadata),{metadata:{shippingRateId:h}}=o,d=h&&await N(h);return{cart:o,lines:s.map(({product:y,quantity:l})=>y?{product:y,quantity:l}:null).filter(Boolean),shippingRate:d||null}}}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function yt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,cache:"no-cache"});if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await k(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await i.paymentIntents.create({currency:g.StripeCurrency,amount:r?.default_price.unit_amount||O,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw u.error(r),r}}async function ee({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return u.warn(`Product not found: ${e}`),t;let i=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),r=t?F(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:i}}async function re({cartId:t,productId:e,quantity:n}){let[a,i]=await Promise.all([Q(e),B(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!i)throw new Error(`Cart not found: ${t}`);if(g.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let r=i.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let o=F(i)+(a.default_price.unit_amount??0);try{return await I({paymentIntentId:t,data:{metadata:r,amount:o||O}})}catch(s){u.error(s)}finally{E(`cart-${t}`)}}async function Q(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ne({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),r=await m({secretKey:a,tagPrefix:n,tags:w.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:U({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(o=>!o.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.all(r.data.map(o=>Q(o.id))),M(G(r).filter(W))}async function ht(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p();if(t.filter?.category){let i=t.filter?.category,o=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:U({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return M(Y(G(o)).filter(W).slice(t.offset,t.first))}else{let r=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return M(Y(G(r)).filter(W).slice(t.offset,t.first))}}async function ae(){let{stripeAccount:t,storeId:e,secretKey:n}=await p(),i=await m({secretKey:n,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return X(i)}async function N(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await i.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie(){let e=(await ht({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function oe(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await i.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function se(){let{stripeAccount:t,storeId:e,secretKey:n}=await p(),a=m({secretKey:n,tagPrefix:e,tags:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await z(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),o=r?.settings?.branding.logo??null;return!o||typeof o=="string"?{account:r,logo:null}:{account:r,logo:o}}catch(i){if(u.error(i),i instanceof R.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return Z(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce(t){let e=await xt(t);if(!e)return null;let n=nt(e.metadata),a=await Promise.all(n.map(async([o,s])=>({product:await k(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await N(i);return{order:e,lines:a.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}},rt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],nt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),wt=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(rt.includes(r.status))return D(r)}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function V(t){let e=nt(t);return await Promise.all(e.map(async([a,i])=>({product:await k(a),quantity:i})))}var at=async t=>{let e=await wt(t);if(!e)return null;let n=await V(e.metadata),{metadata:{shippingRateId:a}}=e,i=a&&await N(a);return{cart:e,lines:n.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||null}},Ct=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0,_t=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function St({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||i>=r)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,h=_t.some(x=>!n[x]&&!t.cart.metadata[x]?!1:n[x]!==t.cart.metadata[x]),d=a.length!==t.lines.length||a.some(x=>{let v=t.lines.find(f=>f.product.id===x.product?.id);return x.product?.default_price.unit_amount!==v?.product.default_price.unit_amount||x.quantity!==v?.quantity});return s&&o!==s||h||d}var ue=t=>_.object({name:_.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:_.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:_.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:_.string({required_error:t.line1Required}).min(1,t.line1Required),line2:_.string().optional().nullable().default(""),postalCode:_.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:_.string().optional().nullable().default(""),phone:_.string().optional().nullable().default(""),taxId:_.string().optional().nullable().default(""),email:_.string().optional().nullable().default("")}),bt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:o,secretKey:s}=await p(),h=m({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let d=a?await N(a):null,y=typeof d?.tax_code=="string"?d.tax_code:d?.tax_code?.id,l=await vt(),x=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",v=l.defaults.tax_behavior==="inferred_by_currency"?x:l.defaults.tax_behavior??x;l.defaults.tax_behavior||u.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${x}.`),u.time("createTaxCalculation ${cartId}");let f=await h.tax.calculations.create({expand:["line_items"],line_items:t.map(P=>({...P,tax_behavior:P.tax_behavior??v})),currency:g.StripeCurrency,shipping_cost:d?.active&&d?.fixed_amount?{amount:d.fixed_amount.amount,tax_behavior:d.tax_behavior==="inclusive"?"inclusive":d.tax_behavior==="exclusive"?"exclusive":v,tax_code:y??l.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:i?[{type:"eu_vat",value:i}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return u.timeEnd("createTaxCalculation ${cartId}"),f},et={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},I=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:i,secretKey:r}=await p(),o=await at(t);S(o,`Cart not found: ${t}`);let s=K.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let h=await V(s);u.timeEnd("getProductsFromMetadata");let y=!n&&St({oldCart:o,data:e,mergedMetadata:s,lines:h})?await bt({cartId:t,taxId:s.taxId??null,shippingRateId:s.shippingRateId??null,billingAddress:{country:s["billingAddress.country"]??"",city:s["billingAddress.city"]??"",line1:s["billingAddress.line1"]??"",line2:s["billingAddress.line2"]??"",name:s["billingAddress.name"]??"",postalCode:s["billingAddress.postalCode"]??"",state:s["billingAddress.state"]??""},lineItems:h.map(({product:f,quantity:P})=>{if(f?.default_price.unit_amount)return{product:f.id,reference:[f.metadata.slug,f.metadata.variant].filter(Boolean).join("-"),quantity:P,amount:f.default_price.unit_amount*P,tax_behavior:f.default_price.tax_behavior==="exclusive"?"exclusive":f.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:f.tax_code?typeof f.tax_code=="string"?f.tax_code:f.tax_code.id:void 0}}).filter(Boolean)}):null,l=e.amount?e.amount.toString():null;if(y){let f=Object.fromEntries(y.tax_breakdown.map($=>({taxType:$.tax_rate_details.tax_type,taxPercentage:$.tax_rate_details.percentage_decimal,taxAmount:$.amount})).map(($,ot)=>[`taxBreakdown${ot}`,JSON.stringify($)])),P=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let it=await P.paymentIntents.update(t,{...e,amount:y.amount_total,metadata:{...s,...l&&{netAmount:l},...et,...f,taxCalculationId:y.id,taxCalculationExp:y?.expires_at}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),it}let x=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let v=await x.paymentIntents.update(t,{...e,metadata:{...s,...l&&{netAmount:l},...n&&{...et,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),v},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Rt(t):0,Rt=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function de({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([Q(t),B(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(g.StripeCurrency?.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=r.cart.metadata??{},d=L(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let y=F(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:y||O},clearTaxCalculation:a})}catch(l){u.error(l)}finally{E(`cart-${e}`)}}var pe=async({cartId:t,email:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}},le=async({cartId:t,taxId:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}};async function me({cartId:t,shippingRateId:e}){let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);u.time(`cartSaveShipping ${t}`);let a=await N(e);if(u.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:F({...n,shippingRate:a})}});return u.timeEnd(`updatePaymentIntent ${t}`),i}catch(i){u.error(i)}finally{E(`cart-${t}`)}}async function fe({cartId:t,billingAddress:e}){if(!await B(t))throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??"","billingAddress.email":e.email??""}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}}async function vt(){let{stripeAccount:t,storeId:e,secretKey:n}=await p();return await m({secretKey:n,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function ge(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function ye(t){if(!T)return null;let{storeId:e}=await p();return await T`
|
|
2
|
-
select * from reviews
|
|
1
|
+
import{z as c}from"zod";function S(t,e){if(!t)throw new Error(e)}var z=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},L=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 st=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),U=t=>Object.entries(t).map(([e,n])=>`${e}:"${st(n)}"`).join(" AND ").trim();function M(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),i=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(i)||a===i?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(i)?-1:a-i})}var ct=c.object({category:c.string().optional(),order:c.coerce.number().optional(),slug:c.string(),variant:c.string().optional(),stock:c.coerce.number().optional().transform(t=>t===void 0?1/0:t)});function q({default_price:t,marketing_features:e,...n}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...n,default_price:t,marketing_features:e.map(a=>a.name).filter(Boolean),metadata:ct.parse(n.metadata)}}function G(t){return t.data.map(q)}function J(t){return t}function X(t){return t.data.map(J)}function Y(t){return t.filter((e,n,a)=>n===a.findIndex(i=>i.metadata.slug===e.metadata.slug))}var W=t=>!t.deleted&&t.active,K=c.object({shippingRateId:c.string().optional(),taxCalculationId:c.string().optional(),taxCalculationExp:c.string().optional(),taxId:c.string().optional(),"billingAddress.city":c.string().optional(),"billingAddress.country":c.string().optional(),"billingAddress.line1":c.string().optional(),"billingAddress.line2":c.string().optional(),"billingAddress.name":c.string().optional(),"billingAddress.postalCode":c.string().optional(),"billingAddress.state":c.string().optional(),netAmount:c.string().optional(),taxBreakdown0:c.string().optional(),taxBreakdown1:c.string().optional(),taxBreakdown2:c.string().optional(),taxBreakdown3:c.string().optional(),taxBreakdown4:c.string().optional(),taxBreakdown5:c.string().optional()}).and(c.record(c.string())),H=c.object({taxType:c.string(),taxPercentage:c.string(),taxAmount:c.number()});function D(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let n=K.parse(t.metadata),a=Object.entries(n).filter(([i])=>i.startsWith("taxBreakdown")).map(([i,r])=>{let o=H.safeParse(j(String(r)));return o.success?o.data:null}).filter(Boolean);return{...t,metadata:n,payment_method:e,taxBreakdown:a}}function Z({payment_method:t,latest_charge:e,...n}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let a=K.parse(n.metadata),i=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,o])=>{let s=H.safeParse(j(String(o)));return s.success?s.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:i,metadata:a}}import{revalidateTag as E}from"next/cache";import R from"stripe";import{z as _}from"zod";var p=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,publishableKey:void 0};return await global?.__ynsFindStripeAccount?.()??t};import tt from"stripe";var ut=process.env.STRIPE_SECRET_KEY,dt=process.env.STRIPE_CURRENCY,g={StripeSecretKey:ut,StripeCurrency:dt};var pt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],m=({tags:t,revalidate:e,cache:n,tagPrefix:a,secretKey:i})=>{let r=i??g.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");let o=pt(t,a);return new tt(r,{typescript:!0,apiVersion:"2024-09-30.acacia",httpClient:tt.createFetchHttpClient((h,d)=>fetch(h,{...d,cache:n??d?.cache,next:{tags:o??d?.next?.tags,revalidate:e??d?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var b={DEBUG:0,LOG:1,WARN:2,ERROR:3},lt="LOG",mt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in b?process.env.LOG_LEVEL:lt,A=b[mt],u={time(t){A>b.DEBUG||console.time(t)},timeEnd(t){A>b.DEBUG||console.timeEnd(t)},log(...t){A>b.LOG||console.log(...t)},dir(t,e){A>b.LOG||console.dir(t,e)},warn(...t){A>b.WARN||console.warn(...t)},error(...t){A>b.ERROR||console.error(...t)}};var C=t=>t.filter(Boolean),w={accountGetById:{tags:({accountId:t})=>C(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>C(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>C(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>C(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>C(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>C(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>C(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>C(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>C(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>C(["tax-settings"]),revalidate:()=>{}}};import{neon as ft}from"@neondatabase/serverless";var T;process.env.DATABASE_URL&&(T=ft(process.env.DATABASE_URL));var O=1e3;function te({productId:t,cartId:e}){return e?gt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):yt({productId:t})}async function gt({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([k(t),at(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(i.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");if(g.StripeCurrency.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=r.cart.metadata??{},d=L(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let y=Ct(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:y||O},clearTaxCalculation:a})}catch(l){u.error(l)}finally{E(`cart-${e}`)}}async function B(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(rt.includes(r.status)){let o=D(r);if(!o)return null;let s=await V(o.metadata),{metadata:{shippingRateId:h}}=o,d=h&&await N(h);return{cart:o,lines:s.map(({product:y,quantity:l})=>y?{product:y,quantity:l}:null).filter(Boolean),shippingRate:d||null}}}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function yt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,cache:"no-cache"});if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");try{let r=t?await k(t):null;if(r&&r.metadata.stock<=0)throw Error(`Product ${t} is out of stock`);return await i.paymentIntents.create({currency:g.StripeCurrency,amount:r?.default_price.unit_amount||O,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw u.error(r),r}}async function ee({cart:t,add:e}){if(!e)return t;let n=await k(e);if(!n)return u.warn(`Product not found: ${e}`),t;let i=(t?.lines.find(o=>o.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(o=>o.product.id===e?{...o,quantity:o.quantity+1}:o),r=t?F(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:i}}async function re({cartId:t,productId:e,quantity:n}){let[a,i]=await Promise.all([Q(e),B(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!i)throw new Error(`Cart not found: ${t}`);if(g.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let r=i.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let o=F(i)+(a.default_price.unit_amount??0);try{return await I({paymentIntentId:t,data:{metadata:r,amount:o||O}})}catch(s){u.error(s)}finally{E(`cart-${t}`)}}async function Q(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ne({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),r=await m({secretKey:a,tagPrefix:n,tags:w.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:U({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(o=>!o.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return await Promise.all(r.data.map(o=>Q(o.id))),M(G(r).filter(W))}async function ht(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p();if(t.filter?.category){let i=t.filter?.category,o=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({category:i}),cache:"force-cache"}).products.search({limit:100,query:U({active:!0,'metadata["category"]':i}),expand:["data.default_price"]},{stripeAccount:e});return M(Y(G(o)).filter(W).slice(t.offset,t.first))}else{let r=await m({secretKey:a,tagPrefix:n,tags:w.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return M(Y(G(r)).filter(W).slice(t.offset,t.first))}}async function ae(){let{stripeAccount:t,storeId:e,secretKey:n}=await p(),i=await m({secretKey:n,tagPrefix:e,tags:w.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return X(i)}async function N(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await i.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ie(){let e=(await ht({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function oe(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await i.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function se(){let{stripeAccount:t,storeId:e,secretKey:n}=await p(),a=m({secretKey:n,tagPrefix:e,tags:w.accountGetById.tags({}),cache:"force-cache"});try{let[i,r]=await z(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),o=r?.settings?.branding.logo??null;return!o||typeof o=="string"?{account:r,logo:null}:{account:r,logo:o}}catch(i){if(u.error(i),i instanceof R.errors.StripeError&&i.code==="resource_missing")return null;throw i}}async function xt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge","customer"]},{stripeAccount:e});return Z(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ce(t){let e=await xt(t);if(!e)return null;let n=nt(e.metadata),a=await Promise.all(n.map(async([o,s])=>({product:await k(o),quantity:s}))),{metadata:{shippingRateId:i}}=e,r=i&&await N(i);return{order:e,lines:a.map(({product:o,quantity:s})=>o?{product:o,quantity:s}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await i.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return q(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}},rt=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],nt=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),wt=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await p(),i=m({secretKey:a,tagPrefix:n,tags:w.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await i.paymentIntents.retrieve(t,{expand:["payment_method","customer"]},{stripeAccount:e});if(rt.includes(r.status))return D(r)}catch(r){if(u.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function V(t){let e=nt(t);return await Promise.all(e.map(async([a,i])=>({product:await k(a),quantity:i})))}var at=async t=>{let e=await wt(t);if(!e)return null;let n=await V(e.metadata),{metadata:{shippingRateId:a}}=e,i=a&&await N(a);return{cart:e,lines:n.map(({product:r,quantity:o})=>r?{product:r,quantity:o}:null).filter(Boolean),shippingRate:i||null}},Ct=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0,_t=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function St({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let i=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||i>=r)return!0;let o=t.cart.metadata.netAmount||t.cart.amount,s=e.amount,h=_t.some(x=>!n[x]&&!t.cart.metadata[x]?!1:n[x]!==t.cart.metadata[x]),d=a.length!==t.lines.length||a.some(x=>{let v=t.lines.find(f=>f.product.id===x.product?.id);return x.product?.default_price.unit_amount!==v?.product.default_price.unit_amount||x.quantity!==v?.quantity});return s&&o!==s||h||d}var ue=t=>_.object({name:_.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:_.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:_.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:_.string({required_error:t.line1Required}).min(1,t.line1Required),line2:_.string().optional().nullable().default(""),postalCode:_.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:_.string().optional().nullable().default(""),phone:_.string().optional().nullable().default(""),taxId:_.string().optional().nullable().default(""),email:_.string().optional().nullable().default("")}),bt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:i})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;if(!g.StripeCurrency)throw new Error("Missing `STRIPE_CURRENCY` env variable");let{stripeAccount:r,storeId:o,secretKey:s}=await p(),h=m({secretKey:s,tagPrefix:o,tags:w.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let d=a?await N(a):null,y=typeof d?.tax_code=="string"?d.tax_code:d?.tax_code?.id,l=await vt(),x=g.StripeCurrency==="usd"||g.StripeCurrency==="cad"?"exclusive":"inclusive",v=l.defaults.tax_behavior==="inferred_by_currency"?x:l.defaults.tax_behavior??x;l.defaults.tax_behavior||u.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${g.StripeCurrency}: ${x}.`),u.time("createTaxCalculation ${cartId}");let f=await h.tax.calculations.create({expand:["line_items"],line_items:t.map(P=>({...P,tax_behavior:P.tax_behavior??v})),currency:g.StripeCurrency,shipping_cost:d?.active&&d?.fixed_amount?{amount:d.fixed_amount.amount,tax_behavior:d.tax_behavior==="inclusive"?"inclusive":d.tax_behavior==="exclusive"?"exclusive":v,tax_code:y??l.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:i?[{type:"eu_vat",value:i}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return u.timeEnd("createTaxCalculation ${cartId}"),f},et={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},I=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:i,secretKey:r}=await p(),o=await at(t);S(o,`Cart not found: ${t}`);let s=K.parse({...o.cart.metadata,...e.metadata});u.time("getProductsFromMetadata");let h=await V(s);u.timeEnd("getProductsFromMetadata");let y=!n&&St({oldCart:o,data:e,mergedMetadata:s,lines:h})?await bt({cartId:t,taxId:s.taxId??null,shippingRateId:s.shippingRateId??null,billingAddress:{country:s["billingAddress.country"]??"",city:s["billingAddress.city"]??"",line1:s["billingAddress.line1"]??"",line2:s["billingAddress.line2"]??"",name:s["billingAddress.name"]??"",postalCode:s["billingAddress.postalCode"]??"",state:s["billingAddress.state"]??""},lineItems:h.map(({product:f,quantity:P})=>{if(f?.default_price.unit_amount)return{product:f.id,reference:[f.metadata.slug,f.metadata.variant].filter(Boolean).join("-"),quantity:P,amount:f.default_price.unit_amount*P,tax_behavior:f.default_price.tax_behavior==="exclusive"?"exclusive":f.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:f.tax_code?typeof f.tax_code=="string"?f.tax_code:f.tax_code.id:void 0}}).filter(Boolean)}):null,l=e.amount?e.amount.toString():null;if(y){let f=Object.fromEntries(y.tax_breakdown.map($=>({taxType:$.tax_rate_details.tax_type,taxPercentage:$.tax_rate_details.percentage_decimal,taxAmount:$.amount})).map(($,ot)=>[`taxBreakdown${ot}`,JSON.stringify($)])),P=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let it=await P.paymentIntents.update(t,{...e,amount:y.amount_total,metadata:{...s,...l&&{netAmount:l},...et,...f,taxCalculationId:y.id,taxCalculationExp:y?.expires_at}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),it}let x=m({secretKey:r,tagPrefix:i,cache:"no-cache"});u.time(`paymentIntents.update ${t}`);let v=await x.paymentIntents.update(t,{...e,metadata:{...s,...l&&{netAmount:l},...n&&{...et,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return u.timeEnd(`paymentIntents.update ${t}`),v},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Rt(t):0,Rt=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function de({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[i,r]=await Promise.all([Q(t),B(e)]);if(!i)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(g.StripeCurrency?.toLowerCase()!==i.default_price.currency.toLowerCase())throw new Error(`Product currency ${i.default_price.currency} does not match cart currency ${g.StripeCurrency}`);let o=r.cart.metadata??{},d=L(o[t])+(n==="INCREASE"?1:-1);d<=0?o[t]="":o[t]=d.toString();let y=F(r)+(i.default_price.unit_amount??0);try{return await I({paymentIntentId:e,data:{metadata:o,amount:y||O},clearTaxCalculation:a})}catch(l){u.error(l)}finally{E(`cart-${e}`)}}var pe=async({cartId:t,email:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,email:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}},le=async({cartId:t,taxId:e})=>{let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}};async function me({cartId:t,shippingRateId:e}){let n=await B(t);if(!n)throw new Error(`Cart not found: ${t}`);u.time(`cartSaveShipping ${t}`);let a=await N(e);if(u.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{u.time(`updatePaymentIntent ${t}`);let i=await I({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:F({...n,shippingRate:a})}});return u.timeEnd(`updatePaymentIntent ${t}`),i}catch(i){u.error(i)}finally{E(`cart-${t}`)}}async function fe({cartId:t,billingAddress:e}){if(!await B(t))throw new Error(`Cart not found: ${t}`);try{return await I({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??"","billingAddress.email":e.email??""}}})}catch(a){u.error(a)}finally{E(`cart-${t}`)}}async function vt(){let{stripeAccount:t,storeId:e,secretKey:n}=await p();return await m({secretKey:n,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function ge(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,L(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function ye(t){if(!T)return null;let{storeId:e}=await p();return await T`
|
|
2
|
+
select * from reviews
|
|
3
3
|
where product_id = ${t.productId} and store_id = ${e}
|
|
4
|
-
order by created_at desc
|
|
5
|
-
limit ${t.first??100}
|
|
4
|
+
order by created_at desc
|
|
5
|
+
limit ${t.first??100}
|
|
6
6
|
offset ${t.offset??0}
|
|
7
7
|
`}async function he(t){if(!T)return null;let{storeId:e}=await p();return await T`
|
|
8
|
-
insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
|
|
8
|
+
insert into reviews (store_id, product_id, author, email, content, rating, created_at, updated_at)
|
|
9
9
|
values (${e}, ${t.productId}, ${t.author}, ${t.email}, ${t.content}, ${t.rating}, now(), now())
|
|
10
10
|
`}var xe=p;export{se as accountGet,Ct as calculateCartTotalNet,Rt as calculateCartTotalNetWithoutShipping,F as calculateCartTotalPossiblyWithTax,te as cartAdd,ee as cartAddOptimistic,de as cartChangeQuantity,ge as cartCount,yt as cartCreate,B as cartGet,fe as cartSaveBillingAddress,pe as cartSaveEmail,me as cartSaveShipping,le as cartSaveTax,re as cartSetQuantity,gt as cartUpdateQuantity,ie as categoryBrowse,xe as contextGet,oe as fileGet,ue as getAddressSchema,at as getCartWithProductsById,nt as getProductsFromCart,V as getProductsFromMetadata,ce as orderGet,ht as productBrowse,ne as productGet,Q as productGetById,he as productReviewAdd,ye as productReviewBrowse,m as provider,ae as shippingBrowse,N as shippingGet,vt as taxDefaultGet,I as updatePaymentIntent};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "commerce-kit",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.30",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
|
7
7
|
"keywords": [
|
|
@@ -48,20 +48,20 @@
|
|
|
48
48
|
],
|
|
49
49
|
"sideEffects": false,
|
|
50
50
|
"devDependencies": {
|
|
51
|
-
"@neondatabase/serverless": "^0.
|
|
52
|
-
"@types/node": "^22.7.
|
|
51
|
+
"@neondatabase/serverless": "^0.10.1",
|
|
52
|
+
"@types/node": "^22.7.5",
|
|
53
53
|
"@types/react": "npm:types-react@19.0.0-rc.1",
|
|
54
54
|
"@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
|
|
55
|
-
"next": "15.0.0-canary.
|
|
55
|
+
"next": "15.0.0-canary.179",
|
|
56
56
|
"prettier": "3.3.3",
|
|
57
57
|
"react": "19.0.0-rc-d8c90fa4-20241001",
|
|
58
58
|
"react-dom": "19.0.0-rc-d8c90fa4-20241001",
|
|
59
59
|
"rimraf": "6.0.1",
|
|
60
60
|
"server-only": "0.0.1",
|
|
61
|
-
"stripe": "^17.
|
|
61
|
+
"stripe": "^17.1.0",
|
|
62
62
|
"tsup": "8.3.0",
|
|
63
63
|
"tsx": "^4.19.1",
|
|
64
|
-
"vitest": "^2.1.
|
|
64
|
+
"vitest": "^2.1.2",
|
|
65
65
|
"zod": "^3.23.8"
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
"@types/node": "^20.14.8 || ^22.7.4",
|
|
70
70
|
"@types/react": "npm:types-react@19.0.0-rc.1",
|
|
71
71
|
"@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
|
|
72
|
-
"next": "15.0.0-canary.
|
|
72
|
+
"next": "15.0.0-canary.179",
|
|
73
73
|
"react": "19.0.0-rc-d8c90fa4-20241001",
|
|
74
74
|
"react-dom": "19.0.0-rc-d8c90fa4-20241001",
|
|
75
75
|
"server-only": "0.0.1",
|