@lockerverse/react 0.2.91 → 0.2.94

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.
@@ -1,2 +1,2 @@
1
- import{array as e,email as t,minLength as n,nonEmpty as r,pipe as i,regex as a,safeParse as o,string as s,transform as c,trim as l}from"valibot";import{jsx as u,jsxs as d}from"react/jsx-runtime";const f=/^#([\da-f]{3}|[\da-f]{6})$/i,p=/^([\da-f]{3}|[\da-f]{6})$/i;function m(e){let t=e.trim();return p.test(t)?`#${t}`:t}function h(e){let t=f.exec(m(e));if(!t)return;let[,n]=t;if(!n)return;let r=n.length===3?Array.from(n,e=>`${e}${e}`).join(``):n;return[0,2,4].map(e=>Number.parseInt(r.slice(e,e+2),16))}function g([e,t,n]){let[r=0,i=0,a=0]=[e,t,n].map((e=0)=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a}function _(e){let t=h(e);if(!t)return;let n=g(t);return(n+.05)/.05>=1.05/(n+.05)?`#000`:`#fff`}function v(e){return e.type===`checkbox`?!1:e.type===`checkboxes`||e.type===`multi_select`?[]:``}function y(e){let t={};for(let n of e)t[n.id]=v(n);return t}function b(e){let t=o(s(),e);return t.success?t.output:``}function x(e,t){return e.map(e=>{let n=t[e.id];return e.type===`checkbox`?{fieldId:e.id,value:n===!0}:e.type===`checkboxes`||e.type===`multi_select`?{fieldId:e.id,value:Array.isArray(n)?n:[]}:{fieldId:e.id,value:b(n)}})}function S(t,a){let c={};for(let u of t){if(!u.required)continue;let t=`${u.label} is required.`,d=a[u.id];if(u.type===`checkbox`){d!==!0&&(c[u.id]=t);continue}let f=u.type===`checkboxes`||u.type===`multi_select`?o(i(e(s()),n(1,t)),d??[]):o(i(s(),l(),r(t)),b(d));f.success||(c[u.id]=f.issues[0]?.message??t)}return c}function C({choiceClassName:e,errorClassName:t,errors:n,fields:r,idPrefix:i,onChange:a,values:o}){return r.map(r=>u(w,{choiceClassName:e,error:n[r.id],errorClassName:t,field:r,idPrefix:i,onChange:e=>a({...o,[r.id]:e}),value:o[r.id]},r.id))}function w(e){let{field:t,idPrefix:n}=e,r=`${n}-custom-${t.id}`,i=`${r}-error`,a={...e,controlId:r,errorId:i};switch(t.type){case`checkbox`:return u(T,{...a,field:t});case`text`:case`textarea`:return u(D,{...a,field:t});case`select`:case`multi_select`:return u(O,{...a,field:t});case`radio`:case`checkboxes`:return u(k,{...a,field:t});default:return null}}function T({choiceClassName:e,controlId:t,error:n,errorClassName:r,errorId:i,field:a,onChange:o,value:s}){return d(`label`,{className:e,htmlFor:t,children:[u(`input`,{"aria-describedby":n?i:void 0,"aria-invalid":n?`true`:void 0,checked:s===!0,id:t,name:`custom:${a.id}`,onChange:e=>o(e.currentTarget.checked),required:a.required,type:`checkbox`}),u(`span`,{children:a.label}),u(E,{className:r,error:n,id:i})]})}function E({className:e,error:t,id:n}){return t?u(`span`,{className:e,id:n,role:`alert`,children:t}):null}function D({controlId:e,error:t,errorClassName:n,errorId:r,field:i,onChange:a,value:o}){let s={"aria-describedby":t?r:void 0,"aria-invalid":t?`true`:void 0,id:e,name:`custom:${i.id}`,onChange:e=>a(e.currentTarget.value),required:i.required,value:b(o)};return d(`label`,{htmlFor:e,children:[u(`span`,{children:i.label}),i.type===`textarea`?u(`textarea`,{...s}):u(`input`,{...s}),u(E,{className:n,error:t,id:r})]})}function O({controlId:e,error:t,errorClassName:n,errorId:r,field:i,onChange:a,value:o}){return d(`label`,{htmlFor:e,children:[u(`span`,{children:i.label}),d(`select`,{"aria-describedby":t?r:void 0,"aria-invalid":t?`true`:void 0,id:e,multiple:i.type===`multi_select`,name:`custom:${i.id}`,onChange:e=>a(i.type===`multi_select`?[...e.currentTarget.selectedOptions].map(e=>e.value):e.currentTarget.value),required:i.required,value:o===!0||o===!1?``:o??(i.type===`multi_select`?[]:``),children:[i.type===`select`?u(`option`,{value:``,children:`Select…`}):null,i.options.map(e=>u(`option`,{value:e.id,children:e.label},e.id))]}),u(E,{className:n,error:t,id:r})]})}function k({choiceClassName:e,controlId:t,error:n,errorClassName:r,errorId:i,field:a,onChange:o,value:s}){let c=Array.isArray(s)?s:[];return d(`fieldset`,{"aria-describedby":n?i:void 0,"aria-invalid":n?`true`:void 0,children:[u(`legend`,{children:a.label}),a.options.map((n,r)=>d(`label`,{className:e,children:[u(`input`,{checked:Array.isArray(s)?s.includes(n.id):s===n.id,id:`${t}-${r}`,name:`custom:${a.id}`,onChange:e=>{if(a.type===`radio`){o(n.id);return}o(e.currentTarget.checked?[...c,n.id]:c.filter(e=>e!==n.id))},required:a.required&&a.type===`radio`,type:a.type===`radio`?`radio`:`checkbox`,value:n.id}),u(`span`,{children:n.label})]},n.id)),u(E,{className:r,error:n,id:i})]})}function A({fieldCount:e,label:t,sectionCount:n=0,showCheckbox:r=!1}){return d(`div`,{className:`lockerverse-form-skeleton__loading`,children:[u(`span`,{className:`lockerverse-form-skeleton__sr-only`,role:`status`,children:t}),d(`div`,{"aria-hidden":`true`,className:`lockerverse-form-skeleton`,children:[d(`div`,{className:`lockerverse-form-skeleton__branding`,children:[u(`span`,{className:`lockerverse-form-skeleton__avatar`}),u(`span`,{className:`lockerverse-form-skeleton__community`})]}),u(`div`,{className:`lockerverse-form-skeleton__fields`,children:Array.from({length:e},(e,t)=>d(`div`,{className:`lockerverse-form-skeleton__field`,children:[u(`span`,{className:`lockerverse-form-skeleton__label`}),u(`span`,{className:`lockerverse-form-skeleton__input`})]},t))}),Array.from({length:n},(e,t)=>d(`div`,{className:`lockerverse-form-skeleton__section`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-label`}),d(`div`,{className:`lockerverse-form-skeleton__section-content`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-full`}),d(`div`,{className:`lockerverse-form-skeleton__section-grid`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-half`}),u(`span`,{className:`lockerverse-form-skeleton__section-half`})]})]})]},t)),d(`div`,{className:`lockerverse-form-skeleton__actions`,children:[r?u(`span`,{className:`lockerverse-form-skeleton__check-line`}):null,u(`span`,{className:`lockerverse-form-skeleton__button`})]})]})]})}const j=`Enter a valid email address.`,M=`Enter a valid phone number.`,N=/^(?:$|[^\s@]+@[^\s@]+\.[^\s@]+)$/,P=/^\+[1-9]\d{6,14}$/,F=/^(?:$|\+[1-9]\d{6,14})$/;function I(e){return e.trim().replace(/[().\s-]/g,``)}const L=i(s(),l(),a(N,j)),R=i(s(),l(),r(`Email is required.`),t(j)),z=i(s(),l(),c(I),a(F,M)),B=i(s(),l(),r(`Phone is required.`),c(I),a(P,M));function V(e,t){if(e)try{Promise.resolve(e(t)).catch(()=>void 0)}catch{}}export{R as a,C as c,S as d,_ as f,z as i,x as l,I as n,B as o,m as p,L as r,A as s,V as t,y as u};
1
+ import{array as e,email as t,minLength as n,nonEmpty as r,pipe as i,regex as a,safeParse as o,string as s,transform as c,trim as l}from"valibot";import{jsx as u,jsxs as d}from"react/jsx-runtime";const f=/^#([\da-f]{3}|[\da-f]{6})$/i,p=/^([\da-f]{3}|[\da-f]{6})$/i;function m(e){let t=e.trim();return p.test(t)?`#${t}`:t}function h(e){let t=f.exec(m(e));if(!t)return;let[,n]=t;if(!n)return;let r=n.length===3?Array.from(n,e=>`${e}${e}`).join(``):n;return[0,2,4].map(e=>Number.parseInt(r.slice(e,e+2),16))}function g([e,t,n]){let[r=0,i=0,a=0]=[e,t,n].map((e=0)=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a}function _(e){let t=h(e);if(!t)return;let n=g(t);return(n+.05)/.05>=1.05/(n+.05)?`#000`:`#fff`}function v(e){return e.type===`checkbox`?!1:e.type===`checkboxes`||e.type===`multi_select`?[]:``}function y(e){let t={};for(let n of e)t[n.id]=v(n);return t}function b(e){let t=o(s(),e);return t.success?t.output:``}function x(e,t){return e.map(e=>{let n=t[e.id];return e.type===`checkbox`?{fieldId:e.id,value:n===!0}:e.type===`checkboxes`||e.type===`multi_select`?{fieldId:e.id,value:Array.isArray(n)?n:[]}:{fieldId:e.id,value:b(n)}})}function S(t,a){let c={};for(let u of t){if(!u.required)continue;let t=`${u.label} is required.`,d=a[u.id];if(u.type===`checkbox`){d!==!0&&(c[u.id]=t);continue}let f=u.type===`checkboxes`||u.type===`multi_select`?o(i(e(s()),n(1,t)),d??[]):o(i(s(),l(),r(t)),b(d));f.success||(c[u.id]=f.issues[0]?.message??t)}return c}function C({choiceClassName:e,errorClassName:t,errors:n,fields:r,idPrefix:i,onChange:a,values:o}){return r.map(r=>u(w,{choiceClassName:e,error:n[r.id],errorClassName:t,field:r,idPrefix:i,onChange:e=>a({...o,[r.id]:e}),value:o[r.id]},r.id))}function w(e){let{field:t,idPrefix:n}=e,r=`${n}-custom-${t.id}`,i=`${r}-error`,a={...e,controlId:r,errorId:i};switch(t.type){case`checkbox`:return u(T,{...a,field:t});case`text`:case`textarea`:return u(D,{...a,field:t});case`select`:case`multi_select`:return u(O,{...a,field:t});case`radio`:case`checkboxes`:return u(k,{...a,field:t});default:return null}}function T({choiceClassName:e,controlId:t,error:n,errorClassName:r,errorId:i,field:a,onChange:o,value:s}){return d(`label`,{className:e,htmlFor:t,children:[u(`input`,{"aria-describedby":n?i:void 0,"aria-invalid":n?`true`:void 0,checked:s===!0,id:t,name:`custom:${a.id}`,onChange:e=>o(e.currentTarget.checked),required:a.required,type:`checkbox`}),u(`span`,{children:a.label}),u(E,{className:r,error:n,id:i})]})}function E({className:e,error:t,id:n}){return t?u(`span`,{className:e,id:n,role:`alert`,children:t}):null}function D({controlId:e,error:t,errorClassName:n,errorId:r,field:i,onChange:a,value:o}){let s={"aria-describedby":t?r:void 0,"aria-invalid":t?`true`:void 0,id:e,name:`custom:${i.id}`,onChange:e=>a(e.currentTarget.value),required:i.required,value:b(o)};return d(`label`,{htmlFor:e,children:[u(`span`,{children:i.label}),i.type===`textarea`?u(`textarea`,{...s}):u(`input`,{...s}),u(E,{className:n,error:t,id:r})]})}function O({controlId:e,error:t,errorClassName:n,errorId:r,field:i,onChange:a,value:o}){return d(`label`,{htmlFor:e,children:[u(`span`,{children:i.label}),d(`select`,{"aria-describedby":t?r:void 0,"aria-invalid":t?`true`:void 0,id:e,multiple:i.type===`multi_select`,name:`custom:${i.id}`,onChange:e=>a(i.type===`multi_select`?[...e.currentTarget.selectedOptions].map(e=>e.value):e.currentTarget.value),required:i.required,value:o===!0||o===!1?``:o??(i.type===`multi_select`?[]:``),children:[i.type===`select`?u(`option`,{value:``,children:`Select…`}):null,i.options.map(e=>u(`option`,{value:e.id,children:e.label},e.id))]}),u(E,{className:n,error:t,id:r})]})}function k({choiceClassName:e,controlId:t,error:n,errorClassName:r,errorId:i,field:a,onChange:o,value:s}){let c=Array.isArray(s)?s:[];return d(`fieldset`,{"aria-describedby":n?i:void 0,"aria-invalid":n?`true`:void 0,children:[u(`legend`,{children:a.label}),a.options.map((n,r)=>d(`label`,{className:e,children:[u(`input`,{checked:Array.isArray(s)?s.includes(n.id):s===n.id,id:`${t}-${r}`,name:`custom:${a.id}`,onChange:e=>{if(a.type===`radio`){o(n.id);return}o(e.currentTarget.checked?[...c,n.id]:c.filter(e=>e!==n.id))},required:a.required&&a.type===`radio`,type:a.type===`radio`?`radio`:`checkbox`,value:n.id}),u(`span`,{children:n.label})]},n.id)),u(E,{className:r,error:n,id:i})]})}function A({fieldCount:e,label:t,sectionCount:n=0,showCheckbox:r=!1}){return d(`div`,{className:`lockerverse-form-skeleton__loading`,children:[u(`span`,{className:`lockerverse-form-skeleton__sr-only`,role:`status`,children:t}),d(`div`,{"aria-hidden":`true`,className:`lockerverse-form-skeleton`,children:[d(`div`,{className:`lockerverse-form-skeleton__branding`,children:[u(`span`,{className:`lockerverse-form-skeleton__avatar`}),u(`span`,{className:`lockerverse-form-skeleton__community`})]}),u(`div`,{className:`lockerverse-form-skeleton__fields`,children:Array.from({length:e},(e,t)=>d(`div`,{className:`lockerverse-form-skeleton__field`,children:[u(`span`,{className:`lockerverse-form-skeleton__label`}),u(`span`,{className:`lockerverse-form-skeleton__input`})]},t))}),Array.from({length:n},(e,t)=>d(`div`,{className:`lockerverse-form-skeleton__section`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-label`}),d(`div`,{className:`lockerverse-form-skeleton__section-content`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-full`}),d(`div`,{className:`lockerverse-form-skeleton__section-grid`,children:[u(`span`,{className:`lockerverse-form-skeleton__section-half`}),u(`span`,{className:`lockerverse-form-skeleton__section-half`})]})]})]},t)),d(`div`,{className:`lockerverse-form-skeleton__actions`,children:[r?u(`span`,{className:`lockerverse-form-skeleton__check-line`}):null,u(`span`,{className:`lockerverse-form-skeleton__button`})]})]})]})}const j=`Enter a valid email address.`,M=`Phone is required.`,N=`Enter a valid phone number.`,P=/^(?:$|[^\s@]+@[^\s@]+\.[^\s@]+)$/,F=/^\+[1-9]\d{6,14}$/,I=/^(?:$|\+[1-9]\d{6,14})$/;function L(e){return e.trim().replace(/[().\s-]/g,``)}const R=i(s(),l(),a(P,j)),z=i(s(),l(),r(`Email is required.`),t(j)),B=i(s(),l(),c(L),a(I,N)),V=i(s(),l(),r(M),c(L),a(F,N)),H=[{callingCode:`+1`,label:`🇺🇸 +1`,value:`US`},{callingCode:`+52`,label:`🇲🇽 +52`,value:`MX`},{callingCode:`+380`,label:`🇺🇦 +380`,value:`UA`},{callingCode:`+48`,label:`🇵🇱 +48`,value:`PL`},{callingCode:`+1`,label:`🇨🇦 +1`,value:`CA`},{callingCode:`+49`,label:`🇩🇪 +49`,value:`DE`},{callingCode:`+44`,label:`🇬🇧 +44`,value:`GB`},{callingCode:`+46`,label:`🇸🇪 +46`,value:`SE`},{callingCode:`+358`,label:`🇫🇮 +358`,value:`FI`},{callingCode:`+1`,label:`🇵🇷 +1`,value:`PR`}];function U(e){if(e===`PAYMENT_WIDGET_PHONE_REQUIRED`||e===`SIGN_UP_WIDGET_PHONE_REQUIRED`)return M;if(e===`PAYMENT_WIDGET_PHONE_INVALID`||e===`SIGN_UP_WIDGET_PHONE_INVALID`)return N}function W(e){return H.find(t=>t.value===e)??H[0]}function G(e,t){let n=`${t}${t}`,r=e;for(;r.startsWith(n);)r=`${t}${r.slice(n.length)}`;return r}function K(e,t){let n=L(e);if(!n)return``;let r=W(t),i=G(n,r.callingCode);return i.startsWith(`+`)?i:`${r.callingCode}${i}`}function q(e,t){if(e)try{Promise.resolve(e(t)).catch(()=>void 0)}catch{}}export{L as a,z as c,C as d,x as f,m as g,_ as h,U as i,V as l,S as m,H as n,R as o,y as p,K as r,B as s,q as t,A as u};
2
2
  //# sourceMappingURL=host-callback.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"host-callback.js","names":[],"sources":["../src/accent-contrast.ts","../src/custom-fields.tsx","../src/form-skeleton.tsx","../src/contact-validation.ts","../src/host-callback.ts"],"sourcesContent":["const HEX_COLOR = /^#([\\da-f]{3}|[\\da-f]{6})$/i;\nconst UNPREFIXED_HEX_COLOR = /^([\\da-f]{3}|[\\da-f]{6})$/i;\n\nexport function normalizeAccentColor(color: string) {\n const trimmedColor = color.trim();\n return UNPREFIXED_HEX_COLOR.test(trimmedColor)\n ? `#${trimmedColor}`\n : trimmedColor;\n}\n\nfunction parseHexColor(color: string) {\n const match = HEX_COLOR.exec(normalizeAccentColor(color));\n if (!match) {\n return;\n }\n const [, value] = match;\n if (!value) {\n return;\n }\n const expanded =\n value.length === 3\n ? Array.from(value, (character) => `${character}${character}`).join(\"\")\n : value;\n return [0, 2, 4].map((offset) =>\n Number.parseInt(expanded.slice(offset, offset + 2), 16)\n );\n}\n\nfunction relativeLuminance([red, green, blue]: number[]) {\n const [linearRed = 0, linearGreen = 0, linearBlue = 0] = [\n red,\n green,\n blue,\n ].map((channel = 0) => {\n const normalized = channel / 255;\n return normalized <= 0.040_45\n ? normalized / 12.92\n : ((normalized + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * linearRed + 0.7152 * linearGreen + 0.0722 * linearBlue;\n}\n\nexport function getAccentContrast(color: string) {\n const parsed = parseHexColor(color);\n if (!parsed) {\n return;\n }\n const luminance = relativeLuminance(parsed);\n const blackContrast = (luminance + 0.05) / 0.05;\n const whiteContrast = 1.05 / (luminance + 0.05);\n return blackContrast >= whiteContrast ? \"#000\" : \"#fff\";\n}\n","import type {\n LockerverseBooleanCustomField,\n LockerverseCustomField,\n LockerverseCustomFieldAnswer,\n LockerverseMultiOptionCustomField,\n LockerverseSingleOptionCustomField,\n} from \"@lockerverse/sdk/checkout\";\nimport {\n array,\n minLength,\n nonEmpty,\n pipe,\n safeParse,\n string,\n trim,\n} from \"valibot\";\n\nexport type CustomFieldValues = Record<string, boolean | string | string[]>;\n\nfunction createCustomFieldValue(field: LockerverseCustomField) {\n if (field.type === \"checkbox\") {\n return false;\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return [];\n }\n return \"\";\n}\n\nexport function createCustomFieldValues(fields: LockerverseCustomField[]) {\n const values: CustomFieldValues = {};\n for (const field of fields) {\n values[field.id] = createCustomFieldValue(field);\n }\n return values;\n}\n\nfunction getStringValue(value: CustomFieldValues[string] | undefined) {\n const result = safeParse(string(), value);\n return result.success ? result.output : \"\";\n}\n\nexport function buildCustomFieldAnswers(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n): LockerverseCustomFieldAnswer[] {\n return fields.map((field): LockerverseCustomFieldAnswer => {\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n return { fieldId: field.id, value: value === true };\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return { fieldId: field.id, value: Array.isArray(value) ? value : [] };\n }\n return {\n fieldId: field.id,\n value: getStringValue(value),\n };\n });\n}\n\nexport function validateCustomFields(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n) {\n const errors: Record<string, string> = {};\n for (const field of fields) {\n if (!field.required) {\n continue;\n }\n const message = `${field.label} is required.`;\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n if (value !== true) {\n errors[field.id] = message;\n }\n continue;\n }\n const result =\n field.type === \"checkboxes\" || field.type === \"multi_select\"\n ? safeParse(pipe(array(string()), minLength(1, message)), value ?? [])\n : safeParse(\n pipe(string(), trim(), nonEmpty(message)),\n getStringValue(value)\n );\n if (!result.success) {\n errors[field.id] = result.issues[0]?.message ?? message;\n }\n }\n return errors;\n}\n\nexport function CustomFields({\n choiceClassName,\n errorClassName,\n errors,\n fields,\n idPrefix,\n onChange,\n values,\n}: {\n choiceClassName: string;\n errorClassName: string;\n errors: Record<string, string>;\n fields: LockerverseCustomField[];\n idPrefix: string;\n onChange: (values: CustomFieldValues) => void;\n values: CustomFieldValues;\n}) {\n return fields.map((field) => (\n <CustomField\n choiceClassName={choiceClassName}\n error={errors[field.id]}\n errorClassName={errorClassName}\n field={field}\n idPrefix={idPrefix}\n key={field.id}\n onChange={(value) => onChange({ ...values, [field.id]: value })}\n value={values[field.id]}\n />\n ));\n}\n\ntype CustomFieldProps = {\n choiceClassName: string;\n error: string | undefined;\n errorClassName: string;\n field: LockerverseCustomField;\n idPrefix: string;\n onChange: (value: boolean | string | string[]) => void;\n value: boolean | string | string[] | undefined;\n};\n\nfunction CustomField(props: CustomFieldProps) {\n const { field, idPrefix } = props;\n const controlId = `${idPrefix}-custom-${field.id}`;\n const errorId = `${controlId}-error`;\n const controlProps = { ...props, controlId, errorId };\n switch (field.type) {\n case \"checkbox\":\n return <BooleanCustomField {...controlProps} field={field} />;\n case \"text\":\n case \"textarea\":\n return <TextCustomField {...controlProps} field={field} />;\n case \"select\":\n case \"multi_select\":\n return <SelectCustomField {...controlProps} field={field} />;\n case \"radio\":\n case \"checkboxes\":\n return <ChoiceCustomField {...controlProps} field={field} />;\n default:\n return null;\n }\n}\n\nfunction BooleanCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & { field: LockerverseBooleanCustomField }) {\n return (\n <label className={choiceClassName} htmlFor={controlId}>\n <input\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n checked={value === true}\n id={controlId}\n name={`custom:${field.id}`}\n onChange={(event) => onChange(event.currentTarget.checked)}\n required={field.required}\n type=\"checkbox\"\n />\n <span>{field.label}</span>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\ntype ControlProps = CustomFieldProps & {\n controlId: string;\n errorId: string;\n};\n\nfunction FieldError({\n className,\n error,\n id,\n}: {\n className: string;\n error: string | undefined;\n id: string;\n}) {\n return error ? (\n <span className={className} id={id} role=\"alert\">\n {error}\n </span>\n ) : null;\n}\n\nfunction TextCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: Extract<LockerverseCustomField, { type: \"text\" | \"textarea\" }>;\n}) {\n const commonProps = {\n \"aria-describedby\": error ? errorId : undefined,\n \"aria-invalid\": error ? (\"true\" as const) : undefined,\n id: controlId,\n name: `custom:${field.id}`,\n onChange: (\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => onChange(event.currentTarget.value),\n required: field.required,\n value: getStringValue(value),\n };\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n {field.type === \"textarea\" ? (\n <textarea {...commonProps} />\n ) : (\n <input {...commonProps} />\n )}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction SelectCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n <select\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n id={controlId}\n multiple={field.type === \"multi_select\"}\n name={`custom:${field.id}`}\n onChange={(event) =>\n onChange(\n field.type === \"multi_select\"\n ? [...event.currentTarget.selectedOptions].map(\n (option) => option.value\n )\n : event.currentTarget.value\n )\n }\n required={field.required}\n value={\n value === true || value === false\n ? \"\"\n : (value ?? (field.type === \"multi_select\" ? [] : \"\"))\n }\n >\n {field.type === \"select\" ? <option value=\"\">Select…</option> : null}\n {field.options.map((option) => (\n <option key={option.id} value={option.id}>\n {option.label}\n </option>\n ))}\n </select>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction ChoiceCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n const selectedValues = Array.isArray(value) ? value : [];\n return (\n <fieldset\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n >\n <legend>{field.label}</legend>\n {field.options.map((option, index) => (\n <label className={choiceClassName} key={option.id}>\n <input\n checked={\n Array.isArray(value)\n ? value.includes(option.id)\n : value === option.id\n }\n id={`${controlId}-${index}`}\n name={`custom:${field.id}`}\n onChange={(event) => {\n if (field.type === \"radio\") {\n onChange(option.id);\n return;\n }\n onChange(\n event.currentTarget.checked\n ? [...selectedValues, option.id]\n : selectedValues.filter((id) => id !== option.id)\n );\n }}\n required={field.required && field.type === \"radio\"}\n type={field.type === \"radio\" ? \"radio\" : \"checkbox\"}\n value={option.id}\n />\n <span>{option.label}</span>\n </label>\n ))}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </fieldset>\n );\n}\n","export function FormSkeleton({\n fieldCount,\n label,\n sectionCount = 0,\n showCheckbox = false,\n}: {\n fieldCount: number;\n label: string;\n sectionCount?: number;\n showCheckbox?: boolean;\n}) {\n return (\n <div className=\"lockerverse-form-skeleton__loading\">\n <span className=\"lockerverse-form-skeleton__sr-only\" role=\"status\">\n {label}\n </span>\n <div aria-hidden=\"true\" className=\"lockerverse-form-skeleton\">\n <div className=\"lockerverse-form-skeleton__branding\">\n <span className=\"lockerverse-form-skeleton__avatar\" />\n <span className=\"lockerverse-form-skeleton__community\" />\n </div>\n <div className=\"lockerverse-form-skeleton__fields\">\n {Array.from({ length: fieldCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__field\" key={index}>\n <span className=\"lockerverse-form-skeleton__label\" />\n <span className=\"lockerverse-form-skeleton__input\" />\n </div>\n ))}\n </div>\n {Array.from({ length: sectionCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__section\" key={index}>\n <span className=\"lockerverse-form-skeleton__section-label\" />\n <div className=\"lockerverse-form-skeleton__section-content\">\n <span className=\"lockerverse-form-skeleton__section-full\" />\n <div className=\"lockerverse-form-skeleton__section-grid\">\n <span className=\"lockerverse-form-skeleton__section-half\" />\n <span className=\"lockerverse-form-skeleton__section-half\" />\n </div>\n </div>\n </div>\n ))}\n <div className=\"lockerverse-form-skeleton__actions\">\n {showCheckbox ? (\n <span className=\"lockerverse-form-skeleton__check-line\" />\n ) : null}\n <span className=\"lockerverse-form-skeleton__button\" />\n </div>\n </div>\n </div>\n );\n}\n","import { email, nonEmpty, pipe, regex, string, transform, trim } from \"valibot\";\n\nexport const EMAIL_REQUIRED_MESSAGE = \"Email is required.\";\nexport const EMAIL_INVALID_MESSAGE = \"Enter a valid email address.\";\nexport const PHONE_REQUIRED_MESSAGE = \"Phone is required.\";\nexport const PHONE_INVALID_MESSAGE = \"Enter a valid phone number.\";\n\nconst OPTIONAL_EMAIL_PATTERN = /^(?:$|[^\\s@]+@[^\\s@]+\\.[^\\s@]+)$/;\nconst INTERNATIONAL_PHONE_PATTERN = /^\\+[1-9]\\d{6,14}$/;\nconst OPTIONAL_INTERNATIONAL_PHONE_PATTERN = /^(?:$|\\+[1-9]\\d{6,14})$/;\n\nexport function normalizePhone(input: string) {\n return input.trim().replace(/[().\\s-]/g, \"\");\n}\n\nexport const optionalEmailSchema = pipe(\n string(),\n trim(),\n regex(OPTIONAL_EMAIL_PATTERN, EMAIL_INVALID_MESSAGE)\n);\n\nexport const requiredEmailSchema = pipe(\n string(),\n trim(),\n nonEmpty(EMAIL_REQUIRED_MESSAGE),\n email(EMAIL_INVALID_MESSAGE)\n);\n\nexport const optionalPhoneSchema = pipe(\n string(),\n trim(),\n transform(normalizePhone),\n regex(OPTIONAL_INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n\nexport const requiredPhoneSchema = pipe(\n string(),\n trim(),\n nonEmpty(PHONE_REQUIRED_MESSAGE),\n transform(normalizePhone),\n regex(INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n","export function notifyHostCallback<Value>(\n callback: ((value: Value) => void) | undefined,\n value: Value\n) {\n if (!callback) {\n return;\n }\n try {\n Promise.resolve(callback(value)).catch(() => undefined);\n } catch {\n // Host callback failures must not change completed SDK state.\n }\n}\n"],"mappings":"mMAAA,MAAM,EAAY,8BACZ,EAAuB,6BAE7B,SAAgB,EAAqB,EAAe,CAClD,IAAM,EAAe,EAAM,KAAK,EAChC,OAAO,EAAqB,KAAK,CAAY,EACzC,IAAI,IACJ,CACN,CAEA,SAAS,EAAc,EAAe,CACpC,IAAM,EAAQ,EAAU,KAAK,EAAqB,CAAK,CAAC,EACxD,GAAI,CAAC,EACH,OAEF,GAAM,EAAG,GAAS,EAClB,GAAI,CAAC,EACH,OAEF,IAAM,EACJ,EAAM,SAAW,EACb,MAAM,KAAK,EAAQ,GAAc,GAAG,IAAY,GAAW,CAAC,CAAC,KAAK,EAAE,EACpE,EACN,MAAO,CAAC,EAAG,EAAG,CAAC,CAAC,CAAC,IAAK,GACpB,OAAO,SAAS,EAAS,MAAM,EAAQ,EAAS,CAAC,EAAG,EAAE,CACxD,CACF,CAEA,SAAS,EAAkB,CAAC,EAAK,EAAO,GAAiB,CACvD,GAAM,CAAC,EAAY,EAAG,EAAc,EAAG,EAAa,GAAK,CACvD,EACA,EACA,CACF,CAAC,CAAC,KAAK,EAAU,IAAM,CACrB,IAAM,EAAa,EAAU,IAC7B,OAAO,GAAc,OACjB,EAAa,QACX,EAAa,MAAS,QAAU,GACxC,CAAC,EACD,MAAO,OAAS,EAAY,MAAS,EAAc,MAAS,CAC9D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ACF,CAAA,CAAA,CAToD,EAAA,CASpD,CACN,EACD,EAAC,MAAD,CAAK,UAAU,qCAAf,SAAA,CACG,EACC,EAAC,OAAD,CAAM,UAAU,uCAAyC,CAAA,EACvD,KACJ,EAAC,OAAD,CAAM,UAAU,mCAAqC,CAAA,CAClD,GACF,CACF,CAAA,CAAA,GAET,CChDA,MACa,EAAwB,+BAExB,EAAwB,8BAE/B,EAAyB,mCACzB,EAA8B,oBAC9B,EAAuC,0BAE7C,SAAgB,EAAe,EAAe,CAC5C,OAAO,EAAM,KAAK,CAAC,CAAC,QAAQ,YAAa,EAAE,CAC7C,CAEA,MAAa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAM,EAAwB,CAAqB,CACrD,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAS,oBAAsB,EAC/B,EAAM,CAAqB,CAC7B,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAU,CAAc,EACxB,EAAM,EAAsC,CAAqB,CACnE,EAEa,EAAsB,EACjC,EAAO,EACP,EAAK,EACL,EAAS,oBAAsB,EAC/B,EAAU,CAAc,EACxB,EAAM,EAA6B,CAAqB,CAC1D,ECzCA,SAAgB,EACd,EACA,EACA,CACK,KAGL,GAAI,CACF,QAAQ,QAAQ,EAAS,CAAK,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,CACxD,MAAQ,CAER,CACF"}
