commerce-kit 0.0.15 → 0.0.17
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 +2 -2
- package/dist/index.js +4 -4
- package/dist/yns.d.ts +11 -5
- package/dist/yns.js +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -716,14 +716,14 @@ declare function productReviewBrowse(params: {
|
|
|
716
716
|
last?: number;
|
|
717
717
|
offset?: number;
|
|
718
718
|
filter?: {};
|
|
719
|
-
}): Promise<Review[]>;
|
|
719
|
+
}): Promise<Review[] | null>;
|
|
720
720
|
declare function productReviewAdd(params: {
|
|
721
721
|
productId: string;
|
|
722
722
|
author: string;
|
|
723
723
|
email: string;
|
|
724
724
|
content: string;
|
|
725
725
|
rating: number;
|
|
726
|
-
}): Promise<Record<string, any>[]>;
|
|
726
|
+
}): Promise<Record<string, any>[] | null>;
|
|
727
727
|
declare const contextGet: () => Promise<{
|
|
728
728
|
stripeAccount: string | undefined;
|
|
729
729
|
storeId: string | undefined;
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import"server-only";import"server-only";import{z as u}from"zod";function S(t,e){if(!t)throw new Error(e)}var z=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},$=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},K=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var dt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),U=t=>Object.entries(t).map(([e,a])=>`${e}:"${dt(a)}"`).join(" AND ").trim();function G(t){return t.toSorted((e,a)=>{let n=Number(e.metadata.order),o=Number(a.metadata.order);return Number.isNaN(n)&&Number.isNaN(o)||n===o?a.updated-e.updated:Number.isNaN(n)?1:Number.isNaN(o)?-1:n-o})}var pt=u.object({category:u.string().optional(),order:u.coerce.number().optional(),slug:u.string(),variant:u.string().optional()});function M({default_price:t,marketing_features:e,...a}){return S(t,"Product must have a default price"),S(typeof t=="object","Product default price must be an object"),{...a,default_price:t,marketing_features:e.map(n=>n.name).filter(Boolean),metadata:pt.parse(a.metadata)}}function q(t){return t.data.map(M)}function H(t){return t}function J(t){return t.data.map(H)}function D(t){return t.filter((e,a,n)=>a===n.findIndex(o=>o.metadata.slug===e.metadata.slug))}var W=t=>!t.deleted&&t.active,j=u.object({shippingRateId:u.string().optional(),taxCalculationId:u.string().optional(),taxCalculationExp:u.string().optional(),taxId:u.string().optional(),"billingAddress.city":u.string().optional(),"billingAddress.country":u.string().optional(),"billingAddress.line1":u.string().optional(),"billingAddress.line2":u.string().optional(),"billingAddress.name":u.string().optional(),"billingAddress.postalCode":u.string().optional(),"billingAddress.state":u.string().optional(),netAmount:u.string().optional(),taxBreakdown0:u.string().optional(),taxBreakdown1:u.string().optional(),taxBreakdown2:u.string().optional(),taxBreakdown3:u.string().optional(),taxBreakdown4:u.string().optional(),taxBreakdown5:u.string().optional()}).and(u.record(u.string())),X=u.object({taxType:u.string(),taxPercentage:u.string(),taxAmount:u.number()});function Y(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let a=j.parse(t.metadata),n=Object.entries(a).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,r])=>{let i=X.safeParse(K(String(r)));return i.success?i.data:null}).filter(Boolean);return{...t,metadata:a,payment_method:e,taxBreakdown:n}}function Z({payment_method:t,latest_charge:e,...a}){S(typeof t=="object","Payment method is missing from order"),S(typeof e=="object","Latest charge is missing from order");let n=j.parse(a.metadata),o=Object.entries(n).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let c=X.safeParse(K(String(i)));return c.success?c.data:null}).filter(Boolean);return{...a,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:n}}import"server-only";import{revalidatePath as rt,revalidateTag as E}from"next/cache";import R from"stripe";import{z as b}from"zod";import"server-only";import{z as s}from"zod";var Mt=s.object({hero:s.object({show:s.boolean(),title:s.string(),description:s.string(),button:s.object({label:s.string(),path:s.string()}),image:s.object({src:s.string(),alt:s.string()})}),categorySection:s.object({show:s.boolean()}),nav:s.object({title:s.string(),searchBar:s.object({show:s.boolean()}),links:s.array(s.object({label:s.string(),href:s.string()}))}),footer:s.object({name:s.string(),tagline:s.string(),newsletter:s.object({show:s.boolean()}),credits:s.boolean(),sections:s.array(s.object({header:s.string(),links:s.array(s.object({label:s.string(),href:s.string()}))}))})}),l=async()=>{let t={stripeAccount:void 0,storeId:void 0,secretKey:void 0,config:{hero:{show:!0,title:"Discover our Curated Collection",description:"Explore our carefully selected products for your home and lifestyle.",button:{label:"Shop Now",path:"/"},image:{src:"https://files.stripe.com/links/MDB8YWNjdF8xT3BaeG5GSmNWbVh6bURsfGZsX3Rlc3RfaDVvWXowdU9ZbWlobUIyaHpNc1hCeDM200NBzvUjqP",alt:"Cup of coffee"}},categorySection:{show:!0},nav:{title:"Your Next Store",searchBar:{show:!0},links:[{label:"Home",href:"/"},{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},footer:{name:"Your Next Store",tagline:"Handcrafted with passion in California",newsletter:{show:!0},credits:!0,sections:[{header:"Products",links:[{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},{header:"Support",links:[{label:"Features",href:"https://yournextstore.com/#features"},{label:"Pricing",href:"https://yournextstore.com/#pricing"},{label:"Contact Us",href:"mailto:hi@yournextstore.com"}]}]}}};return global.__ynsFindStripeAccount?await global.__ynsFindStripeAccount()??t:t};import"server-only";import et from"stripe";import"server-only";var lt=process.env.STRIPE_SECRET_KEY,tt=process.env.STRIPE_CURRENCY;if(!tt)throw new Error("Missing STRIPE_CURRENCY");var w={StripeSecretKey:lt,StripeCurrency:tt};var v={DEBUG:0,LOG:1,WARN:2,ERROR:3},mt="LOG",ft=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in v?process.env.LOG_LEVEL:mt,I=v[ft],d={time(t){I>v.DEBUG||console.time(t)},timeEnd(t){I>v.DEBUG||console.timeEnd(t)},log(...t){I>v.LOG||console.log(...t)},dir(t,e){I>v.LOG||console.dir(t,e)},warn(...t){I>v.WARN||console.warn(...t)},error(...t){I>v.ERROR||console.error(...t)}};var gt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(a=>`${e}-${a}`)],f=({tags:t,revalidate:e,cache:a,tagPrefix:n,secretKey:o})=>{let r=o??w.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");d.log(`Using Stripe secret key from ${o?"parameter":"env"}.`);let i=gt(t,n);return new et(r,{typescript:!0,apiVersion:"2024-06-20",httpClient:et.createFetchHttpClient((y,p)=>fetch(y,{...p,cache:a??p?.cache,next:{tags:i??p?.next?.tags,revalidate:e??p?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var _=t=>t.filter(Boolean),C={accountGetById:{tags:({accountId:t})=>_(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>_(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>_(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>_(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>_(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>_(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>_(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>_(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>_(["tax-settings"]),revalidate:()=>{}}};import{neon as ht}from"@neondatabase/serverless";var V=ht(process.env.DATABASE_URL);var O=1e3;function de({productId:t,cartId:e}){return e?yt({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):xt({productId:t})}async function yt({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[o,r]=await Promise.all([k(t),st(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(w.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let i=r.cart.metadata??{},p=$(i[t])+(a==="INCREASE"?1:-1);p<=0?i[t]="":i[t]=p.toString();let h=bt(r)+(o.default_price.unit_amount??0);try{return await T({paymentIntentId:e,data:{metadata:i,amount:h||O},clearTaxCalculation:n})}catch(m){d.error(m)}finally{E(`cart-${e}`)}}async function N(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(ot.includes(r.status)){let i=Y(r);if(!i)return null;let c=await Q(i.metadata),{metadata:{shippingRateId:y}}=i,p=y&&await L(y);return{cart:i,lines:c.map(({product:h,quantity:m})=>h?{product:h,quantity:m}:null).filter(Boolean),shippingRate:p||null}}}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function xt({productId:t}={}){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,cache:"no-cache"});try{let r=t?await k(t):null;return await o.paymentIntents.create({currency:w.StripeCurrency,amount:r?.default_price.unit_amount||O,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw d.error(r),r}}async function pe({cart:t,add:e}){if(!e)return t;let a=await k(e);if(!a)return d.warn(`Product not found: ${e}`),t;let o=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:a,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),r=t?F(t)+(a.default_price.unit_amount??0):a.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:o}}async function le({cartId:t,productId:e,quantity:a}){let[n,o]=await Promise.all([nt(e),N(t)]);if(!n)throw new Error(`Product not found: ${e}`);if(!o)throw new Error(`Cart not found: ${t}`);if(w.StripeCurrency?.toLowerCase()!==n.default_price.currency.toLowerCase())throw new Error(`Product currency ${n.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let r=o.cart.metadata??{};a<=0?r[e]="":r[e]=a.toString();let i=F(o)+(n.default_price.unit_amount??0);try{return await T({paymentIntentId:t,data:{metadata:r,amount:i||O}})}catch(c){d.error(c)}finally{E(`cart-${t}`),rt("/cart"),rt("/cart-overlay")}}async function nt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return M(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function me({slug:t}){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),r=await f({secretKey:n,tagPrefix:a,tags:C.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:U({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return G(q(r).filter(W))}async function wt(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l();if(t.filter?.category){let o=t.filter?.category,i=await f({secretKey:n,tagPrefix:a,tags:C.productBrowse.tags({category:o}),cache:"force-cache"}).products.search({limit:100,query:U({active:!0,'metadata["category"]':o}),expand:["data.default_price"]},{stripeAccount:e});return G(D(q(i)).filter(W).slice(t.offset,t.first))}else{let r=await f({secretKey:n,tagPrefix:a,tags:C.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return G(D(q(r)).filter(W).slice(t.offset,t.first))}}async function fe(){let{stripeAccount:t,storeId:e,secretKey:a}=await l(),o=await f({secretKey:a,tagPrefix:e,tags:C.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return J(o)}async function L(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ge(){let e=(await wt({first:100})).map(n=>n.metadata.category).filter(Boolean),a=new Set(e);return Array.from(a)}async function he(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await o.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ye(){let{stripeAccount:t,storeId:e,secretKey:a}=await l(),n=f({secretKey:a,tagPrefix:e,tags:C.accountGetById.tags({}),cache:"force-cache"});try{let[o,r]=await z(n.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(o){if(d.error(o),o instanceof R.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function Ct(t){let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return Z(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function xe(t){let e=await Ct(t);if(!e)return null;let a=it(e.metadata),n=await Promise.all(a.map(async([i,c])=>({product:await k(i),quantity:c}))),{metadata:{shippingRateId:o}}=e,r=o&&await L(o);return{order:e,lines:n.map(({product:i,quantity:c})=>i?{product:i,quantity:c}:null).filter(Boolean),shippingRate:r||null}}var k=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.products.retrieve(t,{expand:["default_price"]},{stripeAccount:e});return M(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}},ot=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],it=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,$(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),_t=async t=>{let{stripeAccount:e,storeId:a,secretKey:n}=await l(),o=f({secretKey:n,tagPrefix:a,tags:C.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(ot.includes(r.status))return Y(r)}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function Q(t){let e=it(t);return await Promise.all(e.map(async([n,o])=>({product:await k(n),quantity:o})))}var st=async t=>{let e=await _t(t);if(!e)return null;let a=await Q(e.metadata),{metadata:{shippingRateId:n}}=e,o=n&&await L(n);return{cart:e,lines:a.map(({product:r,quantity:i})=>r?{product:r,quantity:i}:null).filter(Boolean),shippingRate:o||null}},bt=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0,St=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function vt({oldCart:t,data:e,mergedMetadata:a,lines:n}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),r=a.taxCalculationExp?Number.parseInt(a.taxCalculationExp)*1e3:null;if(!r||o>=r)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,c=e.amount,y=St.some(x=>!a[x]&&!t.cart.metadata[x]?!1:a[x]!==t.cart.metadata[x]),p=n.length!==t.lines.length||n.some(x=>{let P=t.lines.find(g=>g.product.id===x.product?.id);return x.product?.default_price.unit_amount!==P?.product.default_price.unit_amount||x.quantity!==P?.quantity});return c&&i!==c||y||p}var we=t=>b.object({name:b.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:b.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:b.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:b.string({required_error:t.line1Required}).min(1,t.line1Required),line2:b.string().optional().nullable().default(""),postalCode:b.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:b.string().optional().nullable().default(""),phone:b.string().optional().nullable().default(""),taxId:b.string().optional().nullable().default("")}),Rt=async({lineItems:t,billingAddress:e,cartId:a,shippingRateId:n,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:r,storeId:i,secretKey:c}=await l(),y=f({secretKey:c,tagPrefix:i,tags:C.createTaxCalculation.tags({cartId:a}),cache:"force-cache"});if(!e?.country)return null;let p=n?await L(n):null,h=typeof p?.tax_code=="string"?p.tax_code:p?.tax_code?.id,m=await At(),x=w.StripeCurrency==="usd"||w.StripeCurrency==="cad"?"exclusive":"inclusive",P=m.defaults.tax_behavior==="inferred_by_currency"?x:m.defaults.tax_behavior??x;m.defaults.tax_behavior||d.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${w.StripeCurrency}: ${x}.`),d.time("createTaxCalculation ${cartId}");let g=await y.tax.calculations.create({expand:["line_items"],line_items:t.map(A=>({...A,tax_behavior:A.tax_behavior??P})),currency:w.StripeCurrency,shipping_cost:p?.active&&p?.fixed_amount?{amount:p.fixed_amount.amount,tax_behavior:p.tax_behavior==="inclusive"?"inclusive":p.tax_behavior==="exclusive"?"exclusive":P,tax_code:h??m.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return d.timeEnd("createTaxCalculation ${cartId}"),g},at={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},T=async({paymentIntentId:t,data:e,clearTaxCalculation:a})=>{let{stripeAccount:n,storeId:o,secretKey:r}=await l(),i=await st(t);S(i,`Cart not found: ${t}`);let c=j.parse({...i.cart.metadata,...e.metadata});d.time("getProductsFromMetadata");let y=await Q(c);d.timeEnd("getProductsFromMetadata");let h=!a&&vt({oldCart:i,data:e,mergedMetadata:c,lines:y})?await Rt({cartId:t,taxId:c.taxId??null,shippingRateId:c.shippingRateId??null,billingAddress:{country:c["billingAddress.country"]??"",city:c["billingAddress.city"]??"",line1:c["billingAddress.line1"]??"",line2:c["billingAddress.line2"]??"",name:c["billingAddress.name"]??"",postalCode:c["billingAddress.postalCode"]??"",state:c["billingAddress.state"]??""},lineItems:y.map(({product:g,quantity:A})=>{if(g?.default_price.unit_amount)return{product:g.id,reference:[g.metadata.slug,g.metadata.variant].filter(Boolean).join("-"),quantity:A,amount:g.default_price.unit_amount*A,tax_behavior:g.default_price.tax_behavior==="exclusive"?"exclusive":g.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:g.tax_code?typeof g.tax_code=="string"?g.tax_code:g.tax_code.id:void 0}}).filter(Boolean)}):null,m=e.amount?e.amount.toString():null;if(h){let g=Object.fromEntries(h.tax_breakdown.map(B=>({taxType:B.tax_rate_details.tax_type,taxPercentage:B.tax_rate_details.percentage_decimal,taxAmount:B.amount})).map((B,ut)=>[`taxBreakdown${ut}`,JSON.stringify(B)])),A=f({secretKey:r,tagPrefix:o,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let ct=await A.paymentIntents.update(t,{...e,amount:h.amount_total,metadata:{...c,...m&&{netAmount:m},...at,...g,taxCalculationId:h.id,taxCalculationExp:h?.expires_at}},{stripeAccount:n});return d.timeEnd(`paymentIntents.update ${t}`),ct}let x=f({secretKey:r,tagPrefix:o,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let P=await x.paymentIntents.update(t,{...e,metadata:{...c,...m&&{netAmount:m},...a&&{...at,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:n});return d.timeEnd(`paymentIntents.update ${t}`),P},F=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Pt(t):0,Pt=t=>t?t.lines.reduce((e,{product:a,quantity:n})=>e+(a.default_price?.unit_amount??0)*n,0):0;async function Ce({productId:t,cartId:e,operation:a,clearTaxCalculation:n}){let[o,r]=await Promise.all([nt(t),N(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(w.StripeCurrency?.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let i=r.cart.metadata??{},p=$(i[t])+(a==="INCREASE"?1:-1);p<=0?i[t]="":i[t]=p.toString();let h=F(r)+(o.default_price.unit_amount??0);try{return await T({paymentIntentId:e,data:{metadata:i,amount:h||O},clearTaxCalculation:n})}catch(m){d.error(m)}finally{E(`cart-${e}`)}}var _e=async({cartId:t,taxId:e})=>{let a=await N(t);if(!a)throw new Error(`Cart not found: ${t}`);try{return await T({paymentIntentId:t,data:{metadata:{...a.cart.metadata,taxId:e}}})}catch(n){d.error(n)}finally{E(`cart-${t}`)}};async function be({cartId:t,shippingRateId:e}){let a=await N(t);if(!a)throw new Error(`Cart not found: ${t}`);d.time(`cartSaveShipping ${t}`);let n=await L(e);if(d.timeEnd(`cartSaveShipping ${t}`),!n)throw new Error(`Shipping rate not found: ${e}`);try{d.time(`updatePaymentIntent ${t}`);let o=await T({paymentIntentId:t,data:{metadata:{...a.cart.metadata,shippingRateId:e},amount:F({...a,shippingRate:n})}});return d.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){d.error(o)}finally{E(`cart-${t}`)}}async function Se({cartId:t,billingAddress:e}){if(!await N(t))throw new Error(`Cart not found: ${t}`);try{return await T({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??""}}})}catch(n){d.error(n)}finally{E(`cart-${t}`)}}async function At(){let{stripeAccount:t,storeId:e,secretKey:a}=await l();return await f({secretKey:a,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function ve(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,a])=>[e,$(a)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function Re(t){let{storeId:e}=await l();return await V`
|
|
1
|
+
import"server-only";import"server-only";import{z as u}from"zod";function S(t,e){if(!t)throw new Error(e)}var z=async t=>{try{return[null,await t]}catch(e){return[e instanceof Error?e:new Error(String(e)),null]}},$=t=>{if(t==null)return 0;if(typeof t=="number")return t;let e=Number.parseInt(t,10);return Number.isNaN(e)?0:e},U=t=>{if(t==null)return null;try{return JSON.parse(t)}catch{return null}};var dt=t=>t.toString().replace(/\\/g,"\\\\").replace(/"/g,'\\"'),D=t=>Object.entries(t).map(([e,n])=>`${e}:"${dt(n)}"`).join(" AND ").trim();function M(t){return t.toSorted((e,n)=>{let a=Number(e.metadata.order),o=Number(n.metadata.order);return Number.isNaN(a)&&Number.isNaN(o)||a===o?n.updated-e.updated:Number.isNaN(a)?1:Number.isNaN(o)?-1:a-o})}var pt=u.object({category:u.string().optional(),order:u.coerce.number().optional(),slug:u.string(),variant:u.string().optional()});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:pt.parse(n.metadata)}}function W(t){return t.data.map(q)}function H(t){return t}function J(t){return t.data.map(H)}function Y(t){return t.filter((e,n,a)=>n===a.findIndex(o=>o.metadata.slug===e.metadata.slug))}var j=t=>!t.deleted&&t.active,O=u.object({shippingRateId:u.string().optional(),taxCalculationId:u.string().optional(),taxCalculationExp:u.string().optional(),taxId:u.string().optional(),"billingAddress.city":u.string().optional(),"billingAddress.country":u.string().optional(),"billingAddress.line1":u.string().optional(),"billingAddress.line2":u.string().optional(),"billingAddress.name":u.string().optional(),"billingAddress.postalCode":u.string().optional(),"billingAddress.state":u.string().optional(),netAmount:u.string().optional(),taxBreakdown0:u.string().optional(),taxBreakdown1:u.string().optional(),taxBreakdown2:u.string().optional(),taxBreakdown3:u.string().optional(),taxBreakdown4:u.string().optional(),taxBreakdown5:u.string().optional()}).and(u.record(u.string())),X=u.object({taxType:u.string(),taxPercentage:u.string(),taxAmount:u.number()});function Q(t){let e=t.payment_method;S(typeof e!="string","Payment method is missing from cart");let n=O.parse(t.metadata),a=Object.entries(n).filter(([o])=>o.startsWith("taxBreakdown")).map(([o,r])=>{let i=X.safeParse(U(String(r)));return i.success?i.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=O.parse(n.metadata),o=Object.entries(a).filter(([r])=>r.startsWith("taxBreakdown")).map(([r,i])=>{let c=X.safeParse(U(String(i)));return c.success?c.data:null}).filter(Boolean);return{...n,payment_method:t,latest_charge:e,taxBreakdown:o,metadata:a}}import"server-only";import{revalidatePath as rt,revalidateTag as T}from"next/cache";import R from"stripe";import{z as b}from"zod";import"server-only";import{z as s}from"zod";var Mt=s.object({hero:s.object({show:s.boolean(),title:s.string(),description:s.string(),button:s.object({label:s.string(),path:s.string()}),image:s.object({src:s.string(),alt:s.string()})}),categorySection:s.object({show:s.boolean()}),nav:s.object({title:s.string(),searchBar:s.object({show:s.boolean()}),links:s.array(s.object({label:s.string(),href:s.string()}))}),footer:s.object({name:s.string(),tagline:s.string(),newsletter:s.object({show:s.boolean()}),credits:s.boolean(),sections:s.array(s.object({header:s.string(),links:s.array(s.object({label:s.string(),href:s.string()}))}))})}),l=async()=>{let t={hero:{show:!0,title:"Discover our Curated Collection",description:"Explore our carefully selected products for your home and lifestyle.",button:{label:"Shop Now",path:"/"},image:{src:"https://files.stripe.com/links/MDB8YWNjdF8xT3BaeG5GSmNWbVh6bURsfGZsX3Rlc3RfaDVvWXowdU9ZbWlobUIyaHpNc1hCeDM200NBzvUjqP",alt:"Cup of coffee"}},categorySection:{show:!0},nav:{title:"Your Next Store",searchBar:{show:!0},links:[{label:"Home",href:"/"},{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},footer:{name:"Your Next Store",tagline:"Handcrafted with passion in California",newsletter:{show:!0},credits:!0,sections:[{header:"Products",links:[{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},{header:"Support",links:[{label:"Features",href:"https://yournextstore.com/#features"},{label:"Pricing",href:"https://yournextstore.com/#pricing"},{label:"Contact Us",href:"mailto:hi@yournextstore.com"}]}]}},e={stripeAccount:void 0,storeId:void 0,secretKey:void 0,config:t},n=await global?.__ynsFindStripeAccount?.();return n?{...n,config:n.config??t}:e};import"server-only";import et from"stripe";import"server-only";var lt=process.env.STRIPE_SECRET_KEY,tt=process.env.STRIPE_CURRENCY;if(!tt)throw new Error("Missing STRIPE_CURRENCY");var w={StripeSecretKey:lt,StripeCurrency:tt};var v={DEBUG:0,LOG:1,WARN:2,ERROR:3},ft="LOG",mt=process.env.LOG_LEVEL&&process.env.LOG_LEVEL in v?process.env.LOG_LEVEL:ft,I=v[mt],d={time(t){I>v.DEBUG||console.time(t)},timeEnd(t){I>v.DEBUG||console.timeEnd(t)},log(...t){I>v.LOG||console.log(...t)},dir(t,e){I>v.LOG||console.dir(t,e)},warn(...t){I>v.WARN||console.warn(...t)},error(...t){I>v.ERROR||console.error(...t)}};var gt=(t,e)=>!t||!e?t:[...t,`prefix-${e}`,...t.map(n=>`${e}-${n}`)],m=({tags:t,revalidate:e,cache:n,tagPrefix:a,secretKey:o})=>{let r=o??w.StripeSecretKey;if(!r)throw new Error("Missing `secretKey` parameter and `STRIPE_SECRET_KEY` env variable.");d.log(`Using Stripe secret key from ${o?"parameter":"env"}.`);let i=gt(t,a);return new et(r,{typescript:!0,apiVersion:"2024-06-20",httpClient:et.createFetchHttpClient((h,p)=>fetch(h,{...p,cache:n??p?.cache,next:{tags:i??p?.next?.tags,revalidate:e??p?.next?.revalidate}})),appInfo:{name:"Commerce SDK",version:"beta",url:"https://yournextstore.com",partner_id:"CONS-003378"}})};var _=t=>t.filter(Boolean),C={accountGetById:{tags:({accountId:t})=>_(["account",t&&`account-${t}`]),revalidate:()=>{}},cartGetById:{tags:({cartId:t})=>_(["cart",`cart-${t}`]),revalidate:()=>{}},createTaxCalculation:{tags:({cartId:t})=>_(["tax-calculations",`tax-calculations-${t}`]),revalidate:()=>{}},fileGetById:{tags:({fileId:t})=>_(["files",`file-${t}`]),revalidate:()=>{}},orderGetById:{tags:({orderId:t})=>_(["order",`order-${t}`]),revalidate:()=>{}},productBrowse:{tags:({category:t})=>_(["product",t&&`category-${t}`]),revalidate:()=>{}},productGetById:{tags:({productId:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},productGetBySlug:{tags:({productSlug:t})=>_(["product",`product-${t}`]),revalidate:()=>{}},shippingBrowse:{tags:()=>_(["shipping"]),revalidate:()=>{}},shippingGetById:{tags:({shippingId:t})=>_(["shipping",`shipping-${t}`]),revalidate:()=>{}},taxDefaultGet:{tags:()=>_(["tax-settings"]),revalidate:()=>{}}};import{neon as yt}from"@neondatabase/serverless";var E;process.env.DATABASE_URL&&(E=yt(process.env.DATABASE_URL));var F=1e3;function de({productId:t,cartId:e}){return e?ht({cartId:e,productId:t,operation:"INCREASE",clearTaxCalculation:!0}):xt({productId:t})}async function ht({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([G(t),st(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(w.StripeCurrency.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let i=r.cart.metadata??{},p=$(i[t])+(n==="INCREASE"?1:-1);p<=0?i[t]="":i[t]=p.toString();let y=bt(r)+(o.default_price.unit_amount??0);try{return await B({paymentIntentId:e,data:{metadata:i,amount:y||F},clearTaxCalculation:a})}catch(f){d.error(f)}finally{T(`cart-${e}`)}}async function L(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:C.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(ot.includes(r.status)){let i=Q(r);if(!i)return null;let c=await V(i.metadata),{metadata:{shippingRateId:h}}=i,p=h&&await k(h);return{cart:i,lines:c.map(({product:y,quantity:f})=>y?{product:y,quantity:f}:null).filter(Boolean),shippingRate:p||null}}}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function xt({productId:t}={}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,cache:"no-cache"});try{let r=t?await G(t):null;return await o.paymentIntents.create({currency:w.StripeCurrency,amount:r?.default_price.unit_amount||F,automatic_payment_methods:{enabled:!0},metadata:{...r&&{[r.id]:"1"}}},{stripeAccount:e})}catch(r){throw d.error(r),r}}async function pe({cart:t,add:e}){if(!e)return t;let n=await G(e);if(!n)return d.warn(`Product not found: ${e}`),t;let o=(t?.lines.find(i=>i.product.id===e)?t.lines:[...t?.lines??[],{product:n,quantity:0}]).map(i=>i.product.id===e?{...i,quantity:i.quantity+1}:i),r=t?K(t)+(n.default_price.unit_amount??0):n.default_price.unit_amount??0;return{...t,cart:{...t?.cart,amount:r},lines:o}}async function le({cartId:t,productId:e,quantity:n}){let[a,o]=await Promise.all([at(e),L(t)]);if(!a)throw new Error(`Product not found: ${e}`);if(!o)throw new Error(`Cart not found: ${t}`);if(w.StripeCurrency?.toLowerCase()!==a.default_price.currency.toLowerCase())throw new Error(`Product currency ${a.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let r=o.cart.metadata??{};n<=0?r[e]="":r[e]=n.toString();let i=K(o)+(a.default_price.unit_amount??0);try{return await B({paymentIntentId:t,data:{metadata:r,amount:i||F}})}catch(c){d.error(c)}finally{T(`cart-${t}`),rt("/cart"),rt("/cart-overlay")}}async function at(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:C.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.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 fe({slug:t}){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),r=await m({secretKey:a,tagPrefix:n,tags:C.productGetBySlug.tags({productSlug:t}),cache:"force-cache"}).products.search({query:D({active:!0,'metadata["slug"]':t}),expand:["data.default_price"]},{stripeAccount:e});if(r.data.length>1&&r.data.some(i=>!i.metadata.variant))throw new Error(`Multiple products found with the same slug (${t}) but no variant set.`);return M(W(r).filter(j))}async function wt(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l();if(t.filter?.category){let o=t.filter?.category,i=await m({secretKey:a,tagPrefix:n,tags:C.productBrowse.tags({category:o}),cache:"force-cache"}).products.search({limit:100,query:D({active:!0,'metadata["category"]':o}),expand:["data.default_price"]},{stripeAccount:e});return M(Y(W(i)).filter(j).slice(t.offset,t.first))}else{let r=await m({secretKey:a,tagPrefix:n,tags:C.productBrowse.tags({}),cache:"force-cache"}).products.list({limit:100,active:!0,expand:["data.default_price"]},{stripeAccount:e});return M(Y(W(r)).filter(j).slice(t.offset,t.first))}}async function me(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),o=await m({secretKey:n,tagPrefix:e,tags:C.shippingBrowse.tags(),cache:"force-cache"}).shippingRates.list({active:!0},{stripeAccount:t});return J(o)}async function k(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:C.shippingGetById.tags({shippingId:t}),cache:"force-cache"});try{let r=await o.shippingRates.retrieve(t,{},{stripeAccount:e});return r}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function ge(){let e=(await wt({first:100})).map(a=>a.metadata.category).filter(Boolean),n=new Set(e);return Array.from(n)}async function ye(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:C.fileGetById.tags({fileId:t}),cache:"force-cache"});try{return await o.fileLinks.create({file:t},{stripeAccount:e})}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function he(){let{stripeAccount:t,storeId:e,secretKey:n}=await l(),a=m({secretKey:n,tagPrefix:e,tags:C.accountGetById.tags({}),cache:"force-cache"});try{let[o,r]=await z(a.accounts.retrieve({expand:["settings.branding.logo"]},{stripeAccount:t})),i=r?.settings?.branding.logo??null;return!i||typeof i=="string"?{account:r,logo:null}:{account:r,logo:i}}catch(o){if(d.error(o),o instanceof R.errors.StripeError&&o.code==="resource_missing")return null;throw o}}async function Ct(t){let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:C.orderGetById.tags({orderId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method","latest_charge"]},{stripeAccount:e});return Z(r)}catch(r){if(r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}}async function xe(t){let e=await Ct(t);if(!e)return null;let n=it(e.metadata),a=await Promise.all(n.map(async([i,c])=>({product:await G(i),quantity:c}))),{metadata:{shippingRateId:o}}=e,r=o&&await k(o);return{order:e,lines:a.map(({product:i,quantity:c})=>i?{product:i,quantity:c}:null).filter(Boolean),shippingRate:r||null}}var G=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:C.productGetById.tags({productId:t}),cache:"force-cache"});try{let r=await o.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}},ot=["requires_action","requires_confirmation","requires_capture","requires_payment_method"],it=t=>Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,$(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0),_t=async t=>{let{stripeAccount:e,storeId:n,secretKey:a}=await l(),o=m({secretKey:a,tagPrefix:n,tags:C.cartGetById.tags({cartId:t}),cache:"force-cache"});try{let r=await o.paymentIntents.retrieve(t,{expand:["payment_method"]},{stripeAccount:e});if(ot.includes(r.status))return Q(r)}catch(r){if(d.error(r),r instanceof R.errors.StripeError&&r.code==="resource_missing")return null;throw r}};async function V(t){let e=it(t);return await Promise.all(e.map(async([a,o])=>({product:await G(a),quantity:o})))}var st=async t=>{let e=await _t(t);if(!e)return null;let n=await V(e.metadata),{metadata:{shippingRateId:a}}=e,o=a&&await k(a);return{cart:e,lines:n.map(({product:r,quantity:i})=>r?{product:r,quantity:i}:null).filter(Boolean),shippingRate:o||null}},bt=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0,St=["billingAddress.country","billingAddress.postalCode","billingAddress.state","taxId","shippingRateId"];function vt({oldCart:t,data:e,mergedMetadata:n,lines:a}){if(!process.env.ENABLE_STRIPE_TAX)return!1;let o=Date.now(),r=n.taxCalculationExp?Number.parseInt(n.taxCalculationExp)*1e3:null;if(!r||o>=r)return!0;let i=t.cart.metadata.netAmount||t.cart.amount,c=e.amount,h=St.some(x=>!n[x]&&!t.cart.metadata[x]?!1:n[x]!==t.cart.metadata[x]),p=a.length!==t.lines.length||a.some(x=>{let P=t.lines.find(g=>g.product.id===x.product?.id);return x.product?.default_price.unit_amount!==P?.product.default_price.unit_amount||x.quantity!==P?.quantity});return c&&i!==c||h||p}var we=t=>b.object({name:b.string({required_error:t.nameRequired}).min(1,t.nameRequired),city:b.string({required_error:t.cityRequired}).min(1,t.cityRequired),country:b.string({required_error:t.countryRequired}).min(1,t.countryRequired),line1:b.string({required_error:t.line1Required}).min(1,t.line1Required),line2:b.string().optional().nullable().default(""),postalCode:b.string({required_error:t.postalCodeRequired}).min(1,t.postalCodeRequired),state:b.string().optional().nullable().default(""),phone:b.string().optional().nullable().default(""),taxId:b.string().optional().nullable().default("")}),Rt=async({lineItems:t,billingAddress:e,cartId:n,shippingRateId:a,taxId:o})=>{if(!process.env.ENABLE_STRIPE_TAX)return null;let{stripeAccount:r,storeId:i,secretKey:c}=await l(),h=m({secretKey:c,tagPrefix:i,tags:C.createTaxCalculation.tags({cartId:n}),cache:"force-cache"});if(!e?.country)return null;let p=a?await k(a):null,y=typeof p?.tax_code=="string"?p.tax_code:p?.tax_code?.id,f=await At(),x=w.StripeCurrency==="usd"||w.StripeCurrency==="cad"?"exclusive":"inclusive",P=f.defaults.tax_behavior==="inferred_by_currency"?x:f.defaults.tax_behavior??x;f.defaults.tax_behavior||d.warn(`Tax behavior not set in Stripe settings. Inferring from currency ${w.StripeCurrency}: ${x}.`),d.time("createTaxCalculation ${cartId}");let g=await h.tax.calculations.create({expand:["line_items"],line_items:t.map(A=>({...A,tax_behavior:A.tax_behavior??P})),currency:w.StripeCurrency,shipping_cost:p?.active&&p?.fixed_amount?{amount:p.fixed_amount.amount,tax_behavior:p.tax_behavior==="inclusive"?"inclusive":p.tax_behavior==="exclusive"?"exclusive":P,tax_code:y??f.defaults.tax_code??void 0}:void 0,customer_details:{tax_ids:o?[{type:"eu_vat",value:o}]:void 0,address_source:"billing",address:{country:e.country,city:e?.city,line1:e?.line1,line2:e?.line2,postal_code:e?.postalCode,state:e?.state}}},{stripeAccount:r});return d.timeEnd("createTaxCalculation ${cartId}"),g},nt={taxBreakdown0:"",taxBreakdown1:"",taxBreakdown2:"",taxBreakdown3:"",taxBreakdown4:"",taxBreakdown5:""},B=async({paymentIntentId:t,data:e,clearTaxCalculation:n})=>{let{stripeAccount:a,storeId:o,secretKey:r}=await l(),i=await st(t);S(i,`Cart not found: ${t}`);let c=O.parse({...i.cart.metadata,...e.metadata});d.time("getProductsFromMetadata");let h=await V(c);d.timeEnd("getProductsFromMetadata");let y=!n&&vt({oldCart:i,data:e,mergedMetadata:c,lines:h})?await Rt({cartId:t,taxId:c.taxId??null,shippingRateId:c.shippingRateId??null,billingAddress:{country:c["billingAddress.country"]??"",city:c["billingAddress.city"]??"",line1:c["billingAddress.line1"]??"",line2:c["billingAddress.line2"]??"",name:c["billingAddress.name"]??"",postalCode:c["billingAddress.postalCode"]??"",state:c["billingAddress.state"]??""},lineItems:h.map(({product:g,quantity:A})=>{if(g?.default_price.unit_amount)return{product:g.id,reference:[g.metadata.slug,g.metadata.variant].filter(Boolean).join("-"),quantity:A,amount:g.default_price.unit_amount*A,tax_behavior:g.default_price.tax_behavior==="exclusive"?"exclusive":g.default_price.tax_behavior==="inclusive"?"inclusive":void 0,tax_code:g.tax_code?typeof g.tax_code=="string"?g.tax_code:g.tax_code.id:void 0}}).filter(Boolean)}):null,f=e.amount?e.amount.toString():null;if(y){let g=Object.fromEntries(y.tax_breakdown.map(N=>({taxType:N.tax_rate_details.tax_type,taxPercentage:N.tax_rate_details.percentage_decimal,taxAmount:N.amount})).map((N,ut)=>[`taxBreakdown${ut}`,JSON.stringify(N)])),A=m({secretKey:r,tagPrefix:o,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let ct=await A.paymentIntents.update(t,{...e,amount:y.amount_total,metadata:{...c,...f&&{netAmount:f},...nt,...g,taxCalculationId:y.id,taxCalculationExp:y?.expires_at}},{stripeAccount:a});return d.timeEnd(`paymentIntents.update ${t}`),ct}let x=m({secretKey:r,tagPrefix:o,cache:"no-cache"});d.time(`paymentIntents.update ${t}`);let P=await x.paymentIntents.update(t,{...e,metadata:{...c,...f&&{netAmount:f},...n&&{...nt,taxCalculationId:"",taxCalculationExp:""}}},{stripeAccount:a});return d.timeEnd(`paymentIntents.update ${t}`),P},K=t=>t?t.cart.metadata?.taxCalculationId?t.cart.amount:(t.shippingRate?.fixed_amount?.amount??0)+Pt(t):0,Pt=t=>t?t.lines.reduce((e,{product:n,quantity:a})=>e+(n.default_price?.unit_amount??0)*a,0):0;async function Ce({productId:t,cartId:e,operation:n,clearTaxCalculation:a}){let[o,r]=await Promise.all([at(t),L(e)]);if(!o)throw new Error(`Product not found: ${t}`);if(!r)throw new Error(`Cart not found: ${e}`);if(w.StripeCurrency?.toLowerCase()!==o.default_price.currency.toLowerCase())throw new Error(`Product currency ${o.default_price.currency} does not match cart currency ${w.StripeCurrency}`);let i=r.cart.metadata??{},p=$(i[t])+(n==="INCREASE"?1:-1);p<=0?i[t]="":i[t]=p.toString();let y=K(r)+(o.default_price.unit_amount??0);try{return await B({paymentIntentId:e,data:{metadata:i,amount:y||F},clearTaxCalculation:a})}catch(f){d.error(f)}finally{T(`cart-${e}`)}}var _e=async({cartId:t,taxId:e})=>{let n=await L(t);if(!n)throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{...n.cart.metadata,taxId:e}}})}catch(a){d.error(a)}finally{T(`cart-${t}`)}};async function be({cartId:t,shippingRateId:e}){let n=await L(t);if(!n)throw new Error(`Cart not found: ${t}`);d.time(`cartSaveShipping ${t}`);let a=await k(e);if(d.timeEnd(`cartSaveShipping ${t}`),!a)throw new Error(`Shipping rate not found: ${e}`);try{d.time(`updatePaymentIntent ${t}`);let o=await B({paymentIntentId:t,data:{metadata:{...n.cart.metadata,shippingRateId:e},amount:K({...n,shippingRate:a})}});return d.timeEnd(`updatePaymentIntent ${t}`),o}catch(o){d.error(o)}finally{T(`cart-${t}`)}}async function Se({cartId:t,billingAddress:e}){if(!await L(t))throw new Error(`Cart not found: ${t}`);try{return await B({paymentIntentId:t,data:{metadata:{"billingAddress.name":e.name,"billingAddress.phone":e.phone,"billingAddress.city":e.city,"billingAddress.country":e.country,"billingAddress.line1":e.line1,"billingAddress.line2":e.line2??"","billingAddress.postalCode":e.postalCode,"billingAddress.state":e.state??""}}})}catch(a){d.error(a)}finally{T(`cart-${t}`)}}async function At(){let{stripeAccount:t,storeId:e,secretKey:n}=await l();return await m({secretKey:n,tagPrefix:e,tags:["tax-settings"],cache:"force-cache"}).tax.settings.retrieve({},{stripeAccount:t})}function ve(t){return Object.entries(t??{}).filter(([e])=>e.startsWith("prod_")).map(([e,n])=>[e,$(n)]).filter(([,e])=>e&&Number.isFinite(e)&&e>0).length}async function Re(t){if(!E)return null;let{storeId:e}=await l();return await E`
|
|
2
2
|
select * from reviews
|
|
3
|
-
where product_id = ${t.productId}
|
|
3
|
+
where product_id = ${t.productId} and store_id = ${e}
|
|
4
4
|
order by created_at desc
|
|
5
5
|
limit ${t.first??100}
|
|
6
6
|
offset ${t.offset??0}
|
|
7
|
-
`}async function Pe(t){let{storeId:e}=await l();return await
|
|
7
|
+
`}async function Pe(t){if(!E)return null;let{storeId:e}=await l();return await E`
|
|
8
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
|
-
`}var Ae=l;export{
|
|
10
|
+
`}var Ae=l;export{he as accountGet,bt as calculateCartTotalNet,Pt as calculateCartTotalNetWithoutShipping,K as calculateCartTotalPossiblyWithTax,de as cartAdd,pe as cartAddOptimistic,Ce as cartChangeQuantity,ve as cartCount,xt as cartCreate,L as cartGet,Se as cartSaveBillingAddress,be as cartSaveShipping,_e as cartSaveTax,le as cartSetQuantity,ht as cartUpdateQuantity,ge as categoryBrowse,Ae as contextGet,ye as fileGet,we as getAddressSchema,st as getCartWithProductsById,it as getProductsFromCart,xe as orderGet,wt as productBrowse,fe as productGet,at as productGetById,Pe as productReviewAdd,Re as productReviewBrowse,m as provider,me as shippingBrowse,k as shippingGet,At as taxDefaultGet};
|
package/dist/yns.d.ts
CHANGED
|
@@ -26,9 +26,9 @@ declare const configSchema: z.ZodObject<{
|
|
|
26
26
|
alt: string;
|
|
27
27
|
}>;
|
|
28
28
|
}, "strip", z.ZodTypeAny, {
|
|
29
|
-
description: string;
|
|
30
29
|
show: boolean;
|
|
31
30
|
title: string;
|
|
31
|
+
description: string;
|
|
32
32
|
button: {
|
|
33
33
|
path: string;
|
|
34
34
|
label: string;
|
|
@@ -38,9 +38,9 @@ declare const configSchema: z.ZodObject<{
|
|
|
38
38
|
alt: string;
|
|
39
39
|
};
|
|
40
40
|
}, {
|
|
41
|
-
description: string;
|
|
42
41
|
show: boolean;
|
|
43
42
|
title: string;
|
|
43
|
+
description: string;
|
|
44
44
|
button: {
|
|
45
45
|
path: string;
|
|
46
46
|
label: string;
|
|
@@ -162,9 +162,9 @@ declare const configSchema: z.ZodObject<{
|
|
|
162
162
|
}>;
|
|
163
163
|
}, "strip", z.ZodTypeAny, {
|
|
164
164
|
hero: {
|
|
165
|
-
description: string;
|
|
166
165
|
show: boolean;
|
|
167
166
|
title: string;
|
|
167
|
+
description: string;
|
|
168
168
|
button: {
|
|
169
169
|
path: string;
|
|
170
170
|
label: string;
|
|
@@ -204,9 +204,9 @@ declare const configSchema: z.ZodObject<{
|
|
|
204
204
|
};
|
|
205
205
|
}, {
|
|
206
206
|
hero: {
|
|
207
|
-
description: string;
|
|
208
207
|
show: boolean;
|
|
209
208
|
title: string;
|
|
209
|
+
description: string;
|
|
210
210
|
button: {
|
|
211
211
|
path: string;
|
|
212
212
|
label: string;
|
|
@@ -247,6 +247,12 @@ declare const configSchema: z.ZodObject<{
|
|
|
247
247
|
}>;
|
|
248
248
|
type Config = z.infer<typeof configSchema>;
|
|
249
249
|
type YnsFindStripeAccountResult = {
|
|
250
|
+
stripeAccount: string | undefined;
|
|
251
|
+
storeId: string | undefined;
|
|
252
|
+
secretKey: string | undefined;
|
|
253
|
+
config: Config | undefined;
|
|
254
|
+
};
|
|
255
|
+
type YnsContextResult = {
|
|
250
256
|
stripeAccount: string | undefined;
|
|
251
257
|
storeId: string | undefined;
|
|
252
258
|
secretKey: string | undefined;
|
|
@@ -259,6 +265,6 @@ declare global {
|
|
|
259
265
|
*/
|
|
260
266
|
function __ynsFindStripeAccount(): YnsFindStripeAccountResult | undefined | Promise<YnsFindStripeAccountResult | undefined>;
|
|
261
267
|
}
|
|
262
|
-
declare const getYnsContext: () => Promise<
|
|
268
|
+
declare const getYnsContext: () => Promise<YnsContextResult>;
|
|
263
269
|
|
|
264
270
|
export { type Config, configSchema, getYnsContext };
|
package/dist/yns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"server-only";import{z as e}from"zod";var
|
|
1
|
+
import"server-only";import{z as e}from"zod";var i=e.object({hero:e.object({show:e.boolean(),title:e.string(),description:e.string(),button:e.object({label:e.string(),path:e.string()}),image:e.object({src:e.string(),alt:e.string()})}),categorySection:e.object({show:e.boolean()}),nav:e.object({title:e.string(),searchBar:e.object({show:e.boolean()}),links:e.array(e.object({label:e.string(),href:e.string()}))}),footer:e.object({name:e.string(),tagline:e.string(),newsletter:e.object({show:e.boolean()}),credits:e.boolean(),sections:e.array(e.object({header:e.string(),links:e.array(e.object({label:e.string(),href:e.string()}))}))})}),c=async()=>{let o={hero:{show:!0,title:"Discover our Curated Collection",description:"Explore our carefully selected products for your home and lifestyle.",button:{label:"Shop Now",path:"/"},image:{src:"https://files.stripe.com/links/MDB8YWNjdF8xT3BaeG5GSmNWbVh6bURsfGZsX3Rlc3RfaDVvWXowdU9ZbWlobUIyaHpNc1hCeDM200NBzvUjqP",alt:"Cup of coffee"}},categorySection:{show:!0},nav:{title:"Your Next Store",searchBar:{show:!0},links:[{label:"Home",href:"/"},{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},footer:{name:"Your Next Store",tagline:"Handcrafted with passion in California",newsletter:{show:!0},credits:!0,sections:[{header:"Products",links:[{label:"Apparel",href:"/category/apparel"},{label:"Accessories",href:"/category/accessories"}]},{header:"Support",links:[{label:"Features",href:"https://yournextstore.com/#features"},{label:"Pricing",href:"https://yournextstore.com/#pricing"},{label:"Contact Us",href:"mailto:hi@yournextstore.com"}]}]}},n={stripeAccount:void 0,storeId:void 0,secretKey:void 0,config:o},t=await global?.__ynsFindStripeAccount?.();return t?{...t,config:t.config??o}:n};export{i as configSchema,c as getYnsContext};
|