//#region src/format-cep/format-cep.d.ts /** Options of `formatCep`. */ type FormatCepOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a given value as a Brazilian postal code (CEP). * * @param {string|number} value - The value to be formatted, either as a string or a number. * @param {FormatCepOptions} [options] - Optional formatting options. * @param {boolean} options.pad - Whether to pad the value with leading zeros. * @returns {string} The formatted CEP string in the pattern "00000-000". * * @example * ```typescript * formatCep("01310930"); // "01310-930" * formatCep("1310930", { pad: true }); // "01310-930" * ``` * * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/tudo-sobre-cep * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/guia-de-enderecamento/guia-de-enderecamento */ export declare const formatCep: (value: string | number, options?: FormatCepOptions) => string; //#endregion //#region src/format-cnpj/format-cnpj.d.ts /** Options of `formatCnpj`. */ type FormatCnpjOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; /** Which CNPJ format to read: `1` numeric only, `2` alphanumeric (default: `1`). */ version?: 1 | 2; /** Whether to hide the first 2 digits and the 2 check digits with `*` (default: `false`, read for truthiness like `pad`). */ obfuscate?: boolean; }; /** * Formats a given CNPJ (Cadastro Nacional da Pessoa Jurídica) value according to the specified options. * * @param {string|number} value - The CNPJ value to be formatted. It can be a string or a number. * @param {FormatCnpjOptions} [options] - Optional configuration for formatting the CNPJ. * @param {boolean} options.pad - If true, the value will be padded with leading zeros if necessary. * @param {1|2} options.version - The version of the CNPJ to be sanitized. * @param {boolean} options.obfuscate - If truthy, hides the first 2 digits and the 2 check * digits. Read for truthiness, the way `pad` is, so a non-boolean such as `1` obfuscates too. * @returns {string} The formatted CNPJ string in the pattern "00.000.000/0000-00". * * @example * ```typescript * formatCnpj("12345678000195"); // "12.345.678/0001-95" * formatCnpj(12345678000195); // "12.345.678/0001-95" * formatCnpj("12345678000195", { pad: true }); // "12.345.678/0001-95" * formatCnpj("12345678", { pad: true }); // "00.000.012/3456-78" * formatCnpj("q0SLFMBD7VX439", { version: 2 }); // "Q0.SLF.MBD/7VX4-39" * formatCnpj("12345678000195", { obfuscate: true }); // "**.345.678/0001-**" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cnpj * @see Official: https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/documentos-tecnicos/cnpj/manual-dv-cnpj.pdf * @see Official: https://www.gov.br/receitafederal/pt-br/acesso-a-informacao/acoes-e-programas/programas-e-atividades/cnpj-alfanumerico */ export declare const formatCnpj: (value: string | number, options?: FormatCnpjOptions) => string; //#endregion //#region src/format-cpf/format-cpf.d.ts /** Options of `formatCpf`. */ type FormatCpfOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; /** Whether to hide the first 3 digits and the 2 check digits with `*` (default: `false`, read for truthiness like `pad`). */ obfuscate?: boolean; }; /** * Formats a given CPF (Cadastro de Pessoas Físicas) value according to the Brazilian standard. * * @param {string|number} value - The CPF value to be formatted. It can be a string or a number. * @param {FormatCpfOptions} [options] - Optional formatting options. * @param {boolean} options.pad - If true, the value will be padded with leading zeros if necessary. * @param {boolean} options.obfuscate - If truthy, hides the first 3 digits and the 2 check * digits. Read for truthiness, the way `pad` is, so a non-boolean such as `1` obfuscates too. * @returns {string} The formatted CPF string in the pattern "000.000.000-00". * * @example * ```typescript * formatCpf("12345678909"); // "123.456.789-09" * formatCpf(12345678909); // "123.456.789-09" * formatCpf("123456789", { pad: true }); // "001.234.567-89" * formatCpf("12345678909", { obfuscate: true }); // "***.456.789-**" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/meu-cpf * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/cpf.py */ export declare const formatCpf: (value: string | number, options?: FormatCpfOptions) => string; //#endregion //#region src/generate-cnpj/generate-cnpj.d.ts /** * The parameters `generateCnpj` accepts, an alternative to passing the version positionally. */ type GenerateCnpjParams = { /** * The version of the CNPJ to be generated: `1` for the numeric CNPJ and `2` for the * alphanumeric one. Defaults to `1`, and any other runtime value also generates a version 1 * (numeric) CNPJ. */ version?: 1 | 2; /** * The "número de ordem" (filial) block, positions 9 to 12 of the CNPJ: an integer from 1 to * 9999, written zero padded to four characters (`3` becomes `"0003"`). Defaults to a random * block, and an integer outside that range, a fractional number or any other runtime value is * ignored, so a random block is used for those as well. The block stays numeric on the * alphanumeric version, which the IN RFB nº 2.229/2024 layout allows. */ branch?: number; }; /** * Generates a valid random CNPJ (Cadastro Nacional da Pessoa Jurídica). * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * The first argument is either the version, as it has always been, or a `GenerateCnpjParams` * object carrying that same version plus the "número de ordem" (filial) block to write in * positions 9 to 12. * * @param {1 | 2 | GenerateCnpjParams} [versionOrParams] - The version of the CNPJ to be * generated: `1` for the numeric CNPJ and `2` for the alphanumeric one, or an options object. * Defaults to `1`, and never throws: `null`, `undefined` and any other runtime value that is * neither `2` nor an object also generate a version 1 (numeric) CNPJ. * @param {1 | 2} [versionOrParams.version] - The version of the CNPJ to be generated, as above. * @param {number} [versionOrParams.branch] - The "número de ordem" (filial) block, an integer * from 1 to 9999 written zero padded to four characters. Defaults to a random block, and an * invalid branch is ignored rather than reported, so a random block is used for it too. * @returns {string} A valid 14-digit CNPJ string without formatting. * * @example * ```typescript * generateCnpj(); // "12345678000195" * generateCnpj(2); // "Q0SLFMBD7VX439" * generateCnpj({ version: 2 }); // "Q0SLFMBD7VX439" * generateCnpj({ branch: 3 }); // "12345678000372", the ordem block is "0003" * generateCnpj({ version: 2, branch: 1 }); // "Q0SLFMBD000148", the ordem block is "0001" * generateCnpj({ branch: 0 }); // "12345678472695", an out of range branch draws a random block * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cnpj * @see Official: https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/documentos-tecnicos/cnpj/manual-dv-cnpj.pdf * @see Official: https://www.gov.br/receitafederal/pt-br/acesso-a-informacao/acoes-e-programas/programas-e-atividades/cnpj-alfanumerico */ export declare const generateCnpj: (versionOrParams?: 1 | 2 | GenerateCnpjParams) => string; //#endregion //#region src/_internals/constants/states.d.ts /** * One Brazilian state, as returned by `getStates`, `getStateByIbgeCode` and the other state * utils. Every state is its own member of the union, so the fields of a state are tied to each * other: `Extract["name"]` is `"São Paulo"`, and narrowing a `State` by * `code` narrows its `name`, `regionCode`, `regionName` and `ibgeCode` too. An impossible * combination such as `{ code: "SP", name: "Acre" }` is not a `State`. * * Each member has the two letter code of the state (`code`, e.g. `"SP"`), its full name * (`name`, e.g. `"São Paulo"`), the code and the full name of the region it belongs to * (`regionCode` and `regionName`, e.g. `"SE"` and `"Sudeste"`) and the 2 digit IBGE code of the * Federative Unit (`ibgeCode`, the "cUF", e.g. `35`). */ type State = { readonly code: "AC"; readonly name: "Acre"; readonly regionCode: "N"; readonly regionName: "Norte"; readonly ibgeCode: 12; } | { readonly code: "AL"; readonly name: "Alagoas"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 27; } | { readonly code: "AP"; readonly name: "Amapá"; readonly regionCode: "N"; readonly regionName: "Norte"; readonly ibgeCode: 16; } | { readonly code: "AM"; readonly name: "Amazonas"; readonly regionCode: "N"; readonly regionName: "Norte"; readonly ibgeCode: 13; } | { readonly code: "BA"; readonly name: "Bahia"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 29; } | { readonly code: "CE"; readonly name: "Ceará"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 23; } | { readonly code: "DF"; readonly name: "Distrito Federal"; readonly regionCode: "CO"; readonly regionName: "Centro-Oeste"; readonly ibgeCode: 53; } | { readonly code: "ES"; readonly name: "Espírito Santo"; readonly regionCode: "SE"; readonly regionName: "Sudeste"; readonly ibgeCode: 32; } | { readonly code: "GO"; readonly name: "Goiás"; readonly regionCode: "CO"; readonly regionName: "Centro-Oeste"; readonly ibgeCode: 52; } | { readonly code: "MA"; readonly name: "Maranhão"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 21; } | { readonly code: "MT"; readonly name: "Mato Grosso"; readonly regionCode: "CO"; readonly regionName: "Centro-Oeste"; readonly ibgeCode: 51; } | { readonly code: "MS"; readonly name: "Mato Grosso do Sul"; readonly regionCode: "CO"; readonly regionName: "Centro-Oeste"; readonly ibgeCode: 50; } | { readonly code: "MG"; readonly name: "Minas Gerais"; readonly regionCode: "SE"; readonly regionName: "Sudeste"; readonly ibgeCode: 31; } | { readonly code: "PA"; readonly name: "Pará"; readonly regionCode: "N"; readonly regionName: "Norte"; readonly ibgeCode: 15; } | { readonly code: "PB"; readonly name: "Paraíba"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 25; } | { readonly code: "PR"; readonly name: "Paraná"; readonly regionCode: "S"; readonly regionName: "Sul"; readonly ibgeCode: 41; } | { readonly code: "PE"; readonly name: "Pernambuco"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 26; } | { readonly code: "PI"; readonly name: "Piauí"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 22; } | { readonly code: "RJ"; readonly name: "Rio de Janeiro"; readonly regionCode: "SE"; readonly regionName: "Sudeste"; readonly ibgeCode: 33; } | { readonly code: "RN"; readonly name: "Rio Grande do Norte"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 24; } | { readonly code: "RS"; readonly name: "Rio Grande do Sul"; readonly regionCode: "S"; readonly regionName: "Sul"; readonly ibgeCode: 43; } | { readonly code: "RO"; readonly name: "Rondônia"; readonly regionCode: "N"; readonly regionName: "Norte"; readonly ibgeCode: 11; } | { readonly code: "RR"; readonly name: "Roraima"; readonly regionCode: "N"; readonly regionName: "Norte"; readonly ibgeCode: 14; } | { readonly code: "SC"; readonly name: "Santa Catarina"; readonly regionCode: "S"; readonly regionName: "Sul"; readonly ibgeCode: 42; } | { readonly code: "SP"; readonly name: "São Paulo"; readonly regionCode: "SE"; readonly regionName: "Sudeste"; readonly ibgeCode: 35; } | { readonly code: "SE"; readonly name: "Sergipe"; readonly regionCode: "NE"; readonly regionName: "Nordeste"; readonly ibgeCode: 28; } | { readonly code: "TO"; readonly name: "Tocantins"; readonly regionCode: "N"; readonly regionName: "Norte"; readonly ibgeCode: 17; }; /** The two letter code of each Brazilian state, as published by the IBGE. */ type StateCode = State["code"]; /** The name of each Brazilian state, as published by the IBGE. */ type StateName = State["name"]; //#endregion //#region src/generate-cpf/generate-cpf.d.ts /** * Generates a valid random CPF (Cadastro de Pessoas Físicas). * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @param {StateCode} [state] - The Brazilian state code to generate a CPF for. An unknown state * draws a random região fiscal digit instead of throwing, a key of the prototype chain * (`"__proto__"`, `"constructor"`) and a value with no string conversion included. * @returns {string} A valid 11-digit CPF string without formatting. * * @example * ```typescript * generateCpf(); // "12345678909" * generateCpf("SP"); // "12345678810" (with the SP state code, 8, in the 9th digit) * ``` * * The região fiscal digit in the 9th position comes from the Receita Federal's folheto * "Cadastros: CPF e CNPJ"; the check digit rule (`REGRA_VALIDA_CPF`) is specified, with the * worked example `280012389-38`, in the Receita Federal's Manual de Preenchimento da * e-Financeira, Anexo II — Leiautes Gerais, approved by the Ato Declaratório Executivo Cofis * nº 10, de 19 de maio de 2026 (DOU de 25/05/2026). The manual's own file used to be served from * `sped.rfb.gov.br`, * a host that no longer answers at all, so the approving act is cited below in its place; its * Receita Federal permalink redirects into the norms viewer, which has to be opened in a * browser. * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/meu-cpf * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/educacao-fiscal/educacao_fiscal/folhetos-orientativos/cadastros-dig.pdf * @see Official: https://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=151372 * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/cpf.py */ export declare const generateCpf: (state?: StateCode) => string; //#endregion //#region src/is-valid-cep/is-valid-cep.d.ts /** * Validates if a CEP (Brazilian postal code) is valid. * * Spaces, dots and hyphens are ignored, so every punctuated form of a CEP is accepted, but * any other character, a letter in particular, makes the value invalid. * * @param {string|number} cep - The CEP value to be validated. * @returns {boolean} True if the CEP is valid, false otherwise. * * @example * ```typescript * isValidCep("01310100"); // true * isValidCep("01310-100"); // true * isValidCep("92.500-000"); // true * isValidCep(20040020); // true * isValidCep("abc01310100"); // false (invalid format) * isValidCep("12345"); // false (invalid length) * ``` * * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/tudo-sobre-cep * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/guia-de-enderecamento/guia-de-enderecamento */ export declare const isValidCep: (cep: string | number) => boolean; //#endregion //#region src/is-valid-cnpj/is-valid-cnpj.d.ts /** Options of `isValidCnpj`. */ type IsValidCnpjOptions = { /** Which CNPJ format to accept: `1` numeric only, `2` alphanumeric (default: `1`). */ version?: 1 | 2; }; /** * Validates if a CNPJ (Cadastro Nacional da Pessoa Jurídica) is valid. * Supports both numeric (version 1) and alphanumeric (version 2) CNPJ formats. * Accepts the usual mask characters (`.`, `-`, `/`) and whitespace around and between groups. * * @param {string} cnpj - The CNPJ value to be validated. * @param {IsValidCnpjOptions} [options] - Optional options. * @param {1|2} [options.version] - `1` validates the numeric-only format (the default), * `2` validates both the numeric and the alphanumeric formats. Any other value is read as `1`, * as `formatCnpj` and `parseCnpj` do. * @returns {boolean} True if the CNPJ is valid, false otherwise. * * @example * ```typescript * // Version 1 (numeric - default) * isValidCnpj("12.345.678/0001-95"); // true * isValidCnpj("12345678000195"); // true * isValidCnpj("12 345 678 0001 95"); // true (whitespace mask) * isValidCnpj("00000000000000"); // false (reserved number) * isValidCnpj("12345678000190"); // false (invalid checksum) * * // Version 2 (alphanumeric) * isValidCnpj("Q0.SLF.MBD/7VX4-39", { version: 2 }); // true (alphanumeric) * isValidCnpj("Q0SLFMBD7VX439", { version: 2 }); // true (alphanumeric) * isValidCnpj("q0slfmbd7vx439", { version: 2 }); // true (case-insensitive) * ``` * * Version 2 has no reserved-value list because the Receita Federal manual defines none for the * alphanumeric format, so a repeated-character alphanumeric base (e.g. all `A`s) that passes the * checksum is accepted, unlike the numeric reserved numbers rejected under version 1. * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cnpj * @see Official: https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/documentos-tecnicos/cnpj/manual-dv-cnpj.pdf * @see Official: https://www.gov.br/receitafederal/pt-br/acesso-a-informacao/acoes-e-programas/programas-e-atividades/cnpj-alfanumerico */ export declare const isValidCnpj: (cnpj: string, options?: IsValidCnpjOptions) => boolean; //#endregion //#region src/is-valid-cpf/is-valid-cpf.d.ts /** * Validates if a CPF (Cadastro de Pessoas Físicas) is valid. * Accepts the usual mask characters (`.`, `-`) and whitespace around and between groups. * * @param {string} cpf - The CPF value to be validated. * @returns {boolean} True if the CPF is valid, false otherwise. * * @example * ```typescript * isValidCpf("123.456.789-09"); // true * isValidCpf("12345678909"); // true * isValidCpf("123 456 789 09"); // true (whitespace mask) * isValidCpf(" 12345678909"); // true (leading whitespace) * isValidCpf("00000000000"); // false (reserved number) * isValidCpf("12345678900"); // false (invalid checksum) * ``` * * The check digit rule (`REGRA_VALIDA_CPF`) is specified, with the worked example * `280012389-38`, in the Receita Federal's Manual de Preenchimento da e-Financeira, Anexo II — * Leiautes Gerais, approved by the Ato Declaratório Executivo Cofis nº 10, de 19 de maio de * 2026 (DOU de 25/05/2026). The manual states the rule in its mirror form, weights 9 down to 1 "a partir da * unidade" with "o resto 10 é considerado 0", which is algebraically the same digit as the * weights 10 down to 2 with `11 - resto` implemented above. The manual's own file used to be * served from `sped.rfb.gov.br`, a host that no longer answers at all, so the approving act is * cited below in its place; its Receita Federal permalink redirects into the norms viewer, which * has to be opened in a browser. * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/meu-cpf * @see Official: https://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=151372 * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/cpf.py */ export declare const isValidCpf: (cpf: string) => boolean; //#endregion //#region src/is-valid-ie/is-valid-ie.d.ts /** The parameters `isValidIe` takes: the registration and the state whose rule it is checked against. */ type IsValidIeParams = { /** The inscrição estadual to validate. */ value: string; /** The two letter state code the registration belongs to, e.g. `"SP"`. Case insensitive. */ stateCode: StateCode; }; /** * Validates a Brazilian state tax registration number (IE). * * Per state notes, all of them deliberate and unchanged since 2.3.0: * - DF: the SINTEGRA page is published but empty, and no SEFAZ-DF roteiro is published either, * so DF follows the 13 digit AC rule under the prefix 07. * - GO: the SINTEGRA page is superseded by the SEFAZ-GO roteiro, which is the source of the * prefixes 10, 11 and 15, of the 10103105 to 10119997 range and of the dual digit * registration 11094402. * - RJ: the SINTEGRA page publishes only the modulus rule; the 8 digit length and the weights * 2, 7, 6, 5, 4, 3 and 2 come from the SINTEGRA validator itself, not from the page. * - SP: characters other than "P" and digits are rejected on purpose, a deliberate deviation * from the Regra Geral of the SINTEGRA page, which ignores them instead. * - AL: the tipo de empresa digit (third position) is not restricted to 0, 3, 5, 7 and 8. * - PE: only the current 9 digit eFisco format is accepted; the old 14 digit CACEPE format * documented on the same page is not. * - TO: the SINTEGRA page documents only the 11 digit form, the one carrying the tipo digits in * positions 3 and 4. The 9 digit form is also accepted, applying the same modulus 11 rule with * weights 9 down to 2 to the first eight digits; it is 2.3.0 behavior kept for compatibility * and no published SEFAZ-TO roteiro covers it. * - An all zero registration is accepted for every state whose published formula yields a * check digit of 0 for it (AM, BA with 8 or 9 digits, CE, ES, MG, MT, PB, PE, PI, PR, RJ, RS, * SC, SE, SP and TO with 9 digits), unlike isValidCpf and isValidCnpj, which reject repeated * digits. AM is on that list through the second branch of its published formula only: the * page's first branch, "Se Soma < 11 Então Dígito = 11 - Soma", gives 11 for an all zero * registration, while the "resto <= 1 ⇒ 0" branch, the one implemented here, gives 0. * * The state can also be passed first and the registration second, `isValidIe('SP', '110042490114')`, * the 2.3.0 form, which still works and is deprecated. The two forms are told apart by the first * argument: an object is the parameters of the current form, a string the state code of the * deprecated one, and anything else returns false. * * @param {IsValidIeParams} params - The registration to validate and the state to validate it against * @param {string} params.value - The state registration number to validate * @param {StateCode} params.stateCode - The state abbreviation (e.g., 'SP', 'RJ', 'MG') * @returns {boolean} True if the state registration number is valid, false otherwise * * @example * ```typescript * isValidIe({ value: '110042490114', stateCode: 'SP' }); // true * isValidIe({ value: 'P011004243002', stateCode: 'SP' }); // true * isValidIe({ value: '12345', stateCode: 'RJ' }); // false * isValidIe({ value: '109161793', stateCode: 'go' as StateCode }); // true (case-insensitive) * ``` * * @see Official: http://www.sintegra.gov.br/insc_est.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_AC.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_AL.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_AM.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_AP.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_BA.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_CE.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_DF.html * The page is published but empty: it carries no format, no weights and no worked example, * and no SEFAZ-DF roteiro is published either, so DF follows the 13 digit AC rule under the * prefix 07. * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_ES.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_GO.html * Superseded for Goiás by the SEFAZ-GO roteiro below: this page still gives the prefixes as * 10, 11 or 20 to 29 and knows nothing of the special ranges. * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_MA.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_MG.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_MS.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_MT.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_PA.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_PB.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_PE.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_PI.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_PR.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_RJ.html * Publishes only the modulus rule: the 8 digit length and the weights 2, 7, 6, 5, 4, 3 and 2 * come from the SINTEGRA validator itself, not from this page. * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_RN.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_RO.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_RR.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_RS.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_SC.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_SE.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_SP.html * @see Official: http://www.sintegra.gov.br/Cad_Estados/cad_TO.html * Documents only the 11 digit form, with the tipo digits 01, 02, 03 and 99 in positions 3 and 4; * the 9 digit form the validator also accepts is not covered by this page or by any other * published SEFAZ-TO roteiro. * @see Official: https://goias.gov.br/economia/roteiro-de-critica-da-inscricao-estadual-de-goias/ * SEFAZ-GO's roteiro de crítica, the source of the Goiás prefixes and special ranges. */ export declare function isValidIe(params: IsValidIeParams): boolean; /** * Validates a Brazilian state tax registration number (IE) with the state given first. See the * overload taking the parameters object for the full documentation. * * @param {StateCode} stateCode - The state abbreviation (e.g., 'SP', 'RJ', 'MG') * @param {string} ie - The state registration number to validate * @returns {boolean} True if the state registration number is valid, false otherwise * * @deprecated Use the object form, `isValidIe({ value, stateCode })`. */ export declare function isValidIe(stateCode: StateCode, ie: string): boolean; //#endregion //#region src/is-valid-pis/is-valid-pis.d.ts /** * Validates a Brazilian PIS (Programa de Integração Social) number. * Accepts the usual mask characters (`.`, `-`, `/`, `(`, `)`, `,`, `*`) and whitespace. * * @param {string} pis - The PIS number to validate. * @returns {boolean} True if the PIS number is valid, false otherwise. * * @example * ```typescript * isValidPis("120.56874.10-7"); // true * isValidPis("120/56874/10-7"); // true * isValidPis("12056874107"); // true * isValidPis("00000000000"); // false (reserved number) * ``` * * The eSocial MOS states the NIS must have 11 numeric digits including the check digit, and the * SIRC technical manual confirms the check digit is verified with módulo 11; neither publishes * the weight vector used below, which follows the community reference cited as `Based on:`. * * @see Official: https://www.gov.br/inss/pt-br/direitos-e-deveres/inscricao-e-contribuicao/inscricao * @see Official: https://www.gov.br/esocial/pt-br/documentacao-tecnica/manuais/mos-manual-de-orientacao-do-esocial-vs-2-4.pdf * @see Official: https://www.sirc.gov.br/wp-content/uploads/manual_sirc_recomendacoes_tecnicas_v7.pdf * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/pis.py */ export declare const isValidPis: (pis: string) => boolean; //#endregion //#region src/_internals/constants/banks.d.ts /** * Brazilian STR (Sistema de Transferência de Reservas) participants that have a compensation * code (commonly known as COMPE), published by Banco Central do Brasil. Generated by * `scripts/banks.ts`. * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv */ type Bank = { /** Compensation code (COMPE), 3 digits, zero-padded. */ code: string; /** Identificador do Sistema de Pagamentos Brasileiro (ISPB), 8 digits, zero-padded. */ ispb: string; /** Institution name, as published by Banco Central do Brasil. */ name: string; }; //#endregion //#region src/_internals/constants/cities.d.ts /** * Brazilian municipalities by state, published by the IBGE. `DATA` holds, for each state, a * `[name, ibgeCode]` tuple per municipality, sorted by name with `localeCompare` in the * "pt-BR" locale. Generated by `scripts/cities.ts`. * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ type Municipality = { /** The 7-digit IBGE municipality code. */ code: string; /** The municipality name. */ name: string; /** The two-letter code of the state the municipality belongs to. */ stateCode: StateCode; }; //#endregion //#region src/_internals/number-to-words/number-to-words.d.ts /** The grammatical gender `convertNumberToWords` agrees the number it writes out with. */ type NumberToWordsGender = "masculine" | "feminine"; //#endregion //#region src/is-business-day/is-business-day.d.ts /** * Options shared by every business day util (`isBusinessDay`, `addBusinessDays`, * `subBusinessDays` and `differenceInBusinessDays`): which holidays count as non-business days. */ type BusinessDayOptions = { /** Two letter state code whose state holidays are also treated as non-business days (default: national holidays only). */ stateCode?: StateCode; /** Whether optional-type holidays (`Holiday.type === "optional"`, e.g. Carnaval, Corpus Christi) count as non-business days (default: `true`). */ includeOptional?: boolean; }; /** * Checks whether a given date is a Brazilian business day (dia útil). * * A day is not a business day when it falls on Saturday or Sunday, or when it is a * Brazilian holiday returned by `getHolidays({ year, stateCode })` for `value`'s **local * calendar day** (its local year/month/day, as read by `Date#getFullYear`/`getMonth`/`getDate`), * the same convention used by `isHoliday`. Build `value` from local components * (`new Date(2024, 11, 25)`) rather than from a date-only ISO string when you mean a * specific local day, for the same reason documented in `isHoliday`. * * `options.includeOptional` defaults to `true`: holidays whose `Holiday.type` is * `"optional"` (Carnaval and Corpus Christi) are treated as non-business days even though * they are not statutory holidays. Pass `false` to only treat statutory (`"national"` and * `"state"`) holidays as non-business days. * * An invalid `options.stateCode` is treated in two different ways, depending on its type, the * same split `isHoliday` makes: * * - a string that is not a known state code is ignored, and only national holidays are * considered, the same behavior as `getHolidays`. The lookup is an own-property one, so a * prototype-chain key such as `"__proto__"` or `"constructor"` is an unknown state code like * any other; * - a `stateCode` that is present and is not a string at all (a number, `null`, an object) is * rejected rather than ignored: `isBusinessDay` returns `false` without looking at the date, * even when that date is an ordinary Tuesday. `undefined`, or an absent property, is the only * non-string value that stands for "no state" instead. `addBusinessDays`, `subBusinessDays` * and `differenceInBusinessDays` reject the same value with `null`. * * Two state rules change what `includeOptional: false` answers. The Distrito Federal declares * Corpus Christi a feriado (Lei distrital nº 72/1989, art. 1º parágrafo único), so with * `stateCode: "DF"` it is typed `"state"` and still counts; and Santa Catarina's two holidays * are observed on the following Sunday when they fall Monday to Friday (Lei SC nº 18.531/2022), * so 11 August 2025, a Monday, is a business day there. * * Only years from 1900 through 2099 are supported, the range `getHolidays` computes; a date * outside it returns `false` rather than silently treating every weekday as a business day. * * @param {Date} value - The date to check. * @param {BusinessDayOptions} [options] - Which holidays count as non-business days. * @param {StateCode} [options.stateCode] - Brazilian state code whose state holidays are also considered. * @param {boolean} [options.includeOptional] - Whether optional holidays count as non-business days (default: `true`). * @returns {boolean} True when `value` is a business day, false otherwise. Bad input also * returns false: a `value` that is not a valid `Date` (including non-`Date` values), a * `value` outside the supported 1900-2099 range, or a `stateCode` that is present and is not a * string. * * @example * ```typescript * isBusinessDay(new Date(2024, 0, 2)); // true (Tuesday, not a holiday) * isBusinessDay(new Date(2024, 0, 1)); // false (Ano novo) * isBusinessDay(new Date(2024, 0, 6)); // false (Saturday) * isBusinessDay(new Date(2024, 1, 13)); // false (Carnaval, optional holiday, counted by default) * isBusinessDay(new Date(2024, 1, 13), { includeOptional: false }); // true * isBusinessDay(new Date(2024, 6, 9), { stateCode: "SP" }); // false (Revolução Constitucionalista) * isBusinessDay(new Date(2024, 6, 9)); // true (state holiday ignored without stateCode) * isBusinessDay(new Date("not a date")); // false * isBusinessDay(new Date(2024, 6, 9), { stateCode: 5 }); // false (a non-string stateCode is rejected) * isBusinessDay(new Date(2100, 0, 4)); // false (a Monday, but 2100 is outside the supported range) * ``` * * The underlying holidays are the ones `getHolidays` computes; see its JSDoc (and * `src/get-holidays/constants.ts` for state holidays) for the full set of laws behind them. * * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l0662.htm * Lei 662/1949, the base national holidays law. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/2002/l10607.htm * Lei 10.607/2002, added Finados (2 November) and folded in Tiradentes (21 April), which had * been national since art. 3º of the Lei 1.266/1950 it revoked. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l6802.htm * Lei 6.802/1980, declared Nossa Senhora Aparecida a national holiday. * @see Official: https://www.planalto.gov.br/ccivil_03/_ato2023-2026/2023/lei/l14759.htm * Lei 14.759/2023, nationalized Dia da Consciência Negra from 2024. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l9093.htm * Lei 9.093/1995, the framework law authorizing state and municipal holidays. * @see Official: https://www.in.gov.br/web/dou/-/portaria-mgi-n-11.460-de-29-de-dezembro-de-2025-678388627 * Portaria MGI nº 11.460/2025, the federal executive's annual calendar of feriados nacionais and * pontos facultativos: the source of three of the four Easter-derived entries, namely * Sexta-feira Santa being observed nationally and Carnaval and Corpus Christi being ponto * facultativo, which is what `includeOptional` switches on. The fourth, Páscoa, has no entry in * the portaria; `getHolidays` derives Easter Sunday arithmetically with the Meeus/Jones/Butcher * algorithm, and it never affects this function because Easter is always a Sunday. */ export declare const isBusinessDay: (value: Date, options?: BusinessDayOptions) => boolean; //#endregion //#region src/add-business-days/add-business-days.d.ts /** * Adds a number of Brazilian business days (dias úteis) to a date. * * A business day is a day for which `isBusinessDay` returns `true` (not a Saturday, a * Sunday, or a Brazilian holiday), evaluated with the same `options`. The function walks one * calendar day at a time, in the direction of `amount`, counting only business days, so it is * exact regardless of the arrangement of holidays around `date` (cheap in practice: * `getHolidays` is memoized per year). * * `amount: 0` returns a **new `Date` equal to `date`, unchanged**, even when `date` itself * falls on a weekend or holiday. This mirrors the verified behavior of date-fns' * `addBusinessDays(date, 0)`, which also returns the input date as-is rather than rolling * it to the next business day; see `@see` below. A negative `amount` walks backwards, one * business day at a time, exactly like date-fns; `subBusinessDays` is the same walk spelled * positively. * * The time-of-day (hours, minutes, seconds, milliseconds) of `date` is preserved in the * result, and `date` itself is never mutated. * * If `options.stateCode` is provided but is not a valid/known state code, it is ignored and * only national holidays are considered (same behavior as `getHolidays`/`isBusinessDay`), so a * prototype-chain key such as `"__proto__"` is an unknown state code like any other. An * `options` that is not an object at all is ignored, exactly as `isBusinessDay` ignores it. * * Only years from 1900 through 2099 are supported, the range `getHolidays` computes. A `date` * outside it, or a walk that leaves it, returns `null`. * * @param {Date} date - The date to count from. Never mutated: a new `Date` is returned. * @param {number} amount - The number of business days to add; a negative value walks backwards. * @param {BusinessDayOptions} [options] - Which holidays count as non-business days. * @param {StateCode} [options.stateCode] - Brazilian state code whose state holidays are also considered. * @param {boolean} [options.includeOptional] - Whether optional holidays count as non-business days (default: `true`). * @returns {Date | null} A new `Date`, `amount` business days after `date`. `null` on bad * input: a `date` that is not a valid `Date` or is outside 1900-2099, an `amount` that is not a * finite integer, a `stateCode` that is not a string, or a walk that leaves the supported years. * * @example * ```typescript * addBusinessDays(new Date(2024, 0, 2, 12), 1); // Wed 2024-01-03, 12:00 (the next day is already a business day) * addBusinessDays(new Date(2024, 11, 31, 12), 1); // Thu 2025-01-02, 12:00 (Jan 1 is Ano novo, skipped) * addBusinessDays(new Date(2024, 0, 5, 12), -1); // Thu 2024-01-04, 12:00 (walks backwards) * addBusinessDays(new Date(2024, 0, 6, 12), 0); // Sat 2024-01-06, 12:00 (unchanged, even though Saturday is not a business day) * addBusinessDays(new Date(2024, 6, 8, 12), 1, { stateCode: "SP" }); // Wed 2024-07-10, 12:00 (Jul 9 is a state holiday in SP) * addBusinessDays(new Date("not a date"), 1); // null * addBusinessDays(new Date(2024, 0, 2), 1.5); // null (not an integer) * addBusinessDays(new Date(2099, 11, 31), 1); // null (the walk leaves the supported years) * addBusinessDays(null, 1); // null * ``` * * @see Based on: https://date-fns.org/docs/addBusinessDays * Reference behavior for `amount: 0`, * for the positional `(date, amount)` argument order and for walking backwards on a negative * `amount`. The underlying holiday determination's official sources are cited in * `isBusinessDay`/`getHolidays`. */ export declare const addBusinessDays: (date: Date, amount: number, options?: BusinessDayOptions) => Date | null; //#endregion //#region src/capitalize/capitalize.d.ts /** Options of `capitalize`. */ type CapitalizeOptions = { /** Words to keep in lower case when they are not the first word (default: the Portuguese prepositions). */ lowerCaseWords?: string[]; /** Words to keep in upper case wherever they appear (default: the Brazilian company designations, document abbreviations and roman numerals). */ upperCaseWords?: string[]; }; /** * Capitalizes a given string according to the way a Brazilian name, company name or address is * written, with no configuration needed: `"jose da silva"` becomes `"Jose da Silva"`, * `"empresa ltda"` becomes `"Empresa LTDA"` and `"santana/rs"` becomes `"Santana/RS"`. * * Words are separated by whitespace, by `-` and `/`, by the apostrophe (`"d'oeste"` becomes * `"d'Oeste"`) and by punctuation that touches a word (`"(empresa)"` becomes `"(Empresa)"`, * `"bairro:centro"` becomes `"Bairro:Centro"`), so `"MOGI-GUAÇU"` becomes `"Mogi-Guaçu"`. The * separators are kept where they are, while every run of whitespace (spaces, tabs, newlines) * collapses into a single space and the leading and trailing whitespace is dropped. The particles * of foreign-origin names (`del`, `della`, `di`, `du`, `van`, `von`, `der`, `den`) stay lower * case like the Portuguese prepositions, so `"luiz von schmidt"` becomes `"Luiz von Schmidt"`. * * - Words listed in `lowerCaseWords` are converted to lower case when they link two words, that * is, when they are neither the first word nor the last one and another word follows them * across whitespace, `-`, `/` or an apostrophe. The default list is the Portuguese * prepositions, articles and conjunctions that stay in lower case inside a proper name ("de", * "da", "do", "e", ...), so `"JOSÉ DA SILVA"` becomes `"José da Silva"`. A word of the list * that ends the value or is followed by punctuation is a designator instead, and keeps its * capital: `"rua a, 100"` becomes `"Rua A, 100"` and `"condomínio a, quadra d, lote o"` becomes * `"Condomínio A, Quadra D, Lote O"`. * - The elided particle `d'` is written in lower case wherever it appears, including as the first * word, but only when an apostrophe and a word follow it, so `"santa bárbara d'oeste"` becomes * `"Santa Bárbara d'Oeste"` and `"dias d'ávila"` becomes `"Dias d'Ávila"` while the designator * `"rua d"` becomes `"Rua D"`. A single letter written right after an apostrophe is the English * possessive and stays in lower case, so `"bob's"` becomes `"Bob's"`, not `"Bob'S"`. * - Words listed in `upperCaseWords` are converted to upper case wherever they appear. The * default list is the company designations and document abbreviations that are written in upper * case in Brazilian usage (`LTDA`, `S.A.`, `S/A`, `S.S.`, `S/S`, `ME`, `EPP`, `MEI`, `EIRELI`, * `CIA`, `SCP`, `CNPJ`, `CPF`, `RG`, `CEP`, `UF`) plus the roman numerals that appear in names * and addresses (`II` through `XXIII`, except `VI`, so `"joão paulo ii"` becomes * `"João Paulo II"` and `"rua xv de novembro"` becomes `"Rua XV de Novembro"`). `ME` is also * the pt-BR pronoun "me", so it is only upper cased in the designation position, as the last * word of the value (`"fulano comércio me"` becomes `"Fulano Comércio ME"`) or right before * another designation (`"fulano me epp"` becomes `"Fulano ME EPP"`); anywhere else it is an * ordinary word, so `"diga-me a verdade"` becomes `"Diga-Me a Verdade"` and the municipality * `"não-me-toque"` becomes `"Não-Me-Toque"`. A designation * written around a slash, `S/A` and `S/S`, is matched across that slash even though a slash * separates words, so `"casa de carnes s/a"` becomes `"Casa de Carnes S/A"`. * - A two letter word that follows a `/` is converted to upper case when it is the code of a * Brazilian state, the way a municipality and its Federative Unit are written together, so * `"porto alegre/rs"` becomes `"Porto Alegre/RS"` while `"santana/br"` becomes `"Santana/Br"`. * A state code that does not follow a `/` is left alone (`"santana rs"` becomes * `"Santana Rs"`), and so is any other two letter word. * - All other words are capitalized (first letter upper case, rest lower case). * * Both lists are compared ignoring the case of the words, and either one given in `options` * replaces its default list entirely, so `capitalize("empresa ltda", { upperCaseWords: [] })` * gives `"Empresa Ltda"`. A `lowerCaseWords`/`upperCaseWords` that is not an array falls back to * its default, and a member of either list that is not a string is ignored, so a malformed * option never throws. * * @param {string} value - The input string to be capitalized. * @param {CapitalizeOptions} [options] - Optional configuration for capitalization. * @param {string[]} [options.lowerCaseWords] - Array of words to keep in lower case (default: the Portuguese prepositions). * @param {string[]} [options.upperCaseWords] - Array of words to keep in upper case (default: the Brazilian company designations, document abbreviations and roman numerals). * @returns {string} The capitalized string according to the specified rules. * * The default `lowerCaseWords` list is the set of prepositions and conjunctions the Manual de * Redação da Presidência da República keeps in lower case inside a proper name, and the default * `upperCaseWords` list is sourced in `constants.ts` from the laws that create each designation. * * @see Official: https://www4.planalto.gov.br/centrodeestudos/assuntos/manual-de-redacao-da-presidencia-da-republica/manual-de-redacao.pdf * Manual de Redação da Presidência da República, 3ª edição (Portaria nº 1.369/2018), item 5.1.8 * b) and item 10.2 a). * @see Official: https://www4.planalto.gov.br/centrodeestudos/assuntos/manual-de-redacao-da-presidencia-da-republica * The Presidência page that publishes it. * * @example * ```typescript * capitalize("JOSÉ DA SILVA"); // "José da Silva" * capitalize("empresa ltda"); // "Empresa LTDA" * capitalize("banco do brasil s.a."); // "Banco do Brasil S.A." * capitalize("santa bárbara d'oeste"); // "Santa Bárbara d'Oeste" * capitalize("bob's"); // "Bob's" * capitalize("rua a, 100"); // "Rua A, 100" * capitalize("fulano comércio me"); // "Fulano Comércio ME" * capitalize("não-me-toque"); // "Não-Me-Toque" * capitalize("(empresa) ltda"); // "(Empresa) LTDA" * capitalize("luiz von schmidt"); // "Luiz von Schmidt" * capitalize("casa de carnes s/a"); // "Casa de Carnes S/A" * capitalize("MOGI-GUAÇU"); // "Mogi-Guaçu" * capitalize("santana/rs"); // "Santana/RS" * capitalize("rua xv de novembro"); // "Rua XV de Novembro" * capitalize("empresa ltda", { upperCaseWords: [] }); // "Empresa Ltda" * capitalize("joao\tsilva"); // "Joao Silva" * ``` */ export declare const capitalize: (value: string, options?: CapitalizeOptions) => string; //#endregion //#region src/convert-currency-to-words/convert-currency-to-words.d.ts /** * Formats a monetary amount in Brazilian Reais as its "por extenso" textual representation, * the style used to write out the amount by hand on cheques and contracts, e.g. `1523.45` * becomes `"mil quinhentos e vinte e três reais e quarenta e cinco centavos"`. * * `value` is truncated (not rounded) to 2 decimal places before conversion, matching * `brutils`' `convert_real_to_text`. The singular noun is used for exactly 1 ("um real", * "um centavo") and "de" is inserted before "reais" when the amount is a round million, * billion or trillion of reais ("um milhão de reais", "dois milhões de reais"). An amount that * truncates to nothing becomes `"zero reais"`, with no "menos" prefix even when `value` is * negative (`-0.001` is not a debt of anything); any other negative amount is prefixed with * "menos". `NaN`/non-finite values and amounts whose reais exceed `NUMBER_TO_WORDS_MAX_VALUE` * (999 trillion) return `""`. Above `Number.MAX_SAFE_INTEGER / 100` reais (about 90 trillion) a * double cannot carry cents at all, so the amount is read as a whole number of reais instead of * reporting cents that the input never held. * * The result is always lowercase; apply any other casing to it yourself. * * @param {number} value - The monetary amount to convert, in reais (e.g. `1523.45` for R$ 1.523,45). * @returns {string} The amount written out in Portuguese, or `""` for invalid input. * * @example * ```typescript * convertCurrencyToWords(1523.45); // "mil quinhentos e vinte e três reais e quarenta e cinco centavos" * convertCurrencyToWords(1); // "um real" * convertCurrencyToWords(0.01); // "um centavo" * convertCurrencyToWords(1000000); // "um milhão de reais" * convertCurrencyToWords(0); // "zero reais" * convertCurrencyToWords(-5.5); // "menos cinco reais e cinquenta centavos" * convertCurrencyToWords(-0.001); // "zero reais" * ``` * * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/currency.py */ export declare const convertCurrencyToWords: (value: number) => string; //#endregion //#region src/convert-date-to-words/convert-date-to-words.d.ts /** Options of `convertDateToWords`. */ type ConvertDateToWordsOptions = { /** Output style: `"full"` spells out the day, month and year (`"dois de março de dois mil e vinte e quatro"`); `"month"` spells out only the month name and leaves the day and year as digits (`"2 de março de 2024"`, day 1 as `"1º"`). Defaults to `"full"`; an invalid value is ignored and `"full"` is used instead. */ style?: "full" | "month"; /** Prefixes the pt-BR weekday name (lowercase) followed by a comma, e.g. `"sábado, dois de março de dois mil e vinte e quatro"`. The weekday is derived from the resolved calendar date (the `Date`'s local calendar date, or the parsed civil date for a string). Defaults to `false`. */ weekday?: boolean; }; /** * Formats a date as its Brazilian Portuguese "por extenso" textual representation, e.g. * `"01/01/2024"` becomes `"primeiro de janeiro de dois mil e vinte e quatro"`. * * `value` can be a `Date` (read by its **local calendar date**, i.e. `getFullYear`/`getMonth`/ * `getDate`, not its underlying UTC instant, the same convention used by `isHoliday`) or a * string in `"dd/mm/yyyy"` or ISO `"yyyy-mm-dd"` format, both parsed as plain calendar dates * with no timezone conversion. With the default `"full"` `options.style`, day 1 is written as * "primeiro" and every other day uses the cardinal number; with `"month"`, only the month name * is spelled out and the day/year are written as digits (day 1 as `"1º"`). Month names are * lowercase. In `"full"` style the year is written out as a cardinal number the way * `convertNumberToWords` writes it (`1999` reads as `"mil novecentos e noventa e nove"`), matching how a * date is read aloud. `options.weekday` prefixes the pt-BR weekday name (lowercase) followed by * a comma. The result is always lowercase; apply any other casing to it yourself. * February 29th is accepted on the leap years of the proleptic Gregorian calendar * (divisible by 4, except centuries that are not divisible by 400). Returns `""` when `value` is * not one of those forms, is an invalid `Date`, names a day/month that does not exist (e.g. * `"31/04/2024"` or `"29/02/2023"`), or falls before year 1, which has no year to write out. * * @param {Date|string} value - The date to convert: a `Date`, `"dd/mm/yyyy"` or ISO `"yyyy-mm-dd"`. * @param {ConvertDateToWordsOptions} [options] - Optional formatting options. * @param {"full"|"month"} [options.style] - Output style. Defaults to `"full"`. * @param {boolean} [options.weekday] - Prefixes the pt-BR weekday name and a comma. Defaults to `false`. * @returns {string} The date written out in Portuguese, or `""` for invalid input. * * @example * ```typescript * convertDateToWords("01/01/2024"); // "primeiro de janeiro de dois mil e vinte e quatro" * convertDateToWords("2024-01-02"); // "dois de janeiro de dois mil e vinte e quatro" * convertDateToWords(new Date(2024, 0, 1)); // "primeiro de janeiro de dois mil e vinte e quatro" * convertDateToWords("02/03/2024", { style: "month" }); // "2 de março de 2024" * convertDateToWords("01/01/2024", { style: "month" }); // "1º de janeiro de 2024" * convertDateToWords("02/03/2024", { weekday: true }); // "sábado, dois de março de dois mil e vinte e quatro" * convertDateToWords("10/05/1999"); // "dez de maio de mil novecentos e noventa e nove" * convertDateToWords("31/04/2024"); // "" (April has 30 days) * convertDateToWords("invalid"); // "" * ``` * * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/date_utils.py */ export declare const convertDateToWords: (value: Date | string, options?: ConvertDateToWordsOptions) => string; //#endregion //#region src/convert-license-plate-to-mercosul/convert-license-plate-to-mercosul.d.ts /** * Converts an old format Brazilian license plate ("LLLNNNN") to the Mercosul format * ("LLLNLNN"), following the official conversion table: the digit in the 5th position (the * 2nd digit of the 4 digit number) becomes a letter, `0` through `9` mapping to `A` through * `J`, and every other character is kept as is. * * @param {string} value - The old format license plate to be converted. * @returns {string} The converted Mercosul format plate, or `""` when `value` is not a valid * old format ("LLLNNNN") license plate. * * @example * ```typescript * convertLicensePlateToMercosul("ABC1234"); // "ABC1C34" * convertLicensePlateToMercosul("abc-1234"); // "ABC1C34" * convertLicensePlateToMercosul("ABC1D23"); // "" (already Mercosul) * convertLicensePlateToMercosul("invalid"); // "" * ``` * * Resolução CONTRAN nº 969/2022, art. 2º § 4º, is what requires the substitution of the second * numeric character, "conforme padrão previsto no Anexo II". Anexo II is the digit to letter * table, and it prints the same worked example as above: "A placa anterior ABC1234 será * substituída pela nova placa com o padrão alfanumérico ABC1C34". The annexes are published in a * PDF of their own, separate from the resolution's text; both are cited below. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022anexos.pdf */ export declare const convertLicensePlateToMercosul: (value: string) => string; //#endregion //#region src/convert-number-to-words/convert-number-to-words.d.ts /** Options of `convertNumberToWords`. */ type ConvertNumberToWordsOptions = { /** Grammatical gender used to agree "um/dois" and the hundreds group ("duzentos/duzentas", etc.) with the noun the number qualifies. Defaults to `"masculine"`. */ gender?: NumberToWordsGender; }; /** * Formats an integer as its Brazilian Portuguese cardinal number words ("por extenso"), * e.g. `1235` becomes `"mil duzentos e trinta e cinco"`. * * Only integers from `-999999999999999` to `999999999999999` (999 trillion in absolute value, * the highest value expressible with the "trilhão" scale word) are supported; anything outside * that range, `NaN` or a non-finite value (`Infinity`/`-Infinity`) returns `""`. A non-integer * `value` is truncated toward zero before conversion (`12.9` behaves like `12`); this function * only writes out whole numbers, it never spells out a decimal part (use * `convertCurrencyToWords` for a monetary amount with cents). * * The result is always lowercase; apply any other casing to it yourself. * * @param {number} value - The integer to convert. * @param {ConvertNumberToWordsOptions} [options] - Optional formatting options. * @param {NumberToWordsGender} [options.gender] - Grammatical gender for "um/dois" and the hundreds group. Defaults to `"masculine"`. * @returns {string} The cardinal number written out in Portuguese, or `""` for invalid input. * * @example * ```typescript * convertNumberToWords(123); // "cento e vinte e três" * convertNumberToWords(1001); // "mil e um" * convertNumberToWords(2000000); // "dois milhões" * convertNumberToWords(-42); // "menos quarenta e dois" * convertNumberToWords(2, { gender: "feminine" }); // "duas" * convertNumberToWords(12.9); // "doze" (truncated toward zero) * convertNumberToWords(NaN); // "" * ``` * * @see Based on: https://github.com/savoirfairelinux/num2words * `brutils` itself has no dedicated * number-to-words module (its `currency.py` delegates the Portuguese numeral text to this * library's `pt_BR` locale); this is the reference for the numeral-word tables reproduced here. */ export declare const convertNumberToWords: (value: number, options?: ConvertNumberToWordsOptions) => string; //#endregion //#region src/difference-in-business-days/difference-in-business-days.d.ts /** * Counts the number of Brazilian business days (dias úteis) between two dates. * * Mirrors the semantics of date-fns' `differenceInBusinessDays`, verified against its source * (`differenceInBusinessDays.js` in the `date-fns` package), argument order included: the walk * starts at `earlierDate` and stops just before `laterDate`, so **`earlierDate` is counted when * it is itself a business day and `laterDate` is never counted**, whatever their order, and every * business day strictly in between is counted once. Only the calendar day of each `Date` matters, * exactly like `differenceInCalendarDays`: the time of day is ignored. * * The result is positive when `laterDate` is after `earlierDate` and negative when it is before * it, the date-fns sign convention; two dates on the same calendar day return `0` (a positive * zero, never `-0`). * * A business day is a day for which `isBusinessDay` returns `true` (not a Saturday, a Sunday, * or a Brazilian holiday), evaluated with the same `options`. * * If `options.stateCode` is provided but is not a valid/known state code, it is ignored and only * national holidays are considered (same behavior as `getHolidays`/`isBusinessDay`), so a * prototype-chain key such as `"__proto__"` is an unknown state code like any other. An `options` * that is not an object at all is ignored, exactly as `isBusinessDay` ignores it. * * Only years from 1900 through 2099 are supported, the range `getHolidays` computes; a * `laterDate` or `earlierDate` outside it returns `null`. * * @param {Date} laterDate - The date to count to. Never counted itself, regardless of whether it is a business day. * @param {Date} earlierDate - The date to count from. Counted as a business day when it is one; never mutated. * @param {BusinessDayOptions} [options] - Which holidays count as non-business days. * @param {StateCode} [options.stateCode] - Brazilian state code whose state holidays are also considered. * @param {boolean} [options.includeOptional] - Whether optional holidays count as non-business days (default: `true`). * @returns {number | null} The number of business days between the two dates, or `null` on bad * input: a `laterDate`/`earlierDate` that is not a valid `Date` or is outside 1900-2099, or a * `stateCode` that is not a string. * * @example * ```typescript * differenceInBusinessDays(new Date(2024, 0, 2), new Date(2024, 0, 1)); // 0 (Jan 1 is Ano novo, not counted) * differenceInBusinessDays(new Date(2024, 0, 3), new Date(2024, 0, 2)); // 1 (Jan 2 counted, a Tuesday; Jan 3 is not) * differenceInBusinessDays(new Date(2024, 0, 2), new Date(2024, 0, 3)); // -1 (the later date comes first, so the count is negative) * differenceInBusinessDays(new Date(2024, 0, 2), new Date(2024, 0, 2)); // 0 (same day) * differenceInBusinessDays(new Date(2024, 6, 10), new Date(2024, 6, 8), { stateCode: "SP" }); // 1 (Jul 9 is a state holiday in SP) * differenceInBusinessDays(new Date(), new Date("not a date")); // null * differenceInBusinessDays(new Date(2100, 0, 5), new Date(2100, 0, 4)); // null (outside the supported years) * ``` * * @see Based on: https://date-fns.org/docs/differenceInBusinessDays * Documented behavior and the * positional `(laterDate, earlierDate)` argument order. * @see Based on: https://unpkg.com/date-fns@4.1.0/differenceInBusinessDays.js * Source used to * verify the exact boundary treatment (`earlierDate` counted, `laterDate` excluded) and the sign * convention. The underlying holiday determination's official sources are cited in * `isBusinessDay`/`getHolidays`. */ export declare const differenceInBusinessDays: (laterDate: Date, earlierDate: Date, options?: BusinessDayOptions) => number | null; //#endregion //#region src/format-boleto/format-boleto.d.ts /** Options of `formatBoleto`. */ type FormatBoletoOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a given value as a Brazilian boleto. * * A 48 digit linha digitável starting with `8` is an "arrecadação" (convênio/tributos) slip * and uses the FEBRABAN arrecadação mask (four blocks of 11 digits, each one followed by its * own check digit) instead of the "cobrança bancária" mask. The 44 digit arrecadação * *barcode* has no display grouping defined by FEBRABAN (§04 describes positions, not a * printed form), so it keeps the published "cobrança bancária" grouping. * * @param {string|number} value - The value to be formatted, either as a string or a number. * @param {FormatBoletoOptions} [options] - Optional formatting options. * @param {boolean} options.pad - Whether to pad the value with leading zeros. * @returns {string} The formatted boleto string in the pattern "00000.00000 00000.000000 00000.000000 0 00000000000000" or, for arrecadação, "00000000000-0 00000000000-0 00000000000-0 00000000000-0". * * @example * ```typescript * formatBoleto("10491443385511900000200000000141325230000093423"); * // "10491.44338 55119.000002 00000.000141 3 25230000093423" * * formatBoleto("826300000011098800100702024102024000000205104519"); * // "82630000001-1 09880010070-2 02410202400-0 00020510451-9" * ``` * * Carta-Circular BCB nº 2.926/2000 specifies the linha digitável fields and the módulo 11 * check digit (using 1 for remainders 0, 10 and 1) of the 47 digit cobrança bancária slip, * including the position of the fator de vencimento field. The FEBRABAN "Layout Padrão de * Arrecadação/Recebimento com Utilização do Código de Barras" and the FEBRABAN layout index * cover the arrecadação slip. * * @see Official: https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf * @see Official: https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf * @see Official: https://portal.febraban.org.br/pagina/3425/33/pt-br/layout-febraban */ export declare const formatBoleto: (value: string | number, options?: FormatBoletoOptions) => string; //#endregion //#region src/format-caepf/format-caepf.d.ts /** Options of `formatCaepf`. */ type FormatCaepfOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a CAEPF (Cadastro de Atividade Econômica da Pessoa Física) number according to the * official mask. * * Formats progressively, as far as the digits given go, so it can also be used as an input * mask while the user is still typing. * * @param {string|number} value - The CAEPF value to be formatted. * @param {FormatCaepfOptions} [options] - Optional formatting options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros up to 14 digits. * @returns {string} The formatted CAEPF string in the pattern "000.000.000/000-00", or an * empty string when there is nothing to format. * * @example * ```typescript * formatCaepf("29311861000184"); // "293.118.610/001-84" * formatCaepf(41142260000101); // "411.422.600/001-01" * formatCaepf("184", { pad: true }); // "000.000.000/001-84" * formatCaepf("184"); // "184" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/caepf * The registry's own page at the Receita Federal, which describes the cadastro but does not * print the mask; the mask below is the one the sources cited by `isValidCaepf` agree on. */ export declare const formatCaepf: (value: string | number, options?: FormatCaepfOptions) => string; //#endregion //#region src/format-cei/format-cei.d.ts /** Options of `formatCei`. */ type FormatCeiOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a CEI (Cadastro Específico do INSS) number according to the usual "00.000.00000/00" * mask, the one the reference implementations of the check digit agree on (the Receita Federal * does not print it). * * Formats progressively, as far as the digits given go, so it can also be used as an input * mask while the user is still typing. * * @param {string|number} value - The CEI value to be formatted. * @param {FormatCeiOptions} [options] - Optional formatting options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros up to 12 digits. * @returns {string} The formatted CEI string in the pattern "00.000.00000/00", or an empty * string when there is nothing to format. * * @example * ```typescript * formatCei("277297118187"); // "27.729.71181/87" * formatCei(249859674386); // "24.985.96743/86" * formatCei("249", { pad: true }); // "00.000.00002/49" * formatCei("249"); // "24.9" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno * The registry's own page at the Receita Federal, which describes the cadastro but does not * print the mask; the mask below is the one the two reference implementations of the check * digit cited by `isValidCei` agree on. */ export declare const formatCei: (value: string | number, options?: FormatCeiOptions) => string; //#endregion //#region src/format-certidao/format-certidao.d.ts /** Options of `formatCertidao`. */ type FormatCertidaoOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats the matrícula of a certidão de registro civil into the printed mask of the norm, the * 32 digits grouped as 6 2 2 4 1 5 3 7 2 and separated by spaces. * * A number is accepted and read as the string of its digits, like in `formatCpf`, but a full 32 * digit matrícula has to be a string: that many digits are more than a JavaScript number can hold * exactly. At runtime the value is read for its digits and masked as far as they go, like in every * formatter of this package, so a partial matrícula still being typed is masked progressively. * * @param {string|number} value - The matrícula value to be formatted. * @param {FormatCertidaoOptions} [options] - Optional formatting options. * @param {boolean} options.pad - If true, pads the value with leading zeros if necessary. * @returns {string} The formatted matrícula in the pattern "000000 00 00 0000 0 00000 000 0000000 00". * * @example * ```typescript * formatCertidao("10453901552013100012021000012321"); * // "104539 01 55 2013 1 00012 021 0000123 21" * * formatCertidao("104539.01.55.2013.1.00012.021.0000123-21"); * // "104539 01 55 2013 1 00012 021 0000123 21" * * formatCertidao("1552010100020112000012087", { pad: true }); * // "000000 01 55 2010 1 00020 112 0000120 87" * * formatCertidao(104539015520); // "104539 01 55 20" (a number is read as the string of its digits) * ``` * * @see Official: https://atos.cnj.jus.br/atos/detalhar/5243 * Código Nacional de Normas da Corregedoria Nacional de Justiça - Foro Extrajudicial (Provimento * CNJ nº 149/2023), art. 473 as currently published: the in-force layout of the 32 digit * matrícula. Inciso II and §§ 1º and 3º to 5º carry the redação of the Provimento CN nº 237, de * 13/07/2026; the rest of the article, § 2º included, and the digit layout this library depends * on, come from the Provimento CN nº 182, de 17/09/2024. * @see Official: https://atos.cnj.jus.br/atos/detalhar/1311 * Provimento CNJ nº 2, de 27/04/2009, art. 1º and 2º, which instituted the modelos únicos de * certidão and ordered that "as certidões passarão a consignar matrícula que identifica o código * nacional da serventia, o código do acervo, o tipo do serviço prestado, o tipo do livro, o número * do livro, o número da folha, o número do termo e o digito verificador" (revoked; historical). * @see Official: https://atos.cnj.jus.br/atos/detalhar/1310 * Provimento CNJ nº 3, de 17/11/2009, art. 7º, which is where that matrícula first got its digit * structure: "a matrícula, de inserção obrigatória nas certidões (primeira e demais vias) emitidas * pelos Cartórios de Registro Civil das Pessoas Naturais a partir de 1º de janeiro de 2010, é * formada pelos seguintes elementos", incisos I to IX fixing the same 6 + 2 + 2 + 4 + 1 + 5 + 3 + * 7 + 2 positions art. 473 carries today (revoked; historical). * @see Based on: http://ghiorzi.org/DVnew.htm * Worked example of the two check digits (sums 288 and 309). * @see Based on: https://github.com/klawdyo/validation-br/blob/feat-certidao/src/certidao.ts * Reference implementation, and the source of the matrículas used as test vectors. * @see Based on: https://github.com/geekcom/validator-docs/blob/master/src/validator-docs/Rules/Certidao.php * Third reference implementation agreeing on the weights and on the remainder of 10 read as 1. */ export declare const formatCertidao: (value: string | number, options?: FormatCertidaoOptions) => string; //#endregion //#region src/format-cnae/format-cnae.d.ts /** Options of `formatCnae`. */ type FormatCnaeOptions = { /** Whether to left pad the value with zeros up to the 7 digits of a complete subclass code (default: `false`). */ pad?: boolean; }; /** * Formats a CNAE (Classificação Nacional de Atividades Econômicas) subclass code. * * This is a purely structural transformation, it does not check the code against the * official table, use `isValidCnae` for that. * * With the default `pad: false` the mask is applied progressively, as far as the value goes, * which is what an input being typed into needs (`"62"` stays `"62"`, `"62015"` becomes * `"6201-5"`). With `pad: true` the value is first left padded with zeros to the 7 digits of a * complete subclass code, so it always comes back fully masked (`"62"` gives `"0000-0/62"`). * A number is treated exactly like the string of its digits: it is only padded under * `pad: true`, so `formatCnae(111301)` gives `"1113-0/1"` and `formatCnae(111301, { pad: true })` * gives `"0111-3/01"`. * * Like every formatter of this package, the value is read for its digits and masked as far as * they go: characters outside the mask are dropped (`formatCnae("abc6201501")` gives * `"6201-5/01"`) and a number is read as the string of its digits, sign and decimal point * included (`formatCnae(-6201501)` gives `"6201-5/01"`). This is the input-mask contract of * `formatCpf`; use `isValidCnae` to check a code. * * @param {string|number} value - The CNAE code to be formatted. * @param {FormatCnaeOptions} [options] - Optional formatting options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros. Defaults to `false`. * @returns {string} The formatted code in the `NNNN-N/NN` pattern, or an empty string * when there is nothing to format. * * @example * ```typescript * formatCnae("6201501"); // "6201-5/01" * formatCnae(6201501); // "6201-5/01" * formatCnae("62"); // "62" (partial values are masked as far as they go) * formatCnae("62015"); // "6201-5" * formatCnae("62", { pad: true }); // "0000-0/62" (padded to 7 digits first) * formatCnae("abc6201501"); // "6201-5/01" (only the digits are read) * formatCnae(-6201501); // "6201-5/01" * ``` * * @see Official: https://servicodados.ibge.gov.br/api/v2/cnae/subclasses */ export declare const formatCnae: (value: string | number, options?: FormatCnaeOptions) => string; //#endregion //#region src/format-cnh/format-cnh.d.ts /** Options of `formatCnh`. */ type FormatCnhOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a Brazilian CNH (Carteira Nacional de Habilitação) number. * * @param {string|number} value - The CNH number to be formatted. * @param {FormatCnhOptions} [options] - Optional options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros. * @returns {string} The formatted CNH, or an empty string when there is nothing to format. * * @example * ```typescript * formatCnh("12345678900"); // "123456789-00" * formatCnh("8900", { pad: true }); // "000000089-00" * ``` * * Resolução CONTRAN nº 886/2021, art. 4º I, defines the CNH registry number as 9 characters plus * 2 security check digits, which is the layout this mask reproduces; no official text publishes * the check-digit weights used to compute them. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/Resolucao8862021F.pdf */ export declare const formatCnh: (value: string | number, options?: FormatCnhOptions) => string; //#endregion //#region src/format-cno/format-cno.d.ts /** Options of `formatCno`. */ type FormatCnoOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a CNO (Cadastro Nacional de Obras) number according to the official mask. * * The CNO replaced the CEI for construction works and kept its numbering, so both share the * same 12 digit, "00.000.00000/00" mask. * * Formats progressively, as far as the digits given go, so it can also be used as an input * mask while the user is still typing. * * @param {string|number} value - The CNO value to be formatted. * @param {FormatCnoOptions} [options] - Optional formatting options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros up to 12 digits. * @returns {string} The formatted CNO string in the pattern "00.000.00000/00", or an empty * string when there is nothing to format. * * @example * ```typescript * formatCno("111130137368"); // "11.113.01373/68" * formatCno(401800097960); // "40.180.00979/60" * formatCno("979", { pad: true }); // "00.000.00009/79" * formatCno("979"); // "97.9" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno * The registry's own page at the Receita Federal, which describes the cadastro but does not * print the mask; the mask below is the one the two reference implementations of the check * digit cited by `isValidCei` agree on. */ export declare const formatCno: (value: string | number, options?: FormatCnoOptions) => string; //#endregion //#region src/format-cns/format-cns.d.ts /** Options of `formatCns`. */ type FormatCnsOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a CNS (Cartão Nacional de Saúde) number into the common display groups of 3-4-4-4 * digits separated by spaces. * * @param {string|number} value - The CNS value to be formatted. It can be a string or a number. * @param {FormatCnsOptions} [options] - Optional formatting options. * @param {boolean} options.pad - If true, pads the value with leading zeros if necessary. * @returns {string} The formatted CNS string in the pattern "000 0000 0000 0000". * * @example * ```typescript * formatCns("123456789010000"); // "123 4567 8901 0000" * formatCns(123456789010000); // "123 4567 8901 0000" * formatCns("89010001", { pad: true }); // "000 0000 8901 0001" * ``` * * @see Official: https://rni-docs.anvisa.gov.br/docs/regras_gerais/validacoes/validacaoCNS/ * ANVISA's two validation routines, the ones implemented here. The page sits behind a bot filter * and answers HTTP 403 to every non-browser client, so it has to be opened in a browser. * @see Based on: https://integracao.esusab.ufsc.br/ledi/documentacao/regras/algoritmo_CNS.html * e-SUS APS documentation of the same DATASUS algorithm, reachable without a browser. It applies * the provisional routine to numbers starting with 5, 7, 8 or 9; this implementation follows the * ANVISA page, which restricts it to 7, 8 and 9, so a 5 prefixed number is rejected even when its * weighted sum checks out. */ export declare const formatCns: (value: string | number, options?: FormatCnsOptions) => string; //#endregion //#region src/format-currency/format-currency.d.ts /** Options of `formatCurrency`. */ type FormatCurrencyOptions = { /** Whether to prefix the result with the "R$" currency symbol (default: `false`). */ symbol?: boolean; /** Number of decimal places to show. Defaults to 2, clamped to 0-20. */ precision?: number; }; /** * Formats a given value as a currency string in Brazilian Real (BRL). * * String inputs are read by the same rule as `parseCurrency`, except that a value written * without any separator stays in whole units: the last `,` or `.` followed by 1 to 2 digits * (or up to `precision` digits, when that is larger) is the decimal separator, every other * `,` or `.` is a thousands separator, and a `-` written before the first digit is preserved. * So `"1.234,56"` formats as `"1.234,56"`, `"-10.5"` as `"-10,50"` and `"1234"` as * `"1.234,00"`. * * A value that is not a finite number, such as `NaN`, `Infinity` or `-Infinity`, formats as * an empty string, and so does a value that cannot be coerced to a number at all, such as a * symbol, a null-prototype object or a plain object (`Number({})` is `NaN`); every other * value goes through `Number()` the way 2.3.0 did, so `null`, `[]` and `true` still format. * * The precision is clamped to `0-20`, the package limit, the bound Node 20 still enforces on * `Intl.NumberFormat` (ES2023 raised it to 100, and newer runtimes accept more), and a * precision that is not a finite number falls back to 2. * * @param {string|number} value - The value to be formatted. Can be a string or a number. * @param {FormatCurrencyOptions} [options] - Optional formatting options. * @param {boolean} options.symbol - If true, includes the currency symbol in the formatted string. * @param {number} options.precision - The number of decimal places to include in the formatted string. Defaults to 2, clamped to 0-20. * @returns {string} The formatted currency string, or an empty string when the value is not finite. * * The `R$` prefix and the comma before the centavos are the ones Lei nº 9.069/1995, art. 1º, * §§ 1º and 2º prescribes; the `.` grouping comes from the CLDR pt-BR locale data behind * `Intl.NumberFormat`. * * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l9069.htm * @see Based on: https://cldr.unicode.org/ * * @example * ```typescript * formatCurrency(1234.56); // "1.234,56" * formatCurrency(1234.56, { symbol: true }); // "R$ 1.234,56" * formatCurrency(-10.5); // "-10,50" * formatCurrency("1.234,56"); // "1.234,56" * formatCurrency("1234"); // "1.234,00" * formatCurrency(Number.NaN); // "" * ``` */ export declare const formatCurrency: (value: string | number, options?: FormatCurrencyOptions) => string; //#endregion //#region src/format-iban/format-iban.d.ts /** * Formats an IBAN in the ISO 13616 print grouping, blocks of 4 characters, the presentation * used on statements and bank forms. * * Does not validate the check digits or the field layout; formats whatever is given, up to * the 29 character length of a Brazilian IBAN, as far as it goes, so the function can also be * used as an input mask, and an IBAN of another country is grouped the same way up to that * length. Use `isValidIban` to check validity. * * The value may be compact (`"BR1500000000000010932840814P2"`), already in the ISO 13616 print * format, or a partial value still being typed. Like every formatter of this package, it is read * for its letters and digits and grouped as far as they go: any other character (a hyphen, a * dot, extra whitespace) is dropped and the letters are uppercased. Only a value that is not a * string gives an empty string. * * @param {string} value - The IBAN to be formatted. * @returns {string} The IBAN uppercased and grouped in blocks of 4 characters, or an empty * string when `value` is not a string. * * @example * ```typescript * formatIban("BR1500000000000010932840814P2"); // "BR15 0000 0000 0000 1093 2840 814P 2" * formatIban("br1500000000000010932840814p2"); // "BR15 0000 0000 0000 1093 2840 814P 2" * formatIban("BR15"); // "BR15" * formatIban("BR1500000000000010932840814P2EXTRA"); // "BR15 0000 0000 0000 1093 2840 814P 2" * formatIban("BR15 0000-0000.0000/1093 2840 814P-2"); // "BR15 0000 0000 0000 1093 2840 814P 2" * ``` * * @see Official: https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf * Circular BCB nº 3.625/2013 * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf * Diretrizes de Implementação do IBAN no Brasil */ export declare const formatIban: (value: string) => string; //#endregion //#region src/format-legal-nature/format-legal-nature.d.ts /** Options of `formatLegalNature`. */ type FormatLegalNatureOptions = { /** Whether to left pad the value with zeros up to the 4 digits of a complete code (default: `false`). */ pad?: boolean; }; /** * Formats a Brazilian legal nature (natureza jurídica) code. * * Like every formatter of this package, the value is read for its digits and masked as far as * they go (`"206"` stays `"206"`, `"2062"` becomes `"206-2"`); with `pad: true` it is first left * padded with zeros to the 4 digits of a complete code. Use `isValidLegalNature` to check a code. * * @param {string|number} value - The legal nature code to be formatted. * @param {FormatLegalNatureOptions} [options] - Optional formatting options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros. Defaults to `false`. * @returns {string} The formatted code, or an empty string when there is nothing to format. * * @example * ```typescript * formatLegalNature("2062"); // "206-2" * formatLegalNature(2062); // "206-2" * formatLegalNature("206"); // "206" (partial values are masked as far as they go) * formatLegalNature("62", { pad: true }); // "006-2" * ``` * * The CONCLA table page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser; the detailed structure PDF next to it is served * normally. * * @see Official: https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021 * @see Official: https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf */ export declare const formatLegalNature: (value: string | number, options?: FormatLegalNatureOptions) => string; //#endregion //#region src/format-license-plate/format-license-plate.d.ts /** * Formats a Brazilian license plate (placa de carro ou moto). * * Old format plates ("LLLNNNN") are hyphenated, while Mercosul plates ("LLLNLNN") are * returned without any separator. Partial values are formatted as far as they go, so the * function can be used as an input mask. * * @param {string} value - The license plate to be formatted. * @returns {string} The formatted license plate, or an empty string when the value cannot * start a valid license plate. * * @example * ```typescript * formatLicensePlate("abc1234"); // "ABC-1234" * formatLicensePlate("abc1d23"); // "ABC1D23" * formatLicensePlate("1234567"); // "" * ``` * * The `AAA-1111` shape of the old PNU is art. 2º § 3º of Resolução CONTRAN nº 969/2022; the * separatorless `LLLNLNN` shape of the Mercosul plate is item 1.2 of its Anexo I, published in a * PDF of its own. Both are cited below. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022anexos.pdf */ export declare const formatLicensePlate: (value: string) => string; //#endregion //#region src/format-ncm/format-ncm.d.ts /** Options of `formatNcm`. */ type FormatNcmOptions = { /** Whether to left pad the value with zeros up to the 8 digits of a complete NCM code (default: `false`). */ pad?: boolean; }; /** * Formats a NCM (Nomenclatura Comum do Mercosul) code. * * This is a purely structural transformation, it does not check the code against the * official table, use `isValidNcm` for that. * * With the default `pad: false` the mask is applied progressively, as far as the value goes, * which is what an input being typed into needs (`"8471"` stays `"8471"`, `"847130"` becomes * `"8471.30"`). With `pad: true` the value is first left padded with zeros to the 8 digits of a * complete code, so it always comes back fully masked (`"8471"` gives `"0000.84.71"`). * A number is treated exactly like the string of its digits: it is only padded under * `pad: true`, so `formatNcm(8471)` gives `"8471"` and `formatNcm(8471, { pad: true })` gives * `"0000.84.71"`. * * Like every formatter of this package, the value is read for its digits and masked as far as * they go: characters outside the mask are dropped (`formatNcm("abc8471")` gives * `"8471"`) and a number is read as the string of its digits, sign and decimal point * included (`formatNcm(-84713012)` gives `"8471.30.12"`). This is the input-mask contract of * `formatCpf`; use `isValidNcm` to check a code. * * @param {string|number} value - The NCM code to be formatted. * @param {FormatNcmOptions} [options] - Optional formatting options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros. Defaults to `false`. * @returns {string} The formatted code in the `NNNN.NN.NN` pattern, or an empty string * when there is nothing to format. * * @example * ```typescript * formatNcm("84713012"); // "8471.30.12" * formatNcm(84713012); // "8471.30.12" * formatNcm("8471"); // "8471" (partial values are masked as far as they go) * formatNcm("847130"); // "8471.30" * formatNcm("8471", { pad: true }); // "0000.84.71" (padded to 8 digits first) * formatNcm("abc8471"); // "8471" (only the digits are read) * formatNcm(-84713012); // "8471.30.12" * ``` * * @see Official: https://portalunico.siscomex.gov.br/classif/api/publico/nomenclatura/download/json */ export declare const formatNcm: (value: string | number, options?: FormatNcmOptions) => string; //#endregion //#region src/format-nfe-key/format-nfe-key.d.ts /** Options of `formatNfeKey`. */ type FormatNfeKeyOptions = { /** Whether to left pad the value with zeros up to the 44 digits of a complete access key (default: `false`). */ pad?: boolean; }; /** * Formats a DF-e (Documento Fiscal eletrônico) access key (chave de acesso) into groups of 4 * digits separated by spaces, the form every auxiliary document prints it in: the DANFE of the * NF-e and the NFC-e, the DACTE of the CT-e, the CT-e OS and the GTV-e, the DAMDFE of the * MDF-e, the DABPE of the BP-e, the DANF3E of the NF3e and the DANFE-COM of the NFCom. * * Like every formatter of this package, the value is read for its digits and grouped as far as * they go, so a masked or partial key still being typed is grouped progressively and anything * without a digit (an object, `true`, an object with a null prototype) gives `""` instead of * throwing. Use `isValidNfeKey` to check a key. * * With `pad: true` the value is first left padded with zeros to the 44 digits of a complete * access key, so it always comes back fully grouped (`"12345"` gives * `"0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 2345"`). * * The parameter is typed as a string because the 44 digits of an access key are more than a * JavaScript number can hold exactly. At runtime a number is read as the string of its digits, * like in every formatter of this package. * * @param {string} value - The access key value to be formatted. * @param {FormatNfeKeyOptions} [options] - Optional formatting options. * @param {boolean} [options.pad] - Whether to pad the value with leading zeros. Defaults to `false`. * @returns {string} The formatted access key, e.g. "3520 0612 3456 ...". * * @example * ```typescript * formatNfeKey("35170458716523000119550010000000121000123458"); * // "3517 0458 7165 2300 0119 5500 1000 0000 1210 0012 3458" * * formatNfeKey("12345"); // "1234 5" (partial values are grouped as far as they go) * * formatNfeKey("12345", { pad: true }); * // "0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 2345" * ``` * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf * Manual de Orientação do Contribuinte (MOC) NF-e, "chave de acesso". */ export declare const formatNfeKey: (value: string, options?: FormatNfeKeyOptions) => string; //#endregion //#region src/format-passport/format-passport.d.ts /** * Formats a Brazilian passport number for display. * Converts to uppercase and removes all non-alphanumeric characters. * * @param {string} passport - A Brazilian passport number (any case, possibly with symbols). * @returns {string} The uppercased, symbol-free value capped to 8 characters, or an empty * string for a non-string input (a number is never a passport number: the series is two letters). * * @example * formatPassport("ab123456") // "AB123456" * formatPassport("AB-123.456") // "AB123456" * formatPassport("") // "" * * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte/ajuda/duvidas_/caderneta/caderneta-numero-onde-fica-e */ export declare const formatPassport: (passport: string) => string; //#endregion //#region src/format-phone/format-phone.d.ts /** The masks `formatPhone` can apply. */ type PhoneMask = "auto" | "e164" | "international" | "service" | "sn" | "nanp"; /** Options of `formatPhone`. */ type FormatPhoneOptions = { /** Which mask to apply, or `"auto"` to pick one from the value (default: `"sn"`). */ mask?: PhoneMask; }; /** * Formats a phone number according to Brazilian phone number patterns. * * `options.mask` accepts: * - `"sn"` (default): Brazilian subscriber number only, e.g. `"98765-4321"` (9 digits, no DDD). * With a DDD present in `value`, `"sn"` **truncates** it, e.g. `formatPhone("11987654321")` * (with `mask` omitted) returns `"11987-6543"`, silently dropping the last digit, because * only the first 9 digits are used and the DDD's 2 digits are consumed as if they were part * of the subscriber number. * - `"nanp"`: DDD + subscriber number, `"(00) 00000-0000"` for the 11 digits of a mobile and * `"(00) 0000-0000"` for the 10 digits of a landline. Any other length keeps the 11 digit * grouping, so a value still being typed reads as a partial mobile. * - `"auto"`: picks a mask from `value`. A leading Brazilian country code (`+55`, `0055` or a * bare `55` followed by 10 or 11 digits) selects `"international"`; a service number selects * `"service"`; otherwise the digit count decides, `"nanp"` when `value` has more digits than * a bare subscriber number (9) and `"sn"` when it does not. * - `"e164"`: the ITU-T E.164 form, `"+5511987654321"`, no separators. * - `"international"`: the way a Brazilian number is printed for foreign callers, * `"+55 11 98765-4321"` (or `"+55 11 3000-0000"` for a landline). * - `"service"`: service numbers, `"0800 123 4567"` for the Códigos Não Geográficos (`0300`, * `0303`, `0500`, `0800`, `0900`) and `"4004-1234"` for the abbreviated `300X`/`400X` ones. * Anatel specifies no display format for either, so these are the conventional groupings. * * `"e164"` and `"international"` drop the country code from `value` first, under the rule * documented in `parsePhone`. A service number has no E.164 form, it is not reachable from * abroad, so both international masks fall back to the `"service"` presentation for it, which * is how such numbers are printed in Brazil. The service-number check itself reads `value` * under the same rule, so `"5508001234567"` is the `0800` number, not a `+55 08` one. * * If `value` includes a DDD (area code), pass `{ mask: "auto" }` (or `"nanp"`) explicitly, * do not rely on the default, since the default `"sn"` mask assumes no DDD is present. A `mask` * outside the union falls back to the default `"sn"` instead of throwing. * * @param {string|number} value - The phone number to format, either as a string or a number. * @param {FormatPhoneOptions} [options] - Optional formatting options. * @param {"auto"|"sn"|"nanp"|"e164"|"international"|"service"} options.mask - The mask to apply for formatting the phone number (default: `"sn"`). * @returns {string} The formatted phone number as a string. * * @example * ```typescript * formatPhone("987654321"); // "98765-4321" (default "sn", no DDD) * formatPhone("11987654321", { mask: "auto" }); // "(11) 98765-4321" * formatPhone("1130000000", { mask: "auto" }); // "(11) 3000-0000" (10 digit landline) * formatPhone("5511987654321", { mask: "auto" }); // "+55 11 98765-4321" * formatPhone("08001234567", { mask: "auto" }); // "0800 123 4567" * formatPhone("5508001234567", { mask: "auto" }); // "0800 123 4567" * formatPhone("11987654321", { mask: "e164" }); // "+5511987654321" * formatPhone("11987654321", { mask: "international" }); // "+55 11 98765-4321" * formatPhone("40041234", { mask: "service" }); // "4004-1234" * formatPhone("11987654321"); // "11987-6543" (BEWARE: default "sn" truncates a DDD-prefixed number) * ``` * * @see Official: https://www.itu.int/rec/T-REC-E.164 * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 */ export declare const formatPhone: (value: string | number, options?: FormatPhoneOptions) => string; //#endregion //#region src/format-pis/format-pis.d.ts /** Options of `formatPis`. */ type FormatPisOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a PIS (Programa de Integração Social) number according to the specified pattern. * * @param {string|number} value - The PIS number to be formatted. It can be a string or a number. * @param {FormatPisOptions} [options] - Optional formatting options. * @param {boolean} options.pad - If true, pads the value with leading zeros if necessary. * @returns {string} The formatted PIS number as a string. * * @example * ```typescript * formatPis("12345678901"); // "123.45678.90-1" * formatPis(12345678901); // "123.45678.90-1" * formatPis("123456789", { pad: true }); // "001.23456.78-9" * ``` * * @see Official: https://www.gov.br/inss/pt-br/direitos-e-deveres/inscricao-e-contribuicao/inscricao * @see Official: https://www.gov.br/esocial/pt-br/documentacao-tecnica/manuais/mos-manual-de-orientacao-do-esocial-vs-2-4.pdf * @see Official: https://www.sirc.gov.br/wp-content/uploads/manual_sirc_recomendacoes_tecnicas_v7.pdf * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/pis.py */ export declare const formatPis: (value: string | number, options?: FormatPisOptions) => string; //#endregion //#region src/format-processo-juridico/format-processo-juridico.d.ts /** Options of `formatProcessoJuridico`. */ type FormatProcessoJuridicoOptions = { /** Whether to left pad the value with zeros up to the number of slots in the pattern (default: `false`). */ pad?: boolean; }; /** * Formats a legal process number (processo jurídico) according to a specific pattern. * * @param {string|number} value - The legal process number to be formatted. It can be a string or a number. * @param {FormatProcessoJuridicoOptions} [options] - Optional formatting options. * @param {boolean} options.pad - If true, the value will be padded with leading zeros if necessary. * @returns {string} The formatted legal process number as a string. * * @example * ```typescript * formatProcessoJuridico("00020802520125150049"); // "0002080-25.2012.5.15.0049" * ``` * * Resolução CNJ nº 65/2008 defines this Número Único de Processo layout and its check digits. * * @see Official: https://atos.cnj.jus.br/atos/detalhar/119 */ export declare const formatProcessoJuridico: (value: string | number, options?: FormatProcessoJuridicoOptions) => string; //#endregion //#region src/format-voter-id/format-voter-id.d.ts /** * Formats a Brazilian voter id (título de eleitor) for display. * * Uses the 12-digit grouping "0000 0000 00 00" by default. The 13-digit grouping * "0000 0000 0 00 00" is used only when the sanitized value has more than 12 digits and its * federative union code (the 10th and 11th digits) is "01" (São Paulo) or "02" (Minas Gerais), * the two states whose voter ids may carry a 9-digit sequential number. * * @param {string|number} value - The voter id value to be formatted. * @returns {string} The formatted voter id string. * * @example * ```typescript * formatVoterId("123456780124"); // "1234 5678 01 24" * formatVoterId("1234567880191"); // "1234 5678 8 01 91" * ``` * * The 13-digit São Paulo/Minas Gerais grouping is brutils parity, not published by the TSE. A * 14-or-more-digit input is read the same way as a 13-digit one: it is grouped as a São Paulo or * Minas Gerais id whenever its 10th and 11th digits are "01"/"02". Both patterns have a fixed * number of slots, 12 and 13, so anything past the last slot is dropped: * `formatVoterId("12345678801912")` returns "1234 5678 8 01 91", the same string the 13-digit * value "1234567880191" produces. * * The TSE resolution page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser. * * @see Official: https://www.tse.jus.br/legislacao/compilada/res/2021/resolucao-no-23-659-de-26-de-outubro-de-2021 * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/voter_id.py */ export declare const formatVoterId: (value: string | number) => string; //#endregion //#region src/generate-boleto/generate-boleto.d.ts /** The parameters of `generateBoleto`. */ type GenerateBoletoParams = { /** Which kind of bank slip to generate (default: `"bancario"`). */ type?: "bancario" | "arrecadacao"; }; /** * Generates a valid random Brazilian bank slip (boleto) number. * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * An arrecadação slip draws its segment from 1 to 7 (segment 9 is the banks' own) and its value * identifier from all four values, `6` and `8` for an effective amount and `7` and `9` for a * reference quantity, so both `hasEffectiveValue` branches of `getBoletoInfo` are reachable. * * @param {GenerateBoletoParams} [params] - Optional parameters. * @param {string} params.type - `"bancario"` (default) or `"arrecadacao"`. * @returns {string} A valid 47-digit boleto string without formatting, or a 48-digit one for arrecadação. * * @example * ```typescript * generateBoleto(); // "00190000090114971860168524522114675860000102656" * generateBoleto({ type: "arrecadacao" }); // "846100000005246100291102005460339004695895061080" * ``` * * Carta-Circular BCB nº 2.926/2000 specifies the linha digitável fields and the módulo 11 * check digit (using 1 for remainders 0, 10 and 1) of the 47 digit cobrança bancária slip, * including the position of the fator de vencimento field. The FEBRABAN "Layout Padrão de * Arrecadação/Recebimento com Utilização do Código de Barras" and the FEBRABAN layout index * cover the arrecadação slip. * * @see Official: https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf * @see Official: https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf * @see Official: https://portal.febraban.org.br/pagina/3425/33/pt-br/layout-febraban */ export declare const generateBoleto: (params?: GenerateBoletoParams) => string; //#endregion //#region src/generate-cep/generate-cep.d.ts /** * Generates a random Brazilian CEP (postal code). * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * A CEP has no check digit, so every 8 digit string is structurally valid. * * @returns {string} A random 8 digit CEP without formatting. * * @example * ```typescript * generateCep(); // "01310930" * ``` * * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/tudo-sobre-cep * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/guia-de-enderecamento/guia-de-enderecamento */ export declare const generateCep: () => string; //#endregion //#region src/generate-cnh/generate-cnh.d.ts /** * Generates a valid random CNH (Carteira Nacional de Habilitação, the Brazilian driver's license number). * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @returns {string} A valid 11-digit CNH string without formatting. * * @example * ```typescript * generateCnh(); // "00000000119" * ``` * * Resolução CONTRAN nº 886/2021, art. 4º I, defines the CNH registry number as 9 characters plus * 2 security check digits, but no official text publishes the check-digit weights; the algorithm * below follows the community reference cited as `Based on:`. * * Art. 4º § 1º of the same resolution states that the check digit is computed by the DSR system * with a "módulo 11" routine in which a remainder of 0 or 1 yields the digit 0. That rounding is * not the rule the registry numbers use in practice: the first verifier keeps the remainder * itself, so a remainder of 1 yields the digit 1 (which is why `"00000000119"` is a valid CNH). * The implementation follows the cited `Based on:` reference, not § 1º. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/Resolucao8862021F.pdf * @see Based on: https://siga0984.wordpress.com/2019/05/01/algoritmos-validacao-de-cnh/ */ export declare const generateCnh: () => string; //#endregion //#region src/generate-legal-nature/generate-legal-nature.d.ts /** * Generates a random valid Brazilian legal nature (natureza jurídica) code. * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * Only the 92 codes of the Tabela de Natureza Jurídica 2021 are drawn: a code a past revision of * the table retired stays valid for `isValidLegalNature`, but is never generated. * * @returns {string} One of the legal nature codes in force published by the CONCLA. * * @example * ```typescript * generateLegalNature(); // "2062" * ``` * * The CONCLA table page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser; the detailed structure PDF next to it is served * normally. * * @see Official: https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021 * @see Official: https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf */ export declare const generateLegalNature: () => string; //#endregion //#region src/get-format-license-plate/get-format-license-plate.d.ts /** The Brazilian license plate formats `getFormatLicensePlate` can identify: the old `LLLNNNN` and the Mercosul `LLLNLNN`. */ type LicensePlateFormat = "LLLNNNN" | "LLLNLNN"; /** * Identifies the format of a Brazilian license plate (placa de carro ou moto). * * Two formats are supported: the old Brazilian `LLLNNNN` and the single Mercosul sequence * `LLLNLNN` that Resolução CONTRAN nº 969/2022 defines for every vehicle, motorcycles * included. * * Returns `null` when the sanitized value does not have exactly 7 alphanumeric characters * (e.g. it is too short, too long, or otherwise malformed) or does not match any of the * supported formats. * * @param {string} value - The license plate value to be checked. * @returns {LicensePlateFormat | null} The identified format, or `null` when it doesn't match * any supported format. * * @example * ```typescript * getFormatLicensePlate("ABC1234"); // "LLLNNNN" * getFormatLicensePlate("ABC1D23"); // "LLLNLNN" * getFormatLicensePlate("ABC12D3"); // null (not a Mercosul sequence) * getFormatLicensePlate("ABC1234EXTRA"); // null (too many characters) * ``` * * The resolution's own text does not spell the sequence out: art. 2º § 2º delegates the * technical specification to Anexo I, whose item 1.2 reads "O padrão de estampagem é composto de * 7 (sete) caracteres alfanuméricos, em alto relevo, na sequência LLLNLNN" and whose item 1.2.1 * reads `L` as a letter and `N` as a numeral. Art. 2º § 1º puts a single rear plate of that same * standard on motorcycles and similar vehicles, and art. 2º § 3º describes the old `AAA-1111` * PNU it coexists with. The annexes are published in a PDF of their own, cited below alongside * the resolution's text. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022anexos.pdf */ export declare const getFormatLicensePlate: (value: string) => LicensePlateFormat | null; //#endregion //#region src/generate-license-plate/generate-license-plate.d.ts /** The license plate formats `generateLicensePlate` can generate. */ type GenerateLicensePlateFormat = LicensePlateFormat; /** * Generates a valid random Brazilian license plate (placa de carro ou moto). * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for * security purposes. * * @param {GenerateLicensePlateFormat} [format] - The format to generate. Defaults to the * Mercosul format ("LLLNLNN"), the single sequence Resolução CONTRAN nº 969/2022 defines for * every vehicle, motorcycles included. * @returns {string} A randomly generated license plate matching the requested format. * * @example * ```typescript * generateLicensePlate(); // "ABC1D23" (Mercosul) * generateLicensePlate("LLLNNNN"); // "ABC1234" (old Brazilian format) * ``` * * The resolution's own text does not spell the sequence out: art. 2º § 2º delegates the * technical specification to Anexo I, whose item 1.2 reads "O padrão de estampagem é composto de * 7 (sete) caracteres alfanuméricos, em alto relevo, na sequência LLLNLNN" and whose item 1.2.1 * reads `L` as a letter and `N` as a numeral. The annexes are published in a PDF of their own, * cited below alongside the resolution's text. * * A `format` outside the two supported literals falls back to the default, like every other * generator of this package does with an option it does not know, so the result is always a plate * `isValidLicensePlate` accepts. (2.3.0 used an unknown string verbatim, so * `generateLicensePlate("LLLNNLN")` produced the withdrawn motorcycle sequence and * `generateLicensePlate("bogus")` five digits; neither is a plate.) * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022anexos.pdf */ export declare const generateLicensePlate: (format?: GenerateLicensePlateFormat) => string; //#endregion //#region src/generate-passport/generate-passport.d.ts /** * Generates a random valid Brazilian passport number. * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @returns {string} A random valid passport number string (e.g. "RY393097"). * * @example * generatePassport() // "RY393097" * generatePassport() // "ZS840088" * * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte/ajuda/duvidas_/caderneta/caderneta-numero-onde-fica-e */ export declare const generatePassport: () => string; //#endregion //#region src/generate-phone/generate-phone.d.ts /** The kinds of phone number `generatePhone` can generate. */ type GeneratePhoneType = "mobile" | "landline" | "service"; /** * Generates a random, structurally-valid Brazilian phone number (DDD + subscriber number, * no formatting/mask applied, see `formatPhone` to format the result). * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @param {GeneratePhoneType} [type] - `"mobile"` (9-digit number starting with 9), * `"landline"` (8-digit number starting with 2-6) or `"service"` (a non-geographic number, * either an 11-digit `0X00` one or an 8-digit `300X`/`400X` one, with no DDD). When omitted, * randomly generates a mobile or a landline, never a service number, since those are not * accepted by `isValidPhone` unless asked for. * @returns {string} A randomly generated phone number as a string of digits (DDD included, * except for service numbers, which have none). * * @example * ```typescript * generatePhone("mobile"); // e.g. "11987654321" * generatePhone("landline"); // e.g. "1132345678" * generatePhone("service"); // e.g. "08001234567" or "40041234" * generatePhone(); // randomly mobile or landline * ``` * * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 */ export declare const generatePhone: (type?: GeneratePhoneType) => string; //#endregion //#region src/generate-pis/generate-pis.d.ts /** * Generates a valid random Brazilian PIS (Programa de Integração Social) number. * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @returns {string} A valid 11-digit PIS string without formatting. * * @example * ```typescript * generatePis(); // "12056874107" * ``` * * The eSocial MOS states the NIS must have 11 numeric digits including the check digit, and the * SIRC technical manual confirms the check digit is verified with módulo 11; neither publishes * the weight vector used below, which follows the community reference cited as `Based on:`. * * @see Official: https://www.gov.br/inss/pt-br/direitos-e-deveres/inscricao-e-contribuicao/inscricao * @see Official: https://www.gov.br/esocial/pt-br/documentacao-tecnica/manuais/mos-manual-de-orientacao-do-esocial-vs-2-4.pdf * @see Official: https://www.sirc.gov.br/wp-content/uploads/manual_sirc_recomendacoes_tecnicas_v7.pdf * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/pis.py */ export declare const generatePis: () => string; //#endregion //#region src/generate-pix-payload/generate-pix-payload.d.ts /** The parameters `generatePixPayload` takes to build a Pix BR Code. */ type GeneratePixPayloadParams = { /** The Pix key of the receiver, in any accepted form. Required unless `url` is given. */ key?: string; /** * The PSP location of a dynamic payload (Bacen field 26-25), without a URL scheme, e.g. * `"pix.example.com/qr/v2/1234"`. When given, the payload is generated as dynamic * (`pointOfInitiation` `"12"`) and carries this URL instead of a key. Required unless `key` * is given; giving both `key` and `url` is invalid, just like giving neither. */ url?: string; /** Name of the receiver, folded to ASCII and truncated to 25 characters. */ merchantName: string; /** City of the receiver, folded to ASCII and truncated to 15 characters. */ merchantCity: string; /** Amount in BRL, with at most two decimal places. Omit it to let the payer type it. Not allowed together with `url`: a dynamic BR Code takes its amount from the PSP location. */ amount?: number; /** Transaction ID, 1 to 25 characters of `[A-Za-z0-9]` (default: the absent marker `***`). Not allowed together with `url`. */ txid?: string; /** Free text shown to the payer, folded to ASCII and truncated to what the template holds. */ description?: string; }; /** * Generates the payload of a Pix BR Code, the string behind a Pix QR Code and behind "Pix * copia e cola". * * Exactly one of `params.key` or `params.url` must be given: `null` is returned when both are * given and when neither is given, since only one of them can occupy the "Merchant Account * Information" template at a time. * * When `params.key` is given, it is normalized to its DICT canonical form by `getPixKeyInfo` and * the payload is static: the "Point of Initiation Method" object is left out, so the payload * may be paid more than once, as in the example of the Bacen manual. * * When `params.url` is given instead, the payload is dynamic per the Manual de Padrões para * Iniciação do Pix: the URL takes the key's place in the "Merchant Account Information" * template (sub-object `25` instead of `01`) and the "Point of Initiation Method" object (`01`) * is set to `"12"`. `params.url` must be at most 77 characters, the length that keeps the * template within its 99 character limit together with the `br.gov.bcb.pix` GUI. `getPixPayloadInfo` * already parses both shapes, so `getPixPayloadInfo(generatePixPayload({ url, ... }))` round-trips. * * Object `01` is optional in the Manual do BR Code (`Uso: O`), so writing it only for a dynamic * payload is one of the shapes the manual allows and follows its own examples; `getPixPayloadInfo` * accepts the others too. The Pix Saque BR Code, which announces the ISPB of the "facilitador de * serviço de saque" in sub-object 26-03 (`fss`), is not generated here, only parsed. * * Unreserved Templates (IDs 80 to 99) are never written: the location always goes in the * "Merchant Account Information" template, so the "QR Code composto" of Pix Automático (Pix * recorrente), which puts its recurrence location in one of them, is out of scope here. * `getPixPayloadInfo` does read a composto, but only as an ordinary dynamic payload. * * The merchant name, the merchant city and the description are folded to printable ASCII * (accents are dropped) and truncated to the lengths the BR Code allows, the description to * whatever is left of the 99 characters the "Merchant Account Information" template holds. * * `params.amount` is written with the two decimal places the BR Code takes, so an amount that * does not survive that round trip (`0.005`, `123.456`) is refused rather than rounded into a * payload that asks the payer for a different sum. * * @param {GeneratePixPayloadParams} params - The parameters of the payload. * @param {string} [params.key] - The Pix key of the receiver. Required unless `url` is given. * @param {string} [params.url] - The PSP location of a dynamic payload. Required unless `key` * is given. * @param {string} params.merchantName - The name of the receiver. * @param {string} params.merchantCity - The city of the receiver. * @param {number} [params.amount] - The amount in BRL, with at most two decimal places. Omit it * to let the payer type it. * @param {string} [params.txid] - The transaction ID, 1 to 25 characters of `[A-Za-z0-9]`. * @param {string} [params.description] - The free text shown to the payer. * @returns {string|null} The BR Code payload, or `null` when the parameters are invalid. * * @example * ```typescript * generatePixPayload({ * key: "123.456.789-09", * merchantName: "Fulano de Tal", * merchantCity: "Brasília", * amount: 123.45, * }); * // "00020126330014br.gov.bcb.pix0111123456789095204000053039865406123.455802BR..." * * generatePixPayload({ * url: "pix.example.com/qr/v2/1234", * merchantName: "Fulano de Tal", * merchantCity: "Brasília", * }); * // "00020101021226480014br.gov.bcb.pix2526pix.example.com/qr/v2/12345204000053039865802BR5913Fulano de Tal6008Brasilia62070503***6304FC66" * * generatePixPayload({ merchantName: "Fulano", merchantCity: "Brasília" }); // null (neither key nor url) * generatePixPayload({ key: "123.456.789-09", url: "pix.example.com/qr/v2/1234", merchantName: "Fulano", merchantCity: "Brasília" }); // null (both key and url) * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/spb_docs/ManualBRCode.pdf * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf * @see Official: https://github.com/bacen/pix-api * Pix (SPI) OpenAPI spec. * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT.html * DICT (Diretório de Identificadores de Contas Transacionais) API specification. */ export declare const generatePixPayload: (params: GeneratePixPayloadParams) => string | null; //#endregion //#region src/generate-processo-juridico/generate-processo-juridico.d.ts /** The parameters of `generateProcessoJuridico`. */ type GenerateProcessoJuridicoParams = { /** Filing year, from the current year to 9999 (default: the current year). */ year?: number; /** Court segment (J), from 1 to 9 (default: random). */ court?: number; }; /** * The parameters of `generateProcessoJuridico`, the 2.3.0 name of * `GenerateProcessoJuridicoParams`. * * @deprecated Use `GenerateProcessoJuridicoParams` instead. */ type GenerateProcessoJuridicoOptions = GenerateProcessoJuridicoParams; /** * Generates a random valid Brazilian Processo Jurídico (court case) number, * following the `NNNNNNNDDAAAAJTROOOO` layout of Resolução CNJ nº 65/2008. * * The órgão (`J`) and the tribunal (`TR`) are drawn from the closed lists of art. 1º, § 4º and * § 5º of the resolution, so the pair always names a court that exists: `court` picks the órgão * and the `TR` is then drawn among the tribunais that órgão has, which is why a `court` outside * 1 to 9, the only value with no tribunal to draw from, returns `null` instead of a number. The * unidade de origem (`OOOO`) is drawn freely, since art. 1º, § 6º leaves its codification to each * tribunal and publishes no central list. * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @param {GenerateProcessoJuridicoParams} [options] - Optional generation options. * @param {number} options.year - The `AAAA` field. Must be an integer between the * current year and 9999. Defaults to the current year. * @param {number} options.court - The `J` field (segmento do Judiciário). Must be an * integer between 1 and 9. Defaults to a random value. * @returns {string|null} The generated number without formatting, or null when the options are invalid. * * @example * ```typescript * generateProcessoJuridico(); // "00020803420265150049" * generateProcessoJuridico({ year: 2030, court: 5 }); // "12345679820305120049" * generateProcessoJuridico({ year: 10000 }); // null * generateProcessoJuridico({ court: 10 }); // null (no such órgão) * ``` * * Resolução CNJ nº 65/2008 defines this Número Único de Processo layout and its check digits, and * closes the list of órgão (`J`) and tribunal (`TR`) codes in art. 1º, § 4º and § 5º. * * @see Official: https://atos.cnj.jus.br/atos/detalhar/119 */ export declare const generateProcessoJuridico: (options?: GenerateProcessoJuridicoParams) => string | null; //#endregion //#region src/generate-renavam/generate-renavam.d.ts /** * Generates a valid random RENAVAM (Registro Nacional de Veículos Automotores) number. * * The result is always the eleven digit form: ten base digits followed by the check digit. A base * whose digits are all the same is drawn again, since `isValidRenavam` rejects a registration like * `"00000000000"`. * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @returns {string} A valid 11-digit RENAVAM string without formatting. * * @example * ```typescript * generateRenavam(); // "12345678900" * ``` * * The Código de Trânsito Brasileiro creates the RENAVAM registry but does not define its check * digit, so the algorithm follows the two community references cited as `Based on:`. * * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l9503compilado.htm * @see Based on: https://github.com/klawdyo/validation-br/blob/main/src/renavam.ts * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/renavam.py */ export declare const generateRenavam: () => string; //#endregion //#region src/generate-voter-id/generate-voter-id.d.ts /** * Generates a valid random Brazilian voter id (título de eleitor). * * Uses `Math.random()` internally, so it is not cryptographically secure, do not use for security purposes. * * @param {StateCode | "ZZ"} state - Optional. The Brazilian state code to generate a voter id * for, or `"ZZ"` for a voter id issued abroad. Defaults to `"ZZ"` when omitted or unknown, a key * of the prototype chain (`"__proto__"`, `"constructor"`) and a value that is not a string * included, so a malformed state never throws. * @returns {string} A valid 12-digit voter id string without formatting. * * @example * ```typescript * generateVoterId(); // "123456782895" (abroad, UF "28") * generateVoterId("SP"); // "123456780191" (UF "01") * generateVoterId("XX" as StateCode); // falls back to "ZZ" instead of throwing * ``` * * Resolução TSE nº 23.659/2021, art. 36, parágrafo único, confirms the federative union table and * the two-step módulo 11 structure; the weights themselves are not published by the TSE and follow * the community reference cited as `Based on:`. * * The TSE resolution page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser. * * @see Official: https://www.tse.jus.br/legislacao/compilada/res/2021/resolucao-no-23-659-de-26-de-outubro-de-2021 * @see Based on: https://siga0984.wordpress.com/2019/05/01/algoritmos-validacao-de-titulo-de-eleitor/ */ export declare const generateVoterId: (state?: StateCode | "ZZ") => string; //#endregion //#region src/get-address-info-by-cep/get-address-info-by-cep.d.ts /** Base class of every error `getAddressInfoByCep` rejects with. */ export declare class GetAddressInfoByCepError extends Error { constructor(message: string); } /** Thrown by `getAddressInfoByCep` when the value given is not a valid CEP. */ export declare class GetAddressInfoByCepValidationError extends GetAddressInfoByCepError { constructor(message: string); } /** Thrown by `getAddressInfoByCep` when no CEP service knows the CEP. */ export declare class GetAddressInfoByCepNotFoundError extends GetAddressInfoByCepError { constructor(message: string); } /** Thrown by `getAddressInfoByCep` when every CEP service failed to answer. */ export declare class GetAddressInfoByCepServiceError extends GetAddressInfoByCepError { constructor(message: string); } /** The address `getAddressInfoByCep` returns for a CEP. */ type AddressInfo = { /** The 8 digit CEP, no mask. */ cep: string; /** Two letter state code, e.g. "SP". */ state: string; /** City name. */ city: string; /** Neighborhood name, empty when the CEP covers a whole city. */ neighborhood: string; /** Street name, empty when the CEP covers a whole city. */ street: string; }; /** The CEP services `getAddressInfoByCep` can query. */ type CepProvider = "viacep" | "widenet" | "brasilapi"; /** Options of `getAddressInfoByCep`. */ type GetAddressInfoByCepOptions = { /** * Which CEP services to race, in the order given (default: `["viacep", "brasilapi"]`; the * deprecated `"widenet"` provider is excluded from the default list, but can still be * requested explicitly). */ providers?: CepProvider[]; }; /** * Fetches address information for a given CEP using multiple providers simultaneously. * Returns the result from the first provider that responds successfully. * * The providers are started together and raced with `Promise.any`, not tried one after the * other, so a provider that is retrying delays nothing for the others: its retries only push * back the moment its own failure lands, and therefore the moment an all-failed rejection can * surface. * * @param {string|number} cep - The CEP (Brazilian postal code) to search for. Can be a string or number. * @param {GetAddressInfoByCepOptions} options - Optional configuration for the function. * @param {CepProvider[]} options.providers - List of providers to use. Defaults to `["viacep", "brasilapi"]` * if not specified (the deprecated `"widenet"` provider is excluded from the default list, but can still * be requested explicitly). * @returns {Promise} A promise that resolves to the address information. * @throws {GetAddressInfoByCepValidationError} If the CEP format is invalid, or if * `options.providers` is given and names no known provider: an empty array, an array of unknown * names, and a value that is not an array at all (`null` included) all reject this way rather * than with a raw `TypeError`. * @throws {GetAddressInfoByCepNotFoundError} If the CEP is not found in any of the services. * @throws {GetAddressInfoByCepServiceError} If all services are unavailable. * * @example * ```typescript * // Using the default providers (["viacep", "brasilapi"]) * const address = await getAddressInfoByCep("01310100"); * * // Using specific providers * const address = await getAddressInfoByCep("01310-100", { * providers: ["viacep", "brasilapi"] * }); * * // Using number input * const address = await getAddressInfoByCep(1310100); * ``` * * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/tudo-sobre-cep * @see Based on: https://viacep.com.br/ * ViaCEP, one of the two default providers. A third-party service, not a Correios one. * @see Based on: https://brasilapi.com.br/docs#tag/CEP * BrasilAPI, the other default provider. A third-party service, not a Correios one. */ export declare const getAddressInfoByCep: (cep: string | number, options?: GetAddressInfoByCepOptions) => Promise; //#endregion //#region src/get-area-code-info/get-area-code-info.d.ts /** The state, and the region it belongs to, that `getAreaCodeInfo` returns for a DDD. */ type AreaCodeInfo = { /** The DDD (area code) as a number, e.g. `11`. */ areaCode: number; /** The two-letter code of the state the DDD belongs to, e.g. `"SP"`. */ stateCode: StateCode; /** The full name of the state the DDD belongs to, e.g. `"São Paulo"`. */ stateName: StateName; /** The code of the region the state belongs to, e.g. `"SE"`. */ regionCode: State["regionCode"]; /** The full name of the region the state belongs to, e.g. `"Sudeste"`. */ regionName: State["regionName"]; /** * Every state the DDD serves, the primary `stateCode` first, e.g. `["SP"]` for 11 and * `["DF", "GO"]` for 61. */ stateCodes: StateCode[]; }; /** * Retrieves the state (and its region) a Brazilian DDD (area code) belongs to. * * `stateCode` is always a single state: the one the DDD is seated in, the state of the city the * code was allocated around, which is not necessarily the state holding most of its * municipalities. Four DDDs straddle a state border, and for those `stateCodes` lists the * other states too. DDD 61 is the widest of them, serving the Distrito Federal and the twelve * Goiás municipalities of the Entorno do Distrito Federal, so its `stateCode` is `"DF"` and * its `stateCodes` is `["DF", "GO"]` even though the Distrito Federal holds only one of its * thirteen municipalities, Brasília. The other three are 42 (`["PR", "SC"]`, for Porto * União), 47 (`["SC", "PR"]`, for Rio Negro) and 49 (`["SC", "PR"]`, for Barracão), and there * the seat does hold every municipality but the one named. * * A `areaCode` given as a number must be a non-negative integer: a sign and a decimal point * are not digits, so `-11` and `1.1` are rejected instead of being read as `11`. * * @param {string|number} areaCode - The DDD to look up. Accepts a string or a non-negative * integer number, with any non-digit characters stripped before matching. * @returns {AreaCodeInfo|null} The area code info, or `null` when `areaCode` is not one of the * 67 DDDs in use under the Plano Geral de Numeração. * * Resolução Anatel nº 749/2022, art. 15, defines the Código Nacional (area code); the gov.br * page below lists the codes actually allocated and links, under "POR MUNICÍPIO", to the Anexo * of Resolução Anatel nº 263/2001, which gives the Código Nacional of every municipality. * * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 * @see Official: https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais * @see Based on: https://informacoes.anatel.gov.br/legislacao/resolucoes/2001/383-resolucao-263 * Anexo of Resolução nº 263/2001 (revoked; still the table Anatel's Códigos Nacionais page links to). * @see Based on: https://brasilapi.com.br/docs#tag/DDD * * @example * ```typescript * getAreaCodeInfo("11"); * // { areaCode: 11, stateCode: "SP", stateName: "São Paulo", regionCode: "SE", regionName: "Sudeste", stateCodes: ["SP"] } * * getAreaCodeInfo(21); * // { areaCode: 21, stateCode: "RJ", stateName: "Rio de Janeiro", regionCode: "SE", regionName: "Sudeste", stateCodes: ["RJ"] } * * getAreaCodeInfo("61"); * // { areaCode: 61, stateCode: "DF", stateName: "Distrito Federal", regionCode: "CO", regionName: "Centro-Oeste", stateCodes: ["DF", "GO"] } * * getAreaCodeInfo("00"); // null * getAreaCodeInfo(-11); // null * ``` */ export declare const getAreaCodeInfo: (areaCode: string | number) => AreaCodeInfo | null; //#endregion //#region src/get-area-codes-by-state/get-area-codes-by-state.d.ts /** * Retrieves every DDD (area code) that serves a given Brazilian state, under the Plano Geral * de Numeração. * * The match is case-insensitive, so `"sp"` and `"SP"` both resolve to the same list. The * result is sorted in ascending order and is a fresh array on every call. * * A DDD that straddles a state border is listed under every state it serves, so DDD 61 comes * back for both `"DF"` and `"GO"`: it serves the Distrito Federal and the twelve Goiás * municipalities of the Entorno do Distrito Federal. The other three are 42, shared by Paraná * and Porto União (SC), 47, shared by Santa Catarina and Rio Negro (PR), and 49, shared by * Santa Catarina and Barracão (PR). * * @param {string} stateCode - The two-letter code (sigla) of the state. * @returns {number[]} The DDDs of the state, sorted ascending, or an empty array when * `stateCode` does not match any Brazilian state. * * @example * ```typescript * getAreaCodesByState("SP"); // [11, 12, 13, 14, 15, 16, 17, 18, 19] * getAreaCodesByState("sp"); // [11, 12, 13, 14, 15, 16, 17, 18, 19] * getAreaCodesByState("AC"); // [68] * getAreaCodesByState("DF"); // [61] * getAreaCodesByState("GO"); // [61, 62, 64] * getAreaCodesByState("XX"); // [] * ``` * * Resolução Anatel nº 749/2022, art. 15, defines the Código Nacional (area code). The Anexo the * gov.br page below links to, giving the Código Nacional of every municipality, is the one this * inverse lookup was derived from and is no longer in force. * * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 * @see Official: https://www.gov.br/anatel/pt-br/regulado/numeracao/codigos-nacionais * @see Based on: https://informacoes.anatel.gov.br/legislacao/resolucoes/2001/383-resolucao-263 * Anexo of Resolução nº 263/2001, revoked, and still the table Anatel's page links to. */ export declare const getAreaCodesByState: (stateCode: string) => number[]; //#endregion //#region src/get-bank-by-code/get-bank-by-code.d.ts /** * Looks up a Brazilian bank by its compensation code (COMPE), published by Banco Central do * Brasil in the STR (Sistema de Transferência de Reservas) participants list. * * @param {string|number} code - The bank's COMPE code, with or without leading zeros. * @returns {Bank|null} A fresh copy of the matching bank, or `null` when no bank has that code. * * @example * ```typescript * getBankByCode("001"); // { code: "001", ispb: "00000000", name: "Banco do Brasil S.A." } * getBankByCode(1); // { code: "001", ispb: "00000000", name: "Banco do Brasil S.A." } * getBankByCode("999"); // null * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv * @see Based on: https://brasilapi.com.br/api/banks/v1 * Fallback source used by the dataset generator (`scripts/banks.ts`) when the Bacen CSV request fails. */ export declare const getBankByCode: (code: string | number) => Bank | null; //#endregion //#region src/get-bank-by-ispb/get-bank-by-ispb.d.ts /** * Looks up a Brazilian bank by its ISPB (Identificador do Sistema de Pagamentos Brasileiro), * the 8 digit code that identifies every participant of the SPB, published by Banco Central do * Brasil in the STR (Sistema de Transferência de Reservas) participants list. Every SPB * participant has an ISPB, but this dataset only carries the institutions that also have a * COMPE code, so an ISPB whose institution has no COMPE code of its own returns `null`. * * @param {string|number} value - The bank's ISPB, with or without leading zeros. * @returns {Bank|null} A fresh copy of the matching bank, or `null` when no bank has that ISPB. * * @example * ```typescript * getBankByIspb("00000000"); // { code: "001", ispb: "00000000", name: "Banco do Brasil S.A." } * getBankByIspb(0); // { code: "001", ispb: "00000000", name: "Banco do Brasil S.A." } * getBankByIspb("60701190"); // { code: "341", ispb: "60701190", name: "ITAÚ UNIBANCO S.A." } * getBankByIspb("99999999"); // null * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv * @see Based on: https://brasilapi.com.br/api/banks/v1 * Fallback source used by the dataset generator (`scripts/banks.ts`) when the Bacen CSV request fails. */ export declare const getBankByIspb: (value: string | number) => Bank | null; //#endregion //#region src/get-banks/get-banks.d.ts /** * Returns every Brazilian bank with a compensation code (COMPE), published by Banco Central * do Brasil in the STR (Sistema de Transferência de Reservas) participants list. * * Each call returns a fresh array of fresh objects, so mutating the result never affects the * underlying data or subsequent calls. * * @returns {Bank[]} Every known bank, in a fixed table order. * * @example * ```typescript * getBanks()[0]; // { code: "001", ispb: "00000000", name: "Banco do Brasil S.A." } * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv * @see Based on: https://brasilapi.com.br/api/banks/v1 * Fallback source used by the dataset generator (`scripts/banks.ts`) when the Bacen CSV request fails. */ export declare const getBanks: () => Bank[]; //#endregion //#region src/get-boleto-info/get-boleto-info.d.ts /** The fields `getBoletoInfo` reads out of a bank slip (boleto). */ type BoletoInfo = { /** Amount in cents. */ amount: number; /** Due date read from the "fator de vencimento", or `null` when the bank slip carries none. */ expirationDate: Date | null; /** Three digit bank code (COMPE), empty for an arrecadação bank slip. */ bankCode: string; /** Present and set to "arrecadacao" only for convênio/tributos bank slips. */ type?: "arrecadacao"; /** Arrecadação segment (1 to 7, or 9 for the bank's own use), the kind of biller the bank slip belongs to. */ segment?: number; /** Arrecadação amount in reais (`amount` divided by 100). */ value?: number; /** Whether the arrecadação amount is an effective value (`true`) or a reference quantity (`false`). */ hasEffectiveValue?: boolean; }; /** Options of `getBoletoInfo`. */ type GetBoletoInfoOptions = { /** Date used to resolve the 9000 day "fator de vencimento" cycle (default: now). */ referenceDate?: Date; }; /** * Extracts information from a Brazilian bank slip (boleto). * * The value is checked with `isValidBoleto` first, so an invalid bank slip gives `null` rather * than a partial result, the way every other getter of this package answers a lookup it cannot * resolve (`getFormatLicensePlate`, `getMunicipality`). * * Supports the 47 digit "cobrança bancária" linha digitável and, additionally, the * "arrecadação" (convênio/tributos) bank slip: 48 digit linha digitável or 44 digit * barcode, both starting with `8`. Arrecadação bank slips also return `type`, `segment`, * `value` and `hasEffectiveValue`, and, carrying neither a bank code nor a fator de vencimento, * come back with `bankCode` set to `""` and `expirationDate` set to `null` rather than with those * two keys missing. * * Neither FEBRABAN nor the Banco Central publishes a way of telling an old cycle fator de * vencimento from a new cycle one, so every factor resolves to either of two dates 9000 days * apart. `referenceDate` (now by default) picks between them through the library's own safety * windows, which means the same slip can resolve to the other candidate as time passes: pass * `referenceDate` explicitly whenever the answer has to stay stable. The search never goes below * the first cycle, so a `referenceDate` older than the scheme itself still resolves a factor to * the oldest date that factor can denote rather than to one before the 07/10/1997 base date. * * @param {string} value - The boleto digitable line (can be with or without mask). * @param {GetBoletoInfoOptions} [options] - Optional options. * @param {Date} options.referenceDate - Date used to resolve the "fator de vencimento" cycle. Defaults to now. * @returns {BoletoInfo | null} An object containing amount (in cents), expirationDate, and bankCode, or null if the boleto is invalid. * * @example * ```typescript * getBoletoInfo('00190000090114971860168524522114675860000102656', { * referenceDate: new Date(2025, 5, 15), * }); * // { amount: 102656, expirationDate: new Date(2018, 6, 15), bankCode: '001' } * * getBoletoInfo('846100000005246100291102005460339004695895061080'); * // { amount: 2461, expirationDate: null, bankCode: '', type: 'arrecadacao', segment: 4, value: 24.61, hasEffectiveValue: true } * * getBoletoInfo('invalid'); // null * ``` * * Carta-Circular BCB nº 2.926/2000 specifies the linha digitável fields and the módulo 11 * check digit (using 1 for remainders 0, 10 and 1) of the 47 digit cobrança bancária slip, * including the position of the fator de vencimento field. The FEBRABAN "Layout Padrão de * Arrecadação/Recebimento com Utilização do Código de Barras" and the FEBRABAN layout index * cover the arrecadação slip. The 22/02/2025 reset of the fator de vencimento is in neither: * the Bradesco cobrança layout manual below reproduces the FEBRABAN rule. See * `src/get-boleto-info/constants.ts` for the fator de vencimento cycle base date and reset. * * @see Official: https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf * @see Official: https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf * @see Official: https://portal.febraban.org.br/pagina/3425/33/pt-br/layout-febraban * @see Based on: https://banco.bradesco/assets/pessoajuridica/pdf/4008-524-0121-layout-cobranca-versao-portugues.pdf * Bradesco "Layout da Cobrança" manual: base date 07/10/1997, 03/07/2000 = 1000, 21/02/2025 = 9999 * and a restart at 1000 on 22/02/2025. */ export declare const getBoletoInfo: (value: string, options?: GetBoletoInfoOptions) => BoletoInfo | null; //#endregion //#region src/get-cbo/get-cbo.d.ts /** * A CBO (Classificação Brasileira de Ocupações) occupation. */ type Cbo = { /** The 6 digit occupation code, without the hyphen mask. */ code: string; /** The official occupation description, the title the MTE table prints. */ description: string; }; /** * Looks a CBO (Classificação Brasileira de Ocupações) code up in the official CBO 2002 * table. * * A string is only read as a code when it is written in one of the documented forms: the 6 * digits, or the `NNNN-NN` mask, with a single separator between the groups and optional * surrounding whitespace. Anything else (`"2124abc05"`) is rejected instead of having its * digits picked out. A number is only read as a code when it is a non-negative safe integer, * since a sign, a decimal point or a rounded magnitude would otherwise be read as a code the * caller never wrote. * * A CBO code is always 6 digits and its leading zeros are part of it, so a value written as * bare digits is left padded with zeros to 6 whether it comes as a string or as a number: * `10205`, `"10205"` and `"010205"` are the same code. A masked value already carries its * separators and is read as written. * * @param {string|number} value - The CBO code to look up, with or without the hyphen * mask, e.g. `"2124-05"`, `"212405"` or `212405`. * @returns {Cbo|null} The matching occupation, or null when the code is unknown or invalid. * * @example * ```typescript * getCbo("2124-05"); // { code: "212405", description: "Analista de desenvolvimento de sistemas" } * getCbo(10205); // { code: "010205", description: "Oficial da aeronáutica" } (padded to 6 digits) * getCbo("10205"); // { code: "010205", description: "Oficial da aeronáutica" } (padded to 6 digits) * getCbo("999999"); // null * getCbo("2124abc05"); // null (not a documented form) * getCbo(-212405); // null (not a non-negative safe integer) * ``` * * @see Official: https://www.gov.br/trabalho-e-emprego/pt-br/assuntos/cbo/servicos/downloads/cbo2002-ocupacao.csv * The CBO 2002 occupation table, as published by the Ministério do Trabalho e Emprego. * @see Based on: https://raw.githubusercontent.com/lucaashoff/lista-cbo-json/main/cbos.json * Community mirror of the same table, the fallback `CBO_TITLES` was built from before the * official CSV was used. */ export declare const getCbo: (value: string | number) => Cbo | null; //#endregion //#region src/get-cep-info-by-address/get-cep-info-by-address.d.ts /** Base class of every error `getCepInfoByAddress` rejects with. */ export declare class GetCepInfoByAddressError extends Error { constructor(message: string); } /** Thrown by `getCepInfoByAddress` when the state, city or street given is missing or invalid. */ export declare class GetCepInfoByAddressValidationError extends GetCepInfoByAddressError { constructor(message: string); } /** Thrown by `getCepInfoByAddress` when no address matches the query. */ export declare class GetCepInfoByAddressNotFoundError extends GetCepInfoByAddressError { constructor(message: string); } /** * One address returned by `getCepInfoByAddress`, under the field names ViaCEP itself uses. The * ViaCEP payload is passed through unchanged, so every field the service sends is present and a * field it adds later shows up even though it is not declared here. */ type CepAddressInfo = { /** The CEP, masked as "00000-000" the way ViaCEP returns it. */ cep: string; /** Street name. */ logradouro: string; /** Extra address information, e.g. a house number range. */ complemento: string; /** Name of the establishment the CEP belongs to, e.g. "AC São Carlos"; empty for a street CEP. */ unidade?: string; /** Neighborhood name. */ bairro: string; /** City name. */ localidade: string; /** Two letter state code, e.g. "SP". */ uf: string; /** Full state name, e.g. "Minas Gerais". */ estado?: string; /** Region name, e.g. "Sudeste". */ regiao?: string; /** The 7 digit IBGE municipality code. */ ibge?: string; /** GIA code, used by the São Paulo state tax authority. */ gia?: string; /** Area code (DDD) of the city. */ ddd?: string; /** SIAFI code of the municipality. */ siafi?: string; }; /** The address `getCepInfoByAddress` looks up. */ type GetCepInfoByAddressParams = { /** Two letter state code, e.g. "SP". */ federalUnit: string; /** City name. Must not be empty; ViaCEP itself rejects values shorter than 3 characters. */ city: string; /** Street name or part of it. Must not be empty; ViaCEP itself rejects values shorter than 3 characters. */ street: string; }; /** * The address `getCepInfoByAddress` looks up, the 2.3.0 name of `GetCepInfoByAddressParams`. * * @deprecated Use `GetCepInfoByAddressParams` instead. */ type GetCepInfoByAddressOptions = GetCepInfoByAddressParams; /** * Looks every CEP of a Brazilian street up on the ViaCEP API. * * @param {GetCepInfoByAddressParams} params - The address to look up. * @param {string} params.federalUnit - The two letter state code (e.g. "SP"). * @param {string} params.city - The city name. * @param {string} params.street - The street name, or part of it. * @returns {Promise} Every address matching the query. * @throws {GetCepInfoByAddressValidationError} When the UF, city or street is missing or invalid. * A `params` that is not an object at all (omitted, `null`, a string) and a `federalUnit` that is * not a string reject this way too, rather than with a raw `TypeError`. * @throws {GetCepInfoByAddressNotFoundError} When no address matches the query. * @throws {GetCepInfoByAddressError} When ViaCEP answers with an HTTP error status. A request * that cannot be performed at all rejects with the underlying `fetch` error instead. * * @example * ```typescript * await getCepInfoByAddress({ federalUnit: "MG", city: "Ouro Preto", street: "Rua Direita" }); * // [ * // { * // cep: "35411-152", * // logradouro: "Rua Direita", * // complemento: "", * // unidade: "", * // bairro: "Riacho (Amarantina)", * // localidade: "Ouro Preto", * // uf: "MG", * // estado: "Minas Gerais", * // regiao: "Sudeste", * // ibge: "3146107", * // gia: "", * // ddd: "31", * // siafi: "4921" * // } * // ] * ``` * * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/tudo-sobre-cep * @see Based on: https://viacep.com.br/ * ViaCEP, the service queried. A third-party service, not a Correios one. */ export declare const getCepInfoByAddress: (params: GetCepInfoByAddressParams) => Promise; //#endregion //#region src/get-certidao-info/get-certidao-info.d.ts /** * The nine books (tipo do livro) a matrícula de registro civil can point to, in the order of the * codes 1 to 9. `getCertidaoInfo` names the book of a matrícula with one of these, and * `isValidCertidao` accepts a list of them. * * The in-force art. 473, V of the Código Nacional de Normas da Corregedoria Nacional de Justiça * lists only the codes 1 to 7, and no CNJ primary text reachable today publishes the other two: * the Anexo IV of the revoked Provimento CNJ nº 63/2017 lists the same seven. The codes 8 * (`"emancipation"`) and 9 (`"interdiction"`) come from the `Based on:` references below: ghiorzi.org and * validation-br both print the nine book list. They are kept because matrículas carrying them * circulate. */ type CertidaoType = "birth" | "marriage" | "religious-marriage" | "death" | "stillbirth" | "banns" | "other" | "emancipation" | "interdiction"; /** The fields `getCertidaoInfo` reads out of the matrícula of a certidão de registro civil. */ type CertidaoInfo = { /** The 6 digit CNS (Código Nacional de Serventia) of the serventia that issued the act. */ registryCns: string; /** * Acervo the book belongs to: `"01"` the serventia's own acervo; `"02"` and up, one per * incorporated acervo. Art. 473, §§ 3º to 5º splits the incorporated ones by the date the * origin serventia was extinguished or deactivated: up to 31 December 2009 the matrícula * carries the CNS of the incorporating unit and an acervo code from `"02"` up, one per * incorporation in their numeric order; from 1 January 2010 on it carries the CNS of the * incorporated unit itself and the acervo code `"01"`, counted as that unit's own acervo. When * one acervo is split between two or more successor serventias, each of them uses its own CNS * with the acervo code `"02"`. */ acervo: string; /** Service rendered by the serventia, always "55", the registro civil das pessoas naturais. */ service: string; /** Four digit year the act was recorded. */ year: number; /** The book the act belongs to, as an English name. */ type: CertidaoType; /** Raw book code, 1 to 9, as printed in the fifteenth position of the matrícula. */ typeCode: number; /** The 5 digit book (livro) number, zero padded. */ book: string; /** The 3 digit page (folha) number, zero padded. */ page: string; /** The 7 digit term (termo) number, zero padded. */ term: string; /** The 2 modulus 11 check digits of the matrícula. */ checkDigits: string; }; /** * Parses the matrícula of a certidão de registro civil into its fields. * * Accepts the same input forms as `isValidCertidao` and returns `null` when the matrícula is * not valid, which includes a serviço other than the `55` art. 473, III fixes for the registro * civil das pessoas naturais, and a book code that is not one of the nine books defined by the * Provimento, since an unknown book cannot be named. * * Only a string is accepted: the 32 digits of a matrícula are more than a JavaScript number can * hold, so a numeric argument always gives `null` instead of being read as a rounded value. * * @param {string} value - The matrícula value to be parsed. * @returns {CertidaoInfo | null} The parsed matrícula, or `null` when it is not valid. * * @example * ```typescript * getCertidaoInfo("104539 01 55 2013 1 00012 021 0000123 21"); * // { registryCns: "104539", acervo: "01", service: "55", year: 2013, type: "birth", * // typeCode: 1, book: "00012", page: "021", term: "0000123", checkDigits: "21" } * * getCertidaoInfo("invalid"); // null * ``` * * @see Official: https://atos.cnj.jus.br/atos/detalhar/5243 * Código Nacional de Normas da Corregedoria Nacional de Justiça - Foro Extrajudicial (Provimento * CNJ nº 149/2023), art. 473 as currently published: the in-force layout of the 32 digit * matrícula. Inciso II and §§ 1º and 3º to 5º carry the redação of the Provimento CN nº 237, de * 13/07/2026; the rest of the article, § 2º included, and the digit layout this library depends * on, come from the Provimento CN nº 182, de 17/09/2024. * @see Official: https://atos.cnj.jus.br/atos/detalhar/1311 * Provimento CNJ nº 2, de 27/04/2009, art. 1º and 2º, which instituted the modelos únicos de * certidão and ordered that "as certidões passarão a consignar matrícula que identifica o código * nacional da serventia, o código do acervo, o tipo do serviço prestado, o tipo do livro, o número * do livro, o número da folha, o número do termo e o digito verificador" (revoked; historical). * @see Official: https://atos.cnj.jus.br/atos/detalhar/1310 * Provimento CNJ nº 3, de 17/11/2009, art. 7º, which is where that matrícula first got its digit * structure: "a matrícula, de inserção obrigatória nas certidões (primeira e demais vias) emitidas * pelos Cartórios de Registro Civil das Pessoas Naturais a partir de 1º de janeiro de 2010, é * formada pelos seguintes elementos", incisos I to IX fixing the same 6 + 2 + 2 + 4 + 1 + 5 + 3 + * 7 + 2 positions art. 473 carries today (revoked; historical). * @see Based on: http://ghiorzi.org/DVnew.htm * Worked example of the two check digits (sums 288 and 309). * @see Based on: https://github.com/klawdyo/validation-br/blob/feat-certidao/src/certidao.ts * Reference implementation, and the source of the matrículas used as test vectors. * @see Based on: https://github.com/geekcom/validator-docs/blob/master/src/validator-docs/Rules/Certidao.php * Third reference implementation agreeing on the weights and on the remainder of 10 read as 1. */ export declare const getCertidaoInfo: (value: string) => CertidaoInfo | null; //#endregion //#region src/get-cfop/get-cfop.d.ts /** * A CFOP (Código Fiscal de Operações e Prestações) code. */ type Cfop = { /** The 4 digit CFOP code. */ code: string; /** The official operation description. */ description: string; }; /** * Looks a CFOP (Código Fiscal de Operações e Prestações) code up in the official table. * * The table is the consolidated Anexo II of Convênio SINIEF s/nº 1970, the text in force * (current wording given by Ajuste SINIEF 03/24, last amended by Ajuste SINIEF 39/25). * * Only operable codes are in the table: the group and subgroup headings of the official * nomenclature, the codes ending in "00" and "50" (1000, 1100, 1150, 5350, ...), are section * titles rather than codes a document can carry, so they give `null`. * * A string is only read as a code when it is written in one of the documented forms: the 4 * digits, or the `N.NNN` form the annex prints, with a single separator between the groups * and optional surrounding whitespace. Anything else (`"abc5102"`) is rejected instead of * having its digits picked out. A number is only read as a code when it is a non-negative * safe integer, since a sign, a decimal point or a rounded magnitude would otherwise be read * as a code the caller never wrote. * * No CFOP code starts with a zero, its first digit is the operation group (1 to 7), so nothing * is ever padded here: a number and the string of the same digits are read identically, and a * value narrower than 4 digits is not a code at all. * * @param {string|number} value - The CFOP code to look up, with or without the `N.NNN` mask, * e.g. `"1.101"`, `"1101"` or `1101`. * @returns {Cfop|null} The matching CFOP entry, or null when the code is unknown or * invalid. * * @example * ```typescript * getCfop("1101"); // { code: "1101", description: "Compra para industrialização ou produção rural" } * getCfop("1.101"); // { code: "1101", description: "Compra para industrialização ou produção rural" } * getCfop("0000"); // null * getCfop("5350"); // null (a subgroup heading, not an operable code) * getCfop("abc5102"); // null (not a documented form) * getCfop(-5102); // null (not a non-negative safe integer) * ``` * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cfop_cvsn_1-6.24 * Anexo II of Convênio SINIEF s/nº 1970, the CFOP table in force. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cvsn_70 * Convênio SINIEF s/nº 1970, the consolidated text the annex belongs to. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2025/AJ039_25 * Ajuste SINIEF 39/25, the last amendment the annex carries (CFOP 7.667, from 01.02.26). * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2001/AJ_007_01 * Ajuste SINIEF 07/01, the historical text that gave the CFOP its 4 digit form. */ export declare const getCfop: (value: string | number) => Cfop | null; //#endregion //#region src/get-cities/get-cities.d.ts /** * Returns a list of city names for a given Brazilian state, or all cities if no state is specified. * * If a state code is provided, the function returns its cities sorted with `localeCompare` * in the "pt-BR" locale. If no state is provided, it returns all cities from all states, * sorted the same way so accented names land where a Brazilian reader expects them (the * combined, sorted list is computed once and cached; every call returns a fresh copy). * * Every falsy `state` asks for the full list, so `getCities(null)` and `getCities("")` return * every city. The sibling `getMunicipalities` is stricter and only reads an omitted (or * `undefined`) state code that way, returning `[]` for `null` and `""`. * * The state code is matched exactly, case included: `getCities("sp")` returns `[]` where * `getCities("SP")` returns the 645 São Paulo cities. `getCities` and `getMunicipalities` are * the only state-taking lookups that are case-sensitive; `getStateNameByCode`, * `getTimezoneByState`, `getAreaCodesByState` and `getMunicipality` all fold case. * * @deprecated Use `getMunicipalities` instead. * * @param {StateCode} [state] - The code of the Brazilian state to filter cities by. Optional. * @returns {string[]} An array of city names, sorted alphabetically. Returns an empty array if the state is not found. * * @example * ```typescript * getCities("SP")[0]; // "Adamantina" * getCities("sp"); // [] (the state code is case-sensitive here) * getCities().length; // every city of every state * ``` * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ export declare const getCities: (state?: StateCode) => string[]; //#endregion //#region src/get-cnae/get-cnae.d.ts /** * A CNAE (Classificação Nacional de Atividades Econômicas) subclass. */ type Cnae = { /** The 7 digit subclass code, without the mask. Use `formatCnae` for the `NNNN-N/NN` form. */ code: string; /** The official subclass description. */ description: string; }; /** * Looks a CNAE (Classificação Nacional de Atividades Econômicas) subclass code up in the * official CNAE-Subclasses 2.3 table, the current subclass revision of CNAE 2.0. * * A string is only read as a code when it is written in one of the documented forms: the 7 * digits, or the `NNNN-N/NN` mask, with a single separator (space, `.`, `-` or `/`) between the groups and optional * surrounding whitespace. Anything else (`"0111abc301"`) is rejected instead of having its * digits picked out. A number is only read as a code when it is a non-negative safe integer, * since a sign, a decimal point or a rounded magnitude would otherwise be read as a code the * caller never wrote. * * A CNAE subclass code is always 7 digits and its leading zeros are part of it, so a value * written as bare digits is left padded with zeros to 7 whether it comes as a string or as a * number: `111301`, `"111301"` and `"0111301"` are the same code. A masked value already * carries its separators and is read as written. * * `code` comes back as those 7 bare digits, like every other lookup of this library; pass it to * `formatCnae` for the `NNNN-N/NN` form. * * @param {string|number} value - The CNAE code to look up, with or without the * `NNNN-N/NN` mask. * @returns {Cnae|null} The matching subclass, or null when the code is unknown or invalid. * * @example * ```typescript * getCnae("6201-5/01"); // { code: "6201501", description: "DESENVOLVIMENTO DE PROGRAMAS DE COMPUTADOR SOB ENCOMENDA" } * getCnae(111301); // { code: "0111301", description: "CULTIVO DE ARROZ" } (padded to 7 digits) * getCnae("111301"); // { code: "0111301", description: "CULTIVO DE ARROZ" } (padded to 7 digits) * getCnae("0000000"); // null * getCnae("0111abc301"); // null (not a documented form) * formatCnae(getCnae("6201501")?.code); // "6201-5/01" (the mask is the formatter's job) * getCnae(-111301); // null (not a non-negative safe integer) * ``` * * @see Official: https://servicodados.ibge.gov.br/api/v2/cnae/subclasses * @see Official: https://concla.ibge.gov.br/busca-online-cnae.html * CONCLA's CNAE search and structure browser, which publishes CNAE-Subclasses 2.3. */ export declare const getCnae: (value: string | number) => Cnae | null; //#endregion //#region src/get-holidays/get-holidays.d.ts /** The class a holiday returned by `getHolidays` falls into. */ type HolidayType = "national" | "state" | "optional" | "religious"; /** One holiday returned by `getHolidays`. */ type Holiday = { /** The holiday name in Brazilian Portuguese, e.g. `"Sexta-feira Santa"`. */ name: string; /** The holiday date, at local midnight of the requested year. */ date: Date; /** How the holiday is observed: national, state, optional (ponto facultativo) or religious. */ type: HolidayType; }; /** The object form `getHolidays` accepts, naming the year to list and, optionally, the state whose holidays are added. */ type GetHolidaysParams = { /** The four digit year to list holidays for. Must be an integer between 1900 and 2099. */ year: number; /** Two letter state code whose state holidays are added to the national ones (default: national holidays only). */ stateCode?: StateCode; }; /** * The object form `getHolidays` accepts, the 2.3.0 name of `GetHolidaysParams`. * * @deprecated Use `GetHolidaysParams` instead. */ type GetHolidaysOptions = GetHolidaysParams; /** * Retrieves all Brazilian holidays for a given year. * * The function returns both fixed holidays (that occur on the same date every year) * and movable holidays (that are calculated based on Easter Sunday). * If a state code is provided, state-specific holidays are also included. * * Holidays are returned sorted by date (chronological order). Results are memoized * per `year`/`stateCode` combination; the returned array (and each `Holiday.date`) is * always a fresh copy, so mutating it never affects subsequent calls. * * If `stateCode` is provided but is not a valid/known state code, it is ignored and * only national holidays are returned (this mirrors passing no `stateCode` at all, * and is kept for backwards compatibility). The lookup is an own-property one, so a * prototype-chain key such as `"__proto__"`, `"constructor"` or `"toString"` is an unknown * state code like any other rather than a crash. * * When a state entry falls on the same date as a national one and carries the same name, the * state entry replaces it instead of being listed twice: this is how the Distrito Federal's * Corpus Christi, a feriado under Lei distrital nº 72/1989 art. 1º parágrafo único, comes back * typed `"state"` for `stateCode: "DF"` while staying `"optional"` everywhere else. * * Only one state holiday per UF is a feriado civil under Lei 9.093/1995 art. 1º, II, which * authorizes "a data magna do Estado fixada em lei estadual" in the singular; the other entries * of `STATE_HOLIDAYS` rest on ordinary state laws and are reported because they are observed in * practice. The date returned is the statutory one. Santa Catarina's two holidays are the only * observance shift the table models: each moves to the following Sunday when it falls Monday to * Friday, 11 August from 2005 on, when Lei SC nº 13.408/2005 extended the transfer to it, and * 25 November from 1999 on, when Lei SC nº 11.213/1999 first introduced it, except in 2004, the * year art. 3º of Lei SC nº 12.906/2004 left it without a transfer clause. Outside those ranges * each holiday stays on 11 August or 25 November. Acre's Tuesday-to-Thursday shift and the Goiás decrees * that may move 26/07 and 28/10 are not modelled, because neither can be resolved from a year * alone. * * @param {number} year - The year for which to retrieve holidays (must be between 1900 and 2099) * @returns {Holiday[]} An array of holidays sorted by date * * @example * ```typescript * // Get all national holidays * const holidays = getHolidays(2024); * * // Get holidays for a specific state * const spHolidays = getHolidays({ year: 2024, stateCode: 'SP' }); * ``` * * The national holiday laws are cited below; the state holiday laws are cited individually, one * `@see` per holiday, in `src/get-holidays/constants.ts`. * * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l0662.htm * Lei 662/1949, the base national holidays law (Ano novo, Dia do trabalhador, Independência do * Brasil, Proclamação da República, Natal). * @see Official: https://www.planalto.gov.br/ccivil_03/leis/2002/l10607.htm * Lei 10.607/2002, rewrote that art. 1º into the list in force: it added Finados (2 November) * to the national holidays and folded in Tiradentes (21 April), already national since art. 3º * of Lei 1.266/1950, which its own art. 3º revoked. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/L1266.htm * Lei 1.266/1950, art. 3º, which first made Tiradentes a national holiday: "É feriado nacional o * dia 21 de abril, consagrado à glorificação de Tiradentes". Revoked by Lei 10.607/2002 only * after that law had carried 21 April into Lei 662/1949. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l6802.htm * Lei 6.802/1980, declared Nossa Senhora Aparecida (12 October) a national holiday. * @see Official: https://www.planalto.gov.br/ccivil_03/_ato2023-2026/2023/lei/l14759.htm * Lei 14.759/2023, nationalized Dia da Consciência Negra (20 November) from * `CONSCIENCIA_NEGRA_NATIONAL_SINCE_YEAR` (2024) onward. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l9093.htm * Lei 9.093/1995, the framework law authorizing one state civil holiday (art. 1º, II, "a data * magna do Estado fixada em lei estadual") and up to four municipal religious holidays, "neste * incluída a Sexta-Feira da Paixão" (art. 2º); the legal basis for the data magna entries of * `STATE_HOLIDAYS`. * @see Official: https://www.in.gov.br/web/dou/-/portaria-mgi-n-11.460-de-29-de-dezembro-de-2025-678388627 * Portaria MGI nº 11.460/2025, the federal executive's annual calendar of feriados nacionais and * pontos facultativos, reissued every December. It is the source of the typing of three of the * four entries derived from Easter, which no federal law declares: "Paixão de Cristo (feriado * nacional)" (Easter minus 2, emitted as `"Sexta-feira Santa"` typed `national`), "Carnaval (ponto * facultativo)" (Easter minus 47) and "Corpus Christi (ponto facultativo)" (Easter plus 60), both * typed `optional`. Sexta-feira Santa has no statutory basis of its own: Lei 9.093/1995 art. 2º * places it among the *municipal* religious holidays, and it is typed `national` here because the * portaria observes it nationwide. The fourth entry, Easter Sunday itself, is emitted as * `"Páscoa"` typed `religious` and has no normative basis at all: the portaria never mentions it, * no federal law declares it, and its date is derived arithmetically by `resolveStateHolidayDate` * with the Meeus/Jones/Butcher algorithm. It is a convenience entry, listed because callers * computing a liturgical calendar expect it, not because it is a holiday anyone observes as a day * off. */ export declare function getHolidays(year: number): Holiday[]; /** * Retrieves all Brazilian holidays for a given year, optionally including the holidays of a * state. See the overload taking a year for the full documentation. * * @param {GetHolidaysParams} options - The year to list holidays for and, optionally, the state whose holidays are added * @returns {Holiday[]} An array of holidays sorted by date */ export declare function getHolidays(options: GetHolidaysParams): Holiday[]; //#endregion //#region src/get-iban-info/get-iban-info.d.ts /** The fields `getIbanInfo` reads out of a Brazilian IBAN. */ type IbanInfo = { /** ISO 3166-1 alpha-2 country code. Always `"BR"`, the only country this parser supports. */ countryCode: "BR"; /** The 2 digit ISO 7064 MOD 97-10 check digits. */ checkDigits: string; /** The 8 digit ISPB (Identificador do Sistema de Pagamentos Brasileiro) of the institution. */ bankIspb: string; /** The 5 digit branch (agência) number, zero-padded. */ branch: string; /** The 10 digit account (conta) number, zero-padded. */ account: string; /** * The 1 letter account type, as published in the "Dicionário de Tipos" of the Catálogo de * Mensagens e de Arquivos do SFN. `"C"` (conta corrente) and `"P"` (conta poupança) are the * usual values, but any letter is allowed. */ accountType: string; /** * The 1 character owner indicator, distinguishing co-owners of the same account: `"1"` for * the first or only holder up to `"9"` for the ninth, then `"A"` to `"Z"` from the tenth. */ owner: string; }; /** * Parses a Brazilian IBAN (International Bank Account Number) into its fields. * * The 29 character Brazilian IBAN is laid out as 2 (country code, always `BR`) + 2 (ISO 7064 * MOD 97-10 check digits) + 8 (ISPB) + 5 (branch) + 10 (account) + 1 (account type, any letter, * usually `C` for conta corrente or `P` for conta poupança) + 1 (owner indicator, `1` to `9` * then `A` to `Z`). Only * Brazilian IBANs are supported: the field layout of the other ISO 13616 countries is out of * scope, so a well-formed non `BR` IBAN also returns `null`. * * Accepts the same input forms as `isValidIban`, compact or in the ISO 13616 print format (groups * of 4 split by a single whitespace, `.`, `-` or `/`), in either case with optional surrounding * whitespace and in any case, and returns `null` whenever `isValidIban` would return `false`, * including a value carrying a separator away from a group boundary, a run of separators or any * character other than letters and digits. * * @param {string} value - The IBAN to be parsed. * @returns {IbanInfo|null} The parsed IBAN, or `null` when it is not a valid Brazilian IBAN. * * @example * ```typescript * getIbanInfo("BR1500000000000010932840814P2"); * // { * // countryCode: "BR", * // checkDigits: "15", * // bankIspb: "00000000", * // branch: "00001", * // account: "0932840814", * // accountType: "P", * // owner: "2", * // } * * getIbanInfo("BR15 0000 0000 0000 1093 2840 814P 2"); // same result (grouping spaces) * getIbanInfo("BR15-0000-0000-0000-1093-2840-814P-2"); // same result (any of the mask characters) * getIbanInfo("DE89370400440532013000"); // null (non Brazilian IBAN) * getIbanInfo("BR1500000000000010932840814P3"); // null (bad check digits) * getIbanInfo("BR15 000 00000 0000 1093 2840 814P 2"); // null (a separator inside a group) * ``` * * @see Official: https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf * Circular BCB nº 3.625/2013 * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf * Diretrizes de Implementação do IBAN no Brasil * @see Official: https://www.iso.org/standard/81090.html * ISO 13616-1:2020 (IBAN structure) * @see Official: https://www.iso.org/standard/31531.html * ISO/IEC 7064:2003 (MOD 97-10 check digit algorithm) */ export declare const getIbanInfo: (value: string) => IbanInfo | null; //#endregion //#region src/_internals/constants/legal-nature-categories.d.ts /** The CONCLA category (natureza jurídica group) a legal nature code belongs to. */ type LegalNatureCategory = { /** The category code, the first digit shared by every legal nature code in the group. */ code: "1" | "2" | "3" | "4" | "5"; /** The official category title in Portuguese, per IBGE/CONCLA. */ description: string; }; //#endregion //#region src/get-legal-nature/get-legal-nature.d.ts /** * A Brazilian legal nature (natureza jurídica) entry. * * `legacy` discriminates the entry: `false` for the 92 codes of the CONCLA 2021 table, the ones * in force, and `true` for the 8 a past revision of the table retired, which carry the extra * `currentCode` field. */ type LegalNature = { /** The 4 digit legal nature code, without formatting. */ code: string; /** The official description in Portuguese, per IBGE/CONCLA. */ description: string; /** The CONCLA category the code belongs to, given by its first digit. */ category: LegalNatureCategory; } & ({ /** `false` when the code is one of the 92 the CONCLA 2021 table publishes. */ legacy: false; } | { /** `true` when a past revision of the CONCLA table retired the code. */ legacy: true; /** * The code this legacy one corresponds to today, per the CONCLA correspondence * spreadsheets, or `null` when the revision that retired it published no successor. */ currentCode: string | null; }); /** * Looks a Brazilian legal nature (natureza jurídica) code up. * * The usual mask characters (hyphens, dots, whitespace) are stripped before the lookup, from a * number as well as from a string, so `getLegalNature(206.2)` resolves like `getLegalNature("206.2")`. * * No legal nature code starts with a zero, its first digit is the CONCLA category (1 to 5), so * nothing is ever padded here: a number and the string of the same digits are read identically, * and a value narrower than 4 digits is not a code at all. * * The entry also carries the CONCLA category of the code, the group the table lists it under, * taken from its first digit: 1 Administração Pública, 2 Entidades Empresariais, 3 Entidades * sem Fins Lucrativos, 4 Pessoas Físicas and 5 Organizações Internacionais e Outras * Instituições Extraterritoriais. * * A code a past revision of the table retired is still looked up, because it keeps appearing in * records filed while it was in force, and comes back with `legacy: true` and the `currentCode` * it corresponds to today per the CONCLA correspondence spreadsheets (`null` when the revision * that retired it published no successor). The 92 codes in force have `legacy: false` and no * `currentCode`. * * @param {string|number} value - The legal nature code to look up, with or without formatting. * @returns {LegalNature|null} The matching legal nature entry, or null when the code is unknown * or invalid. * * The CONCLA table page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser; the detailed structure PDF next to it is served * normally. * * @see Official: https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021 * @see Official: https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf * * @example * ```typescript * getLegalNature("2062"); * // { * // code: "2062", * // description: "Sociedade Empresária Limitada", * // category: { code: "2", description: "Entidades Empresariais" }, * // legacy: false, * // } * getLegalNature("2208"); * // { * // code: "2208", * // description: "Entidade Binacional Itaipu", * // category: { code: "2", description: "Entidades Empresariais" }, * // legacy: true, * // currentCode: "2275", * // } * getLegalNature("3123")?.legacy; // true (Partido Político, retired without a successor) * getLegalNature("206-2")?.code; // "2062" * getLegalNature(206.2)?.category.description; // "Entidades Empresariais" * getLegalNature("0000"); // null * ``` */ export declare const getLegalNature: (value: string | number) => LegalNature | null; //#endregion //#region src/get-legal-natures/get-legal-natures.d.ts /** The object form `getLegalNatures` accepts, saying whether the legacy codes are listed too. */ type GetLegalNaturesParams = { /** * Whether the 8 codes a past revision of the CONCLA table retired are listed alongside the 92 * in force (default: `false`). */ includeLegacy?: boolean; }; /** * Returns every Brazilian legal nature (natureza jurídica) published by the CONCLA. * * Only the 92 codes of the Tabela de Natureza Jurídica 2021, the ones in force, are listed by * default. Pass `{ includeLegacy: true }` to add the 8 a past revision of the table retired, which * `isValidLegalNature` keeps accepting and `getLegalNature` keeps looking up because they still * appear in records filed while they were in force. * * @param {GetLegalNaturesParams} [params] - Optional listing options. * @param {boolean} [params.includeLegacy] - Whether to add the retired codes. Defaults to `false`. * @returns {Record} A fresh object mapping each 4 digit code to its description. * * @example * ```typescript * getLegalNatures()["2062"]; // "Sociedade Empresária Limitada" * Object.keys(getLegalNatures()).length; // 92 * getLegalNatures()["2208"]; // undefined (retired by a past revision) * getLegalNatures({ includeLegacy: true })["2208"]; // "Entidade Binacional Itaipu" * Object.keys(getLegalNatures({ includeLegacy: true })).length; // 100 * ``` * * The CONCLA table page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser; the detailed structure PDF next to it is served * normally. * * @see Official: https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021 * @see Official: https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf */ export declare const getLegalNatures: (params?: GetLegalNaturesParams) => Record; //#endregion //#region src/get-legal-natures-by-category/get-legal-natures-by-category.d.ts /** * The options `getLegalNaturesByCategory` accepts, saying whether the legacy codes of the category * are listed too. */ type GetLegalNaturesByCategoryOptions = { /** * Whether the codes of the category that a past revision of the CONCLA table retired are listed * alongside the ones in force (default: `false`). */ includeLegacy?: boolean; }; /** * Retrieves every Brazilian legal nature (natureza jurídica) of a CONCLA category. * * The category is the first digit of the four digit code, the heading the table lists the code * under: 1 Administração Pública, 2 Entidades Empresariais, 3 Entidades sem Fins Lucrativos, * 4 Pessoas Físicas and 5 Organizações Internacionais e Outras Instituições Extraterritoriais. * It is accepted as a string or as a number, so `"2"` and `2` return the same list. * * Only the codes in force are listed by default. Pass `{ includeLegacy: true }` to add the ones a * past revision of the table retired (2076, 2100 and 2208 in category 2, 3042, 3050, 3093 and 3123 * in category 3, 5002 in category 5), which come back with `legacy: true` and the `currentCode` * they correspond to today. The result is in ascending code order, since the table is keyed by the * codes themselves, and is a fresh array of fresh entries on every call. * * @param {string|number} category - The category code, `"1"` through `"5"` or 1 through 5. * @param {GetLegalNaturesByCategoryOptions} [options] - Optional listing options. * @param {boolean} [options.includeLegacy] - Whether to add the retired codes. Defaults to `false`. * @returns {LegalNature[]} The legal natures of the category, sorted by code, or an empty array * when the category is unknown or the input is invalid. * * The CONCLA table page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser; the detailed structure PDF next to it is served * normally. * * @see Official: https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021 * @see Official: https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf * * @example * ```typescript * getLegalNaturesByCategory("4")[0]; * // { * // code: "4014", * // description: "Empresa Individual Imobiliária", * // category: { code: "4", description: "Pessoas Físicas" }, * // legacy: false, * // } * getLegalNaturesByCategory(4).length; // 6 * getLegalNaturesByCategory("2").length; // 30 * getLegalNaturesByCategory("2", { includeLegacy: true }).length; // 33 * getLegalNaturesByCategory("9"); // [] * ``` */ export declare const getLegalNaturesByCategory: (category: string | number, options?: GetLegalNaturesByCategoryOptions) => LegalNature[]; //#endregion //#region src/get-municipalities/get-municipalities.d.ts /** * Returns Brazilian municipalities published by the IBGE, optionally filtered by state. * * If `stateCode` is provided, only municipalities of that state are returned. If it is * omitted, every municipality of every state is returned, sorted with `localeCompare` in the * "pt-BR" locale so accented names land where a Brazilian reader expects them. Every per-state * list is sorted the same way. * * Only an omitted (or `undefined`) `stateCode` asks for the full list: any other value that is * not a known state code, `null` and `""` included, returns `[]`. The sibling `getCities` is * looser and treats every falsy `state` as "no state given", so `getCities(null)` returns the * full list where `getMunicipalities(null)` returns `[]`. * * The state code is matched exactly, case included: `getMunicipalities("sp")` returns `[]` where * `getMunicipalities("SP")` returns the 645 São Paulo municipalities. `getMunicipalities` and * `getCities` are the only state-taking lookups that are case-sensitive; `getStateNameByCode`, * `getTimezoneByState`, `getAreaCodesByState` and `getMunicipality` all fold case. * * @param {StateCode} [stateCode] - The two letter code of the Brazilian state to filter by. * @returns {Municipality[]} A fresh array of fresh `Municipality` objects. Empty when * `stateCode` is not a known state. * * @example * ```typescript * getMunicipalities("SP")[0]; // { code: "3500105", name: "Adamantina", stateCode: "SP" } * getMunicipalities().length; // every municipality of every state * getMunicipalities("ZZ"); // [] * getMunicipalities("sp"); // [] (the state code is case-sensitive here) * getMunicipalities(null); // [] (only an omitted state code asks for the full list) * ``` * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ export declare const getMunicipalities: (stateCode?: StateCode) => Municipality[]; //#endregion //#region src/get-municipality/get-municipality.d.ts /** The `getMunicipality` query by IBGE municipality code. */ type GetMunicipalityByCodeParams = { /** The 7 digit IBGE municipality code, as a string or a number. */ code: string | number; }; /** The `getMunicipality` query by municipality name and state code. */ type GetMunicipalityByNameParams = { /** The municipality name, accents and casing ignored. */ municipalityName: string; /** The two letter state code the municipality belongs to, e.g. "SP". */ uf: string; }; /** The two ways `getMunicipality` can be queried: by IBGE code, or by municipality name and state code. */ type GetMunicipalityParams = GetMunicipalityByCodeParams | GetMunicipalityByNameParams; /** * The `getMunicipality` query by IBGE municipality code, the 2.3.0 name of * `GetMunicipalityByCodeParams`. * * @deprecated Use `GetMunicipalityByCodeParams` instead. */ type GetMunicipalityByCodeOptions = GetMunicipalityByCodeParams; /** * The `getMunicipality` query by municipality name and state code, the 2.3.0 name of * `GetMunicipalityByNameParams`. * * @deprecated Use `GetMunicipalityByNameParams` instead. */ type GetMunicipalityByNameOptions = GetMunicipalityByNameParams; /** * The two ways `getMunicipality` can be queried, the 2.3.0 name of `GetMunicipalityParams`. * * @deprecated Use `GetMunicipalityParams` instead. */ type GetMunicipalityOptions = GetMunicipalityParams; /** * Looks a Brazilian municipality up by its IBGE code in the offline IBGE "localidades" dataset. * * A `code` given as a number must be a non-negative integer: a sign and a decimal point are not * digits, so `-3550308` and `355030.8` are rejected instead of being read as `3550308`. * * @deprecated Use `getMunicipalityByCode` instead, which is synchronous and offline; matching a * municipality by name is up to the application, over `getMunicipalities`. * * @param {GetMunicipalityByCodeParams} options - The `{ code }` query. * @returns {Promise<[string, string] | null>} A fresh `[name, uf]` pair, which the caller owns * and may mutate, or null when the code is malformed or unknown. * * @example * ```typescript * await getMunicipality({ code: "3550308" }); // ["São Paulo", "SP"] * await getMunicipality({ code: 3550308 }); // ["São Paulo", "SP"] * ``` * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ export declare function getMunicipality(options: GetMunicipalityByCodeParams): Promise<[string, string] | null>; /** * Looks a Brazilian municipality's IBGE code up in the offline IBGE "localidades" dataset. * * The name lookup ignores accents and casing, and every run of whitespace collapses into a * single space, so `"sao paulo"` matches `"São Paulo"`; a name written without the space does * not, since only the runs that are there collapse. The casing is folded to upper case, the * direction Unicode expands `"ß"` to `"SS"` in, so `"Paßos"` matches `"Passos"`. * * @deprecated Use `getMunicipalityByCode` instead, which is synchronous and offline; matching a * municipality by name is up to the application, over `getMunicipalities`. * * @param {GetMunicipalityByNameParams} options - The `{ municipalityName, uf }` query. * @returns {Promise} The 7 digit IBGE code, or null when the state code or the * municipality is unknown. * * @example * ```typescript * await getMunicipality({ municipalityName: "sao paulo", uf: "sp" }); // "3550308" * ``` * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ export declare function getMunicipality(options: GetMunicipalityByNameParams): Promise; /** * Looks a Brazilian municipality up in the offline IBGE "localidades" dataset, from a query * whose direction is only known at run time. * * Given a `code` it resolves the municipality name and its UF; given a `municipalityName` and a * `uf` it resolves the IBGE code. Validation failures and unknown municipalities are reported * as `null`. * * @deprecated Use `getMunicipalityByCode` instead, which is synchronous and offline; matching a * municipality by name is up to the application, over `getMunicipalities`. * * @param {GetMunicipalityParams} options - Either `{ code }` or `{ municipalityName, uf }`. * @returns {Promise<[string, string] | string | null>} The `[name, uf]` pair when looking up * by code, the IBGE code when looking up by name, or null when the municipality is unknown * (this includes `options` itself being missing or not an object, e.g. `null`, `undefined`, * an array or a primitive). * * @example * ```typescript * const lookUp = (options: GetMunicipalityParams) => getMunicipality(options); * * await lookUp({ code: "3550308" }); // ["São Paulo", "SP"] * ``` * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ export declare function getMunicipality(options: GetMunicipalityParams): Promise<[string, string] | string | null>; //#endregion //#region src/get-municipality-by-code/get-municipality-by-code.d.ts /** * Looks up a Brazilian municipality by its 7 digit IBGE code, published by the IBGE. * * A `code` given as a number must be a non-negative integer: a sign and a decimal point are * not digits, so `-3550308` and `355030.8` are rejected instead of being read as `3550308`. * * @param {string|number} code - The 7 digit IBGE municipality code, as a string or a number. * @returns {Municipality|null} A fresh copy of the matching municipality, or `null` when * `code` is not a 7 digit code or does not match any known municipality. * * @example * ```typescript * getMunicipalityByCode("3550308"); // { code: "3550308", name: "São Paulo", stateCode: "SP" } * getMunicipalityByCode(3550308); // { code: "3550308", name: "São Paulo", stateCode: "SP" } * getMunicipalityByCode("0000000"); // null * ``` * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ export declare const getMunicipalityByCode: (code: string | number) => Municipality | null; //#endregion //#region src/get-nfe-key-info/get-nfe-key-info.d.ts /** * The document models a DF-e access key can carry: `"55"` NF-e, `"57"` CT-e, `"58"` MDF-e, * `"62"` NFCom, `"63"` BP-e, `"64"` GTV-e, `"65"` NFC-e, `"66"` NF3e and `"67"` CT-e OS. * Spelled out instead of derived from `VALID_MODELS` because the allowlist is internal and API * Extractor cannot name it in the public report; the type test of `get-nfe-key-info.test.ts` pins * the two together so they cannot drift apart. */ type NfeKeyModel = "55" | "57" | "58" | "62" | "63" | "64" | "65" | "66" | "67"; /** The fields `getNfeKeyInfo` reads out of a DF-e access key (chave de acesso). */ type NfeKeyInfo = { /** Two letter code of the issuing state (UF), read from the IBGE UF code. */ stateCode: StateCode; /** Four digit issue year. */ year: number; /** Issue month, 1 to 12. */ month: number; /** The 14 digit CNPJ (or zero padded CPF) of the issuer. */ taxId: string; /** Document model: "55" NF-e, "57" CT-e, "58" MDF-e, "62" NFCom, "63" BP-e, "64" GTV-e, "65" NFC-e, "66" NF3e, "67" CT-e OS. */ model: NfeKeyModel; /** Document series, 0 to 999. */ series: number; /** Document number, 1 to 999999999. */ number: number; /** Emission type code (tpEmis), one of the codes the MOC of that model assigns. */ emissionType: number; /** * Site of the authorizer that received the document (`nSiteAutoriz`), 0 to 9. Only NFCom * (`"62"`) and NF3e (`"66"`) spend a digit of the key on it. */ authorizationSite?: number; /** The numeric code (cNF) drawn by the issuer: 7 digits for NFCom and NF3e, 8 for the rest. */ code: string; /** The modulo 11 check digit of the key. */ checkDigit: number; }; /** * Parses a DF-e (Documento Fiscal eletrônico) access key (chave de acesso) into its fields. * * Covers every document whose access key is the same 44 digit string: NF-e (modelo 55), NFC-e * (65), CT-e (57), MDF-e (58), CT-e OS (67), GTV-e (64), BP-e (63), NF3e (66) and NFCom (62). * Accepts the same input forms as `isValidNfeKey` (the printed mask of 4 digit groups, split by * whitespace, `.`, `-` or `/`, and the `NFe`, `CTe`, `MDFe`, `BPe`, `NF3e` and `NFCom` prefixes * of the XML `Id` attribute) and returns `null` when the key is not valid. * * The emission type (`tpEmis`) is checked against the codes the MOC of that model assigns, so * the accepted set changes with the model: 1 to 7 and 9 for NF-e and NFC-e, `{1, 3, 4, 5, 7, 8}` * for the CT-e, `{1, 5, 7, 8}` for the CT-e OS and `{1, 2, 7, 8}` for the GTV-e (8 is the * authorização pela SVC-SP of the CT-e MOC), `{1, 2, 3}` for the MDF-e and `{1, 2}` for the * BP-e, the NF3e and the NFCom. * * NFCom and NF3e write `nSiteAutoriz` in position 36 and only 7 digits of `cNF` after it, so * `authorizationSite` is filled for those two models and `code` is 7 characters long instead of * 8; every other model leaves `authorizationSite` out and reads an 8 digit `code`. * * For NF-e and NFC-e the numeric code is also checked against rule B03-10 of the NF-e MOC, * which forbids the twenty repeated and sequential codes it lists and a `cNF` equal to the * document number. That rule arrived with NT 2019.001, so it can turn down a key authorised * before it, and no other MOC states it, which is why it is not applied to the other models. * A document number of all zeros is turned down for every model, following the leiaute rather * than a choice of this library: `nNF` is typed `TNF` in `tiposBasico_v4.00.xsd`, whose pattern * is `[1-9]{1}[0-9]{0,8}`, and the Anexo I of every other model repeats the same regex for its * own number field (`nCT`, `nMDF`, `nBP`, `nNF`). * * @param {string} value - The access key value to be parsed. * @returns {NfeKeyInfo | null} The parsed access key, or `null` when it is not valid. * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf * Manual de Orientação do Contribuinte (MOC) NF-e, "chave de acesso". * @see Official: https://dfe-portal.svrs.rs.gov.br/NFE/Documentos * NF-e schema package (PL_010b, NT2025.002 v1.30): `tiposBasico_v4.00.xsd`, the `TNF` and * `TCodUfIBGE` types. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2007/AJ_009_07 * Ajuste SINIEF 09/07, cláusula primeira, caput: the CT-e, modelo 57. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2019/AJ036_19 * Ajuste SINIEF 36/19, cláusula primeira: the CT-e OS, modelo 67. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2020/ajuste-sinief-03-20 * Ajuste SINIEF 03/20, cláusula primeira: the GTV-e, modelo 64. * @see Official: https://dfe-portal.svrs.rs.gov.br/CTE/Documentos * CT-e MOC 4.00, Anexo I ("MOC CTe 4.00 Anexo I - Leiaute e Regras de Validação"): the `tpEmis` * domains D19, D27 and D15. Published by the SVRS dfe-portal, like the BP-e, NF3e and NFCom * manuals below; the cte.fazenda.gov.br manual index answers "Sistema temporariamente * indisponível" permanently. * @see Official: https://dfe-portal.svrs.rs.gov.br/BPE/Documentos * BP-e MOC 1.00b, Visão Geral and Anexo I: modelo 63. * @see Official: https://dfe-portal.svrs.rs.gov.br/NF3e/Documentos * NF3e MOC 1.00a, Visão Geral and Anexo I: modelo 66 and `nSiteAutoriz`. * @see Official: https://dfe-portal.svrs.rs.gov.br/NFCOM/Documentos * NFCom MOC 1.00a, Visão Geral and Anexo I: modelo 62 and `nSiteAutoriz`. * @see Based on: https://github.com/nfephp-org/sped-common/blob/master/src/Keys.php * NFePHP `Keys::build` reference implementation, source of the SP and RS test vectors. * @see Based on: https://github.com/vmarchesin/br-validate-dfe-access-key * Second reference implementation. * * @example * ```typescript * getNfeKeyInfo("35170458716523000119550010000000121000123458"); * // { stateCode: "SP", year: 2017, month: 4, taxId: "58716523000119", model: "55", * // series: 1, number: 12, emissionType: 1, code: "00012345", checkDigit: 8 } * * getNfeKeyInfo("invalid"); // null * ``` */ export declare const getNfeKeyInfo: (value: string) => NfeKeyInfo | null; //#endregion //#region src/get-pix-key-info/get-pix-key-info.d.ts /** The kinds of Pix key `getPixKeyInfo` recognizes. */ type PixKeyType = "cpf" | "cnpj" | "email" | "phone" | "evp"; /** A Pix key recognized by `getPixKeyInfo`, normalized to the canonical DICT form of its kind. */ type PixKeyInfo = { /** Which kind of Pix key the value was recognized as. */ type: PixKeyType; /** The key in the canonical DICT form for its kind. */ value: string; }; /** * Identifies a Pix key and normalizes it to the canonical form the DICT expects inside a BR * Code. * * The canonical forms are the ones listed in "Formatação das chaves do DICT no BR Code": * - `cpf`: 11 digits, no mask; * - `cnpj`: 14 characters, no mask, uppercase for the alphanumeric format; * - `email`: trimmed and lowercased, at most 77 characters; * - `phone`: E.164, `+55` followed by the DDD and the subscriber number, so at most 14 * characters. The manual registers a "número de telefone celular", so only mobile numbers * are recognized; a landline is not a Pix key. Masked, bare and `+55` prefixed inputs are * all accepted; * - `evp`: the random key, a lowercase UUID written with its punctuation (8-4-4-4-12 * hexadecimal digits). The DICT issues version 4 UUIDs, but neither the pattern the manual * registers nor its own example (`123e4567-e12b-12d1-a456-426655440000`, whose version * nibble is `1`) constrains the version, so the version and variant nibbles are not enforced. * * The CPF and the phone number are recognized by the way they are written, not only by the * digits they carry: a value is read as a CPF when it is the bare 11 digits or the documented * mask, and as a phone number when it holds nothing but digits, spaces and the `+`, `-`, `(`, * `)` and `.` of the usual masks. Surrounding text is not stripped away, so * `"abc123.456.789-09"` is not a CPF key. * * A value with a valid CNPJ check digit is read as a CNPJ, even when it starts with `0055` * (a phone key inside a BR Code always carries the `+55` prefix). An 11 digit value can be * read both as a CPF and as a mobile phone number: when it is valid as both, it is read as a * CPF, unless it was written as a phone number. A `+55`/`0055` prefix or a DDD between * parentheses falls outside the CPF forms above, so a value written that way is never read as * a CPF, even when its digits carry a valid CPF check digit. * * @param {string} value - The Pix key to be parsed. * @returns {PixKeyInfo|null} The normalized key, or `null` when the value is not a valid Pix key. * * @example * ```typescript * getPixKeyInfo("123.456.789-09"); // { type: "cpf", value: "12345678909" } * getPixKeyInfo("Fulano@Example.COM "); // { type: "email", value: "fulano@example.com" } * getPixKeyInfo("(11) 98765-4321"); // { type: "phone", value: "+5511987654321" } * getPixKeyInfo("71C7D9BE-4B85-4E43-9F1C-1F3B8B4E9A2D"); * // { type: "evp", value: "71c7d9be-4b85-4e43-9f1c-1f3b8b4e9a2d" } * getPixKeyInfo("51998259765"); // { type: "cpf", value: "51998259765" } (also a valid phone) * getPixKeyInfo("+5551998259765"); // { type: "phone", value: "+5551998259765" } * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT.html * DICT (Diretório de Identificadores de Contas Transacionais) API specification, key format * reference. * @see Official: https://github.com/bacen/pix-api * Pix (SPI) OpenAPI spec. */ export declare const getPixKeyInfo: (value: string) => PixKeyInfo | null; //#endregion //#region src/get-pix-payload-info/get-pix-payload-info.d.ts /** * How a Pix BR Code is meant to be presented for payment: `"dynamic"` when it carries a PSP * location or when the "Point of Initiation Method" object (`01`) is `"12"`, the value the * Manual do BR Code reads as "só pode ser utilizado uma vez"; `"static"` otherwise. */ type PixPointOfInitiation = "static" | "dynamic"; /** The fields `getPixPayloadInfo` reads out of a Pix BR Code. */ type PixPayloadInfo = { /** The Pix key of the receiver, present in a static payload. */ key?: string; /** URL of the dynamic payload, present instead of `key` in a dynamic one. */ url?: string; /** Free text the receiver wrote for the payer. */ description?: string; /** * The 8 digit ISPB of the "facilitador de serviço de saque" (`fss`, sub-object 26-03), * present only in a Pix Saque BR Code. */ withdrawalFacilitator?: string; /** Name of the receiver, at most 25 ASCII characters. */ merchantName: string; /** City of the receiver, at most 15 ASCII characters. */ merchantCity: string; /** Amount in BRL, absent when the payer types it. */ amount?: number; /** Transaction ID, absent when the payload carries the `***` marker. */ txid?: string; /** Whether the payload is presented as a single use one ("dynamic") or not ("static"). */ pointOfInitiation: PixPointOfInitiation; }; /** * Parses a Pix BR Code payload, the string behind a Pix QR Code and behind "Pix copia e cola". * * The payload is rejected when its TLV (tag-length-value) structure is malformed, when the CRC * does not match, when a mandatory object is missing or malformed, or when none of the * "Merchant Account Information" templates (IDs 26 to 51) carries the `br.gov.bcb.pix` GUI * together with either a key (static) or a URL (dynamic). * * The Pix key itself is not validated: the manual states a static QR Code can be generated * with a key that no longer exists in the DICT, so key ownership is only settled at payment * time. The "Additional Data Field Template" (ID 62) is mandatory in the BR Code table but * optional in the EMV® specification it refers to, so it is accepted when absent. The lengths * the manual reserves for the merchant name (25), the merchant city (15) and the `txid` (25) * are generator side limits, enforced by `generatePixPayload`; payloads in the wild routinely * overrun them, so they are not enforced here, and neither is the 77 character limit of the * Pix key field (26-01). * * Unreserved Templates (IDs 80 to 99) are ignored. The "QR Code composto" of Pix Automático * (Pix recorrente) writes its recurrence location in one of them: when such a payload also * carries a payment location in 26-25, as the composite example of the Pix manual does, it is * parsed here as an ordinary dynamic payload and its recurrence location is dropped, so a * consumer that has to tell the two apart cannot rely on this parser. Only a payload with no * Pix template at all in IDs 26 to 51 returns `null`. * * The merchant account information must carry exactly one of a Pix key (26-01) or a PSP * location (26-25); the location is checked with the same host and path rule * `generatePixPayload` applies. The "Point of Initiation Method" object (`01`) is advisory, as * the Manual do BR Code marks it `Uso: O` and only assigns a meaning to the value `"12"` * ("Se o valor 12 estiver presente, significa que o BR Code só pode ser utilizado uma vez"): * it may be absent from either shape, and only a value outside `{"11", "12"}` is rejected. * `pointOfInitiation` is reported as `"dynamic"` when the payload carries a PSP location or * when `01` is `"12"`, and as `"static"` otherwise. When the payload carries a PSP location the * transaction amount (54) and the `txid` (62-05) are ignored, as the manual mandates, because * the PSP location is the source of truth for both. * * A payload built around a Pix key that carries the transaction amount (54) must state an * amount greater than zero, unless it is a Pix Saque BR Code: §2.6 of the Pix manual puts the * ISPB of the "facilitador de serviço de saque" in sub-object 26-03 (`fss`) of the same * template this parser already reads, and states that "a presença do campo fss, com um ISPB * válido […] indica que esse é um QR Code para Pix Saque", whose amount is settled at payment * time. So `54` set to `"0"` or `"0.00"` is accepted together with `fss` and rejected without * it; that rejection is a deliberate restriction of this library, not a rule of the manual, * whose field table allows `"0"` in any payload. A `fss` that is not 8 digits is rejected, and * so is a `fss` written next to a PSP location: §2.7 of the Manual de Padrões para Iniciação do * Pix maps the dynamic QR Code to exactly two sub-objects, `00` (GUI) and `25` (URL), while * `fss` belongs to the static template of §2.6, whose §2.6.1 states that "não há funcionalidade * de Pix Troco para QR Codes estáticos, apenas para QR Codes dinâmicos". * * @param {string} value - The BR Code payload to be parsed. * @returns {PixPayloadInfo|null} The Pix data of the payload, or `null` when it is not a valid Pix * BR Code. * * @example * ```typescript * getPixPayloadInfo( * "00020126580014br.gov.bcb.pix0136123e4567-e12b-12d1-a456-426655440000" + * "5204000053039865802BR5913Fulano de Tal6008BRASILIA62070503***63041D3D", * ); * // { * // key: "123e4567-e12b-12d1-a456-426655440000", * // merchantName: "Fulano de Tal", * // merchantCity: "BRASILIA", * // pointOfInitiation: "static", * // } * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/spb_docs/ManualBRCode.pdf * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf * @see Official: https://github.com/bacen/pix-api * Pix (SPI) OpenAPI spec. * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT.html * DICT (Diretório de Identificadores de Contas Transacionais) API specification. */ export declare const getPixPayloadInfo: (value: string) => PixPayloadInfo | null; //#endregion //#region src/get-state-by-ibge-code/get-state-by-ibge-code.d.ts /** * Retrieves the Brazilian state whose 2-digit IBGE code ("cUF", the Código da Unidade da * Federação) matches the given value. * * The IBGE code is the same 2-digit UF code found in the first field of every DF-e access key * (chave de acesso) issued for any of the models `isValidNfeKey` covers: NF-e (55), NFC-e * (65), CT-e (57), MDF-e (58), CT-e OS (67), GTV-e (64), BP-e (63), NF3e (66) and NFCom (62). * * A `code` given as a number must be a non-negative integer: a sign and a decimal point are * not digits, so `-35` and `3.5` are rejected instead of being read as `35`. * * @param {string|number} code - The 2-digit IBGE UF code. Accepts a string or a non-negative * integer number, with any non-digit characters stripped before matching. * @returns {State|null} The matching `State` object, or `null` when `code` is not a known * IBGE UF code. * * @see Official: https://servicodados.ibge.gov.br/api/v1/localidades/estados * (IBGE Localidades API, field `id`) * @see Official: https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf * (Manual de Orientação do Contribuinte, "chave de acesso" / "Tabela do IBGE") * * @example * ```typescript * getStateByIbgeCode("35"); // { code: "SP", name: "São Paulo", regionCode: "SE", regionName: "Sudeste", ibgeCode: 35 } * getStateByIbgeCode(35); // { code: "SP", name: "São Paulo", regionCode: "SE", regionName: "Sudeste", ibgeCode: 35 } * getStateByIbgeCode("11"); // { code: "RO", name: "Rondônia", regionCode: "N", regionName: "Norte", ibgeCode: 11 } * getStateByIbgeCode("00"); // null * getStateByIbgeCode(""); // null * getStateByIbgeCode(-35); // null * ``` */ export declare const getStateByIbgeCode: (code: string | number) => State | null; //#endregion //#region src/get-state-code-by-name/get-state-code-by-name.d.ts /** * Retrieves the two-letter code (sigla) of a Brazilian state given its full name. * * The match is accent-insensitive, case-insensitive and ignores leading/trailing whitespace, * so `" são paulo "`, `"Sao Paulo"` and `"SÃO PAULO"` all resolve to `"SP"`. Every run of * internal whitespace collapses into a single space too, so `"Rio de Janeiro"` resolves to * `"RJ"`, while a name written without the space matches nothing: only the runs that are there * collapse, so `"saopaulo"` is not `"São Paulo"`. The casing is folded to lower case, the * direction that leaves `"ß"` alone instead of expanding it into `"SS"`, so `"Mato Großo"` is * not `"Mato Grosso"` either. * * @param {string} name - The full name of the state. * @returns {StateCode|null} The two-letter state code, or `null` when `name` does not match * any Brazilian state. * * @see Official: https://servicodados.ibge.gov.br/api/v1/localidades/estados * (IBGE Localidades API) * * @example * ```typescript * getStateCodeByName("São Paulo"); // "SP" * getStateCodeByName("sao paulo"); // "SP" * getStateCodeByName(" Rio de Janeiro "); // "RJ" * getStateCodeByName("Rio de Janeiro"); // "RJ" * getStateCodeByName("Neverland"); // null * ``` */ export declare const getStateCodeByName: (name: string) => StateCode | null; //#endregion //#region src/get-state-name-by-code/get-state-name-by-code.d.ts /** * Retrieves the full name of a Brazilian state given its two-letter code (sigla). * * The match is case-insensitive and ignores leading/trailing whitespace, so `"sp"`, `"SP"` * and `" Sp "` all resolve to `"São Paulo"`. * * @param {string} code - The two-letter state code. * @returns {StateName|null} The full state name, or `null` when `code` does not match any * Brazilian state. * * @see Official: https://servicodados.ibge.gov.br/api/v1/localidades/estados * (IBGE Localidades API) * * @example * ```typescript * getStateNameByCode("SP"); // "São Paulo" * getStateNameByCode("sp"); // "São Paulo" * getStateNameByCode(" Rj "); // "Rio de Janeiro" * getStateNameByCode("ZZ"); // null * ``` */ export declare const getStateNameByCode: (code: string) => StateName | null; //#endregion //#region src/get-states/get-states.d.ts /** * Retrieves a list of all Brazilian states with their codes and names. * * Returns an array of state objects containing the two-letter state code * and the full state name. The list is sorted by state name with `localeCompare` * in the "pt-BR" locale, so accented names land where a Brazilian reader expects * them: Pará, Paraíba, Paraná and Rio de Janeiro, Rio Grande do Norte, Rio Grande do Sul. * * Each call returns a fresh array of fresh objects, so mutating the result * (e.g. `getStates()[0].name = "X"`) never affects the underlying data or * subsequent calls. * * @returns {State[]} An array of all Brazilian states sorted by name * * @example * ```typescript * getStates()[0]; // { code: "AC", name: "Acre", regionCode: "N", regionName: "Norte", ibgeCode: 12 } * ``` * * @see Official: https://servicodados.ibge.gov.br/api/docs/localidades */ export declare const getStates: () => State[]; //#endregion //#region src/get-timezone-by-state/get-timezone-by-state.d.ts /** * Retrieves the IANA time zone database name (tzdata zone) for a Brazilian state, chosen as * the zone of the state capital. The match is case-insensitive and ignores leading/trailing * whitespace. * * Some tzdata zones cover more than one state: `America/Sao_Paulo` also covers DF, GO, MG, ES, * RJ, PR, SC and RS besides SP, and `America/Fortaleza` also covers MA, PI, RN and PB besides * CE. Pará and Amazonas each straddle two IANA zones themselves (`America/Belem`/ * `America/Santarem` and `America/Manaus`/`America/Eirunepe` respectively); both resolve here * to their capital's zone (Belém and Manaus). Pernambuco resolves to `America/Recife`, not * `America/Noronha`: Fernando de Noronha is an archipelago district of PE, not a state of its * own. * * @param {string} stateCode - The two-letter state code (sigla). * @returns {string|null} The IANA time zone name, or `null` when `stateCode` does not match * any Brazilian state. * * @see Official: https://www.iana.org/time-zones * @see Based on: https://raw.githubusercontent.com/eggert/tz/main/zone1970.tab * (IANA tz * database data file, `BR` rows) * @see Based on: https://en.wikipedia.org/wiki/Time_in_Brazil * Used to confirm the state * coverage of each zone. * * @example * ```typescript * getTimezoneByState("SP"); // "America/Sao_Paulo" * getTimezoneByState("am"); // "America/Manaus" * getTimezoneByState("AC"); // "America/Rio_Branco" * getTimezoneByState("PE"); // "America/Recife" * getTimezoneByState("ZZ"); // null * ``` */ export declare const getTimezoneByState: (stateCode: string) => string | null; //#endregion //#region src/is-holiday/is-holiday.d.ts /** The parameters `isHoliday` takes: the date to check and, optionally, the state whose holidays also count. */ type IsHolidayParams = { /** The date to check, read by its local calendar day. */ targetDate: Date; /** Two letter state code whose state holidays are also considered (default: national holidays only). */ stateCode?: StateCode; }; /** * The parameters `isHoliday` takes, the 2.3.0 name of `IsHolidayParams`. * * @deprecated Use `IsHolidayParams` instead. */ type IsHolidayOptions = IsHolidayParams; /** * Checks whether a given date is a Brazilian holiday. * * The check is based on `targetDate`'s **local calendar date** (its local year/month/day, * as read by `Date#getFullYear`/`getMonth`/`getDate`), not its underlying UTC instant. * This matters because `new Date("2024-12-25")` (a date-only ISO string) is parsed as UTC * midnight, which in timezones behind UTC (e.g. America/Sao_Paulo, UTC-3) represents * "2024-12-24" in local time, so build `targetDate` from local components * (`new Date(2024, 11, 25)`) or from a full ISO datetime when you mean a specific local day. * * An invalid `stateCode` is treated in two different ways, depending on its type: * * - a string that is not a known state code is ignored, and only national holidays are * considered, the same behavior as `getHolidays`. The lookup is an own-property one, so a * prototype-chain key such as `"__proto__"` or `"constructor"` is an unknown state code like * any other; * - a `stateCode` that is present and is not a string at all (a number, `null`, an object) is * rejected rather than ignored: `isHoliday` returns `false` without looking at the date, even * when that date is a national holiday. `undefined`, or an absent property, is the only * non-string value that stands for "no state" instead. * * The date a state holiday is checked against is the statutory one, except for Santa Catarina's * two holidays, which `getHolidays` moves to the following Sunday when they fall Monday to * Friday: 11 August from 2005 on, as Lei SC nº 13.408/2005 introduced, and 25 November from 1999 * on, as Lei SC nº 11.213/1999 introduced, save for 2004, the year art. 3º of Lei SC nº * 12.906/2004 left that date without a transfer clause. Lei SC nº 18.531/2022 now carries both. * * @param {IsHolidayParams} [options] - Options for the check. * @param {Date} options.targetDate - The date to check. * @param {StateCode} [options.stateCode] - Optional Brazilian state code to also consider state holidays. * @returns {boolean} True when the date is a holiday, false otherwise. Bad input also returns * false: missing `options`, a `targetDate` that is not a valid `Date`, or a non-string * `stateCode`. * * @example * ```typescript * isHoliday({ targetDate: new Date(2024, 0, 1) }); // true (Ano novo) * isHoliday({ targetDate: new Date(2024, 5, 10) }); // false * isHoliday(); // false * ``` * * The underlying national holidays are the ones `getHolidays` computes; see its JSDoc (and * `src/get-holidays/constants.ts` for state holidays) for the full set of laws behind them. * * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l0662.htm * Lei 662/1949, the base national holidays law. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/2002/l10607.htm * Lei 10.607/2002, added Finados (2 November) and folded in Tiradentes (21 April), which had * been national since art. 3º of the Lei 1.266/1950 it revoked. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l6802.htm * Lei 6.802/1980, declared Nossa Senhora Aparecida a national holiday. * @see Official: https://www.planalto.gov.br/ccivil_03/_ato2023-2026/2023/lei/l14759.htm * Lei 14.759/2023, nationalized Dia da Consciência Negra from 2024. * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l9093.htm * Lei 9.093/1995, the framework law authorizing state and municipal holidays. * @see Official: https://www.in.gov.br/web/dou/-/portaria-mgi-n-11.460-de-29-de-dezembro-de-2025-678388627 * Portaria MGI nº 11.460/2025, the federal executive's annual calendar of feriados nacionais and * pontos facultativos, the source behind three of the four Easter-derived entries: Sexta-feira * Santa, Carnaval and Corpus Christi. Páscoa is not one of them; the portaria never mentions * Easter Sunday, whose date `getHolidays` derives arithmetically with the Meeus/Jones/Butcher * algorithm. See the `getHolidays` JSDoc for why Sexta-feira Santa is typed `national` without a * law of its own. */ export declare const isHoliday: (options?: IsHolidayParams) => boolean; //#endregion //#region src/is-valid-bank-account/is-valid-bank-account.d.ts /** The bank account `isValidBankAccount` checks: the bank, the agency and the account with its check digit. */ type IsValidBankAccountParams = { /** Three digit bank code (COMPE), e.g. "001" for Banco do Brasil. */ bankCode: string; /** Agency number, digits only, without its own check digit. */ agency: string; /** Account number, digits only, without the check digit. */ account: string; /** * The account check digit: one or two characters, or "X" for Banco do Brasil and "P" for * Bradesco. Banks with a published rule take a single character; the generic fallback also * accepts two, chaining mod10 and mod11 over the account. */ digit: string; }; /** * The bank account `isValidBankAccount` checks: the bank, the agency and the account with its * check digit. * * Kept from 2.3.0: the name violates the naming rule (`Options` is the type of a second, * usually optional, argument, and this object is the only argument `isValidBankAccount` takes), * but it shipped in 2.3.0 as the canonical name, so it stays as an alias until v3. * * @deprecated Use `IsValidBankAccountParams` instead. */ type IsValidBankAccountOptions = IsValidBankAccountParams; /** * Validates a Brazilian bank account. The bank code must belong to the Banco Central do Brasil * STR participants list, otherwise the account is rejected. * * Banks validated by their published check digit algorithm: * Banco do Brasil (001), Santander (033), Banrisul (041), Caixa Econômica Federal (104), * Bradesco (237), Nubank (260, Verhoeff), Itaú Unibanco (341), HSBC/Kirton (399) and * Citibank (745). * * Banks validated by structure only, because they publish no check digit rule: * Inter (077), Ailos (085), XP (102), Unicred (136), Stone (197), BTG Pactual (208), * Original (212), PagBank (290), BMG (318), Mercado Pago (323), C6 (336), PicPay (380), * Cora (403), Pan (623), BV (655), Daycoval (707), Sicredi (748) and Sicoob (756). * For those the agency and account only need to match the documented digit lengths. * * Every other bank of the list falls back to a generic modulus 10 and modulus 11 check. * * @param {IsValidBankAccountParams} params - The bank account parameters. * @param {string} params.bankCode - The bank code (3 digits), as published by Banco Central. * @param {string} params.agency - The agency number (1-5 digits). * @param {string} params.account - The account number (1-13 digits). For Caixa, operação + conta. * @param {string} params.digit - The verification digit (1-2 digits, or "X" for Banco do Brasil and "P" for Bradesco). * @returns {boolean} True if the bank account is valid, false otherwise. * * @example * ```typescript * isValidBankAccount({ bankCode: "001", agency: "1584", account: "00210169", digit: "6" }); // true * isValidBankAccount({ bankCode: "041", agency: "2664", account: "358507670", digit: "6" }); // true * isValidBankAccount({ bankCode: "260", agency: "0001", account: "5216125", digit: "0" }); // true * isValidBankAccount({ bankCode: "999", agency: "1234", account: "123456", digit: "6" }); // false * ``` * * Only bank codes present in the bundled Banco Central participant table are accepted; that table is * regenerated weekly by the datasets workflow, so a bank created after the release becomes valid * on the next release. * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/str1/ParticipantesSTR.csv * @see Based on: https://github.com/eduardokum/laravel-boleto/blob/master/manuais/Regras%20Validacao%20Conta%20Corrente%20VI_EPS.pdf * Icatu Seguros compendium of per bank agency/account check digit rules. * @see Based on: https://github.com/ajmiciano/banktools-br/tree/master/lib/banktools-br/banks * @see Based on: https://github.com/luizalabs/heimdall/blob/main/heimdall_valid_bank/calculate_number_account.py * @see Based on: https://github.com/Xerpa/bran_checker/tree/master/lib/banks */ export declare const isValidBankAccount: (params: IsValidBankAccountParams) => boolean; //#endregion //#region src/is-valid-boleto/is-valid-boleto.d.ts /** * Validates if a Brazilian bank slip (boleto) number is valid. * * Supports the 47 digit "cobrança bancária" linha digitável and, additionally, the * "arrecadação" (convênio/tributos) bank slip: 48 digit linha digitável or 44 digit * barcode, both starting with `8`. * * One leniency is kept from 2.3.0: the código de moeda in position 4 of the cobrança bancária * barcode is not checked, although Carta-Circular BCB nº 2.926/2000 fixes it at `9` (real), so * a slip carrying any other moeda digit still validates. * * @param {string} value - The bank slip number to validate. * @returns {boolean} True if the bank slip number is valid, false otherwise. * * @example * ```typescript * isValidBoleto("00190000090114971860168524522114675860000102656"); // true * isValidBoleto("0019000009 01149.718601 68524.522114 6 75860000102656"); // true * isValidBoleto("846100000005246100291102005460339004695895061080"); // true (arrecadação) * ``` * * Carta-Circular BCB nº 2.926/2000 specifies the linha digitável fields and the módulo 11 * check digit (using 1 for remainders 0, 10 and 1) of the 47 digit cobrança bancária slip, * including the position of the fator de vencimento field. The FEBRABAN "Layout Padrão de * Arrecadação/Recebimento com Utilização do Código de Barras" and the FEBRABAN layout index * cover the arrecadação slip. * * @see Official: https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf * @see Official: https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf * @see Official: https://portal.febraban.org.br/pagina/3425/33/pt-br/layout-febraban */ export declare const isValidBoleto: (value: string) => boolean; //#endregion //#region src/is-valid-caepf/is-valid-caepf.d.ts /** * Validates a CAEPF (Cadastro de Atividade Econômica da Pessoa Física) number. * * The CAEPF replaced the CEI for individuals who hire employees, such as rural producers and * notary officials. It has 14 digits printed as "000.000.000/000-00": the 9 digit CPF base of * the holder, a 3 digit sequence for the holder's several registrations and 2 check digits. * Both check digits are the CNPJ's modulus 11 in the formulation of the cited reference: the * weights cycle from 9 down to 2 from the right and the check digit is the remainder itself, * with a remainder of 10 read as 0 — the same digit the CNPJ's 2-to-9 weights with * `11 - remainder` produce. The pair is then shifted by 12, wrapping around 100, so a CAEPF * whose plain modulus 11 digits would be 72 is printed with 84. * * A base whose 12 digits are all the same is rejected before the check digits are computed, the * way `isValidCei` and `isValidCno` reject a repeated CEI/CNO number, so the otherwise * well-formed `"00000000000012"` is invalid. * * The Receita Federal does not publish the check digit rule of the CAEPF, the shift of 12 and * the repeated-base rejection included, so the calculation follows the reference implementations * cited below. * * @param {string|number} value - The CAEPF value to be validated. * @returns {boolean} True if the CAEPF is valid, false otherwise. * * @example * ```typescript * isValidCaepf("293.118.610/001-84"); // true * isValidCaepf("41142260000101"); // true * isValidCaepf(29311861000184); // true * isValidCaepf("29311861000185"); // false (invalid check digits) * isValidCaepf("00000000000000"); // false (repeated base digits) * isValidCaepf("00000000000012"); // false (repeated base digits) * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/caepf * The registry's own page at the Receita Federal, which describes the cadastro but publishes * neither the 14 digit layout nor the check digit rule. * @see Based on: http://ghiorzi.org/DVnew.htm * Description of the CAEPF layout and of the * shift of 12 applied to the check digit pair. * @see Based on: https://github.com/VitorLuizC/brazilian-values/blob/master/src/validators/isCAEPF.ts * Reference implementation agreeing on the weights and on the shift. * @see Based on: https://github.com/Casilhero/brazilian-validators/blob/main/src/Validators/Caepf.php * Third reference implementation. */ export declare const isValidCaepf: (value: string | number) => boolean; //#endregion //#region src/is-valid-cbo/is-valid-cbo.d.ts /** * Validates if a CBO (Classificação Brasileira de Ocupações) code exists in the official * CBO 2002 table. * * A string is only read as a code when it is written in one of the documented forms: the 6 * digits, or the `NNNN-NN` mask, with a single separator between the groups and optional * surrounding whitespace. A number is only read as a code when it is a non-negative safe * integer. * * A CBO code is always 6 digits and its leading zeros are part of it, so a value written as * bare digits is left padded with zeros to 6 whether it comes as a string or as a number: * `10205`, `"10205"` and `"010205"` are the same code. * * @param {string|number} value - The CBO code to be validated, with or without the hyphen * mask, e.g. `"2124-05"`, `"212405"` or `212405`. * @returns {boolean} True when the code is a known 6 digit occupation code, false otherwise. * * @example * ```typescript * isValidCbo("2124-05"); // true * isValidCbo("212405"); // true * isValidCbo(212405); // true * isValidCbo(10205); // true (padded to 6 digits, so this is "010205") * isValidCbo("10205"); // true (padded to 6 digits, so this is "010205") * isValidCbo("999999"); // false * isValidCbo("2124abc05"); // false (not a documented form) * isValidCbo(-212405); // false (not a non-negative safe integer) * ``` * * @see Official: https://www.gov.br/trabalho-e-emprego/pt-br/assuntos/cbo/servicos/downloads/cbo2002-ocupacao.csv * The CBO 2002 occupation table, as published by the Ministério do Trabalho e Emprego. * @see Based on: https://raw.githubusercontent.com/lucaashoff/lista-cbo-json/main/cbos.json * Community mirror of the same table, the fallback `CBO_TITLES` was built from before the * official CSV was used. */ export declare const isValidCbo: (value: string | number) => boolean; //#endregion //#region src/is-valid-cei/is-valid-cei.d.ts /** * Validates a CEI (Cadastro Específico do INSS) number. * * The CEI identifies an employer that has no CNPJ, such as a construction work or a rural * producer. It has 12 digits printed as "00.000.00000/00": 11 base digits and one check digit. * The check digit weights the base by 7, 4, 1, 8, 5, 2, 1, 6, 3, 7 and 4, adds the tens part of * that sum to its units part and takes the complement of the units digit of the result to 10, * mapping 10 back to 0. The CEI was replaced by the CNO for construction works and by the CAEPF * for individuals, but numbers already issued keep their meaning and their check digit. * * The value has to be written as the 12 digits, optionally split into the printed groups of 2, * 3, 5 and 2 by whitespace or the usual mask characters, a run of them between two groups * included; anything else, a letter among the digits included, is rejected instead of being * read past. * * The Receita Federal does not publish the check digit rule of the CEI/CNO numbering, so the * calculation follows the reference implementations cited below, cross-checked against the CNO * open data of the Receita Federal. * * @param {string|number} value - The CEI value to be validated. * @returns {boolean} True if the CEI is valid, false otherwise. * * @example * ```typescript * isValidCei("11.583.00249/85"); // true * isValidCei("277297118187"); // true * isValidCei(249859674386); // true * isValidCei("24.985.96743/68"); // false (invalid check digit) * isValidCei("000000000000"); // false (repeated digits) * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno * The registry's own page at the Receita Federal, which describes the cadastro but publishes * neither the mask nor the check digit rule. * @see Official: https://dados.gov.br/dados/conjuntos-dados/cadastro-nacional-de-obras-cno * Cadastro Nacional de Obras (CNO), dados abertos da Receita Federal: the catalogue entry for the * dataset this rule was cross-checked against and where the test vectors come from. The check was * run over the Minas Gerais extract of the downloaded dataset, which every registered work passed; * the catalogue page itself publishes only the dataset's description and download links (and * currently flags it "Desatualizado"), not that result. * @see Based on: https://github.com/yiibr/yii2-br-validator/blob/master/src/CeiValidator.php * PHP reference implementation of the CEI check digit. * @see Based on: https://github.com/marcos-cruz/Documento/blob/master/src/Bigai.Documentos.Brasil/Cei/Cei.cs * Second, independent reference implementation agreeing with the first. */ export declare const isValidCei: (value: string | number) => boolean; //#endregion //#region src/is-valid-certidao/is-valid-certidao.d.ts /** Options of `isValidCertidao`. */ type IsValidCertidaoOptions = { /** Kinds of certidão (book types) that count as valid (default: all of them). */ accept?: CertidaoType[]; }; /** * Validates the matrícula of a certidão de registro civil (nascimento, casamento, óbito and the * other acts kept by a serventia de registro civil das pessoas naturais). * * The matrícula has 32 digits laid out as 6 (CNS da serventia) + 2 (acervo) + 2 (serviço) + * 4 (ano) + 1 (tipo do livro) + 5 (livro) + 3 (folha) + 7 (termo) + 2 (dígitos verificadores), * printed as "000000 00 00 0000 0 00000 000 0000000 00". The serviço is fixed at `55`, the code * art. 473, III assigns to the registro civil das pessoas naturais, so a matrícula carrying any * other pair there is rejected. Both check digits are modulus 11: the * first weights the 30 base digits by 2, 3, ... 10, 0, 1, 2, ... restarting the cycle every 11 * digits, the second weights the 31 digits that include the first check digit by 1, 2, ... 10, * 0, 1, ... In both passes the check digit is the remainder itself, with a remainder of 10 read * as 1. * * The book-type digit (fifteenth position of the matrícula) always has to name one of the nine * books (see `CertidaoType`, reused from `getCertidaoInfo`), so a matrícula whose digit is `0` is * rejected however good its check digits are, the same way `getCertidaoInfo` returns `null` for * it. `options.accept` narrows that further to the listed types; when it is omitted, or when it * is not an array, every book type is accepted. * * Only a string is accepted: the 32 digits of a matrícula are more than a JavaScript number can * hold, so a numeric argument is always rejected instead of being read as a rounded value. * * @param {string} value - The matrícula value to be validated. * @param {IsValidCertidaoOptions} [options] - Optional validation options. * @param {CertidaoType[]} [options.accept] - The book types to accept. Defaults to all of them. * @returns {boolean} True if the matrícula is valid, false otherwise. * * @example * ```typescript * isValidCertidao("104539 01 55 2013 1 00012 021 0000123 21"); // true * isValidCertidao("09430001552010100020112000012087"); // true * isValidCertidao("104539 01 55 2013 1 00012 021 0000123 22"); // false (invalid check digits) * isValidCertidao("09400301542011100110002005191744"); // false (serviço is not 55) * isValidCertidao("123456"); // false (wrong length) * isValidCertidao("104539 01 55 2013 1 00012 021 0000123 21", { accept: ["birth"] }); // true * isValidCertidao("104539 01 55 2013 1 00012 021 0000123 21", { accept: ["death"] }); // false * ``` * * @see Official: https://atos.cnj.jus.br/atos/detalhar/5243 * Código Nacional de Normas da Corregedoria Nacional de Justiça - Foro Extrajudicial (Provimento * CNJ nº 149/2023), art. 473 as currently published: the in-force layout of the 32 digit * matrícula. Inciso II and §§ 1º and 3º to 5º carry the redação of the Provimento CN nº 237, de * 13/07/2026; the rest of the article, § 2º included, and the digit layout this library depends * on, come from the Provimento CN nº 182, de 17/09/2024. * @see Official: https://atos.cnj.jus.br/atos/detalhar/1311 * Provimento CNJ nº 2, de 27/04/2009, art. 1º and 2º, which instituted the modelos únicos de * certidão and ordered that "as certidões passarão a consignar matrícula que identifica o código * nacional da serventia, o código do acervo, o tipo do serviço prestado, o tipo do livro, o número * do livro, o número da folha, o número do termo e o digito verificador" (revoked; historical). * @see Official: https://atos.cnj.jus.br/atos/detalhar/1310 * Provimento CNJ nº 3, de 17/11/2009, art. 7º, which is where that matrícula first got its digit * structure: "a matrícula, de inserção obrigatória nas certidões (primeira e demais vias) emitidas * pelos Cartórios de Registro Civil das Pessoas Naturais a partir de 1º de janeiro de 2010, é * formada pelos seguintes elementos", incisos I to IX fixing the same 6 + 2 + 2 + 4 + 1 + 5 + 3 + * 7 + 2 positions art. 473 carries today (revoked; historical). * @see Based on: http://ghiorzi.org/DVnew.htm * Worked example of the two check digits (sums 288 and 309). * @see Based on: https://github.com/klawdyo/validation-br/blob/feat-certidao/src/certidao.ts * Reference implementation, and the source of the matrículas used as test vectors. * @see Based on: https://github.com/geekcom/validator-docs/blob/master/src/validator-docs/Rules/Certidao.php * Third reference implementation agreeing on the weights and on the remainder of 10 read as 1. */ export declare const isValidCertidao: (value: string, options?: IsValidCertidaoOptions) => boolean; //#endregion //#region src/is-valid-cfop/is-valid-cfop.d.ts /** * Validates if a CFOP (Código Fiscal de Operações e Prestações) code exists in the * official table. * * The table is the consolidated Anexo II of Convênio SINIEF s/nº 1970, the text in force * (current wording given by Ajuste SINIEF 03/24, last amended by Ajuste SINIEF 39/25). * * Only operable codes count: the group and subgroup headings of the official nomenclature, * the codes ending in "00" and "50" (1000, 1100, 1150, 5350, ...), are section titles rather * than codes a document can carry, so they are rejected. * * A string is only read as a code when it is written in one of the documented forms: the 4 * digits, or the `N.NNN` form the annex prints, with a single separator between the groups * and optional surrounding whitespace. Anything else (`"abc5102"`) is rejected instead of * having its digits picked out. A number is only read as a code when it is a non-negative * safe integer, since a sign, a decimal point or a rounded magnitude would otherwise be read * as a code the caller never wrote. * * No CFOP code starts with a zero, its first digit is the operation group (1 to 7), so nothing * is ever padded here: a number and the string of the same digits are read identically, and a * value narrower than 4 digits is not a code at all. * * @param {string|number} value - The CFOP code to be validated, with or without the `N.NNN` * mask, e.g. `"1.101"`, `"1101"` or `1101`. * @returns {boolean} True when the code is a known 4 digit CFOP code, false otherwise. * * @example * ```typescript * isValidCfop("1101"); // true * isValidCfop("1.101"); // true * isValidCfop(1101); // true * isValidCfop("0000"); // false * isValidCfop("1150"); // false (a subgroup heading, not an operable code) * isValidCfop("abc5102"); // false (not a documented form) * isValidCfop(-5102); // false (not a non-negative safe integer) * ``` * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cfop_cvsn_1-6.24 * Anexo II of Convênio SINIEF s/nº 1970, the CFOP table in force. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cvsn_70 * Convênio SINIEF s/nº 1970, the consolidated text the annex belongs to. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2025/AJ039_25 * Ajuste SINIEF 39/25, the last amendment the annex carries (CFOP 7.667, from 01.02.26). * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2001/AJ_007_01 * Ajuste SINIEF 07/01, the historical text that gave the CFOP its 4 digit form. */ export declare const isValidCfop: (value: string | number) => boolean; //#endregion //#region src/is-valid-cnae/is-valid-cnae.d.ts /** * Validates if a CNAE (Classificação Nacional de Atividades Econômicas) subclass code * exists in the official CNAE-Subclasses 2.3 table, the current subclass revision of CNAE 2.0. * * A string is only read as a code when it is written in one of the documented forms: the 7 * digits, or the `NNNN-N/NN` mask, with a single separator (space, `.`, `-` or `/`) between the groups and optional * surrounding whitespace. A number is only read as a code when it is a non-negative safe * integer. * * A CNAE subclass code is always 7 digits and its leading zeros are part of it, so a value * written as bare digits is left padded with zeros to 7 whether it comes as a string or as a * number: `111301`, `"111301"` and `"0111301"` are the same code. * * @param {string|number} value - The CNAE code to be validated, with or without the * `NNNN-N/NN` mask, e.g. `"6201-5/01"`, `"6201501"` or `6201501`. * @returns {boolean} True when the code is a known 7 digit subclass, false otherwise. * * @example * ```typescript * isValidCnae("6201-5/01"); // true * isValidCnae("6201501"); // true * isValidCnae(6201501); // true * isValidCnae(111301); // true (padded to 7 digits, so this is "0111301") * isValidCnae("111301"); // true (padded to 7 digits, so this is "0111301") * isValidCnae("0000000"); // false * isValidCnae("0111abc301"); // false (not a documented form) * isValidCnae(-111301); // false (not a non-negative safe integer) * ``` * * @see Official: https://servicodados.ibge.gov.br/api/v2/cnae/subclasses * @see Official: https://concla.ibge.gov.br/busca-online-cnae.html * CONCLA's CNAE search and structure browser, which publishes CNAE-Subclasses 2.3. */ export declare const isValidCnae: (value: string | number) => boolean; //#endregion //#region src/is-valid-cnh/is-valid-cnh.d.ts /** * Validates if a CNH (Carteira Nacional de Habilitação, the Brazilian driver's license number) is valid. * * Spaces, dots and hyphens are ignored, so every punctuated form of a CNH is accepted, but any * other character, a letter in particular, makes the value invalid. * * @param {string} value - The CNH value to be validated. * @returns {boolean} True if the CNH is valid, false otherwise. * * @example * ```typescript * isValidCnh("00000000119"); // true * isValidCnh("000000001-19"); // true * isValidCnh("11111111111"); // false (repeated digits) * isValidCnh("12345678901"); // false (invalid checksum) * isValidCnh("ab00000000119"); // false (invalid format) * ``` * * Resolução CONTRAN nº 886/2021, art. 4º I, defines the CNH registry number as 9 characters plus * 2 security check digits, but no official text publishes the check-digit weights; the algorithm * below follows the community reference cited as `Based on:`. * * Art. 4º § 1º of the same resolution states that the check digit is computed by the DSR system * with a "módulo 11" routine in which a remainder of 0 or 1 yields the digit 0. That rounding is * not the rule the registry numbers use in practice: the first verifier keeps the remainder * itself, so a remainder of 1 yields the digit 1 (which is why `"00000000119"` is accepted). The * implementation follows the cited `Based on:` reference, not § 1º. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/Resolucao8862021F.pdf * @see Based on: https://siga0984.wordpress.com/2019/05/01/algoritmos-validacao-de-cnh/ */ export declare const isValidCnh: (value: string) => boolean; //#endregion //#region src/is-valid-cno/is-valid-cno.d.ts /** * Validates a CNO (Cadastro Nacional de Obras) number, the registration of a construction work * with the Receita Federal. * * The CNO replaced the CEI for construction works and kept its numbering: 12 digits printed as * "00.000.00000/00", the last one being a check digit calculated over the 11 base digits with * the weights 7, 4, 1, 8, 5, 2, 1, 6, 3, 7 and 4. A work registered under a legacy CEI keeps * the same number in the CNO, so both registries validate identically. * * The value has to be written as the 12 digits, optionally split into the printed groups of 2, * 3, 5 and 2 by whitespace or the usual mask characters, a run of them between two groups * included; anything else, a letter among the digits included, is rejected instead of being * read past. * * The Receita Federal does not publish the check digit rule of the CEI/CNO numbering, so the * calculation follows the reference implementations cited below, cross-checked against the CNO * open data of the Receita Federal. * * @param {string|number} value - The CNO value to be validated. * @returns {boolean} True if the CNO is valid, false otherwise. * * @example * ```typescript * isValidCno("11.084.01680/62"); // true * isValidCno("111130137368"); // true * isValidCno(401800097960); // true * isValidCno("110840168063"); // false (invalid check digit) * isValidCno("000000000000"); // false (repeated digits) * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno * The registry's own page at the Receita Federal, which describes the cadastro but publishes * neither the mask nor the check digit rule. * @see Official: https://dados.gov.br/dados/conjuntos-dados/cadastro-nacional-de-obras-cno * Cadastro Nacional de Obras (CNO), dados abertos da Receita Federal: the catalogue entry for the * dataset this rule was cross-checked against and where the test vectors come from. The check was * run over the Minas Gerais extract of the downloaded dataset, which every registered work passed; * the catalogue page itself publishes only the dataset's description and download links (and * currently flags it "Desatualizado"), not that result. * @see Based on: https://github.com/yiibr/yii2-br-validator/blob/master/src/CeiValidator.php * PHP reference implementation of the CEI check digit. */ export declare const isValidCno: (value: string | number) => boolean; //#endregion //#region src/is-valid-cns/is-valid-cns.d.ts /** * Validates a CNS (Cartão Nacional de Saúde) number, the unique identifier of a SUS * (Sistema Único de Saúde) user, health professional or health facility. * * Definitive cards (starting with 1 or 2) are laid out as an 11 digit PIS/PASEP/NIS derived * base, a 3 digit suffix and a check digit. The check digit is 11 minus the remainder of the * base's weighted sum (weights 15 down to 5) divided by 11, with 11 mapped to 0. When that * raw digit is 10, DATASUS raises the weighted sum by 2, recomputes the digit and marks the * card with the suffix `"001"` instead of `"000"`. Provisional cards (starting with 7, 8 or 9) * are validated by a single weighted sum (weights 15 down to 1 over all 15 digits) that must * be a multiple of 11. * * The value has to be written as the 15 digits, optionally split into the printed groups of 3, * 4, 4 and 4 by whitespace, `.`, `-` or `/`, the interchangeable mask characters `isValidCpf` * and `isValidCnpj` accept, a run of them between two groups included; anything else, a letter * among the digits or a separator inside a group included, is rejected instead of being read * past. * * @param {string|number} value - The CNS value to be validated. * @returns {boolean} True if the CNS is valid, false otherwise. * * @example * ```typescript * isValidCns("123456789010000"); // true (definitive, suffix 000) * isValidCns("100000000060018"); // true (definitive, raw check digit 10, suffix 001) * isValidCns("700000000000005"); // true (provisional) * isValidCns("123.4567-8901/0000"); // true (any of the mask characters) * isValidCns("123456789010001"); // false (wrong check digit) * isValidCns("12345678901"); // false (wrong length) * ``` * * @see Official: https://rni-docs.anvisa.gov.br/docs/regras_gerais/validacoes/validacaoCNS/ * ANVISA's two validation routines, the ones implemented here. The page sits behind a bot filter * and answers HTTP 403 to every non-browser client, so it has to be opened in a browser. * @see Based on: https://integracao.esusab.ufsc.br/ledi/documentacao/regras/algoritmo_CNS.html * e-SUS APS documentation of the same DATASUS algorithm, reachable without a browser. It applies * the provisional routine to numbers starting with 5, 7, 8 or 9; this implementation follows the * ANVISA page, which restricts it to 7, 8 and 9, so a 5 prefixed number is rejected even when its * weighted sum checks out. */ export declare const isValidCns: (value: string | number) => boolean; //#endregion //#region src/is-valid-credit-card/is-valid-credit-card.d.ts /** * Validates a payment card number (crédito ou débito) using the Luhn algorithm. * * Accepts the usual mask characters (whitespace, `.`, `-` and `/`, the interchangeable set * `isValidCpf` and `isValidCnpj` accept) between digits, a run of them included, so * `"4111 - 1111 - 1111 - 1111"` reads as the same PAN, and whitespace around the value; any * other character makes the value invalid, so `"4111a1111b1111c1111"` is rejected instead of * being read as `"4111111111111111"`. They are accepted between any two digits rather than at * fixed positions: the printed grouping of a PAN changes with the brand (4-4-4-4 for Visa and * Mastercard, 4-6-5 for American Express, 4-6-4 for Diners Club), so there is no single layout * to pin them to. Only checks the digit count (12 to 19: 12 is * the de-facto industry minimum PAN length, e.g. Maestro, and ISO/IEC 7812-1 caps the PAN at 19) * and the Luhn check digit; it performs no brand detection (Visa, Mastercard, Amex...), issuer * range lookup or expiration/CVV checks. * * A value whose digits are all the same (`"0000000000000000"`) is rejected even when it passes * the Luhn check, as every other validator of this package rejects a repeated-digit document * (`isValidCpf("00000000000")`, `isValidCns`, `isValidCaepf`, `isValidCei`): no issuer hands out * such a PAN, and it is what a placeholder or a zero-filled field looks like. * * A number is only accepted when it is a non-negative safe integer: a card number above * `Number.MAX_SAFE_INTEGER` (2^53 - 1, 16 digits) has already been rounded to a different * number by the time it arrives, and a negative one is not a PAN, so both are rejected rather * than validated as digits the caller never wrote. Pass a longer PAN as a string. * * @param {string|number} value - The card number to be validated. * @returns {boolean} True when `value` sanitizes to 12-19 digits ending in a valid Luhn check digit. * * @example * ```typescript * isValidCreditCard("4111111111111111"); // true (Visa test number) * isValidCreditCard("5555555555554444"); // true (Mastercard test number) * isValidCreditCard("378282246310005"); // true (American Express test number) * isValidCreditCard("4111 1111 1111 1111"); // true (spaced mask) * isValidCreditCard("4111 - 1111 - 1111 - 1111"); // true (a run of separators between the digits) * isValidCreditCard("4111.1111/1111-1111"); // true (any of the mask characters) * isValidCreditCard("4111111111111112"); // false (bad check digit) * isValidCreditCard("0000000000000000"); // false (every digit the same, though the Luhn check passes) * isValidCreditCard("4111a1111b1111c1111"); // false (letters between the digits) * isValidCreditCard("123456789"); // false (too short) * isValidCreditCard(4111111111111111111); // false (above 2^53 - 1, pass it as a string) * ``` * * ISO/IEC 7812-1 (issuer identification numbers) caps the PAN at 19 digits but sets no * minimum; the 12-digit floor here is the de-facto industry minimum (e.g. Maestro). The ISO * catalogue page sits behind a bot filter and answers HTTP 403 to every non-browser client, so * it has to be opened in a browser, where it renders the standard's paywalled abstract rather * than its text. * * @see Official: https://www.iso.org/standard/70484.html */ export declare const isValidCreditCard: (value: string | number) => boolean; //#endregion //#region src/is-valid-csosn/is-valid-csosn.d.ts /** * Validates if a CSOSN (Código de Situação da Operação no Simples Nacional) code is valid. * * Accepted codes are `101, 102, 103, 201, 202, 203, 300, 400, 500, 900`, the table the * consolidated Anexo III-A of Convênio SINIEF s/nº 1970 carries. * * A string is only read as a code when it is written as the bare 3 digits with optional * surrounding whitespace. A CSOSN has no printed grouping (the NF-e carries the origin digit in * its own `orig` field), so a separator inside it (`"1-01"`) is rejected, and so is anything * else (`"abc101"`) instead of having its digits picked out. A number is only read * as a code when it is a non-negative safe integer, since a sign, a decimal point or a rounded * magnitude would otherwise be read as a code the caller never wrote. * * No CSOSN code starts with a zero, the table runs from `101` to `900`, so nothing is ever * padded here: a number and the string of the same digits are read identically, and a value * narrower than 3 digits is not a code at all. * * @param {string|number} value - The CSOSN code to be validated, e.g. `"101"` or `101`. * @returns {boolean} True when the code is a known CSOSN code, false otherwise. * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cvsn_70 * Convênio SINIEF s/nº 1970, whose Anexo III-A carries the CSOSN table in force. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2010/aj_003_10 * Ajuste SINIEF 03/2010, which instituted the CSOSN table. * * @example * ```typescript * isValidCsosn("101"); // true * isValidCsosn(900); // true * isValidCsosn("999"); // false * isValidCsosn("abc101"); // false (not a documented form) * isValidCsosn(-101); // false (not a non-negative safe integer) * ``` */ export declare const isValidCsosn: (value: string | number) => boolean; //#endregion //#region src/is-valid-cst/is-valid-cst.d.ts /** * Options for `isValidCst`. */ type IsValidCstOptions = { /** * The tax whose CST (Código de Situação Tributária) table the value is checked against. * Omit it to accept a code that exists in any of the four tables (`icms`, `ipi`, `pis`, * `cofins`); a value outside those four falls back to that same default at runtime. */ tax?: "icms" | "ipi" | "pis" | "cofins"; }; /** * Validates if a CST (Código de Situação Tributária) code is valid for a given tax. * * `icms` accepts the 3 digit form used on tax documents (1 origin digit from `0` to `8` * followed by 1 of the 15 codes `00, 02, 10, 15, 20, 30, 40, 41, 50, 51, 53, 60, 61, 70, 90` * of the Tabela B in force, the one Ajuste SINIEF 39/23 gave and Ajuste SINIEF 20/24 amended; * `02`, `15`, `53` and `61` are the monofasia de combustíveis codes it added). * * `ipi` accepts 1 of the 14 codes `00, 01, 02, 03, 04, 05, 49, 50, 51, 52, 53, 54, 55, 99`. * * `pis` and `cofins` accept 1 of the 33 codes `01, 02, 03, 04, 05, 06, 07, 08, 09, 49, 50, 51, * 52, 53, 54, 55, 56, 60, 61, 62, 63, 64, 65, 66, 67, 70, 71, 72, 73, 74, 75, 98, 99`. * * `options.tax` is optional. When it is omitted, the code is valid as long as it exists in any * one of the four tables above; when it is given, only that table is consulted. A `tax` outside * the four documented values falls back to that default instead of turning the code down, the * way every other scalar option of this library (`version`, `type`, `style`) treats a value it * does not know. * * A string is only read as a code when it is written in one of the documented forms: the 2 * digits of a Tabela B code, or the 3 digits of the ICMS form with an optional single * separator after the origin digit, plus optional surrounding whitespace. The origin digit is * the only boundary a printed CST has, so `"0 10"` and `"1-10"` are read while `"0-0"`, * `"11-0"` and `"00-"` are not. Anything else (`"abc110"`) is rejected instead of having its * digits picked out. A number is * only read as a code when it is a non-negative safe integer, since a sign, a decimal point or * a rounded magnitude would otherwise be read as a code the caller never wrote. * * A single digit is narrower than either documented form, so it is left padded with zeros to * the 3 digits of the ICMS form, whether it comes as a string or as a number: `0`, `"0"` and * `"000"` are all the ICMS code `000`. A 2 digit value is already a documented form, a Tabela B * code, and is read as written, so `isValidCst("00", { tax: "ipi" })` stays a CST-IPI check and * a Tabela B code keeps its own two digits: `"07"`, not `7`, which is the ICMS code `007`. * * @param {string|number} value - The CST code to be validated, e.g. `"110"`, `"0 10"` or `110`. * @param {IsValidCstOptions} [options] - The tax whose table the value is checked against. * Checks every table when omitted or when the tax is not one of the four documented values. * @returns {boolean} True when the code is valid for the given tax (or for any tax, when * `options.tax` is omitted), false otherwise. * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cvsn_70 * Convênio SINIEF s/nº 1970, whose Anexo I carries the CST tables in force. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2023/ajuste-sinief-39-23 * Ajuste SINIEF 39/23, which gave Tabela B its current wording with effect from 01.12.23. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2024/AJ020_24 * Ajuste SINIEF 20/24, which struck items 12, 13, 52, 72 and 74 from Tabela B (effects from * 09.07.24) before they ever took effect: those items sat in the inciso III of its cláusula * segunda, whose effect the alínea "b" of the inciso I of the cláusula terceira of Ajuste SINIEF * 39/23 had deferred to 1º de outubro de 2024, so the revocation reached them first and the codes * were never in force. Neither ajuste uses the phrase "sem efeitos"; this is the reading of the * two clauses, not a quotation. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/1994/aj_003_94 * Ajuste SINIEF 03/1994, which instituted the ICMS CST as the two digit code AB. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2000/AJ_006_00 * Ajuste SINIEF 06/2000, the historical Tabela B superseded by Ajuste SINIEF 39/23. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2012/aj_020_12 * Ajuste SINIEF 20/2012, which gives Tabela A (origem da mercadoria, 0 to 7). * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2013/aj_015_13 * Ajuste SINIEF 15/2013, which added origem 8 to Tabela A. * @see Official: https://normas.receita.fazenda.gov.br/sijut2consulta/link.action?idAto=15974 * Instrução Normativa RFB nº 1.009/2010, Tabelas I to III (CST-IPI, CST-PIS and CST-COFINS). * * @example * ```typescript * isValidCst("110", { tax: "icms" }); // true * isValidCst("002", { tax: "icms" }); // true (monofasia de combustíveis) * isValidCst("00", { tax: "ipi" }); // true * isValidCst("49", { tax: "pis" }); // true * isValidCst("07", { tax: "cofins" }); // true * isValidCst("99", { tax: "icms" }); // false * isValidCst(0, { tax: "icms" }); // true (a single digit is padded to the 3 digit form, "000") * isValidCst("0", { tax: "icms" }); // true (padded the same way a number is) * isValidCst("110"); // true (found in the icms table) * isValidCst("49"); // true (found in the ipi table) * isValidCst("000", { tax: "nope" }); // true (an unknown tax falls back to checking every table) * isValidCst("999"); // false (not in any table) * isValidCst("abc110"); // false (not a documented form) * isValidCst(-110); // false (not a non-negative safe integer) * ``` */ export declare const isValidCst: (value: string | number, options?: IsValidCstOptions) => boolean; //#endregion //#region src/is-valid-email/is-valid-email.d.ts /** * Validates if an email address is valid. * * @param {string} value - The email address to be validated. * @returns {boolean} True if the email is valid, false otherwise. * * @example * ```typescript * isValidEmail("user@example.com"); // true * isValidEmail("invalid.email"); // false * isValidEmail("test@domain.co.uk"); // true * ``` * * The WHATWG HTML "valid e-mail address" definition is narrowed further: the local part is * limited to letters, digits and `_'+-.`, it may not start with a dot, end with a dot or an * apostrophe, or contain two dots in a row, and the domain must carry at least one dot and end * in an alphabetic label of 2 to 63 letters. Each dotted label follows the WHATWG production `[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?`, * so a label may neither start nor end with a hyphen nor exceed 63 characters, and the final * label is capped at the same 63 characters. It is a practical * subset of that WHATWG definition, not of IETF RFC 5322: quoted local parts and address * literals are rejected. * * @see Official: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address * @see Official: https://www.rfc-editor.org/rfc/rfc5322 */ export declare const isValidEmail: (value: string) => boolean; //#endregion //#region src/is-valid-iban/is-valid-iban.d.ts /** * Validates a Brazilian IBAN (International Bank Account Number). * * Only Brazilian IBANs (country code `BR`) are recognized: the field layout of the other 90+ * ISO 13616 countries is out of scope, so any non `BR` IBAN, however well formed, returns * `false`. Accepts the usual grouping mask and is case-insensitive. * * Both accepted forms are the ones an IBAN is written in: compact, * `"BR1500000000000010932840814P2"`, or the ISO 13616 print format, letters and digits in groups * of 4 (the last one shorter), with optional surrounding whitespace either way. The groups may be * split by whitespace, `.`, `-` or `/`, the interchangeable mask characters `isValidCpf` and * `isValidCnpj` accept, so `"BR1500000000000010932840814P-2"` reads as the same IBAN. Only a * separator away from a group boundary, a run of separators (ISO 13616 prints a single one) or a * character outside letters and digits makes the value something other than an IBAN, so * `"BR15 0000 0000 0000 1093 2840 814P 2"` and `"BR15 000 00000 0000 1093 2840 814P 2"` are * rejected instead of having the offending character stripped. * * The last character is the owner indicator, `1` for the first or only holder up to `9` for the * ninth and then `A` to `Z` from the tenth, per Circular BCB nº 3.625/2013 art. 2º § 1º, so a * value ending in `0` is rejected. * * @param {string} value - The IBAN to be validated. * @returns {boolean} True when `value` is a structurally valid Brazilian IBAN whose ISO 7064 * MOD 97-10 check digits match. * * @example * ```typescript * isValidIban("BR1500000000000010932840814P2"); // true * isValidIban("BR15 0000 0000 0000 1093 2840 814P 2"); // true (grouping spaces) * isValidIban("BR15-0000-0000-0000-1093-2840-814P-2"); // true (any of the mask characters) * isValidIban("br1500000000000010932840814p2"); // true (case-insensitive) * isValidIban("BR1500000000000010932840814P3"); // false (bad check digits) * isValidIban("BR15 000 00000 0000 1093 2840 814P 2"); // false (a separator inside a group) * isValidIban("DE89370400440532013000"); // false (non Brazilian IBAN) * ``` * * @see Official: https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf * Circular BCB nº 3.625/2013 * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf * Diretrizes de Implementação do IBAN no Brasil * @see Official: https://www.iso.org/standard/81090.html * ISO 13616-1:2020 (IBAN structure) * @see Official: https://www.iso.org/standard/31531.html * ISO/IEC 7064:2003 (MOD 97-10 check digit algorithm) * @see Based on: https://www.iban.com/structure * Used to cross check the Brazil IBAN example. */ export declare const isValidIban: (value: string) => boolean; //#endregion //#region src/is-valid-landline-phone/is-valid-landline-phone.d.ts /** * Validates if a phone number is a valid Brazilian landline phone. * * A Brazilian country code (`+55`, `0055` or a bare `55`) is accepted and removed before * validation, under the rule documented in `parsePhone`. * * @param {string} value - The phone number to validate. * @returns {boolean} True if the phone number is a valid landline phone, false otherwise. * * @example * ```typescript * isValidLandlinePhone("(11) 3000-0000"); // true * isValidLandlinePhone("1130000000"); // true * isValidLandlinePhone("+55 11 3000-0000"); // true * isValidLandlinePhone("11987654321"); // false (mobile) * ``` * * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 */ export declare const isValidLandlinePhone: (value: string) => boolean; //#endregion //#region src/is-valid-legal-nature/is-valid-legal-nature.d.ts /** * Validates if a Brazilian legal nature (natureza jurídica) code exists. * * Only the usual mask characters (hyphens, dots, whitespace) are tolerated around the 4 * digits. Any other character makes the value invalid, so `"2062a"` is rejected instead of * being read as `"2062"`. * * The 8 codes a past revision of the CONCLA table retired are accepted alongside the 92 in force, * because they still appear in records filed while they were in force. Use `getLegalNature` to * tell the two apart: a retired code comes back with `legacy: true` and the `currentCode` it * corresponds to today. * * @param {string} code - The legal nature code to be validated, with or without formatting. * @returns {boolean} True when the code is a known 4 digit legal nature, false otherwise. * * @example * ```typescript * isValidLegalNature("2062"); // true * isValidLegalNature("206-2"); // true * isValidLegalNature("2208"); // true (retired by a past revision, still accepted) * isValidLegalNature("2062a"); // false * isValidLegalNature("0000"); // false * ``` * * The CONCLA table page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser; the detailed structure PDF next to it is served * normally. * * @see Official: https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021 * @see Official: https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf */ export declare const isValidLegalNature: (code: string) => boolean; //#endregion //#region src/is-valid-license-plate/is-valid-license-plate.d.ts /** * Validates if a Brazilian license plate (placa de carro ou moto) is valid. * * Supports the old Brazilian format (ABC-1234) and the Mercosul format (ABC1D23), the single * sequence Resolução CONTRAN nº 969/2022 defines for every vehicle, motorcycles included. * Accepts the usual mask characters (hyphens, spaces) and is case-insensitive, mirroring * `getFormatLicensePlate`/`parseLicensePlate` (single source of truth for the supported * formats). * * @param {string} value - The license plate value to be validated. * @returns {boolean} True if the license plate is valid, false otherwise. * * @example * ```typescript * isValidLicensePlate("abc1234"); // true (Brazilian format) * isValidLicensePlate("ABC-1234"); // true (Brazilian format with hyphen) * isValidLicensePlate("ABC 1234"); // true (whitespace mask) * isValidLicensePlate("abc1d23"); // true (Mercosul format) * isValidLicensePlate("ABC12D3"); // false (not a Mercosul sequence) * isValidLicensePlate("ABC1234EXTRA"); // false (too many characters) * isValidLicensePlate("invalid"); // false * ``` * * The resolution's own text does not spell the sequence out: art. 2º § 2º delegates the * technical specification to Anexo I, whose item 1.2 reads "O padrão de estampagem é composto de * 7 (sete) caracteres alfanuméricos, em alto relevo, na sequência LLLNLNN" and whose item 1.2.1 * reads `L` as a letter and `N` as a numeral. Art. 2º § 1º puts a single rear plate of that same * standard on motorcycles and similar vehicles, and art. 2º § 3º describes the old `AAA-1111` * PNU it coexists with. The annexes are published in a PDF of their own, cited below alongside * the resolution's text. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022anexos.pdf */ export declare const isValidLicensePlate: (value: string) => boolean; //#endregion //#region src/is-valid-phone/is-valid-phone.d.ts /** The Brazilian mobile numbering rule to enforce over the 11 digit number: `1` the legacy one (6, 7, 8 or 9), `2` the current one (7, 8 or 9, without the `700` series). */ type PhoneVersion = 1 | 2; /** The kinds of Brazilian phone number `isValidPhone` can accept. */ type PhoneType = "mobile" | "landline" | "service"; /** Options of `isValidPhone`. */ type IsValidPhoneOptions = { /** Mobile numbering rule to enforce, see `isValidMobilePhone` (default: `1`). */ version?: PhoneVersion; /** Kinds of number that count as valid (default: `["mobile", "landline"]`). */ accept?: PhoneType[]; }; /** * Validates a Brazilian phone number. * * A Brazilian country code (`+55`, `0055` or a bare `55`) is accepted and removed before * validation, under the rule documented in `parsePhone`. * * `options.accept` picks which kinds of number count as valid and defaults to * `["mobile", "landline"]`, i.e. geographic numbers only. Add `"service"` to also accept the * non-geographic numbers recognized by `isValidServicePhone`; pass `[]` to accept none. * * `options.version` is forwarded to `isValidMobilePhone` and only affects mobile numbers: * `1` (the default) accepts a first number digit of 6, 7, 8 or 9, and `2` the 7, 8 and 9 of * Resolução Anatel nº 749/2022, art. 12, I, "a", minus its `700` satellite series. * * @param {string} value - The phone number to validate. * @param {IsValidPhoneOptions} options - Optional validation options. * @param {1|2} options.version - The mobile numbering rule to enforce, see `isValidMobilePhone`. * @param {PhoneType[]} options.accept - The kinds of number to accept (default: `["mobile", "landline"]`). * @returns {boolean} True if the phone number is valid, false otherwise. * * @example * ```typescript * isValidPhone("(11) 98765-4321"); // true * isValidPhone("11987654321", { version: 2 }); // true * isValidPhone("11712345678", { version: 2 }); // true (7 is SMP as well) * isValidPhone("11700123456", { version: 2 }); // false (the 700 series is satellite) * isValidPhone("1130000000"); // true (landline) * isValidPhone("+55 11 98765-4321"); // true * isValidPhone("08001234567"); // false (service numbers are not accepted by default) * isValidPhone("08001234567", { accept: ["service"] }); // true * isValidPhone("11987654321", { accept: [] }); // false * ``` * * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 */ export declare const isValidPhone: (value: string, options?: IsValidPhoneOptions) => boolean; //#endregion //#region src/is-valid-mobile-phone/is-valid-mobile-phone.d.ts /** Options of `isValidMobilePhone`. */ type IsValidMobilePhoneOptions = { /** Numbering rule to enforce over the 11 digit number: `1` (default) accepts 6, 7, 8 or 9 as the first number digit, `2` accepts 7, 8 or 9 and rejects the `700` series. */ version?: PhoneVersion; }; /** * Validates if a phone number is a valid Brazilian mobile phone. * * A Brazilian country code (`+55`, `0055` or a bare `55`) is accepted and removed before * validation, under the rule documented in `parsePhone`. * * The `version` option controls which mobile numbering rule is enforced: * - `1` (default): accepts the legacy 11-digit format, whose first number digit * (right after the DDD) may be 6, 7, 8 or 9. * - `2`: enforces the current format, whose first number digit must be 7, 8 or 9 and whose * `700` series is left out. * * @param {string} value - The phone number to validate. * @param {IsValidMobilePhoneOptions} options - Optional validation options. * @param {1|2} options.version - The mobile numbering rule to enforce (see above). Defaults to 1. * @returns {boolean} True if the phone number is a valid mobile phone, false otherwise. * * @example * ```typescript * isValidMobilePhone("(11) 98765-4321"); // true (accepts both v1 and v2) * isValidMobilePhone("11987654321", { version: 2 }); // true * isValidMobilePhone("11712345678", { version: 1 }); // true * isValidMobilePhone("11712345678", { version: 2 }); // true (7 is SMP as well) * isValidMobilePhone("11612345678", { version: 2 }); // false (6 is Reserva Técnica) * isValidMobilePhone("11700123456", { version: 2 }); // false (the 700 series is satellite) * isValidMobilePhone("+55 11 98765-4321"); // true * ``` * * `version: 1` (the default) is the pre-Resolução 749/2022 rule, which also accepts a leading * 6, kept for 2.3.0 compatibility. `version: 2` enforces art. 12, I, "a" of the resolution, * `“7”, "8" e “9”: Serviço Móvel Pessoal (SMP), ressalvado o disposto no inciso II deste * artigo`, so 6 is Reserva Técnica and is rejected. * * That ressalva is art. 12, II, "a", `“700”: Serviço Móvel Global por Satélite (SMGS)`: the * `700` series is not SMP, so `version: 2` rejects `isValidMobilePhone("11700123456")`. * `version: 1` does not carve the series out and accepts it, for 2.3.0 compatibility. * * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 */ export declare const isValidMobilePhone: (value: string, options?: IsValidMobilePhoneOptions) => boolean; //#endregion //#region src/is-valid-ncm/is-valid-ncm.d.ts /** * Validates if a NCM (Nomenclatura Comum do Mercosul) code exists in the official table. * * A string is only read as a code when it is written in one of the documented forms: the 8 * digits, or the `NNNN.NN.NN` mask, with a single separator between the groups and optional * surrounding whitespace. Anything else (`"abc01012100"`) is rejected instead of having its * digits picked out. A number is only read as a code when it is a non-negative safe integer, * since a sign, a decimal point or a rounded magnitude would otherwise be read as a code the * caller never wrote. * * An NCM code is always 8 digits and its leading zeros are part of it, so a value written as * bare digits is left padded with zeros to 8 whether it comes as a string or as a number: * `1012100`, `"1012100"` and `"01012100"` are the same code. A masked value already carries its * separators and is read as written. * * @param {string|number} value - The NCM code to be validated, with or without the * `NNNN.NN.NN` mask. * @returns {boolean} True when the code is a known 8 digit NCM code, false otherwise. * * @example * ```typescript * isValidNcm("0101.21.00"); // true * isValidNcm("01012100"); // true * isValidNcm(1012100); // true (padded to 8 digits, so this is "01012100") * isValidNcm("1012100"); // true (padded to 8 digits, so this is "01012100") * isValidNcm("00000000"); // false * isValidNcm("abc01012100"); // false (not a documented form) * isValidNcm(-84713012); // false (not a non-negative safe integer) * ``` * * @see Official: https://portalunico.siscomex.gov.br/classif/api/publico/nomenclatura/download/json */ export declare const isValidNcm: (value: string | number) => boolean; //#endregion //#region src/is-valid-nfe-key/is-valid-nfe-key.d.ts /** * Validates a DF-e (Documento Fiscal eletrônico) access key (chave de acesso). * * Covers every document whose access key is the same 44 digit string: NF-e (modelo 55), NFC-e * (65), CT-e (57), MDF-e (58), CT-e OS (67, the Conhecimento de Transporte Eletrônico para * Outros Serviços), GTV-e (64, the CT-e Guia de Transporte de Valores), BP-e (63), NF3e (66) * and NFCom (62). The CF-e-SAT (59) is out: its 44 position "chave de consulta" is composed * differently. The 44 digits may be split into the printed groups of 4 by whitespace, `.`, `-` * or `/`, a run of them between two groups included, the same mask rule `isValidCpf` and * `isValidCnpj` follow; a separator inside a group of 4, or any other character, is rejected * instead of being stripped. The `NFe`, `CTe`, `MDFe`, `BPe`, `NF3e` and `NFCom` prefixes found * in the `Id` attribute of the document's XML (e.g. `Id="NFe3517...`) are stripped before that * check, with any whitespace between the prefix and the first group. * * The key is `cUF(2) AAMM(4) CNPJ/CPF(14) mod(2) serie(3) nNF(9) tpEmis(1) cNF(8) cDV(1)`, with * NFCom and NF3e spending position 36 on `nSiteAutoriz` and leaving 7 digits for `cNF`. * `tpEmis` must be one of the codes the MOC of that model assigns, so the accepted set changes * with the model: 1 to 7 and 9 for NF-e and NFC-e, `{1, 3, 4, 5, 7, 8}` for the CT-e, * `{1, 5, 7, 8}` for the CT-e OS, `{1, 2, 7, 8}` for the GTV-e, `{1, 2, 3}` for the MDF-e and * `{1, 2}` for the BP-e, the NF3e and the NFCom. Code 8, the authorização pela SVC-SP, is * assigned by the CT-e MOC only, never by the NF-e one. * The check digit (`cDV`) is a modulus 11 over the first 43 digits, weights 2-9 cycling from * the right, where a remainder of 0 or 1 maps to check digit 0. * * For NF-e and NFC-e the numeric code is also checked against rule B03-10 of the NF-e MOC, * which forbids the twenty repeated and sequential `cNF` values it lists and a `cNF` equal to * the document number. * * @param {string} value - The access key value to be validated. * @returns {boolean} True if the access key is valid, false otherwise. * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf * Manual de Orientação do Contribuinte (MOC) NF-e, "chave de acesso". * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2007/AJ_009_07 * Ajuste SINIEF 09/07, cláusula primeira, caput: the CT-e, modelo 57. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2019/AJ036_19 * Ajuste SINIEF 36/19, cláusula primeira: the CT-e OS, modelo 67. * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/2020/ajuste-sinief-03-20 * Ajuste SINIEF 03/20, cláusula primeira: the GTV-e, modelo 64. * @see Official: https://dfe-portal.svrs.rs.gov.br/CTE/Documentos * CT-e MOC 4.00, Anexo I ("MOC CTe 4.00 Anexo I - Leiaute e Regras de Validação"): the `tpEmis` * domains D19, D27 and D15. Published by the SVRS dfe-portal, like the BP-e, NF3e and NFCom * manuals below; the cte.fazenda.gov.br manual index answers "Sistema temporariamente * indisponível" permanently. * @see Official: https://dfe-portal.svrs.rs.gov.br/BPE/Documentos * BP-e MOC 1.00b, Visão Geral and Anexo I: modelo 63. * @see Official: https://dfe-portal.svrs.rs.gov.br/NF3e/Documentos * NF3e MOC 1.00a, Visão Geral and Anexo I: modelo 66 and `nSiteAutoriz`. * @see Official: https://dfe-portal.svrs.rs.gov.br/NFCOM/Documentos * NFCom MOC 1.00a, Visão Geral and Anexo I: modelo 62 and `nSiteAutoriz`. * @see Based on: https://github.com/nfephp-org/sped-common/blob/master/src/Keys.php * NFePHP `Keys::build`/`Keys::isValid` reference implementation. * @see Based on: https://github.com/vmarchesin/br-validate-dfe-access-key * Second reference implementation and source of additional test vectors. * * @example * ```typescript * isValidNfeKey("35170458716523000119550010000000121000123458"); // true (NF-e, SP) * isValidNfeKey("NFe35170458716523000119550010000000121000123458"); // true (XML Id prefix) * isValidNfeKey("3517 0458 7165 2300 0119 5500 1000 0000 1210 0012 3458"); // true (masked) * isValidNfeKey("3517.0458.7165.2300.0119.5500.1000.0000.1210.0012.3458"); // true (any of the mask characters) * isValidNfeKey("351 70458716523000119550010000000121000123458"); // false (a separator inside a group of 4) * isValidNfeKey("99170458716523000119550010000000121000123458"); // false (invalid cUF) * isValidNfeKey("35170458716523000119010010000000121000123450"); // false (invalid mod) * ``` */ export declare const isValidNfeKey: (value: string) => boolean; //#endregion //#region src/is-valid-passport/is-valid-passport.d.ts /** * Checks if a Brazilian passport number is valid. * To be considered valid, the sanitized input must contain exactly two alphabetical * characters followed by exactly six numerical digits. The input is case-insensitive and * any non-alphanumeric characters (spaces, dots, hyphens, etc.) are ignored, mirroring the * sanitization performed by `formatPassport`/`parsePassport`. * This function does not verify if the input is a real passport number, * as there are no checksums for the Brazilian passport. * A number is accepted for symmetry with `formatPassport`/`parsePassport` but is never valid: * the decimal form of a number never starts with the two letters a passport number needs. * * @param {string|number} passport - The string containing the passport number to be checked. * @returns {boolean} True if the passport number is valid (2 letters followed by 6 digits). * * @example * isValidPassport("AB123456") // true * isValidPassport("ab123456") // true (case-insensitive) * isValidPassport("AB-123.456") // true (symbols are ignored) * isValidPassport("12345678") // false * isValidPassport("DC-221345extra") // false * * The Polícia Federal passport FAQ states the layout: "Ele é composto por duas letras - chamadas * de 'série', e por seis dígitos subsequentes. Por exemplo: Passaporte CS265436." * * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte/ajuda/duvidas_/caderneta/caderneta-numero-onde-fica-e */ export declare const isValidPassport: (passport: string | number) => boolean; //#endregion //#region src/is-valid-pix-key/is-valid-pix-key.d.ts /** Options of `isValidPixKey`. */ type IsValidPixKeyOptions = { /** Kinds of Pix key that count as valid (default: all of them). */ accept?: PixKeyType[]; }; /** * Validates a Pix key (chave Pix) against the DICT key formats. * * A value is valid when `getPixKeyInfo` recognizes it as a CPF, a CNPJ, an e-mail address, a * Brazilian mobile phone number or a random key (EVP), and when that kind is listed in * `options.accept`. The manual registers a "número de telefone celular", so a landline is not * a valid phone key. * * @param {string} value - The Pix key to validate. * @param {IsValidPixKeyOptions} [options] - Optional validation options. * @param {PixKeyType[]} [options.accept] - The kinds of key to accept. Defaults to all of them. * @returns {boolean} True if the value is a valid Pix key, false otherwise. * * @example * ```typescript * isValidPixKey("123.456.789-09"); // true * isValidPixKey("fulano@example.com"); // true * isValidPixKey("(11) 98765-4321"); // true * isValidPixKey("71c7d9be-4b85-4e43-9f1c-1f3b8b4e9a2d"); // true * isValidPixKey("123.456.789-09", { accept: ["email", "evp"] }); // false * isValidPixKey("not a key"); // false * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT.html * DICT (Diretório de Identificadores de Contas Transacionais) API specification, key format * reference. * @see Official: https://github.com/bacen/pix-api * Pix (SPI) OpenAPI spec. */ export declare const isValidPixKey: (value: string, options?: IsValidPixKeyOptions) => boolean; //#endregion //#region src/is-valid-pix-payload/is-valid-pix-payload.d.ts /** * Validates a Pix BR Code payload, the string behind a Pix QR Code and behind "Pix copia e * cola". * * The payload is valid when its TLV (tag-length-value) structure is well-formed, when the * mandatory objects are present and well-formed (payload format indicator `01`, merchant * category code, currency `986`, country `BR`, merchant name and merchant city), when one of * the "Merchant Account Information" templates (IDs 26 to 51) carries the `br.gov.bcb.pix` GUI * together with a key (static QR Code) or a URL (dynamic QR Code), and when the CRC-16 matches * the rest of the payload. The "Point of Initiation Method" object (`01`) is advisory: the * Manual do BR Code marks it `Uso: O` and only assigns a meaning to the value `"12"`, so it may * be absent from either shape and only a value outside `{"11", "12"}` makes the payload * invalid. A payload built around a key that states a transaction amount (`54`) must state one * greater than zero, unless it is a Pix Saque BR Code, i.e. unless it carries the ISPB of the * "facilitador de serviço de saque" in sub-object 26-03 (`fss`) as §2.6 of the Pix manual * prescribes; rejecting `"0"`/`"0.00"` without `fss` is a deliberate restriction of this * library, not a rule of the manual. A `fss` written next to a PSP location makes the payload * invalid: §2.7 of the Manual de Padrões para Iniciação do Pix maps the dynamic QR Code to * exactly two sub-objects, `00` (GUI) and `25` (URL), and `fss` belongs to the static template * of §2.6. * * The key itself is not checked against the DICT formats: the manual states a static QR Code * can be generated with a key that is not (or is no longer) registered, so use `isValidPixKey` * when that matters. * * Unreserved Templates (IDs 80 to 99) are ignored. The "QR Code composto" of Pix Automático * (Pix recorrente) writes its recurrence location in one of them: when such a payload also * carries a payment location in 26-25, as the composite example of the Pix manual does, it is * accepted here and read as an ordinary dynamic payload, its recurrence location dropped. Only * a payload with no Pix template at all in IDs 26 to 51 is reported as invalid. * * @param {string} value - The BR Code payload to validate. * @returns {boolean} True if the payload is a valid Pix BR Code, false otherwise. * * @example * ```typescript * isValidPixPayload( * "00020126580014br.gov.bcb.pix0136123e4567-e12b-12d1-a456-426655440000" + * "5204000053039865802BR5913Fulano de Tal6008BRASILIA62070503***63041D3D", * ); // true * * isValidPixPayload("00020126580014br.gov.bcb.pix..."); // false (broken CRC) * ``` * * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/spb_docs/ManualBRCode.pdf * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/II_ManualdePadroesparaIniciacaodoPix.pdf * @see Official: https://github.com/bacen/pix-api * Pix (SPI) OpenAPI spec. * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT.html * DICT (Diretório de Identificadores de Contas Transacionais) API specification. */ export declare const isValidPixPayload: (value: string) => boolean; //#endregion //#region src/is-valid-processo-juridico/is-valid-processo-juridico.d.ts /** * Validates a Brazilian Processo Jurídico (court case) number. * * Three things are checked: the `NNNNNNN-DD.AAAA.J.TR.OOOO` layout, the `DD` check digits (ISO * 7064 MOD 97-10) and the `J` and `TR` pair, which has to name an órgão and a tribunal Resolução * CNJ nº 65/2008 actually created, so a number carrying a correct check digit but a court that * does not exist, `0000100-23.2008.8.28.0000`, is rejected. The unidade de origem (`OOOO`) is * only read as four digits: art. 1º, § 6º leaves its codification to each tribunal, so there is * no central list to check it against. * * The CNJ mask separators (whitespace, `.` and `-`) are accepted between the * `NNNNNNN-DD.AAAA.J.TR.OOOO` fields, and whitespace around the value is ignored, but any other * character, a letter in particular, makes the value invalid. * * @param {string} value - The Processo Jurídico number to validate. * @returns {boolean} True if the Processo Jurídico number is valid, false otherwise. * * @example * ```typescript * isValidProcessoJuridico("00020802520125150049"); // true * isValidProcessoJuridico("0002080-25.2012.5.15.0049"); // true * isValidProcessoJuridico(" 0002080-25.2012.5.15.0049 "); // true (surrounding whitespace) * isValidProcessoJuridico("0000100-23.2008.8.28.0000"); // false (there is no 28th Tribunal de Justiça) * isValidProcessoJuridico("ab00020802520125150049"); // false (invalid format) * ``` * * Resolução CNJ nº 65/2008 defines this Número Único de Processo layout and its check digits, and * closes the list of órgão (`J`) and tribunal (`TR`) codes in art. 1º, § 4º and § 5º. * * @see Official: https://atos.cnj.jus.br/atos/detalhar/119 */ export declare const isValidProcessoJuridico: (value: string) => boolean; //#endregion //#region src/is-valid-registro-profissional/constants.d.ts /** * Structural format of each supported professional council registration number. * * The citations for these shapes live on the JSDoc of `isValidRegistroProfissional`, which is * also where the councils that publish no number format at all are named. */ type RegistroProfissionalCouncil = "OAB" | "CRM" | "CRO" | "CRP" | "CRC"; //#endregion //#region src/is-valid-registro-profissional/is-valid-registro-profissional.d.ts /** The registration `isValidRegistroProfissional` checks: the number, the council that issued it and, optionally, the UF it must belong to. */ type IsValidRegistroProfissionalParams = { /** The registration number to be validated, e.g. `"123456/SP"`. */ value: string; /** The professional council that issued the registration number. */ council: RegistroProfissionalCouncil; /** The UF the registration is expected to belong to. Ignored for `"CRP"` (see below). */ stateCode?: StateCode; }; /** * Checks the structure of a professional council registration number (registro/inscrição * profissional). * * This is a structural check only: it validates the digit count and, for the councils whose * number embeds the UF, that the UF is a real Brazilian state code, optionally matching * `params.stateCode`. It never computes or asserts a check digit, even for CRC, whose format * includes one (the digit is only checked for presence and shape). * * Supported councils and what is validated: * - `"OAB"` (Ordem dos Advogados do Brasil): 4 to 6 digits + UF, e.g. `"123456/SP"`. * - `"CRM"` (Conselho Regional de Medicina): 4 to 6 digits + UF, e.g. `"123456-SP"`. * - `"CRO"` (Conselho Regional de Odontologia): 3 to 6 digits + UF, e.g. `"12345/SP"`. * - `"CRP"` (Conselho Regional de Psicologia): 2 digit regional code + 4 to 6 digits, e.g. * `"06/12345"`. The regional code must be one of the 24 Conselhos Regionais of the CFP * system, CRP-01 to CRP-24. It is not a literal UF (some regions cover more than one state), * so `params.stateCode` is ignored for this council. * - `"CRC"` (Conselho Regional de Contabilidade): UF + 6 digits + the tipo de registro (`"O"` * Originário or `"P"` Provisório) + 1 check digit whose value is not verified, e.g. * `"SP-123456/O-3"`. The letter says nothing about the professional category: the Manual de * Registro states that the distinction between `"O"` and `"P"` applies "independentemente da * categoria profissional do contabilista". A Registro Transferido or Secundário is written by * appending `"T"` or `"S"` and the UF of the destination CRC **after** the check digit, as the * Resolução CFC nº 1.707/2023, art. 5º, parágrafo único, and the Manual's own examples * (`"SP-123456/O-3 T-MG"`, `"TO-654321/P-8 T-SC"`, `"PI-111222/O-5 S-AC"`) put it. Both UFs * have to be real state codes; `params.stateCode` is compared against the originating one, * the UF the número do Registro Originário belongs to. * * CREA (Conselho Regional de Engenharia e Agronomia) is not supported: since the 2016 national * unification (RNP) its registration number format could not be confirmed from an official, * publicly documented source. * * Only the CRC shape and the CRP regional codes rest on a published source: the CFP page lists * the 24 Conselhos Regionais and nothing else, so the 4 to 6 digit body of a CRP number is as * unsourced as the OAB, CRM and CRO ranges. The OAB, the CFM and the CFO do not publish the * format of the numbers their seccionais and regionais issue, so the digit ranges accepted for * `"OAB"`, `"CRM"` and `"CRO"` are conventional rather than normative, and two counterexamples * are known: the OAB/SP public search field is `maxlength="7"` and rejects only inputs of two * characters or fewer, and the CFM's Manual de Procedimentos Administrativos documents a `300` * prefixed CRM for foreign-trained physicians and a trailing `P` for inscrição provisória, * neither of which the accepted shape can express. * * Everything it needs travels in a single object, the shape `isValidBankAccount` takes: a * registration number means nothing without the council that issued it, so the two are read * together. A value that is not an object, or one missing `value` or `council`, is `false` like * any other registration it cannot recognise. * * @param {IsValidRegistroProfissionalParams} params - The registration to be validated. * @param {string} params.value - The registration number, e.g. `"123456/SP"`. * @param {RegistroProfissionalCouncil} params.council - The issuing council. * @param {string} [params.stateCode] - The expected UF, ignored for `"CRP"`. * @returns {boolean} True if the value has the structure of a registration number for the * given council, false otherwise. * * @example * ```typescript * isValidRegistroProfissional({ value: "123456/SP", council: "OAB" }); // true * isValidRegistroProfissional({ value: "123456-SP", council: "OAB", stateCode: "SP" }); // true * isValidRegistroProfissional({ value: "123456-RJ", council: "OAB", stateCode: "SP" }); // false (UF mismatch) * isValidRegistroProfissional({ value: "06/12345", council: "CRP" }); // true * isValidRegistroProfissional({ value: "SP-123456/O-3", council: "CRC" }); // true * isValidRegistroProfissional({ value: "SP-123456/O-3 T-MG", council: "CRC" }); // true (transferido) * isValidRegistroProfissional({ value: "SP-123456/T-3", council: "CRC" }); // false ("T" is not a tipo) * isValidRegistroProfissional({ value: "123456", council: "OAB" }); // false (no UF) * ``` * * @see Official: https://cfc.org.br/wp-content/uploads/2018/04/1_manual_registro.pdf * Manual de Registro do Sistema CFC/CRCs, item 1.1: the CRC registration is the sigla of the UF, * six sequential digits, the letter of the tipo de registro and a check digit, with * "UF-000001/P-7" and "UF-000002/O-5" as its own worked examples; the same item adds the "T" of * the Registro Transferido "ao número do Registro Definitivo Originário ou Registro Provisório … * acompanhada de um hífen e da sigla designativa da jurisdição do CRC de destino". * @see Official: https://www1.cfc.org.br/sisweb/SRE/docs/Res_1707.pdf * Resolução CFC nº 1.707/2023, art. 5º parágrafo único: "No caso de Registro Transferido, ao * número do Registro Originário será acrescentada a letra 'T', acompanhada da sigla designativa da * jurisdição do CRC de destino." * @see Official: https://site.cfp.org.br/cfp/sistema-conselhos/conselhos-pelo-brasil/ * Conselho Federal de Psicologia: the 24 Conselhos Regionais of the system, numbered CRP-01 to * CRP-24. The page establishes the regional codes only; it publishes no length for the inscription * number itself. * @see Official: https://www.oab.org.br/ * Ordem dos Advogados do Brasil (OAB), the federal body that regulates the profession, which * publishes no format for the número de inscrição and the seccional. * @see Official: https://portal.cfm.org.br/ * Conselho Federal de Medicina (CFM), the autarquia federal that regulates the profession, which * publishes no format for the registration number and the UF. * @see Official: https://cfo.org.br/ * Conselho Federal de Odontologia (CFO), the autarquia federal that regulates the profession, * which publishes no format for the registration number and the UF. */ export declare const isValidRegistroProfissional: (params: IsValidRegistroProfissionalParams) => boolean; //#endregion //#region src/is-valid-renavam/is-valid-renavam.d.ts /** * Validates if a RENAVAM (Registro Nacional de Veículos Automotores) is valid. * * RENAVAM can be in two formats: * - Old format: 9 digits (will be padded to 11 with zeros) * - New format: 11 digits * * The validation uses a checksum algorithm based on modulo 11. * * Spaces, dots and hyphens are ignored, so every punctuated form of a RENAVAM is accepted, but * any other character, a letter in particular, makes the value invalid. A registration whose * digits are all the same (`"00000000000"`) is rejected as well, matching both references below. * * @param {string} renavam - The RENAVAM value to be validated. * @returns {boolean} True if the RENAVAM is valid, false otherwise. * * @example * ```typescript * isValidRenavam("639884962"); // true (9 digits, old format) * isValidRenavam("00639884962"); // true (11 digits, new format) * isValidRenavam("0063988.4962"); // true (dots and hyphens are ignored) * isValidRenavam("12345678901"); // false (invalid checksum) * isValidRenavam("00000000000"); // false (repeated digits) * isValidRenavam("ab00639884962"); // false (invalid format) * ``` * * The Código de Trânsito Brasileiro creates the RENAVAM registry but does not define its check * digit, so the algorithm below follows the two community references cited as `Based on:`. * * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l9503compilado.htm * @see Based on: https://github.com/klawdyo/validation-br/blob/main/src/renavam.ts * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/renavam.py */ export declare const isValidRenavam: (renavam: string | number) => boolean; //#endregion //#region src/is-valid-service-phone/is-valid-service-phone.d.ts /** * Validates if a phone number is a valid Brazilian service number. * * Service numbers are dialed without a DDD, so they are validated by prefix and length alone: * - the Códigos Não Geográficos `0300`, `0303`, `0500`, `0800` and `0900`, each followed by * 7 digits (11 in total, the shorter, extinct `0800` + 6 form is rejected); * - the abbreviated `300X` and `400X` numbers, followed by 4 digits, e.g. `3003-1234`. Anatel * withdrew the 4-digit codes rather than allocating them (Resolução nº 86/1998 art. 43 I and * Ato nº 43.151/2004 art. 2º II both ordered them released), so the accepted roots are the * conventional ones the market settled on. Only `300X` and `400X` are recognised: other * "Número Único" carrier prefixes in market use, such as `4020` and `4062`, are out of scope * and are rejected; * - the 3-digit Códigos de Acesso a Serviços de Utilidade Pública that Anatel has designated, * e.g. `190` and `192`, the consolidated table being the Anexo of Ato nº 43.151/2004. * Undesignated codes in the `1XX` range are rejected, and so are `112` and `911`: Anatel * designates neither, and `911` is not even inside the `1N₂N₁` range Resolução nº 749/2022 * art. 13 destines to public utility services. Handsets route both by GSM convention, which * is not a numbering designation. * * Only the structure is checked: the number does not have to be assigned to anyone, and the * `0500` rule that encodes a donation amount in the last two digits is not enforced. * * @param {string} value - The phone number to validate. * @returns {boolean} True if the phone number is a valid service phone, false otherwise. * * @example * ```typescript * isValidServicePhone("0800 123 4567"); // true * isValidServicePhone("4004-1234"); // true * isValidServicePhone("190"); // true * isValidServicePhone("11987654321"); // false (geographic number) * ``` * * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 * Resolução Anatel nº 749/2022, arts. 13, 14, 18 and 28. * @see Official: https://informacoes.anatel.gov.br/legislacao/atos-de-numeracao/2004/1648-ato-43151 * Ato Anatel nº 43.151/2004, whose Anexo designates the 3-digit public utility codes. */ export declare const isValidServicePhone: (value: string) => boolean; //#endregion //#region src/is-valid-vin/is-valid-vin.d.ts /** * Validates a VIN (Vehicle Identification Number / chassi). * * Checks the length (17 characters), the excluded letters (`I`, `O`, `Q` are never valid; ISO * 3779:2009 structure) and the check digit at the 9th position, with the check digit and * transliteration computed per 49 CFR 565.15. That 9th-position check digit is a North-American * requirement (49 CFR 565.15 / SAE J853): Resolução CONTRAN nº 968/2022 (in force since 1 July 2022, revoking Resolução CONTRAN nº 24/1998 from * 1 January 2025 by its art. 50, II) and ABNT NBR 6066 define * the Brazilian VIN structure but do not mandate it, so many Brazilian-built VINs do not carry * a matching check digit. This function is therefore a North-American-style structural check, * not a universal validator of Brazilian VINs. Case-insensitive and trims surrounding whitespace. * * A VIN is printed as one unbroken run of 17 characters, so, unlike the documents this package * masks (`isValidCpf`, `isValidCnpj`, `isValidNfeKey`), it has no group boundary to write a * separator at and none is accepted: a space, `.`, `-` or `/` among the characters is rejected * instead of being stripped. * * A value whose 17 characters are all the same (`"00000000000000000"`) is rejected even when it * carries a matching check digit, as every other validator of this package rejects a * repeated-digit document (`isValidCpf("00000000000")`, `isValidCns`, `isValidCaepf`, * `isValidCei`): no WMI, VDS and VIS are built out of a single repeated character, and it is what * a placeholder or a zero-filled field looks like. * * @param {string} value - The VIN to be validated. * @returns {boolean} True when `value` is a 17 character VIN with a matching check digit. * * @example * ```typescript * isValidVin("1HGCM82633A004352"); // true * isValidVin("1m8gdm9axkp042788"); // true (check digit X, lowercase) * isValidVin("JH4TB2H26CC000000"); // true * isValidVin("1HGCM82633A004353"); // false (bad check digit) * isValidVin("00000000000000000"); // false (every character the same, though the check digit matches) * isValidVin("1HGCM8263IA004352"); // false (contains the excluded letter I) * isValidVin("1HGCM82633A00435"); // false (16 characters) * ``` * * The ISO catalogue page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser, where it renders the standard's paywalled * abstract rather than its text. * * @see Official: https://www.iso.org/standard/52200.html * @see Official: https://www.ecfr.gov/current/title-49/section-565.15 * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9682022.pdf * Resolução CONTRAN nº 968, de 20 de junho de 2022, art. 2º, I (VIN of 17 characters in three sections) * and art. 50, II (revocation of Resolução nº 24/1998 from 1 January 2025). * @see Official: https://vpic.nhtsa.dot.gov/api/ */ export declare const isValidVin: (value: string) => boolean; //#endregion //#region src/is-valid-voter-id/is-valid-voter-id.d.ts /** * Validates if a Brazilian voter id (título de eleitor) is valid. * * A voter id normally has 12 digits: an 8-digit sequential number, a 2-digit federative * union code (01-28) and a 2-digit verification code. São Paulo (01) and Minas Gerais (02) * may instead issue voter ids with a 9-digit sequential number, totalling 13 digits. * * Whitespace and dots are accepted around and between the "0000 0000 00 00" groups, but any * other character, a letter in particular, makes the value invalid. * * @param {string} value - The voter id value to be validated. * @returns {boolean} True if the voter id is valid, false otherwise. * * @example * ```typescript * isValidVoterId("102385010671"); // true (12 digits) * isValidVoterId("1234567880191"); // true (13 digits, São Paulo) * isValidVoterId("1023 8501 06 71"); // true (whitespace mask) * isValidVoterId("123456780124"); // false (invalid checksum) * isValidVoterId("ab102385010671"); // false (invalid format) * ``` * * Resolução TSE nº 23.659/2021, art. 36, parágrafo único, confirms the federative union table and * the two-step módulo 11 structure ("até 12 algarismos"). The weights used in each step and the * 13-digit São Paulo/Minas Gerais ids are brutils parity, not published by the TSE — siga0984 uses * a different 9-digit rule for the sequential number. * * The TSE resolution page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser. * * @see Official: https://www.tse.jus.br/legislacao/compilada/res/2021/resolucao-no-23-659-de-26-de-outubro-de-2021 * @see Based on: https://siga0984.wordpress.com/2019/05/01/algoritmos-validacao-de-titulo-de-eleitor/ * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/voter_id.py */ export declare const isValidVoterId: (value: string) => boolean; //#endregion //#region src/parse-boleto/parse-boleto.d.ts /** * Removes boleto formatting characters and returns only digits. * * Bank slips starting with `8` are "arrecadação" (convênio/tributos) slips, whose linha * digitável has 48 digits instead of the 47 of a "cobrança bancária" slip. * * @param {string|number} value - The boleto value to be parsed. * @returns {string} The boleto value without formatting. * * @example * ```typescript * parseBoleto("10491.44338 55119.000002 00000.000141 3 25230000093423"); * // "10491443385511900000200000000141325230000093423" * * parseBoleto("82630000001-1 09880010070-2 02410202400-0 00020510451-9"); * // "826300000011098800100702024102024000000205104519" * ``` * * Carta-Circular BCB nº 2.926/2000 specifies the linha digitável fields and the módulo 11 * check digit (using 1 for remainders 0, 10 and 1) of the 47 digit cobrança bancária slip, * including the position of the fator de vencimento field. The FEBRABAN "Layout Padrão de * Arrecadação/Recebimento com Utilização do Código de Barras" and the FEBRABAN layout index * cover the arrecadação slip. * * @see Official: https://www.bcb.gov.br/pre/normativos/c_circ/2000/pdf/c_circ_2926_v1_O.pdf * @see Official: https://cmsarquivos.febraban.org.br/Arquivos/documentos/PDF/Layout%20-%20C%C3%B3digo%20de%20Barras%20-%20Vers%C3%A3o%208%20-%2011_05_2026.pdf * @see Official: https://portal.febraban.org.br/pagina/3425/33/pt-br/layout-febraban */ export declare const parseBoleto: (value: string | number) => string; //#endregion //#region src/parse-caepf/parse-caepf.d.ts /** * Removes CAEPF (Cadastro de Atividade Econômica da Pessoa Física) formatting characters and * returns only digits. * * The number has 14 digits, 12 of base plus the two check digits, which is the length the result * is capped at; a shorter value passes through as far as it goes. Use `isValidCaepf` to check the * number itself. * * @param {string|number} value - The CAEPF value to be parsed. * @returns {string} Up to 14 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCaepf("293.118.610/001-84"); // "29311861000184" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/caepf * The registry's own page at the Receita Federal, which describes the cadastro but does not print * the mask; the mask is the one the sources cited by `isValidCaepf` agree on. */ export declare const parseCaepf: (value: string | number) => string; //#endregion //#region src/parse-cbo/parse-cbo.d.ts /** * Removes CBO (Classificação Brasileira de Ocupações) formatting characters and returns only * digits. * * An occupation code has 6 digits, which is the length the result is capped at; a shorter value * passes through as far as it goes and is never left padded, so the leading zero of a code such * as `010205` has to be written out. Use `getCbo` or `isValidCbo`, which do pad a bare numeric * code, to look an occupation up. * * @param {string|number} value - The CBO code to be parsed. * @returns {string} Up to 6 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCbo("2124-05"); // "212405" * ``` * * @see Official: https://www.gov.br/trabalho-e-emprego/pt-br/assuntos/cbo/servicos/downloads/cbo2002-ocupacao.csv * The CBO 2002 occupation table, as published by the Ministério do Trabalho e Emprego. */ export declare const parseCbo: (value: string | number) => string; //#endregion //#region src/parse-cei/parse-cei.d.ts /** * Removes CEI (Cadastro Específico do INSS) formatting characters and returns only digits. * * The numbering has 12 digits, 11 of base and one check digit, which is the length the result is * capped at; a shorter value passes through as far as it goes, so the mask of an input still * being typed can be stripped with it. Use `isValidCei` to check the number itself. * * @param {string|number} value - The CEI value to be parsed. * @returns {string} Up to 12 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCei("27.729.71181/87"); // "277297118187" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno * The registry's own page at the Receita Federal, which describes the cadastro but does not print * the mask; the mask is the one the reference implementations cited by `isValidCei` agree on. */ export declare const parseCei: (value: string | number) => string; //#endregion //#region src/parse-cep/parse-cep.d.ts /** * Removes CEP formatting characters and returns only digits. * * @param {string|number} value - The CEP value to be parsed. * @returns {string} The CEP value without formatting. * * @example * ```typescript * parseCep("01310-930"); // "01310930" * ``` * * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/tudo-sobre-cep * @see Official: https://www.correios.com.br/enviar/precisa-de-ajuda/guia-de-enderecamento/guia-de-enderecamento */ export declare const parseCep: (value: string | number) => string; //#endregion //#region src/parse-certidao/parse-certidao.d.ts /** * Removes the formatting of the matrícula of a certidão de registro civil and returns only * digits. * * The matrícula has 32 digits, which is the length the result is capped at; a shorter value * passes through as far as it goes, so the mask of an input still being typed can be stripped * with it. This only takes the mask off: use `isValidCertidao` to check the matrícula and * `getCertidaoInfo` to read its fields. * * @param {string|number} value - The matrícula value to be parsed. * @returns {string} Up to 32 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCertidao("104539 01 55 2013 1 00012 021 0000123 21"); * // "10453901552013100012021000012321" * ``` * * @see Official: https://atos.cnj.jus.br/atos/detalhar/5243 * Código Nacional de Normas da Corregedoria Nacional de Justiça - Foro Extrajudicial (Provimento * CNJ nº 149/2023), art. 473: the in-force 6 + 2 + 2 + 4 + 1 + 5 + 3 + 7 + 2 layout of the 32 * digit matrícula. * @see Official: https://atos.cnj.jus.br/atos/detalhar/1310 * Provimento CNJ nº 3, de 17/11/2009, art. 7º, where that matrícula first got the same digit * structure (revoked; historical). */ export declare const parseCertidao: (value: string | number) => string; //#endregion //#region src/parse-cfop/parse-cfop.d.ts /** * Removes CFOP (Código Fiscal de Operações e Prestações) formatting characters and returns only * digits. * * A code has 4 digits, which is the length the result is capped at; a shorter value passes * through as far as it goes. No CFOP code starts with a zero, its first digit is the operation * group from 1 to 7, so nothing is ever padded here. Use `getCfop` or `isValidCfop` to look a * code up in the official table. * * @param {string|number} value - The CFOP code to be parsed. * @returns {string} Up to 4 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCfop("5.102"); // "5102" * ``` * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/ajustes/sinief/cfop_cvsn_1-6.24 * Consolidated Anexo II of Convênio SINIEF s/nº 1970, which prints the codes in the "N.NNN" form. */ export declare const parseCfop: (value: string | number) => string; //#endregion //#region src/parse-cnae/parse-cnae.d.ts /** * Removes CNAE (Classificação Nacional de Atividades Econômicas) formatting characters and * returns only digits. * * A complete subclass code has 7 digits, which is the length the result is capped at; a shorter * value (a division, a group or a class still being typed) passes through as far as it goes and * is never left padded, so the leading zeros a code carries have to be written out. Use * `getCnae` or `isValidCnae`, which do pad a bare numeric code, to look a code up. * * @param {string|number} value - The CNAE code to be parsed. * @returns {string} Up to 7 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCnae("6201-5/01"); // "6201501" * ``` * * @see Official: https://servicodados.ibge.gov.br/api/v2/cnae/subclasses */ export declare const parseCnae: (value: string | number) => string; //#endregion //#region src/parse-cnh/parse-cnh.d.ts /** * Removes CNH (Carteira Nacional de Habilitação) formatting characters and returns only digits. * * @param {string|number} value - The CNH to be parsed. * @returns {string} Up to 11 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCnh("123456789-00"); // "12345678900" * ``` * * Resolução CONTRAN nº 886/2021, art. 4º I, defines the CNH registry number as 9 characters plus * 2 security check digits, which is the layout this parser caps at; no official text publishes * the check-digit weights used to compute them. * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/Resolucao8862021F.pdf */ export declare const parseCnh: (value: string | number) => string; //#endregion //#region src/parse-cno/parse-cno.d.ts /** * Removes CNO (Cadastro Nacional de Obras) formatting characters and returns only digits. * * The CNO replaced the CEI for construction works and kept its 12 digit numbering, so the result * is capped at the same length; a shorter value passes through as far as it goes. Use * `isValidCno` to check the number itself. * * @param {string|number} value - The CNO value to be parsed. * @returns {string} Up to 12 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCno("11.113.01373/68"); // "111130137368" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno * The registry's own page at the Receita Federal, which describes the cadastro but does not print * the mask; the mask is the one the reference implementations cited by `isValidCno` agree on. */ export declare const parseCno: (value: string | number) => string; //#endregion //#region src/parse-cnpj/parse-cnpj.d.ts /** Options of `parseCnpj`. */ type ParseCnpjOptions = Pick; /** * Removes CNPJ formatting characters and returns a normalized value. * * @param {string|number} value - The CNPJ value to be parsed. * @param {ParseCnpjOptions} [options] - Optional parsing options. * @param {1|2} [options.version] - The CNPJ version to normalize. * @returns {string} The CNPJ value without formatting. * * @example * ```typescript * parseCnpj("11.222.333/0001-81"); // "11222333000181" * parseCnpj("12.ABC.345/01DE-35", { version: 2 }); // "12ABC34501DE35" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cnpj * @see Official: https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/documentos-tecnicos/cnpj/manual-dv-cnpj.pdf * @see Official: https://www.gov.br/receitafederal/pt-br/acesso-a-informacao/acoes-e-programas/programas-e-atividades/cnpj-alfanumerico */ export declare const parseCnpj: (value: string | number, options?: ParseCnpjOptions) => string; //#endregion //#region src/parse-cns/parse-cns.d.ts /** * Removes CNS (Cartão Nacional de Saúde) formatting characters and returns only digits. * * The number the ANVISA and DATASUS routines check has 15 digits, the length the result is * capped at; a shorter value passes through as far as it goes, so the parser can strip the mask * off an input still being typed. Use `isValidCns` to check the number itself. * * @param {string|number} value - The CNS value to be parsed. * @returns {string} Up to 15 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseCns("123 4567 8901 0000"); // "123456789010000" * ``` * * @see Official: https://rni-docs.anvisa.gov.br/docs/regras_gerais/validacoes/validacaoCNS/ * ANVISA's validation routines, which fix the 15 digit length. The page sits behind a bot filter * and answers HTTP 403 to every non-browser client, so it has to be opened in a browser. * @see Based on: https://integracao.esusab.ufsc.br/ledi/documentacao/regras/algoritmo_CNS.html * e-SUS APS documentation of the same DATASUS algorithm, reachable without a browser. */ export declare const parseCns: (value: string | number) => string; //#endregion //#region src/parse-cpf/parse-cpf.d.ts /** * Removes CPF formatting characters and returns only digits. * * @param {string|number} value - The CPF value to be parsed. * @returns {string} The CPF value without formatting. * * @example * ```typescript * parseCpf("123.456.789-09"); // "12345678909" * ``` * * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/meu-cpf * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/cpf.py */ export declare const parseCpf: (value: string | number) => string; //#endregion //#region src/parse-currency/parse-currency.d.ts /** Options of `parseCurrency`. */ type ParseCurrencyOptions = { /** Number of decimal places used as the minor unit scale. Fractions accept up to two digits, or `precision` digits when it is greater. Defaults to 2, clamped to 0-20. */ precision?: number; }; /** * Parses a string representing Brazilian currency format into a number. * * The last `,` or `.` followed by 1 to 2 digits (or up to `precision` digits, when that is * larger) is the decimal separator; every other `,` or `.` is a thousands separator, so * `"R$ 1.234,56"` parses to 1234.56 and `"R$ 1.234"` to 1234. A value written without any * separator keeps the cents convention and is divided by `10 ** precision`, so `"1234"` * parses to 12.34. A `-` written before the first digit is preserved, so `"-R$ 1,00"` parses * to -1. * * The precision is clamped to `0-20`, and a precision that is not a finite number falls back * to 2. * * @param {string} value - The string value to be parsed (e.g., "R$ 1.234,56" or "1234,56") * @param {ParseCurrencyOptions} [options] - Optional parsing options. * @param {number} options.precision - The number of decimal places used as the minor unit scale. Fractions accept up to two digits, or `precision` digits when it is greater. Defaults to 2, clamped to 0-20. * @returns {number} The parsed number value (e.g., 1234.56) * * The `R$` prefix and the comma before the centavos are the ones Lei nº 9.069/1995, art. 1º, * §§ 1º and 2º prescribes; the `.` grouping comes from the CLDR pt-BR locale data. * * @see Official: https://www.planalto.gov.br/ccivil_03/leis/l9069.htm * @see Based on: https://cldr.unicode.org/ * * @example * ```typescript * parseCurrency("R$ 1.234,56"); // returns 1234.56 * parseCurrency("1234,56"); // returns 1234.56 * parseCurrency("R$ 0,50"); // returns 0.50 * parseCurrency("R$ 1.234"); // returns 1234 * parseCurrency("1234"); // returns 12.34 * parseCurrency("-R$ 1,00"); // returns -1 * parseCurrency("R$ 1,001", { precision: 3 }); // returns 1.001 * parseCurrency(""); // returns 0 * ``` */ export declare const parseCurrency: (value: string, options?: ParseCurrencyOptions) => number; //#endregion //#region src/parse-iban/parse-iban.d.ts /** * Removes IBAN formatting characters, uppercases the result and returns the compact IBAN. * * An IBAN carries letters as well as digits (the country code, the account type and, from the * tenth holder on, the owner indicator), so the value is read for its letters and digits rather * than for its digits alone, exactly like `parsePassport` and `formatIban` do. The result is * capped at the 29 characters of a Brazilian IBAN, the same cap `formatIban` applies, and a * shorter value passes through as far as it goes. Use `isValidIban` to check the check digits and * `getIbanInfo` to read the fields. * * @param {string|number} value - The IBAN to be parsed. * @returns {string} Up to 29 uppercase alphanumeric characters, or an empty string when there is * no letter or digit at all. * * @example * ```typescript * parseIban("BR15 0000 0000 0000 1093 2840 814P 2"); // "BR1500000000000010932840814P2" * ``` * * @see Official: https://www.bcb.gov.br/pre/normativos/circ/2013/pdf/circ_3625_v1_O.pdf * Circular BCB nº 3.625/2013 * @see Official: https://www.bcb.gov.br/content/estabilidadefinanceira/Documents/sistema_pagamentos_brasileiro/IBAN-Guidelines_%20port.pdf * Diretrizes de Implementação do IBAN no Brasil, which fix the 29 character Brazilian length. */ export declare const parseIban: (value: string | number) => string; //#endregion //#region src/parse-legal-nature/parse-legal-nature.d.ts /** * Removes legal nature (natureza jurídica) formatting characters and returns only digits. * * @param {string|number} value - The legal nature code to be parsed. * @returns {string} Up to 4 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseLegalNature("206-2"); // "2062" * ``` * * The CONCLA table page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser; the detailed structure PDF next to it is served * normally. * * @see Official: https://concla.ibge.gov.br/estrutura/natjur-estrutura/natureza-juridica-2021 * @see Official: https://concla.ibge.gov.br/images/concla/documentacao/CONCLA-TNJ2021-EstruturaDetalhada.pdf */ export declare const parseLegalNature: (value: string | number) => string; //#endregion //#region src/parse-license-plate/parse-license-plate.d.ts /** * Removes license plate formatting characters and returns only uppercase alphanumerics. * * @param {string} value - The license plate to be parsed. * @returns {string} Up to 7 uppercase alphanumeric characters, or an empty string when the * value is not a string. * * @example * ```typescript * parseLicensePlate("abc-1234"); // "ABC1234" * ``` * * @see Official: https://www.gov.br/transportes/pt-br/assuntos/transito/conteudo-contran/resolucoes/resolucao9692022.pdf */ export declare const parseLicensePlate: (value: string) => string; //#endregion //#region src/parse-ncm/parse-ncm.d.ts /** * Removes NCM (Nomenclatura Comum do Mercosul) formatting characters and returns only digits. * * A complete code has 8 digits, which is the length the result is capped at; a shorter value (a * position or a subposition, or a code still being typed) passes through as far as it goes and is * never left padded, so the leading zeros a code carries have to be written out. Use `isValidNcm`, * which does pad a bare numeric code, to check a code against the official table. * * @param {string|number} value - The NCM code to be parsed. * @returns {string} Up to 8 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseNcm("8471.30.12"); // "84713012" * ``` * * @see Official: https://portalunico.siscomex.gov.br/classif/api/publico/nomenclatura/download/json */ export declare const parseNcm: (value: string | number) => string; //#endregion //#region src/parse-nfe-key/parse-nfe-key.d.ts /** * Removes the formatting of a DF-e (Documento Fiscal eletrônico) access key (chave de acesso) and * returns only digits. * * The `NFe`, `CTe`, `MDFe`, `BPe`, `NF3e` and `NFCom` prefixes the `Id` attribute of the * document's XML puts in front of the key are stripped before the digits are read, with any * whitespace around them, the same way `isValidNfeKey` accepts them. The prefix has to go first * because `NF3e` carries a digit of its own that is not part of the key. * * The result is capped at the 44 digits of an access key; a shorter value passes through as far * as it goes, so the grouping of a key still being typed can be stripped with it. Use * `isValidNfeKey` to check the key and `getNfeKeyInfo` to read its fields. * * @param {string|number} value - The access key value to be parsed. * @returns {string} Up to 44 digits, or an empty string when there is no digit at all. * * @example * ```typescript * parseNfeKey("3517 0458 7165 2300 0119 5500 1000 0000 1210 0012 3458"); * // "35170458716523000119550010000000121000123458" * * parseNfeKey("NFe35170458716523000119550010000000121000123458"); * // "35170458716523000119550010000000121000123458" * ``` * * @see Official: https://www.confaz.fazenda.gov.br/legislacao/arquivo-manuais/moc7-visao-geral.pdf * Manual de Orientação do Contribuinte (MOC) NF-e, "chave de acesso", which fixes the 44 digits * and the `Id` attribute the prefixes come from. */ export declare const parseNfeKey: (value: string | number) => string; //#endregion //#region src/parse-passport/parse-passport.d.ts /** * Removes non-alphanumeric characters from a passport number, uppercases it, and caps it to 8 characters. * * @param {string} passport - The string containing a passport number. * @returns {string} The normalized passport number, or an empty string when the value is not * a string (a number is never a passport number: the series is two letters). * * @example * parsePassport("Ab123456") // "AB123456" * parsePassport("Ab-123456") // "AB123456" * parsePassport("Ab -. 123456") // "AB123456" * * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte * @see Official: https://www.gov.br/pf/pt-br/assuntos/passaporte/ajuda/duvidas_/caderneta/caderneta-numero-onde-fica-e */ export declare const parsePassport: (passport: string) => string; //#endregion //#region src/parse-phone/parse-phone.d.ts /** * Removes phone formatting characters, returns only digits, and caps the result to 11 digits. * * A Brazilian country code is stripped first, under a single rule: the leading `0055` or `55` * is removed **only when** the digits left behind are exactly 10 or 11 long, i.e. a plausible * national number (DDD plus an 8 or 9 digit subscriber number). Any other input keeps its * digits, so a number from the `55` area code survives: `"55987654321"` would leave only 9 * digits, so its `55` is read as the DDD. The rule is length-based, not sign-based, which * makes `"+5511987654321"`, `"005511987654321"` and `"5511987654321"` all parse alike. * * @param {string|number} value - The phone value to be parsed. * @returns {string} The phone value without formatting. * * @example * ```typescript * parsePhone("(11) 98765-4321"); // "11987654321" * parsePhone("+55 (11) 98765-4321"); // "11987654321" * parsePhone("5511987654321"); // "11987654321" * parsePhone("55987654321"); // "55987654321" (area code 55, country code kept out of it) * ``` * * @see Official: https://www.itu.int/rec/T-REC-E.164 * @see Official: https://informacoes.anatel.gov.br/legislacao/resolucoes/2022/1641-resolucao-749 */ export declare const parsePhone: (value: string | number) => string; //#endregion //#region src/parse-pis/parse-pis.d.ts /** * Removes PIS formatting characters and returns only digits. * * @param {string|number} value - The PIS value to be parsed. * @returns {string} The PIS value without formatting. * * @example * ```typescript * parsePis("120.12345.67-8"); // "12012345678" * ``` * * @see Official: https://www.gov.br/inss/pt-br/direitos-e-deveres/inscricao-e-contribuicao/inscricao * @see Official: https://www.gov.br/esocial/pt-br/documentacao-tecnica/manuais/mos-manual-de-orientacao-do-esocial-vs-2-4.pdf * @see Official: https://www.sirc.gov.br/wp-content/uploads/manual_sirc_recomendacoes_tecnicas_v7.pdf * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/pis.py */ export declare const parsePis: (value: string | number) => string; //#endregion //#region src/parse-processo-juridico/parse-processo-juridico.d.ts /** * Removes legal process formatting characters and returns only digits. * * @param {string|number} value - The legal process value to be parsed. * @returns {string} The legal process value without formatting. * * @example * ```typescript * parseProcessoJuridico("0002080-34.2026.5.15.0049"); // "00020803420265150049" * ``` * * Resolução CNJ nº 65/2008 defines this Número Único de Processo layout and its check digits. * * @see Official: https://atos.cnj.jus.br/atos/detalhar/119 */ export declare const parseProcessoJuridico: (value: string | number) => string; //#endregion //#region src/parse-voter-id/parse-voter-id.d.ts /** * Removes voter id (título de eleitor) formatting characters and returns only digits. * * Keeps up to 13 digits when the 10th and 11th digits identify São Paulo ("01") or Minas * Gerais ("02"), since those states may issue voter ids with a 9-digit sequential number; * otherwise keeps up to the usual 12 digits. * * @param {string|number} value - The voter id value to be parsed. * @returns {string} The voter id value without formatting. * * @example * ```typescript * parseVoterId("1234 5678 01 24"); // "123456780124" * parseVoterId("1234 5678 8 01 91"); // "1234567880191" * ``` * * The 13-digit São Paulo/Minas Gerais cap is brutils parity, not published by the TSE. A * 14-or-more-digit input whose 10th and 11th digits are "01"/"02" is read as a 13-digit São Paulo * or Minas Gerais id and capped at 13 digits, discarding anything past that. * * The TSE resolution page sits behind a bot filter and answers HTTP 403 to every non-browser * client, so it has to be opened in a browser. * * @see Official: https://www.tse.jus.br/legislacao/compilada/res/2021/resolucao-no-23-659-de-26-de-outubro-de-2021 * @see Based on: https://github.com/brazilian-utils/python/blob/main/brutils/voter_id.py */ export declare const parseVoterId: (value: string | number) => string; //#endregion //#region src/remove-accents/remove-accents.d.ts /** * Removes diacritical marks (accents, tildes, cedillas) from a string, decomposing every * accented character into its base letter plus combining marks (Unicode NFD) and then * dropping every combining mark (Unicode general category M, so accents from any script). * * @param {string} value - The text to strip accents from. * @returns {string} The text with every diacritical mark removed. `""` when `value` is not a * non-empty string. * * @see Official: https://unicode.org/reports/tr15/ * @see Official: https://www.unicode.org/reports/tr44/#General_Category_Values * * @example * ```typescript * removeAccents("São Paulo"); // "Sao Paulo" * removeAccents("Piauí"); // "Piaui" * removeAccents("Ceará"); // "Ceara" * removeAccents("Açaí"); // "Acai" * removeAccents(""); // "" * ``` */ export declare const removeAccents: (value: string) => string; //#endregion //#region src/sub-business-days/sub-business-days.d.ts /** * Subtracts a number of Brazilian business days (dias úteis) from a date. * * The mirror image of `addBusinessDays`, which it delegates to: `subBusinessDays(date, amount)` * is `addBusinessDays(date, -amount)`, down to the last detail. A business day is a day for * which `isBusinessDay` returns `true` (not a Saturday, a Sunday, or a Brazilian holiday), * evaluated with the same `options`, and the walk goes one calendar day at a time, counting only * business days. * * `amount: 0` returns a **new `Date` equal to `date`, unchanged**, even when `date` itself falls * on a weekend or holiday, and a negative `amount` walks *forwards*, exactly like date-fns' * `subBusinessDays`. * * The time-of-day (hours, minutes, seconds, milliseconds) of `date` is preserved in the result, * and `date` itself is never mutated. * * If `options.stateCode` is provided but is not a valid/known state code, it is ignored and only * national holidays are considered (same behavior as `getHolidays`/`isBusinessDay`), so a * prototype-chain key such as `"__proto__"` is an unknown state code like any other. An `options` * that is not an object at all is ignored, exactly as `isBusinessDay` ignores it. * * Only years from 1900 through 2099 are supported, the range `getHolidays` computes. A `date` * outside it, or a walk that leaves it, returns `null`. * * @param {Date} date - The date to count from. Never mutated: a new `Date` is returned. * @param {number} amount - The number of business days to subtract; a negative value walks forwards. * @param {BusinessDayOptions} [options] - Which holidays count as non-business days. * @param {StateCode} [options.stateCode] - Brazilian state code whose state holidays are also considered. * @param {boolean} [options.includeOptional] - Whether optional holidays count as non-business days (default: `true`). * @returns {Date | null} A new `Date`, `amount` business days before `date`. `null` on bad input: * a `date` that is not a valid `Date` or is outside 1900-2099, an `amount` that is not a finite * integer, a `stateCode` that is not a string, or a walk that leaves the supported years. * * @example * ```typescript * subBusinessDays(new Date(2024, 0, 5, 12), 1); // Thu 2024-01-04, 12:00 (the previous day is already a business day) * subBusinessDays(new Date(2024, 0, 8, 12), 1); // Fri 2024-01-05, 12:00 (walks back over the weekend) * subBusinessDays(new Date(2025, 0, 2, 12), 1); // Tue 2024-12-31, 12:00 (Jan 1 is Ano novo, skipped) * subBusinessDays(new Date(2024, 0, 5, 12), -1); // Mon 2024-01-08, 12:00 (walks forwards) * subBusinessDays(new Date(2024, 0, 6, 12), 0); // Sat 2024-01-06, 12:00 (unchanged, even though Saturday is not a business day) * subBusinessDays(new Date(2024, 6, 10, 12), 1, { stateCode: "SP" }); // Mon 2024-07-08, 12:00 (Jul 9 is a state holiday in SP) * subBusinessDays(new Date("not a date"), 1); // null * subBusinessDays(new Date(2024, 0, 2), 1.5); // null (not an integer) * subBusinessDays(new Date(1900, 0, 2), 1); // null (the walk leaves the supported years) * ``` * * @see Based on: https://date-fns.org/docs/subBusinessDays * Reference behavior and the positional * `(date, amount)` argument order. The underlying holiday determination's official sources are * cited in `isBusinessDay`/`getHolidays`. */ export declare const subBusinessDays: (date: Date, amount: number, options?: BusinessDayOptions) => Date | null; //#endregion //#region src/index.d.ts /** * Formats a CEP, the 1.x name of `formatCep`. * * @deprecated Use `formatCep` instead. */ export declare const formatCEP: typeof formatCep; /** * Formats a CNPJ, the 1.x name of `formatCnpj`. * * @deprecated Use `formatCnpj` instead. */ export declare const formatCNPJ: typeof formatCnpj; /** * Formats a CPF, the 1.x name of `formatCpf`. * * @deprecated Use `formatCpf` instead. */ export declare const formatCPF: typeof formatCpf; /** * Generates a valid random CNPJ, the 1.x name of `generateCnpj`. * * @deprecated Use `generateCnpj` instead. */ export declare const generateCNPJ: typeof generateCnpj; /** * Generates a valid random CPF, the 1.x name of `generateCpf`. * * @deprecated Use `generateCpf` instead. */ export declare const generateCPF: typeof generateCpf; /** * Checks whether a CEP is valid, the 1.x name of `isValidCep`. * * @deprecated Use `isValidCep` instead. */ export declare const isValidCEP: typeof isValidCep; /** * Checks whether a CNPJ is valid, the 1.x name of `isValidCnpj`. * * @deprecated Use `isValidCnpj` instead. */ export declare const isValidCNPJ: typeof isValidCnpj; /** * Checks whether a CPF is valid, the 1.x name of `isValidCpf`. * * @deprecated Use `isValidCpf` instead. */ export declare const isValidCPF: typeof isValidCpf; /** * Checks whether a state registration (inscrição estadual) is valid, the 1.x name of `isValidIe`. * * @deprecated Use `isValidIe` instead. */ export declare const isValidIE: typeof isValidIe; /** * Checks whether a PIS/PASEP is valid, the 1.x name of `isValidPis`. * * @deprecated Use `isValidPis` instead. */ export declare const isValidPIS: typeof isValidPis; //#endregion export type { AddressInfo, AreaCodeInfo, Bank, BoletoInfo, BusinessDayOptions, CapitalizeOptions, Cbo, CepAddressInfo, CepProvider, CertidaoInfo, CertidaoType, Cfop, Cnae, ConvertDateToWordsOptions, ConvertNumberToWordsOptions, FormatBoletoOptions, FormatCaepfOptions, FormatCeiOptions, FormatCepOptions, FormatCertidaoOptions, FormatCnaeOptions, FormatCnhOptions, FormatCnoOptions, FormatCnpjOptions, FormatCnsOptions, FormatCpfOptions, FormatCurrencyOptions, FormatLegalNatureOptions, FormatNcmOptions, FormatNfeKeyOptions, FormatPhoneOptions, FormatPisOptions, FormatProcessoJuridicoOptions, GenerateBoletoParams, GenerateCnpjParams, GenerateLicensePlateFormat, GeneratePhoneType, GeneratePixPayloadParams, GenerateProcessoJuridicoOptions, GenerateProcessoJuridicoParams, GetAddressInfoByCepOptions, GetBoletoInfoOptions, GetCepInfoByAddressOptions, GetCepInfoByAddressParams, GetHolidaysOptions, GetHolidaysParams, GetLegalNaturesByCategoryOptions, GetLegalNaturesParams, GetMunicipalityByCodeOptions, GetMunicipalityByCodeParams, GetMunicipalityByNameOptions, GetMunicipalityByNameParams, GetMunicipalityOptions, GetMunicipalityParams, Holiday, HolidayType, IbanInfo, IsHolidayOptions, IsHolidayParams, IsValidBankAccountOptions, IsValidBankAccountParams, IsValidCertidaoOptions, IsValidCnpjOptions, IsValidCstOptions, IsValidIeParams, IsValidMobilePhoneOptions, IsValidPhoneOptions, IsValidPixKeyOptions, IsValidRegistroProfissionalParams, LegalNature, LegalNatureCategory, LicensePlateFormat, Municipality, NfeKeyInfo, NfeKeyModel, NumberToWordsGender, ParseCnpjOptions, ParseCurrencyOptions, PhoneMask, PhoneType, PhoneVersion, PixKeyInfo, PixKeyType, PixPayloadInfo, PixPointOfInitiation, RegistroProfissionalCouncil, State, StateCode, StateName }; //# sourceMappingURL=brazilian-utils.d.ts.map