1
+ {"version":3,"file":"host-callback.js","names":[],"sources":["../src/accent-contrast.ts","../src/custom-fields.tsx","../src/form-skeleton.tsx","../src/contact-validation.ts","../src/phone.ts","../src/host-callback.ts"],"sourcesContent":["const HEX_COLOR = /^#([\\da-f]{3}|[\\da-f]{6})$/i;\nconst UNPREFIXED_HEX_COLOR = /^([\\da-f]{3}|[\\da-f]{6})$/i;\n\nexport function normalizeAccentColor(color: string) {\n const trimmedColor = color.trim();\n return UNPREFIXED_HEX_COLOR.test(trimmedColor)\n ? `#${trimmedColor}`\n : trimmedColor;\n}\n\nfunction parseHexColor(color: string) {\n const match = HEX_COLOR.exec(normalizeAccentColor(color));\n if (!match) {\n return;\n }\n const [, value] = match;\n if (!value) {\n return;\n }\n const expanded =\n value.length === 3\n ? Array.from(value, (character) => `${character}${character}`).join(\"\")\n : value;\n return [0, 2, 4].map((offset) =>\n Number.parseInt(expanded.slice(offset, offset + 2), 16)\n );\n}\n\nfunction relativeLuminance([red, green, blue]: number[]) {\n const [linearRed = 0, linearGreen = 0, linearBlue = 0] = [\n red,\n green,\n blue,\n ].map((channel = 0) => {\n const normalized = channel / 255;\n return normalized <= 0.040_45\n ? normalized / 12.92\n : ((normalized + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * linearRed + 0.7152 * linearGreen + 0.0722 * linearBlue;\n}\n\nexport function getAccentContrast(color: string) {\n const parsed = parseHexColor(color);\n if (!parsed) {\n return;\n }\n const luminance = relativeLuminance(parsed);\n const blackContrast = (luminance + 0.05) / 0.05;\n const whiteContrast = 1.05 / (luminance + 0.05);\n return blackContrast >= whiteContrast ? \"#000\" : \"#fff\";\n}\n","import type {\n LockerverseBooleanCustomField,\n LockerverseCustomField,\n LockerverseCustomFieldAnswer,\n LockerverseMultiOptionCustomField,\n LockerverseSingleOptionCustomField,\n} from \"@lockerverse/sdk/checkout\";\nimport {\n array,\n minLength,\n nonEmpty,\n pipe,\n safeParse,\n string,\n trim,\n} from \"valibot\";\n\nexport type CustomFieldValues = Record<string, boolean | string | string[]>;\n\nfunction createCustomFieldValue(field: LockerverseCustomField) {\n if (field.type === \"checkbox\") {\n return false;\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return [];\n }\n return \"\";\n}\n\nexport function createCustomFieldValues(fields: LockerverseCustomField[]) {\n const values: CustomFieldValues = {};\n for (const field of fields) {\n values[field.id] = createCustomFieldValue(field);\n }\n return values;\n}\n\nfunction getStringValue(value: CustomFieldValues[string] | undefined) {\n const result = safeParse(string(), value);\n return result.success ? result.output : \"\";\n}\n\nexport function buildCustomFieldAnswers(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n): LockerverseCustomFieldAnswer[] {\n return fields.map((field): LockerverseCustomFieldAnswer => {\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n return { fieldId: field.id, value: value === true };\n }\n if (field.type === \"checkboxes\" || field.type === \"multi_select\") {\n return { fieldId: field.id, value: Array.isArray(value) ? value : [] };\n }\n return {\n fieldId: field.id,\n value: getStringValue(value),\n };\n });\n}\n\nexport function validateCustomFields(\n fields: LockerverseCustomField[],\n values: CustomFieldValues\n) {\n const errors: Record<string, string> = {};\n for (const field of fields) {\n if (!field.required) {\n continue;\n }\n const message = `${field.label} is required.`;\n const value = values[field.id];\n if (field.type === \"checkbox\") {\n if (value !== true) {\n errors[field.id] = message;\n }\n continue;\n }\n const result =\n field.type === \"checkboxes\" || field.type === \"multi_select\"\n ? safeParse(pipe(array(string()), minLength(1, message)), value ?? [])\n : safeParse(\n pipe(string(), trim(), nonEmpty(message)),\n getStringValue(value)\n );\n if (!result.success) {\n errors[field.id] = result.issues[0]?.message ?? message;\n }\n }\n return errors;\n}\n\nexport function CustomFields({\n choiceClassName,\n errorClassName,\n errors,\n fields,\n idPrefix,\n onChange,\n values,\n}: {\n choiceClassName: string;\n errorClassName: string;\n errors: Record<string, string>;\n fields: LockerverseCustomField[];\n idPrefix: string;\n onChange: (values: CustomFieldValues) => void;\n values: CustomFieldValues;\n}) {\n return fields.map((field) => (\n <CustomField\n choiceClassName={choiceClassName}\n error={errors[field.id]}\n errorClassName={errorClassName}\n field={field}\n idPrefix={idPrefix}\n key={field.id}\n onChange={(value) => onChange({ ...values, [field.id]: value })}\n value={values[field.id]}\n />\n ));\n}\n\ntype CustomFieldProps = {\n choiceClassName: string;\n error: string | undefined;\n errorClassName: string;\n field: LockerverseCustomField;\n idPrefix: string;\n onChange: (value: boolean | string | string[]) => void;\n value: boolean | string | string[] | undefined;\n};\n\nfunction CustomField(props: CustomFieldProps) {\n const { field, idPrefix } = props;\n const controlId = `${idPrefix}-custom-${field.id}`;\n const errorId = `${controlId}-error`;\n const controlProps = { ...props, controlId, errorId };\n switch (field.type) {\n case \"checkbox\":\n return <BooleanCustomField {...controlProps} field={field} />;\n case \"text\":\n case \"textarea\":\n return <TextCustomField {...controlProps} field={field} />;\n case \"select\":\n case \"multi_select\":\n return <SelectCustomField {...controlProps} field={field} />;\n case \"radio\":\n case \"checkboxes\":\n return <ChoiceCustomField {...controlProps} field={field} />;\n default:\n return null;\n }\n}\n\nfunction BooleanCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & { field: LockerverseBooleanCustomField }) {\n return (\n <label className={choiceClassName} htmlFor={controlId}>\n <input\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n checked={value === true}\n id={controlId}\n name={`custom:${field.id}`}\n onChange={(event) => onChange(event.currentTarget.checked)}\n required={field.required}\n type=\"checkbox\"\n />\n <span>{field.label}</span>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\ntype ControlProps = CustomFieldProps & {\n controlId: string;\n errorId: string;\n};\n\nfunction FieldError({\n className,\n error,\n id,\n}: {\n className: string;\n error: string | undefined;\n id: string;\n}) {\n return error ? (\n <span className={className} id={id} role=\"alert\">\n {error}\n </span>\n ) : null;\n}\n\nfunction TextCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: Extract<LockerverseCustomField, { type: \"text\" | \"textarea\" }>;\n}) {\n const commonProps = {\n \"aria-describedby\": error ? errorId : undefined,\n \"aria-invalid\": error ? (\"true\" as const) : undefined,\n id: controlId,\n name: `custom:${field.id}`,\n onChange: (\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => onChange(event.currentTarget.value),\n required: field.required,\n value: getStringValue(value),\n };\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n {field.type === \"textarea\" ? (\n <textarea {...commonProps} />\n ) : (\n <input {...commonProps} />\n )}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction SelectCustomField({\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n return (\n <label htmlFor={controlId}>\n <span>{field.label}</span>\n <select\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n id={controlId}\n multiple={field.type === \"multi_select\"}\n name={`custom:${field.id}`}\n onChange={(event) =>\n onChange(\n field.type === \"multi_select\"\n ? [...event.currentTarget.selectedOptions].map(\n (option) => option.value\n )\n : event.currentTarget.value\n )\n }\n required={field.required}\n value={\n value === true || value === false\n ? \"\"\n : (value ?? (field.type === \"multi_select\" ? [] : \"\"))\n }\n >\n {field.type === \"select\" ? <option value=\"\">Select…</option> : null}\n {field.options.map((option) => (\n <option key={option.id} value={option.id}>\n {option.label}\n </option>\n ))}\n </select>\n <FieldError className={errorClassName} error={error} id={errorId} />\n </label>\n );\n}\n\nfunction ChoiceCustomField({\n choiceClassName,\n controlId,\n error,\n errorClassName,\n errorId,\n field,\n onChange,\n value,\n}: ControlProps & {\n field: LockerverseMultiOptionCustomField | LockerverseSingleOptionCustomField;\n}) {\n const selectedValues = Array.isArray(value) ? value : [];\n return (\n <fieldset\n aria-describedby={error ? errorId : undefined}\n aria-invalid={error ? \"true\" : undefined}\n >\n <legend>{field.label}</legend>\n {field.options.map((option, index) => (\n <label className={choiceClassName} key={option.id}>\n <input\n checked={\n Array.isArray(value)\n ? value.includes(option.id)\n : value === option.id\n }\n id={`${controlId}-${index}`}\n name={`custom:${field.id}`}\n onChange={(event) => {\n if (field.type === \"radio\") {\n onChange(option.id);\n return;\n }\n onChange(\n event.currentTarget.checked\n ? [...selectedValues, option.id]\n : selectedValues.filter((id) => id !== option.id)\n );\n }}\n required={field.required && field.type === \"radio\"}\n type={field.type === \"radio\" ? \"radio\" : \"checkbox\"}\n value={option.id}\n />\n <span>{option.label}</span>\n </label>\n ))}\n <FieldError className={errorClassName} error={error} id={errorId} />\n </fieldset>\n );\n}\n","export function FormSkeleton({\n fieldCount,\n label,\n sectionCount = 0,\n showCheckbox = false,\n}: {\n fieldCount: number;\n label: string;\n sectionCount?: number;\n showCheckbox?: boolean;\n}) {\n return (\n <div className=\"lockerverse-form-skeleton__loading\">\n <span className=\"lockerverse-form-skeleton__sr-only\" role=\"status\">\n {label}\n </span>\n <div aria-hidden=\"true\" className=\"lockerverse-form-skeleton\">\n <div className=\"lockerverse-form-skeleton__branding\">\n <span className=\"lockerverse-form-skeleton__avatar\" />\n <span className=\"lockerverse-form-skeleton__community\" />\n </div>\n <div className=\"lockerverse-form-skeleton__fields\">\n {Array.from({ length: fieldCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__field\" key={index}>\n <span className=\"lockerverse-form-skeleton__label\" />\n <span className=\"lockerverse-form-skeleton__input\" />\n </div>\n ))}\n </div>\n {Array.from({ length: sectionCount }, (_, index) => (\n <div className=\"lockerverse-form-skeleton__section\" key={index}>\n <span className=\"lockerverse-form-skeleton__section-label\" />\n <div className=\"lockerverse-form-skeleton__section-content\">\n <span className=\"lockerverse-form-skeleton__section-full\" />\n <div className=\"lockerverse-form-skeleton__section-grid\">\n <span className=\"lockerverse-form-skeleton__section-half\" />\n <span className=\"lockerverse-form-skeleton__section-half\" />\n </div>\n </div>\n </div>\n ))}\n <div className=\"lockerverse-form-skeleton__actions\">\n {showCheckbox ? (\n <span className=\"lockerverse-form-skeleton__check-line\" />\n ) : null}\n <span className=\"lockerverse-form-skeleton__button\" />\n </div>\n </div>\n </div>\n );\n}\n","import { email, nonEmpty, pipe, regex, string, transform, trim } from \"valibot\";\n\nexport const EMAIL_REQUIRED_MESSAGE = \"Email is required.\";\nexport const EMAIL_INVALID_MESSAGE = \"Enter a valid email address.\";\nexport const PHONE_REQUIRED_MESSAGE = \"Phone is required.\";\nexport const PHONE_INVALID_MESSAGE = \"Enter a valid phone number.\";\n\nconst OPTIONAL_EMAIL_PATTERN = /^(?:$|[^\\s@]+@[^\\s@]+\\.[^\\s@]+)$/;\nconst INTERNATIONAL_PHONE_PATTERN = /^\\+[1-9]\\d{6,14}$/;\nconst OPTIONAL_INTERNATIONAL_PHONE_PATTERN = /^(?:$|\\+[1-9]\\d{6,14})$/;\n\nexport function normalizePhone(input: string) {\n return input.trim().replace(/[().\\s-]/g, \"\");\n}\n\nexport const optionalEmailSchema = pipe(\n string(),\n trim(),\n regex(OPTIONAL_EMAIL_PATTERN, EMAIL_INVALID_MESSAGE)\n);\n\nexport const requiredEmailSchema = pipe(\n string(),\n trim(),\n nonEmpty(EMAIL_REQUIRED_MESSAGE),\n email(EMAIL_INVALID_MESSAGE)\n);\n\nexport const optionalPhoneSchema = pipe(\n string(),\n trim(),\n transform(normalizePhone),\n regex(OPTIONAL_INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n\nexport const requiredPhoneSchema = pipe(\n string(),\n trim(),\n nonEmpty(PHONE_REQUIRED_MESSAGE),\n transform(normalizePhone),\n regex(INTERNATIONAL_PHONE_PATTERN, PHONE_INVALID_MESSAGE)\n);\n","import {\n normalizePhone,\n PHONE_INVALID_MESSAGE,\n PHONE_REQUIRED_MESSAGE,\n} from \"./contact-validation.ts\";\n\nexport const PHONE_COUNTRIES = [\n {\n callingCode: \"+1\",\n label: \"🇺🇸 +1\",\n value: \"US\",\n },\n {\n callingCode: \"+52\",\n label: \"🇲🇽 +52\",\n value: \"MX\",\n },\n {\n callingCode: \"+380\",\n label: \"🇺🇦 +380\",\n value: \"UA\",\n },\n {\n callingCode: \"+48\",\n label: \"🇵🇱 +48\",\n value: \"PL\",\n },\n {\n callingCode: \"+1\",\n label: \"🇨🇦 +1\",\n value: \"CA\",\n },\n {\n callingCode: \"+49\",\n label: \"🇩🇪 +49\",\n value: \"DE\",\n },\n {\n callingCode: \"+44\",\n label: \"🇬🇧 +44\",\n value: \"GB\",\n },\n {\n callingCode: \"+46\",\n label: \"🇸🇪 +46\",\n value: \"SE\",\n },\n {\n callingCode: \"+358\",\n label: \"🇫🇮 +358\",\n value: \"FI\",\n },\n {\n callingCode: \"+1\",\n label: \"🇵🇷 +1\",\n value: \"PR\",\n },\n] as const;\n\nexport type PhoneCountry = (typeof PHONE_COUNTRIES)[number][\"value\"];\n\nexport function getPhoneServerError(serverCode: string | undefined) {\n if (\n serverCode === \"PAYMENT_WIDGET_PHONE_REQUIRED\" ||\n serverCode === \"SIGN_UP_WIDGET_PHONE_REQUIRED\"\n ) {\n return PHONE_REQUIRED_MESSAGE;\n }\n if (\n serverCode === \"PAYMENT_WIDGET_PHONE_INVALID\" ||\n serverCode === \"SIGN_UP_WIDGET_PHONE_INVALID\"\n ) {\n return PHONE_INVALID_MESSAGE;\n }\n}\n\nfunction getPhoneCountry(country: string) {\n return (\n PHONE_COUNTRIES.find((option) => option.value === country) ??\n PHONE_COUNTRIES[0]\n );\n}\n\nfunction removeRepeatedCallingCode(phone: string, callingCode: string) {\n const repeatedCallingCode = `${callingCode}${callingCode}`;\n let normalizedPhone = phone;\n while (normalizedPhone.startsWith(repeatedCallingCode)) {\n normalizedPhone = `${callingCode}${normalizedPhone.slice(repeatedCallingCode.length)}`;\n }\n return normalizedPhone;\n}\n\nexport function getInternationalPhone(phone: string, country: string) {\n const normalizedPhone = normalizePhone(phone);\n if (!normalizedPhone) {\n return \"\";\n }\n\n const selectedCountry = getPhoneCountry(country);\n const phoneWithOneCallingCode = removeRepeatedCallingCode(\n normalizedPhone,\n selectedCountry.callingCode\n );\n\n return phoneWithOneCallingCode.startsWith(\"+\")\n ? phoneWithOneCallingCode\n : `${selectedCountry.callingCode}${phoneWithOneCallingCode}`;\n}\n","export function notifyHostCallback<Value>(\n callback: ((value: Value) => void) | undefined,\n value: Value\n) {\n if (!callback) {\n return;\n }\n try {\n Promise.resolve(callback(value)).catch(() => undefined);\n } catch {\n // Host callback failures must not change completed SDK state.\n }\n}\n"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C5C,GAAI,CAAC,EACH,MAAO,GAGT,IAAM,EAAkB,EAAgB,CAAO,EACzC,EAA0B,EAC9B,EACA,EAAgB,WAClB,EAEA,OAAO,EAAwB,WAAW,GAAG,EACzC,EACA,GAAG,EAAgB,cAAc,GACvC,CC3GA,SAAgB,EACd,EACA,EACA,CACK,KAGL,GAAI,CACF,QAAQ,QAAQ,EAAS,CAAK,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,CACxD,MAAQ,CAER,CACF"}
@@ -1,2 +1,2 @@
1
- import{f as e,p as t}from"./host-callback.js";import{n,t as r}from"./lockerverse-payment.js";import{Dialog as i}from"@base-ui/react/dialog";import{getLockerverseMinimumCustomAmountCents as a}from"@lockerverse/sdk/checkout";import{createElement as o,useState as s}from"react";import{Fragment as c,jsx as l,jsxs as u}from"react/jsx-runtime";const d=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}),f=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,p=[1e3,2500,5e3,1e4];function m(e){if(!f.test(e))return null;let t=Math.round(Number(e)*100);return Number.isSafeInteger(t)&&t>0?t:null}function h(e,t){let n=``;return t===`monthly`&&(n=`/month`),t===`annually`&&(n=`/year`),`${d.format(e/100)}${n}`}function g({customAmounts:e,product:t,quantities:n,recurringProductId:r,setCustomAmounts:i,setQuantities:o,setRecurringProductId:s}){let c=n[t.id]??0;if(t.pricingMode===`fixed`&&t.paymentOption===`one-time`){let e=t.minimumQuantity??1,n=Math.min(t.maximumQuantity??1/0,t.inventoryQuantity??1/0);return u(`span`,{className:`lockerverse-launcher__quantity`,children:[l(`button`,{"aria-label":`Decrease ${t.name} quantity`,disabled:c===0,onClick:()=>{s(null),o(n=>{let r=n[t.id]??0;return{...n,[t.id]:r<=e?0:r-1}})},type:`button`,children:`−`}),l(`output`,{"aria-label":`${t.name} quantity`,children:c}),l(`button`,{"aria-label":`Increase ${t.name} quantity`,disabled:n<e||c>=n,onClick:()=>{s(null),o(n=>{let r=n[t.id]??0;return{...n,[t.id]:r===0?e:r+1}})},type:`button`,children:`+`})]})}return t.pricingMode===`custom`&&t.paymentOption===`one-time`?u(`span`,{className:`lockerverse-launcher__custom-amount`,children:[l(`span`,{"aria-hidden":`true`,children:`$`}),l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>{s(null),i(n=>({...n,[t.id]:e.target.value}))},placeholder:`0.00`,step:`0.01`,type:`number`,value:e[t.id]??``}),t.minimumAmountCents===null?null:u(`small`,{children:[`Minimum `,d.format(t.minimumAmountCents/100)]})]}):l(`button`,{"aria-label":`Select ${t.name}`,"aria-pressed":r===t.id,className:`lockerverse-launcher__select`,onClick:()=>{o({}),i({}),s(e=>e===t.id?null:t.id)},type:`button`,children:`Select`})}function _({variant:e=`default`,...t}){let{customAmounts:n,product:r,quantities:i,recurringProductId:o}=t,s=m(n[r.id]??``),c=o===r.id||r.paymentOption===`one-time`&&(r.pricingMode===`fixed`&&(i[r.id]??0)>0||r.pricingMode===`custom`&&s!==null&&s>=a(r));return u(`article`,{className:`lockerverse-launcher__product lockerverse-launcher__product--${e}`,"data-selected":c||void 0,children:[u(`span`,{className:`lockerverse-launcher__product-copy`,children:[l(`strong`,{className:`lockerverse-launcher__product-name`,children:r.name}),r.description?l(`small`,{children:r.description}):null,r.amountCents===null?null:l(`span`,{className:`lockerverse-launcher__product-price`,children:h(r.amountCents,r.paymentOption)})]}),l(g,{...t})]})}function v({customAmounts:e,product:t,setCustomAmounts:n,setRecurringProductId:r}){let i=e[t.id]??``,o=m(i),s=p.filter(e=>e>=a(t)),c=s.includes(o??0),f=e=>{r(null),n(n=>({...n,[t.id]:e}))};return l(`div`,{className:`lockerverse-launcher__donation-option`,children:u(`fieldset`,{className:`lockerverse-launcher__donation-choices`,children:[u(`legend`,{className:`lockerverse-launcher__sr-only`,children:[t.name,` amount`]}),l(`button`,{"aria-pressed":i===``,onClick:()=>f(``),type:`button`,children:`No thanks`}),s.map(e=>l(`button`,{"aria-pressed":o===e,onClick:()=>f(String(e/100)),type:`button`,children:d.format(e/100).replace(`.00`,``)},e)),l(`label`,{className:`lockerverse-launcher__donation-other`,"data-selected":i!==``&&!c||void 0,children:l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>f(e.target.value),placeholder:`Other $`,step:`0.01`,type:`number`,value:c?``:i})})]})})}function y({products:e,variant:t=`default`,...n}){return l(`div`,{className:`lockerverse-launcher__product-list`,children:e.map(e=>t===`donation`?o(v,{...n,key:e.id,product:e}):o(_,{...n,key:e.id,product:e,variant:t}))})}function b(e,t){let n=0,r=0;for(let i of t){let t=e.products.find(e=>e.slug===i.productSlug);if(t){if(`quantity`in i){n+=i.quantity,r+=(t.amountCents??0)*i.quantity;continue}n+=1,r+=`amountCents`in i?i.amountCents:t.amountCents??0}}return{amountCents:r,itemCount:n}}function x(){return l(`div`,{"aria-label":`Loading donation options`,className:`lockerverse-launcher__loading`,role:`status`,children:[0,1,2].map(e=>l(`span`,{"aria-hidden":`true`,className:`lockerverse-launcher__loading-row`},e))})}function S(e,t,n,r){if(r){let t=e.products.find(e=>e.id===r&&e.paymentOption!==`one-time`);return t?[{productSlug:t.slug}]:[]}return e.products.flatMap(e=>{let r=t[e.id]??0;if(e.pricingMode===`fixed`&&e.paymentOption===`one-time`&&r>0)return[{productSlug:e.slug,quantity:r}];let i=m(n[e.id]??``);return e.pricingMode===`custom`&&e.paymentOption===`one-time`&&i!==null&&i>=a(e)?[{amountCents:i,productSlug:e.slug}]:[]})}function C({catalog:e,onContinue:t,...n}){let r=S(e,n.quantities,n.customAmounts,n.recurringProductId),i=b(e,r),a=e.products.filter(e=>e.paymentOption===`one-time`&&e.pricingMode===`custom`),o=e.products.filter(e=>!a.includes(e));return u(`form`,{className:`lockerverse-launcher__products`,onSubmit:e=>{e.preventDefault(),r.length>0&&t(r)},children:[o.length>0?l(`section`,{className:`lockerverse-launcher__section`,children:l(y,{...n,products:o})}):null,a.length>0?u(`section`,{className:`lockerverse-launcher__donation`,children:[u(`header`,{className:`lockerverse-launcher__section-header`,children:[l(`h3`,{children:`Add a donation`}),l(`p`,{children:`Choose an amount to add to this order.`})]}),l(y,{...n,products:a,variant:`donation`})]}):null,e.products.length>0?u(`footer`,{className:`lockerverse-launcher__footer`,children:[u(`p`,{"aria-live":`polite`,className:`lockerverse-launcher__summary`,children:[l(`span`,{children:i.itemCount===0?`No items selected`:`${i.itemCount} ${i.itemCount===1?`item`:`items`} selected`}),i.itemCount===0?null:l(`strong`,{children:d.format(i.amountCents/100)})]}),l(`button`,{className:`lockerverse-launcher__continue`,disabled:r.length===0,type:`submit`,children:`Continue`})]}):null]})}function w({onEdit:e,paymentProps:t,selection:n,style:i,widget:a}){return u(`div`,{className:`lockerverse-launcher__checkout`,children:[l(`header`,{className:`lockerverse-launcher__checkout-toolbar`,children:l(`button`,{className:`lockerverse-launcher__back`,onClick:e,type:`button`,children:`Edit order`})}),l(r,{...t,selection:n,style:i,widget:a})]})}function T({catalog:e,checkout:t}){return t?u(c,{children:[l(i.Title,{className:`lockerverse-launcher__sr-only`,children:`Checkout`}),l(i.Description,{className:`lockerverse-launcher__sr-only`,children:`Review the order and complete payment.`})]}):e?u(`header`,{className:`lockerverse-launcher__header`,children:[e.community?u(`div`,{className:`lockerverse-launcher__brand`,children:[e.community.imageUrl?l(`img`,{alt:`${e.community.name} logo`,height:`28`,src:e.community.imageUrl,width:`28`}):null,l(`span`,{children:e.community.name})]}):null,l(i.Title,{className:`lockerverse-launcher__title`,children:e.widget.title??e.widget.name}),l(i.Description,{className:`lockerverse-launcher__description`,children:e.widget.description??`Choose your options, then continue to checkout.`})]}):u(`header`,{className:`lockerverse-launcher__header`,children:[l(i.Title,{className:`lockerverse-launcher__title`,children:`Donate`}),l(i.Description,{className:`lockerverse-launcher__description`,children:`Choose your options, then continue to checkout.`})]})}function E({buttonLabel:r=`Donate`,position:a=`inline`,widget:o,...c}){let[d,f]=s(null),[p,m]=s({}),[h,g]=s({}),[_,v]=s(null),{catalog:y,error:b,loading:S}=o,E=t(c.style?.[`--lockerverse-accent`]??y?.community?.accentColor??`#38d77a`),D=e(E),O={...c.style};(c.style?.[`--lockerverse-accent`]!==void 0||y?.community?.accentColor)&&(O[`--lockerverse-accent`]=E),D&&c.style?.[`--lockerverse-accent-contrast`]===void 0&&(O[`--lockerverse-accent-contrast`]=D);let k;return k=S?l(x,{}):b?u(`div`,{role:`alert`,children:[l(`p`,{children:`Unable to load donation options.`}),l(`button`,{onClick:o.refresh,type:`button`,children:`Retry`})]}):y?l(C,{catalog:y,customAmounts:p,onContinue:f,quantities:h,recurringProductId:_,setCustomAmounts:m,setQuantities:g,setRecurringProductId:v}):l(x,{}),!(S||b)&&d&&y&&(k=l(w,{onEdit:()=>f(null),paymentProps:c,selection:d,style:O,widget:o})),u(i.Root,{onOpenChange:e=>{e&&y&&c.stripeLoader===void 0&&requestAnimationFrame(()=>{n(y)})},children:[l(i.Trigger,{className:`lockerverse-launcher lockerverse-launcher--${a}`,"data-lockerverse-theme":c.theme??`dark`,style:O,children:r}),u(i.Portal,{children:[l(i.Backdrop,{className:`lockerverse-launcher__backdrop`}),l(i.Viewport,{className:`lockerverse-launcher__viewport`,children:u(i.Popup,{className:`lockerverse-launcher__dialog`,"data-lockerverse-theme":c.theme??`dark`,style:O,children:[l(T,{catalog:y,checkout:d!==null}),l(i.Close,{"aria-label":`Close donation dialog`,className:`lockerverse-launcher__close`,children:l(`span`,{"aria-hidden":`true`,children:`×`})}),k]})})]})]})}export{E as t};
1
+ import{g as e,h as t}from"./host-callback.js";import{n,t as r}from"./lockerverse-payment.js";import{Dialog as i}from"@base-ui/react/dialog";import{getLockerverseMinimumCustomAmountCents as a}from"@lockerverse/sdk/checkout";import{createElement as o,useState as s}from"react";import{Fragment as c,jsx as l,jsxs as u}from"react/jsx-runtime";const d=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}),f=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,p=[1e3,2500,5e3,1e4];function m(e){if(!f.test(e))return null;let t=Math.round(Number(e)*100);return Number.isSafeInteger(t)&&t>0?t:null}function h(e,t){let n=``;return t===`monthly`&&(n=`/month`),t===`annually`&&(n=`/year`),`${d.format(e/100)}${n}`}function g({customAmounts:e,product:t,quantities:n,recurringProductId:r,setCustomAmounts:i,setQuantities:o,setRecurringProductId:s}){let c=n[t.id]??0;if(t.pricingMode===`fixed`&&t.paymentOption===`one-time`){let e=t.minimumQuantity??1,n=Math.min(t.maximumQuantity??1/0,t.inventoryQuantity??1/0);return u(`span`,{className:`lockerverse-launcher__quantity`,children:[l(`button`,{"aria-label":`Decrease ${t.name} quantity`,disabled:c===0,onClick:()=>{s(null),o(n=>{let r=n[t.id]??0;return{...n,[t.id]:r<=e?0:r-1}})},type:`button`,children:`−`}),l(`output`,{"aria-label":`${t.name} quantity`,children:c}),l(`button`,{"aria-label":`Increase ${t.name} quantity`,disabled:n<e||c>=n,onClick:()=>{s(null),o(n=>{let r=n[t.id]??0;return{...n,[t.id]:r===0?e:r+1}})},type:`button`,children:`+`})]})}return t.pricingMode===`custom`&&t.paymentOption===`one-time`?u(`span`,{className:`lockerverse-launcher__custom-amount`,children:[l(`span`,{"aria-hidden":`true`,children:`$`}),l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>{s(null),i(n=>({...n,[t.id]:e.target.value}))},placeholder:`0.00`,step:`0.01`,type:`number`,value:e[t.id]??``}),t.minimumAmountCents===null?null:u(`small`,{children:[`Minimum `,d.format(t.minimumAmountCents/100)]})]}):l(`button`,{"aria-label":`Select ${t.name}`,"aria-pressed":r===t.id,className:`lockerverse-launcher__select`,onClick:()=>{o({}),i({}),s(e=>e===t.id?null:t.id)},type:`button`,children:`Select`})}function _({variant:e=`default`,...t}){let{customAmounts:n,product:r,quantities:i,recurringProductId:o}=t,s=m(n[r.id]??``),c=o===r.id||r.paymentOption===`one-time`&&(r.pricingMode===`fixed`&&(i[r.id]??0)>0||r.pricingMode===`custom`&&s!==null&&s>=a(r));return u(`article`,{className:`lockerverse-launcher__product lockerverse-launcher__product--${e}`,"data-selected":c||void 0,children:[u(`span`,{className:`lockerverse-launcher__product-copy`,children:[l(`strong`,{className:`lockerverse-launcher__product-name`,children:r.name}),r.description?l(`small`,{children:r.description}):null,r.amountCents===null?null:l(`span`,{className:`lockerverse-launcher__product-price`,children:h(r.amountCents,r.paymentOption)})]}),l(g,{...t})]})}function v({customAmounts:e,product:t,setCustomAmounts:n,setRecurringProductId:r}){let i=e[t.id]??``,o=m(i),s=p.filter(e=>e>=a(t)),c=s.includes(o??0),f=e=>{r(null),n(n=>({...n,[t.id]:e}))};return l(`div`,{className:`lockerverse-launcher__donation-option`,children:u(`fieldset`,{className:`lockerverse-launcher__donation-choices`,children:[u(`legend`,{className:`lockerverse-launcher__sr-only`,children:[t.name,` amount`]}),l(`button`,{"aria-pressed":i===``,onClick:()=>f(``),type:`button`,children:`No thanks`}),s.map(e=>l(`button`,{"aria-pressed":o===e,onClick:()=>f(String(e/100)),type:`button`,children:d.format(e/100).replace(`.00`,``)},e)),l(`label`,{className:`lockerverse-launcher__donation-other`,"data-selected":i!==``&&!c||void 0,children:l(`input`,{"aria-label":`${t.name} amount`,min:a(t)/100,name:`amount-${t.slug}`,onChange:e=>f(e.target.value),placeholder:`Other $`,step:`0.01`,type:`number`,value:c?``:i})})]})})}function y({products:e,variant:t=`default`,...n}){return l(`div`,{className:`lockerverse-launcher__product-list`,children:e.map(e=>t===`donation`?o(v,{...n,key:e.id,product:e}):o(_,{...n,key:e.id,product:e,variant:t}))})}function b(e,t){let n=0,r=0;for(let i of t){let t=e.products.find(e=>e.slug===i.productSlug);if(t){if(`quantity`in i){n+=i.quantity,r+=(t.amountCents??0)*i.quantity;continue}n+=1,r+=`amountCents`in i?i.amountCents:t.amountCents??0}}return{amountCents:r,itemCount:n}}function x(){return l(`div`,{"aria-label":`Loading donation options`,className:`lockerverse-launcher__loading`,role:`status`,children:[0,1,2].map(e=>l(`span`,{"aria-hidden":`true`,className:`lockerverse-launcher__loading-row`},e))})}function S(e,t,n,r){if(r){let t=e.products.find(e=>e.id===r&&e.paymentOption!==`one-time`);return t?[{productSlug:t.slug}]:[]}return e.products.flatMap(e=>{let r=t[e.id]??0;if(e.pricingMode===`fixed`&&e.paymentOption===`one-time`&&r>0)return[{productSlug:e.slug,quantity:r}];let i=m(n[e.id]??``);return e.pricingMode===`custom`&&e.paymentOption===`one-time`&&i!==null&&i>=a(e)?[{amountCents:i,productSlug:e.slug}]:[]})}function C({catalog:e,onContinue:t,...n}){let r=S(e,n.quantities,n.customAmounts,n.recurringProductId),i=b(e,r),a=e.products.filter(e=>e.paymentOption===`one-time`&&e.pricingMode===`custom`),o=e.products.filter(e=>!a.includes(e));return u(`form`,{className:`lockerverse-launcher__products`,onSubmit:e=>{e.preventDefault(),r.length>0&&t(r)},children:[o.length>0?l(`section`,{className:`lockerverse-launcher__section`,children:l(y,{...n,products:o})}):null,a.length>0?u(`section`,{className:`lockerverse-launcher__donation`,children:[u(`header`,{className:`lockerverse-launcher__section-header`,children:[l(`h3`,{children:`Add a donation`}),l(`p`,{children:`Choose an amount to add to this order.`})]}),l(y,{...n,products:a,variant:`donation`})]}):null,e.products.length>0?u(`footer`,{className:`lockerverse-launcher__footer`,children:[u(`p`,{"aria-live":`polite`,className:`lockerverse-launcher__summary`,children:[l(`span`,{children:i.itemCount===0?`No items selected`:`${i.itemCount} ${i.itemCount===1?`item`:`items`} selected`}),i.itemCount===0?null:l(`strong`,{children:d.format(i.amountCents/100)})]}),l(`button`,{className:`lockerverse-launcher__continue`,disabled:r.length===0,type:`submit`,children:`Continue`})]}):null]})}function w({onEdit:e,paymentProps:t,selection:n,style:i,widget:a}){return u(`div`,{className:`lockerverse-launcher__checkout`,children:[l(`header`,{className:`lockerverse-launcher__checkout-toolbar`,children:l(`button`,{className:`lockerverse-launcher__back`,onClick:e,type:`button`,children:`Edit order`})}),l(r,{...t,selection:n,style:i,widget:a})]})}function T({catalog:e,checkout:t}){return t?u(c,{children:[l(i.Title,{className:`lockerverse-launcher__sr-only`,children:`Checkout`}),l(i.Description,{className:`lockerverse-launcher__sr-only`,children:`Review the order and complete payment.`})]}):e?u(`header`,{className:`lockerverse-launcher__header`,children:[e.community?u(`div`,{className:`lockerverse-launcher__brand`,children:[e.community.imageUrl?l(`img`,{alt:`${e.community.name} logo`,height:`28`,src:e.community.imageUrl,width:`28`}):null,l(`span`,{children:e.community.name})]}):null,l(i.Title,{className:`lockerverse-launcher__title`,children:e.widget.title??e.widget.name}),l(i.Description,{className:`lockerverse-launcher__description`,children:e.widget.description??`Choose your options, then continue to checkout.`})]}):u(`header`,{className:`lockerverse-launcher__header`,children:[l(i.Title,{className:`lockerverse-launcher__title`,children:`Donate`}),l(i.Description,{className:`lockerverse-launcher__description`,children:`Choose your options, then continue to checkout.`})]})}function E({buttonLabel:r=`Donate`,position:a=`inline`,widget:o,...c}){let[d,f]=s(null),[p,m]=s({}),[h,g]=s({}),[_,v]=s(null),{catalog:y,error:b,loading:S}=o,E=e(c.style?.[`--lockerverse-accent`]??y?.community?.accentColor??`#38d77a`),D=t(E),O={...c.style};(c.style?.[`--lockerverse-accent`]!==void 0||y?.community?.accentColor)&&(O[`--lockerverse-accent`]=E),D&&c.style?.[`--lockerverse-accent-contrast`]===void 0&&(O[`--lockerverse-accent-contrast`]=D);let k;return k=S?l(x,{}):b?u(`div`,{role:`alert`,children:[l(`p`,{children:`Unable to load donation options.`}),l(`button`,{onClick:o.refresh,type:`button`,children:`Retry`})]}):y?l(C,{catalog:y,customAmounts:p,onContinue:f,quantities:h,recurringProductId:_,setCustomAmounts:m,setQuantities:g,setRecurringProductId:v}):l(x,{}),!(S||b)&&d&&y&&(k=l(w,{onEdit:()=>f(null),paymentProps:c,selection:d,style:O,widget:o})),u(i.Root,{onOpenChange:e=>{e&&y&&c.stripeLoader===void 0&&requestAnimationFrame(()=>{n(y)})},children:[l(i.Trigger,{className:`lockerverse-launcher lockerverse-launcher--${a}`,"data-lockerverse-theme":c.theme??`dark`,style:O,children:r}),u(i.Portal,{children:[l(i.Backdrop,{className:`lockerverse-launcher__backdrop`}),l(i.Viewport,{className:`lockerverse-launcher__viewport`,children:u(i.Popup,{className:`lockerverse-launcher__dialog`,"data-lockerverse-theme":c.theme??`dark`,style:O,children:[l(T,{catalog:y,checkout:d!==null}),l(i.Close,{"aria-label":`Close donation dialog`,className:`lockerverse-launcher__close`,children:l(`span`,{"aria-hidden":`true`,children:`×`})}),k]})})]})]})}export{E as t};
2
2
  //# sourceMappingURL=lockerverse-donate-launcher.js.map
