@sellforge/storefront 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +17 -1
- package/dist/index.cjs +34 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -3
- package/dist/index.d.ts +10 -3
- package/dist/index.js +34 -9
- package/dist/index.js.map +1 -1
- package/dist/sellforge.global.js +2 -2
- package/dist/sellforge.global.js.map +1 -1
- package/package.json +1 -1
package/dist/sellforge.global.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var Sellforge=(()=>{var A=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var R=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},ie=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of se(e))!oe.call(t,s)&&s!==n&&A(t,s,{get:()=>e[s],enumerable:!(r=ne(e,s))||r.enumerable});return t};var ae=t=>ie(A({},"__esModule",{value:!0}),t);var Ce={};R(Ce,{SellforgeError:()=>m,VERSION:()=>re,createStorefront:()=>we,fitsVehicle:()=>C,format:()=>v,html:()=>q,inputsOf:()=>x,isAvailable:()=>S,isSellforgeError:()=>U,matchLanguage:()=>_,priceOf:()=>b,toCart:()=>h});var m=class extends Error{constructor(n,r,s,o){super(r);this.name="SellforgeError";this.status=n,this.code=s??null,this.details=o??null}};function U(t){return t instanceof m||typeof t=="object"&&t!==null&&t.name==="SellforgeError"}var p={cart:"sellforge.cart",customer:"sellforge.customer",language:"sellforge.language"},ue="https://api.sellforge.ai",g=()=>typeof window<"u"&&typeof document<"u";function O(){let t=new Map;return{getItem:e=>t.has(e)?t.get(e):null,setItem:(e,n)=>void t.set(e,n),removeItem:e=>void t.delete(e)}}function $(t){let e=O(),n=()=>{try{return t()}catch{return}};return{getItem:r=>{try{let s=n();return s?s.getItem(r):e.getItem(r)}catch{return e.getItem(r)}},setItem:(r,s)=>{try{let o=n();o?o.setItem(r,s):e.setItem(r,s)}catch{e.setItem(r,s)}},removeItem:r=>{try{let s=n();s?s.removeItem(r):e.removeItem(r)}catch{e.removeItem(r)}}}}var P=class{constructor(e={}){this.listeners=new Map;if(e.publishableKey!==void 0&&!/^pk_sf_[A-Za-z0-9_-]+$/.test(e.publishableKey))throw new m(0,"publishableKey must start with pk_sf_. Never use a secret API token (sfk_\u2026) in a storefront.","invalid_key");if(this.key=e.publishableKey,this.hosted=!e.publishableKey,e.baseUrl)this.baseUrl=e.baseUrl.replace(/\/+$/,"");else if(e.publishableKey)this.baseUrl=ue;else if(g())this.baseUrl=`${window.location.origin}/_sellforge`;else throw new m(0,"Pass publishableKey (and optionally baseUrl) when not running inside a Sellforge-hosted online store.","missing_key");let n=e.fetch??(typeof fetch=="function"?fetch:void 0);if(!n)throw new m(0,"No fetch implementation available. Pass options.fetch.","missing_fetch");this.fetchFn=(r,s)=>n(r,s),this.origin=e.origin,this.attribution=e.attribution!==!1,this.extraHeaders={...e.headers??{}},this.timeoutMs=e.timeoutMs??3e4,this.catalogCacheMs=e.catalogCacheMs??6e4,this.store=e.storage??(g()?$(()=>window.localStorage):O()),this.session=e.sessionStorage??(g()?$(()=>window.sessionStorage):O()),this.lang=e.language??le()??this.store.getItem(p.language)}get language(){return this.lang}setLanguage(e,n=!0){this.lang=e,n&&(e?this.store.setItem(p.language,e):this.store.removeItem(p.language)),this.emit("language",e)}customer(){let e=this.session.getItem(p.customer);if(!e)return null;try{let n=JSON.parse(e);return n&&typeof n.token=="string"?n:null}catch{return null}}setCustomer(e){e?this.session.setItem(p.customer,JSON.stringify(e)):this.session.removeItem(p.customer),this.emit("customer",e?{id:e.id,email:e.email,name:e.name}:null)}on(e,n){let r=this.listeners.get(e)??new Set;return r.add(n),this.listeners.set(e,r),()=>r.delete(n)}emit(e,n){for(let r of this.listeners.get(e)??[])try{r(n)}catch{}}url(e,n){let r=this.baseUrl+e;if(n){let s=Object.entries(n).filter(([,o])=>o!=null&&o!=="").map(([o,l])=>`${encodeURIComponent(o)}=${encodeURIComponent(String(l))}`);s.length&&(r+=(r.includes("?")?"&":"?")+s.join("&"))}return r}async request(e,n={}){let r={Accept:n.blob?"application/pdf, */*":"application/json",...this.extraHeaders};n.body!==void 0&&(r["Content-Type"]="application/json"),this.key&&(r["X-Public-Key"]=this.key),this.lang&&(r["X-Sellforge-Language"]=this.lang),this.origin&&!g()&&(r.Origin=this.origin),this.attribution&&Object.assign(r,de());let s=n.auth||n.requireAuth?this.customer():null;if(n.requireAuth&&!s)throw new m(401,"Not logged in.","not_logged_in");s&&(r.Authorization=`Bearer ${s.token}`);let o=typeof AbortController=="function"?new AbortController:null,l=o?setTimeout(()=>o.abort(),this.timeoutMs):null,i;try{i=await this.fetchFn(this.url(e,n.query),{method:n.method??"GET",headers:r,body:n.body!==void 0?JSON.stringify(n.body):void 0,credentials:this.hosted?"same-origin":"omit",signal:o?.signal})}catch(d){let c=d?.name==="AbortError";throw new m(0,c?"Request timed out.":"Network error.",c?"timeout":"network_error",d)}finally{l&&clearTimeout(l)}if(i.ok&&n.blob)return await i.blob();if(i.status===204)return null;let u=await i.text();if(i.ok&&n.text)return u;let a=null;try{a=u?JSON.parse(u):null}catch{a=i.ok?u:null}if(!i.ok){let d=a??{};throw i.status===401&&s&&this.setCustomer(null),new m(i.status,d.message||d.error||`Request failed (${i.status})`,d.code??d.error??null,d.details??a)}return a}};function le(){if(!g())return null;try{let t=new URLSearchParams(window.location.search).get("lang");return t&&/^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i.test(t)?t:null}catch{return null}}function T(t){if(!g())return null;try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e&&e[1]?decodeURIComponent(e[1]):null}catch{return null}}function de(){let t={},e=T("sf_vid"),n=T("sf_sid"),r=T("sf_cmp");return e&&(t["X-SF-Visitor"]=e),n&&(t["X-SF-Session"]=n),r&&(t["X-SF-Campaign"]=r),t}var f=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function h(t){let e=t.totals??{},n=Array.isArray(t.line_items)?t.line_items:[],r=new Set,o=(Array.isArray(e.items)?e.items:[]).map(i=>{let u=n.findIndex((d,c)=>!r.has(c)&&(i.cartItemId?d.id===i.cartItemId:d.product_id===i.productId&&(d.variant_id??null)===(i.variantId??null)));u>=0&&r.add(u);let a=u>=0?n[u]:void 0;return{id:a?.id??i.cartItemId??"",product_id:i.productId,variant_id:i.variantId??null,name:i.productName??"",variant_name:i.variantName??null,image_url:i.imageUrl??null,sku:i.sku??null,quantity:f(i.quantity),unit_price_cents:f(i.unitPriceCents),line_total_cents:f(i.lineSubtotalCents),discount_cents:f(i.lineDiscountCents),combo_discount_cents:f(i.kombiRabattCents),combo_deal:i.kombiDealName??null,is_digital:!!i.isDigital,eingaben:i.eingaben??a?.eingaben??[]}}),l=Array.isArray(e.kombi_deals)?e.kombi_deals:[];return{id:t.cart.id,language:t.cart.language??null,discount_code:e.discount_code??t.cart.discount_code??null,lines:o,item_count:o.reduce((i,u)=>i+u.quantity,0),subtotal_cents:f(e.subtotal_cents),shipping_cents:f(e.shipping_cents),discount_cents:f(e.discount_cents),tax_cents:f(e.tax_cents),total_cents:f(e.total_cents),free_shipping:!!e.free_shipping,combo_discount_cents:f(e.kombi_rabatt_cents),combo_deals:l.map(i=>({id:i.deal_id,name:i.name,sets:i.saetze,discount_cents:i.rabatt_cents})),notices:Array.isArray(e.hinweise)?e.hinweise:[],errors:Array.isArray(e.errors)?e.errors:[],raw:t}}var N=(t,e)=>{let n=Math.floor(Number(t??1));if(!Number.isFinite(n)||n<e||n>999)throw new m(400,"Quantity must be between "+e+" and 999.","invalid_quantity");return n};function D(t){let e=()=>t.store.getItem(p.cart),n=u=>u?t.store.setItem(p.cart,u):t.store.removeItem(p.cart),r=u=>(t.emit("cart",u),u),s=async()=>{let u=await t.request("/api/store/cart",{method:"POST",body:{lang:t.language??void 0},auth:!0});return n(u.cart.id),u},o=async()=>{let u=e();if(!u)return s();try{return await t.request(`/api/store/cart/${encodeURIComponent(u)}`,{query:{lang:t.language}})}catch(a){if(a instanceof m&&(a.status===404||a.status===400))return s();throw a}},l=(u,a)=>({product_id:u,variant_id:a.variantId||void 0,option_value_ids:a.optionValueIds?.length?a.optionValueIds:void 0,quantity:N(a.quantity,1),eingaben:a.inputs&&Object.keys(a.inputs).length?a.inputs:void 0});return{id:e,async get(){return h(await o())},async add(u,a={}){let d=l(u,a),c=await o(),y=await t.request(`/api/store/cart/${encodeURIComponent(c.cart.id)}/items`,{method:"POST",body:d});return r(h(y))},async addMany(u){let a=u.filter(c=>c?.productId).map(c=>l(c.productId,c)),d=await o();for(let c of a)d=await t.request(`/api/store/cart/${encodeURIComponent(d.cart.id)}/items`,{method:"POST",body:c});return r(h(d))},async update(u,a){let d={};if(a.quantity!==void 0&&(d.quantity=N(a.quantity,0)),a.inputs!==void 0&&(d.eingaben=a.inputs),!Object.keys(d).length)throw new m(400,"Pass quantity or inputs.","nothing_to_update");let c=await o(),y=await t.request(`/api/store/cart/${encodeURIComponent(c.cart.id)}/items/${encodeURIComponent(u)}`,{method:"PATCH",body:d});return r(h(y))},async remove(u){let a=await o(),d=await t.request(`/api/store/cart/${encodeURIComponent(a.cart.id)}/items/${encodeURIComponent(u)}`,{method:"DELETE"});return r(h(d))},async applyDiscount(u){let a=await o(),d=await t.request(`/api/store/cart/${encodeURIComponent(a.cart.id)}/discount`,{method:"POST",body:{code:u.trim()}});return r(h(d))},async removeDiscount(){let u=await o(),a=await t.request(`/api/store/cart/${encodeURIComponent(u.cart.id)}/discount`,{method:"POST",body:{code:null}});return r(h(a))},async setDetails(u){let a=await o(),d=await t.request(`/api/store/cart/${encodeURIComponent(a.cart.id)}`,{method:"PATCH",body:{customer_email:u.email,shipping_address:u.shippingAddress,billing_address:u.billingAddress,shipping_method:u.shippingMethod}});return r(h(d))},clear(){n(null),r(null)},onChange(u){return t.on("cart",u)}}}function C(t,e){return!e||!e.makeId&&!e.modelId&&!e.year?!0:(t.fitment??[]).some(n=>{if(e.makeId&&n.make_id!==e.makeId||e.modelId&&n.model_id&&n.model_id!==e.modelId)return!1;let r=Number(e.year??0);return!(r&&(n.year_from&&r<n.year_from||n.year_to&&r>n.year_to))})}function S(t){return t.available===!1?!1:!t.track_stock||!t.variants?.length?!0:t.variants.some(e=>Number(e.stock??0)>0)}function b(t,e){let n=e?t.variants?.find(o=>o.id===e):void 0,r=n&&n.price_cents!=null?n.price_cents:t.base_price_cents,s=n&&n.compare_at_price_cents||t.metadata?.compare_at_price_cents||null;return{price_cents:r,compare_at_price_cents:s&&s>r?s:null}}function x(t){let e=t.metadata?.kunden_eingaben;return Array.isArray(e)?e.map(n=>({...n,type:n.type??"text",required:!!n.required,options:n.options??null,placeholder:n.placeholder??null})):[]}function B(t){let e=null,n=null,r=()=>e&&e.lang===t.language&&Date.now()-e.at<t.catalogCacheMs?Promise.resolve(e.products):(n??(n=t.request("/api/store/products").then(s=>{let o=s?.products??[];return e={at:Date.now(),lang:t.language,products:o},o}).finally(()=>{n=null})),n);return t.on("language",()=>{e=null}),{async products(s={}){let o=(s.query??"").trim().toLowerCase(),l=(await r()).filter(c=>s.categoryId&&c.category_id!==s.categoryId||s.brandId&&c.brand_id!==s.brandId||s.inStock&&!S(c)||o&&!`${c.name} ${c.sku??""} ${c.short_description??""} ${c.brand??""}`.toLowerCase().includes(o)?!1:C(c,s.vehicle)),i={price_asc:(c,y)=>b(c).price_cents-b(y).price_cents,price_desc:(c,y)=>b(y).price_cents-b(c).price_cents,name:(c,y)=>c.name.localeCompare(y.name)},u=s.sort?i[s.sort]:void 0;u&&(l=[...l].sort(u));let a=l.length,d=Math.max(0,s.offset??0);return{products:l.slice(d,s.limit?d+s.limit:void 0),total:a}},async product(s){return(await r()).find(o=>o.slug===s||o.id===s)??null},search(s={}){let o=s.vehicle;return t.request("/api/store/search",{query:{q:s.query??"",kategorie:s.categoryId,marke_id:s.brandId,marke:s.brand,make_id:o?.makeId,model_id:o?.modelId,jahr:o?.year,lieferbar:s.inStock?"1":void 0,preis_von:s.minPrice,preis_bis:s.maxPrice,sortierung:s.sort?{relevance:"relevanz",price_asc:"preis_auf",price_desc:"preis_ab",newest:"neu"}[s.sort]:void 0,seite:s.page,pro_seite:s.perPage}})},async categories(){return(await t.request("/api/categories"))?.categories??[]},async brands(){let s=await t.request("/api/brands");return Array.isArray(s)?s:s?.brands??[]},async comboDeals(s){return(await t.request("/api/store/kombi-deals",{query:{produkt:s}}))?.deals??[]},structuredData(s){return t.request(`/api/store/google-merchant/produkt/${encodeURIComponent(s)}`)},sitemapXml(){return t.request("/api/store/google-merchant/sitemap.xml",{text:!0})},refresh(){e=null},fitsVehicle:C,isAvailable:S,priceOf:b,inputsOf:x}}function V(t){return{async makes(){return(await t.request("/api/vehicle-makes"))?.makes??[]},async models(e){return(await t.request(`/api/vehicle-makes/${encodeURIComponent(e)}/models`))?.models??[]},async yearGroups(e){return(await t.request(`/api/vehicle-models/${encodeURIComponent(e)}/year-groups`))?.year_groups??[]},fits:C}}var F=()=>{if(!g())throw new m(400,"returnUrl is required outside the browser.","return_url_required");return`${window.location.origin}/checkout/result`},ce=t=>t.length?Object.fromEntries(t.map(e=>[e.key,e.value])):void 0,K=t=>t&&typeof t=="object"&&Object.keys(t).length?t:void 0;function H(t,e){let n=async s=>(await t.request(`/api/store/orders/${encodeURIComponent(s)}`)).order,r={async createSession(s={}){let o=null,l=s.items;if(!l){if(o=await e.get(),!o.lines.length)throw new m(400,"The cart is empty.","cart_empty");l=o.lines.map(a=>({productId:a.product_id,variantId:a.variant_id??void 0,quantity:a.quantity,inputs:ce(a.eingaben)}))}let i=o?.raw.cart,u=t.customer();return t.request("/api/store/checkout-sessions",{method:"POST",auth:!0,body:{items:l.map(a=>({product_id:a.productId,variant_id:a.variantId||void 0,quantity:a.quantity,eingaben:a.inputs&&Object.keys(a.inputs).length?a.inputs:void 0})),return_url:s.returnUrl??F(),lang:s.language??t.language??void 0,customer:{email:s.email??i?.customer_email??u?.email??void 0,customer_id:u?.id,billing_address:s.billingAddress??K(i?.billing_address),shipping_address:s.shippingAddress??K(i?.shipping_address),shipping_method:s.shippingMethod??i?.shipping_method??void 0,discount_code:s.discountCode??o?.discount_code??void 0}}})},async start(s={}){let o=await r.createSession(s);if(!g())throw new m(400,"start() needs a browser; use createSession() on a server.","browser_required");return window.location.assign(o.url),new Promise(()=>{})},async result(s){let o=new URL(String(s??(g()?window.location.href:"")),g()?window.location.href:void 0),l=o.searchParams.get("status");if(!l)return null;let i=l==="success",u=o.searchParams.get("order_id");i&&e.clear();let a=null;return u&&(a=await n(u).catch(()=>null)),{status:l,success:i,sessionId:o.searchParams.get("session_id"),orderId:u,signature:o.searchParams.get("sig"),order:a}},order:n,validateDiscount(s,o,l={}){return t.request("/api/store/discounts/validate",{method:"POST",body:{code:s,order_subtotal_cents:Math.max(0,Math.round(o)),email:l.email,customer_id:l.customerId??t.customer()?.id}})},async plans(){return(await t.request("/api/store/abo-plans"))?.plans??[]},subscribe(s){return t.request("/api/store/abo-sessions",{method:"POST",body:{plan_id:s.planId,return_url:s.returnUrl??F(),customer_email:s.email??t.customer()?.email??void 0,affiliate_code:s.affiliateCode}})},async startSubscription(s){let o=await r.subscribe(s);if(!g())throw new m(400,"startSubscription() needs a browser; use subscribe() on a server.","browser_required");return window.location.assign(o.url),new Promise(()=>{})}};return r}function j(t){let e=r=>r?{id:r.id,email:r.email,name:r.name}:null,n=r=>{if(r.twofa_required&&r.twofa_token)return{twoFactorRequired:!0,twoFactorToken:r.twofa_token};if(!r.token||!r.user)throw new m(500,"Unexpected login response.","unexpected_response");if(r.user.role&&r.user.role!=="customer")throw new m(403,"Only customer accounts can sign in to a shop. Manage the shop at app.sellforge.ai.","not_a_customer");let s={token:r.token,id:r.user.id,email:r.user.email,name:r.user.display_name??null};return t.setCustomer(s),{twoFactorRequired:!1,customer:e(s)}};return{customer(){return e(t.customer())},isLoggedIn(){return!!t.customer()},async register(r){let s=await t.request("/api/auth/register",{method:"POST",body:{email:r.email,password:r.password,display_name:r.name||r.email,marketing_consent:r.marketingConsent===!0?!0:void 0}}),o=n(s);if(o.twoFactorRequired)throw new m(500,"Unexpected two-factor step after registration.","unexpected_response");return o.customer},async login(r,s){return n(await t.request("/api/auth/login",{method:"POST",body:{email:r,password:s}}))},async verifyTwoFactor(r,s,o={}){let l=n(await t.request("/api/auth/2fa/verify",{method:"POST",body:{twofa_token:r,code:s,is_backup_code:o.backupCode?!0:void 0}}));if(l.twoFactorRequired)throw new m(500,"Unexpected login response.","unexpected_response");return l.customer},logout(){t.setCustomer(null)},async requestPasswordReset(r){await t.request("/api/auth/forgot-password",{method:"POST",body:{email:r}})},async resetPassword(r,s){return n(await t.request("/api/auth/reset-password",{method:"POST",body:{token:r,password:s}}))},async verifyEmail(r){await t.request("/api/auth/verify-email",{method:"POST",body:{token:r}})},async resendVerification(r){await t.request("/api/auth/resend-verification",{method:"POST",body:{email:r}})},async updateProfile(r){let s=await t.request("/api/customer/me",{method:"PATCH",requireAuth:!0,body:{display_name:r.name}}),o=t.customer();return o&&t.setCustomer({...o,name:s.user.display_name??null}),{id:s.user.id,email:s.user.email,name:s.user.display_name??null}},async changePassword(r,s){await t.request("/api/customer/me/password",{method:"POST",requireAuth:!0,body:{current_password:r,new_password:s}})},async orders(){return(await t.request("/api/customer/orders",{requireAuth:!0})).orders??[]},order(r){return t.request(`/api/customer/orders/${encodeURIComponent(r)}`,{requireAuth:!0})},orderInvoice(r){return t.request(`/api/customer/orders/${encodeURIComponent(r)}/invoice`,{requireAuth:!0,blob:!0})},async invoices(){return(await t.request("/api/customer/invoices",{requireAuth:!0})).invoices??[]},invoicePdf(r){return t.request(`/api/customer/invoices/${encodeURIComponent(r)}/pdf`,{requireAuth:!0,blob:!0})},async addresses(){return(await t.request("/api/customer/addresses",{requireAuth:!0})).addresses??[]},async createAddress(r){return(await t.request("/api/customer/addresses",{method:"POST",requireAuth:!0,body:r})).address},async updateAddress(r,s){return(await t.request(`/api/customer/addresses/${encodeURIComponent(r)}`,{method:"PATCH",requireAuth:!0,body:s})).address},async deleteAddress(r){await t.request(`/api/customer/addresses/${encodeURIComponent(r)}`,{method:"DELETE",requireAuth:!0})},async subscriptions(){return(await t.request("/api/customer/abos",{requireAuth:!0})).abos??[]},cancelSubscription(r){return t.request(`/api/customer/abos/${encodeURIComponent(r)}/kuendigen`,{method:"POST",requireAuth:!0})},exportData(){return t.request("/api/customer/me/export",{requireAuth:!0})},async deleteAccount(r){await t.request("/api/customer/me/delete",{method:"POST",requireAuth:!0,body:{password:r,confirm:"DELETE"}}),t.setCustomer(null)},lookupOrder(r){return t.request("/api/customer/order-lookup",{query:{display_id:String(r.orderNumber).replace(/^#/,""),email:r.email,postal_code:r.postalCode}})},onChange(r){return t.on("customer",r)}}}var q={};R(q,{escape:()=>L,isSafeUrl:()=>M,markdown:()=>k,sanitize:()=>he});var me={"&":"&","<":"<",">":">",'"':""","'":"'"};function L(t){return String(t??"").replace(/[&<>"']/g,e=>me[e])}var ge=new Set(["P","BR","STRONG","B","EM","I","U","S","A","UL","OL","LI","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","CODE","PRE","HR","IMG","TABLE","THEAD","TBODY","TR","TH","TD","SPAN","DIV","SMALL","SUP","SUB","FIGURE","FIGCAPTION"]),pe=new Set(["href","src","alt","title","class","colspan","rowspan","width","height"]),fe=/^(SCRIPT|STYLE|IFRAME|OBJECT|EMBED|TEMPLATE|NOSCRIPT|SVG|MATH|FORM|INPUT|BUTTON|TEXTAREA|SELECT|LINK|META|BASE)$/;function M(t,e=!1){let n=String(t||"").trim();return/^https:/i.test(n)||!e&&/^(http:|mailto:|tel:)/i.test(n)?!0:/^[a-z][a-z0-9+.-]*:/i.test(n)||/^\/\//.test(n)?!1:n.length>0}function he(t){let e=String(t??"");if(typeof DOMParser>"u")return L(e);let r=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html").body.firstElementChild;if(!r)return"";let s=o=>{for(let l of Array.from(o.childNodes)){if(l.nodeType===3)continue;if(l.nodeType!==1){o.removeChild(l);continue}let i=l;if(!ge.has(i.nodeName)){if(!fe.test(i.nodeName))for(s(i);i.firstChild;)o.insertBefore(i.firstChild,i);o.removeChild(i);continue}for(let u of Array.from(i.attributes)){let a=u.name.toLowerCase();(!pe.has(a)||(a==="href"||a==="src")&&!M(u.value,a==="src"))&&i.removeAttribute(u.name)}i.nodeName==="A"&&(i.setAttribute("rel","noopener noreferrer"),/^https?:/i.test(i.getAttribute("href")??"")&&i.setAttribute("target","_blank")),s(i)}};return s(r),r.innerHTML}function E(t){return L(t).replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[^*])\*([^*]+)\*/g,"$1<em>$2</em>").replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(e,n,r)=>{let s=r.replace(/&/g,"&");return M(s)?`<a href="${r}" rel="noopener noreferrer">${n}</a>`:n})}function k(t){let e=[],n=null,r=[],s=()=>{r.length&&(e.push(`<p>${r.map(E).join("<br>")}</p>`),r=[])},o=()=>{n&&(e.push(`<${n.tag}>${n.items.map(l=>`<li>${E(l)}</li>`).join("")}</${n.tag}>`),n=null)};for(let l of String(t??"").split(/\r?\n/)){let i=/^(#{1,6})\s+(.*)$/.exec(l),u=/^\s*[-*]\s+(.*)$/.exec(l),a=/^\s*\d+[.)]\s+(.*)$/.exec(l);if(!l.trim()){s(),o();continue}if(i){s(),o(),e.push(`<h${i[1].length}>${E(i[2])}</h${i[1].length}>`);continue}if(/^---+$/.test(l.trim())){s(),o(),e.push("<hr>");continue}if(u||a){s();let d=u?"ul":"ol",c=n;(!c||c.tag!==d)&&(o(),n={tag:d,items:[]}),n.items.push((u??a)[1]);continue}o(),r.push(l.trim())}return s(),o(),e.join(`
|
|
2
|
-
`)}var I=t=>t.catch(e=>{if(e instanceof m&&e.status===404)return null;throw e});function
|
|
1
|
+
"use strict";var Sellforge=(()=>{var R=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var ae=Object.prototype.hasOwnProperty;var A=(t,e)=>{for(var n in e)R(t,n,{get:e[n],enumerable:!0})},ue=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ie(e))!ae.call(t,s)&&s!==n&&R(t,s,{get:()=>e[s],enumerable:!(r=oe(e,s))||r.enumerable});return t};var le=t=>ue(R({},"__esModule",{value:!0}),t);var Se={};A(Se,{SellforgeError:()=>m,VERSION:()=>se,createStorefront:()=>Pe,fitsVehicle:()=>C,format:()=>v,html:()=>q,inputsOf:()=>L,isAvailable:()=>S,isSellforgeError:()=>$,matchLanguage:()=>_,priceOf:()=>b,toCart:()=>y});var m=class extends Error{constructor(n,r,s,o){super(r);this.name="SellforgeError";this.status=n,this.code=s??null,this.details=o??null}};function $(t){return t instanceof m||typeof t=="object"&&t!==null&&t.name==="SellforgeError"}var f={cart:"sellforge.cart",customer:"sellforge.customer",language:"sellforge.language"},de="https://api.sellforge.ai",g=()=>typeof window<"u"&&typeof document<"u",ce=t=>t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost");function O(t){try{let e=new URL(t);return e.username||e.password?!1:e.protocol==="https:"||e.protocol==="http:"&&ce(e.hostname)}catch{return!1}}function x(){let t=new Map;return{getItem:e=>t.has(e)?t.get(e):null,setItem:(e,n)=>void t.set(e,n),removeItem:e=>void t.delete(e)}}function N(t){let e=x(),n=()=>{try{return t()}catch{return}};return{getItem:r=>{try{let s=n();return s?s.getItem(r):e.getItem(r)}catch{return e.getItem(r)}},setItem:(r,s)=>{try{let o=n();o?o.setItem(r,s):e.setItem(r,s)}catch{e.setItem(r,s)}},removeItem:r=>{try{let s=n();s?s.removeItem(r):e.removeItem(r)}catch{e.removeItem(r)}}}}var P=class{constructor(e={}){this.listeners=new Map;if(e.publishableKey!==void 0&&!/^pk_sf_[A-Za-z0-9_-]+$/.test(e.publishableKey))throw new m(0,"publishableKey must start with pk_sf_. Never use a secret API token (sfk_\u2026) in a storefront.","invalid_key");if(this.key=e.publishableKey,this.hosted=!e.publishableKey,e.baseUrl){if(!O(e.baseUrl))throw new m(0,"baseUrl must be an https:// URL (http:// only for localhost).","invalid_base_url");this.baseUrl=e.baseUrl.replace(/\/+$/,"")}else if(e.publishableKey)this.baseUrl=de;else if(g())this.baseUrl=`${window.location.origin}/_sellforge`;else throw new m(0,"Pass publishableKey (and optionally baseUrl) when not running inside a Sellforge-hosted online store.","missing_key");let n=e.fetch??(typeof fetch=="function"?fetch:void 0);if(!n)throw new m(0,"No fetch implementation available. Pass options.fetch.","missing_fetch");this.fetchFn=(r,s)=>n(r,s),this.origin=e.origin,this.attribution=e.attribution!==!1,this.extraHeaders={...e.headers??{}},this.timeoutMs=e.timeoutMs??3e4,this.catalogCacheMs=e.catalogCacheMs??6e4,this.store=e.storage??(g()?N(()=>window.localStorage):x()),this.session=e.sessionStorage??(g()?N(()=>window.sessionStorage):x()),this.lang=e.language??me()??this.store.getItem(f.language)}get language(){return this.lang}setLanguage(e,n=!0){this.lang=e,n&&(e?this.store.setItem(f.language,e):this.store.removeItem(f.language)),this.emit("language",e)}customer(){let e=this.session.getItem(f.customer);if(!e)return null;try{let n=JSON.parse(e);return n&&typeof n.token=="string"?n:null}catch{return null}}setCustomer(e){e?this.session.setItem(f.customer,JSON.stringify(e)):this.session.removeItem(f.customer),this.emit("customer",e?{id:e.id,email:e.email,name:e.name}:null)}on(e,n){let r=this.listeners.get(e)??new Set;return r.add(n),this.listeners.set(e,r),()=>r.delete(n)}emit(e,n){for(let r of this.listeners.get(e)??[])try{r(n)}catch{}}url(e,n){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e))throw new m(0,'Request paths must start with a single "/" (e.g. /api/store/products).',"invalid_path");let r=this.baseUrl+e;if(n){let s=Object.entries(n).filter(([,o])=>o!=null&&o!=="").map(([o,l])=>`${encodeURIComponent(o)}=${encodeURIComponent(String(l))}`);s.length&&(r+=(r.includes("?")?"&":"?")+s.join("&"))}return r}async request(e,n={}){let r={Accept:n.blob?"application/pdf, */*":"application/json",...this.extraHeaders};n.body!==void 0&&(r["Content-Type"]="application/json"),this.key&&(r["X-Public-Key"]=this.key),this.lang&&(r["X-Sellforge-Language"]=this.lang),this.origin&&!g()&&(r.Origin=this.origin),this.attribution&&Object.assign(r,ge());let s=n.auth||n.requireAuth?this.customer():null;if(n.requireAuth&&!s)throw new m(401,"Not logged in.","not_logged_in");s&&(r.Authorization=`Bearer ${s.token}`);let o=this.url(e,n.query),l=typeof AbortController=="function"?new AbortController:null,a=l?setTimeout(()=>l.abort(),this.timeoutMs):null,i;try{i=await this.fetchFn(o,{method:n.method??"GET",headers:r,body:n.body!==void 0?JSON.stringify(n.body):void 0,credentials:this.hosted?"same-origin":"omit",signal:l?.signal})}catch(d){let p=d?.name==="AbortError";throw new m(0,p?"Request timed out.":"Network error.",p?"timeout":"network_error",d)}finally{a&&clearTimeout(a)}if(i.ok&&n.blob)return await i.blob();if(i.status===204)return null;let u=await i.text();if(i.ok&&n.text)return u;let c=null;try{c=u?JSON.parse(u):null}catch{c=i.ok?u:null}if(!i.ok){let d=c??{};throw i.status===401&&s&&this.setCustomer(null),new m(i.status,d.message||d.error||`Request failed (${i.status})`,d.code??d.error??null,d.details??c)}return c}};function me(){if(!g())return null;try{let t=new URLSearchParams(window.location.search).get("lang");return t&&/^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i.test(t)?t:null}catch{return null}}function T(t){if(!g())return null;try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e&&e[1]?decodeURIComponent(e[1]):null}catch{return null}}function ge(){let t={},e=T("sf_vid"),n=T("sf_sid"),r=T("sf_cmp");return e&&(t["X-SF-Visitor"]=e),n&&(t["X-SF-Session"]=n),r&&(t["X-SF-Campaign"]=r),t}var h=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function y(t){let e=t.totals??{},n=Array.isArray(t.line_items)?t.line_items:[],r=new Set,o=(Array.isArray(e.items)?e.items:[]).map(a=>{let i=n.findIndex((c,d)=>!r.has(d)&&(a.cartItemId?c.id===a.cartItemId:c.product_id===a.productId&&(c.variant_id??null)===(a.variantId??null)));i>=0&&r.add(i);let u=i>=0?n[i]:void 0;return{id:u?.id??a.cartItemId??"",product_id:a.productId,variant_id:a.variantId??null,name:a.productName??"",variant_name:a.variantName??null,image_url:a.imageUrl??null,sku:a.sku??null,quantity:h(a.quantity),unit_price_cents:h(a.unitPriceCents),line_total_cents:h(a.lineSubtotalCents),discount_cents:h(a.lineDiscountCents),combo_discount_cents:h(a.kombiRabattCents),combo_deal:a.kombiDealName??null,is_digital:!!a.isDigital,eingaben:a.eingaben??u?.eingaben??[]}}),l=Array.isArray(e.kombi_deals)?e.kombi_deals:[];return{id:t.cart.id,language:t.cart.language??null,discount_code:e.discount_code??t.cart.discount_code??null,lines:o,item_count:o.reduce((a,i)=>a+i.quantity,0),subtotal_cents:h(e.subtotal_cents),shipping_cents:h(e.shipping_cents),discount_cents:h(e.discount_cents),tax_cents:h(e.tax_cents),total_cents:h(e.total_cents),free_shipping:!!e.free_shipping,combo_discount_cents:h(e.kombi_rabatt_cents),combo_deals:l.map(a=>({id:a.deal_id,name:a.name,sets:a.saetze,discount_cents:a.rabatt_cents})),notices:Array.isArray(e.hinweise)?e.hinweise:[],errors:Array.isArray(e.errors)?e.errors:[],raw:t}}var D=(t,e)=>{let n=Math.floor(Number(t??1));if(!Number.isFinite(n)||n<e||n>999)throw new m(400,"Quantity must be between "+e+" and 999.","invalid_quantity");return n};function B(t){let e=()=>t.store.getItem(f.cart),n=i=>i?t.store.setItem(f.cart,i):t.store.removeItem(f.cart),r=i=>(t.emit("cart",i),i),s=async()=>{let i=await t.request("/api/store/cart",{method:"POST",body:{lang:t.language??void 0},auth:!0});return n(i.cart.id),i},o=async()=>{let i=e();if(!i)return s();try{return await t.request(`/api/store/cart/${encodeURIComponent(i)}`,{query:{lang:t.language}})}catch(u){if(u instanceof m&&(u.status===404||u.status===400))return s();throw u}},l=(i,u)=>({product_id:i,variant_id:u.variantId||void 0,option_value_ids:u.optionValueIds?.length?u.optionValueIds:void 0,quantity:D(u.quantity,1),eingaben:u.inputs&&Object.keys(u.inputs).length?u.inputs:void 0});return{id:e,async get(){return y(await o())},async add(i,u={}){let c=l(i,u),d=await o(),p=await t.request(`/api/store/cart/${encodeURIComponent(d.cart.id)}/items`,{method:"POST",body:c});return r(y(p))},async addMany(i){let u=i.filter(d=>d?.productId).map(d=>l(d.productId,d)),c=await o();for(let d of u)c=await t.request(`/api/store/cart/${encodeURIComponent(c.cart.id)}/items`,{method:"POST",body:d});return r(y(c))},async update(i,u){let c={};if(u.quantity!==void 0&&(c.quantity=D(u.quantity,0)),u.inputs!==void 0&&(c.eingaben=u.inputs),!Object.keys(c).length)throw new m(400,"Pass quantity or inputs.","nothing_to_update");let d=await o(),p=await t.request(`/api/store/cart/${encodeURIComponent(d.cart.id)}/items/${encodeURIComponent(i)}`,{method:"PATCH",body:c});return r(y(p))},async remove(i){let u=await o(),c=await t.request(`/api/store/cart/${encodeURIComponent(u.cart.id)}/items/${encodeURIComponent(i)}`,{method:"DELETE"});return r(y(c))},async applyDiscount(i){let u=await o(),c=await t.request(`/api/store/cart/${encodeURIComponent(u.cart.id)}/discount`,{method:"POST",body:{code:i.trim()}});return r(y(c))},async removeDiscount(){let i=await o(),u=await t.request(`/api/store/cart/${encodeURIComponent(i.cart.id)}/discount`,{method:"POST",body:{code:null}});return r(y(u))},async setDetails(i){let u=await o(),c=await t.request(`/api/store/cart/${encodeURIComponent(u.cart.id)}`,{method:"PATCH",body:{customer_email:i.email,shipping_address:i.shippingAddress,billing_address:i.billingAddress,shipping_method:i.shippingMethod}});return r(y(c))},clear(){n(null),r(null)},onChange(i){return t.on("cart",i)}}}function C(t,e){return!e||!e.makeId&&!e.modelId&&!e.year?!0:(t.fitment??[]).some(n=>{if(e.makeId&&n.make_id!==e.makeId||e.modelId&&n.model_id&&n.model_id!==e.modelId)return!1;let r=Number(e.year??0);return!(r&&(n.year_from&&r<n.year_from||n.year_to&&r>n.year_to))})}function S(t){return t.available===!1?!1:!t.track_stock||!t.variants?.length?!0:t.variants.some(e=>Number(e.stock??0)>0)}function b(t,e){let n=e?t.variants?.find(o=>o.id===e):void 0,r=n&&n.price_cents!=null?n.price_cents:t.base_price_cents,s=n&&n.compare_at_price_cents||t.metadata?.compare_at_price_cents||null;return{price_cents:r,compare_at_price_cents:s&&s>r?s:null}}function L(t){let e=t.metadata?.kunden_eingaben;return Array.isArray(e)?e.map(n=>({...n,type:n.type??"text",required:!!n.required,options:n.options??null,placeholder:n.placeholder??null})):[]}function V(t){let e=null,n=null,r=()=>e&&e.lang===t.language&&Date.now()-e.at<t.catalogCacheMs?Promise.resolve(e.products):(n??(n=t.request("/api/store/products").then(s=>{let o=s?.products??[];return e={at:Date.now(),lang:t.language,products:o},o}).finally(()=>{n=null})),n);return t.on("language",()=>{e=null}),{async products(s={}){let o=(s.query??"").trim().toLowerCase(),l=(await r()).filter(d=>s.categoryId&&d.category_id!==s.categoryId||s.brandId&&d.brand_id!==s.brandId||s.inStock&&!S(d)||o&&!`${d.name} ${d.sku??""} ${d.short_description??""} ${d.brand??""}`.toLowerCase().includes(o)?!1:C(d,s.vehicle)),a={price_asc:(d,p)=>b(d).price_cents-b(p).price_cents,price_desc:(d,p)=>b(p).price_cents-b(d).price_cents,name:(d,p)=>d.name.localeCompare(p.name)},i=s.sort?a[s.sort]:void 0;i&&(l=[...l].sort(i));let u=l.length,c=Math.max(0,s.offset??0);return{products:l.slice(c,s.limit?c+s.limit:void 0),total:u}},async product(s){return(await r()).find(o=>o.slug===s||o.id===s)??null},search(s={}){let o=s.vehicle;return t.request("/api/store/search",{query:{q:s.query??"",kategorie:s.categoryId,marke_id:s.brandId,marke:s.brand,make_id:o?.makeId,model_id:o?.modelId,jahr:o?.year,lieferbar:s.inStock?"1":void 0,preis_von:s.minPrice,preis_bis:s.maxPrice,sortierung:s.sort?{relevance:"relevanz",price_asc:"preis_auf",price_desc:"preis_ab",newest:"neu"}[s.sort]:void 0,seite:s.page,pro_seite:s.perPage}})},async categories(){return(await t.request("/api/categories"))?.categories??[]},async brands(){let s=await t.request("/api/brands");return Array.isArray(s)?s:s?.brands??[]},async comboDeals(s){return(await t.request("/api/store/kombi-deals",{query:{produkt:s}}))?.deals??[]},structuredData(s){return t.request(`/api/store/google-merchant/produkt/${encodeURIComponent(s)}`)},sitemapXml(){return t.request("/api/store/google-merchant/sitemap.xml",{text:!0})},refresh(){e=null},fitsVehicle:C,isAvailable:S,priceOf:b,inputsOf:L}}function F(t){return{async makes(){return(await t.request("/api/vehicle-makes"))?.makes??[]},async models(e){return(await t.request(`/api/vehicle-makes/${encodeURIComponent(e)}/models`))?.models??[]},async yearGroups(e){return(await t.request(`/api/vehicle-models/${encodeURIComponent(e)}/year-groups`))?.year_groups??[]},fits:C}}var H=()=>{if(!g())throw new m(400,"returnUrl is required outside the browser.","return_url_required");return`${window.location.origin}/checkout/result`},K=t=>{if(typeof t!="string"||!O(t))throw new m(502,"The checkout returned an unexpected payment address.","invalid_checkout_url");return t},pe=t=>t.length?Object.fromEntries(t.map(e=>[e.key,e.value])):void 0,j=t=>t&&typeof t=="object"&&Object.keys(t).length?t:void 0;function G(t,e){let n=async s=>(await t.request(`/api/store/orders/${encodeURIComponent(s)}`)).order,r={async createSession(s={}){let o=null,l=s.items;if(!l){if(o=await e.get(),!o.lines.length)throw new m(400,"The cart is empty.","cart_empty");l=o.lines.map(u=>({productId:u.product_id,variantId:u.variant_id??void 0,quantity:u.quantity,inputs:pe(u.eingaben)}))}let a=o?.raw.cart,i=t.customer();return t.request("/api/store/checkout-sessions",{method:"POST",auth:!0,body:{items:l.map(u=>({product_id:u.productId,variant_id:u.variantId||void 0,quantity:u.quantity,eingaben:u.inputs&&Object.keys(u.inputs).length?u.inputs:void 0})),return_url:s.returnUrl??H(),lang:s.language??t.language??void 0,customer:{email:s.email??a?.customer_email??i?.email??void 0,customer_id:i?.id,billing_address:s.billingAddress??j(a?.billing_address),shipping_address:s.shippingAddress??j(a?.shipping_address),shipping_method:s.shippingMethod??a?.shipping_method??void 0,discount_code:s.discountCode??o?.discount_code??void 0}}})},async start(s={}){let o=await r.createSession(s);if(!g())throw new m(400,"start() needs a browser; use createSession() on a server.","browser_required");return window.location.assign(K(o.url)),new Promise(()=>{})},async result(s){let o=new URL(String(s??(g()?window.location.href:"")),g()?window.location.href:void 0),l=o.searchParams.get("status");if(!l)return null;let a=l==="success",i=o.searchParams.get("order_id");a&&e.clear();let u=null;return i&&(u=await n(i).catch(()=>null)),{status:l,success:a,sessionId:o.searchParams.get("session_id"),orderId:i,signature:o.searchParams.get("sig"),order:u}},order:n,validateDiscount(s,o,l={}){return t.request("/api/store/discounts/validate",{method:"POST",body:{code:s,order_subtotal_cents:Math.max(0,Math.round(o)),email:l.email,customer_id:l.customerId??t.customer()?.id}})},async plans(){return(await t.request("/api/store/abo-plans"))?.plans??[]},subscribe(s){return t.request("/api/store/abo-sessions",{method:"POST",body:{plan_id:s.planId,return_url:s.returnUrl??H(),customer_email:s.email??t.customer()?.email??void 0,affiliate_code:s.affiliateCode}})},async startSubscription(s){let o=await r.subscribe(s);if(!g())throw new m(400,"startSubscription() needs a browser; use subscribe() on a server.","browser_required");return window.location.assign(K(o.url)),new Promise(()=>{})}};return r}function z(t){let e=r=>r?{id:r.id,email:r.email,name:r.name}:null,n=r=>{if(r.twofa_required&&r.twofa_token)return{twoFactorRequired:!0,twoFactorToken:r.twofa_token};if(!r.token||!r.user)throw new m(500,"Unexpected login response.","unexpected_response");if(r.user.role&&r.user.role!=="customer")throw new m(403,"Only customer accounts can sign in to a shop. Manage the shop at app.sellforge.ai.","not_a_customer");let s={token:r.token,id:r.user.id,email:r.user.email,name:r.user.display_name??null};return t.setCustomer(s),{twoFactorRequired:!1,customer:e(s)}};return{customer(){return e(t.customer())},isLoggedIn(){return!!t.customer()},async register(r){let s=await t.request("/api/auth/register",{method:"POST",body:{email:r.email,password:r.password,display_name:r.name||r.email,marketing_consent:r.marketingConsent===!0?!0:void 0}}),o=n(s);if(o.twoFactorRequired)throw new m(500,"Unexpected two-factor step after registration.","unexpected_response");return o.customer},async login(r,s){return n(await t.request("/api/auth/login",{method:"POST",body:{email:r,password:s}}))},async verifyTwoFactor(r,s,o={}){let l=n(await t.request("/api/auth/2fa/verify",{method:"POST",body:{twofa_token:r,code:s,is_backup_code:o.backupCode?!0:void 0}}));if(l.twoFactorRequired)throw new m(500,"Unexpected login response.","unexpected_response");return l.customer},logout(){t.setCustomer(null)},async requestPasswordReset(r){await t.request("/api/auth/forgot-password",{method:"POST",body:{email:r}})},async resetPassword(r,s){return n(await t.request("/api/auth/reset-password",{method:"POST",body:{token:r,password:s}}))},async verifyEmail(r){await t.request("/api/auth/verify-email",{method:"POST",body:{token:r}})},async resendVerification(r){await t.request("/api/auth/resend-verification",{method:"POST",body:{email:r}})},async updateProfile(r){let s=await t.request("/api/customer/me",{method:"PATCH",requireAuth:!0,body:{display_name:r.name}}),o=t.customer();return o&&t.setCustomer({...o,name:s.user.display_name??null}),{id:s.user.id,email:s.user.email,name:s.user.display_name??null}},async changePassword(r,s){await t.request("/api/customer/me/password",{method:"POST",requireAuth:!0,body:{current_password:r,new_password:s}})},async orders(){return(await t.request("/api/customer/orders",{requireAuth:!0})).orders??[]},order(r){return t.request(`/api/customer/orders/${encodeURIComponent(r)}`,{requireAuth:!0})},orderInvoice(r){return t.request(`/api/customer/orders/${encodeURIComponent(r)}/invoice`,{requireAuth:!0,blob:!0})},async invoices(){return(await t.request("/api/customer/invoices",{requireAuth:!0})).invoices??[]},invoicePdf(r){return t.request(`/api/customer/invoices/${encodeURIComponent(r)}/pdf`,{requireAuth:!0,blob:!0})},async addresses(){return(await t.request("/api/customer/addresses",{requireAuth:!0})).addresses??[]},async createAddress(r){return(await t.request("/api/customer/addresses",{method:"POST",requireAuth:!0,body:r})).address},async updateAddress(r,s){return(await t.request(`/api/customer/addresses/${encodeURIComponent(r)}`,{method:"PATCH",requireAuth:!0,body:s})).address},async deleteAddress(r){await t.request(`/api/customer/addresses/${encodeURIComponent(r)}`,{method:"DELETE",requireAuth:!0})},async subscriptions(){return(await t.request("/api/customer/abos",{requireAuth:!0})).abos??[]},cancelSubscription(r){return t.request(`/api/customer/abos/${encodeURIComponent(r)}/kuendigen`,{method:"POST",requireAuth:!0})},exportData(){return t.request("/api/customer/me/export",{requireAuth:!0})},async deleteAccount(r){await t.request("/api/customer/me/delete",{method:"POST",requireAuth:!0,body:{password:r,confirm:"DELETE"}}),t.setCustomer(null)},lookupOrder(r){return t.request("/api/customer/order-lookup",{query:{display_id:String(r.orderNumber).replace(/^#/,""),email:r.email,postal_code:r.postalCode}})},onChange(r){return t.on("customer",r)}}}var q={};A(q,{escape:()=>M,isSafeUrl:()=>U,markdown:()=>k,sanitize:()=>we});var fe={"&":"&","<":"<",">":">",'"':""","'":"'"};function M(t){return String(t??"").replace(/[&<>"']/g,e=>fe[e])}var he=new Set(["P","BR","STRONG","B","EM","I","U","S","A","UL","OL","LI","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","CODE","PRE","HR","IMG","TABLE","THEAD","TBODY","TR","TH","TD","SPAN","DIV","SMALL","SUP","SUB","FIGURE","FIGCAPTION"]),ye=new Set(["href","src","alt","title","class","colspan","rowspan","width","height"]),be=/^(SCRIPT|STYLE|IFRAME|OBJECT|EMBED|TEMPLATE|NOSCRIPT|SVG|MATH|FORM|INPUT|BUTTON|TEXTAREA|SELECT|LINK|META|BASE)$/;function U(t,e=!1){let n=String(t??"").replace(/[\u0000- \u007f-\u009f]/g,"");return n?/^https:/i.test(n)||!e&&/^(http:|mailto:|tel:)/i.test(n)?!0:!(/^[a-z][a-z0-9+.-]*:/i.test(n)||/^[\\/]{2}/.test(n)):!1}function we(t){let e=String(t??"");if(typeof DOMParser>"u")return M(e);let r=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html").body.firstElementChild;if(!r)return"";let s=o=>{for(let l of Array.from(o.childNodes)){if(l.nodeType===3)continue;if(l.nodeType!==1){o.removeChild(l);continue}let a=l;if(!he.has(a.nodeName)){if(!be.test(a.nodeName))for(s(a);a.firstChild;)o.insertBefore(a.firstChild,a);o.removeChild(a);continue}for(let i of Array.from(a.attributes)){let u=i.name.toLowerCase();(!ye.has(u)||(u==="href"||u==="src")&&!U(i.value,u==="src"))&&a.removeAttribute(i.name)}a.nodeName==="A"&&(a.setAttribute("rel","noopener noreferrer"),/^https?:/i.test(a.getAttribute("href")??"")&&a.setAttribute("target","_blank")),s(a)}};return s(r),r.innerHTML}function E(t){return M(t).replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[^*])\*([^*]+)\*/g,"$1<em>$2</em>").replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(e,n,r)=>{let s=r.replace(/&/g,"&");return U(s)?`<a href="${r}" rel="noopener noreferrer">${n}</a>`:n})}function k(t){let e=[],n=null,r=[],s=()=>{r.length&&(e.push(`<p>${r.map(E).join("<br>")}</p>`),r=[])},o=()=>{n&&(e.push(`<${n.tag}>${n.items.map(l=>`<li>${E(l)}</li>`).join("")}</${n.tag}>`),n=null)};for(let l of String(t??"").split(/\r?\n/)){let a=/^(#{1,6})\s+(.*)$/.exec(l),i=/^\s*[-*]\s+(.*)$/.exec(l),u=/^\s*\d+[.)]\s+(.*)$/.exec(l);if(!l.trim()){s(),o();continue}if(a){s(),o(),e.push(`<h${a[1].length}>${E(a[2])}</h${a[1].length}>`);continue}if(/^---+$/.test(l.trim())){s(),o(),e.push("<hr>");continue}if(i||u){s();let c=i?"ul":"ol",d=n;(!d||d.tag!==c)&&(o(),n={tag:c,items:[]}),n.items.push((i??u)[1]);continue}o(),r.push(l.trim())}return s(),o(),e.join(`
|
|
2
|
+
`)}var I=t=>t.catch(e=>{if(e instanceof m&&e.status===404)return null;throw e});function W(t){return{async list(){return(await t.request("/api/pages"))?.pages??[]},async get(e){let n=await I(t.request(`/api/pages/${encodeURIComponent(e)}`));return n?{...n,html:k(n.bodyMd)}:null}}}function Y(t){return{async list(){return(await t.request("/api/store/legal"))?.texte??[]},async get(e){let n=await I(t.request(`/api/store/legal/${encodeURIComponent(e)}`));return n?{...n,html:n.content?k(n.content):""}:null}}}function X(t){let e=(n,r={})=>t.request(`/api/store/inhalte/${encodeURIComponent(n)}`,{query:{slug:r.slug,seite:r.page,pro_seite:r.perPage,sprache:r.language}});return{list:e,async get(n,r,s={}){return(await I(e(n,{slug:r,language:s.language})))?.eintraege?.[0]??null}}}function w(t,e,n){let r=document.head.querySelector(`meta[${t}="${e}"]`);if(!n){r?.remove();return}r||(r=document.createElement("meta"),r.setAttribute(t,e),document.head.appendChild(r)),r.setAttribute("content",n)}function J(t){return{list(e={}){return t.request("/api/store/blog",{query:{thema:e.topic,produkt:e.productId,kategorie:e.categoryId,seite:e.page,pro_seite:e.perPage}})},post(e){return I(t.request(`/api/store/blog/${encodeURIComponent(e)}`))},async forProduct(e,n=3){return(await t.request("/api/store/blog",{query:{produkt:e,pro_seite:n}}))?.beitraege??[]},async topics(){return(await t.request("/api/store/blog/themen"))?.themen??[]},async sitemap(){return(await t.request("/api/store/blog/sitemap"))?.eintraege??[]},applySeo(e){if(!e?.meta||!g())return;let n=e.meta;document.title=n.title,w("name","description",n.description),w("name","robots",n.robots),w("property","og:type","article"),w("property","og:title",n.title),w("property","og:description",n.description),w("property","og:image",n.og_image);let r=document.head.querySelector('link[rel="canonical"]');n.canonical?(r||(r=document.createElement("link"),r.rel="canonical",document.head.appendChild(r)),r.href=n.canonical):r?.remove(),document.head.querySelectorAll("script[data-sellforge-blog]").forEach(s=>s.remove());for(let s of e.json_ld??[]){let o=document.createElement("script");o.type="application/ld+json",o.setAttribute("data-sellforge-blog",""),o.textContent=JSON.stringify(s).replace(/</g,"\\u003c"),document.head.appendChild(o)}}}}function _(t,e){if(!t)return null;let n=t.toLowerCase(),r=n.split("-")[0];return e.find(s=>s.toLowerCase()===n)??e.find(s=>s.toLowerCase()===r)??e.find(s=>s.toLowerCase().split("-")[0]===r)??null}function Q(t){let e=null,n=()=>(e??(e=t.request("/api/store/languages").catch(r=>{throw e=null,r})),e);return{branding(){return t.request("/api/store/branding",{query:{lang:t.language}})},languages:n,async resolveLanguage(){let r=await n(),s=r.languages?.length?r.languages:[r.default_language],o=_(t.language,s);if(!o&&t.language&&t.store.removeItem(f.language),!o&&r.auto_detect&&(o=_(r.detected_language,s),!o&&g())){for(let a of navigator.languages?.length?navigator.languages:[navigator.language])if(o=_(a,s),o)break}let l=o??r.default_language;if(l!==t.language&&t.setLanguage(l,!1),g())try{document.documentElement.lang=l}catch{}return l},googleAds(){return t.request("/api/store/google-ads")},pinterest(){return t.request("/api/store/pinterest")}}}function Z(t){return{async methods(e="AT"){return(await t.request("/api/shipping-methods",{query:{country:e.toUpperCase()}}))?.methods??[]},async countries(){return(await t.request("/api/shipping-countries"))?.countries??[]}}}function ee(t){return{subscribe(e,n={}){return t.request("/store/newsletter",{method:"POST",body:{email:e,name:n.name,source:n.source??"storefront",consent:n.consent!==!1}})}}}function te(t){return{find(e){return t.request("/api/store/widerruf/bestellung",{method:"POST",body:{bestellnummer:e.orderNumber,email:e.email}})},submit(e){return t.request("/api/store/widerruf",{method:"POST",body:{name:e.name,bestellnummer:e.orderNumber,email:e.email,positionen:e.items?.map(n=>({id:n.id,menge:n.quantity})),nachricht:e.message}})}}}function re(){let t=()=>g()?window.sellforge:void 0;return{available:()=>!!t(),consent:e=>t()?.consent?.(e),track:(e,n)=>t()?.track?.(e,n),search:(e,n)=>t()?.search?.(e,n),vehicle:(e,n,r)=>t()?.vehicle?.(e,n,r)}}var v={};A(v,{date:()=>_e,price:()=>Ce});function Ce(t,e="EUR",n){let r=Number(t??0)/100;try{return new Intl.NumberFormat(n??ne(),{style:"currency",currency:e}).format(r)}catch{return`${r.toFixed(2)} ${e}`}}function _e(t,e,n={dateStyle:"medium"}){try{return new Intl.DateTimeFormat(e??ne(),n).format(new Date(t))}catch{return String(t)}}function ne(){return typeof document<"u"&&document.documentElement?.lang?document.documentElement.lang:"de-AT"}var se="1.0.2";function Pe(t={}){let e=new P(t),n=B(e),r=Q(e);return{version:se,hosted:e.hosted,baseUrl:e.baseUrl,get language(){return e.language},setLanguage(s){e.setLanguage(s)},onLanguageChange(s){return e.on("language",s)},shop:r,catalog:V(e),vehicles:F(e),cart:n,checkout:G(e,n),account:z(e),pages:W(e),legal:Y(e),content:X(e),blog:J(e),shipping:Z(e),newsletter:ee(e),withdrawal:te(e),insights:re(),html:q,format:v,request:e.request.bind(e)}}return le(Se);})();
|
|
3
3
|
//# sourceMappingURL=sellforge.global.js.map
|