@bizzsv/bizz-payment 1.5.6-dev → 1.5.7-dev
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -4
- package/dist/index.global.js +4 -4
- package/dist/index.js +44 -6
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -20,7 +20,7 @@ Private-Lines: `+f+`\r
|
|
|
20
20
|
`,l+=m;var b=o(`putty-private-key-file-mac-key`,t),x=n.util.createBuffer();a(x,s),a(x,c),a(x,r),x.putInt32(u.length()),x.putBuffer(u),x.putInt32(p.length()),x.putBuffer(p);var S=n.hmac.create();return S.start(`sha1`,b),S.update(x.bytes()),l+=`\r
|
|
21
21
|
Private-MAC: `+S.digest().toHex()+`\r
|
|
22
22
|
`,l},r.publicKeyToOpenSSH=function(e,t){var r=`ssh-rsa`;t||=``;var o=n.util.createBuffer();return a(o,r),i(o,e.e),i(o,e.n),r+` `+n.util.encode64(o.bytes())+` `+t},r.privateKeyToOpenSSH=function(e,t){return t?n.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:`aes128`}):n.pki.privateKeyToPem(e)},r.getPublicKeyFingerprint=function(e,t){t||={};var r=t.md||n.md.md5.create(),o=`ssh-rsa`,s=n.util.createBuffer();a(s,o),i(s,e.e),i(s,e.n),r.start(),r.update(s.getBytes());var c=r.digest();if(t.encoding===`hex`){var l=c.toHex();return t.delimiter?l.match(/.{2}/g).join(t.delimiter):l}else if(t.encoding===`binary`)return c.getBytes();else if(t.encoding)throw Error(`Unknown encoding "`+t.encoding+`".`);return c};function i(e,t){var r=t.toString(16);r[0]>=`8`&&(r=`00`+r);var i=n.util.hexToBytes(r);e.putInt32(i.length),e.putBytes(i)}function a(e,t){e.putInt32(t.length),e.putString(t)}function o(){for(var e=n.md.sha1.create(),t=arguments.length,r=0;r<t;++r)e.update(arguments[r]);return e.digest()}})),te=c(o(((e,t)=>{t.exports=d(),g(),U(),v(),m(),C(),K(),b(),q(),J(),Y(),I(),T(),S(),M(),B(),X(),V(),N(),D(),R(),O(),k(),Z(),H(),p()}))(),1),{entries:ne,setPrototypeOf:re,isFrozen:ie,getPrototypeOf:ae,getOwnPropertyDescriptor:oe}=Object,{freeze:se,seal:ce,create:le}=Object,{apply:ue,construct:de}=typeof Reflect<`u`&&Reflect;se||=function(e){return e},ce||=function(e){return e},ue||=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];return e.apply(t,r)},de||=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return new e(...n)};var fe=Ee(Array.prototype.forEach),pe=Ee(Array.prototype.lastIndexOf),me=Ee(Array.prototype.pop),he=Ee(Array.prototype.push),ge=Ee(Array.prototype.splice),_e=Ee(String.prototype.toLowerCase),ve=Ee(String.prototype.toString),ye=Ee(String.prototype.match),be=Ee(String.prototype.replace),xe=Ee(String.prototype.indexOf),Se=Ee(String.prototype.trim),Ce=Ee(Object.prototype.hasOwnProperty),we=Ee(RegExp.prototype.test),Te=De(TypeError);function Ee(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return ue(e,t,r)}}function De(e){return function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return de(e,n)}}function Q(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:_e;re&&re(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(ie(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Oe(e){for(let t=0;t<e.length;t++)Ce(e,t)||(e[t]=null);return e}function ke(e){let t=le(null);for(let[n,r]of ne(e))Ce(e,n)&&(Array.isArray(r)?t[n]=Oe(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=ke(r):t[n]=r);return t}function Ae(e,t){for(;e!==null;){let n=oe(e,t);if(n){if(n.get)return Ee(n.get);if(typeof n.value==`function`)return Ee(n.value)}e=ae(e)}function n(){return null}return n}var je=se(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Me=se(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),Ne=se([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Pe=se([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Fe=se(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Ie=se([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Le=se([`#text`]),Re=se(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns.slot`.split(`.`)),ze=se(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Be=se(`accent.accentunder.align.bevelled.close.columnsalign.columnlines.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lspace.lquote.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),Ve=se([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),He=ce(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Ue=ce(/<%[\w\W]*|[\w\W]*%>/gm),We=ce(/\$\{[\w\W]*/gm),Ge=ce(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ke=ce(/^aria-[\-\w]+$/),qe=ce(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Je=ce(/^(?:\w+script|data):/i),Ye=ce(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Xe=ce(/^html$/i),Ze=ce(/^[a-z][.\w]*(-[.\w]+)+$/i),Qe=Object.freeze({__proto__:null,ARIA_ATTR:Ke,ATTR_WHITESPACE:Ye,CUSTOM_ELEMENT:Ze,DATA_ATTR:Ge,DOCTYPE_NAME:Xe,ERB_EXPR:Ue,IS_ALLOWED_URI:qe,IS_SCRIPT_OR_DATA:Je,MUSTACHE_EXPR:He,TMPLIT_EXPR:We}),$e={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},et=function(){return typeof window>`u`?null:window},tt=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},nt=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function rt(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:et(),t=e=>rt(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==$e.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,i=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:c,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=e,m=c.prototype,h=Ae(m,`cloneNode`),g=Ae(m,`remove`),_=Ae(m,`nextSibling`),v=Ae(m,`childNodes`),y=Ae(m,`parentNode`);if(typeof o==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let b,x=``,{implementation:S,createNodeIterator:C,createDocumentFragment:w,getElementsByTagName:T}=n,{importNode:E}=r,D=nt();t.isSupported=typeof ne==`function`&&typeof y==`function`&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:O,ERB_EXPR:k,TMPLIT_EXPR:A,DATA_ATTR:j,ARIA_ATTR:M,IS_SCRIPT_OR_DATA:N,ATTR_WHITESPACE:P,CUSTOM_ELEMENT:ee}=Qe,{IS_ALLOWED_URI:F}=Qe,I=null,L=Q({},[...je,...Me,...Ne,...Fe,...Le]),R=null,z=Q({},[...Re,...ze,...Be,...Ve]),B=Object.seal(le(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),V=null,H=null,U=Object.seal(le(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),W=!0,G=!0,K=!1,q=!0,J=!1,Y=!0,X=!1,Z=!1,te=!1,re=!1,ie=!1,ae=!1,oe=!0,ce=!1,ue=!0,de=!1,Ee={},De=null,Oe=Q({},[`annotation-xml`,`audio`,`colgroup`,`desc`,`foreignobject`,`head`,`iframe`,`math`,`mi`,`mn`,`mo`,`ms`,`mtext`,`noembed`,`noframes`,`noscript`,`plaintext`,`script`,`style`,`svg`,`template`,`thead`,`title`,`video`,`xmp`]),He=null,Ue=Q({},[`audio`,`video`,`img`,`source`,`image`,`track`]),We=null,Ge=Q({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Ke=`http://www.w3.org/1998/Math/MathML`,Je=`http://www.w3.org/2000/svg`,Ye=`http://www.w3.org/1999/xhtml`,Ze=Ye,it=!1,at=null,ot=Q({},[Ke,Je,Ye],ve),st=Q({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),ct=Q({},[`annotation-xml`]),lt=Q({},[`title`,`style`,`font`,`a`,`script`]),ut=null,dt=[`application/xhtml+xml`,`text/html`],ft=null,pt=null,mt=n.createElement(`form`),ht=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(pt&&pt===e)){if((!e||typeof e!=`object`)&&(e={}),e=ke(e),ut=dt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,ft=ut===`application/xhtml+xml`?ve:_e,I=Ce(e,`ALLOWED_TAGS`)?Q({},e.ALLOWED_TAGS,ft):L,R=Ce(e,`ALLOWED_ATTR`)?Q({},e.ALLOWED_ATTR,ft):z,at=Ce(e,`ALLOWED_NAMESPACES`)?Q({},e.ALLOWED_NAMESPACES,ve):ot,We=Ce(e,`ADD_URI_SAFE_ATTR`)?Q(ke(Ge),e.ADD_URI_SAFE_ATTR,ft):Ge,He=Ce(e,`ADD_DATA_URI_TAGS`)?Q(ke(Ue),e.ADD_DATA_URI_TAGS,ft):Ue,De=Ce(e,`FORBID_CONTENTS`)?Q({},e.FORBID_CONTENTS,ft):Oe,V=Ce(e,`FORBID_TAGS`)?Q({},e.FORBID_TAGS,ft):ke({}),H=Ce(e,`FORBID_ATTR`)?Q({},e.FORBID_ATTR,ft):ke({}),Ee=Ce(e,`USE_PROFILES`)?e.USE_PROFILES:!1,W=e.ALLOW_ARIA_ATTR!==!1,G=e.ALLOW_DATA_ATTR!==!1,K=e.ALLOW_UNKNOWN_PROTOCOLS||!1,q=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,J=e.SAFE_FOR_TEMPLATES||!1,Y=e.SAFE_FOR_XML!==!1,X=e.WHOLE_DOCUMENT||!1,re=e.RETURN_DOM||!1,ie=e.RETURN_DOM_FRAGMENT||!1,ae=e.RETURN_TRUSTED_TYPE||!1,te=e.FORCE_BODY||!1,oe=e.SANITIZE_DOM!==!1,ce=e.SANITIZE_NAMED_PROPS||!1,ue=e.KEEP_CONTENT!==!1,de=e.IN_PLACE||!1,F=e.ALLOWED_URI_REGEXP||qe,Ze=e.NAMESPACE||Ye,st=e.MATHML_TEXT_INTEGRATION_POINTS||st,ct=e.HTML_INTEGRATION_POINTS||ct,B=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(B.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(B.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(B.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),J&&(G=!1),ie&&(re=!0),Ee&&(I=Q({},Le),R=le(null),Ee.html===!0&&(Q(I,je),Q(R,Re)),Ee.svg===!0&&(Q(I,Me),Q(R,ze),Q(R,Ve)),Ee.svgFilters===!0&&(Q(I,Ne),Q(R,ze),Q(R,Ve)),Ee.mathMl===!0&&(Q(I,Fe),Q(R,Be),Q(R,Ve))),Ce(e,`ADD_TAGS`)||(U.tagCheck=null),Ce(e,`ADD_ATTR`)||(U.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?U.tagCheck=e.ADD_TAGS:(I===L&&(I=ke(I)),Q(I,e.ADD_TAGS,ft))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?U.attributeCheck=e.ADD_ATTR:(R===z&&(R=ke(R)),Q(R,e.ADD_ATTR,ft))),e.ADD_URI_SAFE_ATTR&&Q(We,e.ADD_URI_SAFE_ATTR,ft),e.FORBID_CONTENTS&&(De===Oe&&(De=ke(De)),Q(De,e.FORBID_CONTENTS,ft)),e.ADD_FORBID_CONTENTS&&(De===Oe&&(De=ke(De)),Q(De,e.ADD_FORBID_CONTENTS,ft)),ue&&(I[`#text`]=!0),X&&Q(I,[`html`,`head`,`body`]),I.table&&(Q(I,[`tbody`]),delete V.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Te(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Te(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);b=e.TRUSTED_TYPES_POLICY,x=b.createHTML(``)}else b===void 0&&(b=tt(p,i)),b!==null&&typeof x==`string`&&(x=b.createHTML(``));se&&se(e),pt=e}},_t=Q({},[...Me,...Ne,...Pe]),vt=Q({},[...Fe,...Ie]),yt=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:Ze,tagName:`template`});let n=_e(e.tagName),r=_e(t.tagName);return at[e.namespaceURI]?e.namespaceURI===Je?t.namespaceURI===Ye?n===`svg`:t.namespaceURI===Ke?n===`svg`&&(r===`annotation-xml`||st[r]):!!_t[n]:e.namespaceURI===Ke?t.namespaceURI===Ye?n===`math`:t.namespaceURI===Je?n===`math`&&ct[r]:!!vt[n]:e.namespaceURI===Ye?t.namespaceURI===Je&&!ct[r]||t.namespaceURI===Ke&&!st[r]?!1:!vt[n]&&(lt[n]||!_t[n]):!!(ut===`application/xhtml+xml`&&at[e.namespaceURI]):!1},bt=function(e){he(t.removed,{element:e});try{y(e).removeChild(e)}catch{g(e)}},xt=function(e,n){try{he(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{he(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(re||ie)try{bt(n)}catch{}else try{n.setAttribute(e,``)}catch{}},St=function(e){let t=null,r=null;if(te)e=`<remove></remove>`+e;else{let t=ye(e,/^[\r\n\t ]+/);r=t&&t[0]}ut===`application/xhtml+xml`&&Ze===Ye&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=b?b.createHTML(e):e;if(Ze===Ye)try{t=new f().parseFromString(i,ut)}catch{}if(!t||!t.documentElement){t=S.createDocument(Ze,`template`,null);try{t.documentElement.innerHTML=it?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Ze===Ye?T.call(t,X?`html`:`body`)[0]:X?t.documentElement:a},Ct=function(e){return C.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},wt=function(e){return e instanceof d&&(typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||!(e.attributes instanceof u)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`)},Tt=function(e){return typeof s==`function`&&e instanceof s};function Et(e,n,r){fe(e,e=>{e.call(t,n,r,pt)})}let Dt=function(e){let n=null;if(Et(D.beforeSanitizeElements,e,null),wt(e))return bt(e),!0;let r=ft(e.nodeName);if(Et(D.uponSanitizeElement,e,{tagName:r,allowedTags:I}),Y&&e.hasChildNodes()&&!Tt(e.firstElementChild)&&we(/<[/\w!]/g,e.innerHTML)&&we(/<[/\w!]/g,e.textContent)||e.nodeType===$e.progressingInstruction||Y&&e.nodeType===$e.comment&&we(/<[/\w]/g,e.data))return bt(e),!0;if(!(U.tagCheck instanceof Function&&U.tagCheck(r))&&(!I[r]||V[r])){if(!V[r]&&kt(r)&&(B.tagNameCheck instanceof RegExp&&we(B.tagNameCheck,r)||B.tagNameCheck instanceof Function&&B.tagNameCheck(r)))return!1;if(ue&&!De[r]){let t=y(e)||e.parentNode,n=v(e)||e.childNodes;if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=h(n[i],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,_(e))}}}return bt(e),!0}return e instanceof c&&!yt(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&we(/<\/no(script|embed|frames)/i,e.innerHTML)?(bt(e),!0):(J&&e.nodeType===$e.text&&(n=e.textContent,fe([O,k,A],e=>{n=be(n,e,` `)}),e.textContent!==n&&(he(t.removed,{element:e.cloneNode()}),e.textContent=n)),Et(D.afterSanitizeElements,e,null),!1)},Ot=function(e,t,r){if(H[t]||oe&&(t===`id`||t===`name`)&&(r in n||r in mt))return!1;if(!(G&&!H[t]&&we(j,t))&&!(W&&we(M,t))&&!(U.attributeCheck instanceof Function&&U.attributeCheck(t,e))){if(!R[t]||H[t]){if(!(kt(e)&&(B.tagNameCheck instanceof RegExp&&we(B.tagNameCheck,e)||B.tagNameCheck instanceof Function&&B.tagNameCheck(e))&&(B.attributeNameCheck instanceof RegExp&&we(B.attributeNameCheck,t)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck(t,e))||t===`is`&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&we(B.tagNameCheck,r)||B.tagNameCheck instanceof Function&&B.tagNameCheck(r))))return!1}else if(!We[t]&&!we(F,be(r,P,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&xe(r,`data:`)===0&&He[e])&&!(K&&!we(N,be(r,P,``)))&&r)return!1}return!0},kt=function(e){return e!==`annotation-xml`&&ye(e,ee)},At=function(e){Et(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||wt(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:R,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=ft(a),l=s,u=a===`value`?l:Se(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,Et(D.uponSanitizeAttribute,e,r),u=r.attrValue,ce&&(c===`id`||c===`name`)&&(xt(a,e),u=`user-content-`+u),Y&&we(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){xt(a,e);continue}if(c===`attributename`&&ye(u,`href`)){xt(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){xt(a,e);continue}if(!q&&we(/\/>/i,u)){xt(a,e);continue}J&&fe([O,k,A],e=>{u=be(u,e,` `)});let d=ft(e.nodeName);if(!Ot(d,c,u)){xt(a,e);continue}if(b&&typeof p==`object`&&typeof p.getAttributeType==`function`&&!o)switch(p.getAttributeType(d,c)){case`TrustedHTML`:u=b.createHTML(u);break;case`TrustedScriptURL`:u=b.createScriptURL(u);break}if(u!==l)try{o?e.setAttributeNS(o,a,u):e.setAttribute(a,u),wt(e)?bt(e):me(t.removed)}catch{xt(a,e)}}Et(D.afterSanitizeAttributes,e,null)},jt=function e(t){let n=null,r=Ct(t);for(Et(D.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Et(D.uponSanitizeShadowNode,n,null),Dt(n),At(n),n.content instanceof a&&e(n.content);Et(D.afterSanitizeShadowDOM,t,null)};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,o=null,c=null,l=null;if(it=!e,it&&(e=`<!-->`),typeof e!=`string`&&!Tt(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw Te(`dirty is not a string, aborting`)}else throw Te(`toString is not a function`);if(!t.isSupported)return e;if(Z||gt(n),t.removed=[],typeof e==`string`&&(de=!1),de){if(e.nodeName){let t=ft(e.nodeName);if(!I[t]||V[t])throw Te(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=St(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===$e.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!re&&!J&&!X&&e.indexOf(`<`)===-1)return b&&ae?b.createHTML(e):e;if(i=St(e),!i)return re?null:ae?x:``}i&&te&&bt(i.firstChild);let u=Ct(de?e:i);for(;c=u.nextNode();)Dt(c),At(c),c.content instanceof a&&jt(c.content);if(de)return e;if(re){if(ie)for(l=w.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(R.shadowroot||R.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=X?i.outerHTML:i.innerHTML;return X&&I[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&we(Xe,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
23
|
-
`+d),J&&fe([O,k,A],e=>{d=be(d,e,` `)}),b&&ae?b.createHTML(d):d},t.setConfig=function(){gt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),Z=!0},t.clearConfig=function(){pt=null,Z=!1},t.isValidAttribute=function(e,t,n){return pt||gt({}),Ot(ft(e),ft(t),n)},t.addHook=function(e,t){typeof t==`function`&&he(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=pe(D[e],t);return n===-1?void 0:ge(D[e],n,1)[0]}return me(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=nt()},t}var it=rt(),at=`https://devapi.teip.io`,ot=`R33xmWassTrJO5I52s6FZ_3sdQRdiOR7Vc0oDSuf7No`,st=`urn:ietf:wg:oauth:2.0:oob`,ct=`https://cas.static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js`,lt=void 0,ut=void 0,dt=void 0,ft=void 0,pt=void 0,mt=void 0,ht=void 0,gt=void 0,_t=class e{static instance;environment=`production`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}isDevelopmentEnvironment(){return st}getEnvironment(){return this.isDevelopmentEnvironment()?`development`:this.environment}getDevelopmentEnvironment(){return{apiBase:at,externalApiUid:ot,songbirdUrl:ct,externalApiRedirectUri:st}}getProductionEnvironment(){return{apiBase:lt,songbirdUrl:ft,externalApiUid:ut,externalApiRedirectUri:dt}}getSandboxEnvironment(){return{apiBase:pt,songbirdUrl:gt,externalApiUid:mt,externalApiRedirectUri:ht}}setEnvironment(e){e&&(this.environment=e)}getCurrentEnvironment(){switch(this.getEnvironment()){case`production`:return this.getProductionEnvironment();case`sandbox`:return this.getSandboxEnvironment();default:return this.getDevelopmentEnvironment()}}},vt=class e{static instance;get baseUrl(){return _t.getInstance().getCurrentEnvironment().apiBase||``}bearerToken=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setBearerToken(e){this.bearerToken=e}async get(e,t={},n=`api/v1`){return fetch(`${this.baseUrl}/${n}/${e}`,{...t,method:`GET`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...t.headers}})}async post(e,t,n={},r=`api/v1`){return fetch(`${this.baseUrl}/${r}/${e}`,{body:it.sanitize(JSON.stringify(t)),method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...n.headers},...n})}},yt=e=>btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``),bt=async e=>{let t=new TextEncoder().encode(e);return yt(await crypto.subtle.digest(`SHA-256`,t))},xt=class e{static instance;authenticateAuthorize=`oauth/application/authorize`;authenticateToken=`oauth/application/token`;request=vt.getInstance();pkceReady;authToken=null;environment=_t.getInstance();constructor(){this.pkceReady=this.generatePkce()}static getInstance(){return e.instance||=new e,e.instance}getAuthToken(){return this.authToken}async generatePkce(){let e=te.util.bytesToHex(te.random.getBytesSync(32));return{verifier:e,challenge:await bt(e)}}async authorize(e){let{externalApiUid:t,externalApiRedirectUri:n}=this.environment.getCurrentEnvironment(),r={client_id:t,redirect_uri:n,response_type:`code`,code_challenge:e,code_challenge_method:`S256`};return(await this.request.post(this.authenticateAuthorize,r)).json()}async token(e,t){let{externalApiUid:n,externalApiRedirectUri:r}=this.environment.getCurrentEnvironment(),i={client_id:n,code:e,code_verifier:t,redirect_uri:r,grant_type:`authorization_code`};return(await this.request.post(this.authenticateToken,i)).json()}async authenticateAndAuthorize(){let{verifier:e,challenge:t}=await this.pkceReady;try{let n=await this.authorize(t);this.authToken=await this.token(n.redirect_uri.code,e)}catch(e){throw console.error(`Error authenticating or authorizing:`,e),e}}},St=class e{request=vt.getInstance();static instance;urlConfig=`external/online_payments/orders/configuration`;config=null;constructor(e,t,n){this.urlConfig=this.setURLcode(e,t,n)}static getInstance({code:t,paymentRequestCode:n,paymentOrderCode:r}){return!e.instance&&t&&(e.instance=new e(t,n,r)),e.instance}static resetInstance(){e.instance=null}getConfig(){return this.config}setURLcode=(e,t,n)=>t?`${this.urlConfig}?code=${t}&scope=order_template`:n?`${this.urlConfig}?code=${n}&scope=order`:`${this.urlConfig}?code=${e}&scope=branch`;async configRequest(){let e=await this.request.get(this.urlConfig),t=await e.json();return e.ok&&(this.config=t),t}},Ct={400:`Error al cargar orden de pago: solicitud inválida`,401:`Error al cargar orden de pago: autenticación requerida`,403:`Error al cargar orden de pago: autorización denegada`,404:`Error al cargar orden de pago: recurso no encontrado`,500:`Error al cargar orden de pago: falla interna del servicio`,502:`Error al cargar orden de pago: respuesta inválida del servicio upstream`,503:`Error al cargar orden de pago: servicio no disponible`};function wt(e,t){return Ct[e]||`Error al obtener información de sucursal: ${t}`}var Tt=class e{static instance;initPromise=null;auth=xt.getInstance();request=vt.getInstance();branchConfig;environment=_t.getInstance();authToken=null;config=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}static resetInstance(){e.instance=null}async initialize({branchCode:e,paymentRequestCode:t,paymentOrderCode:n,environment:r}){return this.initPromise?this.initPromise:(this.environment.setEnvironment(r),this.initPromise=this.boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}),this.initPromise)}async boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}){await this.auth.authenticateAndAuthorize(),this.authToken=this.auth.getAuthToken(),this.request.setBearerToken(this.authToken?.access_token??``),this.branchConfig=St.getInstance({code:e,paymentRequestCode:t,paymentOrderCode:n});let r=await this.branchConfig.configRequest();if(`error`in r)throw Error(wt(r.status,e));this.config=this.branchConfig.getConfig()}getAuthToken(){if(!this.authToken)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.authToken}getConfig(){if(!this.config)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.config}},Et=class e{request=vt.getInstance();static instance;cardinalToken=null;urlCardinalToken=`external/online_payments/orders/token`;orchestrator=Tt.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCardinalToken(){return this.cardinalToken}setCardinalToken(e){this.cardinalToken=e}generateCardinalTokenPayload(e){let t=this.orchestrator.getConfig();return{order_id:t.data.order_id||void 0,branch_id:t.data.branch_id,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),subtotal_currency:`USD`,tip_cents:0,tip_currency:`USD`,description:e.description}}async fetchCardinalToken(e){let t=await this.request.post(this.urlCardinalToken,{data:e}),n=await t.json();return t.ok,n}},Dt=class e{request=vt.getInstance();static instance;countries=[];countriesLoadError=null;urlCountries=`resources/countries`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCountries(){return this.countries}setCountries(e){this.countries=e}getCountriesLoadError(){return this.countriesLoadError}async fetchCountries(){let e=await this.request.get(this.urlCountries),t=await e.json();return e.ok?(this.countriesLoadError=null,this.setCountries(t.data),t):(this.countriesLoadError=`No se pudo cargar la lista de países.`,t)}},Ot=class e{static instance;states=[];statesLoadError=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getStates(){return this.states}setStates(e){this.states=e}getStatesLoadError(){return this.statesLoadError}async fetchStates(e){let t=await vt.getInstance().get(`resources/countries/${e}/states`),n=await t.json();return t.ok?(this.statesLoadError=null,this.setStates(n.data),n):(this.statesLoadError=`No se pudo cargar la lista de estados.`,this.setStates([]),n)}},kt=e=>{let t=e[0];return Number(t)===4?`visa`:Number(t)===2||Number(t)===5?`mastercard`:Number(t)===6?`union_pay`:`not_valid`},At=e=>{let[t,n]=e.split(`/`);return{month:t,year:n}},jt=e=>e.replace(/\s/g,``),Mt=class e{static instance;get songbirdUrl(){return _t.getInstance().getCurrentEnvironment().songbirdUrl||``}loaded=!1;initialized=!1;constructor(){}static getInstance(){return e.instance||=new e,e.instance}loadSongbird(){return this.loaded?Promise.resolve():new Promise((e,t)=>{let n=document.createElement(`script`);n.src=this.songbirdUrl,n.onload=()=>{this.loaded=!0,e()},n.onerror=()=>t(Error(`Failed to load Songbird script`)),document.head.appendChild(n)})}getBrowserData(){return{browser_java_enabled:!1,browser_language:navigator.language,browser_color_depth:screen.colorDepth,browser_screen_height:screen.height,browser_screen_width:screen.width,browser_time_zone:Intl.DateTimeFormat().resolvedOptions().timeZone||`America/El_Salvador`,user_agent:navigator.userAgent,device_channel:`Browser`,browser_javascript_enabled:!0}}async setupCardinal(e){return await this.loadSongbird(),this.cleanup(),new Promise((t,n)=>{try{Cardinal.configure({timeout:6e3,maxRequestRetries:3,logging:{level:`on`}}),Cardinal.on(`payments.setupComplete`,n=>{Cardinal.off(`payments.setupComplete`),this.submitCollectionForm(e),t(n.sessionId)}),Cardinal.setup(`init`,{jwt:e}),this.initialized=!0}catch(e){n(e)}})}cleanup(){let e=document.querySelector(`iframe[name="cardinalIframe"]`);e&&e.remove();let t=document.getElementById(`collectionForm`);t&&t.remove()}submitCollectionForm(e){this.cleanup();let t=document.createElement(`iframe`);t.name=`cardinalIframe`,t.height=`10`,t.width=`10`,t.style.cssText=`visibility:hidden;position:absolute;top:-1000px;left:-1000px;`,document.body.appendChild(t);let n=document.createElement(`form`);n.id=`collectionForm`,n.name=`devicedata`,n.method=`POST`,n.action=`https://centinelapistag.cardinalcommerce.com/V2/Cruise/Collect`,n.target=`cardinalIframe`;let r=document.createElement(`input`);r.type=`hidden`,r.name=`JWT`,r.value=e,n.appendChild(r),document.body.appendChild(n),n.submit()}onCardinalValidated(){return new Promise(e=>{Cardinal.on(`payments.validated`,t=>{Cardinal.off(`payments.validated`),e(t)})})}continueCardinal(e,t,n){Cardinal.continue(`cca`,{AcsUrl:e.acs_url,Payload:e.payload},{OrderDetails:{TransactionId:e.transaction_id,OrderNumber:e.order_number_client,Amount:t,CurrencyCode:e.currency_code,OrderDescription:n,OrderChannel:e.transaction_mode}})}},Nt=class e{static instance;request=vt.getInstance();cardinalService=Mt.getInstance();registerPaymentResponse=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async registerPayment(e,t){let n={data:{...t,...this.cardinalService.getBrowserData()}},r=await this.request.post(`external/online_payments/orders/${e}/register_payment`,n,{},`api/v2`),i=await r.json();return r.ok&&(this.registerPaymentResponse=i.data),i}async validatePayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/validate_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}async confirmPayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/confirm_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}buildValidatePayloadFromCardinal(e){let t=this.registerPaymentResponse;return{validated:e.Validated,action_code:e.ActionCode,error_number:e.ErrorNumber,error_description:e.ErrorDescription,payment_type:e.Payment.Type,processor_transaction_id:e.Payment.ProcessorTransactionId,cavv:e.Payment.ExtendedData.CAVV,currency_code:e.Payment.ExtendedData.CurrencyCode,eci_flag:e.Payment.ExtendedData.ECIFlag,three_ds_version:e.Payment.ExtendedData.ThreeDSVersion,pares_status:e.Payment.ExtendedData.PAResStatus,signature_verification:e.Payment.ExtendedData.SignatureVerification,cavv_algorithm:t?.cavv_algorithm||void 0,enrolled:t?.enrolled||void 0,ds_transaction_id:t?.ds_transaction_id||void 0}}},Pt=class{request=vt.getInstance();urlEncrypt=`resources/encryption/public_key`;token=null;async getTokenFromServer(){let e=await this.request.get(this.urlEncrypt,{},`api/v2`);if(!e.ok)throw Error(`Failed to get encryption token`);this.token=(await e.json()).data}getToken(){return this.token}encryptData(e){if(!this.token)throw Error(`Encryption token not found`);let t=JSON.stringify({...e,nonce:crypto.randomUUID(),timestamp:Math.floor(Date.now()/1e3)}),n=te.default.random.getBytesSync(32),r=te.default.random.getBytesSync(12),i=te.default.cipher.createCipher(`AES-GCM`,n);i.start({iv:r,additionalData:``,tagLength:128}),i.update(te.default.util.createBuffer(t,`utf8`)),i.finish();let a=te.default.pki.publicKeyFromPem(this.token.public_key).encrypt(n,`RSA-OAEP`);return{encrypted_data:te.default.util.encode64(i.output.getBytes()),encrypted_key:te.default.util.encode64(a),iv:te.default.util.encode64(r),tag:te.default.util.encode64(i.mode.tag.getBytes())}}},Ft=class e{static instance;cardinalToken=Et.getInstance();cardinalService=Mt.getInstance();cardinalPayment=Nt.getInstance();countryContent=Dt.getInstance();stateContent=Ot.getInstance();orchestrator=Tt.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}async process(e,t,n){let r=this.cardinalToken.generateCardinalTokenPayload(e);t&&(r.subtotal_cents=t);let i=await this.cardinalToken.fetchCardinalToken(r);if(`error`in i){n.sendAlert(`Error`,i.error||`Error al procesar el pago`);return}let{id:a,token:o}=i.data,s=await this.cardinalService.setupCardinal(o),c=this.countryContent.getCountries().find(t=>t.id===e.country),l=this.stateContent.getStates().find(t=>t.id===e.region),u=At(e.cardExpiry),d=new Pt;try{await d.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let f=d.encryptData({card_number:jt(e.cardNumber),card_expiration_month:u.month,card_expiration_year:`20${u.year}`,cvv:e.cardCvc,expiration_date:`${u.year}${u.month}`,cardholder_name:e.cardHolder}),p={reference:s,billing_address:e.address,billing_city:e.city,billing_country_code:String(c?.number||``),billing_first_name:e.firstName,billing_last_name:e.lastName,billing_postal_code:e.postalCode,billing_state_code:l?.short_code||``,billing_country_name:c?.name||``,email:e.email,phone_number:e.phone.replace(/\s/g,``),order_id:this.orchestrator.getConfig().data.order_id||void 0,...f},m=await this.cardinalPayment.registerPayment(a,p);if(`error`in m){n.sendAlert(`Error`,m.error||`Error al procesar el pago`);return}let h=m.data;if(h.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
23
|
+
`+d),J&&fe([O,k,A],e=>{d=be(d,e,` `)}),b&&ae?b.createHTML(d):d},t.setConfig=function(){gt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),Z=!0},t.clearConfig=function(){pt=null,Z=!1},t.isValidAttribute=function(e,t,n){return pt||gt({}),Ot(ft(e),ft(t),n)},t.addHook=function(e,t){typeof t==`function`&&he(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=pe(D[e],t);return n===-1?void 0:ge(D[e],n,1)[0]}return me(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=nt()},t}var it=rt(),at=`https://devapi.teip.io`,ot=`R33xmWassTrJO5I52s6FZ_3sdQRdiOR7Vc0oDSuf7No`,st=`urn:ietf:wg:oauth:2.0:oob`,ct=`https://cas.static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js`,lt=void 0,ut=void 0,dt=void 0,ft=void 0,pt=void 0,mt=void 0,ht=void 0,gt=void 0,_t=class e{static instance;environment=`production`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}isDevelopmentEnvironment(){return st}getEnvironment(){return this.isDevelopmentEnvironment()?`development`:this.environment}getDevelopmentEnvironment(){return{apiBase:at,externalApiUid:ot,songbirdUrl:ct,externalApiRedirectUri:st}}getProductionEnvironment(){return{apiBase:lt,songbirdUrl:ft,externalApiUid:ut,externalApiRedirectUri:dt}}getSandboxEnvironment(){return{apiBase:pt,songbirdUrl:gt,externalApiUid:mt,externalApiRedirectUri:ht}}setEnvironment(e){e&&(this.environment=e)}getCurrentEnvironment(){switch(this.getEnvironment()){case`production`:return this.getProductionEnvironment();case`sandbox`:return this.getSandboxEnvironment();default:return this.getDevelopmentEnvironment()}}},vt=class e{static instance;get baseUrl(){return _t.getInstance().getCurrentEnvironment().apiBase||``}bearerToken=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setBearerToken(e){this.bearerToken=e}async get(e,t={},n=`api/v1`){return fetch(`${this.baseUrl}/${n}/${e}`,{...t,method:`GET`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...t.headers}})}async post(e,t,n={},r=`api/v1`){return fetch(`${this.baseUrl}/${r}/${e}`,{body:it.sanitize(JSON.stringify(t)),method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...n.headers},...n})}},yt=e=>btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``),bt=async e=>{let t=new TextEncoder().encode(e);return yt(await crypto.subtle.digest(`SHA-256`,t))},xt=class e{static instance;authenticateAuthorize=`oauth/application/authorize`;authenticateToken=`oauth/application/token`;request=vt.getInstance();pkceReady;authToken=null;environment=_t.getInstance();constructor(){this.pkceReady=this.generatePkce()}static getInstance(){return e.instance||=new e,e.instance}getAuthToken(){return this.authToken}async generatePkce(){let e=te.util.bytesToHex(te.random.getBytesSync(32));return{verifier:e,challenge:await bt(e)}}async authorize(e){let{externalApiUid:t,externalApiRedirectUri:n}=this.environment.getCurrentEnvironment(),r={client_id:t,redirect_uri:n,response_type:`code`,code_challenge:e,code_challenge_method:`S256`};return(await this.request.post(this.authenticateAuthorize,r)).json()}async token(e,t){let{externalApiUid:n,externalApiRedirectUri:r}=this.environment.getCurrentEnvironment(),i={client_id:n,code:e,code_verifier:t,redirect_uri:r,grant_type:`authorization_code`};return(await this.request.post(this.authenticateToken,i)).json()}async authenticateAndAuthorize(){let{verifier:e,challenge:t}=await this.pkceReady;try{let n=await this.authorize(t);this.authToken=await this.token(n.redirect_uri.code,e)}catch(e){throw console.error(`Error authenticating or authorizing:`,e),e}}},St=class e{request=vt.getInstance();static instance;urlConfig=`external/online_payments/orders/configuration`;config=null;constructor(e,t,n){this.urlConfig=this.setURLcode(e,t,n)}static getInstance({code:t,paymentRequestCode:n,paymentOrderCode:r}){return!e.instance&&t&&(e.instance=new e(t,n,r)),e.instance}static resetInstance(){e.instance=null}getConfig(){return this.config}setURLcode=(e,t,n)=>t?`${this.urlConfig}?code=${t}&scope=order_template`:n?`${this.urlConfig}?code=${n}&scope=order`:`${this.urlConfig}?code=${e}&scope=branch`;async configRequest(){let e=await this.request.get(this.urlConfig),t=await e.json();return e.ok&&(this.config=t),t}},Ct={400:`Error al cargar orden de pago: solicitud inválida`,401:`Error al cargar orden de pago: autenticación requerida`,403:`Error al cargar orden de pago: autorización denegada`,404:`Error al cargar orden de pago: recurso no encontrado`,500:`Error al cargar orden de pago: falla interna del servicio`,502:`Error al cargar orden de pago: respuesta inválida del servicio upstream`,503:`Error al cargar orden de pago: servicio no disponible`};function wt(e,t){return Ct[e]||`Error al obtener información de sucursal: ${t}`}var Tt=class e{static instance;initPromise=null;auth=xt.getInstance();request=vt.getInstance();branchConfig;environment=_t.getInstance();authToken=null;config=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}static resetInstance(){e.instance=null}async initialize({branchCode:e,paymentRequestCode:t,paymentOrderCode:n,environment:r}){return this.initPromise?this.initPromise:(this.environment.setEnvironment(r),this.initPromise=this.boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}),this.initPromise)}async boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}){await this.auth.authenticateAndAuthorize(),this.authToken=this.auth.getAuthToken(),this.request.setBearerToken(this.authToken?.access_token??``),this.branchConfig=St.getInstance({code:e,paymentRequestCode:t,paymentOrderCode:n});let r=await this.branchConfig.configRequest();if(`error`in r)throw Error(wt(r.status,e));this.config=this.branchConfig.getConfig()}getAuthToken(){if(!this.authToken)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.authToken}getConfig(){if(!this.config)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.config}},Et=class e{request=vt.getInstance();static instance;cardinalToken=null;urlCardinalToken=`external/online_payments/orders/token`;orchestrator=Tt.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCardinalToken(){return this.cardinalToken}setCardinalToken(e){this.cardinalToken=e}generateCardinalTokenPayload(e){let t=this.orchestrator.getConfig();return{order_id:t.data.order_id||void 0,branch_id:t.data.branch_id,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),subtotal_currency:`USD`,tip_cents:0,tip_currency:`USD`,description:e.description}}async fetchCardinalToken(e){let t=await this.request.post(this.urlCardinalToken,{data:e}),n=await t.json();return t.ok,n}},Dt=class e{request=vt.getInstance();static instance;countries=[];countriesLoadError=null;urlCountries=`resources/countries`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCountries(){return this.countries}setCountries(e){this.countries=e}getCountriesLoadError(){return this.countriesLoadError}async fetchCountries(){let e=await this.request.get(this.urlCountries),t=await e.json();return e.ok?(this.countriesLoadError=null,this.setCountries(t.data),t):(this.countriesLoadError=`No se pudo cargar la lista de países.`,t)}},Ot=class e{static instance;states=[];statesLoadError=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getStates(){return this.states}setStates(e){this.states=e}getStatesLoadError(){return this.statesLoadError}async fetchStates(e){let t=await vt.getInstance().get(`resources/countries/${e}/states`),n=await t.json();return t.ok?(this.statesLoadError=null,this.setStates(n.data),n):(this.statesLoadError=`No se pudo cargar la lista de estados.`,this.setStates([]),n)}},kt=e=>{let t=e[0];return Number(t)===4?`visa`:Number(t)===2||Number(t)===5?`mastercard`:Number(t)===6?`union_pay`:`not_valid`},At=e=>{let[t,n]=e.split(`/`);return{month:t,year:n}},jt=e=>e.replace(/\s/g,``),Mt=class e{static instance;get songbirdUrl(){return _t.getInstance().getCurrentEnvironment().songbirdUrl||``}loaded=!1;initialized=!1;originalAppendChild=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}loadSongbird(){return this.loaded?Promise.resolve():new Promise((e,t)=>{let n=document.createElement(`script`);n.src=this.songbirdUrl,n.onload=()=>{this.loaded=!0,e()},n.onerror=()=>t(Error(`Failed to load Songbird script`)),document.head.appendChild(n)})}getBrowserData(){return{browser_java_enabled:!1,browser_language:navigator.language,browser_color_depth:screen.colorDepth,browser_screen_height:screen.height,browser_screen_width:screen.width,browser_time_zone:Intl.DateTimeFormat().resolvedOptions().timeZone||`America/El_Salvador`,user_agent:navigator.userAgent,device_channel:`Browser`,browser_javascript_enabled:!0}}async setupCardinal(e){return await this.loadSongbird(),this.cleanup(),new Promise((t,n)=>{try{Cardinal.configure({timeout:6e3,maxRequestRetries:3,logging:{level:`on`}}),Cardinal.on(`payments.setupComplete`,n=>{Cardinal.off(`payments.setupComplete`),this.submitCollectionForm(e),t(n.sessionId)}),Cardinal.setup(`init`,{jwt:e}),this.initialized=!0}catch(e){n(e)}})}isCardinalModalNode(e){return!(e instanceof HTMLElement)||e.tagName&&e.tagName.toLowerCase()===`iframe`&&e.name===`cardinalIframe`||e.id===`collectionForm`||e.id===`Cardinal-collector`?!1:!!(e instanceof HTMLIFrameElement&&e.name===`cardinal-test-frame`||e.id===`Cardinal-ElementContainer`||e.id===`Cardinal-ElementLoader`||e.id===`Cardinal-Modal`||e.id===`Cardinal-Overlay`||e.id===`Cardinal-cca-IFrame`||e.id===`Cardinal-CCA-IFrame`||e.querySelector?.(`#Cardinal-Modal, #Cardinal-Overlay, #Cardinal-cca-IFrame, #Cardinal-CCA-IFrame`))}prepareModalElement(e){e instanceof HTMLIFrameElement&&e.name===`cardinal-test-frame`?(e.setAttribute(`popover`,`manual`),e.style.cssText+=`;position: fixed; z-index: 2147483647; inset: 0; margin: auto; background: #fff;`):(e.setAttribute(`popover`,`manual`),e.style.cssText+=`;border: none !important; background: transparent !important; padding: 0 !important; margin: 0 !important; width: 0 !important; height: 0 !important; max-width: none !important; max-height: none !important; overflow: visible !important; inset: 0 !important;`);let t=e.querySelector(`#Cardinal-Modal, .cardinalOverlay-content`);t&&t.style.setProperty(`z-index`,`2147483647`,`important`);let n=e.querySelector(`#Cardinal-Overlay, .cardinalOverlay-mask`);n&&n.style.setProperty(`z-index`,`2147483646`,`important`)}promoteToTopLayer(e){try{typeof e.showPopover==`function`&&e.showPopover()}catch{}let t=e.querySelector(`#Cardinal-Modal, .cardinalOverlay-content`);t&&t.style.setProperty(`z-index`,`2147483647`,`important`);let n=e.querySelector(`#Cardinal-Overlay, .cardinalOverlay-mask`);n&&n.style.setProperty(`z-index`,`2147483646`,`important`)}installDomInterceptor(){this.originalAppendChild||(this.originalAppendChild=document.body.appendChild,document.body.appendChild=e=>{if(this.isCardinalModalNode(e)&&e instanceof HTMLElement){this.prepareModalElement(e);let t=document.querySelectorAll(`dialog[open]`),n=t.length>0?t[t.length-1]:null,r=n?n.appendChild(e):this.originalAppendChild.call(document.body,e);return this.promoteToTopLayer(e),r}return this.originalAppendChild.call(document.body,e)})}restoreDomInterceptor(){this.originalAppendChild&&=(document.body.appendChild=this.originalAppendChild,null)}cleanup(){let e=document.querySelector(`iframe[name="cardinalIframe"]`);e&&e.remove();let t=document.getElementById(`collectionForm`);t&&t.remove(),document.querySelectorAll(`#Cardinal-ElementContainer, #Cardinal-ElementLoader, iframe[name="cardinal-test-frame"]`).forEach(e=>{if(e instanceof HTMLElement)try{e.hidePopover?.()}catch{}e.remove()}),this.restoreDomInterceptor()}submitCollectionForm(e){this.cleanup();let t=document.createElement(`iframe`);t.name=`cardinalIframe`,t.height=`10`,t.width=`10`,t.style.cssText=`visibility:hidden;position:absolute;top:-1000px;left:-1000px;`,document.body.appendChild(t);let n=document.createElement(`form`);n.id=`collectionForm`,n.name=`devicedata`,n.method=`POST`,n.action=`https://centinelapistag.cardinalcommerce.com/V2/Cruise/Collect`,n.target=`cardinalIframe`;let r=document.createElement(`input`);r.type=`hidden`,r.name=`JWT`,r.value=e,n.appendChild(r),document.body.appendChild(n),n.submit()}onCardinalValidated(){return new Promise(e=>{Cardinal.on(`payments.validated`,t=>{Cardinal.off(`payments.validated`),this.cleanup(),e(t)})})}continueCardinal(e,t,n){this.installDomInterceptor(),Cardinal.continue(`cca`,{AcsUrl:e.acs_url,Payload:e.payload},{OrderDetails:{TransactionId:e.transaction_id,OrderNumber:e.order_number_client,Amount:t,CurrencyCode:e.currency_code,OrderDescription:n,OrderChannel:e.transaction_mode}})}},Nt=class e{static instance;request=vt.getInstance();cardinalService=Mt.getInstance();registerPaymentResponse=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async registerPayment(e,t){let n={data:{...t,...this.cardinalService.getBrowserData()}},r=await this.request.post(`external/online_payments/orders/${e}/register_payment`,n,{},`api/v2`),i=await r.json();return r.ok&&(this.registerPaymentResponse=i.data),i}async validatePayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/validate_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}async confirmPayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/confirm_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}buildValidatePayloadFromCardinal(e){let t=this.registerPaymentResponse;return{validated:e.Validated,action_code:e.ActionCode,error_number:e.ErrorNumber,error_description:e.ErrorDescription,payment_type:e.Payment.Type,processor_transaction_id:e.Payment.ProcessorTransactionId,cavv:e.Payment.ExtendedData.CAVV,currency_code:e.Payment.ExtendedData.CurrencyCode,eci_flag:e.Payment.ExtendedData.ECIFlag,three_ds_version:e.Payment.ExtendedData.ThreeDSVersion,pares_status:e.Payment.ExtendedData.PAResStatus,signature_verification:e.Payment.ExtendedData.SignatureVerification,cavv_algorithm:t?.cavv_algorithm||void 0,enrolled:t?.enrolled||void 0,ds_transaction_id:t?.ds_transaction_id||void 0}}},Pt=class{request=vt.getInstance();urlEncrypt=`resources/encryption/public_key`;token=null;async getTokenFromServer(){let e=await this.request.get(this.urlEncrypt,{},`api/v2`);if(!e.ok)throw Error(`Failed to get encryption token`);this.token=(await e.json()).data}getToken(){return this.token}encryptData(e){if(!this.token)throw Error(`Encryption token not found`);let t=JSON.stringify({...e,nonce:crypto.randomUUID(),timestamp:Math.floor(Date.now()/1e3)}),n=te.default.random.getBytesSync(32),r=te.default.random.getBytesSync(12),i=te.default.cipher.createCipher(`AES-GCM`,n);i.start({iv:r,additionalData:``,tagLength:128}),i.update(te.default.util.createBuffer(t,`utf8`)),i.finish();let a=te.default.pki.publicKeyFromPem(this.token.public_key).encrypt(n,`RSA-OAEP`);return{encrypted_data:te.default.util.encode64(i.output.getBytes()),encrypted_key:te.default.util.encode64(a),iv:te.default.util.encode64(r),tag:te.default.util.encode64(i.mode.tag.getBytes())}}},Ft=class e{static instance;cardinalToken=Et.getInstance();cardinalService=Mt.getInstance();cardinalPayment=Nt.getInstance();countryContent=Dt.getInstance();stateContent=Ot.getInstance();orchestrator=Tt.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}async process(e,t,n){let r=this.cardinalToken.generateCardinalTokenPayload(e);t&&(r.subtotal_cents=t);let i=await this.cardinalToken.fetchCardinalToken(r);if(`error`in i){n.sendAlert(`Error`,i.error||`Error al procesar el pago`);return}let{id:a,token:o}=i.data,s=await this.cardinalService.setupCardinal(o),c=this.countryContent.getCountries().find(t=>t.id===e.country),l=this.stateContent.getStates().find(t=>t.id===e.region),u=At(e.cardExpiry),d=new Pt;try{await d.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let f=d.encryptData({card_number:jt(e.cardNumber),card_expiration_month:u.month,card_expiration_year:`20${u.year}`,cvv:e.cardCvc,expiration_date:`${u.year}${u.month}`,cardholder_name:e.cardHolder}),p={reference:s,billing_address:e.address,billing_city:e.city,billing_country_code:String(c?.number||``),billing_first_name:e.firstName,billing_last_name:e.lastName,billing_postal_code:e.postalCode,billing_state_code:l?.short_code||``,billing_country_name:c?.name||``,email:e.email,phone_number:e.phone.replace(/\s/g,``),order_id:this.orchestrator.getConfig().data.order_id||void 0,...f},m=await this.cardinalPayment.registerPayment(a,p);if(`error`in m){n.sendAlert(`Error`,m.error||`Error al procesar el pago`);return}let h=m.data;if(h.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
24
24
|
Por favor revisa tu información e inténtalo de nuevo`);return}if(h.required_authentication&&h.acs_url!==``){this.cardinalService.continueCardinal(h,String(r.subtotal_cents),e.description);let t=await this.cardinalService.onCardinalValidated();if(t.ActionCode!==`SUCCESS`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
25
25
|
Por favor revisa tu información e inténtalo de nuevo`);return}let i=this.cardinalPayment.buildValidatePayloadFromCardinal(t),o=await this.cardinalPayment.validatePayment(a,{...i,...f});if(`error`in o){n.sendAlert(`Error`,o.error||`Error al procesar el pago`);return}if(o.data.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
26
26
|
Por favor revisa tu información e inténtalo de nuevo`);return}}else{let e=await this.cardinalPayment.validatePayment(a,{...f});if(`error`in e){n.sendAlert(`Error`,e.error||`Error al procesar el pago`);return}if(e.data.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
@@ -195,7 +195,7 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Zt=[{label:`Docu
|
|
|
195
195
|
${u}
|
|
196
196
|
${i?`\n <template class="operation-form-template" data-operation="crypto">${i}</template>`:``}
|
|
197
197
|
</div>
|
|
198
|
-
`}function xn(e){let t=`<img src="${hn}" alt="Bizz Logo" class="bizz-logo">`,n=e.customBodyHtml??bn(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return pn.replace(`<!--STYLES-->`,`<style>${gn}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--VERSION-->`,`<div class="bizz-sdk-version">v1.5.
|
|
198
|
+
`}function xn(e){let t=`<img src="${hn}" alt="Bizz Logo" class="bizz-logo">`,n=e.customBodyHtml??bn(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return pn.replace(`<!--STYLES-->`,`<style>${gn}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--VERSION-->`,`<div class="bizz-sdk-version">v1.5.7</div>`).replace(`<!--SCRIPT-->`,`<script>${mn}<\/script>`)}function Sn(e){let t=document.createElement(`iframe`);return t.style.border=`none`,t.style.display=`block`,t.style.overflow=`hidden`,t.srcdoc=e,t.style.width=`100%`,t.style.height=`100%`,t}var Cn=class e{static instance;request;constructor(){this.request=vt.getInstance()}static getInstance(){return e.instance||=new e,e.instance}async createCharge(e){let t=await this.request.post(`external/online_payments/orders/crypto/charge`,e);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge creation failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}async getChargeStatus(e){let t=await this.request.get(`external/online_payments/orders/crypto/charge/${e}/status`);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge status failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}},wn=3e3,Tn=`NAKA_CRYPTO`,En=`CRYPTO`,$={UNDERPAID:{title:`Pago incompleto`,message:`El monto pagado en criptomonedas fue inferior al total requerido. El cobro ha finalizado y tu reembolso ha sido gestionado a través de la pasarela.`,retryLabel:`Intentar nuevamente`},OVERPAID:{finishLabel:`Finalizar compra (Pago recibido)`},CANCELED:{title:`¡Pago cancelado!`,message:`El pago con criptomonedas fue cancelado.`},EXPIRED:{title:`¡Cobro expirado!`,message:`El tiempo para completar el pago con criptomonedas ha finalizado.`},FAILED:{title:`¡Pago fallido!`,message:`No se pudo procesar el pago con criptomonedas.`},TIMEOUT:{title:`¡Tiempo de espera agotado!`,message:`El tiempo para completar el pago con criptomonedas ha expirado.`},CONNECTION_ERROR:{title:`¡Error de conexión!`,message:`No fue posible verificar el estado del pago con criptomonedas.`},SESSION_EXPIRED:{title:`¡Sesión expirada!`,message:`Tu sesión ha expirado. Por favor, intenta de nuevo.`},ORDER_NOT_FOUND:{title:`¡Orden no encontrada!`,message:`El cobro no se encuentra disponible o fue cancelado.`},PAYMENT_UNAVAILABLE:{title:`¡Pago no disponible!`,defaultMessage:`No fue posible procesar el cobro con criptomonedas. Por favor, intenta con otro método.`},CREATE_CHARGE_ERROR:{title:`¡Error al crear cobro con Criptomonedas!`,message:`No se pudo conectar con el servicio de pagos en criptomonedas.`}},Dn=`<svg
|
|
199
199
|
xmlns="http://www.w3.org/2000/svg"
|
|
200
200
|
width="24"
|
|
201
201
|
height="24"
|
|
@@ -262,7 +262,7 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Zt=[{label:`Docu
|
|
|
262
262
|
<path d="M12 3a12 12 0 0 0 8.5 3a12 12 0 0 1 -8.5 15a12 12 0 0 1 -8.5 -15a12 12 0 0 0 8.5 -3" />
|
|
263
263
|
<path d="M11 11a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" />
|
|
264
264
|
<path d="M12 12l0 2.5" />
|
|
265
|
-
</svg>`,jn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,Mn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,Nn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,Pn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,Fn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,In=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,Ln={"currency-dollar":Dn,"credit-card":On,calendar:kn,"shield-lock":An,email:jn,user:Mn,description:Nn,document:Pn,phone:Fn,"map-pin":In};function Rn(e){let t=Ln[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var zn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?kt(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Bn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:Rn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?Vt(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}}),Vn=class{static version=`1.5.6`;config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=zn.getInstance();origin=u;serverErrorHandler;orchestrator=Tt.getInstance();paymentIntent=qt.getInstance();points=Jt.getInstance();countryContent=Dt.getInstance();processPayment=Ft.getInstance();stateContent=Ot.getInstance();amountEvaluation=Ut.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;pendingAlert=null;currentCryptoChargeId=null;isCryptoOverpaid=!1;lastCryptoOverpaidSuccess=null;constructor(e){if(this.config={...e},!this.config.paymentOrderCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`o`);e&&(this.config.paymentOrderCode=e)}if(!this.config.paymentRequestCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`t`);e&&(this.config.paymentRequestCode=e)}this.currentAmount=this.config.totalAmount,this.serverErrorHandler=new Kt(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=zt(this.config.i18n?.loading);e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}t.remove(),this.setupMessageHandler();let n=this.orchestrator.getConfig()?.data?.status;if(n===`completed`){await this.renderCompletedOrderView();return}if(n===`cancelled`){await this.renderCancelledOrderView();return}if(this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}setupMessageHandler(){this.messageHandler&&window.removeEventListener(`message`,this.messageHandler),this.messageHandler=async e=>{if(e.source&&e.source!==this.iframe?.contentWindow&&e.source!==window)return;let t=e.data;if(t?.type){if(t.type===`payment-form:ready`&&(this.pendingAlert&&=(this.sendAlert(this.pendingAlert.title,this.pendingAlert.message),null)),t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=Ht(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=Ht(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=Xt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...nn,country:{...nn.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=fn(Bn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}if(t.type===`payment-form:naka-callback`){this.stopNakaPolling();let e=t.chargeId||this.currentCryptoChargeId,n=Cn.getInstance(),r=t.status,i=null;if(e)try{let t=await n.getChargeStatus(e);t?.data&&(i=t.data,r=i.status)}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}if(r===`UNDERPAID`){this.stopNakaPolling(),this.postMessageToIframe({type:`payment-form:crypto-incomplete`,title:$.UNDERPAID.title,message:$.UNDERPAID.message,retryLabel:$.UNDERPAID.retryLabel}),this.sendFailureEmitter(422,$.UNDERPAID.message);return}if(r===`CANCELED`||r===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(r===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(r===`FAILED`||r===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(r===`SUCCESS`||r===`COMPLETED`||r===`PAID`||r===`OVERPAID`){let n=this.orchestrator.getConfig()?.data?.amount_currency||`USD`,r={data:{id:e||``,status:`success`,amount_cents:this.config.totalAmount??this.currentAmount??i?.amount_cents??0,amount_currency:n,response_code:`00`,authorization_number:i?.authorization_number||i?.transaction_id||t.chargeId||`NAKA-${Date.now()}`,reference_number:i?.reference_number||i?.order_number||t.orderNumber||e||``,billing_document_number:``,description:this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:Tn,card_last_digits:En,invoice_serie:null}};this.sendSuccess(r);return}}if(t.type===`payment-form:return-initial`){if(this.stopNakaPolling(),this.isCryptoOverpaid&&this.lastCryptoOverpaidSuccess){this.sendSuccess(this.lastCryptoOverpaidSuccess);return}this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}if(t.type===`payment-form:crypto-retry`){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}}},window.addEventListener(`message`,this.messageHandler)}applyFixedAmountFromOrderTemplate(){let e=this.orchestrator.getConfig();if(!e?.data)return;let{data:t}=e;if(t.order_template_id==null&&t.order_id==null||typeof t.amount_cents!=`number`||t.amount_cents<=0)return;let n=Vt(t.amount_cents/100,t.amount_currency||`USD`,`decimal`);this.config.description=t.description,this.config.totalAmount=Ht(n),this.currentAmount=Ht(n)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...tn,country:{...tn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:en,u=en,d=!!this.config.totalAmount,f=Bn(t,l,this.currentAmount,d),p=n?Bn(t,u,this.currentAmount,d):f,m=Bn(t,{...nn,country:{...nn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=rn(this.config.i18n?.submitButton),g=i?ln(f):``,_=a?un(p):``,v=o?dn(p,h):``,y=s?fn(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?Vt(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=Sn(xn({headerHtml:an({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:Rn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}async renderCompletedOrderView(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=this.orchestrator.getConfig().data,n=`
|
|
265
|
+
</svg>`,jn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,Mn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,Nn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,Pn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,Fn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,In=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,Ln={"currency-dollar":Dn,"credit-card":On,calendar:kn,"shield-lock":An,email:jn,user:Mn,description:Nn,document:Pn,phone:Fn,"map-pin":In};function Rn(e){let t=Ln[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var zn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?kt(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Bn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:Rn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?Vt(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}}),Vn=class{static version=`1.5.7`;config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=zn.getInstance();origin=u;serverErrorHandler;orchestrator=Tt.getInstance();paymentIntent=qt.getInstance();points=Jt.getInstance();countryContent=Dt.getInstance();processPayment=Ft.getInstance();stateContent=Ot.getInstance();amountEvaluation=Ut.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;pendingAlert=null;currentCryptoChargeId=null;isCryptoOverpaid=!1;lastCryptoOverpaidSuccess=null;constructor(e){if(this.config={...e},!this.config.paymentOrderCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`o`);e&&(this.config.paymentOrderCode=e)}if(!this.config.paymentRequestCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`t`);e&&(this.config.paymentRequestCode=e)}this.currentAmount=this.config.totalAmount,this.serverErrorHandler=new Kt(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=zt(this.config.i18n?.loading);e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}t.remove(),this.setupMessageHandler();let n=this.orchestrator.getConfig()?.data?.status;if(n===`completed`){await this.renderCompletedOrderView();return}if(n===`cancelled`){await this.renderCancelledOrderView();return}if(this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}setupMessageHandler(){this.messageHandler&&window.removeEventListener(`message`,this.messageHandler),this.messageHandler=async e=>{if(e.source&&e.source!==this.iframe?.contentWindow&&e.source!==window)return;let t=e.data;if(t?.type){if(t.type===`payment-form:ready`&&(this.pendingAlert&&=(this.sendAlert(this.pendingAlert.title,this.pendingAlert.message),null)),t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=Ht(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=Ht(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=Xt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...nn,country:{...nn.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=fn(Bn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}if(t.type===`payment-form:naka-callback`){this.stopNakaPolling();let e=t.chargeId||this.currentCryptoChargeId,n=Cn.getInstance(),r=t.status,i=null;if(e)try{let t=await n.getChargeStatus(e);t?.data&&(i=t.data,r=i.status)}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}if(r===`UNDERPAID`){this.stopNakaPolling(),this.postMessageToIframe({type:`payment-form:crypto-incomplete`,title:$.UNDERPAID.title,message:$.UNDERPAID.message,retryLabel:$.UNDERPAID.retryLabel}),this.sendFailureEmitter(422,$.UNDERPAID.message);return}if(r===`CANCELED`||r===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(r===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(r===`FAILED`||r===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(r===`SUCCESS`||r===`COMPLETED`||r===`PAID`||r===`OVERPAID`){let n=this.orchestrator.getConfig()?.data?.amount_currency||`USD`,r={data:{id:e||``,status:`success`,amount_cents:this.config.totalAmount??this.currentAmount??i?.amount_cents??0,amount_currency:n,response_code:`00`,authorization_number:i?.authorization_number||i?.transaction_id||t.chargeId||`NAKA-${Date.now()}`,reference_number:i?.reference_number||i?.order_number||t.orderNumber||e||``,billing_document_number:``,description:this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:Tn,card_last_digits:En,invoice_serie:null}};this.sendSuccess(r);return}}if(t.type===`payment-form:return-initial`){if(this.stopNakaPolling(),this.isCryptoOverpaid&&this.lastCryptoOverpaidSuccess){this.sendSuccess(this.lastCryptoOverpaidSuccess);return}this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}if(t.type===`payment-form:crypto-retry`){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}}},window.addEventListener(`message`,this.messageHandler)}applyFixedAmountFromOrderTemplate(){let e=this.orchestrator.getConfig();if(!e?.data)return;let{data:t}=e;if(t.order_template_id==null&&t.order_id==null||typeof t.amount_cents!=`number`||t.amount_cents<=0)return;let n=Vt(t.amount_cents/100,t.amount_currency||`USD`,`decimal`);this.config.description=t.description,this.config.totalAmount=Ht(n),this.currentAmount=Ht(n)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...tn,country:{...tn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:en,u=en,d=!!this.config.totalAmount,f=Bn(t,l,this.currentAmount,d),p=n?Bn(t,u,this.currentAmount,d):f,m=Bn(t,{...nn,country:{...nn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=rn(this.config.i18n?.submitButton),g=i?ln(f):``,_=a?un(p):``,v=o?dn(p,h):``,y=s?fn(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?Vt(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=Sn(xn({headerHtml:an({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:Rn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}async renderCompletedOrderView(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=this.orchestrator.getConfig().data,n=`
|
|
266
266
|
<div class="payment-success">
|
|
267
267
|
<p class="payment-success__amount">${Vt(t.amount_cents/100,t.amount_currency||`USD`)}</p>
|
|
268
268
|
<div class="payment-success__blocks">
|
|
@@ -289,4 +289,4 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Zt=[{label:`Docu
|
|
|
289
289
|
<h3>Orden cancelada</h3>
|
|
290
290
|
<p>Esta orden de pago ha sido cancelada o no está disponible para pago.</p>
|
|
291
291
|
</div>
|
|
292
|
-
`})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}postMessageToIframe(e){try{this.iframe?.contentWindow?.postMessage(e,this.origin)}catch{try{this.iframe?.contentWindow?.postMessage(e,`*`)}catch{}}}resetForm(){this.postMessageToIframe({type:`payment-form:reset`})}setSubmitLoading(e){this.postMessageToIframe({type:`payment-form:set-submit-loading`,disabled:e})}setToken(e){this.postMessageToIframe({type:`payment-form:set-token`,token:e})}sendAlert(e,t){this.postMessageToIframe({type:`payment-form:alert`,title:e,message:t})}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=Xt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??Ht(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.postMessageToIframe({type:`payment-form:success`,paymentIntent:e});let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=Cn.getInstance(),n=this.config.totalAmount??this.currentAmount??Ht(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():void 0),a={data:{branch_id:this.orchestrator.getConfig()?.data?.branch_id||this.config.branchCode,amount_cents:n,currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,description:e.description||this.config.description||`Pago con Criptomonedas`,billing_document_number:e.billingDocumentNumber||``,redirect_url:this.config.redirectUrl||(typeof window<`u`?`${window.location.origin}/paylink/crypto/callback`:void 0),kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,country:i||``,phone:e.phone||void 0,phone_number:e.phone||void 0,nationality:e.nationality?.toUpperCase()||i||void 0,city:e.city||void 0,postal_code:e.postalCode||void 0,zip_code:e.postalCode||e.zipCode||void 0,address:e.address||void 0}}};try{let r=await t.createCharge(a);this.currentCryptoChargeId=r.data.charge_id,this.setSubmitLoading(!1),this.postMessageToIframe({type:`payment-form:naka-checkout`,redirectUrl:r.data.redirect_url,chargeId:r.data.charge_id}),this.startNakaPolling(r.data.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert($.CREATE_CHARGE_ERROR.title,$.CREATE_CHARGE_ERROR.message),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en servicio de criptomonedas`)}}async handleNakaTerminalFailure(e,t,n){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),this.pendingAlert={title:e,message:t},await this.renderForm(),this.sendFailureEmitter(n,t)}startNakaPolling(e,t,n){this.stopNakaPolling();let r=Cn.getInstance(),i=0,a=Date.now();this.nakaPollingInterval=setInterval(async()=>{try{if(Date.now()-a>=18e5){await this.handleNakaTerminalFailure($.TIMEOUT.title,$.TIMEOUT.message,408);return}let o=await r.getChargeStatus(e);i=0;let s=o.data,c=s?.status;if(c===`SUCCESS`||c===`COMPLETED`||c===`PAID`){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:Tn,card_last_digits:En,invoice_serie:null}};this.sendSuccess(r);return}if(c===`CANCELED`||c===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(c===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(c===`FAILED`||c===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(c===`OVERPAID`){this.isCryptoOverpaid=!0,this.lastCryptoOverpaidSuccess={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:Tn,card_last_digits:En,invoice_serie:null}},this.postMessageToIframe({type:`payment-form:crypto-overpaid`,label:$.OVERPAID.finishLabel});return}if(c===`PENDING`||c===`IN_PROGRESS`||c===`OPEN`||c===`UNDERPAID`)return}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}if(e?.status===401||e?.status===403){await this.handleNakaTerminalFailure($.SESSION_EXPIRED.title,$.SESSION_EXPIRED.message,e.status);return}if(i++,i>=5){await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}}},wn)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.pendingAlert=null,this.currentCryptoChargeId=null,this.isCryptoOverpaid=!1,this.lastCryptoOverpaidSuccess=null,this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}},Hn=`1.5.
|
|
292
|
+
`})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}postMessageToIframe(e){try{this.iframe?.contentWindow?.postMessage(e,this.origin)}catch{try{this.iframe?.contentWindow?.postMessage(e,`*`)}catch{}}}resetForm(){this.postMessageToIframe({type:`payment-form:reset`})}setSubmitLoading(e){this.postMessageToIframe({type:`payment-form:set-submit-loading`,disabled:e})}setToken(e){this.postMessageToIframe({type:`payment-form:set-token`,token:e})}sendAlert(e,t){this.postMessageToIframe({type:`payment-form:alert`,title:e,message:t})}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=Xt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??Ht(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.postMessageToIframe({type:`payment-form:success`,paymentIntent:e});let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=Cn.getInstance(),n=this.config.totalAmount??this.currentAmount??Ht(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():void 0),a={data:{branch_id:this.orchestrator.getConfig()?.data?.branch_id||this.config.branchCode,amount_cents:n,currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,description:e.description||this.config.description||`Pago con Criptomonedas`,billing_document_number:e.billingDocumentNumber||``,redirect_url:this.config.redirectUrl||(typeof window<`u`?`${window.location.origin}/paylink/crypto/callback`:void 0),kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,country:i||``,phone:e.phone||void 0,phone_number:e.phone||void 0,nationality:e.nationality?.toUpperCase()||i||void 0,city:e.city||void 0,postal_code:e.postalCode||void 0,zip_code:e.postalCode||e.zipCode||void 0,address:e.address||void 0}}};try{let r=await t.createCharge(a);this.currentCryptoChargeId=r.data.charge_id,this.setSubmitLoading(!1),this.postMessageToIframe({type:`payment-form:naka-checkout`,redirectUrl:r.data.redirect_url,chargeId:r.data.charge_id}),this.startNakaPolling(r.data.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert($.CREATE_CHARGE_ERROR.title,$.CREATE_CHARGE_ERROR.message),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en servicio de criptomonedas`)}}async handleNakaTerminalFailure(e,t,n){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),this.pendingAlert={title:e,message:t},await this.renderForm(),this.sendFailureEmitter(n,t)}startNakaPolling(e,t,n){this.stopNakaPolling();let r=Cn.getInstance(),i=0,a=Date.now();this.nakaPollingInterval=setInterval(async()=>{try{if(Date.now()-a>=18e5){await this.handleNakaTerminalFailure($.TIMEOUT.title,$.TIMEOUT.message,408);return}let o=await r.getChargeStatus(e);i=0;let s=o.data,c=s?.status;if(c===`SUCCESS`||c===`COMPLETED`||c===`PAID`){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:Tn,card_last_digits:En,invoice_serie:null}};this.sendSuccess(r);return}if(c===`CANCELED`||c===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(c===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(c===`FAILED`||c===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(c===`OVERPAID`){this.isCryptoOverpaid=!0,this.lastCryptoOverpaidSuccess={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:Tn,card_last_digits:En,invoice_serie:null}},this.postMessageToIframe({type:`payment-form:crypto-overpaid`,label:$.OVERPAID.finishLabel});return}if(c===`PENDING`||c===`IN_PROGRESS`||c===`OPEN`||c===`UNDERPAID`)return}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}if(e?.status===401||e?.status===403){await this.handleNakaTerminalFailure($.SESSION_EXPIRED.title,$.SESSION_EXPIRED.message,e.status);return}if(i++,i>=5){await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}}},wn)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.pendingAlert=null,this.currentCryptoChargeId=null,this.isCryptoOverpaid=!1,this.lastCryptoOverpaidSuccess=null,this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}},Hn=`1.5.7`;exports.BizzPaymentForm=Vn,exports.VERSION=Hn;
|
package/dist/index.global.js
CHANGED
|
@@ -20,7 +20,7 @@ Private-Lines: `+f+`\r
|
|
|
20
20
|
`,l+=m;var b=o(`putty-private-key-file-mac-key`,t),x=n.util.createBuffer();a(x,s),a(x,c),a(x,r),x.putInt32(u.length()),x.putBuffer(u),x.putInt32(p.length()),x.putBuffer(p);var S=n.hmac.create();return S.start(`sha1`,b),S.update(x.bytes()),l+=`\r
|
|
21
21
|
Private-MAC: `+S.digest().toHex()+`\r
|
|
22
22
|
`,l},r.publicKeyToOpenSSH=function(e,t){var r=`ssh-rsa`;t||=``;var o=n.util.createBuffer();return a(o,r),i(o,e.e),i(o,e.n),r+` `+n.util.encode64(o.bytes())+` `+t},r.privateKeyToOpenSSH=function(e,t){return t?n.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:`aes128`}):n.pki.privateKeyToPem(e)},r.getPublicKeyFingerprint=function(e,t){t||={};var r=t.md||n.md.md5.create(),o=`ssh-rsa`,s=n.util.createBuffer();a(s,o),i(s,e.e),i(s,e.n),r.start(),r.update(s.getBytes());var c=r.digest();if(t.encoding===`hex`){var l=c.toHex();return t.delimiter?l.match(/.{2}/g).join(t.delimiter):l}else if(t.encoding===`binary`)return c.getBytes();else if(t.encoding)throw Error(`Unknown encoding "`+t.encoding+`".`);return c};function i(e,t){var r=t.toString(16);r[0]>=`8`&&(r=`00`+r);var i=n.util.hexToBytes(r);e.putInt32(i.length),e.putBytes(i)}function a(e,t){e.putInt32(t.length),e.putString(t)}function o(){for(var e=n.md.sha1.create(),t=arguments.length,r=0;r<t;++r)e.update(arguments[r]);return e.digest()}})),re=l(s(((e,t)=>{t.exports=f(),_(),U(),y(),h(),w(),K(),x(),q(),J(),Y(),I(),E(),C(),M(),B(),X(),V(),N(),O(),R(),k(),A(),ne(),H(),m()}))(),1),{entries:ie,setPrototypeOf:ae,isFrozen:oe,getPrototypeOf:se,getOwnPropertyDescriptor:ce}=Object,{freeze:le,seal:ue,create:de}=Object,{apply:fe,construct:pe}=typeof Reflect<`u`&&Reflect;le||=function(e){return e},ue||=function(e){return e},fe||=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];return e.apply(t,r)},pe||=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return new e(...n)};var me=Z(Array.prototype.forEach),he=Z(Array.prototype.lastIndexOf),ge=Z(Array.prototype.pop),_e=Z(Array.prototype.push),ve=Z(Array.prototype.splice),ye=Z(String.prototype.toLowerCase),be=Z(String.prototype.toString),xe=Z(String.prototype.match),Se=Z(String.prototype.replace),Ce=Z(String.prototype.indexOf),we=Z(String.prototype.trim),Te=Z(Object.prototype.hasOwnProperty),Ee=Z(RegExp.prototype.test),De=Oe(TypeError);function Z(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return fe(e,t,r)}}function Oe(e){return function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return pe(e,n)}}function Q(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ye;ae&&ae(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(oe(t)||(t[r]=e),i=e)}e[i]=!0}return e}function ke(e){for(let t=0;t<e.length;t++)Te(e,t)||(e[t]=null);return e}function Ae(e){let t=de(null);for(let[n,r]of ie(e))Te(e,n)&&(Array.isArray(r)?t[n]=ke(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=Ae(r):t[n]=r);return t}function je(e,t){for(;e!==null;){let n=ce(e,t);if(n){if(n.get)return Z(n.get);if(typeof n.value==`function`)return Z(n.value)}e=se(e)}function n(){return null}return n}var Me=le(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Ne=le(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),Pe=le([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Fe=le([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Ie=le(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Le=le([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Re=le([`#text`]),ze=le(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns.slot`.split(`.`)),Be=le(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Ve=le(`accent.accentunder.align.bevelled.close.columnsalign.columnlines.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lspace.lquote.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),He=le([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Ue=ue(/\{\{[\w\W]*|[\w\W]*\}\}/gm),We=ue(/<%[\w\W]*|[\w\W]*%>/gm),Ge=ue(/\$\{[\w\W]*/gm),Ke=ue(/^data-[\-\w.\u00B7-\uFFFF]+$/),qe=ue(/^aria-[\-\w]+$/),Je=ue(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ye=ue(/^(?:\w+script|data):/i),Xe=ue(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ze=ue(/^html$/i),Qe=ue(/^[a-z][.\w]*(-[.\w]+)+$/i),$e=Object.freeze({__proto__:null,ARIA_ATTR:qe,ATTR_WHITESPACE:Xe,CUSTOM_ELEMENT:Qe,DATA_ATTR:Ke,DOCTYPE_NAME:Ze,ERB_EXPR:We,IS_ALLOWED_URI:Je,IS_SCRIPT_OR_DATA:Ye,MUSTACHE_EXPR:Ue,TMPLIT_EXPR:Ge}),et={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},tt=function(){return typeof window>`u`?null:window},nt=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},rt=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function it(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:tt(),t=e=>it(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==et.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,i=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:c,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=e,m=c.prototype,h=je(m,`cloneNode`),g=je(m,`remove`),_=je(m,`nextSibling`),v=je(m,`childNodes`),y=je(m,`parentNode`);if(typeof o==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let b,x=``,{implementation:S,createNodeIterator:C,createDocumentFragment:w,getElementsByTagName:T}=n,{importNode:E}=r,D=rt();t.isSupported=typeof ie==`function`&&typeof y==`function`&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:O,ERB_EXPR:k,TMPLIT_EXPR:A,DATA_ATTR:ee,ARIA_ATTR:j,IS_SCRIPT_OR_DATA:M,ATTR_WHITESPACE:N,CUSTOM_ELEMENT:te}=$e,{IS_ALLOWED_URI:P}=$e,F=null,I=Q({},[...Me,...Ne,...Pe,...Ie,...Re]),L=null,R=Q({},[...ze,...Be,...Ve,...He]),z=Object.seal(de(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),B=null,V=null,H=Object.seal(de(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),U=!0,W=!0,G=!1,K=!0,q=!1,J=!0,Y=!1,X=!1,ne=!1,re=!1,ae=!1,oe=!1,se=!0,ce=!1,ue=!0,fe=!1,pe={},Z=null,Oe=Q({},[`annotation-xml`,`audio`,`colgroup`,`desc`,`foreignobject`,`head`,`iframe`,`math`,`mi`,`mn`,`mo`,`ms`,`mtext`,`noembed`,`noframes`,`noscript`,`plaintext`,`script`,`style`,`svg`,`template`,`thead`,`title`,`video`,`xmp`]),ke=null,Ue=Q({},[`audio`,`video`,`img`,`source`,`image`,`track`]),We=null,Ge=Q({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Ke=`http://www.w3.org/1998/Math/MathML`,qe=`http://www.w3.org/2000/svg`,Ye=`http://www.w3.org/1999/xhtml`,Xe=Ye,Qe=!1,at=null,ot=Q({},[Ke,qe,Ye],be),st=Q({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),ct=Q({},[`annotation-xml`]),lt=Q({},[`title`,`style`,`font`,`a`,`script`]),ut=null,dt=[`application/xhtml+xml`,`text/html`],ft=null,pt=null,mt=n.createElement(`form`),ht=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(pt&&pt===e)){if((!e||typeof e!=`object`)&&(e={}),e=Ae(e),ut=dt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,ft=ut===`application/xhtml+xml`?be:ye,F=Te(e,`ALLOWED_TAGS`)?Q({},e.ALLOWED_TAGS,ft):I,L=Te(e,`ALLOWED_ATTR`)?Q({},e.ALLOWED_ATTR,ft):R,at=Te(e,`ALLOWED_NAMESPACES`)?Q({},e.ALLOWED_NAMESPACES,be):ot,We=Te(e,`ADD_URI_SAFE_ATTR`)?Q(Ae(Ge),e.ADD_URI_SAFE_ATTR,ft):Ge,ke=Te(e,`ADD_DATA_URI_TAGS`)?Q(Ae(Ue),e.ADD_DATA_URI_TAGS,ft):Ue,Z=Te(e,`FORBID_CONTENTS`)?Q({},e.FORBID_CONTENTS,ft):Oe,B=Te(e,`FORBID_TAGS`)?Q({},e.FORBID_TAGS,ft):Ae({}),V=Te(e,`FORBID_ATTR`)?Q({},e.FORBID_ATTR,ft):Ae({}),pe=Te(e,`USE_PROFILES`)?e.USE_PROFILES:!1,U=e.ALLOW_ARIA_ATTR!==!1,W=e.ALLOW_DATA_ATTR!==!1,G=e.ALLOW_UNKNOWN_PROTOCOLS||!1,K=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,q=e.SAFE_FOR_TEMPLATES||!1,J=e.SAFE_FOR_XML!==!1,Y=e.WHOLE_DOCUMENT||!1,re=e.RETURN_DOM||!1,ae=e.RETURN_DOM_FRAGMENT||!1,oe=e.RETURN_TRUSTED_TYPE||!1,ne=e.FORCE_BODY||!1,se=e.SANITIZE_DOM!==!1,ce=e.SANITIZE_NAMED_PROPS||!1,ue=e.KEEP_CONTENT!==!1,fe=e.IN_PLACE||!1,P=e.ALLOWED_URI_REGEXP||Je,Xe=e.NAMESPACE||Ye,st=e.MATHML_TEXT_INTEGRATION_POINTS||st,ct=e.HTML_INTEGRATION_POINTS||ct,z=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(z.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(z.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(z.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),q&&(W=!1),ae&&(re=!0),pe&&(F=Q({},Re),L=de(null),pe.html===!0&&(Q(F,Me),Q(L,ze)),pe.svg===!0&&(Q(F,Ne),Q(L,Be),Q(L,He)),pe.svgFilters===!0&&(Q(F,Pe),Q(L,Be),Q(L,He)),pe.mathMl===!0&&(Q(F,Ie),Q(L,Ve),Q(L,He))),Te(e,`ADD_TAGS`)||(H.tagCheck=null),Te(e,`ADD_ATTR`)||(H.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?H.tagCheck=e.ADD_TAGS:(F===I&&(F=Ae(F)),Q(F,e.ADD_TAGS,ft))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?H.attributeCheck=e.ADD_ATTR:(L===R&&(L=Ae(L)),Q(L,e.ADD_ATTR,ft))),e.ADD_URI_SAFE_ATTR&&Q(We,e.ADD_URI_SAFE_ATTR,ft),e.FORBID_CONTENTS&&(Z===Oe&&(Z=Ae(Z)),Q(Z,e.FORBID_CONTENTS,ft)),e.ADD_FORBID_CONTENTS&&(Z===Oe&&(Z=Ae(Z)),Q(Z,e.ADD_FORBID_CONTENTS,ft)),ue&&(F[`#text`]=!0),Y&&Q(F,[`html`,`head`,`body`]),F.table&&(Q(F,[`tbody`]),delete B.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw De(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw De(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);b=e.TRUSTED_TYPES_POLICY,x=b.createHTML(``)}else b===void 0&&(b=nt(p,i)),b!==null&&typeof x==`string`&&(x=b.createHTML(``));le&&le(e),pt=e}},_t=Q({},[...Ne,...Pe,...Fe]),vt=Q({},[...Ie,...Le]),yt=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:Xe,tagName:`template`});let n=ye(e.tagName),r=ye(t.tagName);return at[e.namespaceURI]?e.namespaceURI===qe?t.namespaceURI===Ye?n===`svg`:t.namespaceURI===Ke?n===`svg`&&(r===`annotation-xml`||st[r]):!!_t[n]:e.namespaceURI===Ke?t.namespaceURI===Ye?n===`math`:t.namespaceURI===qe?n===`math`&&ct[r]:!!vt[n]:e.namespaceURI===Ye?t.namespaceURI===qe&&!ct[r]||t.namespaceURI===Ke&&!st[r]?!1:!vt[n]&&(lt[n]||!_t[n]):!!(ut===`application/xhtml+xml`&&at[e.namespaceURI]):!1},bt=function(e){_e(t.removed,{element:e});try{y(e).removeChild(e)}catch{g(e)}},xt=function(e,n){try{_e(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{_e(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(re||ae)try{bt(n)}catch{}else try{n.setAttribute(e,``)}catch{}},St=function(e){let t=null,r=null;if(ne)e=`<remove></remove>`+e;else{let t=xe(e,/^[\r\n\t ]+/);r=t&&t[0]}ut===`application/xhtml+xml`&&Xe===Ye&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=b?b.createHTML(e):e;if(Xe===Ye)try{t=new f().parseFromString(i,ut)}catch{}if(!t||!t.documentElement){t=S.createDocument(Xe,`template`,null);try{t.documentElement.innerHTML=Qe?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Xe===Ye?T.call(t,Y?`html`:`body`)[0]:Y?t.documentElement:a},Ct=function(e){return C.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},wt=function(e){return e instanceof d&&(typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||!(e.attributes instanceof u)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`)},Tt=function(e){return typeof s==`function`&&e instanceof s};function Et(e,n,r){me(e,e=>{e.call(t,n,r,pt)})}let Dt=function(e){let n=null;if(Et(D.beforeSanitizeElements,e,null),wt(e))return bt(e),!0;let r=ft(e.nodeName);if(Et(D.uponSanitizeElement,e,{tagName:r,allowedTags:F}),J&&e.hasChildNodes()&&!Tt(e.firstElementChild)&&Ee(/<[/\w!]/g,e.innerHTML)&&Ee(/<[/\w!]/g,e.textContent)||e.nodeType===et.progressingInstruction||J&&e.nodeType===et.comment&&Ee(/<[/\w]/g,e.data))return bt(e),!0;if(!(H.tagCheck instanceof Function&&H.tagCheck(r))&&(!F[r]||B[r])){if(!B[r]&&kt(r)&&(z.tagNameCheck instanceof RegExp&&Ee(z.tagNameCheck,r)||z.tagNameCheck instanceof Function&&z.tagNameCheck(r)))return!1;if(ue&&!Z[r]){let t=y(e)||e.parentNode,n=v(e)||e.childNodes;if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=h(n[i],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,_(e))}}}return bt(e),!0}return e instanceof c&&!yt(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&Ee(/<\/no(script|embed|frames)/i,e.innerHTML)?(bt(e),!0):(q&&e.nodeType===et.text&&(n=e.textContent,me([O,k,A],e=>{n=Se(n,e,` `)}),e.textContent!==n&&(_e(t.removed,{element:e.cloneNode()}),e.textContent=n)),Et(D.afterSanitizeElements,e,null),!1)},Ot=function(e,t,r){if(V[t]||se&&(t===`id`||t===`name`)&&(r in n||r in mt))return!1;if(!(W&&!V[t]&&Ee(ee,t))&&!(U&&Ee(j,t))&&!(H.attributeCheck instanceof Function&&H.attributeCheck(t,e))){if(!L[t]||V[t]){if(!(kt(e)&&(z.tagNameCheck instanceof RegExp&&Ee(z.tagNameCheck,e)||z.tagNameCheck instanceof Function&&z.tagNameCheck(e))&&(z.attributeNameCheck instanceof RegExp&&Ee(z.attributeNameCheck,t)||z.attributeNameCheck instanceof Function&&z.attributeNameCheck(t,e))||t===`is`&&z.allowCustomizedBuiltInElements&&(z.tagNameCheck instanceof RegExp&&Ee(z.tagNameCheck,r)||z.tagNameCheck instanceof Function&&z.tagNameCheck(r))))return!1}else if(!We[t]&&!Ee(P,Se(r,N,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&Ce(r,`data:`)===0&&ke[e])&&!(G&&!Ee(M,Se(r,N,``)))&&r)return!1}return!0},kt=function(e){return e!==`annotation-xml`&&xe(e,te)},At=function(e){Et(D.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||wt(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=ft(a),l=s,u=a===`value`?l:we(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,Et(D.uponSanitizeAttribute,e,r),u=r.attrValue,ce&&(c===`id`||c===`name`)&&(xt(a,e),u=`user-content-`+u),J&&Ee(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){xt(a,e);continue}if(c===`attributename`&&xe(u,`href`)){xt(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){xt(a,e);continue}if(!K&&Ee(/\/>/i,u)){xt(a,e);continue}q&&me([O,k,A],e=>{u=Se(u,e,` `)});let d=ft(e.nodeName);if(!Ot(d,c,u)){xt(a,e);continue}if(b&&typeof p==`object`&&typeof p.getAttributeType==`function`&&!o)switch(p.getAttributeType(d,c)){case`TrustedHTML`:u=b.createHTML(u);break;case`TrustedScriptURL`:u=b.createScriptURL(u);break}if(u!==l)try{o?e.setAttributeNS(o,a,u):e.setAttribute(a,u),wt(e)?bt(e):ge(t.removed)}catch{xt(a,e)}}Et(D.afterSanitizeAttributes,e,null)},jt=function e(t){let n=null,r=Ct(t);for(Et(D.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Et(D.uponSanitizeShadowNode,n,null),Dt(n),At(n),n.content instanceof a&&e(n.content);Et(D.afterSanitizeShadowDOM,t,null)};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,o=null,c=null,l=null;if(Qe=!e,Qe&&(e=`<!-->`),typeof e!=`string`&&!Tt(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw De(`dirty is not a string, aborting`)}else throw De(`toString is not a function`);if(!t.isSupported)return e;if(X||gt(n),t.removed=[],typeof e==`string`&&(fe=!1),fe){if(e.nodeName){let t=ft(e.nodeName);if(!F[t]||B[t])throw De(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=St(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===et.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!re&&!q&&!Y&&e.indexOf(`<`)===-1)return b&&oe?b.createHTML(e):e;if(i=St(e),!i)return re?null:oe?x:``}i&&ne&&bt(i.firstChild);let u=Ct(fe?e:i);for(;c=u.nextNode();)Dt(c),At(c),c.content instanceof a&&jt(c.content);if(fe)return e;if(re){if(ae)for(l=w.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(L.shadowroot||L.shadowrootmode)&&(l=E.call(r,l,!0)),l}let d=Y?i.outerHTML:i.innerHTML;return Y&&F[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&Ee(Ze,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
23
|
-
`+d),q&&me([O,k,A],e=>{d=Se(d,e,` `)}),b&&oe?b.createHTML(d):d},t.setConfig=function(){gt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),X=!0},t.clearConfig=function(){pt=null,X=!1},t.isValidAttribute=function(e,t,n){return pt||gt({}),Ot(ft(e),ft(t),n)},t.addHook=function(e,t){typeof t==`function`&&_e(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=he(D[e],t);return n===-1?void 0:ve(D[e],n,1)[0]}return ge(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=rt()},t}var at=it(),ot=`https://devapi.teip.io`,st=`R33xmWassTrJO5I52s6FZ_3sdQRdiOR7Vc0oDSuf7No`,ct=`urn:ietf:wg:oauth:2.0:oob`,lt=`https://cas.static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js`,ut=void 0,dt=void 0,ft=void 0,pt=void 0,mt=void 0,ht=void 0,gt=void 0,_t=void 0,vt=class e{static instance;environment=`production`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}isDevelopmentEnvironment(){return ct}getEnvironment(){return this.isDevelopmentEnvironment()?`development`:this.environment}getDevelopmentEnvironment(){return{apiBase:ot,externalApiUid:st,songbirdUrl:lt,externalApiRedirectUri:ct}}getProductionEnvironment(){return{apiBase:ut,songbirdUrl:pt,externalApiUid:dt,externalApiRedirectUri:ft}}getSandboxEnvironment(){return{apiBase:mt,songbirdUrl:_t,externalApiUid:ht,externalApiRedirectUri:gt}}setEnvironment(e){e&&(this.environment=e)}getCurrentEnvironment(){switch(this.getEnvironment()){case`production`:return this.getProductionEnvironment();case`sandbox`:return this.getSandboxEnvironment();default:return this.getDevelopmentEnvironment()}}},yt=class e{static instance;get baseUrl(){return vt.getInstance().getCurrentEnvironment().apiBase||``}bearerToken=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setBearerToken(e){this.bearerToken=e}async get(e,t={},n=`api/v1`){return fetch(`${this.baseUrl}/${n}/${e}`,{...t,method:`GET`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...t.headers}})}async post(e,t,n={},r=`api/v1`){return fetch(`${this.baseUrl}/${r}/${e}`,{body:at.sanitize(JSON.stringify(t)),method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...n.headers},...n})}},bt=e=>btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``),xt=async e=>{let t=new TextEncoder().encode(e);return bt(await crypto.subtle.digest(`SHA-256`,t))},St=class e{static instance;authenticateAuthorize=`oauth/application/authorize`;authenticateToken=`oauth/application/token`;request=yt.getInstance();pkceReady;authToken=null;environment=vt.getInstance();constructor(){this.pkceReady=this.generatePkce()}static getInstance(){return e.instance||=new e,e.instance}getAuthToken(){return this.authToken}async generatePkce(){let e=re.util.bytesToHex(re.random.getBytesSync(32));return{verifier:e,challenge:await xt(e)}}async authorize(e){let{externalApiUid:t,externalApiRedirectUri:n}=this.environment.getCurrentEnvironment(),r={client_id:t,redirect_uri:n,response_type:`code`,code_challenge:e,code_challenge_method:`S256`};return(await this.request.post(this.authenticateAuthorize,r)).json()}async token(e,t){let{externalApiUid:n,externalApiRedirectUri:r}=this.environment.getCurrentEnvironment(),i={client_id:n,code:e,code_verifier:t,redirect_uri:r,grant_type:`authorization_code`};return(await this.request.post(this.authenticateToken,i)).json()}async authenticateAndAuthorize(){let{verifier:e,challenge:t}=await this.pkceReady;try{let n=await this.authorize(t);this.authToken=await this.token(n.redirect_uri.code,e)}catch(e){throw console.error(`Error authenticating or authorizing:`,e),e}}},Ct=class e{request=yt.getInstance();static instance;urlConfig=`external/online_payments/orders/configuration`;config=null;constructor(e,t,n){this.urlConfig=this.setURLcode(e,t,n)}static getInstance({code:t,paymentRequestCode:n,paymentOrderCode:r}){return!e.instance&&t&&(e.instance=new e(t,n,r)),e.instance}static resetInstance(){e.instance=null}getConfig(){return this.config}setURLcode=(e,t,n)=>t?`${this.urlConfig}?code=${t}&scope=order_template`:n?`${this.urlConfig}?code=${n}&scope=order`:`${this.urlConfig}?code=${e}&scope=branch`;async configRequest(){let e=await this.request.get(this.urlConfig),t=await e.json();return e.ok&&(this.config=t),t}},wt={400:`Error al cargar orden de pago: solicitud inválida`,401:`Error al cargar orden de pago: autenticación requerida`,403:`Error al cargar orden de pago: autorización denegada`,404:`Error al cargar orden de pago: recurso no encontrado`,500:`Error al cargar orden de pago: falla interna del servicio`,502:`Error al cargar orden de pago: respuesta inválida del servicio upstream`,503:`Error al cargar orden de pago: servicio no disponible`};function Tt(e,t){return wt[e]||`Error al obtener información de sucursal: ${t}`}var Et=class e{static instance;initPromise=null;auth=St.getInstance();request=yt.getInstance();branchConfig;environment=vt.getInstance();authToken=null;config=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}static resetInstance(){e.instance=null}async initialize({branchCode:e,paymentRequestCode:t,paymentOrderCode:n,environment:r}){return this.initPromise?this.initPromise:(this.environment.setEnvironment(r),this.initPromise=this.boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}),this.initPromise)}async boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}){await this.auth.authenticateAndAuthorize(),this.authToken=this.auth.getAuthToken(),this.request.setBearerToken(this.authToken?.access_token??``),this.branchConfig=Ct.getInstance({code:e,paymentRequestCode:t,paymentOrderCode:n});let r=await this.branchConfig.configRequest();if(`error`in r)throw Error(Tt(r.status,e));this.config=this.branchConfig.getConfig()}getAuthToken(){if(!this.authToken)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.authToken}getConfig(){if(!this.config)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.config}},Dt=class e{request=yt.getInstance();static instance;cardinalToken=null;urlCardinalToken=`external/online_payments/orders/token`;orchestrator=Et.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCardinalToken(){return this.cardinalToken}setCardinalToken(e){this.cardinalToken=e}generateCardinalTokenPayload(e){let t=this.orchestrator.getConfig();return{order_id:t.data.order_id||void 0,branch_id:t.data.branch_id,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),subtotal_currency:`USD`,tip_cents:0,tip_currency:`USD`,description:e.description}}async fetchCardinalToken(e){let t=await this.request.post(this.urlCardinalToken,{data:e}),n=await t.json();return t.ok,n}},Ot=class e{request=yt.getInstance();static instance;countries=[];countriesLoadError=null;urlCountries=`resources/countries`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCountries(){return this.countries}setCountries(e){this.countries=e}getCountriesLoadError(){return this.countriesLoadError}async fetchCountries(){let e=await this.request.get(this.urlCountries),t=await e.json();return e.ok?(this.countriesLoadError=null,this.setCountries(t.data),t):(this.countriesLoadError=`No se pudo cargar la lista de países.`,t)}},kt=class e{static instance;states=[];statesLoadError=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getStates(){return this.states}setStates(e){this.states=e}getStatesLoadError(){return this.statesLoadError}async fetchStates(e){let t=await yt.getInstance().get(`resources/countries/${e}/states`),n=await t.json();return t.ok?(this.statesLoadError=null,this.setStates(n.data),n):(this.statesLoadError=`No se pudo cargar la lista de estados.`,this.setStates([]),n)}},At=e=>{let t=e[0];return Number(t)===4?`visa`:Number(t)===2||Number(t)===5?`mastercard`:Number(t)===6?`union_pay`:`not_valid`},jt=e=>{let[t,n]=e.split(`/`);return{month:t,year:n}},Mt=e=>e.replace(/\s/g,``),Nt=class e{static instance;get songbirdUrl(){return vt.getInstance().getCurrentEnvironment().songbirdUrl||``}loaded=!1;initialized=!1;constructor(){}static getInstance(){return e.instance||=new e,e.instance}loadSongbird(){return this.loaded?Promise.resolve():new Promise((e,t)=>{let n=document.createElement(`script`);n.src=this.songbirdUrl,n.onload=()=>{this.loaded=!0,e()},n.onerror=()=>t(Error(`Failed to load Songbird script`)),document.head.appendChild(n)})}getBrowserData(){return{browser_java_enabled:!1,browser_language:navigator.language,browser_color_depth:screen.colorDepth,browser_screen_height:screen.height,browser_screen_width:screen.width,browser_time_zone:Intl.DateTimeFormat().resolvedOptions().timeZone||`America/El_Salvador`,user_agent:navigator.userAgent,device_channel:`Browser`,browser_javascript_enabled:!0}}async setupCardinal(e){return await this.loadSongbird(),this.cleanup(),new Promise((t,n)=>{try{Cardinal.configure({timeout:6e3,maxRequestRetries:3,logging:{level:`on`}}),Cardinal.on(`payments.setupComplete`,n=>{Cardinal.off(`payments.setupComplete`),this.submitCollectionForm(e),t(n.sessionId)}),Cardinal.setup(`init`,{jwt:e}),this.initialized=!0}catch(e){n(e)}})}cleanup(){let e=document.querySelector(`iframe[name="cardinalIframe"]`);e&&e.remove();let t=document.getElementById(`collectionForm`);t&&t.remove()}submitCollectionForm(e){this.cleanup();let t=document.createElement(`iframe`);t.name=`cardinalIframe`,t.height=`10`,t.width=`10`,t.style.cssText=`visibility:hidden;position:absolute;top:-1000px;left:-1000px;`,document.body.appendChild(t);let n=document.createElement(`form`);n.id=`collectionForm`,n.name=`devicedata`,n.method=`POST`,n.action=`https://centinelapistag.cardinalcommerce.com/V2/Cruise/Collect`,n.target=`cardinalIframe`;let r=document.createElement(`input`);r.type=`hidden`,r.name=`JWT`,r.value=e,n.appendChild(r),document.body.appendChild(n),n.submit()}onCardinalValidated(){return new Promise(e=>{Cardinal.on(`payments.validated`,t=>{Cardinal.off(`payments.validated`),e(t)})})}continueCardinal(e,t,n){Cardinal.continue(`cca`,{AcsUrl:e.acs_url,Payload:e.payload},{OrderDetails:{TransactionId:e.transaction_id,OrderNumber:e.order_number_client,Amount:t,CurrencyCode:e.currency_code,OrderDescription:n,OrderChannel:e.transaction_mode}})}},Pt=class e{static instance;request=yt.getInstance();cardinalService=Nt.getInstance();registerPaymentResponse=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async registerPayment(e,t){let n={data:{...t,...this.cardinalService.getBrowserData()}},r=await this.request.post(`external/online_payments/orders/${e}/register_payment`,n,{},`api/v2`),i=await r.json();return r.ok&&(this.registerPaymentResponse=i.data),i}async validatePayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/validate_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}async confirmPayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/confirm_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}buildValidatePayloadFromCardinal(e){let t=this.registerPaymentResponse;return{validated:e.Validated,action_code:e.ActionCode,error_number:e.ErrorNumber,error_description:e.ErrorDescription,payment_type:e.Payment.Type,processor_transaction_id:e.Payment.ProcessorTransactionId,cavv:e.Payment.ExtendedData.CAVV,currency_code:e.Payment.ExtendedData.CurrencyCode,eci_flag:e.Payment.ExtendedData.ECIFlag,three_ds_version:e.Payment.ExtendedData.ThreeDSVersion,pares_status:e.Payment.ExtendedData.PAResStatus,signature_verification:e.Payment.ExtendedData.SignatureVerification,cavv_algorithm:t?.cavv_algorithm||void 0,enrolled:t?.enrolled||void 0,ds_transaction_id:t?.ds_transaction_id||void 0}}},Ft=class{request=yt.getInstance();urlEncrypt=`resources/encryption/public_key`;token=null;async getTokenFromServer(){let e=await this.request.get(this.urlEncrypt,{},`api/v2`);if(!e.ok)throw Error(`Failed to get encryption token`);this.token=(await e.json()).data}getToken(){return this.token}encryptData(e){if(!this.token)throw Error(`Encryption token not found`);let t=JSON.stringify({...e,nonce:crypto.randomUUID(),timestamp:Math.floor(Date.now()/1e3)}),n=re.default.random.getBytesSync(32),r=re.default.random.getBytesSync(12),i=re.default.cipher.createCipher(`AES-GCM`,n);i.start({iv:r,additionalData:``,tagLength:128}),i.update(re.default.util.createBuffer(t,`utf8`)),i.finish();let a=re.default.pki.publicKeyFromPem(this.token.public_key).encrypt(n,`RSA-OAEP`);return{encrypted_data:re.default.util.encode64(i.output.getBytes()),encrypted_key:re.default.util.encode64(a),iv:re.default.util.encode64(r),tag:re.default.util.encode64(i.mode.tag.getBytes())}}},It=class e{static instance;cardinalToken=Dt.getInstance();cardinalService=Nt.getInstance();cardinalPayment=Pt.getInstance();countryContent=Ot.getInstance();stateContent=kt.getInstance();orchestrator=Et.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}async process(e,t,n){let r=this.cardinalToken.generateCardinalTokenPayload(e);t&&(r.subtotal_cents=t);let i=await this.cardinalToken.fetchCardinalToken(r);if(`error`in i){n.sendAlert(`Error`,i.error||`Error al procesar el pago`);return}let{id:a,token:o}=i.data,s=await this.cardinalService.setupCardinal(o),c=this.countryContent.getCountries().find(t=>t.id===e.country),l=this.stateContent.getStates().find(t=>t.id===e.region),u=jt(e.cardExpiry),d=new Ft;try{await d.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let f=d.encryptData({card_number:Mt(e.cardNumber),card_expiration_month:u.month,card_expiration_year:`20${u.year}`,cvv:e.cardCvc,expiration_date:`${u.year}${u.month}`,cardholder_name:e.cardHolder}),p={reference:s,billing_address:e.address,billing_city:e.city,billing_country_code:String(c?.number||``),billing_first_name:e.firstName,billing_last_name:e.lastName,billing_postal_code:e.postalCode,billing_state_code:l?.short_code||``,billing_country_name:c?.name||``,email:e.email,phone_number:e.phone.replace(/\s/g,``),order_id:this.orchestrator.getConfig().data.order_id||void 0,...f},m=await this.cardinalPayment.registerPayment(a,p);if(`error`in m){n.sendAlert(`Error`,m.error||`Error al procesar el pago`);return}let h=m.data;if(h.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
23
|
+
`+d),q&&me([O,k,A],e=>{d=Se(d,e,` `)}),b&&oe?b.createHTML(d):d},t.setConfig=function(){gt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),X=!0},t.clearConfig=function(){pt=null,X=!1},t.isValidAttribute=function(e,t,n){return pt||gt({}),Ot(ft(e),ft(t),n)},t.addHook=function(e,t){typeof t==`function`&&_e(D[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=he(D[e],t);return n===-1?void 0:ve(D[e],n,1)[0]}return ge(D[e])},t.removeHooks=function(e){D[e]=[]},t.removeAllHooks=function(){D=rt()},t}var at=it(),ot=`https://devapi.teip.io`,st=`R33xmWassTrJO5I52s6FZ_3sdQRdiOR7Vc0oDSuf7No`,ct=`urn:ietf:wg:oauth:2.0:oob`,lt=`https://cas.static.client.cardinaltrusted.com/songbird/v2.0.0/songbird.js`,ut=void 0,dt=void 0,ft=void 0,pt=void 0,mt=void 0,ht=void 0,gt=void 0,_t=void 0,vt=class e{static instance;environment=`production`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}isDevelopmentEnvironment(){return ct}getEnvironment(){return this.isDevelopmentEnvironment()?`development`:this.environment}getDevelopmentEnvironment(){return{apiBase:ot,externalApiUid:st,songbirdUrl:lt,externalApiRedirectUri:ct}}getProductionEnvironment(){return{apiBase:ut,songbirdUrl:pt,externalApiUid:dt,externalApiRedirectUri:ft}}getSandboxEnvironment(){return{apiBase:mt,songbirdUrl:_t,externalApiUid:ht,externalApiRedirectUri:gt}}setEnvironment(e){e&&(this.environment=e)}getCurrentEnvironment(){switch(this.getEnvironment()){case`production`:return this.getProductionEnvironment();case`sandbox`:return this.getSandboxEnvironment();default:return this.getDevelopmentEnvironment()}}},yt=class e{static instance;get baseUrl(){return vt.getInstance().getCurrentEnvironment().apiBase||``}bearerToken=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}setBearerToken(e){this.bearerToken=e}async get(e,t={},n=`api/v1`){return fetch(`${this.baseUrl}/${n}/${e}`,{...t,method:`GET`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...t.headers}})}async post(e,t,n={},r=`api/v1`){return fetch(`${this.baseUrl}/${r}/${e}`,{body:at.sanitize(JSON.stringify(t)),method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.bearerToken}`,...n.headers},...n})}},bt=e=>btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``),xt=async e=>{let t=new TextEncoder().encode(e);return bt(await crypto.subtle.digest(`SHA-256`,t))},St=class e{static instance;authenticateAuthorize=`oauth/application/authorize`;authenticateToken=`oauth/application/token`;request=yt.getInstance();pkceReady;authToken=null;environment=vt.getInstance();constructor(){this.pkceReady=this.generatePkce()}static getInstance(){return e.instance||=new e,e.instance}getAuthToken(){return this.authToken}async generatePkce(){let e=re.util.bytesToHex(re.random.getBytesSync(32));return{verifier:e,challenge:await xt(e)}}async authorize(e){let{externalApiUid:t,externalApiRedirectUri:n}=this.environment.getCurrentEnvironment(),r={client_id:t,redirect_uri:n,response_type:`code`,code_challenge:e,code_challenge_method:`S256`};return(await this.request.post(this.authenticateAuthorize,r)).json()}async token(e,t){let{externalApiUid:n,externalApiRedirectUri:r}=this.environment.getCurrentEnvironment(),i={client_id:n,code:e,code_verifier:t,redirect_uri:r,grant_type:`authorization_code`};return(await this.request.post(this.authenticateToken,i)).json()}async authenticateAndAuthorize(){let{verifier:e,challenge:t}=await this.pkceReady;try{let n=await this.authorize(t);this.authToken=await this.token(n.redirect_uri.code,e)}catch(e){throw console.error(`Error authenticating or authorizing:`,e),e}}},Ct=class e{request=yt.getInstance();static instance;urlConfig=`external/online_payments/orders/configuration`;config=null;constructor(e,t,n){this.urlConfig=this.setURLcode(e,t,n)}static getInstance({code:t,paymentRequestCode:n,paymentOrderCode:r}){return!e.instance&&t&&(e.instance=new e(t,n,r)),e.instance}static resetInstance(){e.instance=null}getConfig(){return this.config}setURLcode=(e,t,n)=>t?`${this.urlConfig}?code=${t}&scope=order_template`:n?`${this.urlConfig}?code=${n}&scope=order`:`${this.urlConfig}?code=${e}&scope=branch`;async configRequest(){let e=await this.request.get(this.urlConfig),t=await e.json();return e.ok&&(this.config=t),t}},wt={400:`Error al cargar orden de pago: solicitud inválida`,401:`Error al cargar orden de pago: autenticación requerida`,403:`Error al cargar orden de pago: autorización denegada`,404:`Error al cargar orden de pago: recurso no encontrado`,500:`Error al cargar orden de pago: falla interna del servicio`,502:`Error al cargar orden de pago: respuesta inválida del servicio upstream`,503:`Error al cargar orden de pago: servicio no disponible`};function Tt(e,t){return wt[e]||`Error al obtener información de sucursal: ${t}`}var Et=class e{static instance;initPromise=null;auth=St.getInstance();request=yt.getInstance();branchConfig;environment=vt.getInstance();authToken=null;config=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}static resetInstance(){e.instance=null}async initialize({branchCode:e,paymentRequestCode:t,paymentOrderCode:n,environment:r}){return this.initPromise?this.initPromise:(this.environment.setEnvironment(r),this.initPromise=this.boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}),this.initPromise)}async boot({branchCode:e,paymentRequestCode:t,paymentOrderCode:n}){await this.auth.authenticateAndAuthorize(),this.authToken=this.auth.getAuthToken(),this.request.setBearerToken(this.authToken?.access_token??``),this.branchConfig=Ct.getInstance({code:e,paymentRequestCode:t,paymentOrderCode:n});let r=await this.branchConfig.configRequest();if(`error`in r)throw Error(Tt(r.status,e));this.config=this.branchConfig.getConfig()}getAuthToken(){if(!this.authToken)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.authToken}getConfig(){if(!this.config)throw Error(`PaymentOrchestrator not initialized. Call initialize() first.`);return this.config}},Dt=class e{request=yt.getInstance();static instance;cardinalToken=null;urlCardinalToken=`external/online_payments/orders/token`;orchestrator=Et.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCardinalToken(){return this.cardinalToken}setCardinalToken(e){this.cardinalToken=e}generateCardinalTokenPayload(e){let t=this.orchestrator.getConfig();return{order_id:t.data.order_id||void 0,branch_id:t.data.branch_id,subtotal_cents:parseInt(e.amount.replace(`.`,``).replace(`,`,``)),subtotal_currency:`USD`,tip_cents:0,tip_currency:`USD`,description:e.description}}async fetchCardinalToken(e){let t=await this.request.post(this.urlCardinalToken,{data:e}),n=await t.json();return t.ok,n}},Ot=class e{request=yt.getInstance();static instance;countries=[];countriesLoadError=null;urlCountries=`resources/countries`;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getCountries(){return this.countries}setCountries(e){this.countries=e}getCountriesLoadError(){return this.countriesLoadError}async fetchCountries(){let e=await this.request.get(this.urlCountries),t=await e.json();return e.ok?(this.countriesLoadError=null,this.setCountries(t.data),t):(this.countriesLoadError=`No se pudo cargar la lista de países.`,t)}},kt=class e{static instance;states=[];statesLoadError=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}getStates(){return this.states}setStates(e){this.states=e}getStatesLoadError(){return this.statesLoadError}async fetchStates(e){let t=await yt.getInstance().get(`resources/countries/${e}/states`),n=await t.json();return t.ok?(this.statesLoadError=null,this.setStates(n.data),n):(this.statesLoadError=`No se pudo cargar la lista de estados.`,this.setStates([]),n)}},At=e=>{let t=e[0];return Number(t)===4?`visa`:Number(t)===2||Number(t)===5?`mastercard`:Number(t)===6?`union_pay`:`not_valid`},jt=e=>{let[t,n]=e.split(`/`);return{month:t,year:n}},Mt=e=>e.replace(/\s/g,``),Nt=class e{static instance;get songbirdUrl(){return vt.getInstance().getCurrentEnvironment().songbirdUrl||``}loaded=!1;initialized=!1;originalAppendChild=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}loadSongbird(){return this.loaded?Promise.resolve():new Promise((e,t)=>{let n=document.createElement(`script`);n.src=this.songbirdUrl,n.onload=()=>{this.loaded=!0,e()},n.onerror=()=>t(Error(`Failed to load Songbird script`)),document.head.appendChild(n)})}getBrowserData(){return{browser_java_enabled:!1,browser_language:navigator.language,browser_color_depth:screen.colorDepth,browser_screen_height:screen.height,browser_screen_width:screen.width,browser_time_zone:Intl.DateTimeFormat().resolvedOptions().timeZone||`America/El_Salvador`,user_agent:navigator.userAgent,device_channel:`Browser`,browser_javascript_enabled:!0}}async setupCardinal(e){return await this.loadSongbird(),this.cleanup(),new Promise((t,n)=>{try{Cardinal.configure({timeout:6e3,maxRequestRetries:3,logging:{level:`on`}}),Cardinal.on(`payments.setupComplete`,n=>{Cardinal.off(`payments.setupComplete`),this.submitCollectionForm(e),t(n.sessionId)}),Cardinal.setup(`init`,{jwt:e}),this.initialized=!0}catch(e){n(e)}})}isCardinalModalNode(e){return!(e instanceof HTMLElement)||e.tagName&&e.tagName.toLowerCase()===`iframe`&&e.name===`cardinalIframe`||e.id===`collectionForm`||e.id===`Cardinal-collector`?!1:!!(e instanceof HTMLIFrameElement&&e.name===`cardinal-test-frame`||e.id===`Cardinal-ElementContainer`||e.id===`Cardinal-ElementLoader`||e.id===`Cardinal-Modal`||e.id===`Cardinal-Overlay`||e.id===`Cardinal-cca-IFrame`||e.id===`Cardinal-CCA-IFrame`||e.querySelector?.(`#Cardinal-Modal, #Cardinal-Overlay, #Cardinal-cca-IFrame, #Cardinal-CCA-IFrame`))}prepareModalElement(e){e instanceof HTMLIFrameElement&&e.name===`cardinal-test-frame`?(e.setAttribute(`popover`,`manual`),e.style.cssText+=`;position: fixed; z-index: 2147483647; inset: 0; margin: auto; background: #fff;`):(e.setAttribute(`popover`,`manual`),e.style.cssText+=`;border: none !important; background: transparent !important; padding: 0 !important; margin: 0 !important; width: 0 !important; height: 0 !important; max-width: none !important; max-height: none !important; overflow: visible !important; inset: 0 !important;`);let t=e.querySelector(`#Cardinal-Modal, .cardinalOverlay-content`);t&&t.style.setProperty(`z-index`,`2147483647`,`important`);let n=e.querySelector(`#Cardinal-Overlay, .cardinalOverlay-mask`);n&&n.style.setProperty(`z-index`,`2147483646`,`important`)}promoteToTopLayer(e){try{typeof e.showPopover==`function`&&e.showPopover()}catch{}let t=e.querySelector(`#Cardinal-Modal, .cardinalOverlay-content`);t&&t.style.setProperty(`z-index`,`2147483647`,`important`);let n=e.querySelector(`#Cardinal-Overlay, .cardinalOverlay-mask`);n&&n.style.setProperty(`z-index`,`2147483646`,`important`)}installDomInterceptor(){this.originalAppendChild||(this.originalAppendChild=document.body.appendChild,document.body.appendChild=e=>{if(this.isCardinalModalNode(e)&&e instanceof HTMLElement){this.prepareModalElement(e);let t=document.querySelectorAll(`dialog[open]`),n=t.length>0?t[t.length-1]:null,r=n?n.appendChild(e):this.originalAppendChild.call(document.body,e);return this.promoteToTopLayer(e),r}return this.originalAppendChild.call(document.body,e)})}restoreDomInterceptor(){this.originalAppendChild&&=(document.body.appendChild=this.originalAppendChild,null)}cleanup(){let e=document.querySelector(`iframe[name="cardinalIframe"]`);e&&e.remove();let t=document.getElementById(`collectionForm`);t&&t.remove(),document.querySelectorAll(`#Cardinal-ElementContainer, #Cardinal-ElementLoader, iframe[name="cardinal-test-frame"]`).forEach(e=>{if(e instanceof HTMLElement)try{e.hidePopover?.()}catch{}e.remove()}),this.restoreDomInterceptor()}submitCollectionForm(e){this.cleanup();let t=document.createElement(`iframe`);t.name=`cardinalIframe`,t.height=`10`,t.width=`10`,t.style.cssText=`visibility:hidden;position:absolute;top:-1000px;left:-1000px;`,document.body.appendChild(t);let n=document.createElement(`form`);n.id=`collectionForm`,n.name=`devicedata`,n.method=`POST`,n.action=`https://centinelapistag.cardinalcommerce.com/V2/Cruise/Collect`,n.target=`cardinalIframe`;let r=document.createElement(`input`);r.type=`hidden`,r.name=`JWT`,r.value=e,n.appendChild(r),document.body.appendChild(n),n.submit()}onCardinalValidated(){return new Promise(e=>{Cardinal.on(`payments.validated`,t=>{Cardinal.off(`payments.validated`),this.cleanup(),e(t)})})}continueCardinal(e,t,n){this.installDomInterceptor(),Cardinal.continue(`cca`,{AcsUrl:e.acs_url,Payload:e.payload},{OrderDetails:{TransactionId:e.transaction_id,OrderNumber:e.order_number_client,Amount:t,CurrencyCode:e.currency_code,OrderDescription:n,OrderChannel:e.transaction_mode}})}},Pt=class e{static instance;request=yt.getInstance();cardinalService=Nt.getInstance();registerPaymentResponse=null;constructor(){}static getInstance(){return e.instance||=new e,e.instance}async registerPayment(e,t){let n={data:{...t,...this.cardinalService.getBrowserData()}},r=await this.request.post(`external/online_payments/orders/${e}/register_payment`,n,{},`api/v2`),i=await r.json();return r.ok&&(this.registerPaymentResponse=i.data),i}async validatePayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/validate_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}async confirmPayment(e,t){let n=await this.request.post(`external/online_payments/orders/${e}/confirm_payment`,{data:t},{},`api/v2`),r=await n.json();return n.ok,r}buildValidatePayloadFromCardinal(e){let t=this.registerPaymentResponse;return{validated:e.Validated,action_code:e.ActionCode,error_number:e.ErrorNumber,error_description:e.ErrorDescription,payment_type:e.Payment.Type,processor_transaction_id:e.Payment.ProcessorTransactionId,cavv:e.Payment.ExtendedData.CAVV,currency_code:e.Payment.ExtendedData.CurrencyCode,eci_flag:e.Payment.ExtendedData.ECIFlag,three_ds_version:e.Payment.ExtendedData.ThreeDSVersion,pares_status:e.Payment.ExtendedData.PAResStatus,signature_verification:e.Payment.ExtendedData.SignatureVerification,cavv_algorithm:t?.cavv_algorithm||void 0,enrolled:t?.enrolled||void 0,ds_transaction_id:t?.ds_transaction_id||void 0}}},Ft=class{request=yt.getInstance();urlEncrypt=`resources/encryption/public_key`;token=null;async getTokenFromServer(){let e=await this.request.get(this.urlEncrypt,{},`api/v2`);if(!e.ok)throw Error(`Failed to get encryption token`);this.token=(await e.json()).data}getToken(){return this.token}encryptData(e){if(!this.token)throw Error(`Encryption token not found`);let t=JSON.stringify({...e,nonce:crypto.randomUUID(),timestamp:Math.floor(Date.now()/1e3)}),n=re.default.random.getBytesSync(32),r=re.default.random.getBytesSync(12),i=re.default.cipher.createCipher(`AES-GCM`,n);i.start({iv:r,additionalData:``,tagLength:128}),i.update(re.default.util.createBuffer(t,`utf8`)),i.finish();let a=re.default.pki.publicKeyFromPem(this.token.public_key).encrypt(n,`RSA-OAEP`);return{encrypted_data:re.default.util.encode64(i.output.getBytes()),encrypted_key:re.default.util.encode64(a),iv:re.default.util.encode64(r),tag:re.default.util.encode64(i.mode.tag.getBytes())}}},It=class e{static instance;cardinalToken=Dt.getInstance();cardinalService=Nt.getInstance();cardinalPayment=Pt.getInstance();countryContent=Ot.getInstance();stateContent=kt.getInstance();orchestrator=Et.getInstance();constructor(){}static getInstance(){return e.instance||=new e,e.instance}async process(e,t,n){let r=this.cardinalToken.generateCardinalTokenPayload(e);t&&(r.subtotal_cents=t);let i=await this.cardinalToken.fetchCardinalToken(r);if(`error`in i){n.sendAlert(`Error`,i.error||`Error al procesar el pago`);return}let{id:a,token:o}=i.data,s=await this.cardinalService.setupCardinal(o),c=this.countryContent.getCountries().find(t=>t.id===e.country),l=this.stateContent.getStates().find(t=>t.id===e.region),u=jt(e.cardExpiry),d=new Ft;try{await d.getTokenFromServer()}catch(e){throw Error(`Failed to get encryption token: `+e)}let f=d.encryptData({card_number:Mt(e.cardNumber),card_expiration_month:u.month,card_expiration_year:`20${u.year}`,cvv:e.cardCvc,expiration_date:`${u.year}${u.month}`,cardholder_name:e.cardHolder}),p={reference:s,billing_address:e.address,billing_city:e.city,billing_country_code:String(c?.number||``),billing_first_name:e.firstName,billing_last_name:e.lastName,billing_postal_code:e.postalCode,billing_state_code:l?.short_code||``,billing_country_name:c?.name||``,email:e.email,phone_number:e.phone.replace(/\s/g,``),order_id:this.orchestrator.getConfig().data.order_id||void 0,...f},m=await this.cardinalPayment.registerPayment(a,p);if(`error`in m){n.sendAlert(`Error`,m.error||`Error al procesar el pago`);return}let h=m.data;if(h.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
24
24
|
Por favor revisa tu información e inténtalo de nuevo`);return}if(h.required_authentication&&h.acs_url!==``){this.cardinalService.continueCardinal(h,String(r.subtotal_cents),e.description);let t=await this.cardinalService.onCardinalValidated();if(t.ActionCode!==`SUCCESS`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
25
25
|
Por favor revisa tu información e inténtalo de nuevo`);return}let i=this.cardinalPayment.buildValidatePayloadFromCardinal(t),o=await this.cardinalPayment.validatePayment(a,{...i,...f});if(`error`in o){n.sendAlert(`Error`,o.error||`Error al procesar el pago`);return}if(o.data.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
26
26
|
Por favor revisa tu información e inténtalo de nuevo`);return}}else{let e=await this.cardinalPayment.validatePayment(a,{...f});if(`error`in e){n.sendAlert(`Error`,e.error||`Error al procesar el pago`);return}if(e.data.status!==`success`){n.sendAlert(`Error al pagar`,`Tu compra no pudo ser procesada.
|
|
@@ -195,7 +195,7 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Qt=[{label:`Docu
|
|
|
195
195
|
${u}
|
|
196
196
|
${i?`\n <template class="operation-form-template" data-operation="crypto">${i}</template>`:``}
|
|
197
197
|
</div>
|
|
198
|
-
`}function Sn(e){let t=`<img src="${gn}" alt="Bizz Logo" class="bizz-logo">`,n=e.customBodyHtml??xn(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return mn.replace(`<!--STYLES-->`,`<style>${_n}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--VERSION-->`,`<div class="bizz-sdk-version">v1.5.
|
|
198
|
+
`}function Sn(e){let t=`<img src="${gn}" alt="Bizz Logo" class="bizz-logo">`,n=e.customBodyHtml??xn(e.cardFormHtml||``,e.submitButtonHtml,e.pointsFormHtml||``,e.installmentFormHtml||``,e.cryptoFormHtml||``);return mn.replace(`<!--STYLES-->`,`<style>${_n}</style>`).replace(`<!--BIZZ_LOGO-->`,t).replace(`<!--HEADER-->`,e.headerHtml).replace(`<!--OPERATION_SELECTION-->`,n).replace(`<!--VERSION-->`,`<div class="bizz-sdk-version">v1.5.7</div>`).replace(`<!--SCRIPT-->`,`<script>${hn}<\/script>`)}function Cn(e){let t=document.createElement(`iframe`);return t.style.border=`none`,t.style.display=`block`,t.style.overflow=`hidden`,t.srcdoc=e,t.style.width=`100%`,t.style.height=`100%`,t}var wn=class e{static instance;request;constructor(){this.request=yt.getInstance()}static getInstance(){return e.instance||=new e,e.instance}async createCharge(e){let t=await this.request.post(`external/online_payments/orders/crypto/charge`,e);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge creation failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}async getChargeStatus(e){let t=await this.request.get(`external/online_payments/orders/crypto/charge/${e}/status`);if(!t.ok){let e=typeof t.json==`function`?await t.json().catch(()=>null):null,n=e?.error||e?.message||(typeof e==`object`&&e?JSON.stringify(e):null)||`Charge status failed with status ${t.status}`,r=Error(n);throw r.status=t.status,r.data=e,r}return await t.json()}},Tn=3e3,En=`NAKA_CRYPTO`,Dn=`CRYPTO`,$={UNDERPAID:{title:`Pago incompleto`,message:`El monto pagado en criptomonedas fue inferior al total requerido. El cobro ha finalizado y tu reembolso ha sido gestionado a través de la pasarela.`,retryLabel:`Intentar nuevamente`},OVERPAID:{finishLabel:`Finalizar compra (Pago recibido)`},CANCELED:{title:`¡Pago cancelado!`,message:`El pago con criptomonedas fue cancelado.`},EXPIRED:{title:`¡Cobro expirado!`,message:`El tiempo para completar el pago con criptomonedas ha finalizado.`},FAILED:{title:`¡Pago fallido!`,message:`No se pudo procesar el pago con criptomonedas.`},TIMEOUT:{title:`¡Tiempo de espera agotado!`,message:`El tiempo para completar el pago con criptomonedas ha expirado.`},CONNECTION_ERROR:{title:`¡Error de conexión!`,message:`No fue posible verificar el estado del pago con criptomonedas.`},SESSION_EXPIRED:{title:`¡Sesión expirada!`,message:`Tu sesión ha expirado. Por favor, intenta de nuevo.`},ORDER_NOT_FOUND:{title:`¡Orden no encontrada!`,message:`El cobro no se encuentra disponible o fue cancelado.`},PAYMENT_UNAVAILABLE:{title:`¡Pago no disponible!`,defaultMessage:`No fue posible procesar el cobro con criptomonedas. Por favor, intenta con otro método.`},CREATE_CHARGE_ERROR:{title:`¡Error al crear cobro con Criptomonedas!`,message:`No se pudo conectar con el servicio de pagos en criptomonedas.`}},On=`<svg
|
|
199
199
|
xmlns="http://www.w3.org/2000/svg"
|
|
200
200
|
width="24"
|
|
201
201
|
height="24"
|
|
@@ -262,7 +262,7 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Qt=[{label:`Docu
|
|
|
262
262
|
<path d="M12 3a12 12 0 0 0 8.5 3a12 12 0 0 1 -8.5 15a12 12 0 0 1 -8.5 -15a12 12 0 0 0 8.5 -3" />
|
|
263
263
|
<path d="M11 11a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" />
|
|
264
264
|
<path d="M12 12l0 2.5" />
|
|
265
|
-
</svg>`,Mn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,Nn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,Pn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,Fn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,In=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,Ln=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,Rn={"currency-dollar":On,"credit-card":kn,calendar:An,"shield-lock":jn,email:Mn,user:Nn,description:Pn,document:Fn,phone:In,"map-pin":Ln};function zn(e){let t=Rn[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var Bn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?At(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Vn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:zn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?Ht(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}});return e.BizzPaymentForm=class{static version=`1.5.6`;config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=Bn.getInstance();origin=d;serverErrorHandler;orchestrator=Et.getInstance();paymentIntent=Jt.getInstance();points=Yt.getInstance();countryContent=Ot.getInstance();processPayment=It.getInstance();stateContent=kt.getInstance();amountEvaluation=Wt.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;pendingAlert=null;currentCryptoChargeId=null;isCryptoOverpaid=!1;lastCryptoOverpaidSuccess=null;constructor(e){if(this.config={...e},!this.config.paymentOrderCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`o`);e&&(this.config.paymentOrderCode=e)}if(!this.config.paymentRequestCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`t`);e&&(this.config.paymentRequestCode=e)}this.currentAmount=this.config.totalAmount,this.serverErrorHandler=new qt(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=Bt(this.config.i18n?.loading);e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}t.remove(),this.setupMessageHandler();let n=this.orchestrator.getConfig()?.data?.status;if(n===`completed`){await this.renderCompletedOrderView();return}if(n===`cancelled`){await this.renderCancelledOrderView();return}if(this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}setupMessageHandler(){this.messageHandler&&window.removeEventListener(`message`,this.messageHandler),this.messageHandler=async e=>{if(e.source&&e.source!==this.iframe?.contentWindow&&e.source!==window)return;let t=e.data;if(t?.type){if(t.type===`payment-form:ready`&&(this.pendingAlert&&=(this.sendAlert(this.pendingAlert.title,this.pendingAlert.message),null)),t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=Ut(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=Ut(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=Zt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...rn,country:{...rn.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=pn(Vn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}if(t.type===`payment-form:naka-callback`){this.stopNakaPolling();let e=t.chargeId||this.currentCryptoChargeId,n=wn.getInstance(),r=t.status,i=null;if(e)try{let t=await n.getChargeStatus(e);t?.data&&(i=t.data,r=i.status)}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}if(r===`UNDERPAID`){this.stopNakaPolling(),this.postMessageToIframe({type:`payment-form:crypto-incomplete`,title:$.UNDERPAID.title,message:$.UNDERPAID.message,retryLabel:$.UNDERPAID.retryLabel}),this.sendFailureEmitter(422,$.UNDERPAID.message);return}if(r===`CANCELED`||r===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(r===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(r===`FAILED`||r===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(r===`SUCCESS`||r===`COMPLETED`||r===`PAID`||r===`OVERPAID`){let n=this.orchestrator.getConfig()?.data?.amount_currency||`USD`,r={data:{id:e||``,status:`success`,amount_cents:this.config.totalAmount??this.currentAmount??i?.amount_cents??0,amount_currency:n,response_code:`00`,authorization_number:i?.authorization_number||i?.transaction_id||t.chargeId||`NAKA-${Date.now()}`,reference_number:i?.reference_number||i?.order_number||t.orderNumber||e||``,billing_document_number:``,description:this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:En,card_last_digits:Dn,invoice_serie:null}};this.sendSuccess(r);return}}if(t.type===`payment-form:return-initial`){if(this.stopNakaPolling(),this.isCryptoOverpaid&&this.lastCryptoOverpaidSuccess){this.sendSuccess(this.lastCryptoOverpaidSuccess);return}this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}if(t.type===`payment-form:crypto-retry`){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}}},window.addEventListener(`message`,this.messageHandler)}applyFixedAmountFromOrderTemplate(){let e=this.orchestrator.getConfig();if(!e?.data)return;let{data:t}=e;if(t.order_template_id==null&&t.order_id==null||typeof t.amount_cents!=`number`||t.amount_cents<=0)return;let n=Ht(t.amount_cents/100,t.amount_currency||`USD`,`decimal`);this.config.description=t.description,this.config.totalAmount=Ut(n),this.currentAmount=Ut(n)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...nn,country:{...nn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:tn,u=tn,d=!!this.config.totalAmount,f=Vn(t,l,this.currentAmount,d),p=n?Vn(t,u,this.currentAmount,d):f,m=Vn(t,{...rn,country:{...rn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=an(this.config.i18n?.submitButton),g=i?un(f):``,_=a?dn(p):``,v=o?fn(p,h):``,y=s?pn(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?Ht(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=Cn(Sn({headerHtml:on({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:zn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}async renderCompletedOrderView(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=this.orchestrator.getConfig().data,n=`
|
|
265
|
+
</svg>`,Mn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-mail"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /><path d="M3 7l9 6l9 -6" /></svg>`,Nn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0" /><path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /></svg>`,Pn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-message-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1" /></svg>`,Fn=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-id"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M3 7a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v10a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3l0 -10" /><path d="M7 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M15 8l2 0" /><path d="M15 12l2 0" /><path d="M7 16l10 0" /></svg>`,In=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-device-mobile"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M6 5a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-14" /><path d="M11 4h2" /><path d="M12 17v.01" /></svg>`,Ln=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0" /></svg>`,Rn={"currency-dollar":On,"credit-card":kn,calendar:An,"shield-lock":jn,email:Mn,user:Nn,description:Pn,document:Fn,phone:In,"map-pin":Ln};function zn(e){let t=Rn[e];if(!t)throw Error(`Icon "${e}" not found`);return t}var Bn=class e{static instance;currentDate=new Date;currentYear=this.currentDate.getFullYear();currentMonth=this.currentDate.getMonth()+1;static getInstance(){return e.instance||=new e,e.instance}validateField(e,t){return this.inputRequired(t)||({amount:e=>this.amountInput(e),cardNumber:e=>this.cardNumberInput(e),cardExpiry:e=>this.cardExpiryInput(e),cardCvc:e=>this.cardCvcInput(e),email:e=>this.emailInput(e)}[e]?.(t)??``)}inputRequired(e){return e.trim()===``?`Este campo es requerido`:``}amountInput(e){return Number(e)<=0?`El monto debe ser mayor a 0`:``}cardNumberInput(e){let t=e.replace(/\s/g,``);return/^[0-9]{16}$/.test(t)?At(t)===`not_valid`?`Por favor ingrese una tarjeta visa, mastercard o union_pay`:``:`Por favor, ingrese un número de tarjeta válido`}cardExpiryInput(e){let[t,n]=e.split(`/`),r=Number(this.currentYear.toString().slice(-2));return Number(n)<r?`El año de expiración no puede ser anterior al año actual`:Number(t)<1||Number(t)>12?`El mes de expiración debe estar entre 01 y 12`:Number(n)===r&&Number(t)<this.currentMonth?`La tarjeta está expirada`:``}emailInput(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?``:`Por favor, ingrese un email válido`}cardCvcInput(e){return/^[0-9]{3,4}$/.test(e)?``:`Por favor, ingrese un código de seguridad válido`}},Vn=(e,t,n,r)=>Object.keys(t).map(i=>{let a=t[i],o=e.get(i);return{name:i,label:o?.label??a.label,placeholder:o?.placeholder??a.placeholder??a.label,iconSvg:zn(a.icon),mask:a.mask,divider:a.divider,type:a.type??`text`,options:a.type===`select`?a.options:void 0,default:a.default,amountValue:n?Ht(n/100,`USD`,`decimal`):void 0,disabled:i===`amount`?r:!1,autocomplete:a.autocomplete}});return e.BizzPaymentForm=class{static version=`1.5.7`;config;iframe=null;messageHandler=null;successListeners=new Set;failureListeners=new Set;readyListeners=new Set;sizingListeners=new Set;validation=Bn.getInstance();origin=d;serverErrorHandler;orchestrator=Et.getInstance();paymentIntent=Jt.getInstance();points=Yt.getInstance();countryContent=Ot.getInstance();processPayment=It.getInstance();stateContent=kt.getInstance();amountEvaluation=Wt.getInstance();currentAmount;currentValues={};pointsPaymentContext=null;nakaPollingInterval=null;pendingAlert=null;currentCryptoChargeId=null;isCryptoOverpaid=!1;lastCryptoOverpaidSuccess=null;constructor(e){if(this.config={...e},!this.config.paymentOrderCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`o`);e&&(this.config.paymentOrderCode=e)}if(!this.config.paymentRequestCode&&typeof window<`u`&&window.location?.search){let e=new URLSearchParams(window.location.search).get(`t`);e&&(this.config.paymentRequestCode=e)}this.currentAmount=this.config.totalAmount,this.serverErrorHandler=new qt(this.origin)}on(e,t){e===`success`?this.successListeners.add(t):e===`failure`?this.failureListeners.add(t):e===`ready`?this.readyListeners.add(t):e===`sizing`&&this.sizingListeners.add(t)}async setup(){let e=document.querySelector(this.config.iframeTarget);if(!e)throw Error(`Element not found: ${this.config.iframeTarget}`);let t=Bt(this.config.i18n?.loading);e.appendChild(t);try{await this.orchestrator.initialize({branchCode:this.config.branchCode,paymentRequestCode:this.config.paymentRequestCode,paymentOrderCode:this.config.paymentOrderCode,environment:this.config.environment})}catch(n){t.remove();let r=document.createElement(`div`);r.style.cssText=`font-family:Poppins,sans-serif;text-align:center;padding:32px;color:#DB3339;font-size:14px;`,r.textContent=n instanceof Error?n.message:`Pago no procesado`,e.appendChild(r);return}t.remove(),this.setupMessageHandler();let n=this.orchestrator.getConfig()?.data?.status;if(n===`completed`){await this.renderCompletedOrderView();return}if(n===`cancelled`){await this.renderCancelledOrderView();return}if(this.applyFixedAmountFromOrderTemplate(),await this.renderForm(),this.config.totalAmount&&Number(this.config.totalAmount)>0)try{this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(this.config.totalAmount.toString());if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}catch{this.setSubmitLoading(!1),this.sendAlert(`¡Error al validar el monto!`,`Asegúrate de que el monto a pagar sea válido`)}}setupMessageHandler(){this.messageHandler&&window.removeEventListener(`message`,this.messageHandler),this.messageHandler=async e=>{if(e.source&&e.source!==this.iframe?.contentWindow&&e.source!==window)return;let t=e.data;if(t?.type){if(t.type===`payment-form:ready`&&(this.pendingAlert&&=(this.sendAlert(this.pendingAlert.title,this.pendingAlert.message),null)),t.type===`payment-form:states-loaded`&&this.stateContent.setStates(t.states),t.type===`payment-form:sizing`&&(this.iframe&&(this.iframe.style.height=`${t.height}px`),this.sendSizingEmitter(t.width,t.height)),t.type===`payment-form:validate-amount`){this.currentAmount=Ut(t.amount),this.setSubmitLoading(!0);let e=await this.amountEvaluation.validateAmount(t.amount,t.force);if(this.setSubmitLoading(!1),e&&`data`in e){let t=this.orchestrator.getConfig();t.data.secure_mode!==e.data.secure_mode&&(t.data.secure_mode=e.data.secure_mode,await this.renderForm())}}if(t.type===`payment-form:validate`){this.currentValues[t.field]=t.value;let e=this.validation.validateField(t.field,t.value);this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:t.field,error:e},this.origin)}if(t.type===`payment-form:submit`){t.value.amount&&(this.currentAmount=Ut(t.value.amount));let e=!1,n=Object.keys(t.value);for(let r of n){let n=this.validation.validateField(r,t.value[r]??``);n&&(e=!0,this.iframe?.contentWindow?.postMessage({type:`payment-form:validation-result`,field:r,error:n},this.origin))}if(!e){if(this.setSubmitLoading(!0),t.value.operation===`crypto`){await this.handleCryptoPayment(t.value);return}if(t.value.operation===`points`){await this.handlePointsBalance(t.value),this.setSubmitLoading(!1);return}if(this.orchestrator.getConfig().data.secure_mode){try{await this.processPayment.process(t.value,this.config.totalAmount,{sendAlert:(e,t)=>this.sendAlert(e,t),sendSuccess:e=>this.sendSuccess(e),resetForm:()=>this.resetForm()})}catch{let e=`No pudimos obtener información de encriptación`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(0,e)}finally{this.setSubmitLoading(!1)}return}let e=await this.paymentIntent.generatePaymentIntentPayload(t.value).catch(e=>{this.setSubmitLoading(!1),this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`)});if(!e)return;this.config.totalAmount&&(e.subtotal_cents=this.config.totalAmount),t.value.operation===`installments`&&(e.months=t.value.installments);let n=await this.paymentIntent.createPaymentIntent(e);if(this.setSubmitLoading(!1),`error`in n&&`code`in n){if(n.status===422&&this.serverErrorHandler.hasEncryptionPayloadErrors(n.error)){let e=`Error al encriptar tus datos.`;this.sendAlert(`¡Error al encriptar tus datos!`,e),this.sendFailureEmitter(n.status,e);return}if(n.status===422&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,n.error)){this.sendFailureEmitter(n.status,`Por favor, revisa los campos`);return}n.code===`inactive_company_commerce`?this.sendAlert(`¡Comercio inactivo!`,`Tu compra no pudo ser procesada! El comercio no está disponible por el momento`):n.code===`payment_limit_exceeded`?this.sendAlert(`¡Límite de pago excedido!`,`Por favor, contacta al comercio.`):n.status===422?this.sendAlert(`¡Revisa la información!`,`Por favor, revisa los campos`):this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(n.status,this.serverErrorHandler.resolveServerErrorMessage(n.error));return}if(n.data.status!==`success`){let e=Zt(n.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message);return}if(n.data.status===`success`){this.sendSuccess(n),this.resetForm();return}}}if(t.type===`payment-form:points-pay`&&await this.processPointsPayment(),t.type===`payment-form:load-crypto-countries`){this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let e=this.countryContent.getCountries(),t={...rn,country:{...rn.country,options:[{label:`Selecciona aquí`,value:``},...e.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},n=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),r=!!this.config.totalAmount,i=pn(Vn(n,t,this.currentAmount,r));this.iframe?.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{crypto:i}},this.origin)}if(t.type===`payment-form:naka-callback`){this.stopNakaPolling();let e=t.chargeId||this.currentCryptoChargeId,n=wn.getInstance(),r=t.status,i=null;if(e)try{let t=await n.getChargeStatus(e);t?.data&&(i=t.data,r=i.status)}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}if(r===`UNDERPAID`){this.stopNakaPolling(),this.postMessageToIframe({type:`payment-form:crypto-incomplete`,title:$.UNDERPAID.title,message:$.UNDERPAID.message,retryLabel:$.UNDERPAID.retryLabel}),this.sendFailureEmitter(422,$.UNDERPAID.message);return}if(r===`CANCELED`||r===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(r===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(r===`FAILED`||r===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(r===`SUCCESS`||r===`COMPLETED`||r===`PAID`||r===`OVERPAID`){let n=this.orchestrator.getConfig()?.data?.amount_currency||`USD`,r={data:{id:e||``,status:`success`,amount_cents:this.config.totalAmount??this.currentAmount??i?.amount_cents??0,amount_currency:n,response_code:`00`,authorization_number:i?.authorization_number||i?.transaction_id||t.chargeId||`NAKA-${Date.now()}`,reference_number:i?.reference_number||i?.order_number||t.orderNumber||e||``,billing_document_number:``,description:this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:En,card_last_digits:Dn,invoice_serie:null}};this.sendSuccess(r);return}}if(t.type===`payment-form:return-initial`){if(this.stopNakaPolling(),this.isCryptoOverpaid&&this.lastCryptoOverpaidSuccess){this.sendSuccess(this.lastCryptoOverpaidSuccess);return}this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}if(t.type===`payment-form:crypto-retry`){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),await this.renderForm();return}}},window.addEventListener(`message`,this.messageHandler)}applyFixedAmountFromOrderTemplate(){let e=this.orchestrator.getConfig();if(!e?.data)return;let{data:t}=e;if(t.order_template_id==null&&t.order_id==null||typeof t.amount_cents!=`number`||t.amount_cents<=0)return;let n=Ht(t.amount_cents/100,t.amount_currency||`USD`,`decimal`);this.config.description=t.description,this.config.totalAmount=Ut(n),this.currentAmount=Ut(n)}async renderForm(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=new Map((this.config.i18n?.fields??[]).map(e=>[e.name,e])),n=this.orchestrator.getConfig().data.secure_mode,r=this.orchestrator.getConfig().data.payment_methods,i=r.includes(`emv`),a=r.includes(`ba_puntos`),o=r.includes(`ba_plazos`),s=r.includes(`crypto`);n&&this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let c=this.countryContent.getCountries(),l=n?{...nn,country:{...nn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.id}))]}}:tn,u=tn,d=!!this.config.totalAmount,f=Vn(t,l,this.currentAmount,d),p=n?Vn(t,u,this.currentAmount,d):f,m=Vn(t,{...rn,country:{...rn.country,options:[{label:`Selecciona aquí`,value:``},...c.map(e=>({label:e.name,value:e.alpha2||e.id}))]}},this.currentAmount,d);[f,p,m].forEach(e=>{e.forEach(e=>{this.currentValues[e.name]!==void 0&&e.name!==`amount`&&(e.default=this.currentValues[e.name])})});let h=an(this.config.i18n?.submitButton),g=i?un(f):``,_=a?dn(p):``,v=o?fn(p,h):``,y=s?pn(m):``;if(this.iframe){this.iframe.contentWindow?.postMessage({type:`payment-form:update-forms`,forms:{default:g+h,points:_,installments:v,crypto:y}},this.origin),this.notifyCountriesLoadError();return}let b=this.config.totalAmount?Ht(this.config.totalAmount/100,`USD`,`decimal`):``;this.iframe=Cn(Sn({headerHtml:on({logo:this.orchestrator.getConfig().data.logo_url,name:this.orchestrator.getConfig().data.name,description:this.config.description,header:this.config.header,totalAmount:b,...b?{icon:zn(`currency-dollar`)}:{}}),cardFormHtml:g,submitButtonHtml:h,pointsFormHtml:_,installmentFormHtml:v,cryptoFormHtml:y})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.setToken(this.orchestrator.getAuthToken().access_token),this.notifyCountriesLoadError(),this.sendReadyEmitter()})}async renderCompletedOrderView(){let e=document.querySelector(this.config.iframeTarget);if(!e)return;let t=this.orchestrator.getConfig().data,n=`
|
|
266
266
|
<div class="payment-success">
|
|
267
267
|
<p class="payment-success__amount">${Ht(t.amount_cents/100,t.amount_currency||`USD`)}</p>
|
|
268
268
|
<div class="payment-success__blocks">
|
|
@@ -289,4 +289,4 @@ Por favor revisa tu información e inténtalo de nuevo`,code:0},Qt=[{label:`Docu
|
|
|
289
289
|
<h3>Orden cancelada</h3>
|
|
290
290
|
<p>Esta orden de pago ha sido cancelada o no está disponible para pago.</p>
|
|
291
291
|
</div>
|
|
292
|
-
`})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}postMessageToIframe(e){try{this.iframe?.contentWindow?.postMessage(e,this.origin)}catch{try{this.iframe?.contentWindow?.postMessage(e,`*`)}catch{}}}resetForm(){this.postMessageToIframe({type:`payment-form:reset`})}setSubmitLoading(e){this.postMessageToIframe({type:`payment-form:set-submit-loading`,disabled:e})}setToken(e){this.postMessageToIframe({type:`payment-form:set-token`,token:e})}sendAlert(e,t){this.postMessageToIframe({type:`payment-form:alert`,title:e,message:t})}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=Zt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??Ut(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.postMessageToIframe({type:`payment-form:success`,paymentIntent:e});let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=wn.getInstance(),n=this.config.totalAmount??this.currentAmount??Ut(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():void 0),a={data:{branch_id:this.orchestrator.getConfig()?.data?.branch_id||this.config.branchCode,amount_cents:n,currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,description:e.description||this.config.description||`Pago con Criptomonedas`,billing_document_number:e.billingDocumentNumber||``,redirect_url:this.config.redirectUrl||(typeof window<`u`?`${window.location.origin}/paylink/crypto/callback`:void 0),kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,country:i||``,phone:e.phone||void 0,phone_number:e.phone||void 0,nationality:e.nationality?.toUpperCase()||i||void 0,city:e.city||void 0,postal_code:e.postalCode||void 0,zip_code:e.postalCode||e.zipCode||void 0,address:e.address||void 0}}};try{let r=await t.createCharge(a);this.currentCryptoChargeId=r.data.charge_id,this.setSubmitLoading(!1),this.postMessageToIframe({type:`payment-form:naka-checkout`,redirectUrl:r.data.redirect_url,chargeId:r.data.charge_id}),this.startNakaPolling(r.data.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert($.CREATE_CHARGE_ERROR.title,$.CREATE_CHARGE_ERROR.message),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en servicio de criptomonedas`)}}async handleNakaTerminalFailure(e,t,n){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),this.pendingAlert={title:e,message:t},await this.renderForm(),this.sendFailureEmitter(n,t)}startNakaPolling(e,t,n){this.stopNakaPolling();let r=wn.getInstance(),i=0,a=Date.now();this.nakaPollingInterval=setInterval(async()=>{try{if(Date.now()-a>=18e5){await this.handleNakaTerminalFailure($.TIMEOUT.title,$.TIMEOUT.message,408);return}let o=await r.getChargeStatus(e);i=0;let s=o.data,c=s?.status;if(c===`SUCCESS`||c===`COMPLETED`||c===`PAID`){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:En,card_last_digits:Dn,invoice_serie:null}};this.sendSuccess(r);return}if(c===`CANCELED`||c===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(c===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(c===`FAILED`||c===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(c===`OVERPAID`){this.isCryptoOverpaid=!0,this.lastCryptoOverpaidSuccess={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:En,card_last_digits:Dn,invoice_serie:null}},this.postMessageToIframe({type:`payment-form:crypto-overpaid`,label:$.OVERPAID.finishLabel});return}if(c===`PENDING`||c===`IN_PROGRESS`||c===`OPEN`||c===`UNDERPAID`)return}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}if(e?.status===401||e?.status===403){await this.handleNakaTerminalFailure($.SESSION_EXPIRED.title,$.SESSION_EXPIRED.message,e.status);return}if(i++,i>=5){await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}}},Tn)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.pendingAlert=null,this.currentCryptoChargeId=null,this.isCryptoOverpaid=!1,this.lastCryptoOverpaidSuccess=null,this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}},e.VERSION=`1.5.
|
|
292
|
+
`})),e.appendChild(this.iframe),this.iframe.addEventListener(`load`,()=>{this.sendReadyEmitter()})}notifyCountriesLoadError(){let e=this.countryContent.getCountriesLoadError();e&&this.serverErrorHandler.sendServerValidationErrors(this.iframe?.contentWindow,{country:[e]})}postMessageToIframe(e){try{this.iframe?.contentWindow?.postMessage(e,this.origin)}catch{try{this.iframe?.contentWindow?.postMessage(e,`*`)}catch{}}}resetForm(){this.postMessageToIframe({type:`payment-form:reset`})}setSubmitLoading(e){this.postMessageToIframe({type:`payment-form:set-submit-loading`,disabled:e})}setToken(e){this.postMessageToIframe({type:`payment-form:set-token`,token:e})}sendAlert(e,t){this.postMessageToIframe({type:`payment-form:alert`,title:e,message:t})}sendFailureEmitter(e,t){for(let n of this.failureListeners)n({status:e,message:t})}async processPointsPayment(){if(!this.pointsPaymentContext)return;let{value:e,points:t}=this.pointsPaymentContext,n;try{n=await this.paymentIntent.generatePaymentIntentPayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.resetPointsPayButton();return}n.operation=`points`,n.points=t.toString(),this.config.totalAmount&&(n.subtotal_cents=this.config.totalAmount);let r=await this.paymentIntent.createPaymentIntent(n);if(`error`in r&&`code`in r){this.sendAlert(`¡Error al procesar el pago!`,`Por favor, intenta nuevamente, o contacta al comercio.`),this.sendFailureEmitter(r.status,this.serverErrorHandler.resolveServerErrorMessage(r.error)),this.resetPointsPayButton();return}if(r.data.status!==`success`){let e=Zt(r.data.response_code??``);this.sendAlert(e.title,e.message),this.sendFailureEmitter(0,e.message),this.resetPointsPayButton();return}this.sendSuccess(r)}resetPointsPayButton(){this.iframe?.contentWindow?.postMessage({type:`payment-form:points-pay-reset`},this.origin)}async handlePointsBalance(e){let t;try{t=await this.points.generatePayload(e)}catch{this.sendAlert(`¡Error al cifrar tus datos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let n=await this.points.getPointsBalance(t).catch(()=>null);if(!n||`error`in n||n.data.in_dollar_cents<=0){this.sendAlert(`¡Error al consultar tus puntos!`,`Por favor, intenta nuevamente, o contacta al comercio.`);return}let r=this.config.totalAmount??this.currentAmount??Ut(e.amount),i=Math.round(r*n.data.points/n.data.in_dollar_cents);this.pointsPaymentContext={value:e,points:i},this.iframe?.contentWindow?.postMessage({type:`payment-form:points-balance`,balance:{availableCents:n.data.in_dollar_cents,availablePoints:n.data.points,currency:n.data.in_dollar_currency,purchaseCents:r,purchasePoints:i},formValues:e},this.origin)}sendReadyEmitter(){for(let e of this.readyListeners)e()}sendSizingEmitter(e,t){for(let n of this.sizingListeners)n({width:e,height:t})}sendSuccess(e){this.config.totalAmount&&(e.data.amount_cents=this.config.totalAmount),this.postMessageToIframe({type:`payment-form:success`,paymentIntent:e});let{id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o}=e.data,s={id:t,status:n,amount_cents:r,response_code:i,authorization_number:a,reference_number:o};for(let e of this.successListeners)e(s)}async handleCryptoPayment(e){this.setSubmitLoading(!0);let t=wn.getInstance(),n=this.config.totalAmount??this.currentAmount??Ut(e.amount||`0`);this.countryContent.getCountries().length===0&&await this.countryContent.fetchCountries();let r=e.country||``,i=this.countryContent.getCountries().find(e=>e.id===r||e.alpha2===r||e.name===r)?.alpha2||(r.length===2?r.toUpperCase():void 0),a={data:{branch_id:this.orchestrator.getConfig()?.data?.branch_id||this.config.branchCode,amount_cents:n,currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,description:e.description||this.config.description||`Pago con Criptomonedas`,billing_document_number:e.billingDocumentNumber||``,redirect_url:this.config.redirectUrl||(typeof window<`u`?`${window.location.origin}/paylink/crypto/callback`:void 0),kyc:{email:e.email||``,first_name:e.firstName||``,last_name:e.lastName||``,country:i||``,phone:e.phone||void 0,phone_number:e.phone||void 0,nationality:e.nationality?.toUpperCase()||i||void 0,city:e.city||void 0,postal_code:e.postalCode||void 0,zip_code:e.postalCode||e.zipCode||void 0,address:e.address||void 0}}};try{let r=await t.createCharge(a);this.currentCryptoChargeId=r.data.charge_id,this.setSubmitLoading(!1),this.postMessageToIframe({type:`payment-form:naka-checkout`,redirectUrl:r.data.redirect_url,chargeId:r.data.charge_id}),this.startNakaPolling(r.data.charge_id,n,e)}catch(e){this.setSubmitLoading(!1),this.sendAlert($.CREATE_CHARGE_ERROR.title,$.CREATE_CHARGE_ERROR.message),this.sendFailureEmitter(500,e instanceof Error?e.message:`Error en servicio de criptomonedas`)}}async handleNakaTerminalFailure(e,t,n){this.stopNakaPolling(),this.iframe&&=(this.iframe.remove(),null),this.pendingAlert={title:e,message:t},await this.renderForm(),this.sendFailureEmitter(n,t)}startNakaPolling(e,t,n){this.stopNakaPolling();let r=wn.getInstance(),i=0,a=Date.now();this.nakaPollingInterval=setInterval(async()=>{try{if(Date.now()-a>=18e5){await this.handleNakaTerminalFailure($.TIMEOUT.title,$.TIMEOUT.message,408);return}let o=await r.getChargeStatus(e);i=0;let s=o.data,c=s?.status;if(c===`SUCCESS`||c===`COMPLETED`||c===`PAID`){this.stopNakaPolling();let r={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:En,card_last_digits:Dn,invoice_serie:null}};this.sendSuccess(r);return}if(c===`CANCELED`||c===`CANCELLED`){await this.handleNakaTerminalFailure($.CANCELED.title,$.CANCELED.message,400);return}if(c===`EXPIRED`){await this.handleNakaTerminalFailure($.EXPIRED.title,$.EXPIRED.message,410);return}if(c===`FAILED`||c===`REJECTED`){await this.handleNakaTerminalFailure($.FAILED.title,$.FAILED.message,422);return}if(c===`OVERPAID`){this.isCryptoOverpaid=!0,this.lastCryptoOverpaidSuccess={data:{id:e,status:`success`,amount_cents:t,amount_currency:this.orchestrator.getConfig()?.data?.amount_currency||`USD`,response_code:`00`,authorization_number:s.authorization_number||s.transaction_id||`NAKA-${Date.now()}`,reference_number:s.reference_number||s.order_number||e,billing_document_number:n.billingDocumentNumber||``,description:n.description||this.config.description||`Pago con Criptomonedas`,date:new Date().toISOString().split(`T`)[0],time:new Date().toTimeString().split(` `)[0],commerce_name:this.orchestrator.getConfig()?.data?.name||``,branch_name:this.orchestrator.getConfig()?.data?.branch_name||``,card_network:En,card_last_digits:Dn,invoice_serie:null}},this.postMessageToIframe({type:`payment-form:crypto-overpaid`,label:$.OVERPAID.finishLabel});return}if(c===`PENDING`||c===`IN_PROGRESS`||c===`OPEN`||c===`UNDERPAID`)return}catch(e){if(e?.status===422){let t=e?.data?.error||$.PAYMENT_UNAVAILABLE.defaultMessage;await this.handleNakaTerminalFailure($.PAYMENT_UNAVAILABLE.title,t,422);return}if(e?.status===404){await this.handleNakaTerminalFailure($.ORDER_NOT_FOUND.title,$.ORDER_NOT_FOUND.message,404);return}if(e?.status===401||e?.status===403){await this.handleNakaTerminalFailure($.SESSION_EXPIRED.title,$.SESSION_EXPIRED.message,e.status);return}if(i++,i>=5){await this.handleNakaTerminalFailure($.CONNECTION_ERROR.title,$.CONNECTION_ERROR.message,500);return}}},Tn)}stopNakaPolling(){this.nakaPollingInterval&&=(clearInterval(this.nakaPollingInterval),null)}destroy(){this.stopNakaPolling(),this.pendingAlert=null,this.currentCryptoChargeId=null,this.isCryptoOverpaid=!1,this.lastCryptoOverpaidSuccess=null,this.messageHandler&&=(window.removeEventListener(`message`,this.messageHandler),null),this.successListeners.clear(),this.failureListeners.clear(),this.readyListeners.clear(),this.sizingListeners.clear(),this.iframe&&=(this.iframe.remove(),null)}},e.VERSION=`1.5.7`,e})({});
|
package/dist/index.js
CHANGED
|
@@ -11035,6 +11035,7 @@ var Tt = class e {
|
|
|
11035
11035
|
}
|
|
11036
11036
|
loaded = !1;
|
|
11037
11037
|
initialized = !1;
|
|
11038
|
+
originalAppendChild = null;
|
|
11038
11039
|
constructor() {}
|
|
11039
11040
|
static getInstance() {
|
|
11040
11041
|
return e.instance ||= new e(), e.instance;
|
|
@@ -11075,11 +11076,48 @@ var Tt = class e {
|
|
|
11075
11076
|
}
|
|
11076
11077
|
});
|
|
11077
11078
|
}
|
|
11079
|
+
isCardinalModalNode(e) {
|
|
11080
|
+
return !(e instanceof HTMLElement) || e.tagName && e.tagName.toLowerCase() === "iframe" && e.name === "cardinalIframe" || e.id === "collectionForm" || e.id === "Cardinal-collector" ? !1 : !!(e instanceof HTMLIFrameElement && e.name === "cardinal-test-frame" || e.id === "Cardinal-ElementContainer" || e.id === "Cardinal-ElementLoader" || e.id === "Cardinal-Modal" || e.id === "Cardinal-Overlay" || e.id === "Cardinal-cca-IFrame" || e.id === "Cardinal-CCA-IFrame" || e.querySelector?.("#Cardinal-Modal, #Cardinal-Overlay, #Cardinal-cca-IFrame, #Cardinal-CCA-IFrame"));
|
|
11081
|
+
}
|
|
11082
|
+
prepareModalElement(e) {
|
|
11083
|
+
e instanceof HTMLIFrameElement && e.name === "cardinal-test-frame" ? (e.setAttribute("popover", "manual"), e.style.cssText += ";position: fixed; z-index: 2147483647; inset: 0; margin: auto; background: #fff;") : (e.setAttribute("popover", "manual"), e.style.cssText += ";border: none !important; background: transparent !important; padding: 0 !important; margin: 0 !important; width: 0 !important; height: 0 !important; max-width: none !important; max-height: none !important; overflow: visible !important; inset: 0 !important;");
|
|
11084
|
+
let t = e.querySelector("#Cardinal-Modal, .cardinalOverlay-content");
|
|
11085
|
+
t && t.style.setProperty("z-index", "2147483647", "important");
|
|
11086
|
+
let n = e.querySelector("#Cardinal-Overlay, .cardinalOverlay-mask");
|
|
11087
|
+
n && n.style.setProperty("z-index", "2147483646", "important");
|
|
11088
|
+
}
|
|
11089
|
+
promoteToTopLayer(e) {
|
|
11090
|
+
try {
|
|
11091
|
+
typeof e.showPopover == "function" && e.showPopover();
|
|
11092
|
+
} catch {}
|
|
11093
|
+
let t = e.querySelector("#Cardinal-Modal, .cardinalOverlay-content");
|
|
11094
|
+
t && t.style.setProperty("z-index", "2147483647", "important");
|
|
11095
|
+
let n = e.querySelector("#Cardinal-Overlay, .cardinalOverlay-mask");
|
|
11096
|
+
n && n.style.setProperty("z-index", "2147483646", "important");
|
|
11097
|
+
}
|
|
11098
|
+
installDomInterceptor() {
|
|
11099
|
+
this.originalAppendChild || (this.originalAppendChild = document.body.appendChild, document.body.appendChild = (e) => {
|
|
11100
|
+
if (this.isCardinalModalNode(e) && e instanceof HTMLElement) {
|
|
11101
|
+
this.prepareModalElement(e);
|
|
11102
|
+
let t = document.querySelectorAll("dialog[open]"), n = t.length > 0 ? t[t.length - 1] : null, r = n ? n.appendChild(e) : this.originalAppendChild.call(document.body, e);
|
|
11103
|
+
return this.promoteToTopLayer(e), r;
|
|
11104
|
+
}
|
|
11105
|
+
return this.originalAppendChild.call(document.body, e);
|
|
11106
|
+
});
|
|
11107
|
+
}
|
|
11108
|
+
restoreDomInterceptor() {
|
|
11109
|
+
this.originalAppendChild &&= (document.body.appendChild = this.originalAppendChild, null);
|
|
11110
|
+
}
|
|
11078
11111
|
cleanup() {
|
|
11079
11112
|
let e = document.querySelector("iframe[name=\"cardinalIframe\"]");
|
|
11080
11113
|
e && e.remove();
|
|
11081
11114
|
let t = document.getElementById("collectionForm");
|
|
11082
|
-
t && t.remove()
|
|
11115
|
+
t && t.remove(), document.querySelectorAll("#Cardinal-ElementContainer, #Cardinal-ElementLoader, iframe[name=\"cardinal-test-frame\"]").forEach((e) => {
|
|
11116
|
+
if (e instanceof HTMLElement) try {
|
|
11117
|
+
e.hidePopover?.();
|
|
11118
|
+
} catch {}
|
|
11119
|
+
e.remove();
|
|
11120
|
+
}), this.restoreDomInterceptor();
|
|
11083
11121
|
}
|
|
11084
11122
|
submitCollectionForm(e) {
|
|
11085
11123
|
this.cleanup();
|
|
@@ -11093,12 +11131,12 @@ var Tt = class e {
|
|
|
11093
11131
|
onCardinalValidated() {
|
|
11094
11132
|
return new Promise((e) => {
|
|
11095
11133
|
Cardinal.on("payments.validated", (t) => {
|
|
11096
|
-
Cardinal.off("payments.validated"), e(t);
|
|
11134
|
+
Cardinal.off("payments.validated"), this.cleanup(), e(t);
|
|
11097
11135
|
});
|
|
11098
11136
|
});
|
|
11099
11137
|
}
|
|
11100
11138
|
continueCardinal(e, t, n) {
|
|
11101
|
-
Cardinal.continue("cca", {
|
|
11139
|
+
this.installDomInterceptor(), Cardinal.continue("cca", {
|
|
11102
11140
|
AcsUrl: e.acs_url,
|
|
11103
11141
|
Payload: e.payload
|
|
11104
11142
|
}, { OrderDetails: {
|
|
@@ -11998,7 +12036,7 @@ function bn(e, t, n, r, i) {
|
|
|
11998
12036
|
//#region src/content/html/iframeTemplate.ts
|
|
11999
12037
|
function xn(e) {
|
|
12000
12038
|
let t = `<img src="${hn}" alt="Bizz Logo" class="bizz-logo">`, n = e.customBodyHtml ?? bn(e.cardFormHtml || "", e.submitButtonHtml, e.pointsFormHtml || "", e.installmentFormHtml || "", e.cryptoFormHtml || "");
|
|
12001
|
-
return pn.replace("<!--STYLES-->", `<style>${gn}</style>`).replace("<!--BIZZ_LOGO-->", t).replace("<!--HEADER-->", e.headerHtml).replace("<!--OPERATION_SELECTION-->", n).replace("<!--VERSION-->", "<div class=\"bizz-sdk-version\">v1.5.
|
|
12039
|
+
return pn.replace("<!--STYLES-->", `<style>${gn}</style>`).replace("<!--BIZZ_LOGO-->", t).replace("<!--HEADER-->", e.headerHtml).replace("<!--OPERATION_SELECTION-->", n).replace("<!--VERSION-->", "<div class=\"bizz-sdk-version\">v1.5.7</div>").replace("<!--SCRIPT-->", `<script>${mn}<\/script>`);
|
|
12002
12040
|
}
|
|
12003
12041
|
function Sn(e) {
|
|
12004
12042
|
let t = document.createElement("iframe");
|
|
@@ -12147,7 +12185,7 @@ var zn = class e {
|
|
|
12147
12185
|
autocomplete: a.autocomplete
|
|
12148
12186
|
};
|
|
12149
12187
|
}), Vn = class {
|
|
12150
|
-
static version = "1.5.
|
|
12188
|
+
static version = "1.5.7";
|
|
12151
12189
|
config;
|
|
12152
12190
|
iframe = null;
|
|
12153
12191
|
messageHandler = null;
|
|
@@ -12796,6 +12834,6 @@ var zn = class e {
|
|
|
12796
12834
|
destroy() {
|
|
12797
12835
|
this.stopNakaPolling(), this.pendingAlert = null, this.currentCryptoChargeId = null, this.isCryptoOverpaid = !1, this.lastCryptoOverpaidSuccess = null, this.messageHandler &&= (window.removeEventListener("message", this.messageHandler), null), this.successListeners.clear(), this.failureListeners.clear(), this.readyListeners.clear(), this.sizingListeners.clear(), this.iframe &&= (this.iframe.remove(), null);
|
|
12798
12836
|
}
|
|
12799
|
-
}, Hn = "1.5.
|
|
12837
|
+
}, Hn = "1.5.7";
|
|
12800
12838
|
//#endregion
|
|
12801
12839
|
export { Vn as BizzPaymentForm, Hn as VERSION };
|
package/package.json
CHANGED