tempest-react-sdk 0.76.0 → 0.78.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 +2 -2
- package/bin/create-tempest-app.e2e.test.mjs +112 -0
- package/bin/create-tempest-app.mjs +69 -28
- package/bin/lib/alias/collect.mjs +20 -3
- package/bin/lib/alias/index.mjs +12 -1
- package/bin/lib/alias/index.test.mjs +24 -0
- package/bin/lib/component/generate.mjs +191 -0
- package/bin/lib/component/generate.test.mjs +336 -0
- package/bin/lib/css/analyze.test.mjs +21 -1
- package/bin/lib/css/collect.mjs +14 -0
- package/bin/lib/css/extract.mjs +63 -5
- package/bin/lib/css/extract.test.mjs +110 -1
- package/bin/lib/css/fix.e2e.test.mjs +50 -0
- package/bin/lib/css/index.mjs +6 -1
- package/bin/lib/fs/contain.mjs +50 -0
- package/bin/lib/icons/generate.mjs +28 -3
- package/bin/lib/icons/generate.test.mjs +57 -1
- package/bin/lib/openapi/escape.mjs +224 -0
- package/bin/lib/openapi/generate.encode.test.mjs +120 -0
- package/bin/lib/openapi/generate.hostile.test.mjs +621 -0
- package/bin/lib/openapi/generate.mjs +129 -18
- package/bin/lib/openapi/generate.test.mjs +7 -2
- package/bin/lib/openapi/schema-to-zod.mjs +43 -4
- package/bin/tempest-gen.test.mjs +188 -0
- package/bin/tempest.mjs +263 -6
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +203 -58
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/auth/refresh-queue.cjs +1 -1
- package/dist/auth/refresh-queue.cjs.map +1 -1
- package/dist/auth/refresh-queue.js +13 -6
- package/dist/auth/refresh-queue.js.map +1 -1
- package/dist/br/pix.cjs +1 -1
- package/dist/br/pix.cjs.map +1 -1
- package/dist/br/pix.js +85 -72
- package/dist/br/pix.js.map +1 -1
- package/dist/br.d.ts +19 -4
- package/dist/components/Chat/ChatAttachments.cjs +1 -1
- package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
- package/dist/components/Chat/ChatAttachments.js +46 -38
- package/dist/components/Chat/ChatAttachments.js.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.js +1 -1
- package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
- package/dist/components/CodeBlock/tokenize.cjs +1 -1
- package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
- package/dist/components/CodeBlock/tokenize.js +54 -25
- package/dist/components/CodeBlock/tokenize.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +7 -5
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +171 -90
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/components/Toast/Toast.module.cjs +1 -1
- package/dist/components/Toast/Toast.module.cjs.map +1 -1
- package/dist/components/Toast/Toast.module.js +7 -3
- package/dist/components/Toast/Toast.module.js.map +1 -1
- package/dist/components/Toast/ToastProvider.cjs +1 -1
- package/dist/components/Toast/ToastProvider.cjs.map +1 -1
- package/dist/components/Toast/ToastProvider.js +77 -51
- package/dist/components/Toast/ToastProvider.js.map +1 -1
- package/dist/data/create-data-provider.cjs +1 -1
- package/dist/data/create-data-provider.cjs.map +1 -1
- package/dist/data/create-data-provider.js +32 -21
- package/dist/data/create-data-provider.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +81 -73
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/errors.cjs +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js +39 -35
- package/dist/http/errors.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +141 -105
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +5 -6
- package/dist/http/retry.js.map +1 -1
- package/dist/oauth/callback.cjs +2 -0
- package/dist/oauth/callback.cjs.map +1 -0
- package/dist/oauth/callback.js +42 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/use-oauth-callback.cjs +1 -1
- package/dist/oauth/use-oauth-callback.cjs.map +1 -1
- package/dist/oauth/use-oauth-callback.js +13 -20
- package/dist/oauth/use-oauth-callback.js.map +1 -1
- package/dist/push/use-push-subscription.cjs +1 -1
- package/dist/push/use-push-subscription.cjs.map +1 -1
- package/dist/push/use-push-subscription.js +42 -42
- package/dist/push/use-push-subscription.js.map +1 -1
- package/dist/push/web-push-client.cjs +1 -1
- package/dist/push/web-push-client.cjs.map +1 -1
- package/dist/push/web-push-client.js +23 -3
- package/dist/push/web-push-client.js.map +1 -1
- package/dist/query/offline-persistence.cjs +1 -1
- package/dist/query/offline-persistence.cjs.map +1 -1
- package/dist/query/offline-persistence.js +68 -23
- package/dist/query/offline-persistence.js.map +1 -1
- package/dist/styles/component/Toast.css +6 -1
- package/dist/styles/feedback.css +6 -1
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +272 -60
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/cache-inspect.cjs.map +1 -1
- package/dist/sw/cache-inspect.js.map +1 -1
- package/dist/sw/cache.cjs +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js +91 -64
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw/credential-headers.cjs +2 -0
- package/dist/sw/credential-headers.cjs.map +1 -0
- package/dist/sw/credential-headers.js +17 -0
- package/dist/sw/credential-headers.js.map +1 -0
- package/dist/sw/session-data.cjs +2 -0
- package/dist/sw/session-data.cjs.map +1 -0
- package/dist/sw/session-data.js +17 -0
- package/dist/sw/session-data.js.map +1 -0
- package/dist/sw.cjs +1 -1
- package/dist/sw.d.ts +309 -23
- package/dist/sw.js +7 -5
- package/dist/telemetry/app-error-queue.cjs +1 -1
- package/dist/telemetry/app-error-queue.cjs.map +1 -1
- package/dist/telemetry/app-error-queue.js +19 -14
- package/dist/telemetry/app-error-queue.js.map +1 -1
- package/dist/telemetry/app-error-reporter.cjs +1 -1
- package/dist/telemetry/app-error-reporter.cjs.map +1 -1
- package/dist/telemetry/app-error-reporter.js +75 -34
- package/dist/telemetry/app-error-reporter.js.map +1 -1
- package/dist/telemetry/app-error-transport.cjs +1 -1
- package/dist/telemetry/app-error-transport.cjs.map +1 -1
- package/dist/telemetry/app-error-transport.js +16 -3
- package/dist/telemetry/app-error-transport.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +1183 -64
- package/dist/tempest-react-sdk.js +160 -156
- package/dist/utils/csv.cjs +3 -3
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js +18 -14
- package/dist/utils/csv.js.map +1 -1
- package/dist/utils/owner-fingerprint.cjs +2 -0
- package/dist/utils/owner-fingerprint.cjs.map +1 -0
- package/dist/utils/owner-fingerprint.js +18 -0
- package/dist/utils/owner-fingerprint.js.map +1 -0
- package/dist/utils/safe-url.cjs +2 -0
- package/dist/utils/safe-url.cjs.map +1 -0
- package/dist/utils/safe-url.js +39 -0
- package/dist/utils/safe-url.js.map +1 -0
- package/dist/vite/tempest-csp.cjs +2 -2
- package/dist/vite/tempest-csp.cjs.map +1 -1
- package/dist/vite/tempest-csp.js +130 -64
- package/dist/vite/tempest-csp.js.map +1 -1
- package/dist/vite.d.ts +23 -5
- package/dist/webrtc/peer-link.cjs +1 -1
- package/dist/webrtc/peer-link.cjs.map +1 -1
- package/dist/webrtc/peer-link.js +2 -10
- package/dist/webrtc/peer-link.js.map +1 -1
- package/dist/webrtc/peer-mesh.cjs +1 -1
- package/dist/webrtc/peer-mesh.cjs.map +1 -1
- package/dist/webrtc/peer-mesh.js +110 -72
- package/dist/webrtc/peer-mesh.js.map +1 -1
- package/package.json +1 -1
- package/template-pwa/src/pwa.tsx +22 -0
- package/template-pwa/src/sw.ts +27 -14
- package/dist/components/Markdown/markdown-url.cjs +0 -2
- package/dist/components/Markdown/markdown-url.cjs.map +0 -1
- package/dist/components/Markdown/markdown-url.js +0 -28
- package/dist/components/Markdown/markdown-url.js.map +0 -1
package/dist/br/pix.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pix.cjs","names":[],"sources":["../../src/br/pix.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines — EMV®QRCPS-MPM for Pix: the TLV writer, the\n * CRC16-CCITT, the field catalogue with its nesting, key-type detection and the\n * parser that has to accept what other banks emit. Reader and writer live together\n * because each one is the other's test — a payload this file builds is a payload it\n * must parse back.\n */\nimport { validateCNPJ, validateCPF } from \"@/forms/br-validators\";\n\n/**\n * A Pix payload could not be built or read.\n *\n * Its own class so a caller can tell \"the operator typed a bad key\" apart from a\n * bug, and so an `ErrorBoundary` can render a form error instead of a crash.\n */\nexport class PixError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PixError\";\n }\n}\n\n/** The five key formats DICT accepts. */\nexport type PixKeyType = \"cpf\" | \"cnpj\" | \"email\" | \"phone\" | \"evp\";\n\n/** A key after normalisation, ready to go into the payload. */\nexport interface NormalizedPixKey {\n type: PixKeyType;\n /** The exact string written into the BR Code. */\n value: string;\n}\n\n/** One TLV as it appeared in a payload, unknown tags included. */\nexport interface PixField {\n /** Two-character tag, e.g. `\"59\"`. */\n id: string;\n /** Raw value, still encoded when the tag is itself a template. */\n value: string;\n}\n\n/** A BR Code that carries the key — the one you print on a poster. */\nexport interface PixStaticInput {\n kind?: \"static\";\n /** CPF, CNPJ, e-mail, phone or EVP. Validated and normalised. */\n key: string;\n /** Payee name. Truncated by the spec at 25 characters — longer throws. */\n merchantName: string;\n /** Payee city. Truncated by the spec at 15 characters — longer throws. */\n merchantCity: string;\n /** Amount in BRL. Omit for a payer-chooses-the-value QR. */\n amount?: number;\n /** Reference the PSP echoes back, `[A-Za-z0-9]{1,25}`. Defaults to `\"***\"`. */\n txid?: string;\n /** Free text shown by some wallets. Goes into tag 26, sub-tag 02. */\n description?: string;\n /** CEP, digits only. Optional tag 61. */\n postalCode?: string;\n /** Single-use QR: sets tag 01 to `\"12\"` instead of `\"11\"`. */\n oneTime?: boolean;\n}\n\n/** A BR Code that carries a URL the wallet fetches to learn the amount. */\nexport interface PixDynamicInput {\n kind: \"dynamic\";\n /**\n * `payloadLocation` — the https URL the wallet GETs, **without** the scheme,\n * exactly as BACEN specifies (`pix.example.com/qr/v2/abc`).\n */\n url: string;\n merchantName: string;\n merchantCity: string;\n postalCode?: string;\n /** Single-use QR. Defaults to `true`, which is what a dynamic QR normally is. */\n oneTime?: boolean;\n}\n\n/** Everything `pixPayload` accepts. */\nexport type PixInput = PixStaticInput | PixDynamicInput;\n\n/** A payload taken apart again. */\nexport interface PixData {\n /** `\"dynamic\"` when tag 26 carried a URL instead of a key. */\n kind: \"static\" | \"dynamic\";\n /** Present on a static payload. */\n key?: string;\n keyType?: PixKeyType;\n /** Present on a dynamic payload. */\n url?: string;\n merchantName: string;\n merchantCity: string;\n /** Reais. `undefined` when the payer chooses the amount. */\n amount?: number;\n /** ISO 4217 numeric. `\"986\"` for BRL. */\n currency: string;\n countryCode: string;\n merchantCategoryCode: string;\n /** `\"***\"` on a reusable static QR that identifies no single transaction. */\n txid?: string;\n description?: string;\n postalCode?: string;\n /** Tag 01 read as `\"12\"`. */\n oneTime: boolean;\n /** The four hex characters that closed the payload. */\n crc: string;\n /** Whether those four characters match a recomputed CRC. */\n crcValid: boolean;\n /** Every top-level TLV, in payload order, unknown tags included. */\n fields: PixField[];\n}\n\n/** Options for {@link parsePixPayload}. */\nexport interface ParsePixOptions {\n /**\n * Throw when the checksum does not match. Default `true`.\n *\n * Turn it off only to inspect a payload you already know is broken: a BR Code\n * whose CRC fails has been corrupted in transit, and the account it now points\n * at is not the account the payee published.\n */\n requireCrc?: boolean;\n}\n\n/**\n * Generator polynomial of CRC-16/CCITT-FALSE, `x^16 + x^12 + x^5 + 1`.\n *\n * Taken from the CRC catalogue entry `CRC-16/IBM-3740` (alias CCITT-FALSE):\n * `width=16 poly=0x1021 init=0xffff refin=false refout=false xorout=0x0000\n * check=0x29b1`. The BACEN \"Manual de Padrões para Iniciação do Pix\" names this\n * exact variant for tag 63.\n */\nconst CRC16_POLYNOMIAL = 0x1021;\n\n/** Register preset of CRC-16/CCITT-FALSE. Not zero — that is a different variant. */\nconst CRC16_INITIAL = 0xffff;\n\n/** Keeps the shift register 16 bits wide. */\nconst CRC16_MASK = 0xffff;\n\nconst TAG_PAYLOAD_FORMAT = \"00\";\nconst TAG_POINT_OF_INITIATION = \"01\";\nconst TAG_MERCHANT_ACCOUNT_INFO = \"26\";\nconst TAG_MERCHANT_CATEGORY_CODE = \"52\";\nconst TAG_TRANSACTION_CURRENCY = \"53\";\nconst TAG_TRANSACTION_AMOUNT = \"54\";\nconst TAG_COUNTRY_CODE = \"58\";\nconst TAG_MERCHANT_NAME = \"59\";\nconst TAG_MERCHANT_CITY = \"60\";\nconst TAG_POSTAL_CODE = \"61\";\nconst TAG_ADDITIONAL_DATA = \"62\";\nconst TAG_CRC = \"63\";\n\nconst MAI_TAG_GUI = \"00\";\nconst MAI_TAG_KEY = \"01\";\nconst MAI_TAG_DESCRIPTION = \"02\";\nconst MAI_TAG_URL = \"25\";\nconst ADDITIONAL_TAG_TXID = \"05\";\n\n/** Globally Unique Identifier that marks tag 26 as a Pix account. */\nconst PIX_GUI = \"br.gov.bcb.pix\";\n\nconst PAYLOAD_FORMAT_VERSION = \"01\";\nconst POINT_OF_INITIATION_REUSABLE = \"11\";\nconst POINT_OF_INITIATION_SINGLE_USE = \"12\";\nconst DEFAULT_MERCHANT_CATEGORY_CODE = \"0000\";\nconst CURRENCY_BRL = \"986\";\nconst COUNTRY_BR = \"BR\";\nconst TXID_UNSPECIFIED = \"***\";\n\nconst MAX_MERCHANT_NAME = 25;\nconst MAX_MERCHANT_CITY = 15;\nconst MAX_TXID = 25;\nconst MAX_TLV_VALUE = 99;\nconst MAX_EMAIL_KEY = 77;\n\n/**\n * CRC-16/CCITT-FALSE of a string, as four upper-case hex characters.\n *\n * Bitwise rather than table-driven: 200-odd characters at 8 shifts each is\n * nothing, and a 256-entry table is 2 KB of payload every consumer of the `/br`\n * entry would carry.\n *\n * The input is taken as UTF-8 bytes. A Pix payload is ASCII by construction —\n * {@link pixPayload} rejects anything else — but the function is exported and a\n * caller may hand it arbitrary text, and hashing UTF-16 code units would then\n * disagree with every other implementation.\n *\n * @param input - Bytes to run through the register.\n * @returns Four upper-case hex characters, zero-padded.\n *\n * @example\n * pixCrc16(\"123456789\"); // \"29B1\" — the catalogue check value\n */\nexport function pixCrc16(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let crc = CRC16_INITIAL;\n for (const byte of bytes) {\n crc ^= byte << 8;\n for (let bit = 0; bit < 8; bit += 1) {\n crc =\n (crc & 0x8000) !== 0\n ? ((crc << 1) ^ CRC16_POLYNOMIAL) & CRC16_MASK\n : (crc << 1) & CRC16_MASK;\n }\n }\n return crc.toString(16).toUpperCase().padStart(4, \"0\");\n}\n\n/** Digits of a possibly masked value. */\nfunction digits(value: string): string {\n return value.replace(/\\D/g, \"\");\n}\n\n/**\n * Drop diacritics and reject whatever is left outside printable ASCII.\n *\n * The BR Code character set has no room for accents, and a wallet that meets one\n * either fails to parse the QR or shows mojibake. Stripping them is lossy but\n * legible (\"São Paulo\" → \"Sao Paulo\"), which beats both alternatives; anything\n * that is not a diacritic — an emoji, a CJK character — is a mistake the caller\n * has to see, so it throws.\n */\nfunction toPayloadText(value: string, field: string): string {\n const stripped = value.normalize(\"NFD\").replace(/\\p{Diacritic}/gu, \"\");\n if (/[^\\x20-\\x7E]/.test(stripped)) {\n throw new PixError(\n `${field} has characters the BR Code cannot carry: ${JSON.stringify(value)}. ` +\n \"Use unaccented ASCII.\",\n );\n }\n return stripped;\n}\n\n/** One `ID + 2-digit length + value` triple. */\nfunction tlv(id: string, value: string): string {\n if (value.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag ${id} is ${value.length} characters; the EMV length field holds at most ${MAX_TLV_VALUE}.`,\n );\n }\n return `${id}${String(value.length).padStart(2, \"0\")}${value}`;\n}\n\n/**\n * Classify a Pix key, or `null` when it matches no accepted format.\n *\n * !!! warning \"CPF and a national phone number are both eleven digits\"\n * `\"11987654321\"` is a valid mobile number and could be a CPF. The check\n * digits break the tie: an 11-digit string is a CPF when its DV validates and\n * a phone otherwise. Pass phone keys as `+5511987654321` to remove the guess\n * entirely.\n *\n * @param key - Raw key, masked or not.\n * @returns The key type, or `null`.\n */\nexport function pixKeyType(key: string): PixKeyType | null {\n const trimmed = key.trim();\n if (trimmed === \"\") return null;\n\n if (trimmed.includes(\"@\")) {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(trimmed) && trimmed.length <= MAX_EMAIL_KEY\n ? \"email\"\n : null;\n }\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {\n return \"evp\";\n }\n\n const numbers = digits(trimmed);\n if (numbers.length === 14) return validateCNPJ(numbers) ? \"cnpj\" : null;\n if (numbers.length === 11 && validateCPF(numbers)) return \"cpf\";\n if (trimmed.startsWith(\"+\")) {\n return /^\\+55\\d{10,11}$/.test(`+${numbers}`) ? \"phone\" : null;\n }\n if (numbers.length === 10 || numbers.length === 11) return \"phone\";\n if (numbers.length === 12 || numbers.length === 13) {\n return numbers.startsWith(\"55\") ? \"phone\" : null;\n }\n return null;\n}\n\n/**\n * Validate a Pix key and return the exact string to write into the payload.\n *\n * Normalisation per type: CPF and CNPJ lose their mask, a phone becomes E.164\n * with the `+55` country code, an EVP is lower-cased, and an e-mail is\n * lower-cased because DICT stores it that way — a key that differs only in case\n * would otherwise fail to resolve.\n *\n * All validation lives in {@link pixKeyType}; past that gate the normalisation is\n * total, which is why the phone branch strips a country code purely on length\n * rather than re-checking the shape.\n *\n * @param key - Raw key, masked or not.\n * @returns The type and the normalised value.\n * @throws {PixError} When the key matches no accepted format, or when a document\n * key fails its check digits.\n *\n * @example\n * normalizePixKey(\"123.456.789-09\"); // { type: \"cpf\", value: \"12345678909\" }\n * normalizePixKey(\"(11) 98765-4321\"); // { type: \"phone\", value: \"+5511987654321\" }\n */\nexport function normalizePixKey(key: string): NormalizedPixKey {\n const trimmed = key.trim();\n const type = pixKeyType(trimmed);\n if (type === null) {\n throw new PixError(\n `Not a Pix key: ${JSON.stringify(key)}. Expected a CPF, CNPJ, e-mail, ` +\n \"phone (+5511987654321) or EVP (UUID).\",\n );\n }\n\n if (type === \"email\") return { type, value: trimmed.toLowerCase() };\n if (type === \"evp\") return { type, value: trimmed.toLowerCase() };\n if (type === \"phone\") {\n const numbers = digits(trimmed);\n return { type, value: `+55${numbers.length > 11 ? numbers.slice(2) : numbers}` };\n }\n return { type, value: digits(trimmed) };\n}\n\n/** Format an amount the way tag 54 wants it: dot separator, two decimals. */\nfunction toAmountField(amount: number): string {\n if (!Number.isFinite(amount)) {\n throw new PixError(`Amount must be a finite number, got ${amount}.`);\n }\n if (amount <= 0) {\n throw new PixError(\n `Amount must be positive, got ${amount}. Omit \\`amount\\` for a QR whose value the payer types.`,\n );\n }\n const field = amount.toFixed(2);\n if (field.length > 13) {\n throw new PixError(`Amount ${field} does not fit tag 54, which holds 13 characters.`);\n }\n return field;\n}\n\n/** Bound the two free-text identity fields the spec caps hard. */\nfunction toBoundedText(value: string, max: number, field: string): string {\n const text = toPayloadText(value.trim(), field);\n if (text === \"\") throw new PixError(`${field} is required.`);\n if (text.length > max) {\n throw new PixError(\n `${field} is ${text.length} characters; the BR Code allows ${max}. Shorten it — ` +\n \"truncating here would silently change what the payer sees.\",\n );\n }\n return text;\n}\n\n/** Tag 62, which exists only to carry the txid. */\nfunction additionalDataField(txid: string | undefined): string {\n const value = txid?.trim() ?? \"\";\n if (value === \"\" || value === TXID_UNSPECIFIED) {\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, TXID_UNSPECIFIED));\n }\n if (!new RegExp(`^[A-Za-z0-9]{1,${MAX_TXID}}$`).test(value)) {\n throw new PixError(\n `txid must be 1 to ${MAX_TXID} letters or digits, got ${JSON.stringify(txid)}.`,\n );\n }\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, value));\n}\n\n/** Tag 26 for a static payload: GUI, key and the optional description. */\nfunction staticMerchantAccount(input: PixStaticInput): string {\n const { value } = normalizePixKey(input.key);\n let inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_KEY, value);\n const description = input.description?.trim();\n if (description !== undefined && description !== \"\") {\n inner += tlv(MAI_TAG_DESCRIPTION, toPayloadText(description, \"description\"));\n }\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten `description`.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/** Tag 26 for a dynamic payload: GUI plus the URL, and no key. */\nfunction dynamicMerchantAccount(input: PixDynamicInput): string {\n const url = toPayloadText(input.url.trim(), \"url\").replace(/^https?:\\/\\//i, \"\");\n if (url === \"\") throw new PixError(\"url is required for a dynamic BR Code.\");\n const inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_URL, url);\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten the payload URL.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/**\n * Build a Pix \"Copia e Cola\" payload — the string behind a Pix QR code.\n *\n * The format is EMVCo MPM: a flat list of `ID + 2-digit length + value` triples,\n * closed by tag 63 holding a CRC-16/CCITT-FALSE over **everything before it,\n * including the literal `6304` header of tag 63 itself**. That last detail is the\n * one implementations get wrong; see {@link pixCrc16}.\n *\n * Two shapes come out of here:\n *\n * - **static** — tag 26 carries the key, so the QR is self-contained and can be\n * printed. Amount optional; a txid of `\"***\"` means \"identifies no single\n * transaction\", which is what a reusable poster QR wants.\n * - **dynamic** — tag 26 carries a URL instead, and the wallet fetches the amount\n * and payee from the PSP. Use it when the value is per-order. Defaults to\n * single-use (tag 01 = `12`).\n *\n * The distinction matters and is not cosmetic: a static QR settles against\n * whatever the payer typed, a dynamic one against what the PSP served, so a\n * charge that must reconcile to a cent needs the dynamic form.\n *\n * @param input - Static or dynamic payload description.\n * @returns The full payload, CRC included, ready to render as a QR or to copy.\n * @throws {PixError} On an unrecognised key, a field over its length cap, a\n * non-positive amount, or text that is not representable in the BR Code.\n *\n * @example\n * pixPayload({\n * key: \"12345678909\",\n * merchantName: \"Loja Tempest\",\n * merchantCity: \"São Paulo\",\n * amount: 25.5,\n * txid: \"PEDIDO123\",\n * });\n */\nexport function pixPayload(input: PixInput): string {\n const dynamic = input.kind === \"dynamic\";\n const oneTime = input.oneTime ?? dynamic;\n\n let payload = tlv(TAG_PAYLOAD_FORMAT, PAYLOAD_FORMAT_VERSION);\n payload += tlv(\n TAG_POINT_OF_INITIATION,\n oneTime ? POINT_OF_INITIATION_SINGLE_USE : POINT_OF_INITIATION_REUSABLE,\n );\n payload += dynamic ? dynamicMerchantAccount(input) : staticMerchantAccount(input);\n payload += tlv(TAG_MERCHANT_CATEGORY_CODE, DEFAULT_MERCHANT_CATEGORY_CODE);\n payload += tlv(TAG_TRANSACTION_CURRENCY, CURRENCY_BRL);\n if (!dynamic && input.amount !== undefined) {\n payload += tlv(TAG_TRANSACTION_AMOUNT, toAmountField(input.amount));\n }\n payload += tlv(TAG_COUNTRY_CODE, COUNTRY_BR);\n payload += tlv(\n TAG_MERCHANT_NAME,\n toBoundedText(input.merchantName, MAX_MERCHANT_NAME, \"merchantName\"),\n );\n payload += tlv(\n TAG_MERCHANT_CITY,\n toBoundedText(input.merchantCity, MAX_MERCHANT_CITY, \"merchantCity\"),\n );\n const postalCode = input.postalCode === undefined ? \"\" : digits(input.postalCode);\n if (postalCode !== \"\") payload += tlv(TAG_POSTAL_CODE, postalCode);\n payload += additionalDataField(dynamic ? TXID_UNSPECIFIED : input.txid);\n\n const withCrcHeader = `${payload}${TAG_CRC}04`;\n return `${withCrcHeader}${pixCrc16(withCrcHeader)}`;\n}\n\n/**\n * Split a flat run of TLVs. Stops cleanly at the first malformed triple.\n *\n * @throws {PixError} When a length prefix is not two digits or runs past the end.\n */\nfunction parseTlv(input: string, where: string): PixField[] {\n const fields: PixField[] = [];\n let cursor = 0;\n while (cursor < input.length) {\n const id = input.slice(cursor, cursor + 2);\n const rawLength = input.slice(cursor + 2, cursor + 4);\n if (!/^\\d{2}$/.test(id) || !/^\\d{2}$/.test(rawLength)) {\n throw new PixError(\n `Malformed TLV in ${where} at offset ${cursor}: expected a 2-digit tag and length.`,\n );\n }\n const length = Number(rawLength);\n const start = cursor + 4;\n if (start + length > input.length) {\n throw new PixError(\n `Tag ${id} in ${where} declares ${length} characters but only ${input.length - start} remain.`,\n );\n }\n fields.push({ id, value: input.slice(start, start + length) });\n cursor = start + length;\n }\n return fields;\n}\n\n/** First value for a tag, or `undefined`. */\nfunction pick(fields: readonly PixField[], id: string): string | undefined {\n return fields.find((field) => field.id === id)?.value;\n}\n\n/**\n * Read a Pix \"Copia e Cola\" payload back into its parts.\n *\n * Tolerant by design: tags the SDK does not know about are kept verbatim in\n * {@link PixData.fields} instead of raising, because PSPs do add their own\n * templates and a reader that rejects them is useless in production. What is\n * *not* tolerated is a broken frame — a length prefix that runs off the end, a\n * missing tag 63 — or a checksum mismatch, which means the string was corrupted\n * and no longer names the account the payee published.\n *\n * @param payload - The copia-e-cola string. Surrounding whitespace is ignored.\n * @param options - See {@link ParsePixOptions}.\n * @returns The decoded payload.\n * @throws {PixError} On a malformed frame, a missing CRC tag, a tag 26 that is\n * not a Pix account, or — unless `requireCrc` is `false` — a CRC mismatch.\n *\n * @example\n * const data = parsePixPayload(copied);\n * console.log(data.key, data.amount, data.txid);\n */\nexport function parsePixPayload(payload: string, options: ParsePixOptions = {}): PixData {\n const { requireCrc = true } = options;\n const text = payload.trim();\n if (text.length < 8) throw new PixError(\"Payload is too short to be a BR Code.\");\n\n const crcHeaderAt = text.length - 8;\n if (text.slice(crcHeaderAt, crcHeaderAt + 4) !== `${TAG_CRC}04`) {\n throw new PixError(\"Payload does not end in a `6304` CRC tag.\");\n }\n const crc = text.slice(-4).toUpperCase();\n const expected = pixCrc16(text.slice(0, -4));\n const crcValid = crc === expected;\n if (!crcValid && requireCrc) {\n throw new PixError(`CRC mismatch: payload says ${crc}, recomputed ${expected}.`);\n }\n\n const fields = parseTlv(text.slice(0, crcHeaderAt), \"payload\");\n const merchantAccount = pick(fields, TAG_MERCHANT_ACCOUNT_INFO);\n if (merchantAccount === undefined) {\n throw new PixError(\"Payload has no tag 26 (merchant account information).\");\n }\n const account = parseTlv(merchantAccount, \"tag 26\");\n const gui = pick(account, MAI_TAG_GUI);\n if (gui?.toLowerCase() !== PIX_GUI) {\n throw new PixError(\n `Tag 26 is not a Pix account: expected GUI ${PIX_GUI}, got ${JSON.stringify(gui)}.`,\n );\n }\n\n const url = pick(account, MAI_TAG_URL);\n const key = pick(account, MAI_TAG_KEY);\n const amountField = pick(fields, TAG_TRANSACTION_AMOUNT);\n const txid = pick(\n parseTlv(pick(fields, TAG_ADDITIONAL_DATA) ?? \"\", \"tag 62\"),\n ADDITIONAL_TAG_TXID,\n );\n\n return {\n kind: url !== undefined && key === undefined ? \"dynamic\" : \"static\",\n ...(key === undefined ? {} : { key, keyType: pixKeyType(key) ?? undefined }),\n ...(url === undefined ? {} : { url }),\n merchantName: pick(fields, TAG_MERCHANT_NAME) ?? \"\",\n merchantCity: pick(fields, TAG_MERCHANT_CITY) ?? \"\",\n ...(amountField === undefined ? {} : { amount: Number(amountField) }),\n currency: pick(fields, TAG_TRANSACTION_CURRENCY) ?? \"\",\n countryCode: pick(fields, TAG_COUNTRY_CODE) ?? \"\",\n merchantCategoryCode: pick(fields, TAG_MERCHANT_CATEGORY_CODE) ?? \"\",\n ...(txid === undefined ? {} : { txid }),\n ...(pick(account, MAI_TAG_DESCRIPTION) === undefined\n ? {}\n : { description: pick(account, MAI_TAG_DESCRIPTION) }),\n ...(pick(fields, TAG_POSTAL_CODE) === undefined\n ? {}\n : { postalCode: pick(fields, TAG_POSTAL_CODE) }),\n oneTime: pick(fields, TAG_POINT_OF_INITIATION) === POINT_OF_INITIATION_SINGLE_USE,\n crc,\n crcValid,\n fields,\n };\n}\n"],"mappings":"8CAeA,IAAa,EAAb,cAA8B,KAAM,CAChC,YAAY,EAAiB,CACzB,MAAM,CAAO,EACb,KAAK,KAAO,UAChB,CACJ,EA8GM,EAAmB,KAGnB,EAAgB,MAGhB,EAAa,MAEb,EAAqB,KACrB,EAA0B,KAC1B,EAA4B,KAC5B,EAA6B,KAC7B,EAA2B,KAC3B,EAAyB,KACzB,EAAmB,KACnB,EAAoB,KACpB,EAAoB,KACpB,EAAkB,KAClB,EAAsB,KACtB,EAAU,KAEV,EAAc,KACd,EAAc,KACd,EAAsB,KACtB,EAAc,KACd,EAAsB,KAGtB,EAAU,iBAEV,EAAyB,KACzB,EAA+B,KAC/B,EAAiC,KACjC,EAAiC,OACjC,EAAe,MACf,EAAa,KACb,EAAmB,MAEnB,EAAoB,GACpB,EAAoB,GACpB,EAAW,GACX,EAAgB,GAChB,EAAgB,GAoBtB,SAAgB,EAAS,EAAuB,CAC5C,IAAM,EAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,EACxC,EAAM,EACV,IAAK,IAAM,KAAQ,EAAO,CACtB,GAAO,GAAQ,EACf,IAAK,IAAI,EAAM,EAAG,EAAM,EAAG,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EAAQ,CAAwB,GAAK,GACpD,YAAa,EAAK,EAAQ,CAAgB,GAAK,GAC/C,qBAAsB,EAAK,EAAQ,CAA0B,GAAK,GAClE,GAAI,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,EACrC,GAAI,EAAK,EAAS,CAAmB,IAAM,IAAA,GACrC,CAAC,EACD,CAAE,YAAa,EAAK,EAAS,CAAmB,CAAE,EACxD,GAAI,EAAK,EAAQ,CAAe,IAAM,IAAA,GAChC,CAAC,EACD,CAAE,WAAY,EAAK,EAAQ,CAAe,CAAE,EAClD,QAAS,EAAK,EAAQ,CAAuB,IAAM,EACnD,MACA,WACA,QACJ,CACJ"}
|
|
1
|
+
{"version":3,"file":"pix.cjs","names":[],"sources":["../../src/br/pix.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines — EMV®QRCPS-MPM for Pix: the TLV writer, the\n * CRC16-CCITT, the field catalogue with its nesting, key-type detection and the\n * parser that has to accept what other banks emit. Reader and writer live together\n * because each one is the other's test — a payload this file builds is a payload it\n * must parse back.\n */\nimport { validateCNPJ, validateCPF } from \"@/forms/br-validators\";\n\n/**\n * A Pix payload could not be built or read.\n *\n * Its own class so a caller can tell \"the operator typed a bad key\" apart from a\n * bug, and so an `ErrorBoundary` can render a form error instead of a crash.\n */\nexport class PixError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PixError\";\n }\n}\n\n/** The five key formats DICT accepts. */\nexport type PixKeyType = \"cpf\" | \"cnpj\" | \"email\" | \"phone\" | \"evp\";\n\n/** A key after normalisation, ready to go into the payload. */\nexport interface NormalizedPixKey {\n type: PixKeyType;\n /** The exact string written into the BR Code. */\n value: string;\n}\n\n/** One TLV as it appeared in a payload, unknown tags included. */\nexport interface PixField {\n /** Two-character tag, e.g. `\"59\"`. */\n id: string;\n /** Raw value, still encoded when the tag is itself a template. */\n value: string;\n}\n\n/** A BR Code that carries the key — the one you print on a poster. */\nexport interface PixStaticInput {\n kind?: \"static\";\n /** CPF, CNPJ, e-mail, phone or EVP. Validated and normalised. */\n key: string;\n /** Payee name. Truncated by the spec at 25 characters — longer throws. */\n merchantName: string;\n /** Payee city. Truncated by the spec at 15 characters — longer throws. */\n merchantCity: string;\n /** Amount in BRL. Omit for a payer-chooses-the-value QR. */\n amount?: number;\n /** Reference the PSP echoes back, `[A-Za-z0-9]{1,25}`. Defaults to `\"***\"`. */\n txid?: string;\n /** Free text shown by some wallets. Goes into tag 26, sub-tag 02. */\n description?: string;\n /** CEP, digits only. Optional tag 61. */\n postalCode?: string;\n /** Single-use QR: sets tag 01 to `\"12\"` instead of `\"11\"`. */\n oneTime?: boolean;\n}\n\n/** A BR Code that carries a URL the wallet fetches to learn the amount. */\nexport interface PixDynamicInput {\n kind: \"dynamic\";\n /**\n * `payloadLocation` — the https URL the wallet GETs, **without** the scheme,\n * exactly as BACEN specifies (`pix.example.com/qr/v2/abc`).\n */\n url: string;\n merchantName: string;\n merchantCity: string;\n postalCode?: string;\n /** Single-use QR. Defaults to `true`, which is what a dynamic QR normally is. */\n oneTime?: boolean;\n}\n\n/** Everything `pixPayload` accepts. */\nexport type PixInput = PixStaticInput | PixDynamicInput;\n\n/** A payload taken apart again. */\nexport interface PixData {\n /** `\"dynamic\"` when tag 26 carried a URL instead of a key. */\n kind: \"static\" | \"dynamic\";\n /** Present on a static payload. */\n key?: string;\n keyType?: PixKeyType;\n /** Present on a dynamic payload. */\n url?: string;\n merchantName: string;\n merchantCity: string;\n /** Reais. `undefined` when the payer chooses the amount. */\n amount?: number;\n /** ISO 4217 numeric. `\"986\"` for BRL. */\n currency: string;\n countryCode: string;\n merchantCategoryCode: string;\n /** `\"***\"` on a reusable static QR that identifies no single transaction. */\n txid?: string;\n description?: string;\n postalCode?: string;\n /** Tag 01 read as `\"12\"`. */\n oneTime: boolean;\n /** The four hex characters that closed the payload. */\n crc: string;\n /** Whether those four characters match a recomputed CRC. */\n crcValid: boolean;\n /** Every top-level TLV, in payload order, unknown tags included. */\n fields: PixField[];\n}\n\n/** Options for {@link parsePixPayload}. */\nexport interface ParsePixOptions {\n /**\n * Throw when the checksum does not match. Default `true`.\n *\n * Turn it off only to inspect a payload you already know is broken: a BR Code\n * whose CRC fails has been corrupted in transit, and the account it now points\n * at is not the account the payee published.\n */\n requireCrc?: boolean;\n}\n\n/**\n * Generator polynomial of CRC-16/CCITT-FALSE, `x^16 + x^12 + x^5 + 1`.\n *\n * Taken from the CRC catalogue entry `CRC-16/IBM-3740` (alias CCITT-FALSE):\n * `width=16 poly=0x1021 init=0xffff refin=false refout=false xorout=0x0000\n * check=0x29b1`. The BACEN \"Manual de Padrões para Iniciação do Pix\" names this\n * exact variant for tag 63.\n */\nconst CRC16_POLYNOMIAL = 0x1021;\n\n/** Register preset of CRC-16/CCITT-FALSE. Not zero — that is a different variant. */\nconst CRC16_INITIAL = 0xffff;\n\n/** Keeps the shift register 16 bits wide. */\nconst CRC16_MASK = 0xffff;\n\nconst TAG_PAYLOAD_FORMAT = \"00\";\nconst TAG_POINT_OF_INITIATION = \"01\";\nconst TAG_MERCHANT_ACCOUNT_INFO = \"26\";\nconst TAG_MERCHANT_CATEGORY_CODE = \"52\";\nconst TAG_TRANSACTION_CURRENCY = \"53\";\nconst TAG_TRANSACTION_AMOUNT = \"54\";\nconst TAG_COUNTRY_CODE = \"58\";\nconst TAG_MERCHANT_NAME = \"59\";\nconst TAG_MERCHANT_CITY = \"60\";\nconst TAG_POSTAL_CODE = \"61\";\nconst TAG_ADDITIONAL_DATA = \"62\";\nconst TAG_CRC = \"63\";\n\nconst MAI_TAG_GUI = \"00\";\nconst MAI_TAG_KEY = \"01\";\nconst MAI_TAG_DESCRIPTION = \"02\";\nconst MAI_TAG_URL = \"25\";\nconst ADDITIONAL_TAG_TXID = \"05\";\n\n/** Globally Unique Identifier that marks tag 26 as a Pix account. */\nconst PIX_GUI = \"br.gov.bcb.pix\";\n\nconst PAYLOAD_FORMAT_VERSION = \"01\";\nconst POINT_OF_INITIATION_REUSABLE = \"11\";\nconst POINT_OF_INITIATION_SINGLE_USE = \"12\";\nconst DEFAULT_MERCHANT_CATEGORY_CODE = \"0000\";\nconst CURRENCY_BRL = \"986\";\nconst COUNTRY_BR = \"BR\";\nconst TXID_UNSPECIFIED = \"***\";\n\nconst MAX_MERCHANT_NAME = 25;\nconst MAX_MERCHANT_CITY = 15;\nconst MAX_TXID = 25;\nconst MAX_TLV_VALUE = 99;\nconst MAX_EMAIL_KEY = 77;\n\n/**\n * Tag 54 as EMV® QRCPS-MPM writes it: digits, and at most one `.` as the decimal\n * mark, which \"may be present even if there are no decimals\" (`\"98.\"`). Up to two\n * decimals, the minor unit ISO 4217 gives BRL (`986`). No sign, exponent, comma,\n * hex prefix or whitespace — every one of which `Number()` would happily read.\n *\n * Zero (`\"0\"`, `\"0.00\"`) is accepted: EMV asks for a non-zero amount, but the BACEN\n * BR Code manual (v2, Table 1) gives `\"0\"` as an example value of tag 54, and the\n * parser reads payloads other PSPs emit — strict with what is malformed, tolerant\n * with what the Bacen spec accepts. The builder stays stricter: `pixPayload`\n * still refuses a non-positive amount, because it only writes what we choose to emit.\n */\nconst AMOUNT_FIELD = /^\\d+(?:\\.\\d{0,2})?$/;\n\n/** Width of tag 54: \"01..13\" in the BACEN BR Code manual, Table 1. */\nconst MAX_AMOUNT_FIELD = 13;\n\n/**\n * CRC-16/CCITT-FALSE of a string, as four upper-case hex characters.\n *\n * Bitwise rather than table-driven: 200-odd characters at 8 shifts each is\n * nothing, and a 256-entry table is 2 KB of payload every consumer of the `/br`\n * entry would carry.\n *\n * The input is taken as UTF-8 bytes. A Pix payload is ASCII by construction —\n * {@link pixPayload} rejects anything else — but the function is exported and a\n * caller may hand it arbitrary text, and hashing UTF-16 code units would then\n * disagree with every other implementation.\n *\n * @param input - Bytes to run through the register.\n * @returns Four upper-case hex characters, zero-padded.\n *\n * @example\n * pixCrc16(\"123456789\"); // \"29B1\" — the catalogue check value\n */\nexport function pixCrc16(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let crc = CRC16_INITIAL;\n for (const byte of bytes) {\n crc ^= byte << 8;\n for (let bit = 0; bit < 8; bit += 1) {\n crc =\n (crc & 0x8000) !== 0\n ? ((crc << 1) ^ CRC16_POLYNOMIAL) & CRC16_MASK\n : (crc << 1) & CRC16_MASK;\n }\n }\n return crc.toString(16).toUpperCase().padStart(4, \"0\");\n}\n\n/** Digits of a possibly masked value. */\nfunction digits(value: string): string {\n return value.replace(/\\D/g, \"\");\n}\n\n/**\n * Drop diacritics and reject whatever is left outside printable ASCII.\n *\n * The BR Code character set has no room for accents, and a wallet that meets one\n * either fails to parse the QR or shows mojibake. Stripping them is lossy but\n * legible (\"São Paulo\" → \"Sao Paulo\"), which beats both alternatives; anything\n * that is not a diacritic — an emoji, a CJK character — is a mistake the caller\n * has to see, so it throws.\n */\nfunction toPayloadText(value: string, field: string): string {\n const stripped = value.normalize(\"NFD\").replace(/\\p{Diacritic}/gu, \"\");\n if (/[^\\x20-\\x7E]/.test(stripped)) {\n throw new PixError(\n `${field} has characters the BR Code cannot carry: ${JSON.stringify(value)}. ` +\n \"Use unaccented ASCII.\",\n );\n }\n return stripped;\n}\n\n/**\n * The EMV \"Common Character Set\" that an `ans` (Alphanumeric Special) field may\n * carry: printable ASCII, `0x20`–`0x7E`. Every root field of a BR Code is `ans`,\n * and the BACEN BR Code manual (v2, May 2020) only widened it from alphanumeric —\n * \"The restriction that established that only alphanumeric characters could be\n * used has been removed\" — not past it. Only the alternate-language template\n * (tag 64) is `String` and may carry another character set, and the builder\n * never writes it.\n */\nconst COMMON_CHARACTER_SET = /^[\\x20-\\x7E]*$/;\n\n/**\n * One `ID + 2-digit length + value` triple.\n *\n * The length is \"the number of characters included in the [value] field\" (EMV\n * MPM, as restated by the HKMA Common QR Code Specification §2; the BACEN manual:\n * \"size specifies how many characters\"). Inside the common character set a\n * character is one UTF-16 unit and one UTF-8 byte, so `value.length` is exact —\n * which is why a value outside it throws instead of being measured.\n *\n * @throws {PixError} When the value leaves the common character set or exceeds\n * the two-digit length.\n */\nfunction tlv(id: string, value: string): string {\n if (!COMMON_CHARACTER_SET.test(value)) {\n throw new PixError(\n `Tag ${id} has characters outside the EMV common character set (printable ASCII): ` +\n `${JSON.stringify(value)}.`,\n );\n }\n if (value.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag ${id} is ${value.length} characters; the EMV length field holds at most ${MAX_TLV_VALUE}.`,\n );\n }\n return `${id}${String(value.length).padStart(2, \"0\")}${value}`;\n}\n\n/**\n * Classify a Pix key, or `null` when it matches no accepted format.\n *\n * !!! warning \"CPF and a national phone number are both eleven digits\"\n * `\"11987654321\"` is a valid mobile number and could be a CPF. The check\n * digits break the tie: an 11-digit string is a CPF when its DV validates and\n * a phone otherwise. Pass phone keys as `+5511987654321` to remove the guess\n * entirely.\n *\n * @param key - Raw key, masked or not.\n * @returns The key type, or `null`.\n */\nexport function pixKeyType(key: string): PixKeyType | null {\n const trimmed = key.trim();\n if (trimmed === \"\") return null;\n\n if (trimmed.includes(\"@\")) {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(trimmed) && trimmed.length <= MAX_EMAIL_KEY\n ? \"email\"\n : null;\n }\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {\n return \"evp\";\n }\n\n const numbers = digits(trimmed);\n if (numbers.length === 14) return validateCNPJ(numbers) ? \"cnpj\" : null;\n if (numbers.length === 11 && validateCPF(numbers)) return \"cpf\";\n if (trimmed.startsWith(\"+\")) {\n return /^\\+55\\d{10,11}$/.test(`+${numbers}`) ? \"phone\" : null;\n }\n if (numbers.length === 10 || numbers.length === 11) return \"phone\";\n if (numbers.length === 12 || numbers.length === 13) {\n return numbers.startsWith(\"55\") ? \"phone\" : null;\n }\n return null;\n}\n\n/**\n * Validate a Pix key and return the exact string to write into the payload.\n *\n * Normalisation per type: CPF and CNPJ lose their mask, a phone becomes E.164\n * with the `+55` country code, an EVP is lower-cased, and an e-mail is\n * lower-cased because DICT stores it that way — a key that differs only in case\n * would otherwise fail to resolve.\n *\n * All validation lives in {@link pixKeyType}; past that gate the normalisation is\n * total, which is why the phone branch strips a country code purely on length\n * rather than re-checking the shape.\n *\n * @param key - Raw key, masked or not.\n * @returns The type and the normalised value.\n * @throws {PixError} When the key matches no accepted format, or when a document\n * key fails its check digits.\n *\n * @example\n * normalizePixKey(\"123.456.789-09\"); // { type: \"cpf\", value: \"12345678909\" }\n * normalizePixKey(\"(11) 98765-4321\"); // { type: \"phone\", value: \"+5511987654321\" }\n */\nexport function normalizePixKey(key: string): NormalizedPixKey {\n const trimmed = key.trim();\n const type = pixKeyType(trimmed);\n if (type === null) {\n throw new PixError(\n `Not a Pix key: ${JSON.stringify(key)}. Expected a CPF, CNPJ, e-mail, ` +\n \"phone (+5511987654321) or EVP (UUID).\",\n );\n }\n\n if (type === \"email\") return { type, value: trimmed.toLowerCase() };\n if (type === \"evp\") return { type, value: trimmed.toLowerCase() };\n if (type === \"phone\") {\n const numbers = digits(trimmed);\n return { type, value: `+55${numbers.length > 11 ? numbers.slice(2) : numbers}` };\n }\n return { type, value: digits(trimmed) };\n}\n\n/**\n * Format an amount the way tag 54 wants it: dot separator, two decimals.\n *\n * Positivity is checked on the rounded field, not on the input: `0.004` is\n * positive and still writes `\"0.00\"`, a zero-value QR for a positive charge.\n */\nfunction toAmountField(amount: number): string {\n if (!Number.isFinite(amount)) {\n throw new PixError(`Amount must be a finite number, got ${amount}.`);\n }\n if (amount <= 0) {\n throw new PixError(\n `Amount must be positive, got ${amount}. Omit \\`amount\\` for a QR whose value the payer types.`,\n );\n }\n const field = amount.toFixed(2);\n if (Number(field) <= 0) {\n throw new PixError(\n `Amount ${amount} rounds to ${field} at two decimals. Omit \\`amount\\` for a QR whose value the payer types.`,\n );\n }\n if (field.length > 13) {\n throw new PixError(`Amount ${field} does not fit tag 54, which holds 13 characters.`);\n }\n return field;\n}\n\n/** Bound the two free-text identity fields the spec caps hard. */\nfunction toBoundedText(value: string, max: number, field: string): string {\n const text = toPayloadText(value.trim(), field);\n if (text === \"\") throw new PixError(`${field} is required.`);\n if (text.length > max) {\n throw new PixError(\n `${field} is ${text.length} characters; the BR Code allows ${max}. Shorten it — ` +\n \"truncating here would silently change what the payer sees.\",\n );\n }\n return text;\n}\n\n/** Tag 62, which exists only to carry the txid. */\nfunction additionalDataField(txid: string | undefined): string {\n const value = txid?.trim() ?? \"\";\n if (value === \"\" || value === TXID_UNSPECIFIED) {\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, TXID_UNSPECIFIED));\n }\n if (!new RegExp(`^[A-Za-z0-9]{1,${MAX_TXID}}$`).test(value)) {\n throw new PixError(\n `txid must be 1 to ${MAX_TXID} letters or digits, got ${JSON.stringify(txid)}.`,\n );\n }\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, value));\n}\n\n/** Tag 26 for a static payload: GUI, key and the optional description. */\nfunction staticMerchantAccount(input: PixStaticInput): string {\n const { value } = normalizePixKey(input.key);\n let inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_KEY, value);\n const description = input.description?.trim();\n if (description !== undefined && description !== \"\") {\n inner += tlv(MAI_TAG_DESCRIPTION, toPayloadText(description, \"description\"));\n }\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten `description`.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/** Tag 26 for a dynamic payload: GUI plus the URL, and no key. */\nfunction dynamicMerchantAccount(input: PixDynamicInput): string {\n const url = toPayloadText(input.url.trim(), \"url\").replace(/^https?:\\/\\//i, \"\");\n if (url === \"\") throw new PixError(\"url is required for a dynamic BR Code.\");\n const inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_URL, url);\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten the payload URL.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/**\n * Build a Pix \"Copia e Cola\" payload — the string behind a Pix QR code.\n *\n * The format is EMVCo MPM: a flat list of `ID + 2-digit length + value` triples,\n * closed by tag 63 holding a CRC-16/CCITT-FALSE over **everything before it,\n * including the literal `6304` header of tag 63 itself**. That last detail is the\n * one implementations get wrong; see {@link pixCrc16}.\n *\n * Two shapes come out of here:\n *\n * - **static** — tag 26 carries the key, so the QR is self-contained and can be\n * printed. Amount optional; a txid of `\"***\"` means \"identifies no single\n * transaction\", which is what a reusable poster QR wants.\n * - **dynamic** — tag 26 carries a URL instead, and the wallet fetches the amount\n * and payee from the PSP. Use it when the value is per-order. Defaults to\n * single-use (tag 01 = `12`).\n *\n * The distinction matters and is not cosmetic: a static QR settles against\n * whatever the payer typed, a dynamic one against what the PSP served, so a\n * charge that must reconcile to a cent needs the dynamic form.\n *\n * @param input - Static or dynamic payload description.\n * @returns The full payload, CRC included, ready to render as a QR or to copy.\n * @throws {PixError} On an unrecognised key, a field over its length cap, a\n * non-positive amount, or text that is not representable in the BR Code.\n *\n * @example\n * pixPayload({\n * key: \"12345678909\",\n * merchantName: \"Loja Tempest\",\n * merchantCity: \"São Paulo\",\n * amount: 25.5,\n * txid: \"PEDIDO123\",\n * });\n */\nexport function pixPayload(input: PixInput): string {\n const dynamic = input.kind === \"dynamic\";\n const oneTime = input.oneTime ?? dynamic;\n\n let payload = tlv(TAG_PAYLOAD_FORMAT, PAYLOAD_FORMAT_VERSION);\n payload += tlv(\n TAG_POINT_OF_INITIATION,\n oneTime ? POINT_OF_INITIATION_SINGLE_USE : POINT_OF_INITIATION_REUSABLE,\n );\n payload += dynamic ? dynamicMerchantAccount(input) : staticMerchantAccount(input);\n payload += tlv(TAG_MERCHANT_CATEGORY_CODE, DEFAULT_MERCHANT_CATEGORY_CODE);\n payload += tlv(TAG_TRANSACTION_CURRENCY, CURRENCY_BRL);\n if (!dynamic && input.amount !== undefined) {\n payload += tlv(TAG_TRANSACTION_AMOUNT, toAmountField(input.amount));\n }\n payload += tlv(TAG_COUNTRY_CODE, COUNTRY_BR);\n payload += tlv(\n TAG_MERCHANT_NAME,\n toBoundedText(input.merchantName, MAX_MERCHANT_NAME, \"merchantName\"),\n );\n payload += tlv(\n TAG_MERCHANT_CITY,\n toBoundedText(input.merchantCity, MAX_MERCHANT_CITY, \"merchantCity\"),\n );\n const postalCode = input.postalCode === undefined ? \"\" : digits(input.postalCode);\n if (postalCode !== \"\") payload += tlv(TAG_POSTAL_CODE, postalCode);\n payload += additionalDataField(dynamic ? TXID_UNSPECIFIED : input.txid);\n\n const withCrcHeader = `${payload}${TAG_CRC}04`;\n return `${withCrcHeader}${pixCrc16(withCrcHeader)}`;\n}\n\n/**\n * Split a flat run of TLVs. Stops cleanly at the first malformed triple.\n *\n * An ID may appear once per level. The BACEN BR Code manual (v2, May 2020)\n * states it for the root — \"there are no duplicate IDs in the document's root,\n * according to\" EMV® QRCPS-MPM;\n * the same holds here inside tags 26 and 62, which no conforming emitter\n * repeats either. Keeping the first of two values would give the caller one\n * reading of the payload while a wallet that keeps the last pays another.\n *\n * Lengths count characters (code points), as EMV defines them — see {@link tlv}.\n * A payload from another PSP may carry a `String` template (tag 64, or an\n * unreserved one) with non-ASCII text, where counting UTF-16 units would split\n * a character and misread every tag after it.\n *\n * @throws {PixError} When a length prefix is not two digits, runs past the end,\n * or an ID repeats at this level.\n */\nfunction parseTlv(text: string, where: string): PixField[] {\n const input = Array.from(text);\n const fields: PixField[] = [];\n let cursor = 0;\n while (cursor < input.length) {\n const id = input.slice(cursor, cursor + 2).join(\"\");\n const rawLength = input.slice(cursor + 2, cursor + 4).join(\"\");\n if (!/^\\d{2}$/.test(id) || !/^\\d{2}$/.test(rawLength)) {\n throw new PixError(\n `Malformed TLV in ${where} at offset ${cursor}: expected a 2-digit tag and length.`,\n );\n }\n const length = Number(rawLength);\n const start = cursor + 4;\n if (start + length > input.length) {\n throw new PixError(\n `Tag ${id} in ${where} declares ${length} characters but only ${input.length - start} remain.`,\n );\n }\n if (fields.some((field) => field.id === id)) {\n throw new PixError(\n `Tag ${id} in ${where} appears more than once; a BR Code carries each tag once per level.`,\n );\n }\n fields.push({ id, value: input.slice(start, start + length).join(\"\") });\n cursor = start + length;\n }\n return fields;\n}\n\n/** The value of a tag — unique per level, see {@link parseTlv} — or `undefined`. */\nfunction pick(fields: readonly PixField[], id: string): string | undefined {\n return fields.find((field) => field.id === id)?.value;\n}\n\n/**\n * Read tag 54 into reais.\n *\n * @throws {PixError} When the field is outside the EMV format\n * ({@link AMOUNT_FIELD}) or wider than 13 characters. Zero is read as `0`; see\n * {@link AMOUNT_FIELD} for why the reader accepts what `pixPayload` refuses.\n */\nfunction readAmountField(field: string): number {\n if (field.length > MAX_AMOUNT_FIELD || !AMOUNT_FIELD.test(field)) {\n throw new PixError(\n `Tag 54 (amount) must be an amount like \"25.50\", with \".\" as the decimal mark, ` +\n `at most two decimals and ${MAX_AMOUNT_FIELD} characters; got ${JSON.stringify(field)}.`,\n );\n }\n return Number(field);\n}\n\n/**\n * Read a Pix \"Copia e Cola\" payload back into its parts.\n *\n * Tolerant by design: tags the SDK does not know about are kept verbatim in\n * {@link PixData.fields} instead of raising, because PSPs do add their own\n * templates and a reader that rejects them is useless in production. What is\n * *not* tolerated is a broken frame — a length prefix that runs off the end, a\n * missing tag 63 — a checksum mismatch, which means the string was corrupted in\n * transit, or a payload with two readings: a tag repeated at the root or inside\n * tags 26 and 62, a tag 63 anywhere but at the end, a tag 26 with both a key and\n * a URL, or a tag 54 outside the EMV amount format. A preview built from one\n * reading while the wallet pays the other is the failure those rules exist for.\n *\n * Position is checked where EMV® QRCPS-MPM — the reference the BACEN manual\n * defers to — fixes it: tag 00 is the first object and tag 63 the last; every\n * other root tag may appear in any order. Before #475 an inner `6304` + CRC\n * followed by `5405…` and a second `6304` + CRC parsed as a priced payload,\n * while the same text cut at the first CRC was a valid payload with no amount.\n *\n * The CRC detects corruption, not authorship: whoever crafts a payload\n * recomputes it, so a valid CRC says nothing about who published the account.\n *\n * @param payload - The copia-e-cola string. Surrounding whitespace is ignored.\n * @param options - See {@link ParsePixOptions}.\n * @returns The decoded payload.\n * @throws {PixError} On a malformed frame, a missing CRC tag, a tag 00 that is\n * not first or a tag 63 that is not last, a repeated tag, a\n * tag 26 that is not a Pix account or that carries both a key and a URL, an\n * amount outside the EMV format, or — unless `requireCrc` is `false` — a CRC\n * mismatch.\n *\n * @example\n * const data = parsePixPayload(copied);\n * console.log(data.key, data.amount, data.txid);\n */\nexport function parsePixPayload(payload: string, options: ParsePixOptions = {}): PixData {\n const { requireCrc = true } = options;\n const text = payload.trim();\n if (text.length < 8) throw new PixError(\"Payload is too short to be a BR Code.\");\n\n const crcHeaderAt = text.length - 8;\n if (text.slice(crcHeaderAt, crcHeaderAt + 4) !== `${TAG_CRC}04`) {\n throw new PixError(\"Payload does not end in a `6304` CRC tag.\");\n }\n const crc = text.slice(-4).toUpperCase();\n const expected = pixCrc16(text.slice(0, -4));\n const crcValid = crc === expected;\n if (!crcValid && requireCrc) {\n throw new PixError(`CRC mismatch: payload says ${crc}, recomputed ${expected}.`);\n }\n\n const fields = parseTlv(text.slice(0, crcHeaderAt), \"payload\");\n if (fields[0]?.id !== TAG_PAYLOAD_FORMAT) {\n throw new PixError(\"Tag 00 (payload format indicator) must be the first tag of a BR Code.\");\n }\n if (fields.some((field) => field.id === TAG_CRC)) {\n throw new PixError(\n \"Tag 63 (CRC) must be the last tag of a BR Code; this payload carries another one before the end.\",\n );\n }\n const merchantAccount = pick(fields, TAG_MERCHANT_ACCOUNT_INFO);\n if (merchantAccount === undefined) {\n throw new PixError(\"Payload has no tag 26 (merchant account information).\");\n }\n const account = parseTlv(merchantAccount, \"tag 26\");\n const gui = pick(account, MAI_TAG_GUI);\n if (gui?.toLowerCase() !== PIX_GUI) {\n throw new PixError(\n `Tag 26 is not a Pix account: expected GUI ${PIX_GUI}, got ${JSON.stringify(gui)}.`,\n );\n }\n\n const url = pick(account, MAI_TAG_URL);\n const key = pick(account, MAI_TAG_KEY);\n if (url !== undefined && key !== undefined) {\n throw new PixError(\n \"Tag 26 carries both a key (01) and a URL (25); a BR Code is either static or dynamic, not both.\",\n );\n }\n const amountField = pick(fields, TAG_TRANSACTION_AMOUNT);\n const txid = pick(\n parseTlv(pick(fields, TAG_ADDITIONAL_DATA) ?? \"\", \"tag 62\"),\n ADDITIONAL_TAG_TXID,\n );\n\n return {\n kind: url === undefined ? \"static\" : \"dynamic\",\n ...(key === undefined ? {} : { key, keyType: pixKeyType(key) ?? undefined }),\n ...(url === undefined ? {} : { url }),\n merchantName: pick(fields, TAG_MERCHANT_NAME) ?? \"\",\n merchantCity: pick(fields, TAG_MERCHANT_CITY) ?? \"\",\n ...(amountField === undefined ? {} : { amount: readAmountField(amountField) }),\n currency: pick(fields, TAG_TRANSACTION_CURRENCY) ?? \"\",\n countryCode: pick(fields, TAG_COUNTRY_CODE) ?? \"\",\n merchantCategoryCode: pick(fields, TAG_MERCHANT_CATEGORY_CODE) ?? \"\",\n ...(txid === undefined ? {} : { txid }),\n ...(pick(account, MAI_TAG_DESCRIPTION) === undefined\n ? {}\n : { description: pick(account, MAI_TAG_DESCRIPTION) }),\n ...(pick(fields, TAG_POSTAL_CODE) === undefined\n ? {}\n : { postalCode: pick(fields, TAG_POSTAL_CODE) }),\n oneTime: pick(fields, TAG_POINT_OF_INITIATION) === POINT_OF_INITIATION_SINGLE_USE,\n crc,\n crcValid,\n fields,\n };\n}\n"],"mappings":"8CAeA,IAAa,EAAb,cAA8B,KAAM,CAChC,YAAY,EAAiB,CACzB,MAAM,CAAO,EACb,KAAK,KAAO,UAChB,CACJ,EA8GM,EAAmB,KAGnB,EAAgB,MAGhB,EAAa,MAEb,EAAqB,KACrB,EAA0B,KAC1B,EAA4B,KAC5B,EAA6B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AK,EAAQ,CAAiB,GAAK,GACjD,aAAc,EAAK,EAAQ,CAAiB,GAAK,GACjD,GAAI,IAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQ,EAAgB,CAAW,CAAE,EAC5E,SAAU,EAAK,EAAQ,CAAwB,GAAK,GACpD,YAAa,EAAK,EAAQ,CAAgB,GAAK,GAC/C,qBAAsB,EAAK,EAAQ,CAA0B,GAAK,GAClE,GAAI,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,EACrC,GAAI,EAAK,EAAS,CAAmB,IAAM,IAAA,GACrC,CAAC,EACD,CAAE,YAAa,EAAK,EAAS,CAAmB,CAAE,EACxD,GAAI,EAAK,EAAQ,CAAe,IAAM,IAAA,GAChC,CAAC,EACD,CAAE,WAAY,EAAK,EAAQ,CAAe,CAAE,EAClD,QAAS,EAAK,EAAQ,CAAuB,IAAM,EACnD,MACA,WACA,QACJ,CACJ"}
|
package/dist/br/pix.js
CHANGED
|
@@ -4,8 +4,8 @@ var n = class extends Error {
|
|
|
4
4
|
constructor(e) {
|
|
5
5
|
super(e), this.name = "PixError";
|
|
6
6
|
}
|
|
7
|
-
}, r = 4129, i = 65535, a = 65535, o = "00", s = "01", c = "26", l = "52", u = "53", d = "54", f = "58", p = "59", m = "60", h = "61", g = "62", _ = "63", v = "00", y = "01", b = "02", x = "25", S = "05", C = "br.gov.bcb.pix", w = "01", T = "11", E = "12", D = "0000", O = "986", k = "BR", A = "***", j = 25, M = 15, N = 25, P = 99, F = 77;
|
|
8
|
-
function
|
|
7
|
+
}, r = 4129, i = 65535, a = 65535, o = "00", s = "01", c = "26", l = "52", u = "53", d = "54", f = "58", p = "59", m = "60", h = "61", g = "62", _ = "63", v = "00", y = "01", b = "02", x = "25", S = "05", C = "br.gov.bcb.pix", w = "01", T = "11", E = "12", D = "0000", O = "986", k = "BR", A = "***", j = 25, M = 15, N = 25, P = 99, F = 77, I = /^\d+(?:\.\d{0,2})?$/, L = 13;
|
|
8
|
+
function R(e) {
|
|
9
9
|
let t = new TextEncoder().encode(e), n = i;
|
|
10
10
|
for (let e of t) {
|
|
11
11
|
n ^= e << 8;
|
|
@@ -13,35 +13,37 @@ function I(e) {
|
|
|
13
13
|
}
|
|
14
14
|
return n.toString(16).toUpperCase().padStart(4, "0");
|
|
15
15
|
}
|
|
16
|
-
function
|
|
16
|
+
function z(e) {
|
|
17
17
|
return e.replace(/\D/g, "");
|
|
18
18
|
}
|
|
19
|
-
function
|
|
19
|
+
function B(e, t) {
|
|
20
20
|
let r = e.normalize("NFD").replace(/\p{Diacritic}/gu, "");
|
|
21
21
|
if (/[^\x20-\x7E]/.test(r)) throw new n(`${t} has characters the BR Code cannot carry: ${JSON.stringify(e)}. Use unaccented ASCII.`);
|
|
22
22
|
return r;
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
var V = /^[\x20-\x7E]*$/;
|
|
25
|
+
function H(e, t) {
|
|
26
|
+
if (!V.test(t)) throw new n(`Tag ${e} has characters outside the EMV common character set (printable ASCII): ${JSON.stringify(t)}.`);
|
|
25
27
|
if (t.length > P) throw new n(`Tag ${e} is ${t.length} characters; the EMV length field holds at most ${P}.`);
|
|
26
28
|
return `${e}${String(t.length).padStart(2, "0")}${t}`;
|
|
27
29
|
}
|
|
28
|
-
function
|
|
30
|
+
function U(n) {
|
|
29
31
|
let r = n.trim();
|
|
30
32
|
if (r === "") return null;
|
|
31
33
|
if (r.includes("@")) return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(r) && r.length <= F ? "email" : null;
|
|
32
34
|
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r)) return "evp";
|
|
33
|
-
let i =
|
|
35
|
+
let i = z(r);
|
|
34
36
|
return i.length === 14 ? e(i) ? "cnpj" : null : i.length === 11 && t(i) ? "cpf" : r.startsWith("+") ? /^\+55\d{10,11}$/.test(`+${i}`) ? "phone" : null : i.length === 10 || i.length === 11 || (i.length === 12 || i.length === 13) && i.startsWith("55") ? "phone" : null;
|
|
35
37
|
}
|
|
36
|
-
function
|
|
37
|
-
let t = e.trim(), r =
|
|
38
|
+
function W(e) {
|
|
39
|
+
let t = e.trim(), r = U(t);
|
|
38
40
|
if (r === null) throw new n(`Not a Pix key: ${JSON.stringify(e)}. Expected a CPF, CNPJ, e-mail, phone (+5511987654321) or EVP (UUID).`);
|
|
39
41
|
if (r === "email" || r === "evp") return {
|
|
40
42
|
type: r,
|
|
41
43
|
value: t.toLowerCase()
|
|
42
44
|
};
|
|
43
45
|
if (r === "phone") {
|
|
44
|
-
let e =
|
|
46
|
+
let e = z(t);
|
|
45
47
|
return {
|
|
46
48
|
type: r,
|
|
47
49
|
value: `+55${e.length > 11 ? e.slice(2) : e}`
|
|
@@ -49,100 +51,111 @@ function V(e) {
|
|
|
49
51
|
}
|
|
50
52
|
return {
|
|
51
53
|
type: r,
|
|
52
|
-
value:
|
|
54
|
+
value: z(t)
|
|
53
55
|
};
|
|
54
56
|
}
|
|
55
|
-
function
|
|
57
|
+
function G(e) {
|
|
56
58
|
if (!Number.isFinite(e)) throw new n(`Amount must be a finite number, got ${e}.`);
|
|
57
59
|
if (e <= 0) throw new n(`Amount must be positive, got ${e}. Omit \`amount\` for a QR whose value the payer types.`);
|
|
58
60
|
let t = e.toFixed(2);
|
|
61
|
+
if (Number(t) <= 0) throw new n(`Amount ${e} rounds to ${t} at two decimals. Omit \`amount\` for a QR whose value the payer types.`);
|
|
59
62
|
if (t.length > 13) throw new n(`Amount ${t} does not fit tag 54, which holds 13 characters.`);
|
|
60
63
|
return t;
|
|
61
64
|
}
|
|
62
|
-
function
|
|
63
|
-
let i =
|
|
65
|
+
function K(e, t, r) {
|
|
66
|
+
let i = B(e.trim(), r);
|
|
64
67
|
if (i === "") throw new n(`${r} is required.`);
|
|
65
68
|
if (i.length > t) throw new n(`${r} is ${i.length} characters; the BR Code allows ${t}. Shorten it — truncating here would silently change what the payer sees.`);
|
|
66
69
|
return i;
|
|
67
70
|
}
|
|
68
|
-
function
|
|
71
|
+
function q(e) {
|
|
69
72
|
let t = e?.trim() ?? "";
|
|
70
|
-
if (t === "" || t === A) return
|
|
73
|
+
if (t === "" || t === A) return H(g, H(S, A));
|
|
71
74
|
if (!RegExp(`^[A-Za-z0-9]{1,${N}}$`).test(t)) throw new n(`txid must be 1 to ${N} letters or digits, got ${JSON.stringify(e)}.`);
|
|
72
|
-
return
|
|
75
|
+
return H(g, H(S, t));
|
|
73
76
|
}
|
|
74
|
-
function
|
|
75
|
-
let { value: t } =
|
|
76
|
-
if (i !== void 0 && i !== "" && (r +=
|
|
77
|
-
return
|
|
77
|
+
function J(e) {
|
|
78
|
+
let { value: t } = W(e.key), r = H(v, C) + H(y, t), i = e.description?.trim();
|
|
79
|
+
if (i !== void 0 && i !== "" && (r += H(b, B(i, "description"))), r.length > P) throw new n(`Tag 26 is ${r.length} characters, over the ${P} the length field allows. Shorten \`description\`.`);
|
|
80
|
+
return H(c, r);
|
|
78
81
|
}
|
|
79
|
-
function
|
|
80
|
-
let t =
|
|
82
|
+
function Y(e) {
|
|
83
|
+
let t = B(e.url.trim(), "url").replace(/^https?:\/\//i, "");
|
|
81
84
|
if (t === "") throw new n("url is required for a dynamic BR Code.");
|
|
82
|
-
let r =
|
|
85
|
+
let r = H(v, C) + H(x, t);
|
|
83
86
|
if (r.length > P) throw new n(`Tag 26 is ${r.length} characters, over the ${P} the length field allows. Shorten the payload URL.`);
|
|
84
|
-
return
|
|
87
|
+
return H(c, r);
|
|
85
88
|
}
|
|
86
|
-
function
|
|
87
|
-
let t = e.kind === "dynamic", n = e.oneTime ?? t, r =
|
|
88
|
-
r +=
|
|
89
|
-
let i = e.postalCode === void 0 ? "" :
|
|
90
|
-
i !== "" && (r +=
|
|
89
|
+
function X(e) {
|
|
90
|
+
let t = e.kind === "dynamic", n = e.oneTime ?? t, r = H(o, w);
|
|
91
|
+
r += H(s, n ? E : T), r += t ? Y(e) : J(e), r += H(l, D), r += H(u, O), !t && e.amount !== void 0 && (r += H(d, G(e.amount))), r += H(f, k), r += H(p, K(e.merchantName, j, "merchantName")), r += H(m, K(e.merchantCity, M, "merchantCity"));
|
|
92
|
+
let i = e.postalCode === void 0 ? "" : z(e.postalCode);
|
|
93
|
+
i !== "" && (r += H(h, i)), r += q(t ? A : e.txid);
|
|
91
94
|
let a = `${r}${_}04`;
|
|
92
|
-
return `${a}${
|
|
93
|
-
}
|
|
94
|
-
function
|
|
95
|
-
let r = [],
|
|
96
|
-
for (;
|
|
97
|
-
let
|
|
98
|
-
if (!/^\d{2}$/.test(
|
|
99
|
-
let s = Number(o), c =
|
|
100
|
-
if (c + s >
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
95
|
+
return `${a}${R(a)}`;
|
|
96
|
+
}
|
|
97
|
+
function Z(e, t) {
|
|
98
|
+
let r = Array.from(e), i = [], a = 0;
|
|
99
|
+
for (; a < r.length;) {
|
|
100
|
+
let e = r.slice(a, a + 2).join(""), o = r.slice(a + 2, a + 4).join("");
|
|
101
|
+
if (!/^\d{2}$/.test(e) || !/^\d{2}$/.test(o)) throw new n(`Malformed TLV in ${t} at offset ${a}: expected a 2-digit tag and length.`);
|
|
102
|
+
let s = Number(o), c = a + 4;
|
|
103
|
+
if (c + s > r.length) throw new n(`Tag ${e} in ${t} declares ${s} characters but only ${r.length - c} remain.`);
|
|
104
|
+
if (i.some((t) => t.id === e)) throw new n(`Tag ${e} in ${t} appears more than once; a BR Code carries each tag once per level.`);
|
|
105
|
+
i.push({
|
|
106
|
+
id: e,
|
|
107
|
+
value: r.slice(c, c + s).join("")
|
|
108
|
+
}), a = c + s;
|
|
105
109
|
}
|
|
106
|
-
return
|
|
110
|
+
return i;
|
|
107
111
|
}
|
|
108
|
-
function
|
|
112
|
+
function Q(e, t) {
|
|
109
113
|
return e.find((e) => e.id === t)?.value;
|
|
110
114
|
}
|
|
111
|
-
function
|
|
115
|
+
function $(e) {
|
|
116
|
+
if (e.length > L || !I.test(e)) throw new n(`Tag 54 (amount) must be an amount like "25.50", with "." as the decimal mark, at most two decimals and ${L} characters; got ${JSON.stringify(e)}.`);
|
|
117
|
+
return Number(e);
|
|
118
|
+
}
|
|
119
|
+
function ee(e, t = {}) {
|
|
112
120
|
let { requireCrc: r = !0 } = t, i = e.trim();
|
|
113
121
|
if (i.length < 8) throw new n("Payload is too short to be a BR Code.");
|
|
114
122
|
let a = i.length - 8;
|
|
115
123
|
if (i.slice(a, a + 4) !== `${_}04`) throw new n("Payload does not end in a `6304` CRC tag.");
|
|
116
|
-
let
|
|
117
|
-
if (!
|
|
118
|
-
let
|
|
119
|
-
if (O
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
124
|
+
let w = i.slice(-4).toUpperCase(), T = R(i.slice(0, -4)), D = w === T;
|
|
125
|
+
if (!D && r) throw new n(`CRC mismatch: payload says ${w}, recomputed ${T}.`);
|
|
126
|
+
let O = Z(i.slice(0, a), "payload");
|
|
127
|
+
if (O[0]?.id !== o) throw new n("Tag 00 (payload format indicator) must be the first tag of a BR Code.");
|
|
128
|
+
if (O.some((e) => e.id === _)) throw new n("Tag 63 (CRC) must be the last tag of a BR Code; this payload carries another one before the end.");
|
|
129
|
+
let k = Q(O, c);
|
|
130
|
+
if (k === void 0) throw new n("Payload has no tag 26 (merchant account information).");
|
|
131
|
+
let A = Z(k, "tag 26"), j = Q(A, v);
|
|
132
|
+
if (j?.toLowerCase() !== C) throw new n(`Tag 26 is not a Pix account: expected GUI ${C}, got ${JSON.stringify(j)}.`);
|
|
133
|
+
let M = Q(A, x), N = Q(A, y);
|
|
134
|
+
if (M !== void 0 && N !== void 0) throw new n("Tag 26 carries both a key (01) and a URL (25); a BR Code is either static or dynamic, not both.");
|
|
135
|
+
let P = Q(O, d), F = Q(Z(Q(O, g) ?? "", "tag 62"), S);
|
|
123
136
|
return {
|
|
124
|
-
kind:
|
|
125
|
-
...
|
|
126
|
-
key:
|
|
127
|
-
keyType:
|
|
137
|
+
kind: M === void 0 ? "static" : "dynamic",
|
|
138
|
+
...N === void 0 ? {} : {
|
|
139
|
+
key: N,
|
|
140
|
+
keyType: U(N) ?? void 0
|
|
128
141
|
},
|
|
129
|
-
...
|
|
130
|
-
merchantName:
|
|
131
|
-
merchantCity:
|
|
132
|
-
...
|
|
133
|
-
currency:
|
|
134
|
-
countryCode:
|
|
135
|
-
merchantCategoryCode:
|
|
136
|
-
...
|
|
137
|
-
...
|
|
138
|
-
...
|
|
139
|
-
oneTime:
|
|
140
|
-
crc:
|
|
141
|
-
crcValid:
|
|
142
|
-
fields:
|
|
142
|
+
...M === void 0 ? {} : { url: M },
|
|
143
|
+
merchantName: Q(O, p) ?? "",
|
|
144
|
+
merchantCity: Q(O, m) ?? "",
|
|
145
|
+
...P === void 0 ? {} : { amount: $(P) },
|
|
146
|
+
currency: Q(O, u) ?? "",
|
|
147
|
+
countryCode: Q(O, f) ?? "",
|
|
148
|
+
merchantCategoryCode: Q(O, l) ?? "",
|
|
149
|
+
...F === void 0 ? {} : { txid: F },
|
|
150
|
+
...Q(A, b) === void 0 ? {} : { description: Q(A, b) },
|
|
151
|
+
...Q(O, h) === void 0 ? {} : { postalCode: Q(O, h) },
|
|
152
|
+
oneTime: Q(O, s) === E,
|
|
153
|
+
crc: w,
|
|
154
|
+
crcValid: D,
|
|
155
|
+
fields: O
|
|
143
156
|
};
|
|
144
157
|
}
|
|
145
158
|
//#endregion
|
|
146
|
-
export { n as PixError,
|
|
159
|
+
export { n as PixError, W as normalizePixKey, ee as parsePixPayload, R as pixCrc16, U as pixKeyType, X as pixPayload };
|
|
147
160
|
|
|
148
161
|
//# sourceMappingURL=pix.js.map
|
package/dist/br/pix.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pix.js","names":[],"sources":["../../src/br/pix.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines — EMV®QRCPS-MPM for Pix: the TLV writer, the\n * CRC16-CCITT, the field catalogue with its nesting, key-type detection and the\n * parser that has to accept what other banks emit. Reader and writer live together\n * because each one is the other's test — a payload this file builds is a payload it\n * must parse back.\n */\nimport { validateCNPJ, validateCPF } from \"@/forms/br-validators\";\n\n/**\n * A Pix payload could not be built or read.\n *\n * Its own class so a caller can tell \"the operator typed a bad key\" apart from a\n * bug, and so an `ErrorBoundary` can render a form error instead of a crash.\n */\nexport class PixError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PixError\";\n }\n}\n\n/** The five key formats DICT accepts. */\nexport type PixKeyType = \"cpf\" | \"cnpj\" | \"email\" | \"phone\" | \"evp\";\n\n/** A key after normalisation, ready to go into the payload. */\nexport interface NormalizedPixKey {\n type: PixKeyType;\n /** The exact string written into the BR Code. */\n value: string;\n}\n\n/** One TLV as it appeared in a payload, unknown tags included. */\nexport interface PixField {\n /** Two-character tag, e.g. `\"59\"`. */\n id: string;\n /** Raw value, still encoded when the tag is itself a template. */\n value: string;\n}\n\n/** A BR Code that carries the key — the one you print on a poster. */\nexport interface PixStaticInput {\n kind?: \"static\";\n /** CPF, CNPJ, e-mail, phone or EVP. Validated and normalised. */\n key: string;\n /** Payee name. Truncated by the spec at 25 characters — longer throws. */\n merchantName: string;\n /** Payee city. Truncated by the spec at 15 characters — longer throws. */\n merchantCity: string;\n /** Amount in BRL. Omit for a payer-chooses-the-value QR. */\n amount?: number;\n /** Reference the PSP echoes back, `[A-Za-z0-9]{1,25}`. Defaults to `\"***\"`. */\n txid?: string;\n /** Free text shown by some wallets. Goes into tag 26, sub-tag 02. */\n description?: string;\n /** CEP, digits only. Optional tag 61. */\n postalCode?: string;\n /** Single-use QR: sets tag 01 to `\"12\"` instead of `\"11\"`. */\n oneTime?: boolean;\n}\n\n/** A BR Code that carries a URL the wallet fetches to learn the amount. */\nexport interface PixDynamicInput {\n kind: \"dynamic\";\n /**\n * `payloadLocation` — the https URL the wallet GETs, **without** the scheme,\n * exactly as BACEN specifies (`pix.example.com/qr/v2/abc`).\n */\n url: string;\n merchantName: string;\n merchantCity: string;\n postalCode?: string;\n /** Single-use QR. Defaults to `true`, which is what a dynamic QR normally is. */\n oneTime?: boolean;\n}\n\n/** Everything `pixPayload` accepts. */\nexport type PixInput = PixStaticInput | PixDynamicInput;\n\n/** A payload taken apart again. */\nexport interface PixData {\n /** `\"dynamic\"` when tag 26 carried a URL instead of a key. */\n kind: \"static\" | \"dynamic\";\n /** Present on a static payload. */\n key?: string;\n keyType?: PixKeyType;\n /** Present on a dynamic payload. */\n url?: string;\n merchantName: string;\n merchantCity: string;\n /** Reais. `undefined` when the payer chooses the amount. */\n amount?: number;\n /** ISO 4217 numeric. `\"986\"` for BRL. */\n currency: string;\n countryCode: string;\n merchantCategoryCode: string;\n /** `\"***\"` on a reusable static QR that identifies no single transaction. */\n txid?: string;\n description?: string;\n postalCode?: string;\n /** Tag 01 read as `\"12\"`. */\n oneTime: boolean;\n /** The four hex characters that closed the payload. */\n crc: string;\n /** Whether those four characters match a recomputed CRC. */\n crcValid: boolean;\n /** Every top-level TLV, in payload order, unknown tags included. */\n fields: PixField[];\n}\n\n/** Options for {@link parsePixPayload}. */\nexport interface ParsePixOptions {\n /**\n * Throw when the checksum does not match. Default `true`.\n *\n * Turn it off only to inspect a payload you already know is broken: a BR Code\n * whose CRC fails has been corrupted in transit, and the account it now points\n * at is not the account the payee published.\n */\n requireCrc?: boolean;\n}\n\n/**\n * Generator polynomial of CRC-16/CCITT-FALSE, `x^16 + x^12 + x^5 + 1`.\n *\n * Taken from the CRC catalogue entry `CRC-16/IBM-3740` (alias CCITT-FALSE):\n * `width=16 poly=0x1021 init=0xffff refin=false refout=false xorout=0x0000\n * check=0x29b1`. The BACEN \"Manual de Padrões para Iniciação do Pix\" names this\n * exact variant for tag 63.\n */\nconst CRC16_POLYNOMIAL = 0x1021;\n\n/** Register preset of CRC-16/CCITT-FALSE. Not zero — that is a different variant. */\nconst CRC16_INITIAL = 0xffff;\n\n/** Keeps the shift register 16 bits wide. */\nconst CRC16_MASK = 0xffff;\n\nconst TAG_PAYLOAD_FORMAT = \"00\";\nconst TAG_POINT_OF_INITIATION = \"01\";\nconst TAG_MERCHANT_ACCOUNT_INFO = \"26\";\nconst TAG_MERCHANT_CATEGORY_CODE = \"52\";\nconst TAG_TRANSACTION_CURRENCY = \"53\";\nconst TAG_TRANSACTION_AMOUNT = \"54\";\nconst TAG_COUNTRY_CODE = \"58\";\nconst TAG_MERCHANT_NAME = \"59\";\nconst TAG_MERCHANT_CITY = \"60\";\nconst TAG_POSTAL_CODE = \"61\";\nconst TAG_ADDITIONAL_DATA = \"62\";\nconst TAG_CRC = \"63\";\n\nconst MAI_TAG_GUI = \"00\";\nconst MAI_TAG_KEY = \"01\";\nconst MAI_TAG_DESCRIPTION = \"02\";\nconst MAI_TAG_URL = \"25\";\nconst ADDITIONAL_TAG_TXID = \"05\";\n\n/** Globally Unique Identifier that marks tag 26 as a Pix account. */\nconst PIX_GUI = \"br.gov.bcb.pix\";\n\nconst PAYLOAD_FORMAT_VERSION = \"01\";\nconst POINT_OF_INITIATION_REUSABLE = \"11\";\nconst POINT_OF_INITIATION_SINGLE_USE = \"12\";\nconst DEFAULT_MERCHANT_CATEGORY_CODE = \"0000\";\nconst CURRENCY_BRL = \"986\";\nconst COUNTRY_BR = \"BR\";\nconst TXID_UNSPECIFIED = \"***\";\n\nconst MAX_MERCHANT_NAME = 25;\nconst MAX_MERCHANT_CITY = 15;\nconst MAX_TXID = 25;\nconst MAX_TLV_VALUE = 99;\nconst MAX_EMAIL_KEY = 77;\n\n/**\n * CRC-16/CCITT-FALSE of a string, as four upper-case hex characters.\n *\n * Bitwise rather than table-driven: 200-odd characters at 8 shifts each is\n * nothing, and a 256-entry table is 2 KB of payload every consumer of the `/br`\n * entry would carry.\n *\n * The input is taken as UTF-8 bytes. A Pix payload is ASCII by construction —\n * {@link pixPayload} rejects anything else — but the function is exported and a\n * caller may hand it arbitrary text, and hashing UTF-16 code units would then\n * disagree with every other implementation.\n *\n * @param input - Bytes to run through the register.\n * @returns Four upper-case hex characters, zero-padded.\n *\n * @example\n * pixCrc16(\"123456789\"); // \"29B1\" — the catalogue check value\n */\nexport function pixCrc16(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let crc = CRC16_INITIAL;\n for (const byte of bytes) {\n crc ^= byte << 8;\n for (let bit = 0; bit < 8; bit += 1) {\n crc =\n (crc & 0x8000) !== 0\n ? ((crc << 1) ^ CRC16_POLYNOMIAL) & CRC16_MASK\n : (crc << 1) & CRC16_MASK;\n }\n }\n return crc.toString(16).toUpperCase().padStart(4, \"0\");\n}\n\n/** Digits of a possibly masked value. */\nfunction digits(value: string): string {\n return value.replace(/\\D/g, \"\");\n}\n\n/**\n * Drop diacritics and reject whatever is left outside printable ASCII.\n *\n * The BR Code character set has no room for accents, and a wallet that meets one\n * either fails to parse the QR or shows mojibake. Stripping them is lossy but\n * legible (\"São Paulo\" → \"Sao Paulo\"), which beats both alternatives; anything\n * that is not a diacritic — an emoji, a CJK character — is a mistake the caller\n * has to see, so it throws.\n */\nfunction toPayloadText(value: string, field: string): string {\n const stripped = value.normalize(\"NFD\").replace(/\\p{Diacritic}/gu, \"\");\n if (/[^\\x20-\\x7E]/.test(stripped)) {\n throw new PixError(\n `${field} has characters the BR Code cannot carry: ${JSON.stringify(value)}. ` +\n \"Use unaccented ASCII.\",\n );\n }\n return stripped;\n}\n\n/** One `ID + 2-digit length + value` triple. */\nfunction tlv(id: string, value: string): string {\n if (value.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag ${id} is ${value.length} characters; the EMV length field holds at most ${MAX_TLV_VALUE}.`,\n );\n }\n return `${id}${String(value.length).padStart(2, \"0\")}${value}`;\n}\n\n/**\n * Classify a Pix key, or `null` when it matches no accepted format.\n *\n * !!! warning \"CPF and a national phone number are both eleven digits\"\n * `\"11987654321\"` is a valid mobile number and could be a CPF. The check\n * digits break the tie: an 11-digit string is a CPF when its DV validates and\n * a phone otherwise. Pass phone keys as `+5511987654321` to remove the guess\n * entirely.\n *\n * @param key - Raw key, masked or not.\n * @returns The key type, or `null`.\n */\nexport function pixKeyType(key: string): PixKeyType | null {\n const trimmed = key.trim();\n if (trimmed === \"\") return null;\n\n if (trimmed.includes(\"@\")) {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(trimmed) && trimmed.length <= MAX_EMAIL_KEY\n ? \"email\"\n : null;\n }\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {\n return \"evp\";\n }\n\n const numbers = digits(trimmed);\n if (numbers.length === 14) return validateCNPJ(numbers) ? \"cnpj\" : null;\n if (numbers.length === 11 && validateCPF(numbers)) return \"cpf\";\n if (trimmed.startsWith(\"+\")) {\n return /^\\+55\\d{10,11}$/.test(`+${numbers}`) ? \"phone\" : null;\n }\n if (numbers.length === 10 || numbers.length === 11) return \"phone\";\n if (numbers.length === 12 || numbers.length === 13) {\n return numbers.startsWith(\"55\") ? \"phone\" : null;\n }\n return null;\n}\n\n/**\n * Validate a Pix key and return the exact string to write into the payload.\n *\n * Normalisation per type: CPF and CNPJ lose their mask, a phone becomes E.164\n * with the `+55` country code, an EVP is lower-cased, and an e-mail is\n * lower-cased because DICT stores it that way — a key that differs only in case\n * would otherwise fail to resolve.\n *\n * All validation lives in {@link pixKeyType}; past that gate the normalisation is\n * total, which is why the phone branch strips a country code purely on length\n * rather than re-checking the shape.\n *\n * @param key - Raw key, masked or not.\n * @returns The type and the normalised value.\n * @throws {PixError} When the key matches no accepted format, or when a document\n * key fails its check digits.\n *\n * @example\n * normalizePixKey(\"123.456.789-09\"); // { type: \"cpf\", value: \"12345678909\" }\n * normalizePixKey(\"(11) 98765-4321\"); // { type: \"phone\", value: \"+5511987654321\" }\n */\nexport function normalizePixKey(key: string): NormalizedPixKey {\n const trimmed = key.trim();\n const type = pixKeyType(trimmed);\n if (type === null) {\n throw new PixError(\n `Not a Pix key: ${JSON.stringify(key)}. Expected a CPF, CNPJ, e-mail, ` +\n \"phone (+5511987654321) or EVP (UUID).\",\n );\n }\n\n if (type === \"email\") return { type, value: trimmed.toLowerCase() };\n if (type === \"evp\") return { type, value: trimmed.toLowerCase() };\n if (type === \"phone\") {\n const numbers = digits(trimmed);\n return { type, value: `+55${numbers.length > 11 ? numbers.slice(2) : numbers}` };\n }\n return { type, value: digits(trimmed) };\n}\n\n/** Format an amount the way tag 54 wants it: dot separator, two decimals. */\nfunction toAmountField(amount: number): string {\n if (!Number.isFinite(amount)) {\n throw new PixError(`Amount must be a finite number, got ${amount}.`);\n }\n if (amount <= 0) {\n throw new PixError(\n `Amount must be positive, got ${amount}. Omit \\`amount\\` for a QR whose value the payer types.`,\n );\n }\n const field = amount.toFixed(2);\n if (field.length > 13) {\n throw new PixError(`Amount ${field} does not fit tag 54, which holds 13 characters.`);\n }\n return field;\n}\n\n/** Bound the two free-text identity fields the spec caps hard. */\nfunction toBoundedText(value: string, max: number, field: string): string {\n const text = toPayloadText(value.trim(), field);\n if (text === \"\") throw new PixError(`${field} is required.`);\n if (text.length > max) {\n throw new PixError(\n `${field} is ${text.length} characters; the BR Code allows ${max}. Shorten it — ` +\n \"truncating here would silently change what the payer sees.\",\n );\n }\n return text;\n}\n\n/** Tag 62, which exists only to carry the txid. */\nfunction additionalDataField(txid: string | undefined): string {\n const value = txid?.trim() ?? \"\";\n if (value === \"\" || value === TXID_UNSPECIFIED) {\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, TXID_UNSPECIFIED));\n }\n if (!new RegExp(`^[A-Za-z0-9]{1,${MAX_TXID}}$`).test(value)) {\n throw new PixError(\n `txid must be 1 to ${MAX_TXID} letters or digits, got ${JSON.stringify(txid)}.`,\n );\n }\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, value));\n}\n\n/** Tag 26 for a static payload: GUI, key and the optional description. */\nfunction staticMerchantAccount(input: PixStaticInput): string {\n const { value } = normalizePixKey(input.key);\n let inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_KEY, value);\n const description = input.description?.trim();\n if (description !== undefined && description !== \"\") {\n inner += tlv(MAI_TAG_DESCRIPTION, toPayloadText(description, \"description\"));\n }\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten `description`.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/** Tag 26 for a dynamic payload: GUI plus the URL, and no key. */\nfunction dynamicMerchantAccount(input: PixDynamicInput): string {\n const url = toPayloadText(input.url.trim(), \"url\").replace(/^https?:\\/\\//i, \"\");\n if (url === \"\") throw new PixError(\"url is required for a dynamic BR Code.\");\n const inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_URL, url);\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten the payload URL.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/**\n * Build a Pix \"Copia e Cola\" payload — the string behind a Pix QR code.\n *\n * The format is EMVCo MPM: a flat list of `ID + 2-digit length + value` triples,\n * closed by tag 63 holding a CRC-16/CCITT-FALSE over **everything before it,\n * including the literal `6304` header of tag 63 itself**. That last detail is the\n * one implementations get wrong; see {@link pixCrc16}.\n *\n * Two shapes come out of here:\n *\n * - **static** — tag 26 carries the key, so the QR is self-contained and can be\n * printed. Amount optional; a txid of `\"***\"` means \"identifies no single\n * transaction\", which is what a reusable poster QR wants.\n * - **dynamic** — tag 26 carries a URL instead, and the wallet fetches the amount\n * and payee from the PSP. Use it when the value is per-order. Defaults to\n * single-use (tag 01 = `12`).\n *\n * The distinction matters and is not cosmetic: a static QR settles against\n * whatever the payer typed, a dynamic one against what the PSP served, so a\n * charge that must reconcile to a cent needs the dynamic form.\n *\n * @param input - Static or dynamic payload description.\n * @returns The full payload, CRC included, ready to render as a QR or to copy.\n * @throws {PixError} On an unrecognised key, a field over its length cap, a\n * non-positive amount, or text that is not representable in the BR Code.\n *\n * @example\n * pixPayload({\n * key: \"12345678909\",\n * merchantName: \"Loja Tempest\",\n * merchantCity: \"São Paulo\",\n * amount: 25.5,\n * txid: \"PEDIDO123\",\n * });\n */\nexport function pixPayload(input: PixInput): string {\n const dynamic = input.kind === \"dynamic\";\n const oneTime = input.oneTime ?? dynamic;\n\n let payload = tlv(TAG_PAYLOAD_FORMAT, PAYLOAD_FORMAT_VERSION);\n payload += tlv(\n TAG_POINT_OF_INITIATION,\n oneTime ? POINT_OF_INITIATION_SINGLE_USE : POINT_OF_INITIATION_REUSABLE,\n );\n payload += dynamic ? dynamicMerchantAccount(input) : staticMerchantAccount(input);\n payload += tlv(TAG_MERCHANT_CATEGORY_CODE, DEFAULT_MERCHANT_CATEGORY_CODE);\n payload += tlv(TAG_TRANSACTION_CURRENCY, CURRENCY_BRL);\n if (!dynamic && input.amount !== undefined) {\n payload += tlv(TAG_TRANSACTION_AMOUNT, toAmountField(input.amount));\n }\n payload += tlv(TAG_COUNTRY_CODE, COUNTRY_BR);\n payload += tlv(\n TAG_MERCHANT_NAME,\n toBoundedText(input.merchantName, MAX_MERCHANT_NAME, \"merchantName\"),\n );\n payload += tlv(\n TAG_MERCHANT_CITY,\n toBoundedText(input.merchantCity, MAX_MERCHANT_CITY, \"merchantCity\"),\n );\n const postalCode = input.postalCode === undefined ? \"\" : digits(input.postalCode);\n if (postalCode !== \"\") payload += tlv(TAG_POSTAL_CODE, postalCode);\n payload += additionalDataField(dynamic ? TXID_UNSPECIFIED : input.txid);\n\n const withCrcHeader = `${payload}${TAG_CRC}04`;\n return `${withCrcHeader}${pixCrc16(withCrcHeader)}`;\n}\n\n/**\n * Split a flat run of TLVs. Stops cleanly at the first malformed triple.\n *\n * @throws {PixError} When a length prefix is not two digits or runs past the end.\n */\nfunction parseTlv(input: string, where: string): PixField[] {\n const fields: PixField[] = [];\n let cursor = 0;\n while (cursor < input.length) {\n const id = input.slice(cursor, cursor + 2);\n const rawLength = input.slice(cursor + 2, cursor + 4);\n if (!/^\\d{2}$/.test(id) || !/^\\d{2}$/.test(rawLength)) {\n throw new PixError(\n `Malformed TLV in ${where} at offset ${cursor}: expected a 2-digit tag and length.`,\n );\n }\n const length = Number(rawLength);\n const start = cursor + 4;\n if (start + length > input.length) {\n throw new PixError(\n `Tag ${id} in ${where} declares ${length} characters but only ${input.length - start} remain.`,\n );\n }\n fields.push({ id, value: input.slice(start, start + length) });\n cursor = start + length;\n }\n return fields;\n}\n\n/** First value for a tag, or `undefined`. */\nfunction pick(fields: readonly PixField[], id: string): string | undefined {\n return fields.find((field) => field.id === id)?.value;\n}\n\n/**\n * Read a Pix \"Copia e Cola\" payload back into its parts.\n *\n * Tolerant by design: tags the SDK does not know about are kept verbatim in\n * {@link PixData.fields} instead of raising, because PSPs do add their own\n * templates and a reader that rejects them is useless in production. What is\n * *not* tolerated is a broken frame — a length prefix that runs off the end, a\n * missing tag 63 — or a checksum mismatch, which means the string was corrupted\n * and no longer names the account the payee published.\n *\n * @param payload - The copia-e-cola string. Surrounding whitespace is ignored.\n * @param options - See {@link ParsePixOptions}.\n * @returns The decoded payload.\n * @throws {PixError} On a malformed frame, a missing CRC tag, a tag 26 that is\n * not a Pix account, or — unless `requireCrc` is `false` — a CRC mismatch.\n *\n * @example\n * const data = parsePixPayload(copied);\n * console.log(data.key, data.amount, data.txid);\n */\nexport function parsePixPayload(payload: string, options: ParsePixOptions = {}): PixData {\n const { requireCrc = true } = options;\n const text = payload.trim();\n if (text.length < 8) throw new PixError(\"Payload is too short to be a BR Code.\");\n\n const crcHeaderAt = text.length - 8;\n if (text.slice(crcHeaderAt, crcHeaderAt + 4) !== `${TAG_CRC}04`) {\n throw new PixError(\"Payload does not end in a `6304` CRC tag.\");\n }\n const crc = text.slice(-4).toUpperCase();\n const expected = pixCrc16(text.slice(0, -4));\n const crcValid = crc === expected;\n if (!crcValid && requireCrc) {\n throw new PixError(`CRC mismatch: payload says ${crc}, recomputed ${expected}.`);\n }\n\n const fields = parseTlv(text.slice(0, crcHeaderAt), \"payload\");\n const merchantAccount = pick(fields, TAG_MERCHANT_ACCOUNT_INFO);\n if (merchantAccount === undefined) {\n throw new PixError(\"Payload has no tag 26 (merchant account information).\");\n }\n const account = parseTlv(merchantAccount, \"tag 26\");\n const gui = pick(account, MAI_TAG_GUI);\n if (gui?.toLowerCase() !== PIX_GUI) {\n throw new PixError(\n `Tag 26 is not a Pix account: expected GUI ${PIX_GUI}, got ${JSON.stringify(gui)}.`,\n );\n }\n\n const url = pick(account, MAI_TAG_URL);\n const key = pick(account, MAI_TAG_KEY);\n const amountField = pick(fields, TAG_TRANSACTION_AMOUNT);\n const txid = pick(\n parseTlv(pick(fields, TAG_ADDITIONAL_DATA) ?? \"\", \"tag 62\"),\n ADDITIONAL_TAG_TXID,\n );\n\n return {\n kind: url !== undefined && key === undefined ? \"dynamic\" : \"static\",\n ...(key === undefined ? {} : { key, keyType: pixKeyType(key) ?? undefined }),\n ...(url === undefined ? {} : { url }),\n merchantName: pick(fields, TAG_MERCHANT_NAME) ?? \"\",\n merchantCity: pick(fields, TAG_MERCHANT_CITY) ?? \"\",\n ...(amountField === undefined ? {} : { amount: Number(amountField) }),\n currency: pick(fields, TAG_TRANSACTION_CURRENCY) ?? \"\",\n countryCode: pick(fields, TAG_COUNTRY_CODE) ?? \"\",\n merchantCategoryCode: pick(fields, TAG_MERCHANT_CATEGORY_CODE) ?? \"\",\n ...(txid === undefined ? {} : { txid }),\n ...(pick(account, MAI_TAG_DESCRIPTION) === undefined\n ? {}\n : { description: pick(account, MAI_TAG_DESCRIPTION) }),\n ...(pick(fields, TAG_POSTAL_CODE) === undefined\n ? {}\n : { postalCode: pick(fields, TAG_POSTAL_CODE) }),\n oneTime: pick(fields, TAG_POINT_OF_INITIATION) === POINT_OF_INITIATION_SINGLE_USE,\n crc,\n crcValid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"sourcesContent":["/**\n * @tempest-limits file-lines — EMV®QRCPS-MPM for Pix: the TLV writer, the\n * CRC16-CCITT, the field catalogue with its nesting, key-type detection and the\n * parser that has to accept what other banks emit. Reader and writer live together\n * because each one is the other's test — a payload this file builds is a payload it\n * must parse back.\n */\nimport { validateCNPJ, validateCPF } from \"@/forms/br-validators\";\n\n/**\n * A Pix payload could not be built or read.\n *\n * Its own class so a caller can tell \"the operator typed a bad key\" apart from a\n * bug, and so an `ErrorBoundary` can render a form error instead of a crash.\n */\nexport class PixError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PixError\";\n }\n}\n\n/** The five key formats DICT accepts. */\nexport type PixKeyType = \"cpf\" | \"cnpj\" | \"email\" | \"phone\" | \"evp\";\n\n/** A key after normalisation, ready to go into the payload. */\nexport interface NormalizedPixKey {\n type: PixKeyType;\n /** The exact string written into the BR Code. */\n value: string;\n}\n\n/** One TLV as it appeared in a payload, unknown tags included. */\nexport interface PixField {\n /** Two-character tag, e.g. `\"59\"`. */\n id: string;\n /** Raw value, still encoded when the tag is itself a template. */\n value: string;\n}\n\n/** A BR Code that carries the key — the one you print on a poster. */\nexport interface PixStaticInput {\n kind?: \"static\";\n /** CPF, CNPJ, e-mail, phone or EVP. Validated and normalised. */\n key: string;\n /** Payee name. Truncated by the spec at 25 characters — longer throws. */\n merchantName: string;\n /** Payee city. Truncated by the spec at 15 characters — longer throws. */\n merchantCity: string;\n /** Amount in BRL. Omit for a payer-chooses-the-value QR. */\n amount?: number;\n /** Reference the PSP echoes back, `[A-Za-z0-9]{1,25}`. Defaults to `\"***\"`. */\n txid?: string;\n /** Free text shown by some wallets. Goes into tag 26, sub-tag 02. */\n description?: string;\n /** CEP, digits only. Optional tag 61. */\n postalCode?: string;\n /** Single-use QR: sets tag 01 to `\"12\"` instead of `\"11\"`. */\n oneTime?: boolean;\n}\n\n/** A BR Code that carries a URL the wallet fetches to learn the amount. */\nexport interface PixDynamicInput {\n kind: \"dynamic\";\n /**\n * `payloadLocation` — the https URL the wallet GETs, **without** the scheme,\n * exactly as BACEN specifies (`pix.example.com/qr/v2/abc`).\n */\n url: string;\n merchantName: string;\n merchantCity: string;\n postalCode?: string;\n /** Single-use QR. Defaults to `true`, which is what a dynamic QR normally is. */\n oneTime?: boolean;\n}\n\n/** Everything `pixPayload` accepts. */\nexport type PixInput = PixStaticInput | PixDynamicInput;\n\n/** A payload taken apart again. */\nexport interface PixData {\n /** `\"dynamic\"` when tag 26 carried a URL instead of a key. */\n kind: \"static\" | \"dynamic\";\n /** Present on a static payload. */\n key?: string;\n keyType?: PixKeyType;\n /** Present on a dynamic payload. */\n url?: string;\n merchantName: string;\n merchantCity: string;\n /** Reais. `undefined` when the payer chooses the amount. */\n amount?: number;\n /** ISO 4217 numeric. `\"986\"` for BRL. */\n currency: string;\n countryCode: string;\n merchantCategoryCode: string;\n /** `\"***\"` on a reusable static QR that identifies no single transaction. */\n txid?: string;\n description?: string;\n postalCode?: string;\n /** Tag 01 read as `\"12\"`. */\n oneTime: boolean;\n /** The four hex characters that closed the payload. */\n crc: string;\n /** Whether those four characters match a recomputed CRC. */\n crcValid: boolean;\n /** Every top-level TLV, in payload order, unknown tags included. */\n fields: PixField[];\n}\n\n/** Options for {@link parsePixPayload}. */\nexport interface ParsePixOptions {\n /**\n * Throw when the checksum does not match. Default `true`.\n *\n * Turn it off only to inspect a payload you already know is broken: a BR Code\n * whose CRC fails has been corrupted in transit, and the account it now points\n * at is not the account the payee published.\n */\n requireCrc?: boolean;\n}\n\n/**\n * Generator polynomial of CRC-16/CCITT-FALSE, `x^16 + x^12 + x^5 + 1`.\n *\n * Taken from the CRC catalogue entry `CRC-16/IBM-3740` (alias CCITT-FALSE):\n * `width=16 poly=0x1021 init=0xffff refin=false refout=false xorout=0x0000\n * check=0x29b1`. The BACEN \"Manual de Padrões para Iniciação do Pix\" names this\n * exact variant for tag 63.\n */\nconst CRC16_POLYNOMIAL = 0x1021;\n\n/** Register preset of CRC-16/CCITT-FALSE. Not zero — that is a different variant. */\nconst CRC16_INITIAL = 0xffff;\n\n/** Keeps the shift register 16 bits wide. */\nconst CRC16_MASK = 0xffff;\n\nconst TAG_PAYLOAD_FORMAT = \"00\";\nconst TAG_POINT_OF_INITIATION = \"01\";\nconst TAG_MERCHANT_ACCOUNT_INFO = \"26\";\nconst TAG_MERCHANT_CATEGORY_CODE = \"52\";\nconst TAG_TRANSACTION_CURRENCY = \"53\";\nconst TAG_TRANSACTION_AMOUNT = \"54\";\nconst TAG_COUNTRY_CODE = \"58\";\nconst TAG_MERCHANT_NAME = \"59\";\nconst TAG_MERCHANT_CITY = \"60\";\nconst TAG_POSTAL_CODE = \"61\";\nconst TAG_ADDITIONAL_DATA = \"62\";\nconst TAG_CRC = \"63\";\n\nconst MAI_TAG_GUI = \"00\";\nconst MAI_TAG_KEY = \"01\";\nconst MAI_TAG_DESCRIPTION = \"02\";\nconst MAI_TAG_URL = \"25\";\nconst ADDITIONAL_TAG_TXID = \"05\";\n\n/** Globally Unique Identifier that marks tag 26 as a Pix account. */\nconst PIX_GUI = \"br.gov.bcb.pix\";\n\nconst PAYLOAD_FORMAT_VERSION = \"01\";\nconst POINT_OF_INITIATION_REUSABLE = \"11\";\nconst POINT_OF_INITIATION_SINGLE_USE = \"12\";\nconst DEFAULT_MERCHANT_CATEGORY_CODE = \"0000\";\nconst CURRENCY_BRL = \"986\";\nconst COUNTRY_BR = \"BR\";\nconst TXID_UNSPECIFIED = \"***\";\n\nconst MAX_MERCHANT_NAME = 25;\nconst MAX_MERCHANT_CITY = 15;\nconst MAX_TXID = 25;\nconst MAX_TLV_VALUE = 99;\nconst MAX_EMAIL_KEY = 77;\n\n/**\n * Tag 54 as EMV® QRCPS-MPM writes it: digits, and at most one `.` as the decimal\n * mark, which \"may be present even if there are no decimals\" (`\"98.\"`). Up to two\n * decimals, the minor unit ISO 4217 gives BRL (`986`). No sign, exponent, comma,\n * hex prefix or whitespace — every one of which `Number()` would happily read.\n *\n * Zero (`\"0\"`, `\"0.00\"`) is accepted: EMV asks for a non-zero amount, but the BACEN\n * BR Code manual (v2, Table 1) gives `\"0\"` as an example value of tag 54, and the\n * parser reads payloads other PSPs emit — strict with what is malformed, tolerant\n * with what the Bacen spec accepts. The builder stays stricter: `pixPayload`\n * still refuses a non-positive amount, because it only writes what we choose to emit.\n */\nconst AMOUNT_FIELD = /^\\d+(?:\\.\\d{0,2})?$/;\n\n/** Width of tag 54: \"01..13\" in the BACEN BR Code manual, Table 1. */\nconst MAX_AMOUNT_FIELD = 13;\n\n/**\n * CRC-16/CCITT-FALSE of a string, as four upper-case hex characters.\n *\n * Bitwise rather than table-driven: 200-odd characters at 8 shifts each is\n * nothing, and a 256-entry table is 2 KB of payload every consumer of the `/br`\n * entry would carry.\n *\n * The input is taken as UTF-8 bytes. A Pix payload is ASCII by construction —\n * {@link pixPayload} rejects anything else — but the function is exported and a\n * caller may hand it arbitrary text, and hashing UTF-16 code units would then\n * disagree with every other implementation.\n *\n * @param input - Bytes to run through the register.\n * @returns Four upper-case hex characters, zero-padded.\n *\n * @example\n * pixCrc16(\"123456789\"); // \"29B1\" — the catalogue check value\n */\nexport function pixCrc16(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let crc = CRC16_INITIAL;\n for (const byte of bytes) {\n crc ^= byte << 8;\n for (let bit = 0; bit < 8; bit += 1) {\n crc =\n (crc & 0x8000) !== 0\n ? ((crc << 1) ^ CRC16_POLYNOMIAL) & CRC16_MASK\n : (crc << 1) & CRC16_MASK;\n }\n }\n return crc.toString(16).toUpperCase().padStart(4, \"0\");\n}\n\n/** Digits of a possibly masked value. */\nfunction digits(value: string): string {\n return value.replace(/\\D/g, \"\");\n}\n\n/**\n * Drop diacritics and reject whatever is left outside printable ASCII.\n *\n * The BR Code character set has no room for accents, and a wallet that meets one\n * either fails to parse the QR or shows mojibake. Stripping them is lossy but\n * legible (\"São Paulo\" → \"Sao Paulo\"), which beats both alternatives; anything\n * that is not a diacritic — an emoji, a CJK character — is a mistake the caller\n * has to see, so it throws.\n */\nfunction toPayloadText(value: string, field: string): string {\n const stripped = value.normalize(\"NFD\").replace(/\\p{Diacritic}/gu, \"\");\n if (/[^\\x20-\\x7E]/.test(stripped)) {\n throw new PixError(\n `${field} has characters the BR Code cannot carry: ${JSON.stringify(value)}. ` +\n \"Use unaccented ASCII.\",\n );\n }\n return stripped;\n}\n\n/**\n * The EMV \"Common Character Set\" that an `ans` (Alphanumeric Special) field may\n * carry: printable ASCII, `0x20`–`0x7E`. Every root field of a BR Code is `ans`,\n * and the BACEN BR Code manual (v2, May 2020) only widened it from alphanumeric —\n * \"The restriction that established that only alphanumeric characters could be\n * used has been removed\" — not past it. Only the alternate-language template\n * (tag 64) is `String` and may carry another character set, and the builder\n * never writes it.\n */\nconst COMMON_CHARACTER_SET = /^[\\x20-\\x7E]*$/;\n\n/**\n * One `ID + 2-digit length + value` triple.\n *\n * The length is \"the number of characters included in the [value] field\" (EMV\n * MPM, as restated by the HKMA Common QR Code Specification §2; the BACEN manual:\n * \"size specifies how many characters\"). Inside the common character set a\n * character is one UTF-16 unit and one UTF-8 byte, so `value.length` is exact —\n * which is why a value outside it throws instead of being measured.\n *\n * @throws {PixError} When the value leaves the common character set or exceeds\n * the two-digit length.\n */\nfunction tlv(id: string, value: string): string {\n if (!COMMON_CHARACTER_SET.test(value)) {\n throw new PixError(\n `Tag ${id} has characters outside the EMV common character set (printable ASCII): ` +\n `${JSON.stringify(value)}.`,\n );\n }\n if (value.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag ${id} is ${value.length} characters; the EMV length field holds at most ${MAX_TLV_VALUE}.`,\n );\n }\n return `${id}${String(value.length).padStart(2, \"0\")}${value}`;\n}\n\n/**\n * Classify a Pix key, or `null` when it matches no accepted format.\n *\n * !!! warning \"CPF and a national phone number are both eleven digits\"\n * `\"11987654321\"` is a valid mobile number and could be a CPF. The check\n * digits break the tie: an 11-digit string is a CPF when its DV validates and\n * a phone otherwise. Pass phone keys as `+5511987654321` to remove the guess\n * entirely.\n *\n * @param key - Raw key, masked or not.\n * @returns The key type, or `null`.\n */\nexport function pixKeyType(key: string): PixKeyType | null {\n const trimmed = key.trim();\n if (trimmed === \"\") return null;\n\n if (trimmed.includes(\"@\")) {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(trimmed) && trimmed.length <= MAX_EMAIL_KEY\n ? \"email\"\n : null;\n }\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {\n return \"evp\";\n }\n\n const numbers = digits(trimmed);\n if (numbers.length === 14) return validateCNPJ(numbers) ? \"cnpj\" : null;\n if (numbers.length === 11 && validateCPF(numbers)) return \"cpf\";\n if (trimmed.startsWith(\"+\")) {\n return /^\\+55\\d{10,11}$/.test(`+${numbers}`) ? \"phone\" : null;\n }\n if (numbers.length === 10 || numbers.length === 11) return \"phone\";\n if (numbers.length === 12 || numbers.length === 13) {\n return numbers.startsWith(\"55\") ? \"phone\" : null;\n }\n return null;\n}\n\n/**\n * Validate a Pix key and return the exact string to write into the payload.\n *\n * Normalisation per type: CPF and CNPJ lose their mask, a phone becomes E.164\n * with the `+55` country code, an EVP is lower-cased, and an e-mail is\n * lower-cased because DICT stores it that way — a key that differs only in case\n * would otherwise fail to resolve.\n *\n * All validation lives in {@link pixKeyType}; past that gate the normalisation is\n * total, which is why the phone branch strips a country code purely on length\n * rather than re-checking the shape.\n *\n * @param key - Raw key, masked or not.\n * @returns The type and the normalised value.\n * @throws {PixError} When the key matches no accepted format, or when a document\n * key fails its check digits.\n *\n * @example\n * normalizePixKey(\"123.456.789-09\"); // { type: \"cpf\", value: \"12345678909\" }\n * normalizePixKey(\"(11) 98765-4321\"); // { type: \"phone\", value: \"+5511987654321\" }\n */\nexport function normalizePixKey(key: string): NormalizedPixKey {\n const trimmed = key.trim();\n const type = pixKeyType(trimmed);\n if (type === null) {\n throw new PixError(\n `Not a Pix key: ${JSON.stringify(key)}. Expected a CPF, CNPJ, e-mail, ` +\n \"phone (+5511987654321) or EVP (UUID).\",\n );\n }\n\n if (type === \"email\") return { type, value: trimmed.toLowerCase() };\n if (type === \"evp\") return { type, value: trimmed.toLowerCase() };\n if (type === \"phone\") {\n const numbers = digits(trimmed);\n return { type, value: `+55${numbers.length > 11 ? numbers.slice(2) : numbers}` };\n }\n return { type, value: digits(trimmed) };\n}\n\n/**\n * Format an amount the way tag 54 wants it: dot separator, two decimals.\n *\n * Positivity is checked on the rounded field, not on the input: `0.004` is\n * positive and still writes `\"0.00\"`, a zero-value QR for a positive charge.\n */\nfunction toAmountField(amount: number): string {\n if (!Number.isFinite(amount)) {\n throw new PixError(`Amount must be a finite number, got ${amount}.`);\n }\n if (amount <= 0) {\n throw new PixError(\n `Amount must be positive, got ${amount}. Omit \\`amount\\` for a QR whose value the payer types.`,\n );\n }\n const field = amount.toFixed(2);\n if (Number(field) <= 0) {\n throw new PixError(\n `Amount ${amount} rounds to ${field} at two decimals. Omit \\`amount\\` for a QR whose value the payer types.`,\n );\n }\n if (field.length > 13) {\n throw new PixError(`Amount ${field} does not fit tag 54, which holds 13 characters.`);\n }\n return field;\n}\n\n/** Bound the two free-text identity fields the spec caps hard. */\nfunction toBoundedText(value: string, max: number, field: string): string {\n const text = toPayloadText(value.trim(), field);\n if (text === \"\") throw new PixError(`${field} is required.`);\n if (text.length > max) {\n throw new PixError(\n `${field} is ${text.length} characters; the BR Code allows ${max}. Shorten it — ` +\n \"truncating here would silently change what the payer sees.\",\n );\n }\n return text;\n}\n\n/** Tag 62, which exists only to carry the txid. */\nfunction additionalDataField(txid: string | undefined): string {\n const value = txid?.trim() ?? \"\";\n if (value === \"\" || value === TXID_UNSPECIFIED) {\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, TXID_UNSPECIFIED));\n }\n if (!new RegExp(`^[A-Za-z0-9]{1,${MAX_TXID}}$`).test(value)) {\n throw new PixError(\n `txid must be 1 to ${MAX_TXID} letters or digits, got ${JSON.stringify(txid)}.`,\n );\n }\n return tlv(TAG_ADDITIONAL_DATA, tlv(ADDITIONAL_TAG_TXID, value));\n}\n\n/** Tag 26 for a static payload: GUI, key and the optional description. */\nfunction staticMerchantAccount(input: PixStaticInput): string {\n const { value } = normalizePixKey(input.key);\n let inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_KEY, value);\n const description = input.description?.trim();\n if (description !== undefined && description !== \"\") {\n inner += tlv(MAI_TAG_DESCRIPTION, toPayloadText(description, \"description\"));\n }\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten `description`.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/** Tag 26 for a dynamic payload: GUI plus the URL, and no key. */\nfunction dynamicMerchantAccount(input: PixDynamicInput): string {\n const url = toPayloadText(input.url.trim(), \"url\").replace(/^https?:\\/\\//i, \"\");\n if (url === \"\") throw new PixError(\"url is required for a dynamic BR Code.\");\n const inner = tlv(MAI_TAG_GUI, PIX_GUI) + tlv(MAI_TAG_URL, url);\n if (inner.length > MAX_TLV_VALUE) {\n throw new PixError(\n `Tag 26 is ${inner.length} characters, over the ${MAX_TLV_VALUE} the length field allows. ` +\n \"Shorten the payload URL.\",\n );\n }\n return tlv(TAG_MERCHANT_ACCOUNT_INFO, inner);\n}\n\n/**\n * Build a Pix \"Copia e Cola\" payload — the string behind a Pix QR code.\n *\n * The format is EMVCo MPM: a flat list of `ID + 2-digit length + value` triples,\n * closed by tag 63 holding a CRC-16/CCITT-FALSE over **everything before it,\n * including the literal `6304` header of tag 63 itself**. That last detail is the\n * one implementations get wrong; see {@link pixCrc16}.\n *\n * Two shapes come out of here:\n *\n * - **static** — tag 26 carries the key, so the QR is self-contained and can be\n * printed. Amount optional; a txid of `\"***\"` means \"identifies no single\n * transaction\", which is what a reusable poster QR wants.\n * - **dynamic** — tag 26 carries a URL instead, and the wallet fetches the amount\n * and payee from the PSP. Use it when the value is per-order. Defaults to\n * single-use (tag 01 = `12`).\n *\n * The distinction matters and is not cosmetic: a static QR settles against\n * whatever the payer typed, a dynamic one against what the PSP served, so a\n * charge that must reconcile to a cent needs the dynamic form.\n *\n * @param input - Static or dynamic payload description.\n * @returns The full payload, CRC included, ready to render as a QR or to copy.\n * @throws {PixError} On an unrecognised key, a field over its length cap, a\n * non-positive amount, or text that is not representable in the BR Code.\n *\n * @example\n * pixPayload({\n * key: \"12345678909\",\n * merchantName: \"Loja Tempest\",\n * merchantCity: \"São Paulo\",\n * amount: 25.5,\n * txid: \"PEDIDO123\",\n * });\n */\nexport function pixPayload(input: PixInput): string {\n const dynamic = input.kind === \"dynamic\";\n const oneTime = input.oneTime ?? dynamic;\n\n let payload = tlv(TAG_PAYLOAD_FORMAT, PAYLOAD_FORMAT_VERSION);\n payload += tlv(\n TAG_POINT_OF_INITIATION,\n oneTime ? POINT_OF_INITIATION_SINGLE_USE : POINT_OF_INITIATION_REUSABLE,\n );\n payload += dynamic ? dynamicMerchantAccount(input) : staticMerchantAccount(input);\n payload += tlv(TAG_MERCHANT_CATEGORY_CODE, DEFAULT_MERCHANT_CATEGORY_CODE);\n payload += tlv(TAG_TRANSACTION_CURRENCY, CURRENCY_BRL);\n if (!dynamic && input.amount !== undefined) {\n payload += tlv(TAG_TRANSACTION_AMOUNT, toAmountField(input.amount));\n }\n payload += tlv(TAG_COUNTRY_CODE, COUNTRY_BR);\n payload += tlv(\n TAG_MERCHANT_NAME,\n toBoundedText(input.merchantName, MAX_MERCHANT_NAME, \"merchantName\"),\n );\n payload += tlv(\n TAG_MERCHANT_CITY,\n toBoundedText(input.merchantCity, MAX_MERCHANT_CITY, \"merchantCity\"),\n );\n const postalCode = input.postalCode === undefined ? \"\" : digits(input.postalCode);\n if (postalCode !== \"\") payload += tlv(TAG_POSTAL_CODE, postalCode);\n payload += additionalDataField(dynamic ? TXID_UNSPECIFIED : input.txid);\n\n const withCrcHeader = `${payload}${TAG_CRC}04`;\n return `${withCrcHeader}${pixCrc16(withCrcHeader)}`;\n}\n\n/**\n * Split a flat run of TLVs. Stops cleanly at the first malformed triple.\n *\n * An ID may appear once per level. The BACEN BR Code manual (v2, May 2020)\n * states it for the root — \"there are no duplicate IDs in the document's root,\n * according to\" EMV® QRCPS-MPM;\n * the same holds here inside tags 26 and 62, which no conforming emitter\n * repeats either. Keeping the first of two values would give the caller one\n * reading of the payload while a wallet that keeps the last pays another.\n *\n * Lengths count characters (code points), as EMV defines them — see {@link tlv}.\n * A payload from another PSP may carry a `String` template (tag 64, or an\n * unreserved one) with non-ASCII text, where counting UTF-16 units would split\n * a character and misread every tag after it.\n *\n * @throws {PixError} When a length prefix is not two digits, runs past the end,\n * or an ID repeats at this level.\n */\nfunction parseTlv(text: string, where: string): PixField[] {\n const input = Array.from(text);\n const fields: PixField[] = [];\n let cursor = 0;\n while (cursor < input.length) {\n const id = input.slice(cursor, cursor + 2).join(\"\");\n const rawLength = input.slice(cursor + 2, cursor + 4).join(\"\");\n if (!/^\\d{2}$/.test(id) || !/^\\d{2}$/.test(rawLength)) {\n throw new PixError(\n `Malformed TLV in ${where} at offset ${cursor}: expected a 2-digit tag and length.`,\n );\n }\n const length = Number(rawLength);\n const start = cursor + 4;\n if (start + length > input.length) {\n throw new PixError(\n `Tag ${id} in ${where} declares ${length} characters but only ${input.length - start} remain.`,\n );\n }\n if (fields.some((field) => field.id === id)) {\n throw new PixError(\n `Tag ${id} in ${where} appears more than once; a BR Code carries each tag once per level.`,\n );\n }\n fields.push({ id, value: input.slice(start, start + length).join(\"\") });\n cursor = start + length;\n }\n return fields;\n}\n\n/** The value of a tag — unique per level, see {@link parseTlv} — or `undefined`. */\nfunction pick(fields: readonly PixField[], id: string): string | undefined {\n return fields.find((field) => field.id === id)?.value;\n}\n\n/**\n * Read tag 54 into reais.\n *\n * @throws {PixError} When the field is outside the EMV format\n * ({@link AMOUNT_FIELD}) or wider than 13 characters. Zero is read as `0`; see\n * {@link AMOUNT_FIELD} for why the reader accepts what `pixPayload` refuses.\n */\nfunction readAmountField(field: string): number {\n if (field.length > MAX_AMOUNT_FIELD || !AMOUNT_FIELD.test(field)) {\n throw new PixError(\n `Tag 54 (amount) must be an amount like \"25.50\", with \".\" as the decimal mark, ` +\n `at most two decimals and ${MAX_AMOUNT_FIELD} characters; got ${JSON.stringify(field)}.`,\n );\n }\n return Number(field);\n}\n\n/**\n * Read a Pix \"Copia e Cola\" payload back into its parts.\n *\n * Tolerant by design: tags the SDK does not know about are kept verbatim in\n * {@link PixData.fields} instead of raising, because PSPs do add their own\n * templates and a reader that rejects them is useless in production. What is\n * *not* tolerated is a broken frame — a length prefix that runs off the end, a\n * missing tag 63 — a checksum mismatch, which means the string was corrupted in\n * transit, or a payload with two readings: a tag repeated at the root or inside\n * tags 26 and 62, a tag 63 anywhere but at the end, a tag 26 with both a key and\n * a URL, or a tag 54 outside the EMV amount format. A preview built from one\n * reading while the wallet pays the other is the failure those rules exist for.\n *\n * Position is checked where EMV® QRCPS-MPM — the reference the BACEN manual\n * defers to — fixes it: tag 00 is the first object and tag 63 the last; every\n * other root tag may appear in any order. Before #475 an inner `6304` + CRC\n * followed by `5405…` and a second `6304` + CRC parsed as a priced payload,\n * while the same text cut at the first CRC was a valid payload with no amount.\n *\n * The CRC detects corruption, not authorship: whoever crafts a payload\n * recomputes it, so a valid CRC says nothing about who published the account.\n *\n * @param payload - The copia-e-cola string. Surrounding whitespace is ignored.\n * @param options - See {@link ParsePixOptions}.\n * @returns The decoded payload.\n * @throws {PixError} On a malformed frame, a missing CRC tag, a tag 00 that is\n * not first or a tag 63 that is not last, a repeated tag, a\n * tag 26 that is not a Pix account or that carries both a key and a URL, an\n * amount outside the EMV format, or — unless `requireCrc` is `false` — a CRC\n * mismatch.\n *\n * @example\n * const data = parsePixPayload(copied);\n * console.log(data.key, data.amount, data.txid);\n */\nexport function parsePixPayload(payload: string, options: ParsePixOptions = {}): PixData {\n const { requireCrc = true } = options;\n const text = payload.trim();\n if (text.length < 8) throw new PixError(\"Payload is too short to be a BR Code.\");\n\n const crcHeaderAt = text.length - 8;\n if (text.slice(crcHeaderAt, crcHeaderAt + 4) !== `${TAG_CRC}04`) {\n throw new PixError(\"Payload does not end in a `6304` CRC tag.\");\n }\n const crc = text.slice(-4).toUpperCase();\n const expected = pixCrc16(text.slice(0, -4));\n const crcValid = crc === expected;\n if (!crcValid && requireCrc) {\n throw new PixError(`CRC mismatch: payload says ${crc}, recomputed ${expected}.`);\n }\n\n const fields = parseTlv(text.slice(0, crcHeaderAt), \"payload\");\n if (fields[0]?.id !== TAG_PAYLOAD_FORMAT) {\n throw new PixError(\"Tag 00 (payload format indicator) must be the first tag of a BR Code.\");\n }\n if (fields.some((field) => field.id === TAG_CRC)) {\n throw new PixError(\n \"Tag 63 (CRC) must be the last tag of a BR Code; this payload carries another one before the end.\",\n );\n }\n const merchantAccount = pick(fields, TAG_MERCHANT_ACCOUNT_INFO);\n if (merchantAccount === undefined) {\n throw new PixError(\"Payload has no tag 26 (merchant account information).\");\n }\n const account = parseTlv(merchantAccount, \"tag 26\");\n const gui = pick(account, MAI_TAG_GUI);\n if (gui?.toLowerCase() !== PIX_GUI) {\n throw new PixError(\n `Tag 26 is not a Pix account: expected GUI ${PIX_GUI}, got ${JSON.stringify(gui)}.`,\n );\n }\n\n const url = pick(account, MAI_TAG_URL);\n const key = pick(account, MAI_TAG_KEY);\n if (url !== undefined && key !== undefined) {\n throw new PixError(\n \"Tag 26 carries both a key (01) and a URL (25); a BR Code is either static or dynamic, not both.\",\n );\n }\n const amountField = pick(fields, TAG_TRANSACTION_AMOUNT);\n const txid = pick(\n parseTlv(pick(fields, TAG_ADDITIONAL_DATA) ?? \"\", \"tag 62\"),\n ADDITIONAL_TAG_TXID,\n );\n\n return {\n kind: url === undefined ? \"static\" : \"dynamic\",\n ...(key === undefined ? {} : { key, keyType: pixKeyType(key) ?? undefined }),\n ...(url === undefined ? {} : { url }),\n merchantName: pick(fields, TAG_MERCHANT_NAME) ?? \"\",\n merchantCity: pick(fields, TAG_MERCHANT_CITY) ?? \"\",\n ...(amountField === undefined ? {} : { amount: readAmountField(amountField) }),\n currency: pick(fields, TAG_TRANSACTION_CURRENCY) ?? \"\",\n countryCode: pick(fields, TAG_COUNTRY_CODE) ?? \"\",\n merchantCategoryCode: pick(fields, TAG_MERCHANT_CATEGORY_CODE) ?? \"\",\n ...(txid === undefined ? {} : { txid }),\n ...(pick(account, MAI_TAG_DESCRIPTION) === undefined\n ? {}\n : { description: pick(account, MAI_TAG_DESCRIPTION) }),\n ...(pick(fields, TAG_POSTAL_CODE) === undefined\n ? {}\n : { postalCode: pick(fields, TAG_POSTAL_CODE) }),\n oneTime: pick(fields, TAG_POINT_OF_INITIATION) === POINT_OF_INITIATION_SINGLE_USE,\n crc,\n crcValid,\n fields,\n };\n}\n"],"mappings":";;AAeA,IAAa,IAAb,cAA8B,MAAM;CAChC,YAAY,GAAiB;EAEzB,AADA,MAAM,CAAO,GACb,KAAK,OAAO;CAChB;AACJ,GA8GM,IAAmB,MAGnB,IAAgB,OAGhB,IAAa,OAEb,IAAqB,MACrB,IAA0B,MAC1B,IAA4B,MAC5B,IAA6B,MAC7B,IAA2B,MAC3B,IAAyB,MACzB,IAAmB,MACnB,IAAoB,MACpB,IAAoB,MACpB,IAAkB,MAClB,IAAsB,MACtB,IAAU,MAEV,IAAc,MACd,IAAc,MACd,IAAsB,MACtB,IAAc,MACd,IAAsB,MAGtB,IAAU,kBAEV,IAAyB,MACzB,IAA+B,MAC/B,IAAiC,MACjC,IAAiC,QACjC,IAAe,OACf,IAAa,MACb,IAAmB,OAEnB,IAAoB,IACpB,IAAoB,IACpB,IAAW,IACX,IAAgB,IAChB,IAAgB,IAchB,IAAe,uBAGf,IAAmB;AAoBzB,SAAgB,EAAS,GAAuB;CAC5C,IAAM,IAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,GACxC,IAAM;CACV,KAAK,I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ACD,EAAE,YAAY,EAAK,GAAQ,CAAe,EAAE;EAClD,SAAS,EAAK,GAAQ,CAAuB,MAAM;EACnD;EACA;EACA;CACJ;AACJ"}
|
package/dist/br.d.ts
CHANGED
|
@@ -1173,14 +1173,29 @@ export declare interface ParsePixOptions {
|
|
|
1173
1173
|
* {@link PixData.fields} instead of raising, because PSPs do add their own
|
|
1174
1174
|
* templates and a reader that rejects them is useless in production. What is
|
|
1175
1175
|
* *not* tolerated is a broken frame — a length prefix that runs off the end, a
|
|
1176
|
-
* missing tag 63 —
|
|
1177
|
-
*
|
|
1176
|
+
* missing tag 63 — a checksum mismatch, which means the string was corrupted in
|
|
1177
|
+
* transit, or a payload with two readings: a tag repeated at the root or inside
|
|
1178
|
+
* tags 26 and 62, a tag 63 anywhere but at the end, a tag 26 with both a key and
|
|
1179
|
+
* a URL, or a tag 54 outside the EMV amount format. A preview built from one
|
|
1180
|
+
* reading while the wallet pays the other is the failure those rules exist for.
|
|
1181
|
+
*
|
|
1182
|
+
* Position is checked where EMV® QRCPS-MPM — the reference the BACEN manual
|
|
1183
|
+
* defers to — fixes it: tag 00 is the first object and tag 63 the last; every
|
|
1184
|
+
* other root tag may appear in any order. Before #475 an inner `6304` + CRC
|
|
1185
|
+
* followed by `5405…` and a second `6304` + CRC parsed as a priced payload,
|
|
1186
|
+
* while the same text cut at the first CRC was a valid payload with no amount.
|
|
1187
|
+
*
|
|
1188
|
+
* The CRC detects corruption, not authorship: whoever crafts a payload
|
|
1189
|
+
* recomputes it, so a valid CRC says nothing about who published the account.
|
|
1178
1190
|
*
|
|
1179
1191
|
* @param payload - The copia-e-cola string. Surrounding whitespace is ignored.
|
|
1180
1192
|
* @param options - See {@link ParsePixOptions}.
|
|
1181
1193
|
* @returns The decoded payload.
|
|
1182
|
-
* @throws {PixError} On a malformed frame, a missing CRC tag, a tag
|
|
1183
|
-
* not
|
|
1194
|
+
* @throws {PixError} On a malformed frame, a missing CRC tag, a tag 00 that is
|
|
1195
|
+
* not first or a tag 63 that is not last, a repeated tag, a
|
|
1196
|
+
* tag 26 that is not a Pix account or that carries both a key and a URL, an
|
|
1197
|
+
* amount outside the EMV format, or — unless `requireCrc` is `false` — a CRC
|
|
1198
|
+
* mismatch.
|
|
1184
1199
|
*
|
|
1185
1200
|
* @example
|
|
1186
1201
|
* const data = parsePixPayload(copied);
|