@@ -1,2 +1,2 @@
1
- import{a as e,c as t,d as n,f as r,l as i,n as a,o,p as s,s as c,t as l,u}from"./host-callback.js";import{LockerverseSdkError as d,estimateLockerverseCheckout as f}from"@lockerverse/sdk/checkout";import{createContext as p,useCallback as m,useContext as h,useEffect as g,useId as _,useLayoutEffect as v,useMemo as y,useReducer as b,useRef as x,useState as S}from"react";import{AddressElement as C,Elements as w,PaymentElement as T,useElements as E,useStripe as D}from"@stripe/react-stripe-js";import{loadStripe as O}from"@stripe/stripe-js/pure/index.js";import{array as k,minLength as A,minValue as j,nonEmpty as M,number as N,object as P,pipe as F,regex as I,safeInteger as L,safeParse as R,strictObject as z,string as B,trim as V,union as H}from"valibot";import{Fragment as ee,jsx as U,jsxs as W}from"react/jsx-runtime";import{Select as G}from"@base-ui/react/select";const te=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`});function K(e){return te.format(e/100)}const ne=p(void 0);function re({children:e,container:t}){return U(ne.Provider,{value:t,children:e})}function q(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m4 6 4 4 4-4`})})}function J(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m3 8 3 3 7-7`})})}function ie({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=h(ne),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return U(`div`,{className:d,children:W(G.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[W(G.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[U(G.Value,{}),U(G.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:U(q,{})})]}),U(G.Portal,{container:u,children:U(G.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:U(G.Popup,{className:`lockerverse-payment__select-popup`,children:U(G.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>W(G.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[U(G.ItemText,{children:e.label}),U(G.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:U(J,{})})]},e.value))})})})})]})})}const ae=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],Y=[`15`,`12`,`10`,`5`],X=[...Y,`custom`];function oe({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=X.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%X.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+X.length)%X.length;break;case`Home`:r=0;break;case`End`:r=X.length-1;break;default:return}e.preventDefault();let i=X[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return W(`div`,{className:`lockerverse-payment__tip-box`,children:[U(`p`,{children:`Add a tip to support the Lockerverse platform`}),W(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[Y.map(e=>W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),W(`span`,{children:[e,`%`]})]},e)),W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),U(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?W(`label`,{children:[U(`span`,{children:`Custom tip`}),W(`span`,{className:`lockerverse-payment__money-input`,children:[U(`span`,{"aria-hidden":`true`,children:`$`}),U(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?U(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):U(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function se({checked:e,children:t,name:n,onChange:r}){return W(`label`,{className:`lockerverse-payment__check-row`,children:[U(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),U(`span`,{children:t})]})}function ce({customFields:e,errors:n,fields:r,idPrefix:i,isPromoApplying:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return W(`div`,{className:`lockerverse-payment__additional-fields`,children:[r.memberId?W(`label`,{children:[U(`span`,{children:`Member ID`}),U(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,r.merchSize?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${i}-merch-size-label`,children:`Size`}),U(ie,{ariaLabelledBy:`${i}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=ae.find(t=>t===e);t&&u({merchSize:t})},options:ae.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,r.promoCode?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${i}-promo-code-label`,children:`Promo code`}),W(`div`,{className:`lockerverse-payment__promo-control`,children:[U(`input`,{"aria-describedby":c?`${i}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${i}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),U(`button`,{disabled:!l.promoCode.trim()||a,onClick:s,type:`button`,children:a?`Applying…`:`Apply`})]}),c?U(`p`,{className:`lockerverse-payment__field-message`,id:`${i}-promo-code-error`,role:`alert`,children:c}):null]}):null,U(t,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:n,fields:e,idPrefix:i,onChange:e=>u({customFields:e}),values:l.customFields})]})}function le({amountCents:e,enabled:t,onChange:n,values:r}){return t?W(se,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,K(e),` to help cover processing fees`]}):null}function ue(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function Z(e,t,n){return t.includes(e.status)?{...e,...n}:e}function de(e,t){if(e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return Z(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return Z(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return Z(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return Z(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return Z(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return Z(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`quote_changed`:return Z(e,[`submitting`],{status:`editing`});case`retryable_failure`:return Z(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return Z(e,[`recovering`],{error:t.error,status:`editing`});case`succeeded`:return Z(e,[`recovering`,`submitting`],{message:t.message,status:`succeeded`});case`unresolved`:return Z(e,[`recovering`,`submitting`],{message:t.message,status:`unresolved`});default:return e}}function fe(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function pe(e){return e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:fe(e)?`error`:`idle`}function me(e){return e.status===`submitting`}function he(e){return a(e)}function ge(t,n){let r=n?{...t,phone:he(t.phone)}:t,i=P(n?{email:e,phone:o}:{email:e}),a=R(i,r);if(a.success)return{errors:{},value:a.output};let s={};for(let e of a.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!s[t]&&(s[t]=e.message)}return{errors:s,value:null}}const _e=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],ve=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function ye(e,t,n,r){return(n===t.totalCents?ve:_e).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function be(e){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function Q(e,t,n){if(t.checkoutStatus!==`action_required`)return be(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return be(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function xe(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof d&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return Q(e,r,n)}async function Se(e,t,n){try{return Q(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const Ce=F(B(),V(),M()),we=F(N(),L(),j(1)),Te=F(k(H([z({amountCents:we,productSlug:Ce}),z({productSlug:Ce,quantity:we}),z({productSlug:Ce})])),A(1)),Ee=F(B(),V(),I(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function De(e){let t=R(Ee,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function Oe(e){let t=R(Te,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const ke=`This promo code is invalid or cannot be applied.`;function Ae(e,t){return t.tipPercent===`custom`?t.customTip.trim()?De(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function je(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function Me(e,t,n){let r=e.widget.fields.tipping?Ae(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Ne(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?ke:void 0}}function Pe(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?ke:void 0}}function Fe(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Ie(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Fe(r.shipping,`Shipping`)}function Le({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function Re({catalog:e,confirmationToken:t,email:n,fieldValues:r,metadata:a,phone:o,shippingAddress:s}){let c={customFieldAnswers:i(e.widget.customFields,r.customFields),email:n};if(t&&(c.confirmationToken=t),a&&(c.metadata=a),e.widget.fields.memberId&&r.memberId.trim()&&(c.memberId=r.memberId.trim()),e.widget.fields.merchSize&&(c.merchSize=r.merchSize),e.widget.fields.phone&&(c.phone=o),s){let e={city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,postal_code:s.address.postal_code??``,state:s.address.state??``};s.address.line2&&(e.line2=s.address.line2),c.shipping={address:e,name:s.name}}return c}function ze(e){if(!e())throw Error(`Payment component is no longer active.`)}function Be(e,t){l(e,t)}function Ve(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function He({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=he(d),_=Ae(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...je(t,o,h,_.cents),catalog:t,items:n});if(ze(s),v.totalCents>0&&ye(f,v,c,m))return{kind:`quote_changed`,quote:v};let y,b;if(v.totalCents===0)t.widget.fields.shipping&&(y=Ie(t,o,Fe(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),ze(s);let n=await i.submit();if(ze(s),n.error)throw Error(n.error.message);let r=Fe(e.billing,`Billing`);y=Ie(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:Le({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:y})});if(ze(s),a.error)throw Error(a.error.message);b=a.confirmationToken.id}Be(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let x=await xe(r,{checkout:v,submission:Re({catalog:t,confirmationToken:b,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:y})},p);return ze(s),Ve(x,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function Ue(e,t){l(e,t)}function We(e,t){l(e,t)}function Ge(e,t){return{...e,...t}}function Ke(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!t&&!n}function qe({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Ne(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Je({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Pe(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function Ye({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:r,result:i,setDisplayedTotalCents:a,dispatchState:o}){if(i.kind===`quote_changed`){let e=`The total changed to ${K(i.quote.totalCents)}. Review it and pay again.`;r(i.quote,e),a(i.quote.totalCents),o({type:`quote_changed`});return}if(i.kind===`payment_failed`){Ue(t,null),o({error:i.message,type:`retryable_failure`});return}if(i.kind===`payment_unresolved`){o({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),We(n,{paymentReference:i.paymentReference,reason:i.reason});return}r(i.quote),Ue(t,null),o({message:i.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),l(e,Ge(i.payment,{email:i.email,lineItems:i.quote.lineItems}))}function Xe(e){let{catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,metadata:s,onPaymentComplete:c,onResumePaymentFailed:u,onPaymentRecoveryChange:d,onPaymentUncertain:f,onQuoteChange:p,onStateChange:h,quote:_,resumePayment:v,stripe:y,stripeConnectedAccountId:b,stripeLoadFailed:C,paymentState:w,updateState:T}=e,[E,D]=S(_.totalCents),[O,k]=S(),A=x(!1),j=x(0),M=x(0),N=m(e=>T(e,!0),[T]),P=m(()=>{let e=M.current+1;return M.current=e,()=>M.current===e},[]);g(()=>()=>{M.current+=1,j.current+=1},[]);let{parsedTip:F,totalCents:I}=Me(t,o,_);g(()=>{I!==null&&(D(I),I>0&&i?.update({amount:I}))},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,i,o.includeServiceFee,I,_.serviceFeeCents,_.tipCents,_.totalCents,_.subtotalCents]),g(()=>{if(!v||A.current||w.status!==`recovering`)return;A.current=!0;let e=P();return h(pe(w)),Se(r,v.paymentReference,y).then(t=>{if(e()&&!Ke(t,y,C)){if(t.kind===`failed`){Ue(d,null),u(),N({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){N({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),We(f,{paymentReference:t.paymentReference,reason:t.reason});return}Ue(d,null),N({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),l(c,Ge(t.payment,{email:null,lineItems:null}))}}),()=>{e()&&(M.current+=1),A.current=!1}},[r,c,u,d,f,h,v,y,C,P,N,w]);let L=m((e=!1,t=!1)=>{t||(j.current+=1),e&&k(void 0),T({type:`field_changed`})},[T]);async function R(e=!1,i=!1){let s=ge({email:a.trim().toLowerCase(),phone:``},!1);if(!(F.success&&(s.value||e)))return;j.current+=1;let c=j.current;T({type:`quote_refresh_started`});try{let e=await r.calculateTotal({...je(t,o,s.value?.email??``,F.cents),catalog:t,items:n});if(c!==j.current)return;qe({nextQuote:e,onQuoteChange:p,setDisplayedTotalCents:D,setPromoError:k,updateState:T,validatePromo:i})}catch(e){if(c!==j.current)return;Je({error:e,setPromoError:k,updateState:T,validatePromo:i})}}async function z(){k(void 0),await R(!0,!0)}async function B({addresses:e,phone:l}){N({type:`submission_started`});let u=P();try{let m=await He({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:u,locallyPreviewedTotalCents:E,metadata:s,onPaymentRecoveryChange:d,phone:l,quote:_,stripe:y,stripeConnectedAccountId:b});if(!u())return;Ye({dispatchState:N,onPaymentComplete:c,onPaymentRecoveryChange:d,onPaymentUncertain:f,onQuoteChange:p,result:m,setDisplayedTotalCents:D})}catch(e){if(!u())return;Ue(d,null),N({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let V=w.status===`succeeded`||w.status===`unresolved`?w.message:void 0;return{commands:{applyPromo:z,fieldChanged:L,refreshAuthoritativeTotal:R,reportStripeLoadError:e=>N({error:e,type:`retryable_failure`}),reportValidationFailure:()=>N({type:`validation_failed`}),submit:B},state:{displayedTotalCents:E,isRecovering:w.status===`recovering`,isRefreshingQuote:w.status===`refreshing_quote`,isSubmitting:me(w),parsedTip:F,paymentError:fe(w),promoError:O,terminalMessage:V}}}const Ze=new Map,Qe=(e,t)=>{let n=t?.stripeAccount??null,r=Ze.get(e);r||(r=new Map,Ze.set(e,r));let i=r.get(n);if(i)return i;let a=O(e,t).catch(()=>(r?.get(n)===a&&(r.delete(n),r.size===0&&Ze.delete(e)),null));return r.set(n,a),a};function $e(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return Qe(n,t?{stripeAccount:t}:void 0)}function et(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}const tt=[{callingCode:`+1`,label:`🇺🇸 +1`,value:`US`},{callingCode:`+52`,label:`🇲🇽 +52`,value:`MX`},{callingCode:`+380`,label:`🇺🇦 +380`,value:`UA`},{callingCode:`+48`,label:`🇵🇱 +48`,value:`PL`},{callingCode:`+1`,label:`🇨🇦 +1`,value:`CA`},{callingCode:`+49`,label:`🇩🇪 +49`,value:`DE`},{callingCode:`+44`,label:`🇬🇧 +44`,value:`GB`},{callingCode:`+46`,label:`🇸🇪 +46`,value:`SE`},{callingCode:`+358`,label:`🇫🇮 +358`,value:`FI`},{callingCode:`+1`,label:`🇵🇷 +1`,value:`PR`}];function nt(e,t){return e.trim().startsWith(`+`)?e:`${tt.find(e=>e.value===t)?.callingCode??`+1`}${e}`}function rt(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function it({accentColor:e,catalog:t,checkoutItems:n,client:r,fontFamily:i,metadata:a,onPaymentComplete:o,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,quote:d,resumePayment:f,onStateChange:p,stripeLoader:h,theme:_,visualStyle:v}){let[b,C]=S(()=>ue(!!f)),T=x(b);T.current=b;let E=m((e,t=!1)=>{let n=de(T.current,e);n!==T.current&&(T.current=n,C(n),t&&p(pe(n)))},[p]),D=rt(t,d,f),O=x({connectedAccountId:D,paymentOption:d.paymentOption});b.status!==`submitting`&&b.status!==`recovering`&&(O.current={connectedAccountId:D,paymentOption:d.paymentOption});let{connectedAccountId:k,paymentOption:A}=O.current,j=y(()=>h(t.payment.publishableKey,k?{stripeAccount:k}:void 0).catch(()=>null),[t.payment.publishableKey,k,h]),[M,N]=S(!1);return g(()=>{let e=!0;return N(!1),j.then(t=>{e&&t===null&&N(!0)}),()=>{e=!1}},[j]),U(w,{options:{amount:Math.max(d.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:_===`light`?`stripe`:`night`,variables:{borderRadius:v?.[`--lockerverse-radius`]??`10px`,colorBackground:v?.[`--lockerverse-control`]??(_===`light`?`#f5f6f7`:`#121212`),colorDanger:v?.[`--lockerverse-danger`]??(_===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:v?.[`--lockerverse-text`]??(_===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:v?.[`--lockerverse-placeholder`]??(_===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:v?.[`--lockerverse-muted`]??(_===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:t.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:A===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:j,children:U(ht,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:s,onStateChange:p,paymentState:b,quote:d,resumePayment:f,stripeConnectedAccountId:k,stripeLoadFailed:M,updateState:E})},`${t.payment.publishableKey}:${k??`platform`}:${A}`)}function at({label:e}){return W(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[U(`p`,{children:e}),W(`div`,{"aria-hidden":`true`,children:[U(`span`,{}),U(`span`,{}),U(`span`,{})]})]})}function ot({onError:e,onReady:t,ready:n}){return W(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:U(at,{label:`Loading payment form...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(T,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function st({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return W(`div`,{className:`lockerverse-payment__address`,children:[U(`h2`,{children:e}),W(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:U(at,{label:`Loading ${e.toLowerCase()}...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(C,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function ct({message:e}){return e?U(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function lt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return W(ee,{children:[f?U(ot,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?U(st,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?W(`div`,{className:`lockerverse-payment__shipping`,children:[U(se,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:U(st,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function ut({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let i=et(r.paymentOption),a=Math.max(0,e-r.subtotalCents+r.discountCents);return W(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[U(`h2`,{children:`Order summary`}),U(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>W(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[W(`span`,{children:[e.productName,e.quantity>1?W(ee,{children:[` `,W(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?U(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?U(`small`,{children:` · Annual`}):null]}),U(`strong`,{children:K(e.subtotalCents)})]},e.listingId))}),W(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[a>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[U(`span`,{children:`Service fee`}),U(`strong`,{children:K(a)})]}):null,r.discountCents>0&&r.appliedDiscount?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[W(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),W(`strong`,{children:[`-`,K(r.discountCents)]})]}):null,t>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[U(`span`,{children:`Tip`}),U(`strong`,{children:K(t)})]}):null,W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[U(`span`,{children:i?`${i.label} total`:`Total`}),U(`strong`,{children:K(n)})]})]})]})}function dt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isRequiredShippingReady:a,isSubmitting:o,onFieldValuesChange:s,quote:c}){let l=t===0,u=l?!e.widget.fields.shipping||r&&a:i&&r&&a,d=et(c.paymentOption),f=l?`Complete order`:`Pay ${K(t)}`;!l&&d&&(f=`Subscribe for ${K(t)}/${d.interval}`),o&&(f=l?`Completing…`:`Processing…`);let p=`Process payment for ${K(t)} total`;return l?p=`Complete order`:d&&(p=`Start ${d.label.toLowerCase()} subscription for ${K(t)}`),W(`div`,{className:`lockerverse-payment__actions`,children:[U(le,{amountCents:c.serviceFeeCents||Math.round(c.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:s,values:n}),U(`button`,{"aria-busy":o,"aria-label":p,disabled:o||!u,type:`submit`,children:f})]})}function ft(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function pt({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&ft(n,`custom:${o}`)}function mt({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:l,phone:u,phoneCountry:d,phoneEnabled:f,phoneErrorId:p,phoneId:m,phoneRef:h}){return W(`div`,{className:`lockerverse-payment__contact`,children:[U(`label`,{htmlFor:r,children:`Email`}),U(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?U(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:W(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),f?W(ee,{children:[U(`label`,{htmlFor:m,children:`Phone`}),W(`div`,{className:`lockerverse-payment__phone-control`,children:[U(ie,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:l,options:tt,value:d}),U(`input`,{"aria-describedby":a.phone?p:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:m,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:h,type:`tel`,value:u})]}),a.phone?U(`p`,{className:`lockerverse-payment__field-message`,id:p,children:a.phone}):null]}):null]})}function ht({catalog:e,checkoutItems:t,client:r,metadata:i,onPaymentComplete:a,onResumePaymentFailed:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,onStateChange:d,quote:f,resumePayment:p,stripeConnectedAccountId:m,stripeLoadFailed:h,paymentState:v,updateState:y}){let[b,C]=S(``),[w,T]=S(``),[O,k]=S(`US`),[A,j]=S({}),[M,N]=S({}),[P,F]=S(),[I,L]=S(!1),[R,z]=S(!1),[B,V]=S(!1),[H,ee]=S({customFields:u(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),G=x({billing:null,shipping:null}),te=x(null),K=x(null),ne=x(null),re=x(f.totalCents>0),q=Xe({catalog:e,checkoutItems:t,client:r,elements:E(),email:b,fieldValues:H,metadata:i,onPaymentComplete:a,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,onResumePaymentFailed:o,onStateChange:d,paymentState:v,quote:f,resumePayment:p,stripe:D(),stripeConnectedAccountId:m,stripeLoadFailed:h,updateState:y}),{displayedTotalCents:J,isRecovering:ie,isRefreshingQuote:ae,isSubmitting:Y,parsedTip:X,paymentError:se,promoError:le,terminalMessage:ue}=q.state,Z=`lockerverse-${_()}`,de=`${Z}-email`,fe=`${de}-error`,pe=`${Z}-phone`,me=`${pe}-error`,he=`${Z}-tip-error`,_e=(X.success?X.cents:null)??0,ve=J-_e,ye=!e.widget.fields.shipping||H.shippingMatchesBilling||B;g(()=>{Y&&ne.current?.focus({preventScroll:!0})},[Y]),g(()=>{let e=J>0;e&&!re.current&&(L(!1),z(!1)),re.current=e},[J]);function be(e){q.commands.fieldChanged(!1,e!==`email`),j(t=>{let n={...t};return delete n[e],n})}function Q(e){let t=e.promoCode!==H.promoCode,n=e.includeServiceFee!==H.includeServiceFee;q.commands.fieldChanged(t,!(t||n)),ee(e),N({}),F(void 0)}async function xe(t){t.preventDefault();let r=ge({email:b,phone:nt(w,O)},e.widget.fields.phone),i=n(e.widget.customFields,H.customFields);if(!(r.value&&X.success)||Object.keys(i).length>0){j(r.errors),N(i),F(X.success?void 0:X.message),q.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{pt({customFieldErrors:i,emailRef:te,form:e,parsedTipSuccess:X.success,phoneRef:K,validationErrors:r.errors})});return}j({}),N({}),await q.commands.submit({addresses:G.current,phone:nt(w,O)})}return ue?U(`p`,{className:`lockerverse-payment__payment-status`,ref:ne,role:`status`,tabIndex:-1,children:ue}):ie?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):W(`form`,{"aria-busy":Y,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:xe,children:[U(`div`,{"data-lockerverse-input-region":``,inert:Y?!0:void 0,children:W(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:Y,children:[U(ut,{displayedBaseCents:ve,displayedTipCents:_e,displayedTotalCents:J,quote:f}),U(oe,{enabled:e.widget.fields.tipping,error:P,errorId:he,onChange:Q,values:H}),U(mt,{email:b,emailDiscountPercentOff:f.appliedDiscount?.source===`email_list`?f.appliedDiscount.percentageOff:void 0,emailErrorId:fe,emailId:de,emailRef:te,errors:A,onEmailBlur:()=>q.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{C(e),be(`email`)},onPhoneChange:e=>{T(e),be(`phone`)},onPhoneCountryChange:e=>{k(e),q.commands.fieldChanged(!1,!0)},phone:w,phoneCountry:O,phoneEnabled:e.widget.fields.phone,phoneErrorId:me,phoneId:pe,phoneRef:K}),U(lt,{catalog:e,displayedTotalCents:J,fieldValues:H,isBillingAddressReady:R,isPaymentReady:I,isShippingAddressReady:B,onAddressChange:(e,t)=>{G.current[e]=t},onFieldValuesChange:Q,onStripeLoadError:q.commands.reportStripeLoadError,setIsBillingAddressReady:z,setIsPaymentReady:L,setIsShippingAddressReady:V}),U(ce,{customFields:e.widget.customFields,errors:M,fields:e.widget.fields,idPrefix:Z,isPromoApplying:ae,onApplyPromo:q.commands.applyPromo,onChange:Q,promoError:le,values:H}),U(dt,{catalog:e,displayedTotalCents:J,fieldValues:H,isBillingAddressReady:R,isPaymentReady:I,isRequiredShippingReady:ye,isSubmitting:Y,onFieldValuesChange:Q,quote:f})]})}),Y?U(`p`,{className:`lockerverse-payment__sr-only`,ref:ne,role:`status`,tabIndex:-1,children:J===0?`Completing order…`:`Processing payment…`}):null,U(ct,{message:se})]})}function gt(){return U(c,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function _t(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return bt(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function $(e,t){return e===t}function vt({checkout:e}){return{displayedQuote:e,type:`ready`}}function yt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function bt(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function xt(e,t){let n=e.widget.fields.serviceFee;return f(e,{includeServiceFee:n,selection:t})}function St(e,t){try{return bt(xt(e,t),1)}catch(e){return{failure:yt(e),phase:`error`,revision:0}}}function Ct({catalog:e,client:t,paymentState:n,selection:r}){let i=Oe(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=y(()=>i.success?i.value:[],[i.success,a]),[s,c]=b(_t,void 0,()=>i.success?St(e,o):{phase:`loading`,revision:0}),l=x(void 0),u=x(0),d=x(s.phase===`ready`?a:void 0),f=x(s.phase===`error`?a:void 0);g(()=>{if(!i.success||n===`submitting`||n===`success`||n===`unresolved`||$(f.current,a)||$(l.current,a))return;let r=!0;l.current=a;let s=d.current===a;s||c({type:`loading`});function p(e){r&&c(e)}function m(){r&&(l.current=void 0,f.current=a)}let h;function g(e){if(!r||(l.current=void 0,f.current=a,s&&h!==void 0&&u.current!==h))return;let t=yt(e);c(s?{failure:t,type:`quote-error`}:{failure:t,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!s){let t=xt(e,o);s=!0,d.current=a,p(vt({checkout:t}))}m();let r=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});u.current===h&&p({checkout:r,type:`checkout`})}catch(e){g(e)}}return _(),()=>{r=!1,$(l.current,a)&&(l.current=void 0)}},[e,t,i.success,n,a,o]);let p=n===`submitting`||n===`success`||n===`unresolved`,m=$(d.current,a)||$(f.current,a)||$(l.current,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}function wt({catalog:e,client:t,...n}){let{branding:i,className:a,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,style:p,stripeLoader:h=Qe,theme:_=`dark`,...y}=n,[b,C]=S(d),w=x(null),[T,E]=S(),[D,O]=S(`idle`),k=x(void 0),{selectionError:A,session:j,updateCheckout:M}=Ct({catalog:e,client:t,paymentState:D,selection:f}),N=j.phase===`ready`?j.revision:void 0,P=m(e=>{N!==void 0&&(k.current=N),O(e)},[N]),F=m(e=>l?.(e),[l]),I=m(()=>{C(void 0)},[]);g(()=>{j.phase===`loading`&&E(void 0)},[j.phase]),v(()=>{j.phase===`ready`&&k.current!==j.revision&&O(e=>e===`success`||e===`unresolved`?e:`idle`)},[j.phase,j.revision]);let L=[`lockerverse-payment`,a].filter(Boolean).join(` `),R=i??e.community,z=s(p?.[`--lockerverse-accent`]??R?.accentColor??`#38d77a`),B=r(z),V={...p};return(p?.[`--lockerverse-accent`]!==void 0||R?.accentColor)&&(V[`--lockerverse-accent`]=z),B&&p?.[`--lockerverse-accent-contrast`]===void 0&&(V[`--lockerverse-accent-contrast`]=B),A?U(`section`,{...y,className:L,"data-lockerverse-theme":_,role:`alert`,style:V,children:A}):j.phase===`error`?U(`section`,{...y,className:L,"data-lockerverse-theme":_,style:V,children:U(`p`,{role:`alert`,children:j.failure})}):j.phase===`ready`?W(`section`,{...y,"aria-label":`Payment`,className:L,"data-lockerverse-theme":_,"data-payment-state":D,ref:w,style:V,children:[W(`header`,{children:[e.widget.showCommunityBranding&&R?W(`div`,{className:`lockerverse-payment__branding`,children:[R.imageUrl?U(`img`,{alt:R.name,height:`48`,src:R.imageUrl,width:`48`}):null,U(`strong`,{children:R.name})]}):null,U(`h1`,{children:e.widget.title??e.widget.name}),e.widget.description?U(`p`,{children:e.widget.description}):null]}),T?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:T}):null,j.quoteFailure?W(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[U(`span`,{children:j.quoteFailure}),U(`span`,{children:` The final total will be checked when you submit.`})]}):null,U(re,{container:w,children:U(it,{accentColor:z,catalog:e,checkoutItems:j.checkoutItems,client:t,fontFamily:p?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:F,onPaymentUncertain:u,onQuoteChange:(e,t)=>{E(t),M(e)},onResumePaymentFailed:I,onStateChange:P,quote:j.displayedQuote,resumePayment:b,stripeLoader:h,theme:_,visualStyle:V},j.revision)})]}):U(`section`,{...y,"aria-busy":`true`,"aria-label":`Payment`,className:L,"data-lockerverse-theme":_,style:V,children:U(gt,{})})}function Tt({children:e,loading:t=!1,viewProps:n}){let{branding:i,className:a,metadata:o,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,stripeLoader:p,style:m,theme:h=`dark`,...g}=n,_=s(m?.[`--lockerverse-accent`]??i?.accentColor??`#38d77a`),v=r(_),y={...m};return(m?.[`--lockerverse-accent`]!==void 0||i?.accentColor)&&(y[`--lockerverse-accent`]=_),v&&m?.[`--lockerverse-accent-contrast`]===void 0&&(y[`--lockerverse-accent-contrast`]=v),U(`section`,{...g,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,a].filter(Boolean).join(` `),"data-lockerverse-theme":h,style:y,children:e})}function Et({widget:e,...t}){return e.error?W(Tt,{viewProps:t,children:[U(`p`,{role:`alert`,children:e.error.message}),U(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading||!e.catalog?U(Tt,{loading:!0,viewProps:t,children:U(gt,{})}):U(wt,{catalog:e.catalog,client:e.client,...t})}export{$e as n,Et as t};
1
+ import{a as e,c as t,d as n,f as r,g as i,h as a,i as o,l as s,m as c,n as l,p as u,r as d,t as f,u as p}from"./host-callback.js";import{LockerverseSdkError as m,estimateLockerverseCheckout as h}from"@lockerverse/sdk/checkout";import{createContext as g,useCallback as _,useContext as v,useEffect as y,useId as b,useLayoutEffect as x,useMemo as S,useReducer as C,useRef as w,useState as T}from"react";import{AddressElement as E,Elements as D,PaymentElement as O,useElements as k,useStripe as A}from"@stripe/react-stripe-js";import{loadStripe as j}from"@stripe/stripe-js/pure/index.js";import{array as M,minLength as N,minValue as P,nonEmpty as F,number as I,object as L,pipe as R,regex as ee,safeInteger as te,safeParse as z,strictObject as B,string as V,trim as ne,union as re}from"valibot";import{Fragment as H,jsx as U,jsxs as W}from"react/jsx-runtime";import{Select as G}from"@base-ui/react/select";const ie=new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`});function K(e){return ie.format(e/100)}const q=g(void 0);function J({children:e,container:t}){return U(q.Provider,{value:t,children:e})}function ae(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m4 6 4 4 4-4`})})}function oe(){return U(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:U(`path`,{d:`m3 8 3 3 7-7`})})}function Y({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=v(q),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return U(`div`,{className:d,children:W(G.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[W(G.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[U(G.Value,{}),U(G.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:U(ae,{})})]}),U(G.Portal,{container:u,children:U(G.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:U(G.Popup,{className:`lockerverse-payment__select-popup`,children:U(G.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>W(G.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[U(G.ItemText,{children:e.label}),U(G.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:U(oe,{})})]},e.value))})})})})]})})}const X=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],se=[`15`,`12`,`10`,`5`],Z=[...se,`custom`];function ce({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=Z.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%Z.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+Z.length)%Z.length;break;case`Home`:r=0;break;case`End`:r=Z.length-1;break;default:return}e.preventDefault();let i=Z[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return W(`div`,{className:`lockerverse-payment__tip-box`,children:[U(`p`,{children:`Add a tip to support the Lockerverse platform`}),W(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[se.map(e=>W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),W(`span`,{children:[e,`%`]})]},e)),W(`label`,{className:`lockerverse-payment__tip-choice`,children:[U(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),U(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?W(`label`,{children:[U(`span`,{children:`Custom tip`}),W(`span`,{className:`lockerverse-payment__money-input`,children:[U(`span`,{"aria-hidden":`true`,children:`$`}),U(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?U(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):U(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function le({checked:e,children:t,name:n,onChange:r}){return W(`label`,{className:`lockerverse-payment__check-row`,children:[U(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),U(`span`,{children:t})]})}function ue({customFields:e,errors:t,fields:r,idPrefix:i,isPromoApplying:a,onChange:o,onApplyPromo:s,promoError:c,values:l}){let u=e=>o({...l,...e});return W(`div`,{className:`lockerverse-payment__additional-fields`,children:[r.memberId?W(`label`,{children:[U(`span`,{children:`Member ID`}),U(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,r.merchSize?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${i}-merch-size-label`,children:`Size`}),U(Y,{ariaLabelledBy:`${i}-merch-size-label`,name:`merchSize`,onValueChange:e=>{let t=X.find(t=>t===e);t&&u({merchSize:t})},options:X.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,r.promoCode?W(`div`,{className:`lockerverse-payment__field`,children:[U(`span`,{id:`${i}-promo-code-label`,children:`Promo code`}),W(`div`,{className:`lockerverse-payment__promo-control`,children:[U(`input`,{"aria-describedby":c?`${i}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${i}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),U(`button`,{disabled:!l.promoCode.trim()||a,onClick:s,type:`button`,children:a?`Applying…`:`Apply`})]}),c?U(`p`,{className:`lockerverse-payment__field-message`,id:`${i}-promo-code-error`,role:`alert`,children:c}):null]}):null,U(n,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:i,onChange:e=>u({customFields:e}),values:l.customFields})]})}function de({amountCents:e,enabled:t,onChange:n,values:r}){return t?W(le,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,K(e),` to help cover processing fees`]}):null}function fe(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function Q(e,t,n){return t.includes(e.status)?{...e,...n}:e}function pe(e,t){if(e.status===`sold_out`||e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return Q(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`editing`});case`validation_failed`:return Q(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return Q(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return Q(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return Q(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return Q(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`submission_validation_failed`:return Q(e,[`submitting`],{error:void 0,status:`invalid`});case`quote_changed`:return Q(e,[`submitting`],{status:`editing`});case`retryable_failure`:return Q(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return Q(e,[`recovering`],{error:t.error,status:`editing`});case`sold_out`:return{error:void 0,message:void 0,status:`sold_out`};case`succeeded`:return Q(e,[`recovering`,`submitting`],{message:t.message,status:`succeeded`});case`unresolved`:return Q(e,[`recovering`,`submitting`],{message:t.message,status:`unresolved`});default:return e}}function me(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function he(e){return e.status===`sold_out`?`sold_out`:e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:me(e)?`error`:`idle`}function ge(e){return e.status===`submitting`}function _e(t){return e(t)}function ve(e,n){let r=n?{...e,phone:_e(e.phone)}:e,i=L(n?{email:t,phone:s}:{email:t}),a=z(i,r);if(a.success)return{errors:{},value:a.output};let o={};for(let e of a.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!o[t]&&(o[t]=e.message)}return{errors:o,value:null}}const ye=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],be=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function xe(e,t,n,r){return(n===t.totalCents?be:ye).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function Se(e){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function Ce(e,t,n){if(t.checkoutStatus!==`action_required`)return Se(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return Se(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function we(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof m&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return Ce(e,r,n)}async function Te(e,t,n){try{return Ce(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const Ee=R(V(),ne(),F()),De=R(I(),te(),P(1)),Oe=R(M(re([B({amountCents:De,productSlug:Ee}),B({productSlug:Ee,quantity:De}),B({productSlug:Ee})])),N(1)),ke=R(V(),ne(),ee(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function Ae(e){let t=z(ke,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function je(e){let t=z(Oe,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}const Me=`This promo code is invalid or cannot be applied.`;function Ne(e,t){return t.tipPercent===`custom`?t.customTip.trim()?Ae(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Pe(e,t,n,r){let i={};return n&&(i.email=n),e.widget.fields.serviceFee&&(i.includeServiceFee=t.includeServiceFee),e.widget.fields.promoCode&&t.promoCode.trim()&&(i.promoCode=t.promoCode.trim()),e.widget.fields.tipping&&(i.tipCents=r),i}function Fe(e,t,n){let r=e.widget.fields.tipping?Ne(n.subtotalCents,t):{cents:0,success:!0};if(!r.success)return{parsedTip:r,totalCents:null};let i=e.widget.fields.serviceFee&&t.includeServiceFee?n.serviceFeeCents||Math.round(n.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4):0;return{parsedTip:r,totalCents:n.totalCents-n.serviceFeeCents-n.tipCents+i+r.cents}}function Ie(e,t){return{displayedTotalCents:e.totalCents,promoError:t&&e.appliedDiscount?.source!==`promo_code`?Me:void 0}}function Le(e,t){let n;return t||(n=e instanceof Error?e.message:`The order total could not be updated.`),{paymentError:n,promoError:t?Me:void 0}}function Re(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function ze(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Re(r.shipping,`Shipping`)}function Be({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){let a={payment_method_data:{billing_details:t.widget.fields.phone?{address:e.address,email:n,name:e.name,phone:r}:{address:e.address,email:n,name:e.name}}};return i?{...a,shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:a}function Ve({catalog:e,confirmationToken:t,email:n,fieldValues:i,metadata:a,phone:o,shippingAddress:s}){let c={customFieldAnswers:r(e.widget.customFields,i.customFields),email:n};if(t&&(c.confirmationToken=t),a&&(c.metadata=a),e.widget.fields.memberId&&i.memberId.trim()&&(c.memberId=i.memberId.trim()),e.widget.fields.merchSize&&(c.merchSize=i.merchSize),e.widget.fields.phone&&(c.phone=o),s){let e={city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,postal_code:s.address.postal_code??``,state:s.address.state??``};s.address.line2&&(e.line2=s.address.line2),c.shipping={address:e,name:s.name}}return c}function He(e){if(!e())throw Error(`Payment component is no longer active.`)}function Ue(e,t){f(e,t)}function We(e,t,n,r){return e.kind===`failed`?{kind:`payment_failed`,message:r}:e.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:e.paymentReference,reason:e.reason}:{email:n,kind:`payment`,payment:e.payment,quote:t}}async function Ge({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=_e(d),_=Ne(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=await r.calculateTotal({...Pe(t,o,h,_.cents),catalog:t,items:n});if(He(s),v.totalCents>0&&xe(f,v,c,m))return{kind:`quote_changed`,quote:v};let y,b;if(v.totalCents===0)t.widget.fields.shipping&&(y=ze(t,o,Re(e.billing,`Billing`),e));else{if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),He(s);let n=await i.submit();if(He(s),n.error)throw Error(n.error.message);let r=Re(e.billing,`Billing`);y=ze(t,o,r,e);let a=await p.createConfirmationToken({elements:i,params:Be({billingAddress:r,catalog:t,email:h,phone:g,shippingAddress:y})});if(He(s),a.error)throw Error(a.error.message);b=a.confirmationToken.id}Ue(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let x=await we(r,{checkout:v,submission:Ve({catalog:t,confirmationToken:b,email:h,fieldValues:o,metadata:l,phone:g,shippingAddress:y})},p);return He(s),We(x,v,h,v.totalCents===0?`Order could not be completed. Review the details and try again.`:`Payment was declined. Check your payment details and try again.`)}function Ke(e,t){f(e,t)}function qe(e,t){f(e,t)}function Je(e,t){return{...e,...t}}function Ye(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!t&&!n}function Xe(e){return e instanceof m&&e.serverCode===`PAYMENT_WIDGET_SALES_LIMIT_REACHED`}function Ze({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateState:i,validatePromo:a}){let o=Ie(e,a);i({type:`quote_refresh_succeeded`}),n(o.displayedTotalCents),t(e),a&&r(o.promoError)}function Qe({error:e,setPromoError:t,updateState:n,validatePromo:r}){let i=Le(e,r);r&&t(i.promoError),n(i.paymentError===void 0?{type:`quote_refresh_failed`}:{error:i.paymentError,type:`quote_refresh_failed`})}function $e({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:r,result:i,setDisplayedTotalCents:a,dispatchState:o}){if(i.kind===`quote_changed`){let e=`The total changed to ${K(i.quote.totalCents)}. Review it and pay again.`;r(i.quote,e),a(i.quote.totalCents),o({type:`quote_changed`});return}if(i.kind===`payment_failed`){Ke(t,null),o({error:i.message,type:`retryable_failure`});return}if(i.kind===`payment_unresolved`){o({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),qe(n,{paymentReference:i.paymentReference,reason:i.reason});return}r(i.quote),Ke(t,null),o({message:i.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),f(e,Je(i.payment,{email:i.email,lineItems:i.quote.lineItems}))}function et(e){let{catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:s,metadata:c,onPaymentComplete:l,onResumePaymentFailed:u,onPaymentRecoveryChange:d,onPaymentUncertain:p,onQuoteChange:h,onStateChange:g,quote:v,resumePayment:b,stripe:x,stripeConnectedAccountId:S,stripeLoadFailed:C,paymentState:E,updateState:D}=e,[O,k]=T(v.totalCents),[A,j]=T(),M=w(!1),N=w(0),P=w(0),F=_(e=>D(e,!0),[D]),I=_(()=>{let e=P.current+1;return P.current=e,()=>P.current===e},[]);y(()=>()=>{P.current+=1,N.current+=1},[]);let{parsedTip:L,totalCents:R}=Fe(t,s,v);y(()=>{R!==null&&(k(R),R>0&&i?.update({amount:R}))},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,i,s.includeServiceFee,R,v.serviceFeeCents,v.tipCents,v.totalCents,v.subtotalCents]),y(()=>{if(!b||M.current||E.status!==`recovering`)return;M.current=!0;let e=I();return g(he(E)),Te(r,b.paymentReference,x).then(t=>{if(e()&&!Ye(t,x,C)){if(t.kind===`failed`){Ke(d,null),u(),F({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){F({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),qe(p,{paymentReference:t.paymentReference,reason:t.reason});return}Ke(d,null),F({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`}),f(l,Je(t.payment,{email:null,lineItems:null}))}}),()=>{e()&&(P.current+=1),M.current=!1}},[r,l,u,d,p,g,b,x,C,I,F,E]);let ee=_((e=!1,t=!1)=>{t||(N.current+=1),e&&j(void 0),D({type:`field_changed`})},[D]);async function te(e=!1,i=!1){let o=ve({email:a.trim().toLowerCase(),phone:``},!1);if(!(L.success&&(o.value||e)))return;N.current+=1;let c=N.current;D({type:`quote_refresh_started`});try{let e=await r.calculateTotal({...Pe(t,s,o.value?.email??``,L.cents),catalog:t,items:n});if(c!==N.current)return;Ze({nextQuote:e,onQuoteChange:h,setDisplayedTotalCents:k,setPromoError:j,updateState:D,validatePromo:i})}catch(e){if(c!==N.current)return;if(Xe(e)){D({type:`sold_out`});return}Qe({error:e,setPromoError:j,updateState:D,validatePromo:i})}}async function z(){j(void 0),await te(!0,!0)}async function B({addresses:e,phone:u}){F({type:`submission_started`});let f=I();try{let o=await Ge({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:s,isAttemptActive:f,locallyPreviewedTotalCents:O,metadata:c,onPaymentRecoveryChange:d,phone:u,quote:v,stripe:x,stripeConnectedAccountId:S});if(!f())return;$e({dispatchState:F,onPaymentComplete:l,onPaymentRecoveryChange:d,onPaymentUncertain:p,onQuoteChange:h,result:o,setDisplayedTotalCents:k})}catch(e){if(!f())return;if(Ke(d,null),Xe(e)){F({type:`sold_out`});return}let t=e instanceof m?o(e.serverCode):void 0;if(t)return F({type:`submission_validation_failed`}),{phoneError:t};F({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let V=E.status===`succeeded`||E.status===`unresolved`?E.message:void 0;return{commands:{applyPromo:z,fieldChanged:ee,refreshAuthoritativeTotal:te,reportStripeLoadError:e=>F({error:e,type:`retryable_failure`}),reportValidationFailure:()=>F({type:`validation_failed`}),submit:B},state:{displayedTotalCents:O,isRecovering:E.status===`recovering`,isRefreshingQuote:E.status===`refreshing_quote`,isSubmitting:ge(E),parsedTip:L,paymentError:me(E),promoError:A,terminalMessage:V}}}const tt=new Map,nt=(e,t)=>{let n=t?.stripeAccount??null,r=tt.get(e);r||(r=new Map,tt.set(e,r));let i=r.get(n);if(i)return i;let a=j(e,t).catch(()=>(r?.get(n)===a&&(r.delete(n),r.size===0&&tt.delete(e)),null));return r.set(n,a),a};function rt(e){let{connectedAccountId:t,publishableKey:n}=e.payment;return nt(n,t?{stripeAccount:t}:void 0)}function it(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}function at(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function ot({accentColor:e,catalog:t,checkoutItems:n,client:r,fontFamily:i,metadata:a,onPaymentComplete:o,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,quote:d,resumePayment:f,onStateChange:p,stripeLoader:m,theme:h,visualStyle:g}){let[v,b]=T(()=>fe(!!f)),x=w(v);x.current=v;let C=_((e,t=!1)=>{let n=pe(x.current,e);n!==x.current&&(x.current=n,b(n),t&&p(he(n)))},[p]),E=at(t,d,f),O=w({connectedAccountId:E,paymentOption:d.paymentOption});v.status!==`submitting`&&v.status!==`recovering`&&(O.current={connectedAccountId:E,paymentOption:d.paymentOption});let{connectedAccountId:k,paymentOption:A}=O.current,j=S(()=>m(t.payment.publishableKey,k?{stripeAccount:k}:void 0).catch(()=>null),[t.payment.publishableKey,k,m]),[M,N]=T(!1);return y(()=>{let e=!0;return N(!1),j.then(t=>{e&&t===null&&N(!0)}),()=>{e=!1}},[j]),U(D,{options:{amount:Math.max(d.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:h===`light`?`stripe`:`night`,variables:{borderRadius:g?.[`--lockerverse-radius`]??`10px`,colorBackground:g?.[`--lockerverse-control`]??(h===`light`?`#f5f6f7`:`#121212`),colorDanger:g?.[`--lockerverse-danger`]??(h===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:g?.[`--lockerverse-text`]??(h===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:g?.[`--lockerverse-placeholder`]??(h===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:g?.[`--lockerverse-muted`]??(h===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:t.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:A===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:j,children:U(_t,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:s,onStateChange:p,paymentState:v,quote:d,resumePayment:f,stripeConnectedAccountId:k,stripeLoadFailed:M,updateState:C})},`${t.payment.publishableKey}:${k??`platform`}:${A}`)}function st({label:e}){return W(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[U(`p`,{children:e}),W(`div`,{"aria-hidden":`true`,children:[U(`span`,{}),U(`span`,{}),U(`span`,{})]})]})}function ct({onError:e,onReady:t,ready:n}){return W(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:U(st,{label:`Loading payment form...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(O,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function lt({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return W(`div`,{className:`lockerverse-payment__address`,children:[U(`h2`,{children:e}),W(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:U(st,{label:`Loading ${e.toLowerCase()}...`}),U(`div`,{className:`lockerverse-payment__stripe-mount`,children:U(E,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function ut({message:e}){return e?U(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function dt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return W(H,{children:[f?U(ct,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?U(lt,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?W(`div`,{className:`lockerverse-payment__shipping`,children:[U(le,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:U(lt,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function ft({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let i=it(r.paymentOption),a=Math.max(0,e-r.subtotalCents+r.discountCents);return W(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[U(`h2`,{children:`Order summary`}),U(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>W(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[W(`span`,{children:[e.productName,e.quantity>1?W(H,{children:[` `,W(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?U(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?U(`small`,{children:` · Annual`}):null]}),U(`strong`,{children:K(e.subtotalCents)})]},e.listingId))}),W(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[a>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[U(`span`,{children:`Service fee`}),U(`strong`,{children:K(a)})]}):null,r.discountCents>0&&r.appliedDiscount?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[W(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),W(`strong`,{children:[`-`,K(r.discountCents)]})]}):null,t>0?W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[U(`span`,{children:`Tip`}),U(`strong`,{children:K(t)})]}):null,W(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[U(`span`,{children:i?`${i.label} total`:`Total`}),U(`strong`,{children:K(n)})]})]})]})}function pt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isRequiredShippingReady:a,isSubmitting:o,onFieldValuesChange:s,quote:c}){let l=t===0,u=l?!e.widget.fields.shipping||r&&a:i&&r&&a,d=it(c.paymentOption),f=l?`Complete order`:`Pay ${K(t)}`;!l&&d&&(f=`Subscribe for ${K(t)}/${d.interval}`),o&&(f=l?`Completing…`:`Processing…`);let p=`Process payment for ${K(t)} total`;return l?p=`Complete order`:d&&(p=`Start ${d.label.toLowerCase()} subscription for ${K(t)}`),W(`div`,{className:`lockerverse-payment__actions`,children:[U(de,{amountCents:c.serviceFeeCents||Math.round(c.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:s,values:n}),U(`button`,{"aria-busy":o,"aria-label":p,disabled:o||!u,type:`submit`,children:f})]})}function mt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function ht({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&mt(n,`custom:${o}`)}function gt({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:u,phone:d,phoneCountry:f,phoneEnabled:p,phoneErrorId:m,phoneId:h,phoneRef:g}){return W(`div`,{className:`lockerverse-payment__contact`,children:[U(`label`,{htmlFor:r,children:`Email`}),U(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?U(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:W(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),p?W(H,{children:[U(`label`,{htmlFor:h,children:`Phone`}),W(`div`,{className:`lockerverse-payment__phone-control`,children:[U(Y,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:u,options:l,value:f}),U(`input`,{"aria-describedby":a.phone?m:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:h,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:g,type:`tel`,value:d})]}),a.phone?U(`p`,{className:`lockerverse-payment__field-message`,id:m,children:a.phone}):null]}):null]})}function _t({catalog:e,checkoutItems:t,client:n,metadata:r,onPaymentComplete:i,onResumePaymentFailed:a,onPaymentRecoveryChange:o,onPaymentUncertain:s,onQuoteChange:l,onStateChange:f,quote:p,resumePayment:m,stripeConnectedAccountId:h,stripeLoadFailed:g,paymentState:_,updateState:v}){let[x,S]=T(``),[C,E]=T(``),[D,O]=T(`US`),[j,M]=T({}),[N,P]=T({}),[F,I]=T(),[L,R]=T(!1),[ee,te]=T(!1),[z,B]=T(!1),[V,ne]=T({customFields:u(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),re=w({billing:null,shipping:null}),H=w(null),G=w(null),ie=w(null),K=w(p.totalCents>0),q=et({catalog:e,checkoutItems:t,client:n,elements:k(),email:x,fieldValues:V,metadata:r,onPaymentComplete:i,onPaymentRecoveryChange:o,onPaymentUncertain:s,onQuoteChange:l,onResumePaymentFailed:a,onStateChange:f,paymentState:_,quote:p,resumePayment:m,stripe:A(),stripeConnectedAccountId:h,stripeLoadFailed:g,updateState:v}),{displayedTotalCents:J,isRecovering:ae,isRefreshingQuote:oe,isSubmitting:Y,parsedTip:X,paymentError:se,promoError:Z,terminalMessage:le}=q.state,de=`lockerverse-${b()}`,fe=`${de}-email`,Q=`${fe}-error`,pe=`${de}-phone`,me=`${pe}-error`,he=`${de}-tip-error`,ge=(X.success?X.cents:null)??0,_e=J-ge,ye=!e.widget.fields.shipping||V.shippingMatchesBilling||z;y(()=>{Y&&ie.current?.focus({preventScroll:!0})},[Y]),y(()=>{Y||j.email||!j.phone||G.current?.focus()},[j.email,j.phone,Y]),y(()=>{let e=J>0;e&&!K.current&&(R(!1),te(!1)),K.current=e},[J]);function be(e){q.commands.fieldChanged(!1,e!==`email`),M(t=>{let n={...t};return delete n[e],n})}function xe(e){let t=e.promoCode!==V.promoCode,n=e.includeServiceFee!==V.includeServiceFee;q.commands.fieldChanged(t,!(t||n)),ne(e),P({}),I(void 0)}async function Se(t){t.preventDefault();let n=d(C,D),r=ve({email:x,phone:n},e.widget.fields.phone),i=c(e.widget.customFields,V.customFields);if(!(r.value&&X.success)||Object.keys(i).length>0){M(r.errors),P(i),I(X.success?void 0:X.message),q.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{ht({customFieldErrors:i,emailRef:H,form:e,parsedTipSuccess:X.success,phoneRef:G,validationErrors:r.errors})});return}M({}),P({});let a=await q.commands.submit({addresses:re.current,phone:n});a?.phoneError&&M({phone:a.phoneError})}return le?U(`p`,{className:`lockerverse-payment__payment-status`,ref:ie,role:`status`,tabIndex:-1,children:le}):ae?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):W(`form`,{"aria-busy":Y,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Se,children:[U(`div`,{"data-lockerverse-input-region":``,inert:Y?!0:void 0,children:W(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:Y,children:[U(ft,{displayedBaseCents:_e,displayedTipCents:ge,displayedTotalCents:J,quote:p}),U(ce,{enabled:e.widget.fields.tipping,error:F,errorId:he,onChange:xe,values:V}),U(gt,{email:x,emailDiscountPercentOff:p.appliedDiscount?.source===`email_list`?p.appliedDiscount.percentageOff:void 0,emailErrorId:Q,emailId:fe,emailRef:H,errors:j,onEmailBlur:()=>q.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{S(e),be(`email`)},onPhoneChange:e=>{E(e),be(`phone`)},onPhoneCountryChange:e=>{O(e),q.commands.fieldChanged(!1,!0)},phone:C,phoneCountry:D,phoneEnabled:e.widget.fields.phone,phoneErrorId:me,phoneId:pe,phoneRef:G}),U(dt,{catalog:e,displayedTotalCents:J,fieldValues:V,isBillingAddressReady:ee,isPaymentReady:L,isShippingAddressReady:z,onAddressChange:(e,t)=>{re.current[e]=t},onFieldValuesChange:xe,onStripeLoadError:q.commands.reportStripeLoadError,setIsBillingAddressReady:te,setIsPaymentReady:R,setIsShippingAddressReady:B}),U(ue,{customFields:e.widget.customFields,errors:N,fields:e.widget.fields,idPrefix:de,isPromoApplying:oe,onApplyPromo:q.commands.applyPromo,onChange:xe,promoError:Z,values:V}),U(pt,{catalog:e,displayedTotalCents:J,fieldValues:V,isBillingAddressReady:ee,isPaymentReady:L,isRequiredShippingReady:ye,isSubmitting:Y,onFieldValuesChange:xe,quote:p})]})}),Y?U(`p`,{className:`lockerverse-payment__sr-only`,ref:ie,role:`status`,tabIndex:-1,children:J===0?`Completing order…`:`Processing payment…`}):null,U(ut,{message:se})]})}function vt(){return U(p,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function yt(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return St(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function $(e,t){return e===t}function bt({checkout:e}){return{displayedQuote:e,type:`ready`}}function xt(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function St(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function Ct(e,t){let n=e.widget.fields.serviceFee;return h(e,{includeServiceFee:n,selection:t})}function wt(e,t){try{return St(Ct(e,t),1)}catch(e){return{failure:xt(e),phase:`error`,revision:0}}}function Tt({catalog:e,client:t,paymentState:n,selection:r}){let i=je(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=S(()=>i.success?i.value:[],[i.success,a]),[s,c]=C(yt,void 0,()=>i.success?wt(e,o):{phase:`loading`,revision:0}),l=w(void 0),u=w(0),d=w(s.phase===`ready`?a:void 0),f=w(s.phase===`error`?a:void 0);y(()=>{if(!i.success||n===`submitting`||n===`success`||n===`unresolved`||$(f.current,a)||$(l.current,a))return;let r=!0;l.current=a;let s=d.current===a;s||c({type:`loading`});function p(e){r&&c(e)}function m(){r&&(l.current=void 0,f.current=a)}let h;function g(e){if(!r||(l.current=void 0,f.current=a,s&&h!==void 0&&u.current!==h))return;let t=xt(e);if(t===`This option is sold out.`){c({failure:t,type:`error`});return}c(s?{failure:t,type:`quote-error`}:{failure:t,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!s){let t=Ct(e,o);s=!0,d.current=a,p(bt({checkout:t}))}m();let r=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});u.current===h&&p({checkout:r,type:`checkout`})}catch(e){g(e)}}return _(),()=>{r=!1,$(l.current,a)&&(l.current=void 0)}},[e,t,i.success,n,a,o]);let p=n===`submitting`||n===`success`||n===`unresolved`,m=$(d.current,a)||$(f.current,a)||$(l.current,a),h=p||m?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:h,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}function Et(e,t){let n=i(e?.[`--lockerverse-accent`]??t?.accentColor??`#38d77a`),r=a(n),o={...e};return(e?.[`--lockerverse-accent`]!==void 0||t?.accentColor)&&(o[`--lockerverse-accent`]=n),r&&e?.[`--lockerverse-accent-contrast`]===void 0&&(o[`--lockerverse-accent-contrast`]=r),{accent:n,rootStyle:o}}function Dt({catalog:e,client:t,...n}){let{branding:r,className:i,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,resumePayment:l,selection:u,style:d,stripeLoader:f=nt,theme:p=`dark`,...m}=n,[h,g]=T(l),v=w(null),[b,S]=T(),[C,E]=T(`idle`),D=w(void 0),{selectionError:O,session:k,updateCheckout:A}=Tt({catalog:e,client:t,paymentState:C,selection:u}),j=k.phase===`ready`?k.revision:void 0,M=_(e=>{j!==void 0&&(D.current=j),E(e)},[j]),N=_(e=>s?.(e),[s]),P=_(()=>{g(void 0)},[]);y(()=>{k.phase===`loading`&&S(void 0)},[k.phase]),x(()=>{k.phase===`ready`&&D.current!==k.revision&&E(e=>e===`success`||e===`unresolved`?e:`idle`)},[k.phase,k.revision]);let F=[`lockerverse-payment`,i].filter(Boolean).join(` `),I=r??e.community,{accent:L,rootStyle:R}=Et(d,I);return O?U(`section`,{...m,className:F,"data-lockerverse-theme":p,role:`alert`,style:R,children:O}):k.phase===`error`&&k.failure===`This option is sold out.`||C===`sold_out`?W(`section`,{...m,className:F,"data-lockerverse-theme":p,role:`alert`,style:R,children:[U(`h1`,{children:`Sold out`}),U(`p`,{children:`This option is sold out.`})]}):k.phase===`error`?U(`section`,{...m,className:F,"data-lockerverse-theme":p,style:R,children:U(`p`,{role:`alert`,children:k.failure})}):k.phase===`ready`?W(`section`,{...m,"aria-label":`Payment`,className:F,"data-lockerverse-theme":p,"data-payment-state":C,ref:v,style:R,children:[W(`header`,{children:[e.widget.showCommunityBranding&&I?W(`div`,{className:`lockerverse-payment__branding`,children:[I.imageUrl?U(`img`,{alt:I.name,height:`48`,src:I.imageUrl,width:`48`}):null,U(`strong`,{children:I.name})]}):null,U(`h1`,{children:e.widget.title??e.widget.name}),e.widget.description?U(`p`,{children:e.widget.description}):null]}),b?U(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:b}):null,k.quoteFailure?W(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[U(`span`,{children:k.quoteFailure}),U(`span`,{children:` The final total will be checked when you submit.`})]}):null,U(J,{container:v,children:U(ot,{accentColor:L,catalog:e,checkoutItems:k.checkoutItems,client:t,fontFamily:d?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:N,onPaymentUncertain:c,onQuoteChange:(e,t)=>{S(t),A(e)},onResumePaymentFailed:P,onStateChange:M,quote:k.displayedQuote,resumePayment:h,stripeLoader:f,theme:p,visualStyle:R},k.revision)})]}):U(`section`,{...m,"aria-busy":`true`,"aria-label":`Payment`,className:F,"data-lockerverse-theme":p,style:R,children:U(vt,{})})}function Ot({children:e,loading:t=!1,viewProps:n}){let{branding:r,className:o,metadata:s,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,stripeLoader:p,style:m,theme:h=`dark`,...g}=n,_=i(m?.[`--lockerverse-accent`]??r?.accentColor??`#38d77a`),v=a(_),y={...m};return(m?.[`--lockerverse-accent`]!==void 0||r?.accentColor)&&(y[`--lockerverse-accent`]=_),v&&m?.[`--lockerverse-accent-contrast`]===void 0&&(y[`--lockerverse-accent-contrast`]=v),U(`section`,{...g,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,o].filter(Boolean).join(` `),"data-lockerverse-theme":h,style:y,children:e})}function kt({widget:e,...t}){return e.error?W(Ot,{viewProps:t,children:[U(`p`,{role:`alert`,children:e.error.message}),U(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading||!e.catalog?U(Ot,{loading:!0,viewProps:t,children:U(vt,{})}):U(Dt,{catalog:e.catalog,client:e.client,...t})}export{rt as n,kt as t};
2
2
  //# sourceMappingURL=lockerverse-payment.js.map