@mupag/widget 0.1.0
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/README.md +84 -0
- package/dist/index.cjs +10 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +107 -0
- package/dist/index.d.ts +107 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/widget.global.js +10 -0
- package/dist/widget.global.js.map +1 -0
- package/examples/shopify-theme.liquid +14 -0
- package/examples/vanilla.html +24 -0
- package/examples/wix.html +17 -0
- package/examples/wordpress-theme.html +15 -0
- package/package.json +69 -0
package/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# @mupag/widget
|
|
2
|
+
|
|
3
|
+
Browser SDK para abrir o checkout MuPag em modal via iframe, sem redirect obrigatório.
|
|
4
|
+
|
|
5
|
+
## Distribuição
|
|
6
|
+
|
|
7
|
+
> **CDN oficial ainda não publicado.** O domínio CDN próprio da MuPag ainda está pendente.
|
|
8
|
+
> Depois que `@mupag/widget@0.1.0` for publicado no npm, você poderá usar o pacote pelo npm,
|
|
9
|
+
> unpkg ou jsDelivr:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @mupag/widget
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Alternativa via unpkg:
|
|
16
|
+
|
|
17
|
+
```html
|
|
18
|
+
<script src="https://unpkg.com/@mupag/widget@0.1.0/dist/widget.global.js" defer></script>
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Alternativa via jsDelivr:
|
|
22
|
+
|
|
23
|
+
```html
|
|
24
|
+
<script src="https://cdn.jsdelivr.net/npm/@mupag/widget@0.1.0/dist/widget.global.js" defer></script>
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
O bundle expõe apenas `window.MuPagWidget` com `{ MuPag, init, version }`.
|
|
28
|
+
|
|
29
|
+
## Uso via atributos de dados
|
|
30
|
+
|
|
31
|
+
```html
|
|
32
|
+
<button
|
|
33
|
+
data-mupag-widget
|
|
34
|
+
data-environment="test"
|
|
35
|
+
data-publishable-key="pk_test_..."
|
|
36
|
+
data-item-name="Plano Pro"
|
|
37
|
+
data-unit-amount-cents="10990"
|
|
38
|
+
data-quantity="1"
|
|
39
|
+
data-success-url="https://sua-loja.example/pagamento/sucesso"
|
|
40
|
+
data-cancel-url="https://sua-loja.example/carrinho"
|
|
41
|
+
>
|
|
42
|
+
Comprar agora
|
|
43
|
+
</button>
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## NPM
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npm install @mupag/widget
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { MuPag } from "@mupag/widget";
|
|
54
|
+
|
|
55
|
+
const mupag = new MuPag({
|
|
56
|
+
environment: "test",
|
|
57
|
+
publishableKey: "pk_test_...",
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
await mupag.openCheckout({
|
|
61
|
+
items: [{ name: "Plano Pro", quantity: 1, unit_amount_cents: 10_990 }],
|
|
62
|
+
success_url: "https://sua-loja.example/pagamento/sucesso",
|
|
63
|
+
cancel_url: "https://sua-loja.example/carrinho",
|
|
64
|
+
customer_data: { email: "user@example.com" },
|
|
65
|
+
onSuccess: (charge) => console.log("Paid", charge),
|
|
66
|
+
onClose: () => console.log("Closed"),
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Segurança e compatibilidade
|
|
71
|
+
|
|
72
|
+
- A chave `publishable` precisa do escopo `checkout_sessions.create`.
|
|
73
|
+
- `environment` é obrigatório e a chave deve corresponder a `test` (`pk_test_`) ou `prd` (`pk_prd_`).
|
|
74
|
+
- Nunca use uma chave secreta no navegador.
|
|
75
|
+
- O widget cria uma `Idempotency-Key` criptograficamente segura para cada nova sessão; informe
|
|
76
|
+
`idempotencyKey` para reutilizar a mesma operação em uma tentativa controlada.
|
|
77
|
+
- Sem `eval`, top-level await ou dependências runtime externas.
|
|
78
|
+
- Baseline ES2018.
|
|
79
|
+
- Modal isolado com Shadow DOM e iframe com sandbox.
|
|
80
|
+
- `postMessage` aceita eventos apenas da origem e da janela do iframe ativo.
|
|
81
|
+
- A URL de checkout retornada precisa usar a origem configurada e o caminho `/c/{session_id}`.
|
|
82
|
+
- Para domínio próprio de checkout, configure `checkoutBaseUrl` explicitamente com a origem HTTPS.
|
|
83
|
+
- Em telas menores que 640px o modal vira fullscreen.
|
|
84
|
+
- Se o iframe não carregar, o SDK faz fallback para redirect.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
'use strict';var q="0.1.0",T={test:"https://api.sandbox.mupag.com.br",prd:"https://api.mupag.com.br"},A={test:"https://checkout.sandbox.mupag.com.br",prd:"https://checkout.mupag.com.br"},K=8e3,F=15e3,W=256*1024,D=1024*1024,E=9e15,L="mupagWidgetBound";function H(e){return e.replace(/\/+$/,"")}function J(e){return e==="pt-BR"||e==="en-US"?e:typeof navigator!="undefined"&&navigator.language.toLowerCase().startsWith("en")?"en-US":"pt-BR"}function z(e,t){var r;let n=J(t.locale);return e.searchParams.set("locale",n),t.theme&&Object.keys(t.theme).length>0&&e.searchParams.set("theme",JSON.stringify(t.theme)),typeof window!="undefined"&&((r=window.location)!=null&&r.origin)&&e.searchParams.set("parent_origin",window.location.origin),e}function V(e,t,n){var p,w,y;let r=document.createElement("div");r.dataset.mupagWidgetRoot="true";let o=r.attachShadow({mode:"open"}),a=document.createElement("div");a.setAttribute("part","overlay");let i=document.createElement("section");i.setAttribute("part","dialog"),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-label","Checkout seguro MuPag");let c=document.createElement("button");c.type="button",c.textContent="Fechar",c.setAttribute("part","close"),c.addEventListener("click",n);let s=document.createElement("iframe");s.src=e,s.title="Checkout seguro MuPag",s.allow="payment *",s.referrerPolicy="strict-origin-when-cross-origin",s.setAttribute("part","iframe"),s.setAttribute("loading","eager"),s.setAttribute("sandbox","allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.append(c,s),a.append(i);let l=(p=t==null?void 0:t.primaryColor)!=null?p:"#176bff",u=(w=t==null?void 0:t.borderRadius)!=null?w:"18px",m=(y=t==null?void 0:t.fontFamily)!=null?y:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif",d=`
|
|
2
|
+
:host{all:initial;--gw-primary:${l};--gw-radius:${u};font-family:${m}}
|
|
3
|
+
[part=overlay]{position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(10,18,32,.54);padding:24px}
|
|
4
|
+
[part=dialog]{position:relative;width:min(100%,760px);height:min(92vh,860px);overflow:hidden;border-radius:var(--gw-radius);background:#fff;box-shadow:0 24px 80px rgba(10,18,32,.28)}
|
|
5
|
+
[part=close]{position:absolute;right:12px;top:10px;z-index:2;border:1px solid rgba(15,23,42,.16);border-radius:999px;background:#fff;color:#243044;font:600 13px/1.2 inherit;padding:8px 12px;cursor:pointer}
|
|
6
|
+
[part=close]:focus{outline:3px solid color-mix(in srgb,var(--gw-primary) 35%,transparent);outline-offset:2px}
|
|
7
|
+
[part=iframe]{display:block;width:100%;height:100%;border:0;background:#fff}
|
|
8
|
+
@media (max-width:640px){[part=overlay]{align-items:stretch;padding:0;background:#fff}[part=dialog]{width:100%;height:100vh;max-height:none;border-radius:0;box-shadow:none}[part=close]{right:10px;top:8px}}
|
|
9
|
+
`;if("adoptedStyleSheets"in o&&"CSSStyleSheet"in window){let h=new CSSStyleSheet;h.replaceSync(d),o.adoptedStyleSheets=[h],o.append(a);}else {let h=document.createElement("style");h.textContent=d,o.append(h,a);}return document.body.append(r),{host:r,iframe:s}}function X(e){return !e||typeof e!="object"||!("type"in e)||typeof e.type!="string"?false:["mupag:loaded","mupag:payment_completed","mupag:close","mupag:error"].includes(e.type)}var U=class{constructor(t){this.active=null;var n,r,o,a,i,c,s;Y(t),this.options={...t,checkoutBaseUrl:O((n=t.checkoutBaseUrl)!=null?n:A[t.environment],A[t.environment],t.environment,"checkoutBaseUrl"),apiBaseUrl:O((r=t.apiBaseUrl)!=null?r:T[t.environment],T[t.environment],t.environment,"apiBaseUrl"),fetch:(o=t.fetch)!=null?o:globalThis.fetch.bind(globalThis),fallbackRedirect:(a=t.fallbackRedirect)!=null?a:true,iframeLoadTimeoutMs:(i=t.iframeLoadTimeoutMs)!=null?i:K,requestTimeoutMs:(c=t.requestTimeoutMs)!=null?c:F,maxResponseBytes:(s=t.maxResponseBytes)!=null?s:W},this.handleMessage=this.handleMessage.bind(this);}async openCheckout(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Checkout params must be an object.");let{onSuccess:n,onClose:r,onError:o,idempotencyKey:a,...i}=t;B(i,this.options.environment);let c,s;try{c=JSON.stringify(i),s=JSON.parse(c);}catch(v){throw new Error("Checkout payload must be valid JSON.")}if(B(s,this.options.environment),new TextEncoder().encode(c).byteLength>D)throw new Error("Checkout payload exceeds the safe 1 MiB limit.");let l=a===void 0?ne():re(a),u=new AbortController,m=window.setTimeout(()=>u.abort(),this.options.requestTimeoutMs),d;try{d=await this.options.fetch(`${this.options.apiBaseUrl}/v1/checkout-sessions`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.options.publishableKey}`,"Idempotency-Key":l},body:c,signal:u.signal});}catch(v){let S={code:"checkout_network_error",message:"Checkout session request failed."};throw o==null||o(S),new Error(S.message)}finally{window.clearTimeout(m);}let p=await te(d,this.options.maxResponseBytes);if(!d.ok){let v={code:"checkout_session_failed",message:`Checkout session failed (${d.status}).`};throw o==null||o(v),new Error(v.message)}let w=G(p),y=ee(w.url,w.id,this.options.checkoutBaseUrl),h=z(y,this.options),_={};n&&(_.onSuccess=n),r&&(_.onClose=r),o&&(_.onError=o),this.openUrl(h.toString(),_);}close(){this.active&&(this.active.loadTimer&&window.clearTimeout(this.active.loadTimer),window.removeEventListener("message",this.handleMessage),this.active.host.remove(),this.active=null);}openUrl(t,n){this.close();let r=new URL(t).origin,a={...V(t,this.options.theme,()=>{var i;(i=n.onClose)==null||i.call(n),this.close();}),checkoutOrigin:r,callbacks:n,fallbackUrl:t,loaded:false,loadTimer:void 0};a.iframe.addEventListener("load",()=>{a.loaded=true,a.loadTimer&&window.clearTimeout(a.loadTimer);}),a.loadTimer=window.setTimeout(()=>{!a.loaded&&this.options.fallbackRedirect&&window.location.assign(a.fallbackUrl);},this.options.iframeLoadTimeoutMs),this.active=a,window.addEventListener("message",this.handleMessage);}handleMessage(t){var n,r,o,a,i,c,s,l,u,m,d;if(!(!this.active||t.origin!==this.active.checkoutOrigin||t.source===null||this.active.iframe.contentWindow===null||t.source!==this.active.iframe.contentWindow||!X(t.data))){if(t.data.type==="mupag:loaded"){this.active.loaded=true;return}if(t.data.type==="mupag:payment_completed"){let p=(o=(r=t.data.charge)!=null?r:(n=t.data.payload)==null?void 0:n.charge)!=null?o:{status:"paid",...t.data.payload};(i=(a=this.active.callbacks).onSuccess)==null||i.call(a,p),this.close();return}if(t.data.type==="mupag:close"){(s=(c=this.active.callbacks).onClose)==null||s.call(c),this.close();return}t.data.type==="mupag:error"&&((d=(m=this.active.callbacks).onError)==null||d.call(m,(u=(l=t.data.error)!=null?l:t.data.payload)!=null?u:{code:"checkout_error",message:"Checkout error."}));}}};function ce(e=document){e.querySelectorAll("[data-mupag-widget]").forEach(n=>{n.dataset[L]!=="true"&&(n.dataset[L]="true",n.addEventListener("click",()=>{try{let r=oe(n),o={};n.dataset.primaryColor&&(o.primaryColor=n.dataset.primaryColor),n.dataset.accentColor&&(o.accentColor=n.dataset.accentColor),n.dataset.fontFamily&&(o.fontFamily=n.dataset.fontFamily),Object.keys(o).length>0&&(r.theme=o),new U(r).openCheckout(ae(n)).catch(i=>R(n,i));}catch(r){R(n,r);}}));});}function R(e,t){e.dispatchEvent(new CustomEvent("mupag:error",{detail:{code:"checkout_failed",message:se(t)}}));}function Y(e){if(!e||e.environment!=="test"&&e.environment!=="prd")throw new Error("environment must be explicitly test or prd.");let t=e.environment==="test"?"pk_test_":"pk_prd_";if(typeof e.publishableKey!="string"||!e.publishableKey.startsWith(t)||e.publishableKey.length>512||!/^[\x21-\x7e]+$/.test(e.publishableKey))throw new Error("publishableKey is invalid or does not match the selected environment.");C(e.iframeLoadTimeoutMs,1,12e4,"iframeLoadTimeoutMs"),C(e.requestTimeoutMs,1,12e4,"requestTimeoutMs"),C(e.maxResponseBytes,1,4*1024*1024,"maxResponseBytes"),ie(e.theme);}function O(e,t,n,r){let o;try{o=new URL(e);}catch(s){throw new Error(`${r} is invalid.`)}let a=n==="test"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname),i=o.origin===new URL(t).origin,c=r==="checkoutBaseUrl"&&o.protocol==="https:"&&!Q(o.hostname);if(!i&&!a&&!c||o.protocol!=="https:"&&!(a&&o.protocol==="http:")||o.username||o.password||o.pathname!==""&&o.pathname!=="/"||o.search||o.hash)throw new Error(`${r} is not an allowed origin.`);return H(o.origin)}function Q(e){return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)||e.includes(":")}function B(e,t){if(M(e,["items","success_url","cancel_url","customer_id","customer_data","allowed_payment_methods","affiliate_code","coupon_id","utm_params","expires_in_minutes","metadata","collect_shipping_address","delivery_type","allow_coupons"],"checkout"),!Array.isArray(e.items)||e.items.length<1||e.items.length>100)throw new Error("Checkout items must contain between 1 and 100 entries.");let n=0;for(let r of e.items){M(r,["name","quantity","unit_amount_cents"],"checkout item"),j(r.name,200,"item.name"),f(r.name,"item.name"),b(r.quantity,1,1e6,"item.quantity"),b(r.unit_amount_cents,100,E,"item.unit_amount_cents");let o=r.quantity*r.unit_amount_cents;if(!Number.isSafeInteger(o)||o>E)throw new Error("Checkout item total is outside the supported range.");if(n+=o,!Number.isSafeInteger(n)||n>E)throw new Error("Checkout total is outside the supported range.")}if(I(e.success_url,t,"success_url"),I(e.cancel_url,t,"cancel_url"),e.customer_id!==void 0&&e.customer_data!==void 0)throw new Error("customer_id and customer_data are mutually exclusive.");if(e.customer_id!==void 0&&!P(e.customer_id))throw new Error("customer_id must be a UUID.");if(f(e.customer_id,"customer_id"),e.customer_data!==void 0&&(M(e.customer_data,["name","email","document","phone"],"customer_data"),g(e.customer_data.name,200,"customer_data.name"),f(e.customer_data.name,"customer_data.name"),g(e.customer_data.email,320,"customer_data.email"),f(e.customer_data.email,"customer_data.email"),g(e.customer_data.document,64,"customer_data.document"),g(e.customer_data.phone,32,"customer_data.phone")),e.allowed_payment_methods!==void 0&&(!Array.isArray(e.allowed_payment_methods)||e.allowed_payment_methods.length<1||e.allowed_payment_methods.length>2||new Set(e.allowed_payment_methods).size!==e.allowed_payment_methods.length||e.allowed_payment_methods.some(r=>r!=="pix"&&r!=="credit_card")))throw new Error("allowed_payment_methods is invalid.");if(g(e.affiliate_code,128,"affiliate_code"),f(e.affiliate_code,"affiliate_code"),e.coupon_id!==void 0&&!P(e.coupon_id))throw new Error("coupon_id must be a UUID.");if(e.allow_coupons===false&&e.coupon_id!==void 0)throw new Error("coupon_id cannot be used when allow_coupons is false.");e.expires_in_minutes!==void 0&&b(e.expires_in_minutes,1,1440,"expires_in_minutes"),e.metadata!==void 0&&$(e.metadata,"metadata"),e.utm_params!==void 0&&$(e.utm_params,"utm_params"),g(e.delivery_type,64,"delivery_type"),f(e.delivery_type,"delivery_type"),N(e.collect_shipping_address,"collect_shipping_address"),N(e.allow_coupons,"allow_coupons");}function M(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new Error(`${n} must be a plain object.`);let r=new Set(t),o=Object.keys(e).find(a=>!r.has(a));if(o!==void 0)throw new Error(`${n} contains unsupported field ${o}.`)}function $(e,t){if(e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new Error(`${t} must be a plain JSON object.`);let n=[{value:e,depth:0}],r=new WeakSet,o=0;for(;n.length>0;){let a=n.pop();if(!a)break;if(o+=1,o>1e4||a.depth>32)throw new Error(`${t} is too complex.`);if(!(a.value===null||typeof a.value=="boolean")){if(typeof a.value=="string"){if(k(a.value))throw new Error(`${t} contains a possible card number.`);continue}if(typeof a.value=="number"){if(!Number.isFinite(a.value))throw new Error(`${t} contains an invalid number.`);if(k(JSON.stringify(a.value)))throw new Error(`${t} contains a possible card number.`);continue}if(typeof a.value!="object")throw new Error(`${t} contains a non-JSON value.`);if(r.has(a.value))throw new Error(`${t} contains a cycle.`);r.add(a.value);for(let[i,c]of Object.entries(a.value)){if(k(i))throw new Error(`${t} contains a possible card number.`);let s=i.toLowerCase(),l=s.replace(/[^a-z0-9]/g,""),u=l.replace(/[0-9]+$/,"").replace(/(cvv|cvc|csc|cid|cav)[0-9]+/g,"$1");if(["__proto__","prototype","constructor"].includes(s)||["pan","cardnumber"].includes(l)||["cvv","cvc","cav"].some(m=>["","value","code","number"].some(d=>u.endsWith(m+d)))||["csc","cid"].some(m=>["","value","code","number"].some(d=>u===m+d||["card","amex","americanexpress"].some(p=>u.endsWith(p+m+d))))||u.endsWith("cardidentificationnumber")||u.endsWith("cardsecuritynumber")||["securitycode","securityvalue","verificationcode","verificationnumber","verificationvalue"].some(m=>u.endsWith(m)))throw new Error(`${t} contains a forbidden field.`);n.push({value:c,depth:a.depth+1});}}}}function k(e){let t="";for(let n of e)if(n>="0"&&n<="9"){t=(t+n).slice(-19);for(let r=12;r<=t.length;r+=1)if(Z(t.slice(-r)))return true}else {if(/^\p{Nd}$/u.test(n))return true;if(/^[\s\p{P}\p{S}\p{M}\p{Cc}\p{Cf}]$/u.test(n))continue;t="";}return false}function f(e,t){if(e!==void 0&&(typeof e!="string"||k(e)))throw new Error(`${t} contains a possible card number.`)}function Z(e){if(!/^[0-9]{12,19}$/.test(e))return false;let t=0,n=false;for(let r=e.length-1;r>=0;r-=1){let o=e.charCodeAt(r)-48;n&&(o*=2,o>9&&(o-=9)),t+=o,n=!n;}return t%10===0}function I(e,t,n){let r;try{r=new URL(e);}catch(a){throw new Error(`${n} must be an absolute URL.`)}let o=t==="test"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(r.protocol!=="https:"&&!(o&&r.protocol==="http:")||r.username||r.password||e.length>2048)throw new Error(`${n} must be a safe HTTPS URL.`)}function G(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid checkout response.");let t=e;if(!P(t.id)||typeof t.url!="string"||typeof t.expires_at!="string")throw new Error("Invalid checkout response.");if(Number.isNaN(Date.parse(t.expires_at)))throw new Error("Invalid checkout response.");return {id:t.id,url:t.url,expires_at:t.expires_at}}function ee(e,t,n){let r;try{r=new URL(e);}catch(o){throw new Error("Invalid checkout URL in API response.")}if(r.origin!==new URL(n).origin||r.username||r.password||r.protocol!==new URL(n).protocol||r.pathname!==`/c/${t}`||r.search||r.hash)throw new Error("Invalid checkout URL in API response.");return r}async function te(e,t){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>t))throw new Error("Checkout response exceeds the configured limit.");if(!e.body)return;let r=e.body.getReader(),o=[],a=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(u){if(a+=u.byteLength,a>t)throw await r.cancel("response limit exceeded"),new Error("Checkout response exceeds the configured limit.");o.push(u);}}}finally{r.releaseLock();}let i=new Uint8Array(a),c=0;for(let l of o)i.set(l,c),c+=l.byteLength;let s=new TextDecoder().decode(i);if(s.trim().length!==0)try{return JSON.parse(s)}catch(l){throw new Error("Checkout response is not valid JSON.")}}function ne(){let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return `widget_${e.randomUUID()}`;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("A secure random generator is required to create an Idempotency-Key.");let t=new Uint8Array(16);return e.getRandomValues(t),`widget_${Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}`}function re(e){if(e.length<1||e.length>128||!/^[\x21-\x7e]+$/.test(e))throw new Error("idempotencyKey must contain 1-128 visible ASCII characters.");return e}function oe(e){var t;return {environment:e.dataset.environment,publishableKey:(t=e.dataset.publishableKey)!=null?t:"",...e.dataset.checkoutBaseUrl?{checkoutBaseUrl:e.dataset.checkoutBaseUrl}:{},...e.dataset.apiBaseUrl?{apiBaseUrl:e.dataset.apiBaseUrl}:{},...e.dataset.locale?{locale:e.dataset.locale}:{}}}function ae(e){var t,n,r,o,a;return {items:[{name:(t=e.dataset.itemName)!=null?t:"",quantity:Number((n=e.dataset.quantity)!=null?n:"1"),unit_amount_cents:Number((r=e.dataset.unitAmountCents)!=null?r:"")}],success_url:(o=e.dataset.successUrl)!=null?o:"",cancel_url:(a=e.dataset.cancelUrl)!=null?a:""}}function ie(e){if(e){if(e.primaryColor!==void 0&&(!x("color",e.primaryColor)||/url\s*\(/i.test(e.primaryColor)))throw new Error("theme.primaryColor is invalid.");if(e.accentColor!==void 0&&(!x("color",e.accentColor)||/url\s*\(/i.test(e.accentColor)))throw new Error("theme.accentColor is invalid.");if(e.borderRadius!==void 0&&(!x("border-radius",e.borderRadius)||/url\s*\(/i.test(e.borderRadius)))throw new Error("theme.borderRadius is invalid.");if(e.fontFamily!==void 0&&!/^[A-Za-z0-9 ,_'"-]{1,200}$/.test(e.fontFamily))throw new Error("theme.fontFamily is invalid.")}}function x(e,t){var n;return typeof((n=globalThis.CSS)==null?void 0:n.supports)=="function"&&globalThis.CSS.supports(e,t)}function C(e,t,n,r){e!==void 0&&b(e,t,n,r);}function b(e,t,n,r){if(!Number.isSafeInteger(e)||e<t||e>n)throw new Error(`${r} is invalid.`)}function j(e,t,n){if(typeof e!="string"||e.trim().length<1||e.length>t||/[\x00-\x1f\x7f]/.test(e))throw new Error(`${n} is invalid.`)}function g(e,t,n){e!==void 0&&j(e,t,n);}function N(e,t){if(e!==void 0&&typeof e!="boolean")throw new Error(`${t} is invalid.`)}function P(e){return typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function se(e){return (e instanceof Error?e.message:"Checkout failed.").replace(/[\r\n\t]+/g," ").slice(0,256)}var ue=q;exports.MuPag=U;exports.initDataAttributes=ce;exports.version=ue;//# sourceMappingURL=index.cjs.map
|
|
10
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["VERSION","API_BASE_URLS","CHECKOUT_BASE_URLS","DEFAULT_IFRAME_TIMEOUT_MS","DEFAULT_REQUEST_TIMEOUT_MS","DEFAULT_MAX_RESPONSE_BYTES","MAX_REQUEST_BYTES","MAX_MONEY_CENTS","DATA_BOUND","trimSlash","value","resolveLocale","locale","appendWidgetParams","url","options","_a","createModal","theme","onClose","_b","_c","host","root","overlay","dialog","close","iframe","primary","radius","font","css","sheet","style","isMuPagMessage","data","MuPag","_d","_e","_f","_g","validateOptions","allowedOrigin","params","onSuccess","onError","idempotencyKey","body","validateCheckout","encodedBody","canonicalBody","e","key","createIdempotencyKey","validateIdempotencyKey","controller","timer","response","error","responseBody","readBoundedJson","payload","checkoutResponse","checkoutUrl","safeCheckoutUrl","callbacks","checkoutOrigin","active","event","_h","_i","_j","_k","charge","initDataAttributes","button","dataOptions","dataCheckout","dispatchWidgetError","safeErrorMessage","expectedPrefix","boundedInteger","validateTheme","canonical","environment","field","loopback","isCanonical","explicitCheckoutDomain","isIpAddress","hostname","onlyKeys","total","item","text","rejectPANLikeOptionalText","integer","lineTotal","redirectUrl","uuid","optionalText","method","jsonObject","optionalBoolean","allowed","allowlist","unsupported","stack","seen","nodes","current","containsPANLikeSequence","child","normalized","compact","sensitiveBase","token","descriptor","qualifier","suffix","retainedDigits","character","length","validPANSequence","digits","sum","doubleDigit","index","digit","sessionId","baseUrl","maximumBytes","reader","chunks","done","buffer","offset","chunk","textBody","cryptoApi","bytes","entry","cssSupports","property","minimum","maximum","version"],"mappings":"aA0BA,IAAMA,CAAAA,CAAU,OAAA,CACVC,CAAAA,CAAkD,CACtD,IAAA,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AAG,CACxD,KAEawF,EAAAA,CAAUlJ","file":"index.cjs","sourcesContent":["import type {\n Charge,\n CheckoutParams,\n MuPagCallbacks,\n MuPagEnvironment,\n MuPagLocale,\n MuPagMessage,\n MuPagOptions,\n MuPagTheme,\n MuPagWidgetError,\n} from \"./types.js\";\n\nexport type {\n Charge,\n CheckoutCustomer,\n CheckoutItem,\n CheckoutParams,\n MuPagCallbacks,\n MuPagEnvironment,\n MuPagLocale,\n MuPagOptions,\n MuPagTheme,\n MuPagMessage,\n MuPagWidgetError,\n} from \"./types.js\";\n\nconst VERSION = \"0.1.0\";\nconst API_BASE_URLS: Record<MuPagEnvironment, string> = {\n test: \"https://api.sandbox.mupag.com.br\",\n prd: \"https://api.mupag.com.br\",\n};\nconst CHECKOUT_BASE_URLS: Record<MuPagEnvironment, string> = {\n test: \"https://checkout.sandbox.mupag.com.br\",\n prd: \"https://checkout.mupag.com.br\",\n};\nconst DEFAULT_IFRAME_TIMEOUT_MS = 8_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 15_000;\nconst DEFAULT_MAX_RESPONSE_BYTES = 256 * 1024;\nconst MAX_REQUEST_BYTES = 1024 * 1024;\nconst MAX_MONEY_CENTS = 9_000_000_000_000_000;\nconst DATA_BOUND = \"mupagWidgetBound\";\n\ninterface ActiveModal {\n host: HTMLElement;\n iframe: HTMLIFrameElement;\n checkoutOrigin: string;\n callbacks: MuPagCallbacks;\n fallbackUrl: string;\n loaded: boolean;\n loadTimer: number | undefined;\n}\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction resolveLocale(locale: MuPagOptions[\"locale\"]): MuPagLocale {\n if (locale === \"pt-BR\" || locale === \"en-US\") {\n return locale;\n }\n if (typeof navigator !== \"undefined\" && navigator.language.toLowerCase().startsWith(\"en\")) {\n return \"en-US\";\n }\n return \"pt-BR\";\n}\n\nfunction appendWidgetParams(url: URL, options: Required<Pick<MuPagOptions, \"checkoutBaseUrl\">> & MuPagOptions): URL {\n const locale = resolveLocale(options.locale);\n url.searchParams.set(\"locale\", locale);\n if (options.theme && Object.keys(options.theme).length > 0) {\n url.searchParams.set(\"theme\", JSON.stringify(options.theme));\n }\n if (typeof window !== \"undefined\" && window.location?.origin) {\n url.searchParams.set(\"parent_origin\", window.location.origin);\n }\n return url;\n}\n\nfunction createModal(url: string, theme: MuPagTheme | undefined, onClose: () => void): { host: HTMLElement; iframe: HTMLIFrameElement } {\n const host = document.createElement(\"div\");\n host.dataset.mupagWidgetRoot = \"true\";\n const root = host.attachShadow({ mode: \"open\" });\n const overlay = document.createElement(\"div\");\n overlay.setAttribute(\"part\", \"overlay\");\n const dialog = document.createElement(\"section\");\n dialog.setAttribute(\"part\", \"dialog\");\n dialog.setAttribute(\"role\", \"dialog\");\n dialog.setAttribute(\"aria-modal\", \"true\");\n dialog.setAttribute(\"aria-label\", \"Checkout seguro MuPag\");\n const close = document.createElement(\"button\");\n close.type = \"button\";\n close.textContent = \"Fechar\";\n close.setAttribute(\"part\", \"close\");\n close.addEventListener(\"click\", onClose);\n const iframe = document.createElement(\"iframe\");\n iframe.src = url;\n iframe.title = \"Checkout seguro MuPag\";\n iframe.allow = \"payment *\";\n iframe.referrerPolicy = \"strict-origin-when-cross-origin\";\n iframe.setAttribute(\"part\", \"iframe\");\n iframe.setAttribute(\"loading\", \"eager\");\n iframe.setAttribute(\n \"sandbox\",\n \"allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation\",\n );\n dialog.append(close, iframe);\n overlay.append(dialog);\n\n const primary = theme?.primaryColor ?? \"#176bff\";\n const radius = theme?.borderRadius ?? \"18px\";\n const font = theme?.fontFamily ?? \"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif\";\n const css = `\n :host{all:initial;--gw-primary:${primary};--gw-radius:${radius};font-family:${font}}\n [part=overlay]{position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(10,18,32,.54);padding:24px}\n [part=dialog]{position:relative;width:min(100%,760px);height:min(92vh,860px);overflow:hidden;border-radius:var(--gw-radius);background:#fff;box-shadow:0 24px 80px rgba(10,18,32,.28)}\n [part=close]{position:absolute;right:12px;top:10px;z-index:2;border:1px solid rgba(15,23,42,.16);border-radius:999px;background:#fff;color:#243044;font:600 13px/1.2 inherit;padding:8px 12px;cursor:pointer}\n [part=close]:focus{outline:3px solid color-mix(in srgb,var(--gw-primary) 35%,transparent);outline-offset:2px}\n [part=iframe]{display:block;width:100%;height:100%;border:0;background:#fff}\n @media (max-width:640px){[part=overlay]{align-items:stretch;padding:0;background:#fff}[part=dialog]{width:100%;height:100vh;max-height:none;border-radius:0;box-shadow:none}[part=close]{right:10px;top:8px}}\n `;\n if (\"adoptedStyleSheets\" in root && \"CSSStyleSheet\" in window) {\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(css);\n root.adoptedStyleSheets = [sheet];\n root.append(overlay);\n } else {\n const style = document.createElement(\"style\");\n style.textContent = css;\n root.append(style, overlay);\n }\n document.body.append(host);\n return { host, iframe };\n}\n\nfunction isMuPagMessage(data: unknown): data is MuPagMessage {\n if (!data || typeof data !== \"object\" || !(\"type\" in data) || typeof data.type !== \"string\") {\n return false;\n }\n return [\"mupag:loaded\", \"mupag:payment_completed\", \"mupag:close\", \"mupag:error\"].includes(data.type);\n}\n\nexport class MuPag {\n private readonly options: Required<\n Pick<\n MuPagOptions,\n | \"checkoutBaseUrl\"\n | \"apiBaseUrl\"\n | \"fetch\"\n | \"fallbackRedirect\"\n | \"iframeLoadTimeoutMs\"\n | \"requestTimeoutMs\"\n | \"maxResponseBytes\"\n >\n > &\n MuPagOptions;\n private active: ActiveModal | null = null;\n\n constructor(options: MuPagOptions) {\n validateOptions(options);\n this.options = {\n ...options,\n checkoutBaseUrl: allowedOrigin(\n options.checkoutBaseUrl ?? CHECKOUT_BASE_URLS[options.environment],\n CHECKOUT_BASE_URLS[options.environment],\n options.environment,\n \"checkoutBaseUrl\",\n ),\n apiBaseUrl: allowedOrigin(\n options.apiBaseUrl ?? API_BASE_URLS[options.environment],\n API_BASE_URLS[options.environment],\n options.environment,\n \"apiBaseUrl\",\n ),\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n fallbackRedirect: options.fallbackRedirect ?? true,\n iframeLoadTimeoutMs: options.iframeLoadTimeoutMs ?? DEFAULT_IFRAME_TIMEOUT_MS,\n requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,\n };\n this.handleMessage = this.handleMessage.bind(this);\n }\n\n async openCheckout(params: CheckoutParams): Promise<void> {\n if (!params || typeof params !== \"object\" || Array.isArray(params)) {\n throw new Error(\"Checkout params must be an object.\");\n }\n const { onSuccess, onClose, onError, idempotencyKey, ...body } = params;\n validateCheckout(body, this.options.environment);\n let encodedBody: string;\n let canonicalBody: typeof body;\n try {\n encodedBody = JSON.stringify(body);\n canonicalBody = JSON.parse(encodedBody) as typeof body;\n } catch {\n throw new Error(\"Checkout payload must be valid JSON.\");\n }\n validateCheckout(canonicalBody, this.options.environment);\n if (new TextEncoder().encode(encodedBody).byteLength > MAX_REQUEST_BYTES) {\n throw new Error(\"Checkout payload exceeds the safe 1 MiB limit.\");\n }\n const key = idempotencyKey === undefined ? createIdempotencyKey() : validateIdempotencyKey(idempotencyKey);\n const controller = new AbortController();\n const timer = window.setTimeout(() => controller.abort(), this.options.requestTimeoutMs);\n let response: Response;\n try {\n response = await this.options.fetch(`${this.options.apiBaseUrl}/v1/checkout-sessions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${this.options.publishableKey}`,\n \"Idempotency-Key\": key,\n },\n body: encodedBody,\n signal: controller.signal,\n });\n } catch {\n const error = { code: \"checkout_network_error\", message: \"Checkout session request failed.\" };\n onError?.(error);\n throw new Error(error.message);\n } finally {\n window.clearTimeout(timer);\n }\n const responseBody = await readBoundedJson(response, this.options.maxResponseBytes);\n if (!response.ok) {\n const error = { code: \"checkout_session_failed\", message: `Checkout session failed (${response.status}).` };\n onError?.(error);\n throw new Error(error.message);\n }\n const payload = checkoutResponse(responseBody);\n const checkoutUrl = safeCheckoutUrl(payload.url, payload.id, this.options.checkoutBaseUrl);\n const url = appendWidgetParams(checkoutUrl, this.options);\n const callbacks: MuPagCallbacks = {};\n if (onSuccess) {\n callbacks.onSuccess = onSuccess;\n }\n if (onClose) {\n callbacks.onClose = onClose;\n }\n if (onError) {\n callbacks.onError = onError;\n }\n this.openUrl(url.toString(), callbacks);\n }\n\n close(): void {\n if (!this.active) {\n return;\n }\n if (this.active.loadTimer) {\n window.clearTimeout(this.active.loadTimer);\n }\n window.removeEventListener(\"message\", this.handleMessage);\n this.active.host.remove();\n this.active = null;\n }\n\n private openUrl(url: string, callbacks: MuPagCallbacks): void {\n this.close();\n const checkoutOrigin = new URL(url).origin;\n const modal = createModal(url, this.options.theme, () => {\n callbacks.onClose?.();\n this.close();\n });\n const active: ActiveModal = {\n ...modal,\n checkoutOrigin,\n callbacks,\n fallbackUrl: url,\n loaded: false,\n loadTimer: undefined,\n };\n active.iframe.addEventListener(\"load\", () => {\n active.loaded = true;\n if (active.loadTimer) {\n window.clearTimeout(active.loadTimer);\n }\n });\n active.loadTimer = window.setTimeout(() => {\n if (!active.loaded && this.options.fallbackRedirect) {\n window.location.assign(active.fallbackUrl);\n }\n }, this.options.iframeLoadTimeoutMs);\n this.active = active;\n window.addEventListener(\"message\", this.handleMessage);\n }\n\n private handleMessage(event: MessageEvent): void {\n if (\n !this.active ||\n event.origin !== this.active.checkoutOrigin ||\n event.source === null ||\n this.active.iframe.contentWindow === null ||\n event.source !== this.active.iframe.contentWindow ||\n !isMuPagMessage(event.data)\n ) {\n return;\n }\n if (event.data.type === \"mupag:loaded\") {\n this.active.loaded = true;\n return;\n }\n if (event.data.type === \"mupag:payment_completed\") {\n const charge = event.data.charge ?? event.data.payload?.charge ?? ({ status: \"paid\", ...event.data.payload } as Charge);\n this.active.callbacks.onSuccess?.(charge);\n this.close();\n return;\n }\n if (event.data.type === \"mupag:close\") {\n this.active.callbacks.onClose?.();\n this.close();\n return;\n }\n if (event.data.type === \"mupag:error\") {\n this.active.callbacks.onError?.(event.data.error ?? event.data.payload ?? { code: \"checkout_error\", message: \"Checkout error.\" });\n }\n }\n}\n\nexport function initDataAttributes(root: ParentNode = document): void {\n const buttons = root.querySelectorAll<HTMLElement>(\"[data-mupag-widget]\");\n buttons.forEach((button) => {\n if (button.dataset[DATA_BOUND] === \"true\") {\n return;\n }\n button.dataset[DATA_BOUND] = \"true\";\n button.addEventListener(\"click\", () => {\n try {\n const options = dataOptions(button);\n const theme: MuPagTheme = {};\n if (button.dataset.primaryColor) {\n theme.primaryColor = button.dataset.primaryColor;\n }\n if (button.dataset.accentColor) {\n theme.accentColor = button.dataset.accentColor;\n }\n if (button.dataset.fontFamily) {\n theme.fontFamily = button.dataset.fontFamily;\n }\n if (Object.keys(theme).length > 0) {\n options.theme = theme;\n }\n const mupag = new MuPag(options);\n void mupag.openCheckout(dataCheckout(button)).catch((error: unknown) => dispatchWidgetError(button, error));\n } catch (error) {\n dispatchWidgetError(button, error);\n }\n });\n });\n}\n\nfunction dispatchWidgetError(button: HTMLElement, error: unknown): void {\n button.dispatchEvent(\n new CustomEvent(\"mupag:error\", {\n detail: { code: \"checkout_failed\", message: safeErrorMessage(error) },\n }),\n );\n}\n\nfunction validateOptions(options: MuPagOptions): void {\n if (!options || (options.environment !== \"test\" && options.environment !== \"prd\")) {\n throw new Error(\"environment must be explicitly test or prd.\");\n }\n const expectedPrefix = options.environment === \"test\" ? \"pk_test_\" : \"pk_prd_\";\n if (\n typeof options.publishableKey !== \"string\" ||\n !options.publishableKey.startsWith(expectedPrefix) ||\n options.publishableKey.length > 512 ||\n !/^[\\x21-\\x7e]+$/.test(options.publishableKey)\n ) {\n throw new Error(\"publishableKey is invalid or does not match the selected environment.\");\n }\n boundedInteger(options.iframeLoadTimeoutMs, 1, 120_000, \"iframeLoadTimeoutMs\");\n boundedInteger(options.requestTimeoutMs, 1, 120_000, \"requestTimeoutMs\");\n boundedInteger(options.maxResponseBytes, 1, 4 * 1024 * 1024, \"maxResponseBytes\");\n validateTheme(options.theme);\n}\n\nfunction allowedOrigin(value: string, canonical: string, environment: MuPagEnvironment, field: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${field} is invalid.`);\n }\n const loopback = environment === \"test\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n const isCanonical = url.origin === new URL(canonical).origin;\n const explicitCheckoutDomain = field === \"checkoutBaseUrl\" && url.protocol === \"https:\" && !isIpAddress(url.hostname);\n if (\n (!isCanonical && !loopback && !explicitCheckoutDomain) ||\n (url.protocol !== \"https:\" && !(loopback && url.protocol === \"http:\")) ||\n url.username ||\n url.password ||\n (url.pathname !== \"\" && url.pathname !== \"/\") ||\n url.search ||\n url.hash\n ) {\n throw new Error(`${field} is not an allowed origin.`);\n }\n return trimSlash(url.origin);\n}\n\nfunction isIpAddress(hostname: string): boolean {\n return /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(hostname) || hostname.includes(\":\");\n}\n\nfunction validateCheckout(body: Omit<CheckoutParams, keyof MuPagCallbacks | \"idempotencyKey\">, environment: MuPagEnvironment): void {\n onlyKeys(\n body,\n [\n \"items\",\n \"success_url\",\n \"cancel_url\",\n \"customer_id\",\n \"customer_data\",\n \"allowed_payment_methods\",\n \"affiliate_code\",\n \"coupon_id\",\n \"utm_params\",\n \"expires_in_minutes\",\n \"metadata\",\n \"collect_shipping_address\",\n \"delivery_type\",\n \"allow_coupons\",\n ],\n \"checkout\",\n );\n if (!Array.isArray(body.items) || body.items.length < 1 || body.items.length > 100) {\n throw new Error(\"Checkout items must contain between 1 and 100 entries.\");\n }\n let total = 0;\n for (const item of body.items) {\n onlyKeys(item, [\"name\", \"quantity\", \"unit_amount_cents\"], \"checkout item\");\n text(item.name, 200, \"item.name\");\n rejectPANLikeOptionalText(item.name, \"item.name\");\n integer(item.quantity, 1, 1_000_000, \"item.quantity\");\n integer(item.unit_amount_cents, 100, MAX_MONEY_CENTS, \"item.unit_amount_cents\");\n const lineTotal = item.quantity * item.unit_amount_cents;\n if (!Number.isSafeInteger(lineTotal) || lineTotal > MAX_MONEY_CENTS) {\n throw new Error(\"Checkout item total is outside the supported range.\");\n }\n total += lineTotal;\n if (!Number.isSafeInteger(total) || total > MAX_MONEY_CENTS) {\n throw new Error(\"Checkout total is outside the supported range.\");\n }\n }\n redirectUrl(body.success_url, environment, \"success_url\");\n redirectUrl(body.cancel_url, environment, \"cancel_url\");\n if (body.customer_id !== undefined && body.customer_data !== undefined) {\n throw new Error(\"customer_id and customer_data are mutually exclusive.\");\n }\n if (body.customer_id !== undefined && !uuid(body.customer_id)) {\n throw new Error(\"customer_id must be a UUID.\");\n }\n rejectPANLikeOptionalText(body.customer_id, \"customer_id\");\n if (body.customer_data !== undefined) {\n onlyKeys(body.customer_data, [\"name\", \"email\", \"document\", \"phone\"], \"customer_data\");\n optionalText(body.customer_data.name, 200, \"customer_data.name\");\n rejectPANLikeOptionalText(body.customer_data.name, \"customer_data.name\");\n optionalText(body.customer_data.email, 320, \"customer_data.email\");\n rejectPANLikeOptionalText(body.customer_data.email, \"customer_data.email\");\n optionalText(body.customer_data.document, 64, \"customer_data.document\");\n optionalText(body.customer_data.phone, 32, \"customer_data.phone\");\n }\n if (\n body.allowed_payment_methods !== undefined &&\n (!Array.isArray(body.allowed_payment_methods) ||\n body.allowed_payment_methods.length < 1 ||\n body.allowed_payment_methods.length > 2 ||\n new Set(body.allowed_payment_methods).size !== body.allowed_payment_methods.length ||\n body.allowed_payment_methods.some((method) => method !== \"pix\" && method !== \"credit_card\"))\n ) {\n throw new Error(\"allowed_payment_methods is invalid.\");\n }\n optionalText(body.affiliate_code, 128, \"affiliate_code\");\n rejectPANLikeOptionalText(body.affiliate_code, \"affiliate_code\");\n if (body.coupon_id !== undefined && !uuid(body.coupon_id)) throw new Error(\"coupon_id must be a UUID.\");\n if (body.allow_coupons === false && body.coupon_id !== undefined) {\n throw new Error(\"coupon_id cannot be used when allow_coupons is false.\");\n }\n if (body.expires_in_minutes !== undefined) integer(body.expires_in_minutes, 1, 24 * 60, \"expires_in_minutes\");\n if (body.metadata !== undefined) jsonObject(body.metadata, \"metadata\");\n if (body.utm_params !== undefined) jsonObject(body.utm_params, \"utm_params\");\n optionalText(body.delivery_type, 64, \"delivery_type\");\n rejectPANLikeOptionalText(body.delivery_type, \"delivery_type\");\n optionalBoolean(body.collect_shipping_address, \"collect_shipping_address\");\n optionalBoolean(body.allow_coupons, \"allow_coupons\");\n}\n\nfunction onlyKeys(value: unknown, allowed: readonly string[], field: string): asserts value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {\n throw new Error(`${field} must be a plain object.`);\n }\n const allowlist = new Set(allowed);\n const unsupported = Object.keys(value).find((key) => !allowlist.has(key));\n if (unsupported !== undefined) {\n throw new Error(`${field} contains unsupported field ${unsupported}.`);\n }\n}\n\nfunction jsonObject(value: object, field: string): void {\n if (value === null || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {\n throw new Error(`${field} must be a plain JSON object.`);\n }\n const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];\n const seen = new WeakSet<object>();\n let nodes = 0;\n while (stack.length > 0) {\n const current = stack.pop();\n if (!current) break;\n nodes += 1;\n if (nodes > 10_000 || current.depth > 32) throw new Error(`${field} is too complex.`);\n if (current.value === null || typeof current.value === \"boolean\") continue;\n if (typeof current.value === \"string\") {\n if (containsPANLikeSequence(current.value)) throw new Error(`${field} contains a possible card number.`);\n continue;\n }\n if (typeof current.value === \"number\") {\n if (!Number.isFinite(current.value)) throw new Error(`${field} contains an invalid number.`);\n if (containsPANLikeSequence(JSON.stringify(current.value))) {\n throw new Error(`${field} contains a possible card number.`);\n }\n continue;\n }\n if (typeof current.value !== \"object\") throw new Error(`${field} contains a non-JSON value.`);\n if (seen.has(current.value)) throw new Error(`${field} contains a cycle.`);\n seen.add(current.value);\n for (const [key, child] of Object.entries(current.value)) {\n if (containsPANLikeSequence(key)) {\n throw new Error(`${field} contains a possible card number.`);\n }\n const normalized = key.toLowerCase();\n const compact = normalized.replace(/[^a-z0-9]/g, \"\");\n const sensitiveBase = compact\n .replace(/[0-9]+$/, \"\")\n .replace(/(cvv|cvc|csc|cid|cav)[0-9]+/g, \"$1\");\n if (\n [\"__proto__\", \"prototype\", \"constructor\"].includes(normalized)\n || [\"pan\", \"cardnumber\"].includes(compact)\n || [\"cvv\", \"cvc\", \"cav\"].some((token) =>\n [\"\", \"value\", \"code\", \"number\"].some((descriptor) => sensitiveBase.endsWith(token + descriptor))\n )\n || [\"csc\", \"cid\"].some((token) =>\n [\"\", \"value\", \"code\", \"number\"].some(\n (descriptor) =>\n sensitiveBase === token + descriptor\n || [\"card\", \"amex\", \"americanexpress\"].some((qualifier) =>\n sensitiveBase.endsWith(qualifier + token + descriptor)\n )\n )\n )\n || sensitiveBase.endsWith(\"cardidentificationnumber\")\n || sensitiveBase.endsWith(\"cardsecuritynumber\")\n || [\n \"securitycode\",\n \"securityvalue\",\n \"verificationcode\",\n \"verificationnumber\",\n \"verificationvalue\",\n ].some((suffix) => sensitiveBase.endsWith(suffix))\n ) {\n throw new Error(`${field} contains a forbidden field.`);\n }\n stack.push({ value: child, depth: current.depth + 1 });\n }\n }\n}\n\nfunction containsPANLikeSequence(value: string): boolean {\n let retainedDigits = \"\";\n\n for (const character of value) {\n if (character >= \"0\" && character <= \"9\") {\n retainedDigits = (retainedDigits + character).slice(-19);\n for (let length = 12; length <= retainedDigits.length; length += 1) {\n if (validPANSequence(retainedDigits.slice(-length))) return true;\n }\n } else if (/^\\p{Nd}$/u.test(character)) {\n return true;\n } else if (/^[\\s\\p{P}\\p{S}\\p{M}\\p{Cc}\\p{Cf}]$/u.test(character)) {\n continue;\n } else {\n retainedDigits = \"\";\n }\n }\n return false;\n}\n\nfunction rejectPANLikeOptionalText(value: unknown, field: string): void {\n if (value !== undefined && (typeof value !== \"string\" || containsPANLikeSequence(value))) {\n throw new Error(`${field} contains a possible card number.`);\n }\n}\n\nfunction validPANSequence(digits: string): boolean {\n if (!/^[0-9]{12,19}$/.test(digits)) return false;\n let sum = 0;\n let doubleDigit = false;\n for (let index = digits.length - 1; index >= 0; index -= 1) {\n let digit = digits.charCodeAt(index) - 48;\n if (doubleDigit) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n sum += digit;\n doubleDigit = !doubleDigit;\n }\n return sum % 10 === 0;\n}\n\nfunction redirectUrl(value: string, environment: MuPagEnvironment, field: string): void {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${field} must be an absolute URL.`);\n }\n const loopback = environment === \"test\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n if ((url.protocol !== \"https:\" && !(loopback && url.protocol === \"http:\")) || url.username || url.password || value.length > 2048) {\n throw new Error(`${field} must be a safe HTTPS URL.`);\n }\n}\n\nfunction checkoutResponse(value: unknown): { id: string; url: string; expires_at: string } {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Invalid checkout response.\");\n const response = value as Record<string, unknown>;\n if (!uuid(response.id) || typeof response.url !== \"string\" || typeof response.expires_at !== \"string\") {\n throw new Error(\"Invalid checkout response.\");\n }\n if (Number.isNaN(Date.parse(response.expires_at))) throw new Error(\"Invalid checkout response.\");\n return { id: response.id, url: response.url, expires_at: response.expires_at };\n}\n\nfunction safeCheckoutUrl(value: string, sessionId: string, baseUrl: string): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(\"Invalid checkout URL in API response.\");\n }\n if (\n url.origin !== new URL(baseUrl).origin ||\n url.username ||\n url.password ||\n url.protocol !== new URL(baseUrl).protocol ||\n url.pathname !== `/c/${sessionId}` ||\n url.search ||\n url.hash\n ) {\n throw new Error(\"Invalid checkout URL in API response.\");\n }\n return url;\n}\n\nasync function readBoundedJson(response: Response, maximumBytes: number): Promise<unknown> {\n const length = response.headers.get(\"content-length\");\n if (length !== null && (!/^\\d+$/.test(length) || Number(length) > maximumBytes)) {\n throw new Error(\"Checkout response exceeds the configured limit.\");\n }\n if (!response.body) return undefined;\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n total += value.byteLength;\n if (total > maximumBytes) {\n await reader.cancel(\"response limit exceeded\");\n throw new Error(\"Checkout response exceeds the configured limit.\");\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n const buffer = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n const textBody = new TextDecoder().decode(buffer);\n if (textBody.trim().length === 0) return undefined;\n try {\n return JSON.parse(textBody) as unknown;\n } catch {\n throw new Error(\"Checkout response is not valid JSON.\");\n }\n}\n\nfunction createIdempotencyKey(): string {\n const cryptoApi = globalThis.crypto;\n if (typeof cryptoApi?.randomUUID === \"function\") return `widget_${cryptoApi.randomUUID()}`;\n if (typeof cryptoApi?.getRandomValues !== \"function\") {\n throw new Error(\"A secure random generator is required to create an Idempotency-Key.\");\n }\n const bytes = new Uint8Array(16);\n cryptoApi.getRandomValues(bytes);\n return `widget_${Array.from(bytes, (entry) => entry.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction validateIdempotencyKey(value: string): string {\n if (value.length < 1 || value.length > 128 || !/^[\\x21-\\x7e]+$/.test(value)) {\n throw new Error(\"idempotencyKey must contain 1-128 visible ASCII characters.\");\n }\n return value;\n}\n\nfunction dataOptions(button: HTMLElement): MuPagOptions {\n return {\n environment: button.dataset.environment as MuPagEnvironment,\n publishableKey: button.dataset.publishableKey ?? \"\",\n ...(button.dataset.checkoutBaseUrl ? { checkoutBaseUrl: button.dataset.checkoutBaseUrl } : {}),\n ...(button.dataset.apiBaseUrl ? { apiBaseUrl: button.dataset.apiBaseUrl } : {}),\n ...(button.dataset.locale ? { locale: button.dataset.locale as MuPagLocale | \"auto\" } : {}),\n };\n}\n\nfunction dataCheckout(button: HTMLElement): CheckoutParams {\n return {\n items: [\n {\n name: button.dataset.itemName ?? \"\",\n quantity: Number(button.dataset.quantity ?? \"1\"),\n unit_amount_cents: Number(button.dataset.unitAmountCents ?? \"\"),\n },\n ],\n success_url: button.dataset.successUrl ?? \"\",\n cancel_url: button.dataset.cancelUrl ?? \"\",\n };\n}\n\nfunction validateTheme(theme: MuPagTheme | undefined): void {\n if (!theme) return;\n if (theme.primaryColor !== undefined && (!cssSupports(\"color\", theme.primaryColor) || /url\\s*\\(/i.test(theme.primaryColor))) {\n throw new Error(\"theme.primaryColor is invalid.\");\n }\n if (theme.accentColor !== undefined && (!cssSupports(\"color\", theme.accentColor) || /url\\s*\\(/i.test(theme.accentColor))) {\n throw new Error(\"theme.accentColor is invalid.\");\n }\n if (theme.borderRadius !== undefined && (!cssSupports(\"border-radius\", theme.borderRadius) || /url\\s*\\(/i.test(theme.borderRadius))) {\n throw new Error(\"theme.borderRadius is invalid.\");\n }\n if (theme.fontFamily !== undefined && !/^[A-Za-z0-9 ,_'\"-]{1,200}$/.test(theme.fontFamily)) {\n throw new Error(\"theme.fontFamily is invalid.\");\n }\n}\n\nfunction cssSupports(property: string, value: string): boolean {\n return typeof globalThis.CSS?.supports === \"function\" && globalThis.CSS.supports(property, value);\n}\n\nfunction boundedInteger(value: number | undefined, minimum: number, maximum: number, field: string): void {\n if (value !== undefined) integer(value, minimum, maximum, field);\n}\n\nfunction integer(value: number, minimum: number, maximum: number, field: string): void {\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw new Error(`${field} is invalid.`);\n}\n\nfunction text(value: unknown, maximum: number, field: string): void {\n if (typeof value !== \"string\" || value.trim().length < 1 || value.length > maximum || /[\\x00-\\x1f\\x7f]/.test(value)) {\n throw new Error(`${field} is invalid.`);\n }\n}\n\nfunction optionalText(value: unknown, maximum: number, field: string): void {\n if (value !== undefined) text(value, maximum, field);\n}\n\nfunction optionalBoolean(value: boolean | undefined, field: string): void {\n if (value !== undefined && typeof value !== \"boolean\") throw new Error(`${field} is invalid.`);\n}\n\nfunction uuid(value: unknown): value is string {\n return typeof value === \"string\" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);\n}\n\nfunction safeErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : \"Checkout failed.\";\n return message.replace(/[\\r\\n\\t]+/g, \" \").slice(0, 256);\n}\n\nexport const version = VERSION;\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
type MuPagLocale = "pt-BR" | "en-US";
|
|
2
|
+
type MuPagEnvironment = "test" | "prd";
|
|
3
|
+
interface MuPagTheme {
|
|
4
|
+
primaryColor?: string;
|
|
5
|
+
accentColor?: string;
|
|
6
|
+
fontFamily?: string;
|
|
7
|
+
borderRadius?: string;
|
|
8
|
+
}
|
|
9
|
+
interface MuPagOptions {
|
|
10
|
+
environment: MuPagEnvironment;
|
|
11
|
+
publishableKey: string;
|
|
12
|
+
checkoutBaseUrl?: string;
|
|
13
|
+
apiBaseUrl?: string;
|
|
14
|
+
fetch?: typeof globalThis.fetch;
|
|
15
|
+
locale?: MuPagLocale | "auto";
|
|
16
|
+
theme?: MuPagTheme;
|
|
17
|
+
fallbackRedirect?: boolean;
|
|
18
|
+
iframeLoadTimeoutMs?: number;
|
|
19
|
+
requestTimeoutMs?: number;
|
|
20
|
+
maxResponseBytes?: number;
|
|
21
|
+
}
|
|
22
|
+
interface CheckoutItem {
|
|
23
|
+
name: string;
|
|
24
|
+
quantity: number;
|
|
25
|
+
unit_amount_cents: number;
|
|
26
|
+
}
|
|
27
|
+
interface CheckoutCustomer {
|
|
28
|
+
email?: string;
|
|
29
|
+
name?: string;
|
|
30
|
+
document?: string;
|
|
31
|
+
phone?: string;
|
|
32
|
+
}
|
|
33
|
+
interface Charge {
|
|
34
|
+
id?: string;
|
|
35
|
+
charge_id?: string;
|
|
36
|
+
status: string;
|
|
37
|
+
amount_total_cents?: number;
|
|
38
|
+
currency?: string;
|
|
39
|
+
[key: string]: unknown;
|
|
40
|
+
}
|
|
41
|
+
interface CheckoutParams extends MuPagCallbacks {
|
|
42
|
+
items: CheckoutItem[];
|
|
43
|
+
success_url: string;
|
|
44
|
+
cancel_url: string;
|
|
45
|
+
customer_id?: string;
|
|
46
|
+
customer_data?: CheckoutCustomer;
|
|
47
|
+
allowed_payment_methods?: Array<"pix" | "credit_card">;
|
|
48
|
+
affiliate_code?: string;
|
|
49
|
+
coupon_id?: string;
|
|
50
|
+
utm_params?: Record<string, unknown>;
|
|
51
|
+
expires_in_minutes?: number;
|
|
52
|
+
metadata?: Record<string, unknown>;
|
|
53
|
+
collect_shipping_address?: boolean;
|
|
54
|
+
delivery_type?: string;
|
|
55
|
+
allow_coupons?: boolean;
|
|
56
|
+
idempotencyKey?: string;
|
|
57
|
+
}
|
|
58
|
+
interface MuPagCallbacks {
|
|
59
|
+
onSuccess?: (charge: Charge) => void;
|
|
60
|
+
onClose?: () => void;
|
|
61
|
+
onError?: (error: MuPagWidgetError) => void;
|
|
62
|
+
}
|
|
63
|
+
interface MuPagWidgetError {
|
|
64
|
+
code: string;
|
|
65
|
+
message: string;
|
|
66
|
+
detail?: unknown;
|
|
67
|
+
}
|
|
68
|
+
type MuPagMessage = {
|
|
69
|
+
type: "mupag:loaded";
|
|
70
|
+
} | {
|
|
71
|
+
type: "mupag:payment_completed";
|
|
72
|
+
charge?: Charge;
|
|
73
|
+
payload?: {
|
|
74
|
+
charge?: Charge;
|
|
75
|
+
session_id?: string;
|
|
76
|
+
};
|
|
77
|
+
} | {
|
|
78
|
+
type: "mupag:close";
|
|
79
|
+
} | {
|
|
80
|
+
type: "mupag:error";
|
|
81
|
+
error?: MuPagWidgetError;
|
|
82
|
+
payload?: MuPagWidgetError;
|
|
83
|
+
};
|
|
84
|
+
interface MuPagWidgetNamespace {
|
|
85
|
+
MuPag: typeof MuPag;
|
|
86
|
+
init: typeof initDataAttributes;
|
|
87
|
+
version: string;
|
|
88
|
+
}
|
|
89
|
+
declare global {
|
|
90
|
+
interface Window {
|
|
91
|
+
MuPagWidget?: MuPagWidgetNamespace;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
declare class MuPag {
|
|
96
|
+
private readonly options;
|
|
97
|
+
private active;
|
|
98
|
+
constructor(options: MuPagOptions);
|
|
99
|
+
openCheckout(params: CheckoutParams): Promise<void>;
|
|
100
|
+
close(): void;
|
|
101
|
+
private openUrl;
|
|
102
|
+
private handleMessage;
|
|
103
|
+
}
|
|
104
|
+
declare function initDataAttributes(root?: ParentNode): void;
|
|
105
|
+
declare const version = "0.1.0";
|
|
106
|
+
|
|
107
|
+
export { type Charge, type CheckoutCustomer, type CheckoutItem, type CheckoutParams, MuPag, type MuPagCallbacks, type MuPagEnvironment, type MuPagLocale, type MuPagMessage, type MuPagOptions, type MuPagTheme, type MuPagWidgetError, initDataAttributes, version };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
type MuPagLocale = "pt-BR" | "en-US";
|
|
2
|
+
type MuPagEnvironment = "test" | "prd";
|
|
3
|
+
interface MuPagTheme {
|
|
4
|
+
primaryColor?: string;
|
|
5
|
+
accentColor?: string;
|
|
6
|
+
fontFamily?: string;
|
|
7
|
+
borderRadius?: string;
|
|
8
|
+
}
|
|
9
|
+
interface MuPagOptions {
|
|
10
|
+
environment: MuPagEnvironment;
|
|
11
|
+
publishableKey: string;
|
|
12
|
+
checkoutBaseUrl?: string;
|
|
13
|
+
apiBaseUrl?: string;
|
|
14
|
+
fetch?: typeof globalThis.fetch;
|
|
15
|
+
locale?: MuPagLocale | "auto";
|
|
16
|
+
theme?: MuPagTheme;
|
|
17
|
+
fallbackRedirect?: boolean;
|
|
18
|
+
iframeLoadTimeoutMs?: number;
|
|
19
|
+
requestTimeoutMs?: number;
|
|
20
|
+
maxResponseBytes?: number;
|
|
21
|
+
}
|
|
22
|
+
interface CheckoutItem {
|
|
23
|
+
name: string;
|
|
24
|
+
quantity: number;
|
|
25
|
+
unit_amount_cents: number;
|
|
26
|
+
}
|
|
27
|
+
interface CheckoutCustomer {
|
|
28
|
+
email?: string;
|
|
29
|
+
name?: string;
|
|
30
|
+
document?: string;
|
|
31
|
+
phone?: string;
|
|
32
|
+
}
|
|
33
|
+
interface Charge {
|
|
34
|
+
id?: string;
|
|
35
|
+
charge_id?: string;
|
|
36
|
+
status: string;
|
|
37
|
+
amount_total_cents?: number;
|
|
38
|
+
currency?: string;
|
|
39
|
+
[key: string]: unknown;
|
|
40
|
+
}
|
|
41
|
+
interface CheckoutParams extends MuPagCallbacks {
|
|
42
|
+
items: CheckoutItem[];
|
|
43
|
+
success_url: string;
|
|
44
|
+
cancel_url: string;
|
|
45
|
+
customer_id?: string;
|
|
46
|
+
customer_data?: CheckoutCustomer;
|
|
47
|
+
allowed_payment_methods?: Array<"pix" | "credit_card">;
|
|
48
|
+
affiliate_code?: string;
|
|
49
|
+
coupon_id?: string;
|
|
50
|
+
utm_params?: Record<string, unknown>;
|
|
51
|
+
expires_in_minutes?: number;
|
|
52
|
+
metadata?: Record<string, unknown>;
|
|
53
|
+
collect_shipping_address?: boolean;
|
|
54
|
+
delivery_type?: string;
|
|
55
|
+
allow_coupons?: boolean;
|
|
56
|
+
idempotencyKey?: string;
|
|
57
|
+
}
|
|
58
|
+
interface MuPagCallbacks {
|
|
59
|
+
onSuccess?: (charge: Charge) => void;
|
|
60
|
+
onClose?: () => void;
|
|
61
|
+
onError?: (error: MuPagWidgetError) => void;
|
|
62
|
+
}
|
|
63
|
+
interface MuPagWidgetError {
|
|
64
|
+
code: string;
|
|
65
|
+
message: string;
|
|
66
|
+
detail?: unknown;
|
|
67
|
+
}
|
|
68
|
+
type MuPagMessage = {
|
|
69
|
+
type: "mupag:loaded";
|
|
70
|
+
} | {
|
|
71
|
+
type: "mupag:payment_completed";
|
|
72
|
+
charge?: Charge;
|
|
73
|
+
payload?: {
|
|
74
|
+
charge?: Charge;
|
|
75
|
+
session_id?: string;
|
|
76
|
+
};
|
|
77
|
+
} | {
|
|
78
|
+
type: "mupag:close";
|
|
79
|
+
} | {
|
|
80
|
+
type: "mupag:error";
|
|
81
|
+
error?: MuPagWidgetError;
|
|
82
|
+
payload?: MuPagWidgetError;
|
|
83
|
+
};
|
|
84
|
+
interface MuPagWidgetNamespace {
|
|
85
|
+
MuPag: typeof MuPag;
|
|
86
|
+
init: typeof initDataAttributes;
|
|
87
|
+
version: string;
|
|
88
|
+
}
|
|
89
|
+
declare global {
|
|
90
|
+
interface Window {
|
|
91
|
+
MuPagWidget?: MuPagWidgetNamespace;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
declare class MuPag {
|
|
96
|
+
private readonly options;
|
|
97
|
+
private active;
|
|
98
|
+
constructor(options: MuPagOptions);
|
|
99
|
+
openCheckout(params: CheckoutParams): Promise<void>;
|
|
100
|
+
close(): void;
|
|
101
|
+
private openUrl;
|
|
102
|
+
private handleMessage;
|
|
103
|
+
}
|
|
104
|
+
declare function initDataAttributes(root?: ParentNode): void;
|
|
105
|
+
declare const version = "0.1.0";
|
|
106
|
+
|
|
107
|
+
export { type Charge, type CheckoutCustomer, type CheckoutItem, type CheckoutParams, MuPag, type MuPagCallbacks, type MuPagEnvironment, type MuPagLocale, type MuPagMessage, type MuPagOptions, type MuPagTheme, type MuPagWidgetError, initDataAttributes, version };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
var q="0.1.0",T={test:"https://api.sandbox.mupag.com.br",prd:"https://api.mupag.com.br"},A={test:"https://checkout.sandbox.mupag.com.br",prd:"https://checkout.mupag.com.br"},K=8e3,F=15e3,W=256*1024,D=1024*1024,E=9e15,L="mupagWidgetBound";function H(e){return e.replace(/\/+$/,"")}function J(e){return e==="pt-BR"||e==="en-US"?e:typeof navigator!="undefined"&&navigator.language.toLowerCase().startsWith("en")?"en-US":"pt-BR"}function z(e,t){var r;let n=J(t.locale);return e.searchParams.set("locale",n),t.theme&&Object.keys(t.theme).length>0&&e.searchParams.set("theme",JSON.stringify(t.theme)),typeof window!="undefined"&&((r=window.location)!=null&&r.origin)&&e.searchParams.set("parent_origin",window.location.origin),e}function V(e,t,n){var p,w,y;let r=document.createElement("div");r.dataset.mupagWidgetRoot="true";let o=r.attachShadow({mode:"open"}),a=document.createElement("div");a.setAttribute("part","overlay");let i=document.createElement("section");i.setAttribute("part","dialog"),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-label","Checkout seguro MuPag");let c=document.createElement("button");c.type="button",c.textContent="Fechar",c.setAttribute("part","close"),c.addEventListener("click",n);let s=document.createElement("iframe");s.src=e,s.title="Checkout seguro MuPag",s.allow="payment *",s.referrerPolicy="strict-origin-when-cross-origin",s.setAttribute("part","iframe"),s.setAttribute("loading","eager"),s.setAttribute("sandbox","allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.append(c,s),a.append(i);let l=(p=t==null?void 0:t.primaryColor)!=null?p:"#176bff",u=(w=t==null?void 0:t.borderRadius)!=null?w:"18px",m=(y=t==null?void 0:t.fontFamily)!=null?y:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif",d=`
|
|
2
|
+
:host{all:initial;--gw-primary:${l};--gw-radius:${u};font-family:${m}}
|
|
3
|
+
[part=overlay]{position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(10,18,32,.54);padding:24px}
|
|
4
|
+
[part=dialog]{position:relative;width:min(100%,760px);height:min(92vh,860px);overflow:hidden;border-radius:var(--gw-radius);background:#fff;box-shadow:0 24px 80px rgba(10,18,32,.28)}
|
|
5
|
+
[part=close]{position:absolute;right:12px;top:10px;z-index:2;border:1px solid rgba(15,23,42,.16);border-radius:999px;background:#fff;color:#243044;font:600 13px/1.2 inherit;padding:8px 12px;cursor:pointer}
|
|
6
|
+
[part=close]:focus{outline:3px solid color-mix(in srgb,var(--gw-primary) 35%,transparent);outline-offset:2px}
|
|
7
|
+
[part=iframe]{display:block;width:100%;height:100%;border:0;background:#fff}
|
|
8
|
+
@media (max-width:640px){[part=overlay]{align-items:stretch;padding:0;background:#fff}[part=dialog]{width:100%;height:100vh;max-height:none;border-radius:0;box-shadow:none}[part=close]{right:10px;top:8px}}
|
|
9
|
+
`;if("adoptedStyleSheets"in o&&"CSSStyleSheet"in window){let h=new CSSStyleSheet;h.replaceSync(d),o.adoptedStyleSheets=[h],o.append(a);}else {let h=document.createElement("style");h.textContent=d,o.append(h,a);}return document.body.append(r),{host:r,iframe:s}}function X(e){return !e||typeof e!="object"||!("type"in e)||typeof e.type!="string"?false:["mupag:loaded","mupag:payment_completed","mupag:close","mupag:error"].includes(e.type)}var U=class{constructor(t){this.active=null;var n,r,o,a,i,c,s;Y(t),this.options={...t,checkoutBaseUrl:O((n=t.checkoutBaseUrl)!=null?n:A[t.environment],A[t.environment],t.environment,"checkoutBaseUrl"),apiBaseUrl:O((r=t.apiBaseUrl)!=null?r:T[t.environment],T[t.environment],t.environment,"apiBaseUrl"),fetch:(o=t.fetch)!=null?o:globalThis.fetch.bind(globalThis),fallbackRedirect:(a=t.fallbackRedirect)!=null?a:true,iframeLoadTimeoutMs:(i=t.iframeLoadTimeoutMs)!=null?i:K,requestTimeoutMs:(c=t.requestTimeoutMs)!=null?c:F,maxResponseBytes:(s=t.maxResponseBytes)!=null?s:W},this.handleMessage=this.handleMessage.bind(this);}async openCheckout(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Checkout params must be an object.");let{onSuccess:n,onClose:r,onError:o,idempotencyKey:a,...i}=t;B(i,this.options.environment);let c,s;try{c=JSON.stringify(i),s=JSON.parse(c);}catch(v){throw new Error("Checkout payload must be valid JSON.")}if(B(s,this.options.environment),new TextEncoder().encode(c).byteLength>D)throw new Error("Checkout payload exceeds the safe 1 MiB limit.");let l=a===void 0?ne():re(a),u=new AbortController,m=window.setTimeout(()=>u.abort(),this.options.requestTimeoutMs),d;try{d=await this.options.fetch(`${this.options.apiBaseUrl}/v1/checkout-sessions`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.options.publishableKey}`,"Idempotency-Key":l},body:c,signal:u.signal});}catch(v){let S={code:"checkout_network_error",message:"Checkout session request failed."};throw o==null||o(S),new Error(S.message)}finally{window.clearTimeout(m);}let p=await te(d,this.options.maxResponseBytes);if(!d.ok){let v={code:"checkout_session_failed",message:`Checkout session failed (${d.status}).`};throw o==null||o(v),new Error(v.message)}let w=G(p),y=ee(w.url,w.id,this.options.checkoutBaseUrl),h=z(y,this.options),_={};n&&(_.onSuccess=n),r&&(_.onClose=r),o&&(_.onError=o),this.openUrl(h.toString(),_);}close(){this.active&&(this.active.loadTimer&&window.clearTimeout(this.active.loadTimer),window.removeEventListener("message",this.handleMessage),this.active.host.remove(),this.active=null);}openUrl(t,n){this.close();let r=new URL(t).origin,a={...V(t,this.options.theme,()=>{var i;(i=n.onClose)==null||i.call(n),this.close();}),checkoutOrigin:r,callbacks:n,fallbackUrl:t,loaded:false,loadTimer:void 0};a.iframe.addEventListener("load",()=>{a.loaded=true,a.loadTimer&&window.clearTimeout(a.loadTimer);}),a.loadTimer=window.setTimeout(()=>{!a.loaded&&this.options.fallbackRedirect&&window.location.assign(a.fallbackUrl);},this.options.iframeLoadTimeoutMs),this.active=a,window.addEventListener("message",this.handleMessage);}handleMessage(t){var n,r,o,a,i,c,s,l,u,m,d;if(!(!this.active||t.origin!==this.active.checkoutOrigin||t.source===null||this.active.iframe.contentWindow===null||t.source!==this.active.iframe.contentWindow||!X(t.data))){if(t.data.type==="mupag:loaded"){this.active.loaded=true;return}if(t.data.type==="mupag:payment_completed"){let p=(o=(r=t.data.charge)!=null?r:(n=t.data.payload)==null?void 0:n.charge)!=null?o:{status:"paid",...t.data.payload};(i=(a=this.active.callbacks).onSuccess)==null||i.call(a,p),this.close();return}if(t.data.type==="mupag:close"){(s=(c=this.active.callbacks).onClose)==null||s.call(c),this.close();return}t.data.type==="mupag:error"&&((d=(m=this.active.callbacks).onError)==null||d.call(m,(u=(l=t.data.error)!=null?l:t.data.payload)!=null?u:{code:"checkout_error",message:"Checkout error."}));}}};function ce(e=document){e.querySelectorAll("[data-mupag-widget]").forEach(n=>{n.dataset[L]!=="true"&&(n.dataset[L]="true",n.addEventListener("click",()=>{try{let r=oe(n),o={};n.dataset.primaryColor&&(o.primaryColor=n.dataset.primaryColor),n.dataset.accentColor&&(o.accentColor=n.dataset.accentColor),n.dataset.fontFamily&&(o.fontFamily=n.dataset.fontFamily),Object.keys(o).length>0&&(r.theme=o),new U(r).openCheckout(ae(n)).catch(i=>R(n,i));}catch(r){R(n,r);}}));});}function R(e,t){e.dispatchEvent(new CustomEvent("mupag:error",{detail:{code:"checkout_failed",message:se(t)}}));}function Y(e){if(!e||e.environment!=="test"&&e.environment!=="prd")throw new Error("environment must be explicitly test or prd.");let t=e.environment==="test"?"pk_test_":"pk_prd_";if(typeof e.publishableKey!="string"||!e.publishableKey.startsWith(t)||e.publishableKey.length>512||!/^[\x21-\x7e]+$/.test(e.publishableKey))throw new Error("publishableKey is invalid or does not match the selected environment.");C(e.iframeLoadTimeoutMs,1,12e4,"iframeLoadTimeoutMs"),C(e.requestTimeoutMs,1,12e4,"requestTimeoutMs"),C(e.maxResponseBytes,1,4*1024*1024,"maxResponseBytes"),ie(e.theme);}function O(e,t,n,r){let o;try{o=new URL(e);}catch(s){throw new Error(`${r} is invalid.`)}let a=n==="test"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname),i=o.origin===new URL(t).origin,c=r==="checkoutBaseUrl"&&o.protocol==="https:"&&!Q(o.hostname);if(!i&&!a&&!c||o.protocol!=="https:"&&!(a&&o.protocol==="http:")||o.username||o.password||o.pathname!==""&&o.pathname!=="/"||o.search||o.hash)throw new Error(`${r} is not an allowed origin.`);return H(o.origin)}function Q(e){return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)||e.includes(":")}function B(e,t){if(M(e,["items","success_url","cancel_url","customer_id","customer_data","allowed_payment_methods","affiliate_code","coupon_id","utm_params","expires_in_minutes","metadata","collect_shipping_address","delivery_type","allow_coupons"],"checkout"),!Array.isArray(e.items)||e.items.length<1||e.items.length>100)throw new Error("Checkout items must contain between 1 and 100 entries.");let n=0;for(let r of e.items){M(r,["name","quantity","unit_amount_cents"],"checkout item"),j(r.name,200,"item.name"),f(r.name,"item.name"),b(r.quantity,1,1e6,"item.quantity"),b(r.unit_amount_cents,100,E,"item.unit_amount_cents");let o=r.quantity*r.unit_amount_cents;if(!Number.isSafeInteger(o)||o>E)throw new Error("Checkout item total is outside the supported range.");if(n+=o,!Number.isSafeInteger(n)||n>E)throw new Error("Checkout total is outside the supported range.")}if(I(e.success_url,t,"success_url"),I(e.cancel_url,t,"cancel_url"),e.customer_id!==void 0&&e.customer_data!==void 0)throw new Error("customer_id and customer_data are mutually exclusive.");if(e.customer_id!==void 0&&!P(e.customer_id))throw new Error("customer_id must be a UUID.");if(f(e.customer_id,"customer_id"),e.customer_data!==void 0&&(M(e.customer_data,["name","email","document","phone"],"customer_data"),g(e.customer_data.name,200,"customer_data.name"),f(e.customer_data.name,"customer_data.name"),g(e.customer_data.email,320,"customer_data.email"),f(e.customer_data.email,"customer_data.email"),g(e.customer_data.document,64,"customer_data.document"),g(e.customer_data.phone,32,"customer_data.phone")),e.allowed_payment_methods!==void 0&&(!Array.isArray(e.allowed_payment_methods)||e.allowed_payment_methods.length<1||e.allowed_payment_methods.length>2||new Set(e.allowed_payment_methods).size!==e.allowed_payment_methods.length||e.allowed_payment_methods.some(r=>r!=="pix"&&r!=="credit_card")))throw new Error("allowed_payment_methods is invalid.");if(g(e.affiliate_code,128,"affiliate_code"),f(e.affiliate_code,"affiliate_code"),e.coupon_id!==void 0&&!P(e.coupon_id))throw new Error("coupon_id must be a UUID.");if(e.allow_coupons===false&&e.coupon_id!==void 0)throw new Error("coupon_id cannot be used when allow_coupons is false.");e.expires_in_minutes!==void 0&&b(e.expires_in_minutes,1,1440,"expires_in_minutes"),e.metadata!==void 0&&$(e.metadata,"metadata"),e.utm_params!==void 0&&$(e.utm_params,"utm_params"),g(e.delivery_type,64,"delivery_type"),f(e.delivery_type,"delivery_type"),N(e.collect_shipping_address,"collect_shipping_address"),N(e.allow_coupons,"allow_coupons");}function M(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new Error(`${n} must be a plain object.`);let r=new Set(t),o=Object.keys(e).find(a=>!r.has(a));if(o!==void 0)throw new Error(`${n} contains unsupported field ${o}.`)}function $(e,t){if(e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new Error(`${t} must be a plain JSON object.`);let n=[{value:e,depth:0}],r=new WeakSet,o=0;for(;n.length>0;){let a=n.pop();if(!a)break;if(o+=1,o>1e4||a.depth>32)throw new Error(`${t} is too complex.`);if(!(a.value===null||typeof a.value=="boolean")){if(typeof a.value=="string"){if(k(a.value))throw new Error(`${t} contains a possible card number.`);continue}if(typeof a.value=="number"){if(!Number.isFinite(a.value))throw new Error(`${t} contains an invalid number.`);if(k(JSON.stringify(a.value)))throw new Error(`${t} contains a possible card number.`);continue}if(typeof a.value!="object")throw new Error(`${t} contains a non-JSON value.`);if(r.has(a.value))throw new Error(`${t} contains a cycle.`);r.add(a.value);for(let[i,c]of Object.entries(a.value)){if(k(i))throw new Error(`${t} contains a possible card number.`);let s=i.toLowerCase(),l=s.replace(/[^a-z0-9]/g,""),u=l.replace(/[0-9]+$/,"").replace(/(cvv|cvc|csc|cid|cav)[0-9]+/g,"$1");if(["__proto__","prototype","constructor"].includes(s)||["pan","cardnumber"].includes(l)||["cvv","cvc","cav"].some(m=>["","value","code","number"].some(d=>u.endsWith(m+d)))||["csc","cid"].some(m=>["","value","code","number"].some(d=>u===m+d||["card","amex","americanexpress"].some(p=>u.endsWith(p+m+d))))||u.endsWith("cardidentificationnumber")||u.endsWith("cardsecuritynumber")||["securitycode","securityvalue","verificationcode","verificationnumber","verificationvalue"].some(m=>u.endsWith(m)))throw new Error(`${t} contains a forbidden field.`);n.push({value:c,depth:a.depth+1});}}}}function k(e){let t="";for(let n of e)if(n>="0"&&n<="9"){t=(t+n).slice(-19);for(let r=12;r<=t.length;r+=1)if(Z(t.slice(-r)))return true}else {if(/^\p{Nd}$/u.test(n))return true;if(/^[\s\p{P}\p{S}\p{M}\p{Cc}\p{Cf}]$/u.test(n))continue;t="";}return false}function f(e,t){if(e!==void 0&&(typeof e!="string"||k(e)))throw new Error(`${t} contains a possible card number.`)}function Z(e){if(!/^[0-9]{12,19}$/.test(e))return false;let t=0,n=false;for(let r=e.length-1;r>=0;r-=1){let o=e.charCodeAt(r)-48;n&&(o*=2,o>9&&(o-=9)),t+=o,n=!n;}return t%10===0}function I(e,t,n){let r;try{r=new URL(e);}catch(a){throw new Error(`${n} must be an absolute URL.`)}let o=t==="test"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(r.protocol!=="https:"&&!(o&&r.protocol==="http:")||r.username||r.password||e.length>2048)throw new Error(`${n} must be a safe HTTPS URL.`)}function G(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid checkout response.");let t=e;if(!P(t.id)||typeof t.url!="string"||typeof t.expires_at!="string")throw new Error("Invalid checkout response.");if(Number.isNaN(Date.parse(t.expires_at)))throw new Error("Invalid checkout response.");return {id:t.id,url:t.url,expires_at:t.expires_at}}function ee(e,t,n){let r;try{r=new URL(e);}catch(o){throw new Error("Invalid checkout URL in API response.")}if(r.origin!==new URL(n).origin||r.username||r.password||r.protocol!==new URL(n).protocol||r.pathname!==`/c/${t}`||r.search||r.hash)throw new Error("Invalid checkout URL in API response.");return r}async function te(e,t){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>t))throw new Error("Checkout response exceeds the configured limit.");if(!e.body)return;let r=e.body.getReader(),o=[],a=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(u){if(a+=u.byteLength,a>t)throw await r.cancel("response limit exceeded"),new Error("Checkout response exceeds the configured limit.");o.push(u);}}}finally{r.releaseLock();}let i=new Uint8Array(a),c=0;for(let l of o)i.set(l,c),c+=l.byteLength;let s=new TextDecoder().decode(i);if(s.trim().length!==0)try{return JSON.parse(s)}catch(l){throw new Error("Checkout response is not valid JSON.")}}function ne(){let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return `widget_${e.randomUUID()}`;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("A secure random generator is required to create an Idempotency-Key.");let t=new Uint8Array(16);return e.getRandomValues(t),`widget_${Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}`}function re(e){if(e.length<1||e.length>128||!/^[\x21-\x7e]+$/.test(e))throw new Error("idempotencyKey must contain 1-128 visible ASCII characters.");return e}function oe(e){var t;return {environment:e.dataset.environment,publishableKey:(t=e.dataset.publishableKey)!=null?t:"",...e.dataset.checkoutBaseUrl?{checkoutBaseUrl:e.dataset.checkoutBaseUrl}:{},...e.dataset.apiBaseUrl?{apiBaseUrl:e.dataset.apiBaseUrl}:{},...e.dataset.locale?{locale:e.dataset.locale}:{}}}function ae(e){var t,n,r,o,a;return {items:[{name:(t=e.dataset.itemName)!=null?t:"",quantity:Number((n=e.dataset.quantity)!=null?n:"1"),unit_amount_cents:Number((r=e.dataset.unitAmountCents)!=null?r:"")}],success_url:(o=e.dataset.successUrl)!=null?o:"",cancel_url:(a=e.dataset.cancelUrl)!=null?a:""}}function ie(e){if(e){if(e.primaryColor!==void 0&&(!x("color",e.primaryColor)||/url\s*\(/i.test(e.primaryColor)))throw new Error("theme.primaryColor is invalid.");if(e.accentColor!==void 0&&(!x("color",e.accentColor)||/url\s*\(/i.test(e.accentColor)))throw new Error("theme.accentColor is invalid.");if(e.borderRadius!==void 0&&(!x("border-radius",e.borderRadius)||/url\s*\(/i.test(e.borderRadius)))throw new Error("theme.borderRadius is invalid.");if(e.fontFamily!==void 0&&!/^[A-Za-z0-9 ,_'"-]{1,200}$/.test(e.fontFamily))throw new Error("theme.fontFamily is invalid.")}}function x(e,t){var n;return typeof((n=globalThis.CSS)==null?void 0:n.supports)=="function"&&globalThis.CSS.supports(e,t)}function C(e,t,n,r){e!==void 0&&b(e,t,n,r);}function b(e,t,n,r){if(!Number.isSafeInteger(e)||e<t||e>n)throw new Error(`${r} is invalid.`)}function j(e,t,n){if(typeof e!="string"||e.trim().length<1||e.length>t||/[\x00-\x1f\x7f]/.test(e))throw new Error(`${n} is invalid.`)}function g(e,t,n){e!==void 0&&j(e,t,n);}function N(e,t){if(e!==void 0&&typeof e!="boolean")throw new Error(`${t} is invalid.`)}function P(e){return typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function se(e){return (e instanceof Error?e.message:"Checkout failed.").replace(/[\r\n\t]+/g," ").slice(0,256)}var ue=q;export{U as MuPag,ce as initDataAttributes,ue as version};//# sourceMappingURL=index.js.map
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["VERSION","API_BASE_URLS","CHECKOUT_BASE_URLS","DEFAULT_IFRAME_TIMEOUT_MS","DEFAULT_REQUEST_TIMEOUT_MS","DEFAULT_MAX_RESPONSE_BYTES","MAX_REQUEST_BYTES","MAX_MONEY_CENTS","DATA_BOUND","trimSlash","value","resolveLocale","locale","appendWidgetParams","url","options","_a","createModal","theme","onClose","_b","_c","host","root","overlay","dialog","close","iframe","primary","radius","font","css","sheet","style","isMuPagMessage","data","MuPag","_d","_e","_f","_g","validateOptions","allowedOrigin","params","onSuccess","onError","idempotencyKey","body","validateCheckout","encodedBody","canonicalBody","e","key","createIdempotencyKey","validateIdempotencyKey","controller","timer","response","error","responseBody","readBoundedJson","payload","checkoutResponse","checkoutUrl","safeCheckoutUrl","callbacks","checkoutOrigin","active","event","_h","_i","_j","_k","charge","initDataAttributes","button","dataOptions","dataCheckout","dispatchWidgetError","safeErrorMessage","expectedPrefix","boundedInteger","validateTheme","canonical","environment","field","loopback","isCanonical","explicitCheckoutDomain","isIpAddress","hostname","onlyKeys","total","item","text","rejectPANLikeOptionalText","integer","lineTotal","redirectUrl","uuid","optionalText","method","jsonObject","optionalBoolean","allowed","allowlist","unsupported","stack","seen","nodes","current","containsPANLikeSequence","child","normalized","compact","sensitiveBase","token","descriptor","qualifier","suffix","retainedDigits","character","length","validPANSequence","digits","sum","doubleDigit","index","digit","sessionId","baseUrl","maximumBytes","reader","chunks","done","buffer","offset","chunk","textBody","cryptoApi","bytes","entry","cssSupports","property","minimum","maximum","version"],"mappings":"AA0BA,IAAMA,CAAAA,CAAU,OAAA,CACVC,CAAAA,CAAkD,CACtD,IAAA,CAAM,kCAAA,CACN,GAAA,CAAK,0BACP,CAAA,CACMC,CAAAA,CAAuD,CAC3D,IAAA,CAAM,wCACN,GAAA,CAAK,+BACP,CAAA,CACMC,CAAAA,CAA4B,GAAA,CAC5BC,CAAAA,CAA6B,IAAA,CAC7BC,CAAAA,CAA6B,IAAM,IAAA,CACnCC,CAAAA,CAAoB,IAAA,CAAO,IAAA,CAC3BC,CAAAA,CAAkB,IAAA,CAClBC,CAAAA,CAAa,kBAAA,CAYnB,SAASC,CAAAA,CAAUC,CAAAA,CAAuB,CACxC,OAAOA,CAAAA,CAAM,OAAA,CAAQ,MAAA,CAAQ,EAAE,CACjC,CAEA,SAASC,CAAAA,CAAcC,CAAAA,CAA6C,CAClE,OAAIA,CAAAA,GAAW,SAAWA,CAAAA,GAAW,OAAA,CAC5BA,CAAAA,CAEL,OAAO,SAAA,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AAI,KAAA,CAAM,GAAG2E,CAAK,CAAA,YAAA,CAAc,CAE1C,CAEA,SAASe,EAAa1F,CAAAA,CAAgBuI,CAAAA,CAAiB5D,CAAAA,CAAqB,CACtE3E,IAAU,MAAA,EAAWoF,CAAAA,CAAKpF,CAAAA,CAAOuI,CAAAA,CAAS5D,CAAK,EACrD,CAEA,SAASkB,CAAAA,CAAgB7F,EAA4B2E,CAAAA,CAAqB,CACxE,GAAI3E,CAAAA,GAAU,MAAA,EAAa,OAAOA,CAAAA,EAAU,SAAA,CAAW,MAAM,IAAI,MAAM,CAAA,EAAG2E,CAAK,CAAA,YAAA,CAAc,CAC/F,CAEA,SAASc,CAAAA,CAAKzF,CAAAA,CAAiC,CAC7C,OAAO,OAAOA,CAAAA,EAAU,UAAY,iEAAA,CAAkE,IAAA,CAAKA,CAAK,CAClH,CAEA,SAASqE,EAAAA,CAAiBrB,EAAwB,CAEhD,OAAA,CADgBA,aAAiB,KAAA,CAAQA,CAAAA,CAAM,QAAU,kBAAA,EAC1C,OAAA,CAAQ,YAAA,CAAc,GAAG,EAAE,KAAA,CAAM,CAAA,CAAG,GAAG,CACxD,KAEawF,EAAAA,CAAUlJ","file":"index.js","sourcesContent":["import type {\n Charge,\n CheckoutParams,\n MuPagCallbacks,\n MuPagEnvironment,\n MuPagLocale,\n MuPagMessage,\n MuPagOptions,\n MuPagTheme,\n MuPagWidgetError,\n} from \"./types.js\";\n\nexport type {\n Charge,\n CheckoutCustomer,\n CheckoutItem,\n CheckoutParams,\n MuPagCallbacks,\n MuPagEnvironment,\n MuPagLocale,\n MuPagOptions,\n MuPagTheme,\n MuPagMessage,\n MuPagWidgetError,\n} from \"./types.js\";\n\nconst VERSION = \"0.1.0\";\nconst API_BASE_URLS: Record<MuPagEnvironment, string> = {\n test: \"https://api.sandbox.mupag.com.br\",\n prd: \"https://api.mupag.com.br\",\n};\nconst CHECKOUT_BASE_URLS: Record<MuPagEnvironment, string> = {\n test: \"https://checkout.sandbox.mupag.com.br\",\n prd: \"https://checkout.mupag.com.br\",\n};\nconst DEFAULT_IFRAME_TIMEOUT_MS = 8_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 15_000;\nconst DEFAULT_MAX_RESPONSE_BYTES = 256 * 1024;\nconst MAX_REQUEST_BYTES = 1024 * 1024;\nconst MAX_MONEY_CENTS = 9_000_000_000_000_000;\nconst DATA_BOUND = \"mupagWidgetBound\";\n\ninterface ActiveModal {\n host: HTMLElement;\n iframe: HTMLIFrameElement;\n checkoutOrigin: string;\n callbacks: MuPagCallbacks;\n fallbackUrl: string;\n loaded: boolean;\n loadTimer: number | undefined;\n}\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction resolveLocale(locale: MuPagOptions[\"locale\"]): MuPagLocale {\n if (locale === \"pt-BR\" || locale === \"en-US\") {\n return locale;\n }\n if (typeof navigator !== \"undefined\" && navigator.language.toLowerCase().startsWith(\"en\")) {\n return \"en-US\";\n }\n return \"pt-BR\";\n}\n\nfunction appendWidgetParams(url: URL, options: Required<Pick<MuPagOptions, \"checkoutBaseUrl\">> & MuPagOptions): URL {\n const locale = resolveLocale(options.locale);\n url.searchParams.set(\"locale\", locale);\n if (options.theme && Object.keys(options.theme).length > 0) {\n url.searchParams.set(\"theme\", JSON.stringify(options.theme));\n }\n if (typeof window !== \"undefined\" && window.location?.origin) {\n url.searchParams.set(\"parent_origin\", window.location.origin);\n }\n return url;\n}\n\nfunction createModal(url: string, theme: MuPagTheme | undefined, onClose: () => void): { host: HTMLElement; iframe: HTMLIFrameElement } {\n const host = document.createElement(\"div\");\n host.dataset.mupagWidgetRoot = \"true\";\n const root = host.attachShadow({ mode: \"open\" });\n const overlay = document.createElement(\"div\");\n overlay.setAttribute(\"part\", \"overlay\");\n const dialog = document.createElement(\"section\");\n dialog.setAttribute(\"part\", \"dialog\");\n dialog.setAttribute(\"role\", \"dialog\");\n dialog.setAttribute(\"aria-modal\", \"true\");\n dialog.setAttribute(\"aria-label\", \"Checkout seguro MuPag\");\n const close = document.createElement(\"button\");\n close.type = \"button\";\n close.textContent = \"Fechar\";\n close.setAttribute(\"part\", \"close\");\n close.addEventListener(\"click\", onClose);\n const iframe = document.createElement(\"iframe\");\n iframe.src = url;\n iframe.title = \"Checkout seguro MuPag\";\n iframe.allow = \"payment *\";\n iframe.referrerPolicy = \"strict-origin-when-cross-origin\";\n iframe.setAttribute(\"part\", \"iframe\");\n iframe.setAttribute(\"loading\", \"eager\");\n iframe.setAttribute(\n \"sandbox\",\n \"allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation\",\n );\n dialog.append(close, iframe);\n overlay.append(dialog);\n\n const primary = theme?.primaryColor ?? \"#176bff\";\n const radius = theme?.borderRadius ?? \"18px\";\n const font = theme?.fontFamily ?? \"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif\";\n const css = `\n :host{all:initial;--gw-primary:${primary};--gw-radius:${radius};font-family:${font}}\n [part=overlay]{position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(10,18,32,.54);padding:24px}\n [part=dialog]{position:relative;width:min(100%,760px);height:min(92vh,860px);overflow:hidden;border-radius:var(--gw-radius);background:#fff;box-shadow:0 24px 80px rgba(10,18,32,.28)}\n [part=close]{position:absolute;right:12px;top:10px;z-index:2;border:1px solid rgba(15,23,42,.16);border-radius:999px;background:#fff;color:#243044;font:600 13px/1.2 inherit;padding:8px 12px;cursor:pointer}\n [part=close]:focus{outline:3px solid color-mix(in srgb,var(--gw-primary) 35%,transparent);outline-offset:2px}\n [part=iframe]{display:block;width:100%;height:100%;border:0;background:#fff}\n @media (max-width:640px){[part=overlay]{align-items:stretch;padding:0;background:#fff}[part=dialog]{width:100%;height:100vh;max-height:none;border-radius:0;box-shadow:none}[part=close]{right:10px;top:8px}}\n `;\n if (\"adoptedStyleSheets\" in root && \"CSSStyleSheet\" in window) {\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(css);\n root.adoptedStyleSheets = [sheet];\n root.append(overlay);\n } else {\n const style = document.createElement(\"style\");\n style.textContent = css;\n root.append(style, overlay);\n }\n document.body.append(host);\n return { host, iframe };\n}\n\nfunction isMuPagMessage(data: unknown): data is MuPagMessage {\n if (!data || typeof data !== \"object\" || !(\"type\" in data) || typeof data.type !== \"string\") {\n return false;\n }\n return [\"mupag:loaded\", \"mupag:payment_completed\", \"mupag:close\", \"mupag:error\"].includes(data.type);\n}\n\nexport class MuPag {\n private readonly options: Required<\n Pick<\n MuPagOptions,\n | \"checkoutBaseUrl\"\n | \"apiBaseUrl\"\n | \"fetch\"\n | \"fallbackRedirect\"\n | \"iframeLoadTimeoutMs\"\n | \"requestTimeoutMs\"\n | \"maxResponseBytes\"\n >\n > &\n MuPagOptions;\n private active: ActiveModal | null = null;\n\n constructor(options: MuPagOptions) {\n validateOptions(options);\n this.options = {\n ...options,\n checkoutBaseUrl: allowedOrigin(\n options.checkoutBaseUrl ?? CHECKOUT_BASE_URLS[options.environment],\n CHECKOUT_BASE_URLS[options.environment],\n options.environment,\n \"checkoutBaseUrl\",\n ),\n apiBaseUrl: allowedOrigin(\n options.apiBaseUrl ?? API_BASE_URLS[options.environment],\n API_BASE_URLS[options.environment],\n options.environment,\n \"apiBaseUrl\",\n ),\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n fallbackRedirect: options.fallbackRedirect ?? true,\n iframeLoadTimeoutMs: options.iframeLoadTimeoutMs ?? DEFAULT_IFRAME_TIMEOUT_MS,\n requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,\n };\n this.handleMessage = this.handleMessage.bind(this);\n }\n\n async openCheckout(params: CheckoutParams): Promise<void> {\n if (!params || typeof params !== \"object\" || Array.isArray(params)) {\n throw new Error(\"Checkout params must be an object.\");\n }\n const { onSuccess, onClose, onError, idempotencyKey, ...body } = params;\n validateCheckout(body, this.options.environment);\n let encodedBody: string;\n let canonicalBody: typeof body;\n try {\n encodedBody = JSON.stringify(body);\n canonicalBody = JSON.parse(encodedBody) as typeof body;\n } catch {\n throw new Error(\"Checkout payload must be valid JSON.\");\n }\n validateCheckout(canonicalBody, this.options.environment);\n if (new TextEncoder().encode(encodedBody).byteLength > MAX_REQUEST_BYTES) {\n throw new Error(\"Checkout payload exceeds the safe 1 MiB limit.\");\n }\n const key = idempotencyKey === undefined ? createIdempotencyKey() : validateIdempotencyKey(idempotencyKey);\n const controller = new AbortController();\n const timer = window.setTimeout(() => controller.abort(), this.options.requestTimeoutMs);\n let response: Response;\n try {\n response = await this.options.fetch(`${this.options.apiBaseUrl}/v1/checkout-sessions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${this.options.publishableKey}`,\n \"Idempotency-Key\": key,\n },\n body: encodedBody,\n signal: controller.signal,\n });\n } catch {\n const error = { code: \"checkout_network_error\", message: \"Checkout session request failed.\" };\n onError?.(error);\n throw new Error(error.message);\n } finally {\n window.clearTimeout(timer);\n }\n const responseBody = await readBoundedJson(response, this.options.maxResponseBytes);\n if (!response.ok) {\n const error = { code: \"checkout_session_failed\", message: `Checkout session failed (${response.status}).` };\n onError?.(error);\n throw new Error(error.message);\n }\n const payload = checkoutResponse(responseBody);\n const checkoutUrl = safeCheckoutUrl(payload.url, payload.id, this.options.checkoutBaseUrl);\n const url = appendWidgetParams(checkoutUrl, this.options);\n const callbacks: MuPagCallbacks = {};\n if (onSuccess) {\n callbacks.onSuccess = onSuccess;\n }\n if (onClose) {\n callbacks.onClose = onClose;\n }\n if (onError) {\n callbacks.onError = onError;\n }\n this.openUrl(url.toString(), callbacks);\n }\n\n close(): void {\n if (!this.active) {\n return;\n }\n if (this.active.loadTimer) {\n window.clearTimeout(this.active.loadTimer);\n }\n window.removeEventListener(\"message\", this.handleMessage);\n this.active.host.remove();\n this.active = null;\n }\n\n private openUrl(url: string, callbacks: MuPagCallbacks): void {\n this.close();\n const checkoutOrigin = new URL(url).origin;\n const modal = createModal(url, this.options.theme, () => {\n callbacks.onClose?.();\n this.close();\n });\n const active: ActiveModal = {\n ...modal,\n checkoutOrigin,\n callbacks,\n fallbackUrl: url,\n loaded: false,\n loadTimer: undefined,\n };\n active.iframe.addEventListener(\"load\", () => {\n active.loaded = true;\n if (active.loadTimer) {\n window.clearTimeout(active.loadTimer);\n }\n });\n active.loadTimer = window.setTimeout(() => {\n if (!active.loaded && this.options.fallbackRedirect) {\n window.location.assign(active.fallbackUrl);\n }\n }, this.options.iframeLoadTimeoutMs);\n this.active = active;\n window.addEventListener(\"message\", this.handleMessage);\n }\n\n private handleMessage(event: MessageEvent): void {\n if (\n !this.active ||\n event.origin !== this.active.checkoutOrigin ||\n event.source === null ||\n this.active.iframe.contentWindow === null ||\n event.source !== this.active.iframe.contentWindow ||\n !isMuPagMessage(event.data)\n ) {\n return;\n }\n if (event.data.type === \"mupag:loaded\") {\n this.active.loaded = true;\n return;\n }\n if (event.data.type === \"mupag:payment_completed\") {\n const charge = event.data.charge ?? event.data.payload?.charge ?? ({ status: \"paid\", ...event.data.payload } as Charge);\n this.active.callbacks.onSuccess?.(charge);\n this.close();\n return;\n }\n if (event.data.type === \"mupag:close\") {\n this.active.callbacks.onClose?.();\n this.close();\n return;\n }\n if (event.data.type === \"mupag:error\") {\n this.active.callbacks.onError?.(event.data.error ?? event.data.payload ?? { code: \"checkout_error\", message: \"Checkout error.\" });\n }\n }\n}\n\nexport function initDataAttributes(root: ParentNode = document): void {\n const buttons = root.querySelectorAll<HTMLElement>(\"[data-mupag-widget]\");\n buttons.forEach((button) => {\n if (button.dataset[DATA_BOUND] === \"true\") {\n return;\n }\n button.dataset[DATA_BOUND] = \"true\";\n button.addEventListener(\"click\", () => {\n try {\n const options = dataOptions(button);\n const theme: MuPagTheme = {};\n if (button.dataset.primaryColor) {\n theme.primaryColor = button.dataset.primaryColor;\n }\n if (button.dataset.accentColor) {\n theme.accentColor = button.dataset.accentColor;\n }\n if (button.dataset.fontFamily) {\n theme.fontFamily = button.dataset.fontFamily;\n }\n if (Object.keys(theme).length > 0) {\n options.theme = theme;\n }\n const mupag = new MuPag(options);\n void mupag.openCheckout(dataCheckout(button)).catch((error: unknown) => dispatchWidgetError(button, error));\n } catch (error) {\n dispatchWidgetError(button, error);\n }\n });\n });\n}\n\nfunction dispatchWidgetError(button: HTMLElement, error: unknown): void {\n button.dispatchEvent(\n new CustomEvent(\"mupag:error\", {\n detail: { code: \"checkout_failed\", message: safeErrorMessage(error) },\n }),\n );\n}\n\nfunction validateOptions(options: MuPagOptions): void {\n if (!options || (options.environment !== \"test\" && options.environment !== \"prd\")) {\n throw new Error(\"environment must be explicitly test or prd.\");\n }\n const expectedPrefix = options.environment === \"test\" ? \"pk_test_\" : \"pk_prd_\";\n if (\n typeof options.publishableKey !== \"string\" ||\n !options.publishableKey.startsWith(expectedPrefix) ||\n options.publishableKey.length > 512 ||\n !/^[\\x21-\\x7e]+$/.test(options.publishableKey)\n ) {\n throw new Error(\"publishableKey is invalid or does not match the selected environment.\");\n }\n boundedInteger(options.iframeLoadTimeoutMs, 1, 120_000, \"iframeLoadTimeoutMs\");\n boundedInteger(options.requestTimeoutMs, 1, 120_000, \"requestTimeoutMs\");\n boundedInteger(options.maxResponseBytes, 1, 4 * 1024 * 1024, \"maxResponseBytes\");\n validateTheme(options.theme);\n}\n\nfunction allowedOrigin(value: string, canonical: string, environment: MuPagEnvironment, field: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${field} is invalid.`);\n }\n const loopback = environment === \"test\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n const isCanonical = url.origin === new URL(canonical).origin;\n const explicitCheckoutDomain = field === \"checkoutBaseUrl\" && url.protocol === \"https:\" && !isIpAddress(url.hostname);\n if (\n (!isCanonical && !loopback && !explicitCheckoutDomain) ||\n (url.protocol !== \"https:\" && !(loopback && url.protocol === \"http:\")) ||\n url.username ||\n url.password ||\n (url.pathname !== \"\" && url.pathname !== \"/\") ||\n url.search ||\n url.hash\n ) {\n throw new Error(`${field} is not an allowed origin.`);\n }\n return trimSlash(url.origin);\n}\n\nfunction isIpAddress(hostname: string): boolean {\n return /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(hostname) || hostname.includes(\":\");\n}\n\nfunction validateCheckout(body: Omit<CheckoutParams, keyof MuPagCallbacks | \"idempotencyKey\">, environment: MuPagEnvironment): void {\n onlyKeys(\n body,\n [\n \"items\",\n \"success_url\",\n \"cancel_url\",\n \"customer_id\",\n \"customer_data\",\n \"allowed_payment_methods\",\n \"affiliate_code\",\n \"coupon_id\",\n \"utm_params\",\n \"expires_in_minutes\",\n \"metadata\",\n \"collect_shipping_address\",\n \"delivery_type\",\n \"allow_coupons\",\n ],\n \"checkout\",\n );\n if (!Array.isArray(body.items) || body.items.length < 1 || body.items.length > 100) {\n throw new Error(\"Checkout items must contain between 1 and 100 entries.\");\n }\n let total = 0;\n for (const item of body.items) {\n onlyKeys(item, [\"name\", \"quantity\", \"unit_amount_cents\"], \"checkout item\");\n text(item.name, 200, \"item.name\");\n rejectPANLikeOptionalText(item.name, \"item.name\");\n integer(item.quantity, 1, 1_000_000, \"item.quantity\");\n integer(item.unit_amount_cents, 100, MAX_MONEY_CENTS, \"item.unit_amount_cents\");\n const lineTotal = item.quantity * item.unit_amount_cents;\n if (!Number.isSafeInteger(lineTotal) || lineTotal > MAX_MONEY_CENTS) {\n throw new Error(\"Checkout item total is outside the supported range.\");\n }\n total += lineTotal;\n if (!Number.isSafeInteger(total) || total > MAX_MONEY_CENTS) {\n throw new Error(\"Checkout total is outside the supported range.\");\n }\n }\n redirectUrl(body.success_url, environment, \"success_url\");\n redirectUrl(body.cancel_url, environment, \"cancel_url\");\n if (body.customer_id !== undefined && body.customer_data !== undefined) {\n throw new Error(\"customer_id and customer_data are mutually exclusive.\");\n }\n if (body.customer_id !== undefined && !uuid(body.customer_id)) {\n throw new Error(\"customer_id must be a UUID.\");\n }\n rejectPANLikeOptionalText(body.customer_id, \"customer_id\");\n if (body.customer_data !== undefined) {\n onlyKeys(body.customer_data, [\"name\", \"email\", \"document\", \"phone\"], \"customer_data\");\n optionalText(body.customer_data.name, 200, \"customer_data.name\");\n rejectPANLikeOptionalText(body.customer_data.name, \"customer_data.name\");\n optionalText(body.customer_data.email, 320, \"customer_data.email\");\n rejectPANLikeOptionalText(body.customer_data.email, \"customer_data.email\");\n optionalText(body.customer_data.document, 64, \"customer_data.document\");\n optionalText(body.customer_data.phone, 32, \"customer_data.phone\");\n }\n if (\n body.allowed_payment_methods !== undefined &&\n (!Array.isArray(body.allowed_payment_methods) ||\n body.allowed_payment_methods.length < 1 ||\n body.allowed_payment_methods.length > 2 ||\n new Set(body.allowed_payment_methods).size !== body.allowed_payment_methods.length ||\n body.allowed_payment_methods.some((method) => method !== \"pix\" && method !== \"credit_card\"))\n ) {\n throw new Error(\"allowed_payment_methods is invalid.\");\n }\n optionalText(body.affiliate_code, 128, \"affiliate_code\");\n rejectPANLikeOptionalText(body.affiliate_code, \"affiliate_code\");\n if (body.coupon_id !== undefined && !uuid(body.coupon_id)) throw new Error(\"coupon_id must be a UUID.\");\n if (body.allow_coupons === false && body.coupon_id !== undefined) {\n throw new Error(\"coupon_id cannot be used when allow_coupons is false.\");\n }\n if (body.expires_in_minutes !== undefined) integer(body.expires_in_minutes, 1, 24 * 60, \"expires_in_minutes\");\n if (body.metadata !== undefined) jsonObject(body.metadata, \"metadata\");\n if (body.utm_params !== undefined) jsonObject(body.utm_params, \"utm_params\");\n optionalText(body.delivery_type, 64, \"delivery_type\");\n rejectPANLikeOptionalText(body.delivery_type, \"delivery_type\");\n optionalBoolean(body.collect_shipping_address, \"collect_shipping_address\");\n optionalBoolean(body.allow_coupons, \"allow_coupons\");\n}\n\nfunction onlyKeys(value: unknown, allowed: readonly string[], field: string): asserts value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {\n throw new Error(`${field} must be a plain object.`);\n }\n const allowlist = new Set(allowed);\n const unsupported = Object.keys(value).find((key) => !allowlist.has(key));\n if (unsupported !== undefined) {\n throw new Error(`${field} contains unsupported field ${unsupported}.`);\n }\n}\n\nfunction jsonObject(value: object, field: string): void {\n if (value === null || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {\n throw new Error(`${field} must be a plain JSON object.`);\n }\n const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];\n const seen = new WeakSet<object>();\n let nodes = 0;\n while (stack.length > 0) {\n const current = stack.pop();\n if (!current) break;\n nodes += 1;\n if (nodes > 10_000 || current.depth > 32) throw new Error(`${field} is too complex.`);\n if (current.value === null || typeof current.value === \"boolean\") continue;\n if (typeof current.value === \"string\") {\n if (containsPANLikeSequence(current.value)) throw new Error(`${field} contains a possible card number.`);\n continue;\n }\n if (typeof current.value === \"number\") {\n if (!Number.isFinite(current.value)) throw new Error(`${field} contains an invalid number.`);\n if (containsPANLikeSequence(JSON.stringify(current.value))) {\n throw new Error(`${field} contains a possible card number.`);\n }\n continue;\n }\n if (typeof current.value !== \"object\") throw new Error(`${field} contains a non-JSON value.`);\n if (seen.has(current.value)) throw new Error(`${field} contains a cycle.`);\n seen.add(current.value);\n for (const [key, child] of Object.entries(current.value)) {\n if (containsPANLikeSequence(key)) {\n throw new Error(`${field} contains a possible card number.`);\n }\n const normalized = key.toLowerCase();\n const compact = normalized.replace(/[^a-z0-9]/g, \"\");\n const sensitiveBase = compact\n .replace(/[0-9]+$/, \"\")\n .replace(/(cvv|cvc|csc|cid|cav)[0-9]+/g, \"$1\");\n if (\n [\"__proto__\", \"prototype\", \"constructor\"].includes(normalized)\n || [\"pan\", \"cardnumber\"].includes(compact)\n || [\"cvv\", \"cvc\", \"cav\"].some((token) =>\n [\"\", \"value\", \"code\", \"number\"].some((descriptor) => sensitiveBase.endsWith(token + descriptor))\n )\n || [\"csc\", \"cid\"].some((token) =>\n [\"\", \"value\", \"code\", \"number\"].some(\n (descriptor) =>\n sensitiveBase === token + descriptor\n || [\"card\", \"amex\", \"americanexpress\"].some((qualifier) =>\n sensitiveBase.endsWith(qualifier + token + descriptor)\n )\n )\n )\n || sensitiveBase.endsWith(\"cardidentificationnumber\")\n || sensitiveBase.endsWith(\"cardsecuritynumber\")\n || [\n \"securitycode\",\n \"securityvalue\",\n \"verificationcode\",\n \"verificationnumber\",\n \"verificationvalue\",\n ].some((suffix) => sensitiveBase.endsWith(suffix))\n ) {\n throw new Error(`${field} contains a forbidden field.`);\n }\n stack.push({ value: child, depth: current.depth + 1 });\n }\n }\n}\n\nfunction containsPANLikeSequence(value: string): boolean {\n let retainedDigits = \"\";\n\n for (const character of value) {\n if (character >= \"0\" && character <= \"9\") {\n retainedDigits = (retainedDigits + character).slice(-19);\n for (let length = 12; length <= retainedDigits.length; length += 1) {\n if (validPANSequence(retainedDigits.slice(-length))) return true;\n }\n } else if (/^\\p{Nd}$/u.test(character)) {\n return true;\n } else if (/^[\\s\\p{P}\\p{S}\\p{M}\\p{Cc}\\p{Cf}]$/u.test(character)) {\n continue;\n } else {\n retainedDigits = \"\";\n }\n }\n return false;\n}\n\nfunction rejectPANLikeOptionalText(value: unknown, field: string): void {\n if (value !== undefined && (typeof value !== \"string\" || containsPANLikeSequence(value))) {\n throw new Error(`${field} contains a possible card number.`);\n }\n}\n\nfunction validPANSequence(digits: string): boolean {\n if (!/^[0-9]{12,19}$/.test(digits)) return false;\n let sum = 0;\n let doubleDigit = false;\n for (let index = digits.length - 1; index >= 0; index -= 1) {\n let digit = digits.charCodeAt(index) - 48;\n if (doubleDigit) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n sum += digit;\n doubleDigit = !doubleDigit;\n }\n return sum % 10 === 0;\n}\n\nfunction redirectUrl(value: string, environment: MuPagEnvironment, field: string): void {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${field} must be an absolute URL.`);\n }\n const loopback = environment === \"test\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n if ((url.protocol !== \"https:\" && !(loopback && url.protocol === \"http:\")) || url.username || url.password || value.length > 2048) {\n throw new Error(`${field} must be a safe HTTPS URL.`);\n }\n}\n\nfunction checkoutResponse(value: unknown): { id: string; url: string; expires_at: string } {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Invalid checkout response.\");\n const response = value as Record<string, unknown>;\n if (!uuid(response.id) || typeof response.url !== \"string\" || typeof response.expires_at !== \"string\") {\n throw new Error(\"Invalid checkout response.\");\n }\n if (Number.isNaN(Date.parse(response.expires_at))) throw new Error(\"Invalid checkout response.\");\n return { id: response.id, url: response.url, expires_at: response.expires_at };\n}\n\nfunction safeCheckoutUrl(value: string, sessionId: string, baseUrl: string): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(\"Invalid checkout URL in API response.\");\n }\n if (\n url.origin !== new URL(baseUrl).origin ||\n url.username ||\n url.password ||\n url.protocol !== new URL(baseUrl).protocol ||\n url.pathname !== `/c/${sessionId}` ||\n url.search ||\n url.hash\n ) {\n throw new Error(\"Invalid checkout URL in API response.\");\n }\n return url;\n}\n\nasync function readBoundedJson(response: Response, maximumBytes: number): Promise<unknown> {\n const length = response.headers.get(\"content-length\");\n if (length !== null && (!/^\\d+$/.test(length) || Number(length) > maximumBytes)) {\n throw new Error(\"Checkout response exceeds the configured limit.\");\n }\n if (!response.body) return undefined;\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n total += value.byteLength;\n if (total > maximumBytes) {\n await reader.cancel(\"response limit exceeded\");\n throw new Error(\"Checkout response exceeds the configured limit.\");\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n const buffer = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n const textBody = new TextDecoder().decode(buffer);\n if (textBody.trim().length === 0) return undefined;\n try {\n return JSON.parse(textBody) as unknown;\n } catch {\n throw new Error(\"Checkout response is not valid JSON.\");\n }\n}\n\nfunction createIdempotencyKey(): string {\n const cryptoApi = globalThis.crypto;\n if (typeof cryptoApi?.randomUUID === \"function\") return `widget_${cryptoApi.randomUUID()}`;\n if (typeof cryptoApi?.getRandomValues !== \"function\") {\n throw new Error(\"A secure random generator is required to create an Idempotency-Key.\");\n }\n const bytes = new Uint8Array(16);\n cryptoApi.getRandomValues(bytes);\n return `widget_${Array.from(bytes, (entry) => entry.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction validateIdempotencyKey(value: string): string {\n if (value.length < 1 || value.length > 128 || !/^[\\x21-\\x7e]+$/.test(value)) {\n throw new Error(\"idempotencyKey must contain 1-128 visible ASCII characters.\");\n }\n return value;\n}\n\nfunction dataOptions(button: HTMLElement): MuPagOptions {\n return {\n environment: button.dataset.environment as MuPagEnvironment,\n publishableKey: button.dataset.publishableKey ?? \"\",\n ...(button.dataset.checkoutBaseUrl ? { checkoutBaseUrl: button.dataset.checkoutBaseUrl } : {}),\n ...(button.dataset.apiBaseUrl ? { apiBaseUrl: button.dataset.apiBaseUrl } : {}),\n ...(button.dataset.locale ? { locale: button.dataset.locale as MuPagLocale | \"auto\" } : {}),\n };\n}\n\nfunction dataCheckout(button: HTMLElement): CheckoutParams {\n return {\n items: [\n {\n name: button.dataset.itemName ?? \"\",\n quantity: Number(button.dataset.quantity ?? \"1\"),\n unit_amount_cents: Number(button.dataset.unitAmountCents ?? \"\"),\n },\n ],\n success_url: button.dataset.successUrl ?? \"\",\n cancel_url: button.dataset.cancelUrl ?? \"\",\n };\n}\n\nfunction validateTheme(theme: MuPagTheme | undefined): void {\n if (!theme) return;\n if (theme.primaryColor !== undefined && (!cssSupports(\"color\", theme.primaryColor) || /url\\s*\\(/i.test(theme.primaryColor))) {\n throw new Error(\"theme.primaryColor is invalid.\");\n }\n if (theme.accentColor !== undefined && (!cssSupports(\"color\", theme.accentColor) || /url\\s*\\(/i.test(theme.accentColor))) {\n throw new Error(\"theme.accentColor is invalid.\");\n }\n if (theme.borderRadius !== undefined && (!cssSupports(\"border-radius\", theme.borderRadius) || /url\\s*\\(/i.test(theme.borderRadius))) {\n throw new Error(\"theme.borderRadius is invalid.\");\n }\n if (theme.fontFamily !== undefined && !/^[A-Za-z0-9 ,_'\"-]{1,200}$/.test(theme.fontFamily)) {\n throw new Error(\"theme.fontFamily is invalid.\");\n }\n}\n\nfunction cssSupports(property: string, value: string): boolean {\n return typeof globalThis.CSS?.supports === \"function\" && globalThis.CSS.supports(property, value);\n}\n\nfunction boundedInteger(value: number | undefined, minimum: number, maximum: number, field: string): void {\n if (value !== undefined) integer(value, minimum, maximum, field);\n}\n\nfunction integer(value: number, minimum: number, maximum: number, field: string): void {\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw new Error(`${field} is invalid.`);\n}\n\nfunction text(value: unknown, maximum: number, field: string): void {\n if (typeof value !== \"string\" || value.trim().length < 1 || value.length > maximum || /[\\x00-\\x1f\\x7f]/.test(value)) {\n throw new Error(`${field} is invalid.`);\n }\n}\n\nfunction optionalText(value: unknown, maximum: number, field: string): void {\n if (value !== undefined) text(value, maximum, field);\n}\n\nfunction optionalBoolean(value: boolean | undefined, field: string): void {\n if (value !== undefined && typeof value !== \"boolean\") throw new Error(`${field} is invalid.`);\n}\n\nfunction uuid(value: unknown): value is string {\n return typeof value === \"string\" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);\n}\n\nfunction safeErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : \"Checkout failed.\";\n return message.replace(/[\\r\\n\\t]+/g, \" \").slice(0, 256);\n}\n\nexport const version = VERSION;\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
var MuPagWidget=(function(){'use strict';var K="0.1.0",L={test:"https://api.sandbox.mupag.com.br",prd:"https://api.mupag.com.br"},A={test:"https://checkout.sandbox.mupag.com.br",prd:"https://checkout.mupag.com.br"},F=8e3,H=15e3,J=256*1024,z=1024*1024,x=9e15,R="mupagWidgetBound";function V(e){return e.replace(/\/+$/,"")}function X(e){return e==="pt-BR"||e==="en-US"?e:typeof navigator!="undefined"&&navigator.language.toLowerCase().startsWith("en")?"en-US":"pt-BR"}function Y(e,t){var r;let n=X(t.locale);return e.searchParams.set("locale",n),t.theme&&Object.keys(t.theme).length>0&&e.searchParams.set("theme",JSON.stringify(t.theme)),typeof window!="undefined"&&((r=window.location)!=null&&r.origin)&&e.searchParams.set("parent_origin",window.location.origin),e}function Q(e,t,n){var p,w,_;let r=document.createElement("div");r.dataset.mupagWidgetRoot="true";let o=r.attachShadow({mode:"open"}),a=document.createElement("div");a.setAttribute("part","overlay");let i=document.createElement("section");i.setAttribute("part","dialog"),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-label","Checkout seguro MuPag");let c=document.createElement("button");c.type="button",c.textContent="Fechar",c.setAttribute("part","close"),c.addEventListener("click",n);let s=document.createElement("iframe");s.src=e,s.title="Checkout seguro MuPag",s.allow="payment *",s.referrerPolicy="strict-origin-when-cross-origin",s.setAttribute("part","iframe"),s.setAttribute("loading","eager"),s.setAttribute("sandbox","allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.append(c,s),a.append(i);let l=(p=t==null?void 0:t.primaryColor)!=null?p:"#176bff",u=(w=t==null?void 0:t.borderRadius)!=null?w:"18px",m=(_=t==null?void 0:t.fontFamily)!=null?_:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif",d=`
|
|
2
|
+
:host{all:initial;--gw-primary:${l};--gw-radius:${u};font-family:${m}}
|
|
3
|
+
[part=overlay]{position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(10,18,32,.54);padding:24px}
|
|
4
|
+
[part=dialog]{position:relative;width:min(100%,760px);height:min(92vh,860px);overflow:hidden;border-radius:var(--gw-radius);background:#fff;box-shadow:0 24px 80px rgba(10,18,32,.28)}
|
|
5
|
+
[part=close]{position:absolute;right:12px;top:10px;z-index:2;border:1px solid rgba(15,23,42,.16);border-radius:999px;background:#fff;color:#243044;font:600 13px/1.2 inherit;padding:8px 12px;cursor:pointer}
|
|
6
|
+
[part=close]:focus{outline:3px solid color-mix(in srgb,var(--gw-primary) 35%,transparent);outline-offset:2px}
|
|
7
|
+
[part=iframe]{display:block;width:100%;height:100%;border:0;background:#fff}
|
|
8
|
+
@media (max-width:640px){[part=overlay]{align-items:stretch;padding:0;background:#fff}[part=dialog]{width:100%;height:100vh;max-height:none;border-radius:0;box-shadow:none}[part=close]{right:10px;top:8px}}
|
|
9
|
+
`;if("adoptedStyleSheets"in o&&"CSSStyleSheet"in window){let f=new CSSStyleSheet;f.replaceSync(d),o.adoptedStyleSheets=[f],o.append(a);}else {let f=document.createElement("style");f.textContent=d,o.append(f,a);}return document.body.append(r),{host:r,iframe:s}}function Z(e){return !e||typeof e!="object"||!("type"in e)||typeof e.type!="string"?false:["mupag:loaded","mupag:payment_completed","mupag:close","mupag:error"].includes(e.type)}var y=class{constructor(t){this.active=null;var n,r,o,a,i,c,s;G(t),this.options={...t,checkoutBaseUrl:B((n=t.checkoutBaseUrl)!=null?n:A[t.environment],A[t.environment],t.environment,"checkoutBaseUrl"),apiBaseUrl:B((r=t.apiBaseUrl)!=null?r:L[t.environment],L[t.environment],t.environment,"apiBaseUrl"),fetch:(o=t.fetch)!=null?o:globalThis.fetch.bind(globalThis),fallbackRedirect:(a=t.fallbackRedirect)!=null?a:true,iframeLoadTimeoutMs:(i=t.iframeLoadTimeoutMs)!=null?i:F,requestTimeoutMs:(c=t.requestTimeoutMs)!=null?c:H,maxResponseBytes:(s=t.maxResponseBytes)!=null?s:J},this.handleMessage=this.handleMessage.bind(this);}async openCheckout(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Checkout params must be an object.");let{onSuccess:n,onClose:r,onError:o,idempotencyKey:a,...i}=t;$(i,this.options.environment);let c,s;try{c=JSON.stringify(i),s=JSON.parse(c);}catch(k){throw new Error("Checkout payload must be valid JSON.")}if($(s,this.options.environment),new TextEncoder().encode(c).byteLength>z)throw new Error("Checkout payload exceeds the safe 1 MiB limit.");let l=a===void 0?ae():ie(a),u=new AbortController,m=window.setTimeout(()=>u.abort(),this.options.requestTimeoutMs),d;try{d=await this.options.fetch(`${this.options.apiBaseUrl}/v1/checkout-sessions`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.options.publishableKey}`,"Idempotency-Key":l},body:c,signal:u.signal});}catch(k){let T={code:"checkout_network_error",message:"Checkout session request failed."};throw o==null||o(T),new Error(T.message)}finally{window.clearTimeout(m);}let p=await oe(d,this.options.maxResponseBytes);if(!d.ok){let k={code:"checkout_session_failed",message:`Checkout session failed (${d.status}).`};throw o==null||o(k),new Error(k.message)}let w=ne(p),_=re(w.url,w.id,this.options.checkoutBaseUrl),f=Y(_,this.options),v={};n&&(v.onSuccess=n),r&&(v.onClose=r),o&&(v.onError=o),this.openUrl(f.toString(),v);}close(){this.active&&(this.active.loadTimer&&window.clearTimeout(this.active.loadTimer),window.removeEventListener("message",this.handleMessage),this.active.host.remove(),this.active=null);}openUrl(t,n){this.close();let r=new URL(t).origin,a={...Q(t,this.options.theme,()=>{var i;(i=n.onClose)==null||i.call(n),this.close();}),checkoutOrigin:r,callbacks:n,fallbackUrl:t,loaded:false,loadTimer:void 0};a.iframe.addEventListener("load",()=>{a.loaded=true,a.loadTimer&&window.clearTimeout(a.loadTimer);}),a.loadTimer=window.setTimeout(()=>{!a.loaded&&this.options.fallbackRedirect&&window.location.assign(a.fallbackUrl);},this.options.iframeLoadTimeoutMs),this.active=a,window.addEventListener("message",this.handleMessage);}handleMessage(t){var n,r,o,a,i,c,s,l,u,m,d;if(!(!this.active||t.origin!==this.active.checkoutOrigin||t.source===null||this.active.iframe.contentWindow===null||t.source!==this.active.iframe.contentWindow||!Z(t.data))){if(t.data.type==="mupag:loaded"){this.active.loaded=true;return}if(t.data.type==="mupag:payment_completed"){let p=(o=(r=t.data.charge)!=null?r:(n=t.data.payload)==null?void 0:n.charge)!=null?o:{status:"paid",...t.data.payload};(i=(a=this.active.callbacks).onSuccess)==null||i.call(a,p),this.close();return}if(t.data.type==="mupag:close"){(s=(c=this.active.callbacks).onClose)==null||s.call(c),this.close();return}t.data.type==="mupag:error"&&((d=(m=this.active.callbacks).onError)==null||d.call(m,(u=(l=t.data.error)!=null?l:t.data.payload)!=null?u:{code:"checkout_error",message:"Checkout error."}));}}};function M(e=document){e.querySelectorAll("[data-mupag-widget]").forEach(n=>{n.dataset[R]!=="true"&&(n.dataset[R]="true",n.addEventListener("click",()=>{try{let r=se(n),o={};n.dataset.primaryColor&&(o.primaryColor=n.dataset.primaryColor),n.dataset.accentColor&&(o.accentColor=n.dataset.accentColor),n.dataset.fontFamily&&(o.fontFamily=n.dataset.fontFamily),Object.keys(o).length>0&&(r.theme=o),new y(r).openCheckout(ce(n)).catch(i=>O(n,i));}catch(r){O(n,r);}}));});}function O(e,t){e.dispatchEvent(new CustomEvent("mupag:error",{detail:{code:"checkout_failed",message:le(t)}}));}function G(e){if(!e||e.environment!=="test"&&e.environment!=="prd")throw new Error("environment must be explicitly test or prd.");let t=e.environment==="test"?"pk_test_":"pk_prd_";if(typeof e.publishableKey!="string"||!e.publishableKey.startsWith(t)||e.publishableKey.length>512||!/^[\x21-\x7e]+$/.test(e.publishableKey))throw new Error("publishableKey is invalid or does not match the selected environment.");U(e.iframeLoadTimeoutMs,1,12e4,"iframeLoadTimeoutMs"),U(e.requestTimeoutMs,1,12e4,"requestTimeoutMs"),U(e.maxResponseBytes,1,4*1024*1024,"maxResponseBytes"),ue(e.theme);}function B(e,t,n,r){let o;try{o=new URL(e);}catch(s){throw new Error(`${r} is invalid.`)}let a=n==="test"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname),i=o.origin===new URL(t).origin,c=r==="checkoutBaseUrl"&&o.protocol==="https:"&&!ee(o.hostname);if(!i&&!a&&!c||o.protocol!=="https:"&&!(a&&o.protocol==="http:")||o.username||o.password||o.pathname!==""&&o.pathname!=="/"||o.search||o.hash)throw new Error(`${r} is not an allowed origin.`);return V(o.origin)}function ee(e){return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)||e.includes(":")}function $(e,t){if(C(e,["items","success_url","cancel_url","customer_id","customer_data","allowed_payment_methods","affiliate_code","coupon_id","utm_params","expires_in_minutes","metadata","collect_shipping_address","delivery_type","allow_coupons"],"checkout"),!Array.isArray(e.items)||e.items.length<1||e.items.length>100)throw new Error("Checkout items must contain between 1 and 100 entries.");let n=0;for(let r of e.items){C(r,["name","quantity","unit_amount_cents"],"checkout item"),q(r.name,200,"item.name"),h(r.name,"item.name"),E(r.quantity,1,1e6,"item.quantity"),E(r.unit_amount_cents,100,x,"item.unit_amount_cents");let o=r.quantity*r.unit_amount_cents;if(!Number.isSafeInteger(o)||o>x)throw new Error("Checkout item total is outside the supported range.");if(n+=o,!Number.isSafeInteger(n)||n>x)throw new Error("Checkout total is outside the supported range.")}if(N(e.success_url,t,"success_url"),N(e.cancel_url,t,"cancel_url"),e.customer_id!==void 0&&e.customer_data!==void 0)throw new Error("customer_id and customer_data are mutually exclusive.");if(e.customer_id!==void 0&&!S(e.customer_id))throw new Error("customer_id must be a UUID.");if(h(e.customer_id,"customer_id"),e.customer_data!==void 0&&(C(e.customer_data,["name","email","document","phone"],"customer_data"),g(e.customer_data.name,200,"customer_data.name"),h(e.customer_data.name,"customer_data.name"),g(e.customer_data.email,320,"customer_data.email"),h(e.customer_data.email,"customer_data.email"),g(e.customer_data.document,64,"customer_data.document"),g(e.customer_data.phone,32,"customer_data.phone")),e.allowed_payment_methods!==void 0&&(!Array.isArray(e.allowed_payment_methods)||e.allowed_payment_methods.length<1||e.allowed_payment_methods.length>2||new Set(e.allowed_payment_methods).size!==e.allowed_payment_methods.length||e.allowed_payment_methods.some(r=>r!=="pix"&&r!=="credit_card")))throw new Error("allowed_payment_methods is invalid.");if(g(e.affiliate_code,128,"affiliate_code"),h(e.affiliate_code,"affiliate_code"),e.coupon_id!==void 0&&!S(e.coupon_id))throw new Error("coupon_id must be a UUID.");if(e.allow_coupons===false&&e.coupon_id!==void 0)throw new Error("coupon_id cannot be used when allow_coupons is false.");e.expires_in_minutes!==void 0&&E(e.expires_in_minutes,1,1440,"expires_in_minutes"),e.metadata!==void 0&&I(e.metadata,"metadata"),e.utm_params!==void 0&&I(e.utm_params,"utm_params"),g(e.delivery_type,64,"delivery_type"),h(e.delivery_type,"delivery_type"),j(e.collect_shipping_address,"collect_shipping_address"),j(e.allow_coupons,"allow_coupons");}function C(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new Error(`${n} must be a plain object.`);let r=new Set(t),o=Object.keys(e).find(a=>!r.has(a));if(o!==void 0)throw new Error(`${n} contains unsupported field ${o}.`)}function I(e,t){if(e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new Error(`${t} must be a plain JSON object.`);let n=[{value:e,depth:0}],r=new WeakSet,o=0;for(;n.length>0;){let a=n.pop();if(!a)break;if(o+=1,o>1e4||a.depth>32)throw new Error(`${t} is too complex.`);if(!(a.value===null||typeof a.value=="boolean")){if(typeof a.value=="string"){if(b(a.value))throw new Error(`${t} contains a possible card number.`);continue}if(typeof a.value=="number"){if(!Number.isFinite(a.value))throw new Error(`${t} contains an invalid number.`);if(b(JSON.stringify(a.value)))throw new Error(`${t} contains a possible card number.`);continue}if(typeof a.value!="object")throw new Error(`${t} contains a non-JSON value.`);if(r.has(a.value))throw new Error(`${t} contains a cycle.`);r.add(a.value);for(let[i,c]of Object.entries(a.value)){if(b(i))throw new Error(`${t} contains a possible card number.`);let s=i.toLowerCase(),l=s.replace(/[^a-z0-9]/g,""),u=l.replace(/[0-9]+$/,"").replace(/(cvv|cvc|csc|cid|cav)[0-9]+/g,"$1");if(["__proto__","prototype","constructor"].includes(s)||["pan","cardnumber"].includes(l)||["cvv","cvc","cav"].some(m=>["","value","code","number"].some(d=>u.endsWith(m+d)))||["csc","cid"].some(m=>["","value","code","number"].some(d=>u===m+d||["card","amex","americanexpress"].some(p=>u.endsWith(p+m+d))))||u.endsWith("cardidentificationnumber")||u.endsWith("cardsecuritynumber")||["securitycode","securityvalue","verificationcode","verificationnumber","verificationvalue"].some(m=>u.endsWith(m)))throw new Error(`${t} contains a forbidden field.`);n.push({value:c,depth:a.depth+1});}}}}function b(e){let t="";for(let n of e)if(n>="0"&&n<="9"){t=(t+n).slice(-19);for(let r=12;r<=t.length;r+=1)if(te(t.slice(-r)))return true}else {if(/^\p{Nd}$/u.test(n))return true;if(/^[\s\p{P}\p{S}\p{M}\p{Cc}\p{Cf}]$/u.test(n))continue;t="";}return false}function h(e,t){if(e!==void 0&&(typeof e!="string"||b(e)))throw new Error(`${t} contains a possible card number.`)}function te(e){if(!/^[0-9]{12,19}$/.test(e))return false;let t=0,n=false;for(let r=e.length-1;r>=0;r-=1){let o=e.charCodeAt(r)-48;n&&(o*=2,o>9&&(o-=9)),t+=o,n=!n;}return t%10===0}function N(e,t,n){let r;try{r=new URL(e);}catch(a){throw new Error(`${n} must be an absolute URL.`)}let o=t==="test"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(r.protocol!=="https:"&&!(o&&r.protocol==="http:")||r.username||r.password||e.length>2048)throw new Error(`${n} must be a safe HTTPS URL.`)}function ne(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid checkout response.");let t=e;if(!S(t.id)||typeof t.url!="string"||typeof t.expires_at!="string")throw new Error("Invalid checkout response.");if(Number.isNaN(Date.parse(t.expires_at)))throw new Error("Invalid checkout response.");return {id:t.id,url:t.url,expires_at:t.expires_at}}function re(e,t,n){let r;try{r=new URL(e);}catch(o){throw new Error("Invalid checkout URL in API response.")}if(r.origin!==new URL(n).origin||r.username||r.password||r.protocol!==new URL(n).protocol||r.pathname!==`/c/${t}`||r.search||r.hash)throw new Error("Invalid checkout URL in API response.");return r}async function oe(e,t){let n=e.headers.get("content-length");if(n!==null&&(!/^\d+$/.test(n)||Number(n)>t))throw new Error("Checkout response exceeds the configured limit.");if(!e.body)return;let r=e.body.getReader(),o=[],a=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(u){if(a+=u.byteLength,a>t)throw await r.cancel("response limit exceeded"),new Error("Checkout response exceeds the configured limit.");o.push(u);}}}finally{r.releaseLock();}let i=new Uint8Array(a),c=0;for(let l of o)i.set(l,c),c+=l.byteLength;let s=new TextDecoder().decode(i);if(s.trim().length!==0)try{return JSON.parse(s)}catch(l){throw new Error("Checkout response is not valid JSON.")}}function ae(){let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return `widget_${e.randomUUID()}`;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("A secure random generator is required to create an Idempotency-Key.");let t=new Uint8Array(16);return e.getRandomValues(t),`widget_${Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}`}function ie(e){if(e.length<1||e.length>128||!/^[\x21-\x7e]+$/.test(e))throw new Error("idempotencyKey must contain 1-128 visible ASCII characters.");return e}function se(e){var t;return {environment:e.dataset.environment,publishableKey:(t=e.dataset.publishableKey)!=null?t:"",...e.dataset.checkoutBaseUrl?{checkoutBaseUrl:e.dataset.checkoutBaseUrl}:{},...e.dataset.apiBaseUrl?{apiBaseUrl:e.dataset.apiBaseUrl}:{},...e.dataset.locale?{locale:e.dataset.locale}:{}}}function ce(e){var t,n,r,o,a;return {items:[{name:(t=e.dataset.itemName)!=null?t:"",quantity:Number((n=e.dataset.quantity)!=null?n:"1"),unit_amount_cents:Number((r=e.dataset.unitAmountCents)!=null?r:"")}],success_url:(o=e.dataset.successUrl)!=null?o:"",cancel_url:(a=e.dataset.cancelUrl)!=null?a:""}}function ue(e){if(e){if(e.primaryColor!==void 0&&(!P("color",e.primaryColor)||/url\s*\(/i.test(e.primaryColor)))throw new Error("theme.primaryColor is invalid.");if(e.accentColor!==void 0&&(!P("color",e.accentColor)||/url\s*\(/i.test(e.accentColor)))throw new Error("theme.accentColor is invalid.");if(e.borderRadius!==void 0&&(!P("border-radius",e.borderRadius)||/url\s*\(/i.test(e.borderRadius)))throw new Error("theme.borderRadius is invalid.");if(e.fontFamily!==void 0&&!/^[A-Za-z0-9 ,_'"-]{1,200}$/.test(e.fontFamily))throw new Error("theme.fontFamily is invalid.")}}function P(e,t){var n;return typeof((n=globalThis.CSS)==null?void 0:n.supports)=="function"&&globalThis.CSS.supports(e,t)}function U(e,t,n,r){e!==void 0&&E(e,t,n,r);}function E(e,t,n,r){if(!Number.isSafeInteger(e)||e<t||e>n)throw new Error(`${r} is invalid.`)}function q(e,t,n){if(typeof e!="string"||e.trim().length<1||e.length>t||/[\x00-\x1f\x7f]/.test(e))throw new Error(`${n} is invalid.`)}function g(e,t,n){e!==void 0&&q(e,t,n);}function j(e,t){if(e!==void 0&&typeof e!="boolean")throw new Error(`${t} is invalid.`)}function S(e){return typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function le(e){return (e instanceof Error?e.message:"Checkout failed.").replace(/[\r\n\t]+/g," ").slice(0,256)}var W=K;var D={MuPag:y,init:M,version:W};typeof window!="undefined"&&(window.MuPagWidget=D,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>M(document),{once:true}):M(document));var pe=D;return pe;})();//# sourceMappingURL=widget.global.js.map
|
|
10
|
+
//# sourceMappingURL=widget.global.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/global.ts"],"names":["VERSION","API_BASE_URLS","CHECKOUT_BASE_URLS","DEFAULT_IFRAME_TIMEOUT_MS","DEFAULT_REQUEST_TIMEOUT_MS","DEFAULT_MAX_RESPONSE_BYTES","MAX_REQUEST_BYTES","MAX_MONEY_CENTS","DATA_BOUND","trimSlash","value","resolveLocale","locale","appendWidgetParams","url","options","_a","createModal","theme","onClose","_b","_c","host","root","overlay","dialog","close","iframe","primary","radius","font","css","sheet","style","isMuPagMessage","data","MuPag","_d","_e","_f","_g","validateOptions","allowedOrigin","params","onSuccess","onError","idempotencyKey","body","validateCheckout","encodedBody","canonicalBody","e","key","createIdempotencyKey","validateIdempotencyKey","controller","timer","response","error","responseBody","readBoundedJson","payload","checkoutResponse","checkoutUrl","safeCheckoutUrl","callbacks","checkoutOrigin","active","event","_h","_i","_j","_k","charge","initDataAttributes","button","dataOptions","dataCheckout","dispatchWidgetError","safeErrorMessage","expectedPrefix","boundedInteger","validateTheme","canonical","environment","field","loopback","isCanonical","explicitCheckoutDomain","isIpAddress","hostname","onlyKeys","total","item","text","rejectPANLikeOptionalText","integer","lineTotal","redirectUrl","uuid","optionalText","method","jsonObject","optionalBoolean","allowed","allowlist","unsupported","stack","seen","nodes","current","containsPANLikeSequence","child","normalized","compact","sensitiveBase","token","descriptor","qualifier","suffix","retainedDigits","character","length","validPANSequence","digits","sum","doubleDigit","index","digit","sessionId","baseUrl","maximumBytes","reader","chunks","done","buffer","offset","chunk","textBody","cryptoApi","bytes","entry","cssSupports","property","minimum","maximum","version","namespace","global_default"],"mappings":"yCA0BA,IAAMA,CAAAA,CAAU,OAAA,CACVC,CAAAA,CAAkD,CACtD,IAAA,CAAM,kCAAA,CACN,GAAA,CAAK,0BACP,CAAA,CACMC,CAAAA,CAAuD,CAC3D,IAAA,CAAM,wCACN,GAAA,CAAK,+BACP,CAAA,CACMC,CAAAA,CAA4B,GAAA,CAC5BC,CAAAA,CAA6B,IAAA,CAC7BC,CAAAA,CAA6B,IAAM,IAAA,CACnCC,CAAAA,CAAoB,IAAA,CAAO,IAAA,CAC3BC,CAAAA,CAAkB,IAAA,CAClBC,CAAAA,CAAa,kBAAA,CAYnB,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AQ,CAAA,CAAA,KAIxB0E,EAAAA,CAAQD","file":"widget.global.js","sourcesContent":["import type {\n Charge,\n CheckoutParams,\n MuPagCallbacks,\n MuPagEnvironment,\n MuPagLocale,\n MuPagMessage,\n MuPagOptions,\n MuPagTheme,\n MuPagWidgetError,\n} from \"./types.js\";\n\nexport type {\n Charge,\n CheckoutCustomer,\n CheckoutItem,\n CheckoutParams,\n MuPagCallbacks,\n MuPagEnvironment,\n MuPagLocale,\n MuPagOptions,\n MuPagTheme,\n MuPagMessage,\n MuPagWidgetError,\n} from \"./types.js\";\n\nconst VERSION = \"0.1.0\";\nconst API_BASE_URLS: Record<MuPagEnvironment, string> = {\n test: \"https://api.sandbox.mupag.com.br\",\n prd: \"https://api.mupag.com.br\",\n};\nconst CHECKOUT_BASE_URLS: Record<MuPagEnvironment, string> = {\n test: \"https://checkout.sandbox.mupag.com.br\",\n prd: \"https://checkout.mupag.com.br\",\n};\nconst DEFAULT_IFRAME_TIMEOUT_MS = 8_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 15_000;\nconst DEFAULT_MAX_RESPONSE_BYTES = 256 * 1024;\nconst MAX_REQUEST_BYTES = 1024 * 1024;\nconst MAX_MONEY_CENTS = 9_000_000_000_000_000;\nconst DATA_BOUND = \"mupagWidgetBound\";\n\ninterface ActiveModal {\n host: HTMLElement;\n iframe: HTMLIFrameElement;\n checkoutOrigin: string;\n callbacks: MuPagCallbacks;\n fallbackUrl: string;\n loaded: boolean;\n loadTimer: number | undefined;\n}\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction resolveLocale(locale: MuPagOptions[\"locale\"]): MuPagLocale {\n if (locale === \"pt-BR\" || locale === \"en-US\") {\n return locale;\n }\n if (typeof navigator !== \"undefined\" && navigator.language.toLowerCase().startsWith(\"en\")) {\n return \"en-US\";\n }\n return \"pt-BR\";\n}\n\nfunction appendWidgetParams(url: URL, options: Required<Pick<MuPagOptions, \"checkoutBaseUrl\">> & MuPagOptions): URL {\n const locale = resolveLocale(options.locale);\n url.searchParams.set(\"locale\", locale);\n if (options.theme && Object.keys(options.theme).length > 0) {\n url.searchParams.set(\"theme\", JSON.stringify(options.theme));\n }\n if (typeof window !== \"undefined\" && window.location?.origin) {\n url.searchParams.set(\"parent_origin\", window.location.origin);\n }\n return url;\n}\n\nfunction createModal(url: string, theme: MuPagTheme | undefined, onClose: () => void): { host: HTMLElement; iframe: HTMLIFrameElement } {\n const host = document.createElement(\"div\");\n host.dataset.mupagWidgetRoot = \"true\";\n const root = host.attachShadow({ mode: \"open\" });\n const overlay = document.createElement(\"div\");\n overlay.setAttribute(\"part\", \"overlay\");\n const dialog = document.createElement(\"section\");\n dialog.setAttribute(\"part\", \"dialog\");\n dialog.setAttribute(\"role\", \"dialog\");\n dialog.setAttribute(\"aria-modal\", \"true\");\n dialog.setAttribute(\"aria-label\", \"Checkout seguro MuPag\");\n const close = document.createElement(\"button\");\n close.type = \"button\";\n close.textContent = \"Fechar\";\n close.setAttribute(\"part\", \"close\");\n close.addEventListener(\"click\", onClose);\n const iframe = document.createElement(\"iframe\");\n iframe.src = url;\n iframe.title = \"Checkout seguro MuPag\";\n iframe.allow = \"payment *\";\n iframe.referrerPolicy = \"strict-origin-when-cross-origin\";\n iframe.setAttribute(\"part\", \"iframe\");\n iframe.setAttribute(\"loading\", \"eager\");\n iframe.setAttribute(\n \"sandbox\",\n \"allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation\",\n );\n dialog.append(close, iframe);\n overlay.append(dialog);\n\n const primary = theme?.primaryColor ?? \"#176bff\";\n const radius = theme?.borderRadius ?? \"18px\";\n const font = theme?.fontFamily ?? \"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif\";\n const css = `\n :host{all:initial;--gw-primary:${primary};--gw-radius:${radius};font-family:${font}}\n [part=overlay]{position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(10,18,32,.54);padding:24px}\n [part=dialog]{position:relative;width:min(100%,760px);height:min(92vh,860px);overflow:hidden;border-radius:var(--gw-radius);background:#fff;box-shadow:0 24px 80px rgba(10,18,32,.28)}\n [part=close]{position:absolute;right:12px;top:10px;z-index:2;border:1px solid rgba(15,23,42,.16);border-radius:999px;background:#fff;color:#243044;font:600 13px/1.2 inherit;padding:8px 12px;cursor:pointer}\n [part=close]:focus{outline:3px solid color-mix(in srgb,var(--gw-primary) 35%,transparent);outline-offset:2px}\n [part=iframe]{display:block;width:100%;height:100%;border:0;background:#fff}\n @media (max-width:640px){[part=overlay]{align-items:stretch;padding:0;background:#fff}[part=dialog]{width:100%;height:100vh;max-height:none;border-radius:0;box-shadow:none}[part=close]{right:10px;top:8px}}\n `;\n if (\"adoptedStyleSheets\" in root && \"CSSStyleSheet\" in window) {\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(css);\n root.adoptedStyleSheets = [sheet];\n root.append(overlay);\n } else {\n const style = document.createElement(\"style\");\n style.textContent = css;\n root.append(style, overlay);\n }\n document.body.append(host);\n return { host, iframe };\n}\n\nfunction isMuPagMessage(data: unknown): data is MuPagMessage {\n if (!data || typeof data !== \"object\" || !(\"type\" in data) || typeof data.type !== \"string\") {\n return false;\n }\n return [\"mupag:loaded\", \"mupag:payment_completed\", \"mupag:close\", \"mupag:error\"].includes(data.type);\n}\n\nexport class MuPag {\n private readonly options: Required<\n Pick<\n MuPagOptions,\n | \"checkoutBaseUrl\"\n | \"apiBaseUrl\"\n | \"fetch\"\n | \"fallbackRedirect\"\n | \"iframeLoadTimeoutMs\"\n | \"requestTimeoutMs\"\n | \"maxResponseBytes\"\n >\n > &\n MuPagOptions;\n private active: ActiveModal | null = null;\n\n constructor(options: MuPagOptions) {\n validateOptions(options);\n this.options = {\n ...options,\n checkoutBaseUrl: allowedOrigin(\n options.checkoutBaseUrl ?? CHECKOUT_BASE_URLS[options.environment],\n CHECKOUT_BASE_URLS[options.environment],\n options.environment,\n \"checkoutBaseUrl\",\n ),\n apiBaseUrl: allowedOrigin(\n options.apiBaseUrl ?? API_BASE_URLS[options.environment],\n API_BASE_URLS[options.environment],\n options.environment,\n \"apiBaseUrl\",\n ),\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n fallbackRedirect: options.fallbackRedirect ?? true,\n iframeLoadTimeoutMs: options.iframeLoadTimeoutMs ?? DEFAULT_IFRAME_TIMEOUT_MS,\n requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,\n };\n this.handleMessage = this.handleMessage.bind(this);\n }\n\n async openCheckout(params: CheckoutParams): Promise<void> {\n if (!params || typeof params !== \"object\" || Array.isArray(params)) {\n throw new Error(\"Checkout params must be an object.\");\n }\n const { onSuccess, onClose, onError, idempotencyKey, ...body } = params;\n validateCheckout(body, this.options.environment);\n let encodedBody: string;\n let canonicalBody: typeof body;\n try {\n encodedBody = JSON.stringify(body);\n canonicalBody = JSON.parse(encodedBody) as typeof body;\n } catch {\n throw new Error(\"Checkout payload must be valid JSON.\");\n }\n validateCheckout(canonicalBody, this.options.environment);\n if (new TextEncoder().encode(encodedBody).byteLength > MAX_REQUEST_BYTES) {\n throw new Error(\"Checkout payload exceeds the safe 1 MiB limit.\");\n }\n const key = idempotencyKey === undefined ? createIdempotencyKey() : validateIdempotencyKey(idempotencyKey);\n const controller = new AbortController();\n const timer = window.setTimeout(() => controller.abort(), this.options.requestTimeoutMs);\n let response: Response;\n try {\n response = await this.options.fetch(`${this.options.apiBaseUrl}/v1/checkout-sessions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${this.options.publishableKey}`,\n \"Idempotency-Key\": key,\n },\n body: encodedBody,\n signal: controller.signal,\n });\n } catch {\n const error = { code: \"checkout_network_error\", message: \"Checkout session request failed.\" };\n onError?.(error);\n throw new Error(error.message);\n } finally {\n window.clearTimeout(timer);\n }\n const responseBody = await readBoundedJson(response, this.options.maxResponseBytes);\n if (!response.ok) {\n const error = { code: \"checkout_session_failed\", message: `Checkout session failed (${response.status}).` };\n onError?.(error);\n throw new Error(error.message);\n }\n const payload = checkoutResponse(responseBody);\n const checkoutUrl = safeCheckoutUrl(payload.url, payload.id, this.options.checkoutBaseUrl);\n const url = appendWidgetParams(checkoutUrl, this.options);\n const callbacks: MuPagCallbacks = {};\n if (onSuccess) {\n callbacks.onSuccess = onSuccess;\n }\n if (onClose) {\n callbacks.onClose = onClose;\n }\n if (onError) {\n callbacks.onError = onError;\n }\n this.openUrl(url.toString(), callbacks);\n }\n\n close(): void {\n if (!this.active) {\n return;\n }\n if (this.active.loadTimer) {\n window.clearTimeout(this.active.loadTimer);\n }\n window.removeEventListener(\"message\", this.handleMessage);\n this.active.host.remove();\n this.active = null;\n }\n\n private openUrl(url: string, callbacks: MuPagCallbacks): void {\n this.close();\n const checkoutOrigin = new URL(url).origin;\n const modal = createModal(url, this.options.theme, () => {\n callbacks.onClose?.();\n this.close();\n });\n const active: ActiveModal = {\n ...modal,\n checkoutOrigin,\n callbacks,\n fallbackUrl: url,\n loaded: false,\n loadTimer: undefined,\n };\n active.iframe.addEventListener(\"load\", () => {\n active.loaded = true;\n if (active.loadTimer) {\n window.clearTimeout(active.loadTimer);\n }\n });\n active.loadTimer = window.setTimeout(() => {\n if (!active.loaded && this.options.fallbackRedirect) {\n window.location.assign(active.fallbackUrl);\n }\n }, this.options.iframeLoadTimeoutMs);\n this.active = active;\n window.addEventListener(\"message\", this.handleMessage);\n }\n\n private handleMessage(event: MessageEvent): void {\n if (\n !this.active ||\n event.origin !== this.active.checkoutOrigin ||\n event.source === null ||\n this.active.iframe.contentWindow === null ||\n event.source !== this.active.iframe.contentWindow ||\n !isMuPagMessage(event.data)\n ) {\n return;\n }\n if (event.data.type === \"mupag:loaded\") {\n this.active.loaded = true;\n return;\n }\n if (event.data.type === \"mupag:payment_completed\") {\n const charge = event.data.charge ?? event.data.payload?.charge ?? ({ status: \"paid\", ...event.data.payload } as Charge);\n this.active.callbacks.onSuccess?.(charge);\n this.close();\n return;\n }\n if (event.data.type === \"mupag:close\") {\n this.active.callbacks.onClose?.();\n this.close();\n return;\n }\n if (event.data.type === \"mupag:error\") {\n this.active.callbacks.onError?.(event.data.error ?? event.data.payload ?? { code: \"checkout_error\", message: \"Checkout error.\" });\n }\n }\n}\n\nexport function initDataAttributes(root: ParentNode = document): void {\n const buttons = root.querySelectorAll<HTMLElement>(\"[data-mupag-widget]\");\n buttons.forEach((button) => {\n if (button.dataset[DATA_BOUND] === \"true\") {\n return;\n }\n button.dataset[DATA_BOUND] = \"true\";\n button.addEventListener(\"click\", () => {\n try {\n const options = dataOptions(button);\n const theme: MuPagTheme = {};\n if (button.dataset.primaryColor) {\n theme.primaryColor = button.dataset.primaryColor;\n }\n if (button.dataset.accentColor) {\n theme.accentColor = button.dataset.accentColor;\n }\n if (button.dataset.fontFamily) {\n theme.fontFamily = button.dataset.fontFamily;\n }\n if (Object.keys(theme).length > 0) {\n options.theme = theme;\n }\n const mupag = new MuPag(options);\n void mupag.openCheckout(dataCheckout(button)).catch((error: unknown) => dispatchWidgetError(button, error));\n } catch (error) {\n dispatchWidgetError(button, error);\n }\n });\n });\n}\n\nfunction dispatchWidgetError(button: HTMLElement, error: unknown): void {\n button.dispatchEvent(\n new CustomEvent(\"mupag:error\", {\n detail: { code: \"checkout_failed\", message: safeErrorMessage(error) },\n }),\n );\n}\n\nfunction validateOptions(options: MuPagOptions): void {\n if (!options || (options.environment !== \"test\" && options.environment !== \"prd\")) {\n throw new Error(\"environment must be explicitly test or prd.\");\n }\n const expectedPrefix = options.environment === \"test\" ? \"pk_test_\" : \"pk_prd_\";\n if (\n typeof options.publishableKey !== \"string\" ||\n !options.publishableKey.startsWith(expectedPrefix) ||\n options.publishableKey.length > 512 ||\n !/^[\\x21-\\x7e]+$/.test(options.publishableKey)\n ) {\n throw new Error(\"publishableKey is invalid or does not match the selected environment.\");\n }\n boundedInteger(options.iframeLoadTimeoutMs, 1, 120_000, \"iframeLoadTimeoutMs\");\n boundedInteger(options.requestTimeoutMs, 1, 120_000, \"requestTimeoutMs\");\n boundedInteger(options.maxResponseBytes, 1, 4 * 1024 * 1024, \"maxResponseBytes\");\n validateTheme(options.theme);\n}\n\nfunction allowedOrigin(value: string, canonical: string, environment: MuPagEnvironment, field: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${field} is invalid.`);\n }\n const loopback = environment === \"test\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n const isCanonical = url.origin === new URL(canonical).origin;\n const explicitCheckoutDomain = field === \"checkoutBaseUrl\" && url.protocol === \"https:\" && !isIpAddress(url.hostname);\n if (\n (!isCanonical && !loopback && !explicitCheckoutDomain) ||\n (url.protocol !== \"https:\" && !(loopback && url.protocol === \"http:\")) ||\n url.username ||\n url.password ||\n (url.pathname !== \"\" && url.pathname !== \"/\") ||\n url.search ||\n url.hash\n ) {\n throw new Error(`${field} is not an allowed origin.`);\n }\n return trimSlash(url.origin);\n}\n\nfunction isIpAddress(hostname: string): boolean {\n return /^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(hostname) || hostname.includes(\":\");\n}\n\nfunction validateCheckout(body: Omit<CheckoutParams, keyof MuPagCallbacks | \"idempotencyKey\">, environment: MuPagEnvironment): void {\n onlyKeys(\n body,\n [\n \"items\",\n \"success_url\",\n \"cancel_url\",\n \"customer_id\",\n \"customer_data\",\n \"allowed_payment_methods\",\n \"affiliate_code\",\n \"coupon_id\",\n \"utm_params\",\n \"expires_in_minutes\",\n \"metadata\",\n \"collect_shipping_address\",\n \"delivery_type\",\n \"allow_coupons\",\n ],\n \"checkout\",\n );\n if (!Array.isArray(body.items) || body.items.length < 1 || body.items.length > 100) {\n throw new Error(\"Checkout items must contain between 1 and 100 entries.\");\n }\n let total = 0;\n for (const item of body.items) {\n onlyKeys(item, [\"name\", \"quantity\", \"unit_amount_cents\"], \"checkout item\");\n text(item.name, 200, \"item.name\");\n rejectPANLikeOptionalText(item.name, \"item.name\");\n integer(item.quantity, 1, 1_000_000, \"item.quantity\");\n integer(item.unit_amount_cents, 100, MAX_MONEY_CENTS, \"item.unit_amount_cents\");\n const lineTotal = item.quantity * item.unit_amount_cents;\n if (!Number.isSafeInteger(lineTotal) || lineTotal > MAX_MONEY_CENTS) {\n throw new Error(\"Checkout item total is outside the supported range.\");\n }\n total += lineTotal;\n if (!Number.isSafeInteger(total) || total > MAX_MONEY_CENTS) {\n throw new Error(\"Checkout total is outside the supported range.\");\n }\n }\n redirectUrl(body.success_url, environment, \"success_url\");\n redirectUrl(body.cancel_url, environment, \"cancel_url\");\n if (body.customer_id !== undefined && body.customer_data !== undefined) {\n throw new Error(\"customer_id and customer_data are mutually exclusive.\");\n }\n if (body.customer_id !== undefined && !uuid(body.customer_id)) {\n throw new Error(\"customer_id must be a UUID.\");\n }\n rejectPANLikeOptionalText(body.customer_id, \"customer_id\");\n if (body.customer_data !== undefined) {\n onlyKeys(body.customer_data, [\"name\", \"email\", \"document\", \"phone\"], \"customer_data\");\n optionalText(body.customer_data.name, 200, \"customer_data.name\");\n rejectPANLikeOptionalText(body.customer_data.name, \"customer_data.name\");\n optionalText(body.customer_data.email, 320, \"customer_data.email\");\n rejectPANLikeOptionalText(body.customer_data.email, \"customer_data.email\");\n optionalText(body.customer_data.document, 64, \"customer_data.document\");\n optionalText(body.customer_data.phone, 32, \"customer_data.phone\");\n }\n if (\n body.allowed_payment_methods !== undefined &&\n (!Array.isArray(body.allowed_payment_methods) ||\n body.allowed_payment_methods.length < 1 ||\n body.allowed_payment_methods.length > 2 ||\n new Set(body.allowed_payment_methods).size !== body.allowed_payment_methods.length ||\n body.allowed_payment_methods.some((method) => method !== \"pix\" && method !== \"credit_card\"))\n ) {\n throw new Error(\"allowed_payment_methods is invalid.\");\n }\n optionalText(body.affiliate_code, 128, \"affiliate_code\");\n rejectPANLikeOptionalText(body.affiliate_code, \"affiliate_code\");\n if (body.coupon_id !== undefined && !uuid(body.coupon_id)) throw new Error(\"coupon_id must be a UUID.\");\n if (body.allow_coupons === false && body.coupon_id !== undefined) {\n throw new Error(\"coupon_id cannot be used when allow_coupons is false.\");\n }\n if (body.expires_in_minutes !== undefined) integer(body.expires_in_minutes, 1, 24 * 60, \"expires_in_minutes\");\n if (body.metadata !== undefined) jsonObject(body.metadata, \"metadata\");\n if (body.utm_params !== undefined) jsonObject(body.utm_params, \"utm_params\");\n optionalText(body.delivery_type, 64, \"delivery_type\");\n rejectPANLikeOptionalText(body.delivery_type, \"delivery_type\");\n optionalBoolean(body.collect_shipping_address, \"collect_shipping_address\");\n optionalBoolean(body.allow_coupons, \"allow_coupons\");\n}\n\nfunction onlyKeys(value: unknown, allowed: readonly string[], field: string): asserts value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {\n throw new Error(`${field} must be a plain object.`);\n }\n const allowlist = new Set(allowed);\n const unsupported = Object.keys(value).find((key) => !allowlist.has(key));\n if (unsupported !== undefined) {\n throw new Error(`${field} contains unsupported field ${unsupported}.`);\n }\n}\n\nfunction jsonObject(value: object, field: string): void {\n if (value === null || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {\n throw new Error(`${field} must be a plain JSON object.`);\n }\n const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];\n const seen = new WeakSet<object>();\n let nodes = 0;\n while (stack.length > 0) {\n const current = stack.pop();\n if (!current) break;\n nodes += 1;\n if (nodes > 10_000 || current.depth > 32) throw new Error(`${field} is too complex.`);\n if (current.value === null || typeof current.value === \"boolean\") continue;\n if (typeof current.value === \"string\") {\n if (containsPANLikeSequence(current.value)) throw new Error(`${field} contains a possible card number.`);\n continue;\n }\n if (typeof current.value === \"number\") {\n if (!Number.isFinite(current.value)) throw new Error(`${field} contains an invalid number.`);\n if (containsPANLikeSequence(JSON.stringify(current.value))) {\n throw new Error(`${field} contains a possible card number.`);\n }\n continue;\n }\n if (typeof current.value !== \"object\") throw new Error(`${field} contains a non-JSON value.`);\n if (seen.has(current.value)) throw new Error(`${field} contains a cycle.`);\n seen.add(current.value);\n for (const [key, child] of Object.entries(current.value)) {\n if (containsPANLikeSequence(key)) {\n throw new Error(`${field} contains a possible card number.`);\n }\n const normalized = key.toLowerCase();\n const compact = normalized.replace(/[^a-z0-9]/g, \"\");\n const sensitiveBase = compact\n .replace(/[0-9]+$/, \"\")\n .replace(/(cvv|cvc|csc|cid|cav)[0-9]+/g, \"$1\");\n if (\n [\"__proto__\", \"prototype\", \"constructor\"].includes(normalized)\n || [\"pan\", \"cardnumber\"].includes(compact)\n || [\"cvv\", \"cvc\", \"cav\"].some((token) =>\n [\"\", \"value\", \"code\", \"number\"].some((descriptor) => sensitiveBase.endsWith(token + descriptor))\n )\n || [\"csc\", \"cid\"].some((token) =>\n [\"\", \"value\", \"code\", \"number\"].some(\n (descriptor) =>\n sensitiveBase === token + descriptor\n || [\"card\", \"amex\", \"americanexpress\"].some((qualifier) =>\n sensitiveBase.endsWith(qualifier + token + descriptor)\n )\n )\n )\n || sensitiveBase.endsWith(\"cardidentificationnumber\")\n || sensitiveBase.endsWith(\"cardsecuritynumber\")\n || [\n \"securitycode\",\n \"securityvalue\",\n \"verificationcode\",\n \"verificationnumber\",\n \"verificationvalue\",\n ].some((suffix) => sensitiveBase.endsWith(suffix))\n ) {\n throw new Error(`${field} contains a forbidden field.`);\n }\n stack.push({ value: child, depth: current.depth + 1 });\n }\n }\n}\n\nfunction containsPANLikeSequence(value: string): boolean {\n let retainedDigits = \"\";\n\n for (const character of value) {\n if (character >= \"0\" && character <= \"9\") {\n retainedDigits = (retainedDigits + character).slice(-19);\n for (let length = 12; length <= retainedDigits.length; length += 1) {\n if (validPANSequence(retainedDigits.slice(-length))) return true;\n }\n } else if (/^\\p{Nd}$/u.test(character)) {\n return true;\n } else if (/^[\\s\\p{P}\\p{S}\\p{M}\\p{Cc}\\p{Cf}]$/u.test(character)) {\n continue;\n } else {\n retainedDigits = \"\";\n }\n }\n return false;\n}\n\nfunction rejectPANLikeOptionalText(value: unknown, field: string): void {\n if (value !== undefined && (typeof value !== \"string\" || containsPANLikeSequence(value))) {\n throw new Error(`${field} contains a possible card number.`);\n }\n}\n\nfunction validPANSequence(digits: string): boolean {\n if (!/^[0-9]{12,19}$/.test(digits)) return false;\n let sum = 0;\n let doubleDigit = false;\n for (let index = digits.length - 1; index >= 0; index -= 1) {\n let digit = digits.charCodeAt(index) - 48;\n if (doubleDigit) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n sum += digit;\n doubleDigit = !doubleDigit;\n }\n return sum % 10 === 0;\n}\n\nfunction redirectUrl(value: string, environment: MuPagEnvironment, field: string): void {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${field} must be an absolute URL.`);\n }\n const loopback = environment === \"test\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n if ((url.protocol !== \"https:\" && !(loopback && url.protocol === \"http:\")) || url.username || url.password || value.length > 2048) {\n throw new Error(`${field} must be a safe HTTPS URL.`);\n }\n}\n\nfunction checkoutResponse(value: unknown): { id: string; url: string; expires_at: string } {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Invalid checkout response.\");\n const response = value as Record<string, unknown>;\n if (!uuid(response.id) || typeof response.url !== \"string\" || typeof response.expires_at !== \"string\") {\n throw new Error(\"Invalid checkout response.\");\n }\n if (Number.isNaN(Date.parse(response.expires_at))) throw new Error(\"Invalid checkout response.\");\n return { id: response.id, url: response.url, expires_at: response.expires_at };\n}\n\nfunction safeCheckoutUrl(value: string, sessionId: string, baseUrl: string): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(\"Invalid checkout URL in API response.\");\n }\n if (\n url.origin !== new URL(baseUrl).origin ||\n url.username ||\n url.password ||\n url.protocol !== new URL(baseUrl).protocol ||\n url.pathname !== `/c/${sessionId}` ||\n url.search ||\n url.hash\n ) {\n throw new Error(\"Invalid checkout URL in API response.\");\n }\n return url;\n}\n\nasync function readBoundedJson(response: Response, maximumBytes: number): Promise<unknown> {\n const length = response.headers.get(\"content-length\");\n if (length !== null && (!/^\\d+$/.test(length) || Number(length) > maximumBytes)) {\n throw new Error(\"Checkout response exceeds the configured limit.\");\n }\n if (!response.body) return undefined;\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n total += value.byteLength;\n if (total > maximumBytes) {\n await reader.cancel(\"response limit exceeded\");\n throw new Error(\"Checkout response exceeds the configured limit.\");\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n const buffer = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n const textBody = new TextDecoder().decode(buffer);\n if (textBody.trim().length === 0) return undefined;\n try {\n return JSON.parse(textBody) as unknown;\n } catch {\n throw new Error(\"Checkout response is not valid JSON.\");\n }\n}\n\nfunction createIdempotencyKey(): string {\n const cryptoApi = globalThis.crypto;\n if (typeof cryptoApi?.randomUUID === \"function\") return `widget_${cryptoApi.randomUUID()}`;\n if (typeof cryptoApi?.getRandomValues !== \"function\") {\n throw new Error(\"A secure random generator is required to create an Idempotency-Key.\");\n }\n const bytes = new Uint8Array(16);\n cryptoApi.getRandomValues(bytes);\n return `widget_${Array.from(bytes, (entry) => entry.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction validateIdempotencyKey(value: string): string {\n if (value.length < 1 || value.length > 128 || !/^[\\x21-\\x7e]+$/.test(value)) {\n throw new Error(\"idempotencyKey must contain 1-128 visible ASCII characters.\");\n }\n return value;\n}\n\nfunction dataOptions(button: HTMLElement): MuPagOptions {\n return {\n environment: button.dataset.environment as MuPagEnvironment,\n publishableKey: button.dataset.publishableKey ?? \"\",\n ...(button.dataset.checkoutBaseUrl ? { checkoutBaseUrl: button.dataset.checkoutBaseUrl } : {}),\n ...(button.dataset.apiBaseUrl ? { apiBaseUrl: button.dataset.apiBaseUrl } : {}),\n ...(button.dataset.locale ? { locale: button.dataset.locale as MuPagLocale | \"auto\" } : {}),\n };\n}\n\nfunction dataCheckout(button: HTMLElement): CheckoutParams {\n return {\n items: [\n {\n name: button.dataset.itemName ?? \"\",\n quantity: Number(button.dataset.quantity ?? \"1\"),\n unit_amount_cents: Number(button.dataset.unitAmountCents ?? \"\"),\n },\n ],\n success_url: button.dataset.successUrl ?? \"\",\n cancel_url: button.dataset.cancelUrl ?? \"\",\n };\n}\n\nfunction validateTheme(theme: MuPagTheme | undefined): void {\n if (!theme) return;\n if (theme.primaryColor !== undefined && (!cssSupports(\"color\", theme.primaryColor) || /url\\s*\\(/i.test(theme.primaryColor))) {\n throw new Error(\"theme.primaryColor is invalid.\");\n }\n if (theme.accentColor !== undefined && (!cssSupports(\"color\", theme.accentColor) || /url\\s*\\(/i.test(theme.accentColor))) {\n throw new Error(\"theme.accentColor is invalid.\");\n }\n if (theme.borderRadius !== undefined && (!cssSupports(\"border-radius\", theme.borderRadius) || /url\\s*\\(/i.test(theme.borderRadius))) {\n throw new Error(\"theme.borderRadius is invalid.\");\n }\n if (theme.fontFamily !== undefined && !/^[A-Za-z0-9 ,_'\"-]{1,200}$/.test(theme.fontFamily)) {\n throw new Error(\"theme.fontFamily is invalid.\");\n }\n}\n\nfunction cssSupports(property: string, value: string): boolean {\n return typeof globalThis.CSS?.supports === \"function\" && globalThis.CSS.supports(property, value);\n}\n\nfunction boundedInteger(value: number | undefined, minimum: number, maximum: number, field: string): void {\n if (value !== undefined) integer(value, minimum, maximum, field);\n}\n\nfunction integer(value: number, minimum: number, maximum: number, field: string): void {\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw new Error(`${field} is invalid.`);\n}\n\nfunction text(value: unknown, maximum: number, field: string): void {\n if (typeof value !== \"string\" || value.trim().length < 1 || value.length > maximum || /[\\x00-\\x1f\\x7f]/.test(value)) {\n throw new Error(`${field} is invalid.`);\n }\n}\n\nfunction optionalText(value: unknown, maximum: number, field: string): void {\n if (value !== undefined) text(value, maximum, field);\n}\n\nfunction optionalBoolean(value: boolean | undefined, field: string): void {\n if (value !== undefined && typeof value !== \"boolean\") throw new Error(`${field} is invalid.`);\n}\n\nfunction uuid(value: unknown): value is string {\n return typeof value === \"string\" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);\n}\n\nfunction safeErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : \"Checkout failed.\";\n return message.replace(/[\\r\\n\\t]+/g, \" \").slice(0, 256);\n}\n\nexport const version = VERSION;\n","import { MuPag, initDataAttributes, version } from \"./index.js\";\nimport type { MuPagWidgetNamespace } from \"./types.js\";\n\nconst namespace: MuPagWidgetNamespace = {\n MuPag,\n init: initDataAttributes,\n version,\n};\n\nif (typeof window !== \"undefined\") {\n window.MuPagWidget = namespace;\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => initDataAttributes(document), { once: true });\n } else {\n initDataAttributes(document);\n }\n}\n\nexport default namespace;\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
<button
|
|
2
|
+
data-mupag-widget
|
|
3
|
+
data-environment="test"
|
|
4
|
+
data-publishable-key="{{ settings.mupag_publishable_key | escape }}"
|
|
5
|
+
data-item-name="{{ product.title | escape }}"
|
|
6
|
+
data-unit-amount-cents="{{ product.selected_or_first_available_variant.price }}"
|
|
7
|
+
data-quantity="1"
|
|
8
|
+
data-success-url="{{ shop.url }}/pages/pagamento-sucesso"
|
|
9
|
+
data-cancel-url="{{ shop.url }}{{ routes.cart_url }}"
|
|
10
|
+
data-primary-color="{{ settings.colors_accent_1 }}"
|
|
11
|
+
>
|
|
12
|
+
Comprar com MuPag
|
|
13
|
+
</button>
|
|
14
|
+
<script src="https://unpkg.com/@mupag/widget@0.1.0/dist/widget.global.js" defer></script>
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="pt-BR">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<title>MuPag widget vanilla</title>
|
|
7
|
+
</head>
|
|
8
|
+
<body>
|
|
9
|
+
<button
|
|
10
|
+
data-mupag-widget
|
|
11
|
+
data-environment="test"
|
|
12
|
+
data-publishable-key="pk_test_..."
|
|
13
|
+
data-item-name="Plano Pro"
|
|
14
|
+
data-unit-amount-cents="10990"
|
|
15
|
+
data-quantity="1"
|
|
16
|
+
data-success-url="https://merchant.example/pagamento/sucesso"
|
|
17
|
+
data-cancel-url="https://merchant.example/carrinho"
|
|
18
|
+
data-primary-color="#176bff"
|
|
19
|
+
>
|
|
20
|
+
Comprar agora
|
|
21
|
+
</button>
|
|
22
|
+
<script src="https://unpkg.com/@mupag/widget@0.1.0/dist/widget.global.js" defer></script>
|
|
23
|
+
</body>
|
|
24
|
+
</html>
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<button id="mupag-buy">Comprar com MuPag</button>
|
|
2
|
+
<script src="https://unpkg.com/@mupag/widget@0.1.0/dist/widget.global.js"></script>
|
|
3
|
+
<script>
|
|
4
|
+
document.getElementById("mupag-buy").addEventListener("click", function () {
|
|
5
|
+
const mupag = new window.MuPagWidget.MuPag({
|
|
6
|
+
environment: "test",
|
|
7
|
+
publishableKey: "pk_test_...",
|
|
8
|
+
});
|
|
9
|
+
mupag.openCheckout({
|
|
10
|
+
items: [{ name: "Plano Pro", quantity: 1, unit_amount_cents: 10990 }],
|
|
11
|
+
success_url: "https://merchant.example/pagamento/sucesso",
|
|
12
|
+
cancel_url: "https://merchant.example/carrinho",
|
|
13
|
+
}).catch(function () {
|
|
14
|
+
// Exiba uma mensagem amigável sem expor detalhes internos da resposta.
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
</script>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<!-- Cole no bloco HTML ou no template do tema WordPress. -->
|
|
2
|
+
<button
|
|
3
|
+
data-mupag-widget
|
|
4
|
+
data-environment="test"
|
|
5
|
+
data-publishable-key="pk_test_..."
|
|
6
|
+
data-item-name="Plano Pro"
|
|
7
|
+
data-unit-amount-cents="10990"
|
|
8
|
+
data-quantity="1"
|
|
9
|
+
data-success-url="https://merchant.example/pagamento/sucesso"
|
|
10
|
+
data-cancel-url="https://merchant.example/carrinho"
|
|
11
|
+
data-locale="pt-BR"
|
|
12
|
+
>
|
|
13
|
+
Comprar com MuPag
|
|
14
|
+
</button>
|
|
15
|
+
<script src="https://unpkg.com/@mupag/widget@0.1.0/dist/widget.global.js" defer></script>
|
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mupag/widget",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Browser widget SDK for embedding MuPag checkout in merchant sites.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": [
|
|
7
|
+
"./dist/widget.global.js"
|
|
8
|
+
],
|
|
9
|
+
"main": "./dist/index.cjs",
|
|
10
|
+
"module": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.js",
|
|
16
|
+
"require": "./dist/index.cjs"
|
|
17
|
+
},
|
|
18
|
+
"./widget.js": "./dist/widget.global.js"
|
|
19
|
+
},
|
|
20
|
+
"unpkg": "./dist/widget.global.js",
|
|
21
|
+
"jsdelivr": "./dist/widget.global.js",
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"examples",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsup",
|
|
29
|
+
"test": "vitest run && node --test scripts/readme-cdn.test.mjs",
|
|
30
|
+
"typecheck": "tsc --noEmit",
|
|
31
|
+
"lint": "tsc --noEmit",
|
|
32
|
+
"storybook": "STORYBOOK_DISABLE_TELEMETRY=1 storybook dev -p 6007",
|
|
33
|
+
"build-storybook": "STORYBOOK_DISABLE_TELEMETRY=1 storybook build",
|
|
34
|
+
"size": "npm run build && node scripts/check-bundle-size.mjs",
|
|
35
|
+
"check": "npm run typecheck && npm run test && npm run build && npm run size"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"mupag",
|
|
39
|
+
"checkout",
|
|
40
|
+
"widget",
|
|
41
|
+
"payments"
|
|
42
|
+
],
|
|
43
|
+
"author": "MuPag",
|
|
44
|
+
"license": "UNLICENSED",
|
|
45
|
+
"homepage": "https://docs.mupag.com.br",
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=18"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@types/node": "^22.15.21",
|
|
54
|
+
"@storybook/addon-essentials": "^8.6.14",
|
|
55
|
+
"@storybook/addon-interactions": "^8.6.14",
|
|
56
|
+
"@storybook/html": "^8.6.14",
|
|
57
|
+
"@storybook/html-vite": "^8.6.14",
|
|
58
|
+
"gzip-size": "^7.0.0",
|
|
59
|
+
"jsdom": "^26.1.0",
|
|
60
|
+
"storybook": "^8.6.14",
|
|
61
|
+
"tsup": "^8.5.0",
|
|
62
|
+
"typescript": "^5.8.3",
|
|
63
|
+
"vitest": "4.1.8"
|
|
64
|
+
},
|
|
65
|
+
"overrides": {
|
|
66
|
+
"uuid": "11.1.1",
|
|
67
|
+
"esbuild": "0.28.2"
|
|
68
|
+
}
|
|
69
|
+
}
|