mupag-sdk 0.2.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 +224 -0
- package/dist/chunk-FQHYME3I.js +2 -0
- package/dist/chunk-FQHYME3I.js.map +1 -0
- package/dist/chunk-M4RQIIHN.js +2 -0
- package/dist/chunk-M4RQIIHN.js.map +1 -0
- package/dist/errors.cjs +2 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +70 -0
- package/dist/errors.d.ts +70 -0
- package/dist/errors.js +2 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +133 -0
- package/dist/index.d.ts +133 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/types-C1s3-E1E.d.cts +225 -0
- package/dist/types-C1s3-E1E.d.ts +225 -0
- package/dist/webhooks.cjs +2 -0
- package/dist/webhooks.cjs.map +1 -0
- package/dist/webhooks.d.cts +18 -0
- package/dist/webhooks.d.ts +18 -0
- package/dist/webhooks.js +2 -0
- package/dist/webhooks.js.map +1 -0
- package/examples/card.ts +23 -0
- package/examples/pix.ts +20 -0
- package/examples/refund.ts +13 -0
- package/examples/subscription.ts +13 -0
- package/examples/webhook-validation.ts +20 -0
- package/package.json +67 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {b}from'./chunk-FQHYME3I.js';export{b as WebhooksResource,a as constructWebhookEvent}from'./chunk-FQHYME3I.js';import {a as a$1,i,g as g$1,b as b$1,c}from'./chunk-M4RQIIHN.js';export{b as APIError,e as AuthError,f as IdempotencyError,a as MuPagError,g as OutcomeUnknownError,c as RateLimitError,d as ValidationError,h as WebhookSignatureError,i as createApiError}from'./chunk-M4RQIIHN.js';function R(e){let n="";for(let t of e){let o=Te(t);if(o!==void 0){n=(n+o).slice(-19);for(let r=12;r<=n.length;r+=1)if(Ee(n.slice(-r)))return true}else {if(/^[\s\p{P}\p{S}\p{M}\p{Cc}\p{Cf}]$/u.test(t))continue;n="";}}return false}function Te(e){let n=e.codePointAt(0);if(n>=48&&n<=57)return e;if(!/^\p{Decimal_Number}$/u.test(e))return;let t=n;for(;t>0&&/^\p{Decimal_Number}$/u.test(String.fromCodePoint(t-1));)t-=1;return String((n-t)%10)}function Ee(e){if(!/^[0-9]{12,19}$/.test(e))return false;let n=0,t=false;for(let o=e.length-1;o>=0;o-=1){let r=e.charCodeAt(o)-48;t&&(r*=2,r>9&&(r-=9)),n+=r,t=!t;}return n%10===0}var X="0.2.0";var Se={maxRetries:2,initialDelayMs:200,maxDelayMs:2e3},Pe=2*1024*1024,Ae=16*1024*1024,xe=1024*1024,Ie=new Set(["fingerprint_conflict","idempotency_fingerprint_conflict","idempotency_key_reused"]),Z={test:"https://api.sandbox.mupag.com.br",prd:"https://api.mupag.com.br"},M=class{apiKey;baseUrl;fetcher;timeoutMs;maxResponseBytes;retry;constructor(n){if(typeof n.apiKey!="string"||!n.apiKey.trim()||n.apiKey.length>512||!/^[\x21-\x7e]+$/.test(n.apiKey))throw new a$1({message:"Informe uma apiKey valida para criar o cliente MuPag.",code:"missing_api_key",suggestion:"Use uma chave sk_test_ no sandbox ou sk_prd_ em producao."});if(n.env!=="test"&&n.env!=="prd")throw new a$1({message:"Informe explicitamente o ambiente test ou prd.",code:"missing_environment",suggestion:"Use env: test enquanto estiver integrando no sandbox."});let t=n.env==="test"?"sk_test_":"sk_prd_";if(!n.apiKey.startsWith(t))throw new a$1({message:"A apiKey informada nao pertence ao ambiente selecionado.",code:"api_key_environment_mismatch",suggestion:`Use uma chave ${t} no ambiente ${n.env}.`});this.apiKey=n.apiKey,this.baseUrl=je(n.baseUrl??Z[n.env],n.env);let o=n.fetch??globalThis.fetch;if(typeof o!="function")throw new a$1({message:"O runtime nao oferece fetch.",code:"fetch_unavailable"});this.fetcher=o.bind(globalThis),this.timeoutMs=n.timeoutMs??3e4,this.retry={...Se,...n.retry},this.maxResponseBytes=n.maxResponseBytes??Pe,Fe(this.timeoutMs,this.maxResponseBytes,this.retry);}async request(n,t,o={}){let r=n.toUpperCase(),i$1=ve(r),s=o.idempotencyKey??(i$1?Oe():void 0),y=this.createUrl(t,o.query),h=new Headers({authorization:`Bearer ${this.apiKey}`,accept:"application/json","user-agent":`mupag-sdk/${X}`}),f;if(o.body!==void 0&&(h.set("content-type","application/json"),f=JSON.stringify(o.body),new TextEncoder().encode(f).byteLength>xe))throw new a$1({message:"O corpo da requisicao excede o limite seguro do SDK.",code:"request_too_large",suggestion:"Reduza metadata e itens antes de enviar a requisicao."});s!==void 0&&(Ne(s,o.idempotencyKey!==void 0),h.set("idempotency-key",s));let C=r==="GET"||r==="DELETE"||s!==void 0,_=0,l,b;for(;;){let v=new AbortController,ke=setTimeout(()=>v.abort(),this.timeoutMs),V={method:r,headers:h,signal:v.signal};f!==void 0&&(V.body=f);try{let c=await this.fetcher(y,V),L=await $e(c,this.maxResponseBytes);if(c.ok){let Ce=l!==void 0&&o.validateResponseAfterAmbiguous!==void 0?o.validateResponseAfterAmbiguous:o.validateResponse;if((i$1||o.validateResponse!==void 0)&&!Ke(L,Ce))throw K(c,"invalid_success_response",i$1?"A API retornou sucesso sem uma confirmacao valida da mutacao.":"A API retornou sucesso com um contrato de resposta invalido.");return L}throw i(c.status,L,c.headers)}catch(c){if(b=c,i$1&&Le(c)&&l===void 0&&(l=c),i$1&&Q(c))throw new g$1(s,c);if(!Ue(c,C)||_>=this.retry.maxRetries)throw i$1&&(l!==void 0||ee(c))?new g$1(s,l??c):c}finally{clearTimeout(ke);}await Be(Me(_,this.retry,b)),_+=1;}}createUrl(n,t={}){let o=new URL(`${this.baseUrl}${n}`);for(let[r,i]of Object.entries(t))i!==void 0&&o.searchParams.set(r,String(i));return o}};function Oe(){let e=globalThis.crypto;if(typeof e?.randomUUID=="function")return `sdk_${e.randomUUID()}`;if(typeof e?.getRandomValues=="function"){let n=new Uint8Array(16);return e.getRandomValues(n),`sdk_${Array.from(n,t=>t.toString(16).padStart(2,"0")).join("")}`}throw new a$1({message:"O runtime nao oferece um gerador criptografico para a Idempotency-Key.",code:"secure_random_unavailable",suggestion:"Use um runtime com Web Crypto habilitado ou informe uma Idempotency-Key segura."})}function Ne(e,n){if(e.length<1||e.length>128||!/^[\x21-\x7e]+$/.test(e)||n&&R(e))throw new a$1({message:"Idempotency-Key invalida.",code:"invalid_idempotency_key",suggestion:"Envie de 1 a 128 caracteres ASCII visiveis, sem espacos."})}async function $e(e,n){let t=await qe(e,n);if(t.trim())try{return JSON.parse(t)}catch{throw new b$1({message:"A API retornou um corpo que nao e JSON.",status:e.status,code:"invalid_json_response",suggestion:"Tente novamente e informe o request_id ao suporte se o problema persistir."})}}async function qe(e,n){let t=e.headers.get("content-length");if(t!==null){if(!/^\d+$/.test(t)||!Number.isSafeInteger(Number(t)))throw K(e,"invalid_content_length","A API retornou Content-Length invalido.");if(Number(t)>n)throw K(e,"response_too_large","A resposta da API excedeu o limite configurado.")}if(!e.body)return "";let o=e.body.getReader(),r=[],i=0;try{for(;;){let{done:h,value:f}=await o.read();if(h)break;if(f){if(i+=f.byteLength,i>n)throw await o.cancel("response limit exceeded"),K(e,"response_too_large","A resposta da API excedeu o limite configurado.");r.push(f);}}}finally{o.releaseLock();}let s=new Uint8Array(i),y=0;for(let h of r)s.set(h,y),y+=h.byteLength;return new TextDecoder().decode(s)}function K(e,n,t){return new b$1({message:t,status:e.status,code:n,suggestion:"Tente novamente e informe o request_id ao suporte se o problema persistir."})}function Ue(e,n){return n?e instanceof b$1?e.status===408||e.status===425||e.status===429||e.status===409&&e.code==="idempotency_in_progress"||e.status!==void 0&&e.status>=500:true:false}function ve(e){return e==="POST"||e==="PUT"||e==="PATCH"||e==="DELETE"}function Le(e){return e instanceof b$1?e.status===408||e.status===425||e.status!==void 0&&e.status>=500||e.status!==void 0&&e.status>=200&&e.status<400||ee(e)||Q(e):true}function Q(e){return !(e instanceof b$1)||e.status!==409||e.code==="idempotency_in_progress"?false:!Ie.has(e.code??"")}function ee(e){return e instanceof b$1&&e.status===409&&e.code==="idempotency_in_progress"}function Ke(e,n){return n!==void 0?n(e):typeof e=="object"&&e!==null&&!Array.isArray(e)}function Me(e,n,t){return t instanceof c&&t.retryAfter!==void 0?Math.min(Math.max(t.retryAfter,0)*1e3,3e4):De(e,n)}function De(e,n){return Math.min(n.initialDelayMs*2**e,n.maxDelayMs)}function Be(e){return e<=0?Promise.resolve():new Promise(n=>setTimeout(n,e))}function je(e,n){let t;try{t=new URL(e);}catch{throw new a$1({message:"baseUrl invalida.",code:"invalid_base_url"})}let o=new URL(Z[n]).origin,r=n==="test"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname),i=t.origin===o||r,s=t.protocol==="https:"||r&&t.protocol==="http:";if(!i||!s||t.username||t.password||t.pathname!==""&&t.pathname!=="/"||t.search||t.hash)throw new a$1({message:"baseUrl nao e uma origem permitida para o ambiente selecionado.",code:"invalid_base_url"});return t.origin}function Fe(e,n,t){if(!Number.isSafeInteger(e)||e<1||e>12e4)throw new a$1({message:"timeoutMs invalido.",code:"invalid_timeout"});if(!Number.isSafeInteger(n)||n<1||n>Ae)throw new a$1({message:"maxResponseBytes invalido.",code:"invalid_response_limit"});if(!Number.isSafeInteger(t.maxRetries)||t.maxRetries<0||t.maxRetries>5||!Number.isSafeInteger(t.initialDelayMs)||t.initialDelayMs<0||!Number.isSafeInteger(t.maxDelayMs)||t.maxDelayMs<t.initialDelayMs||t.maxDelayMs>3e4)throw new a$1({message:"Configuracao de retry invalida.",code:"invalid_retry_config"})}var ze=9e15,Je=/^[A-Za-z0-9_-]+$/,D=class{constructor(n){this.http=n;}http;create(n,t={}){let o=mn(u(n,"checkout session")),r=u(t,"request options");return this.http.request("POST","/v1/checkout-sessions",{body:o,idempotencyKey:r.idempotencyKey,validateResponse:Ve})}},B=class{constructor(n){this.http=n;}http;create(n,t={}){let o=ln(u(n,"charge")),r=u(t,"request options");return this.http.request("POST","/v1/charges",{body:o,idempotencyKey:r.idempotencyKey,validateResponse:i=>ne(i,o),validateResponseAfterAmbiguous:i=>ne(i,o,false)})}cancel(n,t){x(n,"charge id");let o=u(t,"charge cancellation options");return un(o),this.http.request("POST",`/v1/charges/${encodeURIComponent(n)}/cancel`,{body:o.reason===void 0?{}:{reason:o.reason},idempotencyKey:o.idempotencyKey,validateResponse:r=>Xe(r,n)})}list(n={}){let t=u(n,"charge list");return gn(t),this.http.request("GET","/v1/charges",{query:t,validateResponse:o=>Ze(o,t)})}},j=class{constructor(n){this.http=n;}http;create(n,t={}){let o=pn(u(n,"subscription")),r=u(t,"request options");return re(r,80),this.http.request("POST","/v1/subscriptions",{body:o,idempotencyKey:r.idempotencyKey,validateResponse:i=>fe(i,o),validateResponseAfterAmbiguous:i=>en(i,o)})}cancel(n,t,o={}){x(n,"subscription id");let r=yn(u(t,"subscription cancellation")),i=u(o,"request options");return re(i,80),this.http.request("POST",`/v1/subscriptions/${encodeURIComponent(n)}/cancel`,{body:r,idempotencyKey:i.idempotencyKey,validateResponse:s=>nn(s,n,r)})}},F=class{constructor(n){this.http=n;}http;update(n,t,o={}){x(n,"customer id"),a(n,"customer id");let r=u(t,"customer update"),i=u(o,"request options");return hn(r),this.http.request("PATCH",`/v1/customers/${encodeURIComponent(n)}`,{body:r,idempotencyKey:i.idempotencyKey,validateResponse:s=>tn(s,n)})}},z=class{constructor(n){this.http=n;}http;create(n,t,o={}){x(n,"charge id");let r=He(u(t,"refund")),i=u(o,"request options");return this.http.request("POST",`/v1/charges/${encodeURIComponent(n)}/refunds`,{body:r,idempotencyKey:i.idempotencyKey,validateResponse:s=>te(s,n,r),validateResponseAfterAmbiguous:s=>r.amount_cents!==void 0&&te(s,n,r)})}get(n){return x(n,"refund id"),this.http.request("GET",`/v1/refunds/${encodeURIComponent(n)}`,{validateResponse:t=>le(t,n)})}listByCharge(n,t={}){x(n,"charge id");let o=u(t,"refund list");return fn(o),this.http.request("GET",`/v1/charges/${encodeURIComponent(n)}/refunds`,{query:o,validateResponse:r=>on(r,o,n)})}};function He(e){let n=e.amount_cents,t=e.full,o=e.reason,r=n!==void 0;if(r===(t===true))throw new TypeError("Refund exige exatamente amount_cents ou full=true.");if(r&&(!Number.isSafeInteger(n)||n<=0))throw new TypeError("Refund amount_cents precisa ser um inteiro seguro positivo.");if(o===void 0)return e;if(typeof o!="string")throw new TypeError("Refund reason invalido.");let s=ae(o);if(s.length<1||s.length>500||/[\x00-\x1f\x7f]/.test(s))throw new TypeError("Refund reason invalido.");return a(s,"reason"),{...e,reason:s}}function ae(e){let n=0,t=e.length;for(;n<t&&e.charCodeAt(n)<=32;)n+=1;for(;t>n&&e.charCodeAt(t-1)<=32;)t-=1;return e.slice(n,t)}function Ve(e){return p(e)&&P(e.id)&&P(e.url)&&cn(e.url)&&P(e.expires_at)&&$(e.expires_at)}var We=new Set(["created","pending","authorized","paid","partially_refunded","refunded","failed","expired","cancelled","disputed","chargeback","under_review"]),de=new Set(["created","pending","authorized","paid","partially_refunded","refunded","failed","expired","cancelled","disputed","chargeback","under_review"]),ce=new Set(["requested","processing","completed","failed","cancelled","unknown"]),Ye=new Set(["trialing","active","past_due","unpaid","paused","incomplete"]),Ge=new Set(["trialing","active","incomplete"]);function ne(e,n,t=true){if(!p(e))return false;let o=e.coupon_code!==void 0,r=o&&e.coupon_code!==null,i=e.original_amount_cents!==void 0,s=e.amount_subtotal_cents!==void 0;if(o&&(e.coupon_code===null?n.coupon_code!==void 0:n.coupon_code===void 0||e.coupon_code!==n.coupon_code)||i&&e.original_amount_cents!==n.amount_cents||s&&e.amount_subtotal_cents!==n.amount_cents)return false;let y=r||i||s;return E(e.charge_id)&&Number.isSafeInteger(e.amount_cents)&&e.amount_cents>0&&(e.amount_cents===n.amount_cents||t&&n.coupon_code!==void 0&&e.amount_cents<=n.amount_cents||!t&&n.coupon_code!==void 0&&y&&e.amount_cents<=n.amount_cents)&&typeof e.status=="string"&&We.has(e.status)&&ge(e)&&q(e.payment_method,n.payment_method)&&_e(e,n.customer.id)&&q(e.external_reference,n.external_reference)}function Xe(e,n){return !p(e)||e.charge_id!==n||e.reason!=="payment_attempt_cancelled"?false:e.status==="cancellation_pending"?e.cancelled_at===null:e.status==="cancelled"&&P(e.cancelled_at)&&$(e.cancelled_at)}function Ze(e,n){return !p(e)||!Array.isArray(e.data)||e.data.length>(n.limit??25)||!me(e.next_cursor,n.cursor)?false:e.data.every(t=>Qe(t,n))}function Qe(e,n){if(!p(e)||!E(e.charge_id)||!Number.isSafeInteger(e.amount_cents)||e.amount_cents<1||typeof e.status!="string"||!de.has(e.status)||typeof e.created_at!="string"||n.status!==void 0&&e.status!==n.status||n.payment_method!==void 0&&e.payment_method!==void 0&&e.payment_method!==n.payment_method||!_e(e,n.customer_id)||!ge(e))return false;let t=A(e.created_at);if(t===void 0)return false;let o=n.created_at_from===void 0?void 0:A(n.created_at_from),r=n.created_at_to===void 0?void 0:A(n.created_at_to);return (o===void 0||t>=o)&&(r===void 0||t<r)}function ue(e,n){return p(e)&&P(e.id)&&(n===void 0||e.id===n)&&P(e.status)}function fe(e,n){return ue(e)&&Ge.has(e.status)&&e.customer_id===n.customer_id&&e.plan_id===n.plan_id&&e.payment_method===n.payment_method&&q(e.card_token_id,n.card_token_id)&&q(e.external_reference,n.external_reference)&&rn(e,"coupon_id",n.coupon_id)&&e.cancel_at_period_end===false}function en(e,n){return fe(e,n)&&(n.coupon_id===void 0||p(e)&&e.coupon_id===n.coupon_id)}function nn(e,n,t){if(!ue(e,n))return false;if(Object.prototype.hasOwnProperty.call(e,"cancellation_reason")){let o=e.cancellation_reason;if(t.reason===void 0?o!==null:o!==t.reason)return false}return t.mode==="immediate"?e.status==="canceled"&&e.cancel_at_period_end===false:e.cancel_at_period_end===true&&Ye.has(e.status)}function tn(e,n){return p(e)&&e.id===n}function te(e,n,t){return p(e)&&E(e.refund_id)&&e.charge_id===n&&Number.isSafeInteger(e.amount_cents)&&e.amount_cents>0&&(t.amount_cents===void 0||e.amount_cents===t.amount_cents)&&typeof e.status=="string"&&ce.has(e.status)&&w(e.reason)&&q(e.reason,t.reason)&&typeof e.requested_at=="string"&&$(e.requested_at)}function le(e,n,t){return p(e)&&E(e.refund_id)&&(n===void 0||e.refund_id===n)&&E(e.charge_id)&&(t===void 0||e.charge_id===t)&&Number.isSafeInteger(e.amount_cents)&&e.amount_cents>0&&typeof e.status=="string"&&ce.has(e.status)&&typeof e.requested_at=="string"&&$(e.requested_at)&&w(e.psp_refund_id)&&w(e.reason)&&he(e.completed_at)&&w(e.failure_reason)}function on(e,n,t){return p(e)&&Array.isArray(e.refunds)&&e.refunds.length<=(n.limit??100)&&me(e.next_cursor,n.cursor)&&e.refunds.every(o=>le(o,void 0,t))}function p(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P(e){return typeof e=="string"&&e.length>0}function E(e){return typeof e=="string"&&e.length<=256&&/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(e)}function q(e,n){return e===void 0?true:e===null?n===void 0:n!==void 0&&e===n}function rn(e,n,t){if(!Object.prototype.hasOwnProperty.call(e,n))return true;let o=e[n];return t===void 0?o===null:o===t}function _e(e,n){let t=[];if(Object.prototype.hasOwnProperty.call(e,"customer_id")){if(!E(e.customer_id))return false;t.push(e.customer_id);}if(Object.prototype.hasOwnProperty.call(e,"customer")){if(!p(e.customer)||!Object.prototype.hasOwnProperty.call(e.customer,"id")||!E(e.customer.id))return false;t.push(e.customer.id);}return t.every(o=>o===t[0]&&(n===void 0||o===n))}function me(e,n){return e==null||e===""||typeof e=="string"&&pe(e,256)&&e!==n}function pe(e,n){if(e.length<1||e.length>n||!Je.test(e))return false;let o=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4);try{let r=atob(o);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")===e}catch{return false}}function $(e){return A(e)!==void 0}function A(e){let n=/^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/.exec(e);if(n===null)return;let t=Number(n[1]),o=Number(n[2]),r=Number(n[3]),i=Number(n[4]),s=Number(n[5]),y=Number(n[6]),h=n[7]===void 0?0:Number(n[7]),f=n[8]===void 0?0:Number(n[8]);if(o<1||o>12||r<1||r>sn(t,o)||i>23||s>59||y>60||h>23||f>59)return;let C=e.replace("t","T").replace(/z$/,"Z"),_=y===60,l=_?`${C.slice(0,17)}59${C.slice(19)}`:C,b=Date.parse(l);return Number.isNaN(b)?void 0:b+(_?1e3:0)}function sn(e,n){return n===2?e%4===0&&(e%100!==0||e%400===0)?29:28:[4,6,9,11].includes(n)?30:31}function oe(e){return e===void 0||typeof e=="string"}function w(e){return e==null||typeof e=="string"}function an(e){return e===void 0||E(e)}function dn(e){return e===null||an(e)}function ye(e){return e===void 0||typeof e=="string"&&$(e)}function he(e){return e===null||ye(e)}function ge(e){return w(e.psp_charge_id)&&dn(e.card_token_id)&&w(e.card_brand)&&w(e.card_last4)&&w(e.three_ds_acs_url)&&w(e.failure_classification)&&w(e.pix_qr_code_base64)&&w(e.pix_emv_code)&&oe(e.pix_qr_code)&&oe(e.pix_copy_paste)&&he(e.expires_at)&&ye(e.created_at)}function cn(e){try{return new URL(e).origin!=="null"}catch{return false}}function un(e){if(g(e,["idempotencyKey","reason"],"charge cancellation options"),typeof e.idempotencyKey!="string"||e.idempotencyKey.length<1||e.idempotencyKey.length>128||!/^[\x21-\x7e]+$/.test(e.idempotencyKey))throw new TypeError("Idempotency-Key de cancelamento deve ser ASCII visivel com ate 128 caracteres.");if(e.reason!==void 0&&e.reason!=="payment_attempt_cancelled")throw new TypeError("reason invalido para cancelamento de charge.")}function fn(e){if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new TypeError("Refund list limit precisa estar entre 1 e 100.");we(e.cursor,256,"cursor");}function ln(e){if(g(e,["amount_cents","payment_method","customer","installments","card_token","card_token_id","save_card","description","soft_descriptor","payer_ip","auth_only","product_max_installments","external_reference","expires_in_seconds","metadata","affiliate_code","coupon_code","split_rules","is_mit","initial_mit_reference_id"],"charge"),N(e.amount_cents,100,ze,"amount_cents"),e.payment_method!=="pix"&&e.payment_method!=="credit_card")throw new TypeError("payment_method precisa ser pix ou credit_card.");if(g(e.customer,["id","name","email","tax_id"],"customer"),T(e.customer.id,"customer.id"),a(e.customer.id,"customer.id"),k(e.customer.name,200,"customer.name"),a(e.customer.name,"customer.name"),k(e.customer.email,254,"customer.email"),a(e.customer.email,"customer.email"),!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.customer.email))throw new TypeError("customer.email invalido.");if(k(e.customer.tax_id,14,"customer.tax_id"),!/^(?:[0-9]{11}|[0-9]{14})$/.test(e.customer.tax_id))throw new TypeError("customer.tax_id precisa conter CPF ou CNPJ sem formatacao.");if(I(e.installments,1,1,"installments"),I(e.product_max_installments,1,1,"product_max_installments"),I(e.expires_in_seconds,60,Number.MAX_SAFE_INTEGER,"expires_in_seconds"),d(e.card_token,4096,"card_token"),T(e.card_token_id,"card_token_id"),e.card_token!==void 0&&R(e.card_token))throw new TypeError("card_token contem possivel numero de cartao.");if(e.card_token_id!==void 0&&R(e.card_token_id))throw new TypeError("card_token_id contem possivel numero de cartao.");if(d(e.description,500,"description"),a(e.description,"description"),e.soft_descriptor!==void 0&&(typeof e.soft_descriptor!="string"||e.soft_descriptor!==""))throw new TypeError("soft_descriptor nao e suportado pelo PSP Asaas.");if(e.payer_ip!==void 0){let r=k(e.payer_ip,45,"payer_ip");if(!wn(r))throw new TypeError("payer_ip precisa ser um IP literal IPv4 ou IPv6.")}if(d(e.external_reference,256,"external_reference"),a(e.external_reference,"external_reference"),d(e.affiliate_code,128,"affiliate_code"),a(e.affiliate_code,"affiliate_code"),d(e.coupon_code,128,"coupon_code"),a(e.coupon_code,"coupon_code"),O(e.save_card,"save_card"),O(e.auth_only,"auth_only"),O(e.is_mit,"is_mit"),e.auth_only===true)throw new TypeError("auth_only ainda nao e suportado pela API.");let n=e.metadata===void 0?void 0:J(e.metadata,"metadata"),t=e.card_token!==void 0,o=e.card_token_id!==void 0;if(e.payment_method==="credit_card"&&e.payer_ip===void 0)throw new TypeError("credit_card exige payer_ip literal do pagador.");if(e.payment_method==="credit_card"&&t===o)throw new TypeError("credit_card exige exatamente card_token ou card_token_id.");if(e.payment_method==="pix"&&(t||o||e.save_card!==void 0||e.installments!==void 0||e.product_max_installments!==void 0))throw new TypeError("Campos de cartao nao podem ser enviados em uma cobranca PIX.");if(e.is_mit===true){if(!o||e.initial_mit_reference_id===void 0||t)throw new TypeError("MIT exige card_token_id e initial_mit_reference_id, sem card_token bruto.")}else if(e.initial_mit_reference_id!==void 0)throw new TypeError("initial_mit_reference_id exige is_mit=true.");return T(e.initial_mit_reference_id,"initial_mit_reference_id"),a(e.initial_mit_reference_id,"initial_mit_reference_id"),_n(e.split_rules,e.amount_cents),n===void 0?e:{...e,metadata:n}}function _n(e,n){if(e===void 0)return;if(!Array.isArray(e)||e.length>50)throw new TypeError("split_rules aceita no maximo 50 itens.");let t=BigInt(n),o=0n,r=0n;for(let i of e)if(g(i,["recipient_id","value_type","value_bps","value_cents"],"split rule"),U(i.recipient_id,"split_rules.recipient_id"),a(i.recipient_id,"split_rules.recipient_id"),i.value_type==="fixed_amount"){if(N(i.value_cents,1,n,"split_rules.value_cents"),i.value_bps!==void 0)throw new TypeError("fixed_amount nao aceita value_bps.");o+=BigInt(i.value_cents);}else if(i.value_type==="percentage_of_gross"){if(N(i.value_bps,1,1e4,"split_rules.value_bps"),i.value_cents!==void 0)throw new TypeError("percentage_of_gross nao aceita value_cents.");r+=BigInt(i.value_bps),o+=t*BigInt(i.value_bps)/10000n;}else throw new TypeError("split_rules.value_type invalido.");if(r>10000n||o>t)throw new TypeError("split_rules agregado nao pode exceder o valor da cobranca.")}function mn(e){if(g(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 TypeError("items precisa conter de 1 a 100 itens.");let n=0;for(let r of e.items){g(r,["name","quantity","unit_amount_cents"],"checkout item"),k(r.name,200,"items.name"),a(r.name,"items.name"),N(r.quantity,1,1e6,"items.quantity"),N(r.unit_amount_cents,100,Number.MAX_SAFE_INTEGER,"items.unit_amount_cents");let i=r.quantity*r.unit_amount_cents;if(n+=i,!Number.isSafeInteger(i)||!Number.isSafeInteger(n))throw new TypeError("Total do checkout excede o limite seguro.")}if(se(e.success_url,"success_url"),se(e.cancel_url,"cancel_url"),e.customer_id!==void 0&&e.customer_data!==void 0)throw new TypeError("customer_id e customer_data sao mutuamente exclusivos.");if(T(e.customer_id,"customer_id"),a(e.customer_id,"customer_id"),e.customer_data!==void 0&&(g(e.customer_data,["name","email","document","phone"],"customer_data"),d(e.customer_data.name,200,"customer_data.name"),a(e.customer_data.name,"customer_data.name"),d(e.customer_data.email,320,"customer_data.email"),a(e.customer_data.email,"customer_data.email"),d(e.customer_data.document,64,"customer_data.document"),d(e.customer_data.phone,32,"customer_data.phone")),e.allowed_payment_methods!==void 0){let r=[...e.allowed_payment_methods];if(r.length<1||r.length>2||new Set(r).size!==r.length||r.some(i=>i!=="pix"&&i!=="credit_card"))throw new TypeError("allowed_payment_methods invalido.")}if(T(e.coupon_id,"coupon_id"),e.allow_coupons===false&&e.coupon_id!==void 0)throw new TypeError("coupon_id nao pode ser usado quando allow_coupons=false.");d(e.affiliate_code,128,"affiliate_code"),a(e.affiliate_code,"affiliate_code"),d(e.delivery_type,64,"delivery_type"),a(e.delivery_type,"delivery_type"),I(e.expires_in_minutes,1,1440,"expires_in_minutes"),O(e.collect_shipping_address,"collect_shipping_address"),O(e.allow_coupons,"allow_coupons");let t=e.metadata===void 0?void 0:J(e.metadata,"metadata"),o=e.utm_params===void 0?void 0:J(e.utm_params,"utm_params");return t===void 0&&o===void 0?e:{...e,metadata:t,utm_params:o}}function pn(e){if(g(e,["customer_id","plan_id","payment_method","trial_days","card_token_id","coupon_id","affiliate_code","metadata","external_reference"],"subscription"),U(e.customer_id,"customer_id"),a(e.customer_id,"customer_id"),U(e.plan_id,"plan_id"),e.payment_method!=="pix"&&e.payment_method!=="credit_card")throw new TypeError("payment_method precisa ser pix ou credit_card.");if(T(e.card_token_id,"card_token_id"),e.card_token_id!==void 0&&R(e.card_token_id))throw new TypeError("card_token_id contem possivel numero de cartao.");if(e.payment_method==="credit_card"&&e.card_token_id===void 0)throw new TypeError("credit_card exige card_token_id.");if(e.payment_method==="pix"&&e.card_token_id!==void 0)throw new TypeError("card_token_id nao pode ser enviado para PIX.");T(e.coupon_id,"coupon_id"),I(e.trial_days,0,365,"trial_days"),d(e.affiliate_code,128,"affiliate_code"),a(e.affiliate_code,"affiliate_code"),d(e.external_reference,256,"external_reference"),a(e.external_reference,"external_reference");let n=e.metadata===void 0?void 0:J(e.metadata,"metadata");return n===void 0?e:{...e,metadata:n}}function yn(e){if(g(e,["mode","reason"],"subscription cancellation"),e.mode!=="immediate"&&e.mode!=="end_of_period")throw new TypeError("mode invalido.");if(e.reason===void 0)return e;if(typeof e.reason!="string")throw new TypeError("reason invalido.");let n=ae(e.reason);return n.length===0?{mode:e.mode}:(d(n,500,"reason"),a(n,"reason"),{...e,reason:n})}function hn(e){if(g(e,["name","email","tax_id","phone","birth_date","external_reference","marketing_consent"],"customer"),k(e.name,200,"name"),a(e.name,"name"),k(e.email,320,"email"),a(e.email,"email"),!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.email))throw new TypeError("email invalido.");if(d(e.tax_id,64,"tax_id"),d(e.phone,32,"phone"),d(e.external_reference,256,"external_reference"),a(e.external_reference,"external_reference"),O(e.marketing_consent,"marketing_consent"),e.birth_date!==void 0&&!/^\d{4}-\d{2}-\d{2}$/.test(e.birth_date))throw new TypeError("birth_date precisa usar YYYY-MM-DD.")}function gn(e){if(g(e,["status","customer_id","payment_method","created_at_from","created_at_to","limit","cursor"],"charge list"),e.status!==void 0&&!de.has(e.status))throw new TypeError("status invalido.");if(e.payment_method!==void 0&&e.payment_method!=="pix"&&e.payment_method!=="credit_card")throw new TypeError("payment_method invalido.");if(T(e.customer_id,"customer_id"),a(e.customer_id,"customer_id"),I(e.limit,1,100,"limit"),we(e.cursor,256,"cursor"),ie(e.created_at_from,"created_at_from"),ie(e.created_at_to,"created_at_to"),e.created_at_from!==void 0&&e.created_at_to!==void 0&&A(e.created_at_from)>=A(e.created_at_to))throw new TypeError("created_at_from precisa ser anterior a created_at_to.")}function re(e,n){if(e.idempotencyKey!==void 0&&e.idempotencyKey.length>n)throw new TypeError(`Idempotency-Key deve ter no maximo ${n} caracteres neste recurso.`)}function g(e,n,t){if(e===null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`${t} precisa ser um objeto simples.`);let o=new Set(n),r=Object.keys(e).find(i=>!o.has(i));if(r!==void 0)throw new TypeError(`${t} contem campo nao suportado: ${r}.`)}function x(e,n){let t=U(e,n);a(t,n);}function U(e,n){let t=k(e,256,n);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(t))throw new TypeError(`${n} invalido.`);return t}function T(e,n){e!==void 0&&U(e,n);}function k(e,n,t){if(typeof e!="string"||e.trim().length<1||e.length>n||/[\x00-\x1f\x7f]/.test(e))throw new TypeError(`${t} invalido.`);return e}function d(e,n,t){e!==void 0&&k(e,n,t);}function N(e,n,t,o){if(!Number.isSafeInteger(e)||e<n||e>t)throw new TypeError(`${o} precisa ser inteiro entre ${n} e ${t}.`)}function I(e,n,t,o){e!==void 0&&N(e,n,t,o);}function O(e,n){if(e!==void 0&&typeof e!="boolean")throw new TypeError(`${n} precisa ser boolean.`)}function we(e,n,t){if(e!==void 0&&(typeof e!="string"||!pe(e,n)))throw new TypeError(`${t} invalido.`)}function ie(e,n){if(e!==void 0&&(typeof e!="string"||!$(e)))throw new TypeError(`${n} precisa ser uma data ISO-8601.`)}function wn(e){return be(e)||bn(e)}function be(e){let n=e.split(".");return n.length===4&&n.every(t=>/^(?:0|[1-9][0-9]{0,2})$/.test(t)&&Number(t)<=255)}function bn(e){if(!e.includes(":")||!/^[0-9A-Fa-f:.]+$/.test(e))return false;let n=e.indexOf("::");if(n!==-1&&e.indexOf("::",n+2)!==-1)return false;let o=(n===-1?[e]:[e.slice(0,n),e.slice(n+2)]).flatMap(i=>i===""?[]:i.split(":"));if(o.some(i=>i.length===0))return false;let r=0;for(let[i,s]of o.entries())if(s.includes(".")){if(i!==o.length-1||!be(s))return false;r+=2;}else {if(!/^[0-9A-Fa-f]{1,4}$/.test(s))return false;r+=1;}return n===-1?r===8:r<8}function se(e,n){if(typeof e!="string"||e.length>2048)throw new TypeError(`${n} invalida.`);let t;try{t=new URL(e);}catch{throw new TypeError(`${n} precisa ser URL absoluta.`)}let o=["localhost","127.0.0.1","[::1]"].includes(t.hostname);if(t.protocol!=="https:"&&!(o&&t.protocol==="http:")||t.username||t.password)throw new TypeError(`${n} precisa ser URL HTTPS segura.`)}function Rn(e,n){g(e,Object.keys(e),n);let t=[{value:e,depth:0}],o=new WeakSet,r=0;for(;t.length>0;){let i=t.pop();if(!i)break;if(r+=1,r>1e4||i.depth>32)throw new TypeError(`${n} excede o limite de complexidade.`);let s=i.value;if(!(s===null||typeof s=="boolean")){if(typeof s=="string"){if(R(s))throw new TypeError(`${n} contem possivel numero de cartao.`);continue}if(typeof s=="number"){if(!Number.isFinite(s))throw new TypeError(`${n} contem numero invalido.`);if(R(JSON.stringify(s)))throw new TypeError(`${n} contem possivel numero de cartao.`);continue}if(typeof s!="object")throw new TypeError(`${n} contem valor nao-JSON.`);if(o.has(s))throw new TypeError(`${n} contem ciclo.`);o.add(s);for(let[y,h]of Object.entries(s)){if(R(y))throw new TypeError(`${n} contem possivel numero de cartao.`);let f=y.normalize("NFKC").toLowerCase();if(/[^\x00-\x7f]/.test(f))throw new TypeError(`${n} contem nome de campo Unicode nao suportado.`);let C=f.replace(/[^a-z0-9]/g,""),_=C.replace(/[0-9]+$/,"").replace(/(cvv|cvc|csc|cid|cav)[0-9]+/g,"$1");if(["__proto__","prototype","constructor"].includes(f)||["pan","cardnumber"].includes(C)||["cvv","cvc","cav"].some(l=>["","value","code","number"].some(b=>_.endsWith(l+b)))||["csc","cid"].some(l=>["","value","code","number"].some(b=>_===l+b||["card","amex","americanexpress"].some(v=>_.endsWith(v+l+b))))||_.endsWith("cardidentificationnumber")||_.endsWith("cardsecuritynumber")||["securitycode","securityvalue","verificationcode","verificationnumber","verificationvalue"].some(l=>_.endsWith(l)))throw new TypeError(`${n} contem campo sensivel proibido.`);t.push({value:h,depth:i.depth+1});}}}}function J(e,n){return Rn(e,n),e}function u(e,n){let t;try{t=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${n} contem numero invalido.`);if(["symbol","function","bigint"].includes(typeof i))throw new TypeError(`${n} contem valor nao-JSON.`);return i});}catch{throw new TypeError(`${n} contem valor nao-JSON.`)}if(t===void 0)throw new TypeError(`${n} invalido.`);let o;try{o=JSON.parse(t);}catch{throw new TypeError(`${n} contem valor nao-JSON.`)}if(!p(o))throw new TypeError(`${n} invalido.`);return o}function a(e,n){if(e!==void 0&&R(e))throw new TypeError(`${n} contem possivel numero de cartao.`)}var Re=class{charges;checkoutSessions;customers;refunds;subscriptions;webhooks;constructor(n){let t=new M({env:n.env,apiKey:n.apiKey,baseUrl:n.baseUrl,fetch:n.fetch,timeoutMs:n.timeoutMs,maxResponseBytes:n.maxResponseBytes,retry:n.retry});this.charges=new B(t),this.checkoutSessions=new D(t),this.customers=new F(t),this.refunds=new z(t),this.subscriptions=new j(t),this.webhooks=new b;}};
|
|
2
|
+
export{B as ChargesResource,D as CheckoutSessionsResource,F as CustomersResource,Re as MuPag,z as RefundsResource,j as SubscriptionsResource};//# sourceMappingURL=index.js.map
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pan.ts","../src/version.ts","../src/http.ts","../src/resources.ts","../src/index.ts"],"names":["containsPANLikeSequence","value","retainedDigits","character","decimalDigit","unicodeDecimalDigitValue","length","validPANSequence","codePoint","blockStart","digits","sum","doubleDigit","index","digit","SDK_VERSION","DEFAULT_RETRY","DEFAULT_MAX_RESPONSE_BYTES","MAX_CONFIGURED_RESPONSE_BYTES","MAX_REQUEST_BYTES","DEFINITIVE_CONFLICT_CODES","BASE_URL_BY_ENV","HttpClient","config","MuPagError","expectedPrefix","validateBaseUrl","runtimeFetch","validateClientBounds","method","path","normalizedMethod","mutation","isMutation","effectiveIdempotencyKey","createIdempotencyKey","url","headers","body","validateIdempotencyKey","idempotent","attempt","ambiguousCause","lastError","controller","timeout","init","response","parsed","parseJson","responseValidator","validSuccessResponse","invalidResponse","createApiError","error","isAmbiguousMutationError","isImmediateOutcomeUnknown","OutcomeUnknownError","shouldRetry","isIdempotencyInProgress","delay","retryDelayMs","query","key","cryptoApi","randomBytes","rejectPAN","maxBytes","text","readBoundedResponseText","APIError","contentLength","reader","chunks","total","done","output","offset","chunk","code","message","validator","retry","RateLimitError","backoff","ms","resolve","environment","canonicalOrigin","loopback","allowedOrigin","allowedProtocol","timeoutMs","maxResponseBytes","MAX_CHARGE_AMOUNT_CENTS","BASE64URL_CURSOR_PATTERN","CheckoutSessionsResource","http","params","options","validateCheckoutSessionParams","canonicalRequestSnapshot","requestOptions","isCheckoutSessionResponse","ChargesResource","validateChargeParams","isChargeResponse","id","validateResourceId","request","validateCancelChargeOptions","isChargeCancellationResponse","validateChargeListParams","isChargeListResponse","SubscriptionsResource","validateSubscriptionParams","validateMutationOptions","isSubscriptionCreateResponse","isSubscriptionCreateResponseAfterAmbiguous","validateCancelSubscriptionParams","isSubscriptionCancellationResponse","CustomersResource","rejectPANLikeOptionalText","validateCustomerParams","isCustomerResponse","RefundsResource","chargeId","normalizedParams","normalizeRefundParams","isRefundResponse","refundId","isRefundReadResponse","validateRefundListParams","isRefundListResponse","amount","full","reason","hasAmount","normalizedReason","trimBackendWhitespace","start","end","isObject","nonEmptyString","absoluteUrl","validInstant","CHARGE_STATUSES","LIST_CHARGE_STATUSES","REFUND_STATUSES","SCHEDULED_SUBSCRIPTION_STATUSES","INITIAL_SUBSCRIPTION_STATUSES","expected","allowCouponDiscount","couponCodePresent","couponCodeEchoed","originalAmountEchoed","subtotalAmountEchoed","correlatedCouponEvidence","validIdentifier","validChargeOptionalFields","matchesOptionalEcho","matchesCustomerIdentityEcho","expectedChargeId","validNextCursor","item","isChargeListItem","createdAt","parseInstant","createdAtFrom","createdAtTo","isSubscriptionResponse","expectedId","matchesNullableOptionalEcho","actualReason","validNullableOptionalString","expectedRefundId","validNullableOptionalInstant","refund","actual","field","identities","identity","previous","validCanonicalCursor","maximum","paddedBase64","decoded","match","year","month","day","hour","minute","second","offsetHour","offsetMinute","daysInMonth","normalizedCase","leapSecond","parsable","validOptionalString","validOptionalIdentifier","validNullableOptionalIdentifier","validOptionalInstant","allowedObject","optionalCursor","safeInteger","optionalIdentifier","requiredText","optionalInteger","optionalText","payerIp","isIpLiteral","optionalBoolean","metadata","canonicalJsonObject","hasRawToken","hasStoredToken","validateSplitRules","rules","amountCents","allocatedCents","percentageBps","rule","requiredIdentifier","line","safeRedirectUrl","methods","utmParams","optionalInstant","keys","allowlist","unsupported","identifier","minimum","isIpv4Literal","isIpv6Literal","octets","octet","compression","parts","side","part","units","validateJsonObject","stack","seen","nodes","current","entry","child","normalized","compact","sensitiveBase","token","descriptor","qualifier","suffix","encoded","_key","snapshot","MuPag","WebhooksResource"],"mappings":"4YAAO,SAASA,EAAwBC,CAAAA,CAAwB,CAC9D,IAAIC,CAAAA,CAAiB,EAAA,CAErB,QAAWC,CAAAA,IAAaF,CAAAA,CAAO,CAC7B,IAAMG,EAAeC,EAAAA,CAAyBF,CAAS,EACvD,GAAIC,CAAAA,GAAiB,OAAW,CAC9BF,CAAAA,CAAAA,CAAkBA,CA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AAsBjB,CAAI,CAAA,CACnD,KAAK,QAAA,CAAW,IAAIqK,EACtB,CACF","file":"index.js","sourcesContent":["export function containsPANLikeSequence(value: string): boolean {\n let retainedDigits = '';\n\n for (const character of value) {\n const decimalDigit = unicodeDecimalDigitValue(character);\n if (decimalDigit !== undefined) {\n retainedDigits = (retainedDigits + decimalDigit).slice(-19);\n for (let length = 12; length <= retainedDigits.length; length += 1) {\n if (validPANSequence(retainedDigits.slice(-length))) return true;\n }\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 unicodeDecimalDigitValue(character: string): string | undefined {\n const codePoint = character.codePointAt(0)!;\n if (codePoint >= 0x30 && codePoint <= 0x39) return character;\n if (!/^\\p{Decimal_Number}$/u.test(character)) return undefined;\n\n let blockStart = codePoint;\n while (blockStart > 0 && /^\\p{Decimal_Number}$/u.test(String.fromCodePoint(blockStart - 1))) {\n blockStart -= 1;\n }\n return String((codePoint - blockStart) % 10);\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","export const SDK_VERSION = '0.2.0' as const;\n","import {\n APIError,\n MuPagError,\n OutcomeUnknownError,\n RateLimitError,\n createApiError\n} from './errors.js';\nimport { containsPANLikeSequence } from './pan.js';\nimport { SDK_VERSION } from './version.js';\nimport type {\n Environment,\n FetchLike,\n JsonValue,\n RetryConfig\n} from './types.js';\n\nconst DEFAULT_RETRY: RetryConfig = {\n maxRetries: 2,\n initialDelayMs: 200,\n maxDelayMs: 2_000\n};\nconst DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\nconst MAX_CONFIGURED_RESPONSE_BYTES = 16 * 1024 * 1024;\nconst MAX_REQUEST_BYTES = 1024 * 1024;\nconst DEFINITIVE_CONFLICT_CODES = new Set([\n 'fingerprint_conflict',\n 'idempotency_fingerprint_conflict',\n 'idempotency_key_reused'\n]);\n\nconst BASE_URL_BY_ENV: Record<Environment, string> = {\n test: 'https://api.sandbox.mupag.com.br',\n prd: 'https://api.mupag.com.br'\n};\n\ntype HttpClientConfig = {\n apiKey: string;\n env: Environment;\n baseUrl?: string | undefined;\n fetch?: FetchLike | undefined;\n timeoutMs?: number | undefined;\n maxResponseBytes?: number | undefined;\n retry?: Partial<RetryConfig> | undefined;\n};\n\ntype RequestConfig = {\n query?: Record<string, string | number | boolean | undefined> | undefined;\n body?: unknown;\n idempotencyKey?: string | undefined;\n validateResponse?: ((value: JsonValue | undefined) => boolean) | undefined;\n validateResponseAfterAmbiguous?: ((value: JsonValue | undefined) => boolean) | undefined;\n};\n\nexport class HttpClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly fetcher: FetchLike;\n private readonly timeoutMs: number;\n private readonly maxResponseBytes: number;\n private readonly retry: RetryConfig;\n\n /**\n * Centraliza a parte HTTP do SDK para manter recursos (`charges`, `refunds`) finos.\n *\n * O SDK roda em Node 18+ e runtimes edge, entao dependemos apenas de `fetch`,\n * `AbortController` e Web APIs padrao. A injecao de `fetch` deixa teste rapido e\n * evita chamar API real durante desenvolvimento.\n */\n constructor(config: HttpClientConfig) {\n if (\n typeof config.apiKey !== 'string' ||\n !config.apiKey.trim() ||\n config.apiKey.length > 512 ||\n !/^[\\x21-\\x7e]+$/.test(config.apiKey)\n ) {\n throw new MuPagError({\n message: 'Informe uma apiKey valida para criar o cliente MuPag.',\n code: 'missing_api_key',\n suggestion: 'Use uma chave sk_test_ no sandbox ou sk_prd_ em producao.'\n });\n }\n if (config.env !== 'test' && config.env !== 'prd') {\n throw new MuPagError({\n message: 'Informe explicitamente o ambiente test ou prd.',\n code: 'missing_environment',\n suggestion: 'Use env: test enquanto estiver integrando no sandbox.'\n });\n }\n const expectedPrefix = config.env === 'test' ? 'sk_test_' : 'sk_prd_';\n if (!config.apiKey.startsWith(expectedPrefix)) {\n throw new MuPagError({\n message: 'A apiKey informada nao pertence ao ambiente selecionado.',\n code: 'api_key_environment_mismatch',\n suggestion: `Use uma chave ${expectedPrefix} no ambiente ${config.env}.`\n });\n }\n\n this.apiKey = config.apiKey;\n this.baseUrl = validateBaseUrl(config.baseUrl ?? BASE_URL_BY_ENV[config.env], config.env);\n const runtimeFetch = config.fetch ?? globalThis.fetch;\n if (typeof runtimeFetch !== 'function') {\n throw new MuPagError({ message: 'O runtime nao oferece fetch.', code: 'fetch_unavailable' });\n }\n this.fetcher = runtimeFetch.bind(globalThis);\n this.timeoutMs = config.timeoutMs ?? 30_000;\n this.retry = { ...DEFAULT_RETRY, ...config.retry };\n this.maxResponseBytes = config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;\n validateClientBounds(this.timeoutMs, this.maxResponseBytes, this.retry);\n }\n\n async request<TResponse>(method: string, path: string, config: RequestConfig = {}): Promise<TResponse> {\n const normalizedMethod = method.toUpperCase();\n const mutation = isMutation(normalizedMethod);\n const effectiveIdempotencyKey =\n config.idempotencyKey ?? (mutation ? createIdempotencyKey() : undefined);\n const url = this.createUrl(path, config.query);\n const headers = new Headers({\n authorization: `Bearer ${this.apiKey}`,\n accept: 'application/json',\n 'user-agent': `mupag-sdk/${SDK_VERSION}`\n });\n\n let body: string | undefined;\n if (config.body !== undefined) {\n headers.set('content-type', 'application/json');\n body = JSON.stringify(config.body);\n if (new TextEncoder().encode(body).byteLength > MAX_REQUEST_BYTES) {\n throw new MuPagError({\n message: 'O corpo da requisicao excede o limite seguro do SDK.',\n code: 'request_too_large',\n suggestion: 'Reduza metadata e itens antes de enviar a requisicao.'\n });\n }\n }\n\n if (effectiveIdempotencyKey !== undefined) {\n validateIdempotencyKey(effectiveIdempotencyKey, config.idempotencyKey !== undefined);\n headers.set('idempotency-key', effectiveIdempotencyKey);\n }\n\n const idempotent =\n normalizedMethod === 'GET' ||\n normalizedMethod === 'DELETE' ||\n effectiveIdempotencyKey !== undefined;\n let attempt = 0;\n let ambiguousCause: unknown;\n let lastError: unknown;\n\n while (true) {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n const init: RequestInit = {\n method: normalizedMethod,\n headers,\n signal: controller.signal\n };\n if (body !== undefined) {\n init.body = body;\n }\n\n try {\n const response = await this.fetcher(url, init);\n const parsed = await parseJson(response, this.maxResponseBytes);\n\n if (response.ok) {\n const responseValidator =\n ambiguousCause !== undefined && config.validateResponseAfterAmbiguous !== undefined\n ? config.validateResponseAfterAmbiguous\n : config.validateResponse;\n if ((mutation || config.validateResponse !== undefined) &&\n !validSuccessResponse(parsed, responseValidator)) {\n throw invalidResponse(\n response,\n 'invalid_success_response',\n mutation\n ? 'A API retornou sucesso sem uma confirmacao valida da mutacao.'\n : 'A API retornou sucesso com um contrato de resposta invalido.'\n );\n }\n return parsed as TResponse;\n }\n\n throw createApiError(response.status, parsed, response.headers);\n } catch (error) {\n lastError = error;\n if (mutation && isAmbiguousMutationError(error) && ambiguousCause === undefined) {\n ambiguousCause = error;\n }\n if (mutation && isImmediateOutcomeUnknown(error)) {\n throw new OutcomeUnknownError(effectiveIdempotencyKey!, error);\n }\n\n const retryable = shouldRetry(error, idempotent);\n if (!retryable || attempt >= this.retry.maxRetries) {\n if (mutation && (ambiguousCause !== undefined || isIdempotencyInProgress(error))) {\n throw new OutcomeUnknownError(effectiveIdempotencyKey!, ambiguousCause ?? error);\n }\n throw error;\n }\n } finally {\n clearTimeout(timeout);\n }\n\n await delay(retryDelayMs(attempt, this.retry, lastError));\n attempt += 1;\n }\n }\n\n private createUrl(path: string, query: Record<string, string | number | boolean | undefined> = {}) {\n const url = new URL(`${this.baseUrl}${path}`);\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n return url;\n }\n}\n\nexport function createIdempotencyKey() {\n const cryptoApi = globalThis.crypto;\n if (typeof cryptoApi?.randomUUID === 'function') {\n return `sdk_${cryptoApi.randomUUID()}`;\n }\n if (typeof cryptoApi?.getRandomValues === 'function') {\n const randomBytes = new Uint8Array(16);\n cryptoApi.getRandomValues(randomBytes);\n return `sdk_${Array.from(randomBytes, (value) => value.toString(16).padStart(2, '0')).join('')}`;\n }\n throw new MuPagError({\n message: 'O runtime nao oferece um gerador criptografico para a Idempotency-Key.',\n code: 'secure_random_unavailable',\n suggestion: 'Use um runtime com Web Crypto habilitado ou informe uma Idempotency-Key segura.'\n });\n}\n\nfunction validateIdempotencyKey(value: string, rejectPAN: boolean): void {\n if (\n value.length < 1 ||\n value.length > 128 ||\n !/^[\\x21-\\x7e]+$/.test(value) ||\n (rejectPAN && containsPANLikeSequence(value))\n ) {\n throw new MuPagError({\n message: 'Idempotency-Key invalida.',\n code: 'invalid_idempotency_key',\n suggestion: 'Envie de 1 a 128 caracteres ASCII visiveis, sem espacos.'\n });\n }\n}\n\nasync function parseJson(response: Response, maxBytes: number): Promise<JsonValue | undefined> {\n const text = await readBoundedResponseText(response, maxBytes);\n if (!text.trim()) {\n return undefined;\n }\n\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n throw new APIError({\n message: 'A API retornou um corpo que nao e JSON.',\n status: response.status,\n code: 'invalid_json_response',\n suggestion: 'Tente novamente e informe o request_id ao suporte se o problema persistir.'\n });\n }\n}\n\nasync function readBoundedResponseText(response: Response, maxBytes: number): Promise<string> {\n const contentLength = response.headers.get('content-length');\n if (contentLength !== null) {\n if (!/^\\d+$/.test(contentLength) || !Number.isSafeInteger(Number(contentLength))) {\n throw invalidResponse(response, 'invalid_content_length', 'A API retornou Content-Length invalido.');\n }\n if (Number(contentLength) > maxBytes) {\n throw invalidResponse(response, 'response_too_large', 'A resposta da API excedeu o limite configurado.');\n }\n }\n if (!response.body) return '';\n\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 > maxBytes) {\n await reader.cancel('response limit exceeded');\n throw invalidResponse(response, 'response_too_large', 'A resposta da API excedeu o limite configurado.');\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const output = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n output.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(output);\n}\n\nfunction invalidResponse(response: Response, code: string, message: string): APIError {\n return new APIError({\n message,\n status: response.status,\n code,\n suggestion: 'Tente novamente e informe o request_id ao suporte se o problema persistir.'\n });\n}\n\nfunction shouldRetry(error: unknown, idempotent: boolean) {\n if (!idempotent) return false;\n if (!(error instanceof APIError)) return true;\n return (\n error.status === 408 ||\n error.status === 425 ||\n error.status === 429 ||\n (error.status === 409 && error.code === 'idempotency_in_progress') ||\n (error.status !== undefined && error.status >= 500)\n );\n}\n\nfunction isMutation(method: string): boolean {\n return method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE';\n}\n\nfunction isAmbiguousMutationError(error: unknown): boolean {\n if (!(error instanceof APIError)) return true;\n return (\n error.status === 408 ||\n error.status === 425 ||\n (error.status !== undefined && error.status >= 500) ||\n (error.status !== undefined && error.status >= 200 && error.status < 400) ||\n isIdempotencyInProgress(error) ||\n isImmediateOutcomeUnknown(error)\n );\n}\n\nfunction isImmediateOutcomeUnknown(error: unknown): boolean {\n if (!(error instanceof APIError) || error.status !== 409) return false;\n if (error.code === 'idempotency_in_progress') return false;\n return !DEFINITIVE_CONFLICT_CODES.has(error.code ?? '');\n}\n\nfunction isIdempotencyInProgress(error: unknown): boolean {\n return (\n error instanceof APIError &&\n error.status === 409 &&\n error.code === 'idempotency_in_progress'\n );\n}\n\nfunction validSuccessResponse(\n value: JsonValue | undefined,\n validator: ((value: JsonValue | undefined) => boolean) | undefined\n): boolean {\n if (validator !== undefined) return validator(value);\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction retryDelayMs(attempt: number, retry: RetryConfig, error: unknown): number {\n if (error instanceof RateLimitError && error.retryAfter !== undefined) {\n return Math.min(Math.max(error.retryAfter, 0) * 1_000, 30_000);\n }\n return backoff(attempt, retry);\n}\n\nfunction backoff(attempt: number, retry: RetryConfig) {\n return Math.min(retry.initialDelayMs * 2 ** attempt, retry.maxDelayMs);\n}\n\nfunction delay(ms: number) {\n if (ms <= 0) {\n return Promise.resolve();\n }\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction validateBaseUrl(value: string, environment: Environment): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new MuPagError({ message: 'baseUrl invalida.', code: 'invalid_base_url' });\n }\n const canonicalOrigin = new URL(BASE_URL_BY_ENV[environment]).origin;\n const loopback = environment === 'test' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);\n const allowedOrigin = url.origin === canonicalOrigin || loopback;\n const allowedProtocol = url.protocol === 'https:' || (loopback && url.protocol === 'http:');\n if (\n !allowedOrigin ||\n !allowedProtocol ||\n url.username ||\n url.password ||\n (url.pathname !== '' && url.pathname !== '/') ||\n url.search ||\n url.hash\n ) {\n throw new MuPagError({\n message: 'baseUrl nao e uma origem permitida para o ambiente selecionado.',\n code: 'invalid_base_url'\n });\n }\n return url.origin;\n}\n\nfunction validateClientBounds(timeoutMs: number, maxResponseBytes: number, retry: RetryConfig): void {\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000) {\n throw new MuPagError({ message: 'timeoutMs invalido.', code: 'invalid_timeout' });\n }\n if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || maxResponseBytes > MAX_CONFIGURED_RESPONSE_BYTES) {\n throw new MuPagError({ message: 'maxResponseBytes invalido.', code: 'invalid_response_limit' });\n }\n if (!Number.isSafeInteger(retry.maxRetries) || retry.maxRetries < 0 || retry.maxRetries > 5\n || !Number.isSafeInteger(retry.initialDelayMs) || retry.initialDelayMs < 0\n || !Number.isSafeInteger(retry.maxDelayMs) || retry.maxDelayMs < retry.initialDelayMs || retry.maxDelayMs > 30_000) {\n throw new MuPagError({ message: 'Configuracao de retry invalida.', code: 'invalid_retry_config' });\n }\n}\n","import { HttpClient } from './http.js';\nimport { containsPANLikeSequence } from './pan.js';\nimport type {\n CancelChargeOptions,\n CancelSubscriptionParams,\n Charge,\n ChargeCancellation,\n CheckoutSession,\n CreateChargeParams,\n CreateCheckoutSessionParams,\n CreateRefundParams,\n CreateSubscriptionParams,\n Customer,\n ListRefundsParams,\n ListChargesParams,\n Page,\n Refund,\n RefundList,\n RequestOptions,\n Subscription,\n UpdateCustomerParams\n} from './types.js';\n\nconst MAX_CHARGE_AMOUNT_CENTS = 9_000_000_000_000_000;\nconst BASE64URL_CURSOR_PATTERN = /^[A-Za-z0-9_-]+$/;\n\nexport class CheckoutSessionsResource {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /** Cria uma sessao de checkout hospedada usando o contrato publico real. */\n create(params: CreateCheckoutSessionParams, options: RequestOptions = {}) {\n const body = validateCheckoutSessionParams(canonicalRequestSnapshot(params, 'checkout session'));\n const requestOptions = canonicalRequestSnapshot(options, 'request options');\n return this.http.request<CheckoutSession>('POST', '/v1/checkout-sessions', {\n body,\n idempotencyKey: requestOptions.idempotencyKey,\n validateResponse: isCheckoutSessionResponse\n });\n }\n}\n\nexport class ChargesResource {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Cria uma cobranca na API publica e garante idempotencia por padrao.\n *\n * POST financeiro precisa ser seguro contra retry e clique duplo. Por isso o SDK\n * gera `Idempotency-Key` automaticamente quando o integrador nao informa uma.\n */\n create(params: CreateChargeParams, options: RequestOptions = {}) {\n const body = validateChargeParams(canonicalRequestSnapshot(params, 'charge'));\n const requestOptions = canonicalRequestSnapshot(options, 'request options');\n return this.http.request<Charge>('POST', '/v1/charges', {\n body,\n idempotencyKey: requestOptions.idempotencyKey,\n validateResponse: (value) => isChargeResponse(value, body),\n validateResponseAfterAmbiguous: (value) => isChargeResponse(value, body, false)\n });\n }\n\n /**\n * Cancela uma charge pendente usando uma chave estavel controlada pelo integrador.\n *\n * A chave e obrigatoria porque um retorno `cancellation_pending` precisa ser\n * reconciliado com exatamente a mesma intencao, inclusive entre processos.\n */\n cancel(id: string, options: CancelChargeOptions) {\n validateResourceId(id, 'charge id');\n const request = canonicalRequestSnapshot(options, 'charge cancellation options');\n validateCancelChargeOptions(request);\n return this.http.request<ChargeCancellation>(\n 'POST',\n `/v1/charges/${encodeURIComponent(id)}/cancel`,\n {\n body: request.reason === undefined ? {} : { reason: request.reason },\n idempotencyKey: request.idempotencyKey,\n validateResponse: (value) => isChargeCancellationResponse(value, id)\n }\n );\n }\n\n /**\n * Lista cobrancas recentes usando filtros simples da API publica.\n *\n * GET e naturalmente seguro para retry e nao recebe chave de idempotencia.\n */\n list(params: ListChargesParams = {}) {\n const query = canonicalRequestSnapshot(params, 'charge list');\n validateChargeListParams(query);\n return this.http.request<Page<Charge>>('GET', '/v1/charges', {\n query,\n validateResponse: (value) => isChargeListResponse(value, query)\n });\n }\n}\n\nexport class SubscriptionsResource {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Cria assinatura recorrente via endpoint publico com idempotencia por padrao.\n */\n create(params: CreateSubscriptionParams, options: RequestOptions = {}) {\n const body = validateSubscriptionParams(canonicalRequestSnapshot(params, 'subscription'));\n const requestOptions = canonicalRequestSnapshot(options, 'request options');\n validateMutationOptions(requestOptions, 80);\n return this.http.request<Subscription>('POST', '/v1/subscriptions', {\n body,\n idempotencyKey: requestOptions.idempotencyKey,\n validateResponse: (value) => isSubscriptionCreateResponse(value, body),\n validateResponseAfterAmbiguous: (value) =>\n isSubscriptionCreateResponseAfterAmbiguous(value, body)\n });\n }\n\n /**\n * Cancela assinatura via API publica mantendo retry seguro.\n *\n * Cancelamento e uma mutacao idempotente do ponto de vista do lojista: repetir a\n * mesma intencao nao deve criar efeitos financeiros duplicados.\n */\n cancel(id: string, params: CancelSubscriptionParams, options: RequestOptions = {}) {\n validateResourceId(id, 'subscription id');\n const body = validateCancelSubscriptionParams(\n canonicalRequestSnapshot(params, 'subscription cancellation')\n );\n const requestOptions = canonicalRequestSnapshot(options, 'request options');\n validateMutationOptions(requestOptions, 80);\n return this.http.request<Subscription>('POST', `/v1/subscriptions/${encodeURIComponent(id)}/cancel`, {\n body,\n idempotencyKey: requestOptions.idempotencyKey,\n validateResponse: (value) => isSubscriptionCancellationResponse(value, id, body)\n });\n }\n}\n\nexport class CustomersResource {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Atualiza somente campos publicos permitidos do customer autenticado no merchant.\n */\n update(id: string, params: UpdateCustomerParams, options: RequestOptions = {}) {\n validateResourceId(id, 'customer id');\n rejectPANLikeOptionalText(id, 'customer id');\n const body = canonicalRequestSnapshot(params, 'customer update');\n const requestOptions = canonicalRequestSnapshot(options, 'request options');\n validateCustomerParams(body);\n return this.http.request<Customer>('PATCH', `/v1/customers/${encodeURIComponent(id)}`, {\n body,\n idempotencyKey: requestOptions.idempotencyKey,\n validateResponse: (value) => isCustomerResponse(value, id)\n });\n }\n}\n\nexport class RefundsResource {\n /** @internal */\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Solicita estorno usando endpoint publico e idempotency key automatica.\n *\n * Estorno pode ser acionado por painel, automacao ou webhook do lojista. O SDK\n * evita duplicidade mantendo uma chave estavel durante retry.\n */\n create(chargeId: string, params: CreateRefundParams, options: RequestOptions = {}) {\n validateResourceId(chargeId, 'charge id');\n const normalizedParams = normalizeRefundParams(canonicalRequestSnapshot(params, 'refund'));\n const requestOptions = canonicalRequestSnapshot(options, 'request options');\n return this.http.request<Refund>('POST', `/v1/charges/${encodeURIComponent(chargeId)}/refunds`, {\n body: normalizedParams,\n idempotencyKey: requestOptions.idempotencyKey,\n validateResponse: (value) => isRefundResponse(value, chargeId, normalizedParams),\n validateResponseAfterAmbiguous: (value) =>\n normalizedParams.amount_cents !== undefined && isRefundResponse(value, chargeId, normalizedParams)\n });\n }\n\n /** Consulta um estorno no escopo da API key autenticada. */\n get(refundId: string) {\n validateResourceId(refundId, 'refund id');\n return this.http.request<Refund>('GET', `/v1/refunds/${encodeURIComponent(refundId)}`, {\n validateResponse: (value) => isRefundReadResponse(value, refundId)\n });\n }\n\n /** Lista os estornos de uma cobrança no escopo da API key autenticada. */\n listByCharge(chargeId: string, params: ListRefundsParams = {}) {\n validateResourceId(chargeId, 'charge id');\n const query = canonicalRequestSnapshot(params, 'refund list');\n validateRefundListParams(query);\n return this.http.request<RefundList>('GET', `/v1/charges/${encodeURIComponent(chargeId)}/refunds`, {\n query,\n validateResponse: (value) => isRefundListResponse(value, query, chargeId)\n });\n }\n}\n\nfunction normalizeRefundParams(params: CreateRefundParams): CreateRefundParams {\n const amount = (params as { amount_cents?: unknown }).amount_cents;\n const full = (params as { full?: unknown }).full;\n const reason = (params as { reason?: unknown }).reason;\n const hasAmount = amount !== undefined;\n const isFull = full === true;\n if (hasAmount === isFull) {\n throw new TypeError('Refund exige exatamente amount_cents ou full=true.');\n }\n if (hasAmount && (!Number.isSafeInteger(amount) || (amount as number) <= 0)) {\n throw new TypeError('Refund amount_cents precisa ser um inteiro seguro positivo.');\n }\n if (reason === undefined) return params;\n if (typeof reason !== 'string') throw new TypeError('Refund reason invalido.');\n const normalizedReason = trimBackendWhitespace(reason);\n if (normalizedReason.length < 1 || normalizedReason.length > 500 || /[\\x00-\\x1f\\x7f]/.test(normalizedReason)) {\n throw new TypeError('Refund reason invalido.');\n }\n rejectPANLikeOptionalText(normalizedReason, 'reason');\n return { ...params, reason: normalizedReason };\n}\n\nfunction trimBackendWhitespace(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && value.charCodeAt(start) <= 0x20) start += 1;\n while (end > start && value.charCodeAt(end - 1) <= 0x20) end -= 1;\n return value.slice(start, end);\n}\n\nfunction isCheckoutSessionResponse(value: unknown): boolean {\n return (\n isObject(value) &&\n nonEmptyString(value.id) &&\n nonEmptyString(value.url) &&\n absoluteUrl(value.url) &&\n nonEmptyString(value.expires_at) &&\n validInstant(value.expires_at)\n );\n}\n\nconst CHARGE_STATUSES = new Set([\n 'created',\n 'pending',\n 'authorized',\n 'paid',\n 'partially_refunded',\n 'refunded',\n 'failed',\n 'expired',\n 'cancelled',\n 'disputed',\n 'chargeback',\n 'under_review'\n]);\n\nconst LIST_CHARGE_STATUSES = new Set([\n 'created',\n 'pending',\n 'authorized',\n 'paid',\n 'partially_refunded',\n 'refunded',\n 'failed',\n 'expired',\n 'cancelled',\n 'disputed',\n 'chargeback',\n 'under_review'\n]);\n\nconst REFUND_STATUSES = new Set([\n 'requested',\n 'processing',\n 'completed',\n 'failed',\n 'cancelled',\n 'unknown'\n]);\n\nconst SCHEDULED_SUBSCRIPTION_STATUSES = new Set([\n 'trialing',\n 'active',\n 'past_due',\n 'unpaid',\n 'paused',\n 'incomplete'\n]);\n\nconst INITIAL_SUBSCRIPTION_STATUSES = new Set(['trialing', 'active', 'incomplete']);\n\nfunction isChargeResponse(\n value: unknown,\n expected: CreateChargeParams,\n allowCouponDiscount = true\n): boolean {\n if (!isObject(value)) return false;\n const couponCodePresent = value.coupon_code !== undefined;\n const couponCodeEchoed = couponCodePresent && value.coupon_code !== null;\n const originalAmountEchoed = value.original_amount_cents !== undefined;\n const subtotalAmountEchoed = value.amount_subtotal_cents !== undefined;\n if (\n (couponCodePresent &&\n (value.coupon_code === null\n ? expected.coupon_code !== undefined\n : expected.coupon_code === undefined || value.coupon_code !== expected.coupon_code)) ||\n (originalAmountEchoed && value.original_amount_cents !== expected.amount_cents) ||\n (subtotalAmountEchoed && value.amount_subtotal_cents !== expected.amount_cents)\n ) {\n return false;\n }\n const correlatedCouponEvidence = couponCodeEchoed || originalAmountEchoed || subtotalAmountEchoed;\n return (\n validIdentifier(value.charge_id) &&\n Number.isSafeInteger(value.amount_cents) &&\n (value.amount_cents as number) > 0 &&\n (value.amount_cents === expected.amount_cents ||\n (allowCouponDiscount &&\n expected.coupon_code !== undefined &&\n (value.amount_cents as number) <= expected.amount_cents) ||\n (!allowCouponDiscount &&\n expected.coupon_code !== undefined &&\n correlatedCouponEvidence &&\n (value.amount_cents as number) <= expected.amount_cents)) &&\n typeof value.status === 'string' &&\n CHARGE_STATUSES.has(value.status) &&\n validChargeOptionalFields(value) &&\n matchesOptionalEcho(value.payment_method, expected.payment_method) &&\n matchesCustomerIdentityEcho(value, expected.customer.id) &&\n matchesOptionalEcho(value.external_reference, expected.external_reference)\n );\n}\n\nfunction isChargeCancellationResponse(value: unknown, expectedChargeId: string): boolean {\n if (\n !isObject(value) ||\n value.charge_id !== expectedChargeId ||\n value.reason !== 'payment_attempt_cancelled'\n ) {\n return false;\n }\n if (value.status === 'cancellation_pending') {\n return value.cancelled_at === null;\n }\n return (\n value.status === 'cancelled' &&\n nonEmptyString(value.cancelled_at) &&\n validInstant(value.cancelled_at)\n );\n}\n\nfunction isChargeListResponse(value: unknown, expected: ListChargesParams): boolean {\n if (\n !isObject(value) ||\n !Array.isArray(value.data) ||\n value.data.length > (expected.limit ?? 25) ||\n !validNextCursor(value.next_cursor, expected.cursor)\n ) {\n return false;\n }\n return value.data.every((item) => isChargeListItem(item, expected));\n}\n\nfunction isChargeListItem(value: unknown, expected: ListChargesParams): boolean {\n if (\n !isObject(value) ||\n !validIdentifier(value.charge_id) ||\n !Number.isSafeInteger(value.amount_cents) ||\n (value.amount_cents as number) < 1 ||\n typeof value.status !== 'string' ||\n !LIST_CHARGE_STATUSES.has(value.status) ||\n typeof value.created_at !== 'string' ||\n (expected.status !== undefined && value.status !== expected.status) ||\n (expected.payment_method !== undefined &&\n value.payment_method !== undefined &&\n value.payment_method !== expected.payment_method) ||\n !matchesCustomerIdentityEcho(value, expected.customer_id)\n ) {\n return false;\n }\n if (!validChargeOptionalFields(value)) return false;\n const createdAt = parseInstant(value.created_at);\n if (createdAt === undefined) return false;\n const createdAtFrom = expected.created_at_from === undefined\n ? undefined\n : parseInstant(expected.created_at_from);\n const createdAtTo = expected.created_at_to === undefined\n ? undefined\n : parseInstant(expected.created_at_to);\n return (\n (createdAtFrom === undefined || createdAt >= createdAtFrom) &&\n (createdAtTo === undefined || createdAt < createdAtTo)\n );\n}\n\nfunction isSubscriptionResponse(\n value: unknown,\n expectedId?: string\n): value is Record<string, unknown> {\n return (\n isObject(value) &&\n nonEmptyString(value.id) &&\n (expectedId === undefined || value.id === expectedId) &&\n nonEmptyString(value.status)\n );\n}\n\nfunction isSubscriptionCreateResponse(\n value: unknown,\n expected: CreateSubscriptionParams\n): boolean {\n return (\n isSubscriptionResponse(value) &&\n INITIAL_SUBSCRIPTION_STATUSES.has(value.status as string) &&\n value.customer_id === expected.customer_id &&\n value.plan_id === expected.plan_id &&\n value.payment_method === expected.payment_method &&\n matchesOptionalEcho(value.card_token_id, expected.card_token_id) &&\n matchesOptionalEcho(value.external_reference, expected.external_reference) &&\n matchesNullableOptionalEcho(value, 'coupon_id', expected.coupon_id) &&\n value.cancel_at_period_end === false\n );\n}\n\nfunction isSubscriptionCreateResponseAfterAmbiguous(\n value: unknown,\n expected: CreateSubscriptionParams\n): boolean {\n return (\n isSubscriptionCreateResponse(value, expected) &&\n (expected.coupon_id === undefined || (isObject(value) && value.coupon_id === expected.coupon_id))\n );\n}\n\nfunction isSubscriptionCancellationResponse(\n value: unknown,\n expectedId: string,\n expected: CancelSubscriptionParams\n): boolean {\n if (!isSubscriptionResponse(value, expectedId)) return false;\n if (Object.prototype.hasOwnProperty.call(value, 'cancellation_reason')) {\n const actualReason = value.cancellation_reason;\n if (expected.reason === undefined ? actualReason !== null : actualReason !== expected.reason) {\n return false;\n }\n }\n return expected.mode === 'immediate'\n ? value.status === 'canceled' && value.cancel_at_period_end === false\n : value.cancel_at_period_end === true && SCHEDULED_SUBSCRIPTION_STATUSES.has(value.status as string);\n}\n\nfunction isCustomerResponse(value: unknown, expectedId: string): boolean {\n return isObject(value) && value.id === expectedId;\n}\n\nfunction isRefundResponse(\n value: unknown,\n expectedChargeId: string,\n expected: CreateRefundParams\n): boolean {\n return (\n isObject(value) &&\n validIdentifier(value.refund_id) &&\n value.charge_id === expectedChargeId &&\n Number.isSafeInteger(value.amount_cents) &&\n (value.amount_cents as number) > 0 &&\n (expected.amount_cents === undefined || value.amount_cents === expected.amount_cents) &&\n typeof value.status === 'string' &&\n REFUND_STATUSES.has(value.status) &&\n validNullableOptionalString(value.reason) &&\n matchesOptionalEcho(value.reason, expected.reason) &&\n typeof value.requested_at === 'string' &&\n validInstant(value.requested_at)\n );\n}\n\nfunction isRefundReadResponse(\n value: unknown,\n expectedRefundId: string | undefined,\n expectedChargeId?: string\n): boolean {\n return (\n isObject(value) &&\n validIdentifier(value.refund_id) &&\n (expectedRefundId === undefined || value.refund_id === expectedRefundId) &&\n validIdentifier(value.charge_id) &&\n (expectedChargeId === undefined || value.charge_id === expectedChargeId) &&\n Number.isSafeInteger(value.amount_cents) &&\n (value.amount_cents as number) > 0 &&\n typeof value.status === 'string' &&\n REFUND_STATUSES.has(value.status) &&\n typeof value.requested_at === 'string' &&\n validInstant(value.requested_at) &&\n validNullableOptionalString(value.psp_refund_id) &&\n validNullableOptionalString(value.reason) &&\n validNullableOptionalInstant(value.completed_at) &&\n validNullableOptionalString(value.failure_reason)\n );\n}\n\nfunction isRefundListResponse(\n value: unknown,\n expected: ListRefundsParams,\n expectedChargeId: string\n): boolean {\n return (\n isObject(value) &&\n Array.isArray(value.refunds) &&\n value.refunds.length <= (expected.limit ?? 100) &&\n validNextCursor(value.next_cursor, expected.cursor) &&\n value.refunds.every((refund) => isRefundReadResponse(refund, undefined, expectedChargeId))\n );\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction nonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction validIdentifier(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length <= 256 &&\n /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(value)\n );\n}\n\nfunction matchesOptionalEcho(actual: unknown, expected: unknown): boolean {\n if (actual === undefined) return true;\n if (actual === null) return expected === undefined;\n return expected !== undefined && actual === expected;\n}\n\nfunction matchesNullableOptionalEcho(\n value: Record<string, unknown>,\n field: string,\n expected: string | undefined\n): boolean {\n if (!Object.prototype.hasOwnProperty.call(value, field)) return true;\n const actual = value[field];\n return expected === undefined ? actual === null : actual === expected;\n}\n\nfunction matchesCustomerIdentityEcho(\n value: Record<string, unknown>,\n expected: string | undefined\n): boolean {\n const identities: string[] = [];\n if (Object.prototype.hasOwnProperty.call(value, 'customer_id')) {\n if (!validIdentifier(value.customer_id)) return false;\n identities.push(value.customer_id);\n }\n if (Object.prototype.hasOwnProperty.call(value, 'customer')) {\n if (\n !isObject(value.customer) ||\n !Object.prototype.hasOwnProperty.call(value.customer, 'id') ||\n !validIdentifier(value.customer.id)\n ) {\n return false;\n }\n identities.push(value.customer.id);\n }\n return identities.every(\n (identity) => identity === identities[0] && (expected === undefined || identity === expected)\n );\n}\n\nfunction validNextCursor(value: unknown, previous: string | undefined): boolean {\n return (\n value === undefined || value === null || value === '' ||\n (typeof value === 'string' &&\n validCanonicalCursor(value, 256) &&\n value !== previous)\n );\n}\n\nfunction validCanonicalCursor(value: string, maximum: number): boolean {\n if (value.length < 1 || value.length > maximum || !BASE64URL_CURSOR_PATTERN.test(value)) {\n return false;\n }\n const standardBase64 = value.replace(/-/g, '+').replace(/_/g, '/');\n const paddedBase64 = standardBase64 + '='.repeat((4 - value.length % 4) % 4);\n try {\n const decoded = atob(paddedBase64);\n return btoa(decoded)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '') === value;\n } catch {\n return false;\n }\n}\n\nfunction validInstant(value: string): boolean {\n return parseInstant(value) !== undefined;\n}\n\nfunction parseInstant(value: string): number | undefined {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})[Tt](\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(?:[Zz]|[+-](\\d{2}):(\\d{2}))$/.exec(value);\n if (match === null) return undefined;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = match[7] === undefined ? 0 : Number(match[7]);\n const offsetMinute = match[8] === undefined ? 0 : Number(match[8]);\n if (\n month < 1 || month > 12 ||\n day < 1 || day > daysInMonth(year, month) ||\n hour > 23 || minute > 59 || second > 60 ||\n offsetHour > 23 || offsetMinute > 59\n ) {\n return undefined;\n }\n\n const normalizedCase = value.replace('t', 'T').replace(/z$/, 'Z');\n const leapSecond = second === 60;\n const parsable = leapSecond\n ? `${normalizedCase.slice(0, 17)}59${normalizedCase.slice(19)}`\n : normalizedCase;\n const parsed = Date.parse(parsable);\n return Number.isNaN(parsed) ? undefined : parsed + (leapSecond ? 1_000 : 0);\n}\n\nfunction daysInMonth(year: number, month: number): number {\n if (month === 2) {\n const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n return leapYear ? 29 : 28;\n }\n return [4, 6, 9, 11].includes(month) ? 30 : 31;\n}\n\nfunction validOptionalString(value: unknown): boolean {\n return value === undefined || typeof value === 'string';\n}\n\nfunction validNullableOptionalString(value: unknown): boolean {\n return value === undefined || value === null || typeof value === 'string';\n}\n\nfunction validOptionalIdentifier(value: unknown): boolean {\n return value === undefined || validIdentifier(value);\n}\n\nfunction validNullableOptionalIdentifier(value: unknown): boolean {\n return value === null || validOptionalIdentifier(value);\n}\n\nfunction validOptionalInstant(value: unknown): boolean {\n return value === undefined || (typeof value === 'string' && validInstant(value));\n}\n\nfunction validNullableOptionalInstant(value: unknown): boolean {\n return value === null || validOptionalInstant(value);\n}\n\nfunction validChargeOptionalFields(value: Record<string, unknown>): boolean {\n return (\n validNullableOptionalString(value.psp_charge_id) &&\n validNullableOptionalIdentifier(value.card_token_id) &&\n validNullableOptionalString(value.card_brand) &&\n validNullableOptionalString(value.card_last4) &&\n validNullableOptionalString(value.three_ds_acs_url) &&\n validNullableOptionalString(value.failure_classification) &&\n validNullableOptionalString(value.pix_qr_code_base64) &&\n validNullableOptionalString(value.pix_emv_code) &&\n validOptionalString(value.pix_qr_code) &&\n validOptionalString(value.pix_copy_paste) &&\n validNullableOptionalInstant(value.expires_at) &&\n validOptionalInstant(value.created_at)\n );\n}\n\nfunction absoluteUrl(value: string): boolean {\n try {\n return new URL(value).origin !== 'null';\n } catch {\n return false;\n }\n}\n\nfunction validateCancelChargeOptions(options: CancelChargeOptions): void {\n allowedObject(options, ['idempotencyKey', 'reason'], 'charge cancellation options');\n if (\n typeof options.idempotencyKey !== 'string' ||\n options.idempotencyKey.length < 1 ||\n options.idempotencyKey.length > 128 ||\n !/^[\\x21-\\x7e]+$/.test(options.idempotencyKey)\n ) {\n throw new TypeError('Idempotency-Key de cancelamento deve ser ASCII visivel com ate 128 caracteres.');\n }\n if (options.reason !== undefined && options.reason !== 'payment_attempt_cancelled') {\n throw new TypeError('reason invalido para cancelamento de charge.');\n }\n}\n\nfunction validateRefundListParams(params: ListRefundsParams): void {\n if (params.limit !== undefined && (!Number.isSafeInteger(params.limit) || params.limit < 1 || params.limit > 100)) {\n throw new TypeError('Refund list limit precisa estar entre 1 e 100.');\n }\n optionalCursor(params.cursor, 256, 'cursor');\n}\n\nfunction validateChargeParams(params: CreateChargeParams): CreateChargeParams {\n allowedObject(params, [\n 'amount_cents', 'payment_method', 'customer', 'installments', 'card_token', 'card_token_id',\n 'save_card', 'description', 'soft_descriptor', 'payer_ip', 'auth_only', 'product_max_installments',\n 'external_reference', 'expires_in_seconds', 'metadata', 'affiliate_code', 'coupon_code',\n 'split_rules', 'is_mit', 'initial_mit_reference_id'\n ], 'charge');\n safeInteger(params.amount_cents, 100, MAX_CHARGE_AMOUNT_CENTS, 'amount_cents');\n if (params.payment_method !== 'pix' && params.payment_method !== 'credit_card') {\n throw new TypeError('payment_method precisa ser pix ou credit_card.');\n }\n allowedObject(params.customer, ['id', 'name', 'email', 'tax_id'], 'customer');\n optionalIdentifier(params.customer.id, 'customer.id');\n rejectPANLikeOptionalText(params.customer.id, 'customer.id');\n requiredText(params.customer.name, 200, 'customer.name');\n rejectPANLikeOptionalText(params.customer.name, 'customer.name');\n requiredText(params.customer.email, 254, 'customer.email');\n rejectPANLikeOptionalText(params.customer.email, 'customer.email');\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(params.customer.email)) {\n throw new TypeError('customer.email invalido.');\n }\n requiredText(params.customer.tax_id, 14, 'customer.tax_id');\n if (!/^(?:[0-9]{11}|[0-9]{14})$/.test(params.customer.tax_id)) {\n throw new TypeError('customer.tax_id precisa conter CPF ou CNPJ sem formatacao.');\n }\n optionalInteger(params.installments, 1, 1, 'installments');\n optionalInteger(params.product_max_installments, 1, 1, 'product_max_installments');\n optionalInteger(params.expires_in_seconds, 60, Number.MAX_SAFE_INTEGER, 'expires_in_seconds');\n optionalText(params.card_token, 4_096, 'card_token');\n optionalIdentifier(params.card_token_id, 'card_token_id');\n if (params.card_token !== undefined && containsPANLikeSequence(params.card_token)) {\n throw new TypeError('card_token contem possivel numero de cartao.');\n }\n if (params.card_token_id !== undefined && containsPANLikeSequence(params.card_token_id)) {\n throw new TypeError('card_token_id contem possivel numero de cartao.');\n }\n optionalText(params.description, 500, 'description');\n rejectPANLikeOptionalText(params.description, 'description');\n if (params.soft_descriptor !== undefined &&\n (typeof params.soft_descriptor !== 'string' || params.soft_descriptor !== '')) {\n throw new TypeError('soft_descriptor nao e suportado pelo PSP Asaas.');\n }\n if (params.payer_ip !== undefined) {\n const payerIp = requiredText(params.payer_ip, 45, 'payer_ip');\n if (!isIpLiteral(payerIp)) throw new TypeError('payer_ip precisa ser um IP literal IPv4 ou IPv6.');\n }\n optionalText(params.external_reference, 256, 'external_reference');\n rejectPANLikeOptionalText(params.external_reference, 'external_reference');\n optionalText(params.affiliate_code, 128, 'affiliate_code');\n rejectPANLikeOptionalText(params.affiliate_code, 'affiliate_code');\n optionalText(params.coupon_code, 128, 'coupon_code');\n rejectPANLikeOptionalText(params.coupon_code, 'coupon_code');\n optionalBoolean(params.save_card, 'save_card');\n optionalBoolean(params.auth_only, 'auth_only');\n optionalBoolean(params.is_mit, 'is_mit');\n if (params.auth_only === true) throw new TypeError('auth_only ainda nao e suportado pela API.');\n const metadata = params.metadata === undefined\n ? undefined\n : canonicalJsonObject(params.metadata, 'metadata');\n\n const hasRawToken = params.card_token !== undefined;\n const hasStoredToken = params.card_token_id !== undefined;\n if (params.payment_method === 'credit_card' && params.payer_ip === undefined) {\n throw new TypeError('credit_card exige payer_ip literal do pagador.');\n }\n if (params.payment_method === 'credit_card' && hasRawToken === hasStoredToken) {\n throw new TypeError('credit_card exige exatamente card_token ou card_token_id.');\n }\n if (params.payment_method === 'pix' && (\n hasRawToken ||\n hasStoredToken ||\n params.save_card !== undefined ||\n params.installments !== undefined ||\n params.product_max_installments !== undefined\n )) {\n throw new TypeError('Campos de cartao nao podem ser enviados em uma cobranca PIX.');\n }\n if (params.is_mit === true) {\n if (!hasStoredToken || params.initial_mit_reference_id === undefined || hasRawToken) {\n throw new TypeError('MIT exige card_token_id e initial_mit_reference_id, sem card_token bruto.');\n }\n } else if (params.initial_mit_reference_id !== undefined) {\n throw new TypeError('initial_mit_reference_id exige is_mit=true.');\n }\n optionalIdentifier(params.initial_mit_reference_id, 'initial_mit_reference_id');\n rejectPANLikeOptionalText(params.initial_mit_reference_id, 'initial_mit_reference_id');\n validateSplitRules(params.split_rules, params.amount_cents);\n return metadata === undefined ? params : { ...params, metadata };\n}\n\nfunction validateSplitRules(rules: CreateChargeParams['split_rules'], amountCents: number): void {\n if (rules === undefined) return;\n if (!Array.isArray(rules) || rules.length > 50) throw new TypeError('split_rules aceita no maximo 50 itens.');\n const amount = BigInt(amountCents);\n let allocatedCents = 0n;\n let percentageBps = 0n;\n for (const rule of rules) {\n allowedObject(rule, ['recipient_id', 'value_type', 'value_bps', 'value_cents'], 'split rule');\n requiredIdentifier(rule.recipient_id, 'split_rules.recipient_id');\n rejectPANLikeOptionalText(rule.recipient_id, 'split_rules.recipient_id');\n if (rule.value_type === 'fixed_amount') {\n safeInteger(rule.value_cents, 1, amountCents, 'split_rules.value_cents');\n if (rule.value_bps !== undefined) throw new TypeError('fixed_amount nao aceita value_bps.');\n allocatedCents += BigInt(rule.value_cents);\n } else if (rule.value_type === 'percentage_of_gross') {\n safeInteger(rule.value_bps, 1, 10_000, 'split_rules.value_bps');\n if (rule.value_cents !== undefined) throw new TypeError('percentage_of_gross nao aceita value_cents.');\n percentageBps += BigInt(rule.value_bps);\n allocatedCents += amount * BigInt(rule.value_bps) / 10_000n;\n } else {\n throw new TypeError('split_rules.value_type invalido.');\n }\n }\n if (percentageBps > 10_000n || allocatedCents > amount) {\n throw new TypeError('split_rules agregado nao pode exceder o valor da cobranca.');\n }\n}\n\nfunction validateCheckoutSessionParams(params: CreateCheckoutSessionParams): CreateCheckoutSessionParams {\n allowedObject(params, [\n 'items', 'success_url', 'cancel_url', 'customer_id', 'customer_data', 'allowed_payment_methods',\n 'affiliate_code', 'coupon_id', 'utm_params', 'expires_in_minutes', 'metadata',\n 'collect_shipping_address', 'delivery_type', 'allow_coupons'\n ], 'checkout');\n if (!Array.isArray(params.items) || params.items.length < 1 || params.items.length > 100) {\n throw new TypeError('items precisa conter de 1 a 100 itens.');\n }\n let total = 0;\n for (const item of params.items) {\n allowedObject(item, ['name', 'quantity', 'unit_amount_cents'], 'checkout item');\n requiredText(item.name, 200, 'items.name');\n rejectPANLikeOptionalText(item.name, 'items.name');\n safeInteger(item.quantity, 1, 1_000_000, 'items.quantity');\n safeInteger(item.unit_amount_cents, 100, Number.MAX_SAFE_INTEGER, 'items.unit_amount_cents');\n const line = item.quantity * item.unit_amount_cents;\n total += line;\n if (!Number.isSafeInteger(line) || !Number.isSafeInteger(total)) throw new TypeError('Total do checkout excede o limite seguro.');\n }\n safeRedirectUrl(params.success_url, 'success_url');\n safeRedirectUrl(params.cancel_url, 'cancel_url');\n if (params.customer_id !== undefined && params.customer_data !== undefined) {\n throw new TypeError('customer_id e customer_data sao mutuamente exclusivos.');\n }\n optionalIdentifier(params.customer_id, 'customer_id');\n rejectPANLikeOptionalText(params.customer_id, 'customer_id');\n if (params.customer_data !== undefined) {\n allowedObject(params.customer_data, ['name', 'email', 'document', 'phone'], 'customer_data');\n optionalText(params.customer_data.name, 200, 'customer_data.name');\n rejectPANLikeOptionalText(params.customer_data.name, 'customer_data.name');\n optionalText(params.customer_data.email, 320, 'customer_data.email');\n rejectPANLikeOptionalText(params.customer_data.email, 'customer_data.email');\n optionalText(params.customer_data.document, 64, 'customer_data.document');\n optionalText(params.customer_data.phone, 32, 'customer_data.phone');\n }\n if (params.allowed_payment_methods !== undefined) {\n const methods = [...params.allowed_payment_methods];\n if (methods.length < 1 || methods.length > 2 || new Set(methods).size !== methods.length ||\n methods.some((method) => method !== 'pix' && method !== 'credit_card')) {\n throw new TypeError('allowed_payment_methods invalido.');\n }\n }\n optionalIdentifier(params.coupon_id, 'coupon_id');\n if (params.allow_coupons === false && params.coupon_id !== undefined) {\n throw new TypeError('coupon_id nao pode ser usado quando allow_coupons=false.');\n }\n optionalText(params.affiliate_code, 128, 'affiliate_code');\n rejectPANLikeOptionalText(params.affiliate_code, 'affiliate_code');\n optionalText(params.delivery_type, 64, 'delivery_type');\n rejectPANLikeOptionalText(params.delivery_type, 'delivery_type');\n optionalInteger(params.expires_in_minutes, 1, 1_440, 'expires_in_minutes');\n optionalBoolean(params.collect_shipping_address, 'collect_shipping_address');\n optionalBoolean(params.allow_coupons, 'allow_coupons');\n const metadata = params.metadata === undefined\n ? undefined\n : canonicalJsonObject(params.metadata, 'metadata');\n const utmParams = params.utm_params === undefined\n ? undefined\n : canonicalJsonObject(params.utm_params, 'utm_params');\n if (metadata === undefined && utmParams === undefined) return params;\n return { ...params, metadata, utm_params: utmParams };\n}\n\nfunction validateSubscriptionParams(params: CreateSubscriptionParams): CreateSubscriptionParams {\n allowedObject(params, [\n 'customer_id', 'plan_id', 'payment_method', 'trial_days', 'card_token_id', 'coupon_id',\n 'affiliate_code', 'metadata', 'external_reference'\n ], 'subscription');\n requiredIdentifier(params.customer_id, 'customer_id');\n rejectPANLikeOptionalText(params.customer_id, 'customer_id');\n requiredIdentifier(params.plan_id, 'plan_id');\n if (params.payment_method !== 'pix' && params.payment_method !== 'credit_card') {\n throw new TypeError('payment_method precisa ser pix ou credit_card.');\n }\n optionalIdentifier(params.card_token_id, 'card_token_id');\n if (params.card_token_id !== undefined && containsPANLikeSequence(params.card_token_id)) {\n throw new TypeError('card_token_id contem possivel numero de cartao.');\n }\n if (params.payment_method === 'credit_card' && params.card_token_id === undefined) {\n throw new TypeError('credit_card exige card_token_id.');\n }\n if (params.payment_method === 'pix' && params.card_token_id !== undefined) {\n throw new TypeError('card_token_id nao pode ser enviado para PIX.');\n }\n optionalIdentifier(params.coupon_id, 'coupon_id');\n optionalInteger(params.trial_days, 0, 365, 'trial_days');\n optionalText(params.affiliate_code, 128, 'affiliate_code');\n rejectPANLikeOptionalText(params.affiliate_code, 'affiliate_code');\n optionalText(params.external_reference, 256, 'external_reference');\n rejectPANLikeOptionalText(params.external_reference, 'external_reference');\n const metadata = params.metadata === undefined\n ? undefined\n : canonicalJsonObject(params.metadata, 'metadata');\n return metadata === undefined ? params : { ...params, metadata };\n}\n\nfunction validateCancelSubscriptionParams(params: CancelSubscriptionParams): CancelSubscriptionParams {\n allowedObject(params, ['mode', 'reason'], 'subscription cancellation');\n if (params.mode !== 'immediate' && params.mode !== 'end_of_period') throw new TypeError('mode invalido.');\n if (params.reason === undefined) return params;\n if (typeof params.reason !== 'string') throw new TypeError('reason invalido.');\n const normalizedReason = trimBackendWhitespace(params.reason);\n if (normalizedReason.length === 0) return { mode: params.mode };\n optionalText(normalizedReason, 500, 'reason');\n rejectPANLikeOptionalText(normalizedReason, 'reason');\n return { ...params, reason: normalizedReason };\n}\n\nfunction validateCustomerParams(params: UpdateCustomerParams): void {\n allowedObject(params, [\n 'name', 'email', 'tax_id', 'phone', 'birth_date', 'external_reference', 'marketing_consent'\n ], 'customer');\n requiredText(params.name, 200, 'name');\n rejectPANLikeOptionalText(params.name, 'name');\n requiredText(params.email, 320, 'email');\n rejectPANLikeOptionalText(params.email, 'email');\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(params.email)) throw new TypeError('email invalido.');\n optionalText(params.tax_id, 64, 'tax_id');\n optionalText(params.phone, 32, 'phone');\n optionalText(params.external_reference, 256, 'external_reference');\n rejectPANLikeOptionalText(params.external_reference, 'external_reference');\n optionalBoolean(params.marketing_consent, 'marketing_consent');\n if (params.birth_date !== undefined && !/^\\d{4}-\\d{2}-\\d{2}$/.test(params.birth_date)) {\n throw new TypeError('birth_date precisa usar YYYY-MM-DD.');\n }\n}\n\nfunction validateChargeListParams(params: ListChargesParams): void {\n allowedObject(params, [\n 'status', 'customer_id', 'payment_method', 'created_at_from', 'created_at_to', 'limit', 'cursor'\n ], 'charge list');\n if (params.status !== undefined && !LIST_CHARGE_STATUSES.has(params.status)) throw new TypeError('status invalido.');\n if (params.payment_method !== undefined && params.payment_method !== 'pix' && params.payment_method !== 'credit_card') {\n throw new TypeError('payment_method invalido.');\n }\n optionalIdentifier(params.customer_id, 'customer_id');\n rejectPANLikeOptionalText(params.customer_id, 'customer_id');\n optionalInteger(params.limit, 1, 100, 'limit');\n optionalCursor(params.cursor, 256, 'cursor');\n optionalInstant(params.created_at_from, 'created_at_from');\n optionalInstant(params.created_at_to, 'created_at_to');\n if (params.created_at_from !== undefined && params.created_at_to !== undefined &&\n parseInstant(params.created_at_from)! >= parseInstant(params.created_at_to)!) {\n throw new TypeError('created_at_from precisa ser anterior a created_at_to.');\n }\n}\n\nfunction validateMutationOptions(options: RequestOptions, maximum: number): void {\n if (options.idempotencyKey !== undefined && options.idempotencyKey.length > maximum) {\n throw new TypeError(`Idempotency-Key deve ter no maximo ${maximum} caracteres neste recurso.`);\n }\n}\n\nfunction allowedObject(value: unknown, keys: 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 TypeError(`${field} precisa ser um objeto simples.`);\n }\n const allowlist = new Set(keys);\n const unsupported = Object.keys(value).find((key) => !allowlist.has(key));\n if (unsupported !== undefined) throw new TypeError(`${field} contem campo nao suportado: ${unsupported}.`);\n}\n\nfunction validateResourceId(value: unknown, field: string): void {\n const identifier = requiredIdentifier(value, field);\n rejectPANLikeOptionalText(identifier, field);\n}\n\nfunction requiredIdentifier(value: unknown, field: string): string {\n const identifier = requiredText(value, 256, field);\n if (!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(identifier)) throw new TypeError(`${field} invalido.`);\n return identifier;\n}\n\nfunction optionalIdentifier(value: unknown, field: string): void {\n if (value !== undefined) requiredIdentifier(value, field);\n}\n\nfunction requiredText(value: unknown, maximum: number, field: string): string {\n if (typeof value !== 'string' || value.trim().length < 1 || value.length > maximum || /[\\x00-\\x1f\\x7f]/.test(value)) {\n throw new TypeError(`${field} invalido.`);\n }\n return value;\n}\n\nfunction optionalText(value: unknown, maximum: number, field: string): void {\n if (value !== undefined) requiredText(value, maximum, field);\n}\n\nfunction safeInteger(value: unknown, minimum: number, maximum: number, field: string): void {\n if (!Number.isSafeInteger(value) || (value as number) < minimum || (value as number) > maximum) {\n throw new TypeError(`${field} precisa ser inteiro entre ${minimum} e ${maximum}.`);\n }\n}\n\nfunction optionalInteger(value: unknown, minimum: number, maximum: number, field: string): void {\n if (value !== undefined) safeInteger(value, minimum, maximum, field);\n}\n\nfunction optionalBoolean(value: unknown, field: string): void {\n if (value !== undefined && typeof value !== 'boolean') throw new TypeError(`${field} precisa ser boolean.`);\n}\n\nfunction optionalCursor(value: unknown, maximum: number, field: string): void {\n if (value !== undefined &&\n (typeof value !== 'string' || !validCanonicalCursor(value, maximum))) {\n throw new TypeError(`${field} invalido.`);\n }\n}\n\nfunction optionalInstant(value: unknown, field: string): void {\n if (value !== undefined && (typeof value !== 'string' || !validInstant(value))) {\n throw new TypeError(`${field} precisa ser uma data ISO-8601.`);\n }\n}\n\nfunction isIpLiteral(value: string): boolean {\n return isIpv4Literal(value) || isIpv6Literal(value);\n}\n\nfunction isIpv4Literal(value: string): boolean {\n const octets = value.split('.');\n return octets.length === 4 && octets.every((octet) =>\n /^(?:0|[1-9][0-9]{0,2})$/.test(octet) && Number(octet) <= 255\n );\n}\n\nfunction isIpv6Literal(value: string): boolean {\n if (!value.includes(':') || !/^[0-9A-Fa-f:.]+$/.test(value)) return false;\n const compression = value.indexOf('::');\n if (compression !== -1 && value.indexOf('::', compression + 2) !== -1) return false;\n const sides = compression === -1 ? [value] : [value.slice(0, compression), value.slice(compression + 2)];\n const parts = sides.flatMap((side) => side === '' ? [] : side.split(':'));\n if (parts.some((part) => part.length === 0)) return false;\n\n let units = 0;\n for (const [index, part] of parts.entries()) {\n if (part.includes('.')) {\n if (index !== parts.length - 1 || !isIpv4Literal(part)) return false;\n units += 2;\n } else {\n if (!/^[0-9A-Fa-f]{1,4}$/.test(part)) return false;\n units += 1;\n }\n }\n return compression === -1 ? units === 8 : units < 8;\n}\n\nfunction safeRedirectUrl(value: unknown, field: string): void {\n if (typeof value !== 'string' || value.length > 2_048) throw new TypeError(`${field} invalida.`);\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new TypeError(`${field} precisa ser URL absoluta.`);\n }\n const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);\n if ((url.protocol !== 'https:' && !(loopback && url.protocol === 'http:')) || url.username || url.password) {\n throw new TypeError(`${field} precisa ser URL HTTPS segura.`);\n }\n}\n\nfunction validateJsonObject(value: unknown, field: string): void {\n allowedObject(value, Object.keys(value as object), field);\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 TypeError(`${field} excede o limite de complexidade.`);\n const entry = current.value;\n if (entry === null || typeof entry === 'boolean') continue;\n if (typeof entry === 'string') {\n if (containsPANLikeSequence(entry)) throw new TypeError(`${field} contem possivel numero de cartao.`);\n continue;\n }\n if (typeof entry === 'number') {\n if (!Number.isFinite(entry)) throw new TypeError(`${field} contem numero invalido.`);\n if (containsPANLikeSequence(JSON.stringify(entry))) {\n throw new TypeError(`${field} contem possivel numero de cartao.`);\n }\n continue;\n }\n if (typeof entry !== 'object') throw new TypeError(`${field} contem valor nao-JSON.`);\n if (seen.has(entry)) throw new TypeError(`${field} contem ciclo.`);\n seen.add(entry);\n for (const [key, child] of Object.entries(entry)) {\n if (containsPANLikeSequence(key)) {\n throw new TypeError(`${field} contem possivel numero de cartao.`);\n }\n const normalized = key.normalize('NFKC').toLowerCase();\n if (/[^\\x00-\\x7f]/.test(normalized)) {\n throw new TypeError(`${field} contem nome de campo Unicode nao suportado.`);\n }\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 TypeError(`${field} contem campo sensivel proibido.`);\n }\n stack.push({ value: child, depth: current.depth + 1 });\n }\n }\n}\n\nfunction canonicalJsonObject<T>(value: T, field: string): T {\n validateJsonObject(value, field);\n return value;\n}\n\nfunction canonicalRequestSnapshot<T>(value: T, field: string): T {\n let encoded: string | undefined;\n try {\n encoded = JSON.stringify(value, (_key, child: unknown) => {\n if (typeof child === 'number' && !Number.isFinite(child)) {\n throw new TypeError(`${field} contem numero invalido.`);\n }\n if (['symbol', 'function', 'bigint'].includes(typeof child)) {\n throw new TypeError(`${field} contem valor nao-JSON.`);\n }\n return child;\n });\n } catch {\n throw new TypeError(`${field} contem valor nao-JSON.`);\n }\n if (encoded === undefined) throw new TypeError(`${field} invalido.`);\n\n let snapshot: unknown;\n try {\n snapshot = JSON.parse(encoded);\n } catch {\n throw new TypeError(`${field} contem valor nao-JSON.`);\n }\n if (!isObject(snapshot)) throw new TypeError(`${field} invalido.`);\n\n return snapshot as T;\n}\n\nfunction rejectPANLikeOptionalText(value: string | undefined, field: string): void {\n if (value !== undefined && containsPANLikeSequence(value)) {\n throw new TypeError(`${field} contem possivel numero de cartao.`);\n }\n}\n","import { HttpClient } from './http.js';\nimport {\n ChargesResource,\n CheckoutSessionsResource,\n CustomersResource,\n RefundsResource,\n SubscriptionsResource\n} from './resources.js';\nimport { WebhooksResource } from './webhooks.js';\nimport type { MuPagConfig } from './types.js';\n\nexport * from './errors.js';\nexport * from './resources.js';\nexport * from './types.js';\nexport * from './webhooks.js';\n\nexport class MuPag {\n readonly charges: ChargesResource;\n readonly checkoutSessions: CheckoutSessionsResource;\n readonly customers: CustomersResource;\n readonly refunds: RefundsResource;\n readonly subscriptions: SubscriptionsResource;\n readonly webhooks: WebhooksResource;\n\n /**\n * Cria cliente ergonomico para a API publica da MuPag.\n *\n * A superficie segue `mupag.charges.create(...)` para ficar natural em apps\n * Node/TypeScript e em agentes de coding. O cliente escolhe base URL por ambiente,\n * injeta auth, aplica retries seguros e deixa cada recurso pequeno.\n */\n constructor(config: MuPagConfig) {\n const http = new HttpClient({\n env: config.env,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n fetch: config.fetch,\n timeoutMs: config.timeoutMs,\n maxResponseBytes: config.maxResponseBytes,\n retry: config.retry\n });\n\n this.charges = new ChargesResource(http);\n this.checkoutSessions = new CheckoutSessionsResource(http);\n this.customers = new CustomersResource(http);\n this.refunds = new RefundsResource(http);\n this.subscriptions = new SubscriptionsResource(http);\n this.webhooks = new WebhooksResource();\n }\n}\n"]}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
type Environment = 'test' | 'prd';
|
|
2
|
+
type JsonPrimitive = string | number | boolean | null;
|
|
3
|
+
type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
|
|
4
|
+
type JsonObject = {
|
|
5
|
+
[key: string]: JsonValue;
|
|
6
|
+
};
|
|
7
|
+
type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
8
|
+
type RetryConfig = {
|
|
9
|
+
maxRetries: number;
|
|
10
|
+
initialDelayMs: number;
|
|
11
|
+
maxDelayMs: number;
|
|
12
|
+
};
|
|
13
|
+
type MuPagConfig = {
|
|
14
|
+
apiKey: string;
|
|
15
|
+
env: Environment;
|
|
16
|
+
baseUrl?: string | undefined;
|
|
17
|
+
fetch?: FetchLike | undefined;
|
|
18
|
+
timeoutMs?: number | undefined;
|
|
19
|
+
maxResponseBytes?: number | undefined;
|
|
20
|
+
retry?: Partial<RetryConfig> | undefined;
|
|
21
|
+
};
|
|
22
|
+
type RequestOptions = {
|
|
23
|
+
idempotencyKey?: string | undefined;
|
|
24
|
+
};
|
|
25
|
+
type CheckoutSessionItem = {
|
|
26
|
+
name: string;
|
|
27
|
+
quantity: number;
|
|
28
|
+
unit_amount_cents: number;
|
|
29
|
+
};
|
|
30
|
+
type CheckoutSessionCustomerData = {
|
|
31
|
+
name?: string | undefined;
|
|
32
|
+
email?: string | undefined;
|
|
33
|
+
document?: string | undefined;
|
|
34
|
+
phone?: string | undefined;
|
|
35
|
+
};
|
|
36
|
+
type CreateCheckoutSessionParams = {
|
|
37
|
+
items: CheckoutSessionItem[];
|
|
38
|
+
success_url: string;
|
|
39
|
+
cancel_url: string;
|
|
40
|
+
customer_id?: string | undefined;
|
|
41
|
+
customer_data?: CheckoutSessionCustomerData | undefined;
|
|
42
|
+
allowed_payment_methods?: Array<'pix' | 'credit_card'> | readonly ['pix', 'credit_card'] | undefined;
|
|
43
|
+
affiliate_code?: string | undefined;
|
|
44
|
+
coupon_id?: string | undefined;
|
|
45
|
+
utm_params?: JsonObject | undefined;
|
|
46
|
+
expires_in_minutes?: number | undefined;
|
|
47
|
+
metadata?: JsonObject | undefined;
|
|
48
|
+
collect_shipping_address?: boolean | undefined;
|
|
49
|
+
delivery_type?: string | undefined;
|
|
50
|
+
allow_coupons?: boolean | undefined;
|
|
51
|
+
};
|
|
52
|
+
type CheckoutSession = JsonObject & {
|
|
53
|
+
id: string;
|
|
54
|
+
url: string;
|
|
55
|
+
expires_at: string;
|
|
56
|
+
};
|
|
57
|
+
type Page<TItem extends JsonValue = JsonObject> = {
|
|
58
|
+
data: TItem[];
|
|
59
|
+
next_cursor?: string | null | undefined;
|
|
60
|
+
};
|
|
61
|
+
type Charge = JsonObject & {
|
|
62
|
+
charge_id: string;
|
|
63
|
+
amount_cents: number;
|
|
64
|
+
status: string;
|
|
65
|
+
psp_charge_id?: string | null | undefined;
|
|
66
|
+
card_token_id?: string | null | undefined;
|
|
67
|
+
card_brand?: string | null | undefined;
|
|
68
|
+
card_last4?: string | null | undefined;
|
|
69
|
+
three_ds_acs_url?: string | null | undefined;
|
|
70
|
+
failure_classification?: string | null | undefined;
|
|
71
|
+
pix_qr_code_base64?: string | null | undefined;
|
|
72
|
+
pix_emv_code?: string | null | undefined;
|
|
73
|
+
pix_qr_code?: string | undefined;
|
|
74
|
+
pix_copy_paste?: string | undefined;
|
|
75
|
+
expires_at?: string | null | undefined;
|
|
76
|
+
created_at?: string | undefined;
|
|
77
|
+
};
|
|
78
|
+
type ChargeCancellation = JsonObject & {
|
|
79
|
+
charge_id: string;
|
|
80
|
+
status: 'cancelled' | 'cancellation_pending';
|
|
81
|
+
reason: 'payment_attempt_cancelled';
|
|
82
|
+
cancelled_at: string | null;
|
|
83
|
+
};
|
|
84
|
+
type CancelChargeOptions = {
|
|
85
|
+
idempotencyKey: string;
|
|
86
|
+
reason?: 'payment_attempt_cancelled' | undefined;
|
|
87
|
+
};
|
|
88
|
+
type ChargeCustomer = {
|
|
89
|
+
id: string;
|
|
90
|
+
name: string;
|
|
91
|
+
email: string;
|
|
92
|
+
tax_id: string;
|
|
93
|
+
} | {
|
|
94
|
+
id?: never;
|
|
95
|
+
name: string;
|
|
96
|
+
email: string;
|
|
97
|
+
tax_id: string;
|
|
98
|
+
};
|
|
99
|
+
type ChargeSplitRule = {
|
|
100
|
+
recipient_id: string;
|
|
101
|
+
value_type: 'fixed_amount';
|
|
102
|
+
value_cents: number;
|
|
103
|
+
value_bps?: never;
|
|
104
|
+
} | {
|
|
105
|
+
recipient_id: string;
|
|
106
|
+
value_type: 'percentage_of_gross';
|
|
107
|
+
value_bps: number;
|
|
108
|
+
value_cents?: never;
|
|
109
|
+
};
|
|
110
|
+
type CreateChargeParams = {
|
|
111
|
+
amount_cents: number;
|
|
112
|
+
payment_method: 'pix' | 'credit_card';
|
|
113
|
+
customer: ChargeCustomer;
|
|
114
|
+
installments?: 1 | undefined;
|
|
115
|
+
card_token?: string | undefined;
|
|
116
|
+
card_token_id?: string | undefined;
|
|
117
|
+
save_card?: boolean | undefined;
|
|
118
|
+
description?: string | undefined;
|
|
119
|
+
/** @deprecated O PSP Asaas nao oferece este campo; qualquer valor nao vazio e rejeitado. */
|
|
120
|
+
soft_descriptor?: string | undefined;
|
|
121
|
+
/** IP literal do pagador atestado pelo merchant; obrigatorio para credit_card. */
|
|
122
|
+
payer_ip?: string | undefined;
|
|
123
|
+
auth_only?: boolean | undefined;
|
|
124
|
+
product_max_installments?: 1 | undefined;
|
|
125
|
+
external_reference?: string | undefined;
|
|
126
|
+
expires_in_seconds?: number | undefined;
|
|
127
|
+
metadata?: JsonObject | undefined;
|
|
128
|
+
affiliate_code?: string | undefined;
|
|
129
|
+
coupon_code?: string | undefined;
|
|
130
|
+
split_rules?: ChargeSplitRule[] | undefined;
|
|
131
|
+
is_mit?: boolean | undefined;
|
|
132
|
+
initial_mit_reference_id?: string | undefined;
|
|
133
|
+
};
|
|
134
|
+
type ListChargesParams = {
|
|
135
|
+
status?: string | undefined;
|
|
136
|
+
customer_id?: string | undefined;
|
|
137
|
+
payment_method?: string | undefined;
|
|
138
|
+
created_at_from?: string | undefined;
|
|
139
|
+
created_at_to?: string | undefined;
|
|
140
|
+
limit?: number | undefined;
|
|
141
|
+
cursor?: string | undefined;
|
|
142
|
+
};
|
|
143
|
+
type Subscription = JsonObject & {
|
|
144
|
+
id: string;
|
|
145
|
+
customer_id: string;
|
|
146
|
+
plan_id: string;
|
|
147
|
+
payment_method: string;
|
|
148
|
+
status: string;
|
|
149
|
+
cancel_at_period_end: boolean;
|
|
150
|
+
metadata: JsonObject;
|
|
151
|
+
};
|
|
152
|
+
type CreateSubscriptionParams = {
|
|
153
|
+
customer_id: string;
|
|
154
|
+
plan_id: string;
|
|
155
|
+
payment_method: 'pix' | 'credit_card';
|
|
156
|
+
trial_days?: number | undefined;
|
|
157
|
+
card_token_id?: string | undefined;
|
|
158
|
+
coupon_id?: string | undefined;
|
|
159
|
+
affiliate_code?: string | undefined;
|
|
160
|
+
metadata?: JsonObject | undefined;
|
|
161
|
+
external_reference?: string | undefined;
|
|
162
|
+
};
|
|
163
|
+
type CancelSubscriptionParams = {
|
|
164
|
+
mode: 'immediate' | 'end_of_period';
|
|
165
|
+
reason?: string | undefined;
|
|
166
|
+
};
|
|
167
|
+
type Refund = JsonObject & {
|
|
168
|
+
refund_id: string;
|
|
169
|
+
charge_id: string;
|
|
170
|
+
amount_cents: number;
|
|
171
|
+
status: string;
|
|
172
|
+
psp_refund_id?: string | null | undefined;
|
|
173
|
+
reason?: string | null | undefined;
|
|
174
|
+
requested_at?: string | undefined;
|
|
175
|
+
completed_at?: string | null | undefined;
|
|
176
|
+
failure_reason?: string | null | undefined;
|
|
177
|
+
};
|
|
178
|
+
type CreateRefundParams = {
|
|
179
|
+
amount_cents: number;
|
|
180
|
+
full?: never;
|
|
181
|
+
reason?: string | undefined;
|
|
182
|
+
} | {
|
|
183
|
+
full: true;
|
|
184
|
+
amount_cents?: never;
|
|
185
|
+
reason?: string | undefined;
|
|
186
|
+
};
|
|
187
|
+
type RefundList = {
|
|
188
|
+
refunds: Refund[];
|
|
189
|
+
next_cursor?: string | null | undefined;
|
|
190
|
+
};
|
|
191
|
+
type ListRefundsParams = {
|
|
192
|
+
limit?: number | undefined;
|
|
193
|
+
cursor?: string | undefined;
|
|
194
|
+
};
|
|
195
|
+
type Customer = JsonObject & {
|
|
196
|
+
id: string;
|
|
197
|
+
merchant_id?: string | undefined;
|
|
198
|
+
environment?: string | undefined;
|
|
199
|
+
name?: string | undefined;
|
|
200
|
+
email?: string | undefined;
|
|
201
|
+
tax_id?: string | undefined;
|
|
202
|
+
phone?: string | undefined;
|
|
203
|
+
birth_date?: string | undefined;
|
|
204
|
+
external_reference?: string | undefined;
|
|
205
|
+
marketing_consent?: boolean | undefined;
|
|
206
|
+
created_at?: string | undefined;
|
|
207
|
+
updated_at?: string | undefined;
|
|
208
|
+
};
|
|
209
|
+
type UpdateCustomerParams = {
|
|
210
|
+
name: string;
|
|
211
|
+
email: string;
|
|
212
|
+
tax_id?: string | undefined;
|
|
213
|
+
phone?: string | undefined;
|
|
214
|
+
birth_date?: string | undefined;
|
|
215
|
+
external_reference?: string | undefined;
|
|
216
|
+
marketing_consent?: boolean | undefined;
|
|
217
|
+
};
|
|
218
|
+
type MuPagEvent<TData extends JsonValue = JsonValue> = {
|
|
219
|
+
id: string;
|
|
220
|
+
type: string;
|
|
221
|
+
data: TData;
|
|
222
|
+
created_at?: string;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
export type { CancelChargeOptions as C, Environment as E, FetchLike as F, JsonObject as J, ListChargesParams as L, MuPagConfig as M, Page as P, Refund as R, Subscription as S, UpdateCustomerParams as U, CancelSubscriptionParams as a, Charge as b, ChargeCancellation as c, ChargeCustomer as d, ChargeSplitRule as e, CheckoutSession as f, CheckoutSessionCustomerData as g, CheckoutSessionItem as h, CreateChargeParams as i, CreateCheckoutSessionParams as j, CreateRefundParams as k, CreateSubscriptionParams as l, Customer as m, JsonPrimitive as n, JsonValue as o, ListRefundsParams as p, MuPagEvent as q, RefundList as r, RequestOptions as s, RetryConfig as t };
|