Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

js-brasil

Package Overview
Dependencies
Maintainers
1
Versions
86
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

js-brasil - npm Package Compare versions

Comparing version 1.0.4 to 1.0.5

dist/test/faker.js

5

dist/index.js

@@ -6,3 +6,3 @@ "use strict";

var inscricaoestadual_1 = require("./src/inscricaoestadual");
var faker_1 = require("./src/faker");
var faker = require("./src/faker");
exports.validateBr = {

@@ -25,5 +25,6 @@ cep: validate_1.valida_cep,

};
exports.fakerBr = faker.fakerBr;
exports.default = {
validateBr: exports.validateBr, utilsBr: exports.utilsBr, fakerBr: faker_1.fakerBr
validateBr: exports.validateBr, utilsBr: exports.utilsBr, fakerBr: exports.fakerBr
};
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
var generateMasks = function () {
var fake = {};
var _loop_1 = function (key) {
if (!key) {
return "continue";
}
var val = utils_1.MASKS[key];
// cpf: {
// text: '000.000.000-00',
// textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]
// },
fake[key] = function () {
return val.textMask.map(function (c) {
if (c === /\d/) {
return Math.floor(Math.random() * 10);
}
else if (c === /[A-Za-z]/) {
var num = Math.floor((Math.random() * 57)) + 65;
return Math.floor(Math.random() * 10);
}
else if (c === /[1-9]/) {
return Math.floor(Math.random() * 9) + 1;
}
else {
return c;
}
});
};
var validate_1 = require("./validate");
var randexp_1 = require("randexp");
var makeGeneric = function (val) {
return function () {
var newData = val.textMask.map(function (c) {
c = c.toString();
if (c === /\d/.toString()) {
return Math.floor(Math.random() * 10);
}
else if (c === /[A-Za-z]/.toString()) {
var num = Math.floor((Math.random() * 57)) + 65;
return String.fromCharCode(num);
}
else if (c === /[1-9]/.toString()) {
return Math.floor(Math.random() * 9) + 1;
}
else {
return c;
}
});
return newData.join('');
};
for (var key in utils_1.MASKS) {
_loop_1(key);
}
};
exports.fakerBr = generateMasks();
exports.fakerBr = {
cep: makeGeneric(utils_1.MASKS['cep']),
cepState: function (state) {
return randexp_1.randexp(validate_1.CEPRange[state]);
},
cpf: function () {
var cpf = makeGeneric(utils_1.MASKS['cpf'])();
var restos = validate_1.create_cpf(cpf);
return cpf.substr(0, cpf.length - 2) + restos[0] + restos[1];
},
cnpj: function () {
var cnpj = makeGeneric(utils_1.MASKS['cnpj'])();
cnpj = cnpj.replace(/[^\d]+/g, '');
var restos = validate_1.create_cnpj(cnpj);
cnpj = cnpj.substr(0, cnpj.length - 2) + restos[0] + restos[0];
restos = validate_1.create_cnpj(cnpj);
return cnpj.substr(0, cnpj.length - 1) + restos[1];
},
rg: makeGeneric(utils_1.MASKS['rg']),
telefone: makeGeneric(utils_1.MASKS['telefone']),
inscricaoestadual: makeGeneric(utils_1.MASKS['inscricaoestadual']),
time: makeGeneric(utils_1.MASKS['time']),
// currency: makeGeneric(MASKS['currency']),
percentage: makeGeneric(utils_1.MASKS['percentage']),
placa: makeGeneric(utils_1.MASKS['placa']),
titulo: makeGeneric(utils_1.MASKS['titulo'])
};
//# sourceMappingURL=faker.js.map

2

dist/src/utils.js

@@ -33,3 +33,3 @@ "use strict";

}
if (!userInput || numberLength > 10) {
if (!userInput || numberLength > 10) { // || ddd in DDD5digits
return ['(', /[1-9]/, /[1-9]/, ')', ' ', /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];

@@ -36,0 +36,0 @@ }

@@ -9,2 +9,16 @@ "use strict";

cnpj = cnpj.replace(/[^\d]+/g, '');
var tamanho = cnpj.length - 2;
var digitos = cnpj.substring(tamanho);
var resultados = create_cnpj(cnpj);
if (resultados[0] !== parseInt(digitos.charAt(0), 10)) {
return false;
}
if (resultados[1] !== parseInt(digitos.charAt(1), 10)) {
return false;
}
return true;
}
exports.validate_cnpj = validate_cnpj;
function create_cnpj(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g, '');
if (cnpj === '') {

@@ -32,3 +46,2 @@ return false;

var numeros = cnpj.substring(0, tamanho);
var digitos = cnpj.substring(tamanho);
var soma = 0;

@@ -42,6 +55,4 @@ var pos = tamanho - 7;

}
var resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado !== parseInt(digitos.charAt(0), 10)) {
return false;
}
var resultados = [0, 0];
resultados[0] = soma % 11 < 2 ? 0 : 11 - soma % 11;
tamanho = tamanho + 1;

@@ -57,11 +68,20 @@ numeros = cnpj.substring(0, tamanho);

}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado !== parseInt(digitos.charAt(1), 10)) {
resultados[1] = soma % 11 < 2 ? 0 : 11 - soma % 11;
return resultados;
}
exports.create_cnpj = create_cnpj;
// http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/funcoes.js
function validate_cpf(strCPF) {
strCPF = strCPF.replace(/[^\d]+/g, '');
var restos = create_cpf(strCPF);
if (restos[0] !== parseInt(strCPF.substring(9, 10), 10)) {
return false;
}
if (restos[1] !== parseInt(strCPF.substring(10, 11), 10)) {
return false;
}
return true;
}
exports.validate_cnpj = validate_cnpj;
// http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/funcoes.js
function validate_cpf(strCPF) {
exports.validate_cpf = validate_cpf;
function create_cpf(strCPF) {
strCPF = strCPF.replace(/[^\d]+/g, '');

@@ -82,5 +102,4 @@ var soma;

}
if (resto !== parseInt(strCPF.substring(9, 10), 10)) {
return false;
}
var restos = [];
restos.push(resto);
soma = 0;

@@ -94,9 +113,7 @@ for (var i = 1; i <= 10; i++) {

}
if (resto !== parseInt(strCPF.substring(10, 11), 10)) {
return false;
}
return true;
restos.push(resto);
return restos;
}
exports.validate_cpf = validate_cpf;
var CEPRange = {
exports.create_cpf = create_cpf;
exports.CEPRange = {
'SP': /^([1][0-9]{3}|[01][0-9]{4})[0-9]{3}$/g,

@@ -142,4 +159,4 @@ 'RJ': /^[2][0-8][0-9]{3}[0-9]{3}$/g,

cep = parseInt(cep, 10);
var found = Object.keys(CEPRange).find(function (estado) {
var r = new RegExp(CEPRange[estado]).test(cep);
var found = Object.keys(exports.CEPRange).find(function (estado) {
var r = new RegExp(exports.CEPRange[estado]).test(cep);
if (r) {

@@ -172,3 +189,3 @@ return true;

var state = rg.substr(0, 2).toUpperCase();
if (!exp.test(rg) && !expClean.test(rgClean) && !(state in CEPRange)) {
if (!exp.test(rg) && !expClean.test(rgClean) && !(state in exports.CEPRange)) {
return false;

@@ -175,0 +192,0 @@ }

@@ -9,3 +9,3 @@ import {

import { validar } from './src/inscricaoestadual';
import { fakerBr } from './src/faker';
import * as faker from './src/faker';

@@ -31,4 +31,6 @@ export const validateBr = {

export const fakerBr = faker.fakerBr;
export default {
validateBr, utilsBr, fakerBr
}

@@ -7,3 +7,3 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsbrasil = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

var inscricaoestadual_1 = require("./src/inscricaoestadual");
var faker_1 = require("./src/faker");
var faker = require("./src/faker");
exports.validateBr = {

@@ -26,4 +26,5 @@ cep: validate_1.valida_cep,

};
exports.fakerBr = faker.fakerBr;
exports.default = {
validateBr: exports.validateBr, utilsBr: exports.utilsBr, fakerBr: faker_1.fakerBr
validateBr: exports.validateBr, utilsBr: exports.utilsBr, fakerBr: exports.fakerBr
};

@@ -35,38 +36,54 @@

var utils_1 = require("./utils");
var generateMasks = function () {
var fake = {};
var _loop_1 = function (key) {
if (!key) {
return "continue";
}
var val = utils_1.MASKS[key];
// cpf: {
// text: '000.000.000-00',
// textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]
// },
fake[key] = function () {
return val.textMask.map(function (c) {
if (c === /\d/) {
return Math.floor(Math.random() * 10);
}
else if (c === /[A-Za-z]/) {
var num = Math.floor((Math.random() * 57)) + 65;
return Math.floor(Math.random() * 10);
}
else if (c === /[1-9]/) {
return Math.floor(Math.random() * 9) + 1;
}
else {
return c;
}
});
};
var validate_1 = require("./validate");
var randexp_1 = require("randexp");
var makeGeneric = function (val) {
return function () {
var newData = val.textMask.map(function (c) {
c = c.toString();
if (c === /\d/.toString()) {
return Math.floor(Math.random() * 10);
}
else if (c === /[A-Za-z]/.toString()) {
var num = Math.floor((Math.random() * 57)) + 65;
return String.fromCharCode(num);
}
else if (c === /[1-9]/.toString()) {
return Math.floor(Math.random() * 9) + 1;
}
else {
return c;
}
});
return newData.join('');
};
for (var key in utils_1.MASKS) {
_loop_1(key);
}
};
exports.fakerBr = generateMasks();
exports.fakerBr = {
cep: makeGeneric(utils_1.MASKS['cep']),
cepState: function (state) {
return randexp_1.randexp(validate_1.CEPRange[state]);
},
cpf: function () {
var cpf = makeGeneric(utils_1.MASKS['cpf'])();
var restos = validate_1.create_cpf(cpf);
return cpf.substr(0, cpf.length - 2) + restos[0] + restos[1];
},
cnpj: function () {
var cnpj = makeGeneric(utils_1.MASKS['cnpj'])();
cnpj = cnpj.replace(/[^\d]+/g, '');
var restos = validate_1.create_cnpj(cnpj);
cnpj = cnpj.substr(0, cnpj.length - 2) + restos[0] + restos[0];
restos = validate_1.create_cnpj(cnpj);
return cnpj.substr(0, cnpj.length - 1) + restos[1];
},
rg: makeGeneric(utils_1.MASKS['rg']),
telefone: makeGeneric(utils_1.MASKS['telefone']),
inscricaoestadual: makeGeneric(utils_1.MASKS['inscricaoestadual']),
time: makeGeneric(utils_1.MASKS['time']),
// currency: makeGeneric(MASKS['currency']),
percentage: makeGeneric(utils_1.MASKS['percentage']),
placa: makeGeneric(utils_1.MASKS['placa']),
titulo: makeGeneric(utils_1.MASKS['titulo'])
};
},{"./utils":4}],3:[function(require,module,exports){
},{"./utils":4,"./validate":5,"randexp":7}],3:[function(require,module,exports){
"use strict";

@@ -780,3 +797,3 @@ /**

}
if (!userInput || numberLength > 10) {
if (!userInput || numberLength > 10) { // || ddd in DDD5digits
return ['(', /[1-9]/, /[1-9]/, ')', ' ', /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];

@@ -836,3 +853,3 @@ }

},{"./inscricaoestadual":3,"text-mask-addons/dist/createNumberMask":6}],5:[function(require,module,exports){
},{"./inscricaoestadual":3,"text-mask-addons/dist/createNumberMask":13}],5:[function(require,module,exports){
"use strict";

@@ -846,2 +863,16 @@ Object.defineProperty(exports, "__esModule", { value: true });

cnpj = cnpj.replace(/[^\d]+/g, '');
var tamanho = cnpj.length - 2;
var digitos = cnpj.substring(tamanho);
var resultados = create_cnpj(cnpj);
if (resultados[0] !== parseInt(digitos.charAt(0), 10)) {
return false;
}
if (resultados[1] !== parseInt(digitos.charAt(1), 10)) {
return false;
}
return true;
}
exports.validate_cnpj = validate_cnpj;
function create_cnpj(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g, '');
if (cnpj === '') {

@@ -869,3 +900,2 @@ return false;

var numeros = cnpj.substring(0, tamanho);
var digitos = cnpj.substring(tamanho);
var soma = 0;

@@ -879,6 +909,4 @@ var pos = tamanho - 7;

}
var resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado !== parseInt(digitos.charAt(0), 10)) {
return false;
}
var resultados = [0, 0];
resultados[0] = soma % 11 < 2 ? 0 : 11 - soma % 11;
tamanho = tamanho + 1;

@@ -894,11 +922,20 @@ numeros = cnpj.substring(0, tamanho);

}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado !== parseInt(digitos.charAt(1), 10)) {
resultados[1] = soma % 11 < 2 ? 0 : 11 - soma % 11;
return resultados;
}
exports.create_cnpj = create_cnpj;
// http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/funcoes.js
function validate_cpf(strCPF) {
strCPF = strCPF.replace(/[^\d]+/g, '');
var restos = create_cpf(strCPF);
if (restos[0] !== parseInt(strCPF.substring(9, 10), 10)) {
return false;
}
if (restos[1] !== parseInt(strCPF.substring(10, 11), 10)) {
return false;
}
return true;
}
exports.validate_cnpj = validate_cnpj;
// http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/funcoes.js
function validate_cpf(strCPF) {
exports.validate_cpf = validate_cpf;
function create_cpf(strCPF) {
strCPF = strCPF.replace(/[^\d]+/g, '');

@@ -919,5 +956,4 @@ var soma;

}
if (resto !== parseInt(strCPF.substring(9, 10), 10)) {
return false;
}
var restos = [];
restos.push(resto);
soma = 0;

@@ -931,9 +967,7 @@ for (var i = 1; i <= 10; i++) {

}
if (resto !== parseInt(strCPF.substring(10, 11), 10)) {
return false;
}
return true;
restos.push(resto);
return restos;
}
exports.validate_cpf = validate_cpf;
var CEPRange = {
exports.create_cpf = create_cpf;
exports.CEPRange = {
'SP': /^([1][0-9]{3}|[01][0-9]{4})[0-9]{3}$/g,

@@ -979,4 +1013,4 @@ 'RJ': /^[2][0-8][0-9]{3}[0-9]{3}$/g,

cep = parseInt(cep, 10);
var found = Object.keys(CEPRange).find(function (estado) {
var r = new RegExp(CEPRange[estado]).test(cep);
var found = Object.keys(exports.CEPRange).find(function (estado) {
var r = new RegExp(exports.CEPRange[estado]).test(cep);
if (r) {

@@ -1009,3 +1043,3 @@ return true;

var state = rg.substr(0, 2).toUpperCase();
if (!exp.test(rg) && !expClean.test(rgClean) && !(state in CEPRange)) {
if (!exp.test(rg) && !expClean.test(rgClean) && !(state in exports.CEPRange)) {
return false;

@@ -1110,4 +1144,909 @@ }

},{}],6:[function(require,module,exports){
/* eslint indent: ["warn", 4] */
// Private helper class
class SubRange {
constructor(low, high) {
this.low = low;
this.high = high;
this.length = 1 + high - low;
}
overlaps(range) {
return !(this.high < range.low || this.low > range.high);
}
touches(range) {
return !(this.high + 1 < range.low || this.low - 1 > range.high);
}
// Returns inclusive combination of SubRanges as a SubRange.
add(range) {
return new SubRange(
Math.min(this.low, range.low),
Math.max(this.high, range.high)
);
}
// Returns subtraction of SubRanges as an array of SubRanges.
// (There's a case where subtraction divides it in 2)
subtract(range) {
if (range.low <= this.low && range.high >= this.high) {
return [];
} else if (range.low > this.low && range.high < this.high) {
return [
new SubRange(this.low, range.low - 1),
new SubRange(range.high + 1, this.high)
];
} else if (range.low <= this.low) {
return [new SubRange(range.high + 1, this.high)];
} else {
return [new SubRange(this.low, range.low - 1)];
}
}
toString() {
return this.low == this.high ?
this.low.toString() : this.low + '-' + this.high;
}
}
class DRange {
constructor(a, b) {
this.ranges = [];
this.length = 0;
if (a != null) this.add(a, b);
}
_update_length() {
this.length = this.ranges.reduce((previous, range) => {
return previous + range.length;
}, 0);
}
add(a, b) {
const _add = (subrange) => {
let i = 0;
while (i < this.ranges.length && !subrange.touches(this.ranges[i])) {
i++;
}
const newRanges = this.ranges.slice(0, i);
while (i < this.ranges.length && subrange.touches(this.ranges[i])) {
subrange = subrange.add(this.ranges[i]);
i++;
}
newRanges.push(subrange);
this.ranges = newRanges.concat(this.ranges.slice(i));
this._update_length();
};
if (a instanceof DRange) {
a.ranges.forEach(_add);
} else {
if (b == null) b = a;
_add(new SubRange(a, b));
}
return this;
}
subtract(a, b) {
const _subtract = (subrange) => {
let i = 0;
while (i < this.ranges.length && !subrange.overlaps(this.ranges[i])) {
i++;
}
let newRanges = this.ranges.slice(0, i);
while (i < this.ranges.length && subrange.overlaps(this.ranges[i])) {
newRanges = newRanges.concat(this.ranges[i].subtract(subrange));
i++;
}
this.ranges = newRanges.concat(this.ranges.slice(i));
this._update_length();
};
if (a instanceof DRange) {
a.ranges.forEach(_subtract);
} else {
if (b == null) b = a;
_subtract(new SubRange(a, b));
}
return this;
}
intersect(a, b) {
const newRanges = [];
const _intersect = (subrange) => {
let i = 0;
while (i < this.ranges.length && !subrange.overlaps(this.ranges[i])) {
i++;
}
while (i < this.ranges.length && subrange.overlaps(this.ranges[i])) {
let low = Math.max(this.ranges[i].low, subrange.low);
let high = Math.min(this.ranges[i].high, subrange.high);
newRanges.push(new SubRange(low, high));
i++;
}
};
if (a instanceof DRange) {
a.ranges.forEach(_intersect);
} else {
if (b == null) b = a;
_intersect(new SubRange(a, b));
}
this.ranges = newRanges;
this._update_length();
return this;
}
index(index) {
let i = 0;
while (i < this.ranges.length && this.ranges[i].length <= index) {
index -= this.ranges[i].length;
i++;
}
return this.ranges[i].low + index;
}
toString() {
return '[ ' + this.ranges.join(', ') + ' ]';
}
clone() {
return new DRange(this);
}
numbers() {
return this.ranges.reduce((result, subrange) => {
let i = subrange.low;
while (i <= subrange.high) {
result.push(i);
i++;
}
return result;
}, []);
}
subranges() {
return this.ranges.map((subrange) => ({
low: subrange.low,
high: subrange.high,
length: 1 + subrange.high - subrange.low
}));
}
}
module.exports = DRange;
},{}],7:[function(require,module,exports){
const ret = require('ret');
const DRange = require('drange');
const types = ret.types;
module.exports = class RandExp {
/**
* @constructor
* @param {RegExp|String} regexp
* @param {String} m
*/
constructor(regexp, m) {
this._setDefaults(regexp);
if (regexp instanceof RegExp) {
this.ignoreCase = regexp.ignoreCase;
this.multiline = regexp.multiline;
regexp = regexp.source;
} else if (typeof regexp === 'string') {
this.ignoreCase = m && m.indexOf('i') !== -1;
this.multiline = m && m.indexOf('m') !== -1;
} else {
throw new Error('Expected a regexp or string');
}
this.tokens = ret(regexp);
}
/**
* Checks if some custom properties have been set for this regexp.
*
* @param {RandExp} randexp
* @param {RegExp} regexp
*/
_setDefaults(regexp) {
// When a repetitional token has its max set to Infinite,
// randexp won't actually generate a random amount between min and Infinite
// instead it will see Infinite as min + 100.
this.max = regexp.max != null ? regexp.max :
RandExp.prototype.max != null ? RandExp.prototype.max : 100;
// This allows expanding to include additional characters
// for instance: RandExp.defaultRange.add(0, 65535);
this.defaultRange = regexp.defaultRange ?
regexp.defaultRange : this.defaultRange.clone();
if (regexp.randInt) {
this.randInt = regexp.randInt;
}
}
/**
* Generates the random string.
*
* @return {String}
*/
gen() {
return this._gen(this.tokens, []);
}
/**
* Generate random string modeled after given tokens.
*
* @param {Object} token
* @param {Array.<String>} groups
* @return {String}
*/
_gen(token, groups) {
var stack, str, n, i, l;
switch (token.type) {
case types.ROOT:
case types.GROUP:
// Ignore lookaheads for now.
if (token.followedBy || token.notFollowedBy) { return ''; }
// Insert placeholder until group string is generated.
if (token.remember && token.groupNumber === undefined) {
token.groupNumber = groups.push(null) - 1;
}
stack = token.options ?
this._randSelect(token.options) : token.stack;
str = '';
for (i = 0, l = stack.length; i < l; i++) {
str += this._gen(stack[i], groups);
}
if (token.remember) {
groups[token.groupNumber] = str;
}
return str;
case types.POSITION:
// Do nothing for now.
return '';
case types.SET:
var expandedSet = this._expand(token);
if (!expandedSet.length) { return ''; }
return String.fromCharCode(this._randSelect(expandedSet));
case types.REPETITION:
// Randomly generate number between min and max.
n = this.randInt(token.min,
token.max === Infinity ? token.min + this.max : token.max);
str = '';
for (i = 0; i < n; i++) {
str += this._gen(token.value, groups);
}
return str;
case types.REFERENCE:
return groups[token.value - 1] || '';
case types.CHAR:
var code = this.ignoreCase && this._randBool() ?
this._toOtherCase(token.value) : token.value;
return String.fromCharCode(code);
}
}
/**
* If code is alphabetic, converts to other case.
* If not alphabetic, returns back code.
*
* @param {Number} code
* @return {Number}
*/
_toOtherCase(code) {
return code + (97 <= code && code <= 122 ? -32 :
65 <= code && code <= 90 ? 32 : 0);
}
/**
* Randomly returns a true or false value.
*
* @return {Boolean}
*/
_randBool() {
return !this.randInt(0, 1);
}
/**
* Randomly selects and returns a value from the array.
*
* @param {Array.<Object>} arr
* @return {Object}
*/
_randSelect(arr) {
if (arr instanceof DRange) {
return arr.index(this.randInt(0, arr.length - 1));
}
return arr[this.randInt(0, arr.length - 1)];
}
/**
* expands a token to a DiscontinuousRange of characters which has a
* length and an index function (for random selecting)
*
* @param {Object} token
* @return {DiscontinuousRange}
*/
_expand(token) {
if (token.type === ret.types.CHAR) {
return new DRange(token.value);
} else if (token.type === ret.types.RANGE) {
return new DRange(token.from, token.to);
} else {
let drange = new DRange();
for (let i = 0; i < token.set.length; i++) {
let subrange = this._expand(token.set[i]);
drange.add(subrange);
if (this.ignoreCase) {
for (let j = 0; j < subrange.length; j++) {
let code = subrange.index(j);
let otherCaseCode = this._toOtherCase(code);
if (code !== otherCaseCode) {
drange.add(otherCaseCode);
}
}
}
}
if (token.not) {
return this.defaultRange.clone().subtract(drange);
} else {
return this.defaultRange.clone().intersect(drange);
}
}
}
/**
* Randomly generates and returns a number between a and b (inclusive).
*
* @param {Number} a
* @param {Number} b
* @return {Number}
*/
randInt(a, b) {
return a + Math.floor(Math.random() * (1 + b - a));
}
/**
* Default range of characters to generate from.
*/
get defaultRange() {
return this._range = this._range || new DRange(32, 126);
}
set defaultRange(range) {
this._range = range;
}
/**
*
* Enables use of randexp with a shorter call.
*
* @param {RegExp|String| regexp}
* @param {String} m
* @return {String}
*/
static randexp(regexp, m) {
var randexp;
if(typeof regexp === 'string') {
regexp = new RegExp(regexp, m);
}
if (regexp._randexp === undefined) {
randexp = new RandExp(regexp, m);
regexp._randexp = randexp;
} else {
randexp = regexp._randexp;
randexp._setDefaults(regexp);
}
return randexp.gen();
}
/**
* Enables sugary /regexp/.gen syntax.
*/
static sugar() {
/* eshint freeze:false */
RegExp.prototype.gen = function() {
return RandExp.randexp(this);
};
}
};
},{"drange":6,"ret":8}],8:[function(require,module,exports){
const util = require('./util');
const types = require('./types');
const sets = require('./sets');
const positions = require('./positions');
module.exports = (regexpStr) => {
var i = 0, l, c,
start = { type: types.ROOT, stack: []},
// Keep track of last clause/group and stack.
lastGroup = start,
last = start.stack,
groupStack = [];
var repeatErr = (i) => {
util.error(regexpStr, `Nothing to repeat at column ${i - 1}`);
};
// Decode a few escaped characters.
var str = util.strToChars(regexpStr);
l = str.length;
// Iterate through each character in string.
while (i < l) {
c = str[i++];
switch (c) {
// Handle escaped characters, inclues a few sets.
case '\\':
c = str[i++];
switch (c) {
case 'b':
last.push(positions.wordBoundary());
break;
case 'B':
last.push(positions.nonWordBoundary());
break;
case 'w':
last.push(sets.words());
break;
case 'W':
last.push(sets.notWords());
break;
case 'd':
last.push(sets.ints());
break;
case 'D':
last.push(sets.notInts());
break;
case 's':
last.push(sets.whitespace());
break;
case 'S':
last.push(sets.notWhitespace());
break;
default:
// Check if c is integer.
// In which case it's a reference.
if (/\d/.test(c)) {
last.push({ type: types.REFERENCE, value: parseInt(c, 10) });
// Escaped character.
} else {
last.push({ type: types.CHAR, value: c.charCodeAt(0) });
}
}
break;
// Positionals.
case '^':
last.push(positions.begin());
break;
case '$':
last.push(positions.end());
break;
// Handle custom sets.
case '[':
// Check if this class is 'anti' i.e. [^abc].
var not;
if (str[i] === '^') {
not = true;
i++;
} else {
not = false;
}
// Get all the characters in class.
var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
// Increase index by length of class.
i += classTokens[1];
last.push({
type: types.SET,
set: classTokens[0],
not,
});
break;
// Class of any character except \n.
case '.':
last.push(sets.anyChar());
break;
// Push group onto stack.
case '(':
// Create group.
var group = {
type: types.GROUP,
stack: [],
remember: true,
};
c = str[i];
// If if this is a special kind of group.
if (c === '?') {
c = str[i + 1];
i += 2;
// Match if followed by.
if (c === '=') {
group.followedBy = true;
// Match if not followed by.
} else if (c === '!') {
group.notFollowedBy = true;
} else if (c !== ':') {
util.error(regexpStr,
`Invalid group, character '${c}'` +
` after '?' at column ${i - 1}`);
}
group.remember = false;
}
// Insert subgroup into current group stack.
last.push(group);
// Remember the current group for when the group closes.
groupStack.push(lastGroup);
// Make this new group the current group.
lastGroup = group;
last = group.stack;
break;
// Pop group out of stack.
case ')':
if (groupStack.length === 0) {
util.error(regexpStr, `Unmatched ) at column ${i - 1}`);
}
lastGroup = groupStack.pop();
// Check if this group has a PIPE.
// To get back the correct last stack.
last = lastGroup.options ?
lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
break;
// Use pipe character to give more choices.
case '|':
// Create array where options are if this is the first PIPE
// in this clause.
if (!lastGroup.options) {
lastGroup.options = [lastGroup.stack];
delete lastGroup.stack;
}
// Create a new stack and add to options for rest of clause.
var stack = [];
lastGroup.options.push(stack);
last = stack;
break;
// Repetition.
// For every repetition, remove last element from last stack
// then insert back a RANGE object.
// This design is chosen because there could be more than
// one repetition symbols in a regex i.e. `a?+{2,3}`.
case '{':
var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
if (rs !== null) {
if (last.length === 0) {
repeatErr(i);
}
min = parseInt(rs[1], 10);
max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
i += rs[0].length;
last.push({
type: types.REPETITION,
min,
max,
value: last.pop(),
});
} else {
last.push({
type: types.CHAR,
value: 123,
});
}
break;
case '?':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION,
min: 0,
max: 1,
value: last.pop(),
});
break;
case '+':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION,
min: 1,
max: Infinity,
value: last.pop(),
});
break;
case '*':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION,
min: 0,
max: Infinity,
value: last.pop(),
});
break;
// Default is a character that is not `\[](){}?+*^$`.
default:
last.push({
type: types.CHAR,
value: c.charCodeAt(0),
});
}
}
// Check if any groups have not been closed.
if (groupStack.length !== 0) {
util.error(regexpStr, 'Unterminated group');
}
return start;
};
module.exports.types = types;
},{"./positions":9,"./sets":10,"./types":11,"./util":12}],9:[function(require,module,exports){
const types = require('./types');
exports.wordBoundary = () => ({ type: types.POSITION, value: 'b' });
exports.nonWordBoundary = () => ({ type: types.POSITION, value: 'B' });
exports.begin = () => ({ type: types.POSITION, value: '^' });
exports.end = () => ({ type: types.POSITION, value: '$' });
},{"./types":11}],10:[function(require,module,exports){
const types = require('./types');
const INTS = () => [{ type: types.RANGE , from: 48, to: 57 }];
const WORDS = () => {
return [
{ type: types.CHAR, value: 95 },
{ type: types.RANGE, from: 97, to: 122 },
{ type: types.RANGE, from: 65, to: 90 }
].concat(INTS());
};
const WHITESPACE = () => {
return [
{ type: types.CHAR, value: 9 },
{ type: types.CHAR, value: 10 },
{ type: types.CHAR, value: 11 },
{ type: types.CHAR, value: 12 },
{ type: types.CHAR, value: 13 },
{ type: types.CHAR, value: 32 },
{ type: types.CHAR, value: 160 },
{ type: types.CHAR, value: 5760 },
{ type: types.RANGE, from: 8192, to: 8202 },
{ type: types.CHAR, value: 8232 },
{ type: types.CHAR, value: 8233 },
{ type: types.CHAR, value: 8239 },
{ type: types.CHAR, value: 8287 },
{ type: types.CHAR, value: 12288 },
{ type: types.CHAR, value: 65279 }
];
};
const NOTANYCHAR = () => {
return [
{ type: types.CHAR, value: 10 },
{ type: types.CHAR, value: 13 },
{ type: types.CHAR, value: 8232 },
{ type: types.CHAR, value: 8233 },
];
};
// Predefined class objects.
exports.words = () => ({ type: types.SET, set: WORDS(), not: false });
exports.notWords = () => ({ type: types.SET, set: WORDS(), not: true });
exports.ints = () => ({ type: types.SET, set: INTS(), not: false });
exports.notInts = () => ({ type: types.SET, set: INTS(), not: true });
exports.whitespace = () => ({ type: types.SET, set: WHITESPACE(), not: false });
exports.notWhitespace = () => ({ type: types.SET, set: WHITESPACE(), not: true });
exports.anyChar = () => ({ type: types.SET, set: NOTANYCHAR(), not: true });
},{"./types":11}],11:[function(require,module,exports){
module.exports = {
ROOT : 0,
GROUP : 1,
POSITION : 2,
SET : 3,
RANGE : 4,
REPETITION : 5,
REFERENCE : 6,
CHAR : 7,
};
},{}],12:[function(require,module,exports){
const types = require('./types');
const sets = require('./sets');
const CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
const SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };
/**
* Finds character representations in str and convert all to
* their respective characters
*
* @param {String} str
* @return {String}
*/
exports.strToChars = function(str) {
/* jshint maxlen: false */
var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;
str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {
if (lbs) {
return s;
}
var code = b ? 8 :
a16 ? parseInt(a16, 16) :
b16 ? parseInt(b16, 16) :
c8 ? parseInt(c8, 8) :
dctrl ? CTRL.indexOf(dctrl) :
SLSH[eslsh];
var c = String.fromCharCode(code);
// Escape special regex characters.
if (/[[\]{}^$.|?*+()]/.test(c)) {
c = '\\' + c;
}
return c;
});
return str;
};
/**
* turns class into tokens
* reads str until it encounters a ] not preceeded by a \
*
* @param {String} str
* @param {String} regexpStr
* @return {Array.<Array.<Object>, Number>}
*/
exports.tokenizeClass = (str, regexpStr) => {
/* jshint maxlen: false */
var tokens = [];
var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?([^])/g;
var rs, c;
while ((rs = regexp.exec(str)) != null) {
if (rs[1]) {
tokens.push(sets.words());
} else if (rs[2]) {
tokens.push(sets.ints());
} else if (rs[3]) {
tokens.push(sets.whitespace());
} else if (rs[4]) {
tokens.push(sets.notWords());
} else if (rs[5]) {
tokens.push(sets.notInts());
} else if (rs[6]) {
tokens.push(sets.notWhitespace());
} else if (rs[7]) {
tokens.push({
type: types.RANGE,
from: (rs[8] || rs[9]).charCodeAt(0),
to: rs[10].charCodeAt(0),
});
} else if ((c = rs[12])) {
tokens.push({
type: types.CHAR,
value: c.charCodeAt(0),
});
} else {
return [tokens, regexp.lastIndex];
}
}
exports.error(regexpStr, 'Unterminated character class');
};
/**
* Shortcut to throw errors.
*
* @param {String} regexp
* @param {String} msg
*/
exports.error = (regexp, msg) => {
throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
};
},{"./sets":10,"./types":11}],13:[function(require,module,exports){
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.createNumberMask=t():e.createNumberMask=t()}(this,function(){return function(e){function t(n){if(o[n])return o[n].exports;var i=o[n]={exports:{},id:n,loaded:!1};return e[n].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var o={};return t.m=e,t.c=o,t.p="",t(0)}([function(e,t,o){e.exports=o(2)},,function(e,t){"use strict";function o(){function e(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l,t=e.length;if(e===l||e[0]===y[0]&&1===t)return y.split(l).concat([v]).concat(g.split(l));if(e===k&&M)return y.split(l).concat(["0",k,v]).concat(g.split(l));var o=e[0]===s&&q;o&&(e=e.toString().substr(1));var c=e.lastIndexOf(k),u=c!==-1,a=void 0,b=void 0,h=void 0;if(e.slice(T*-1)===g&&(e=e.slice(0,T*-1)),u&&(M||$)?(a=e.slice(e.slice(0,R)===y?R:0,c),b=e.slice(c+1,t),b=n(b.replace(f,l))):a=e.slice(0,R)===y?e.slice(R):e,P&&("undefined"==typeof P?"undefined":r(P))===p){var S="."===j?"[.]":""+j,w=(a.match(new RegExp(S,"g"))||[]).length;a=a.slice(0,P+w*Z)}return a=a.replace(f,l),E||(a=a.replace(/^0+(0$|[^0])/,"$1")),a=x?i(a,j):a,h=n(a),(u&&M||$===!0)&&(e[c-1]!==k&&h.push(m),h.push(k,m),b&&(("undefined"==typeof L?"undefined":r(L))===p&&(b=b.slice(0,L)),h=h.concat(b)),$===!0&&e[c-1]===k&&h.push(v)),R>0&&(h=y.split(l).concat(h)),o&&(h.length===R&&h.push(v),h=[d].concat(h)),g.length>0&&(h=h.concat(g.split(l))),h}var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=t.prefix,y=void 0===o?c:o,b=t.suffix,g=void 0===b?l:b,h=t.includeThousandsSeparator,x=void 0===h||h,S=t.thousandsSeparatorSymbol,j=void 0===S?u:S,w=t.allowDecimal,M=void 0!==w&&w,N=t.decimalSymbol,k=void 0===N?a:N,D=t.decimalLimit,L=void 0===D?2:D,O=t.requireDecimal,$=void 0!==O&&O,_=t.allowNegative,q=void 0!==_&&_,B=t.allowLeadingZeroes,E=void 0!==B&&B,I=t.integerLimit,P=void 0===I?null:I,R=y&&y.length||0,T=g&&g.length||0,Z=j&&j.length||0;return e.instanceOf="createNumberMask",e}function n(e){return e.split(l).map(function(e){return v.test(e)?v:e})}function i(e,t){return e.replace(/\B(?=(\d{3})+(?!\d))/g,t)}Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.default=o;var c="$",l="",u=",",a=".",s="-",d=/-/,f=/\D+/g,p="number",v=/\d/,m="[]"}])});
},{}]},{},[1])(1)
});
{
"name": "js-brasil",
"version": "1.0.4",
"version": "1.0.5",
"description": "Javascript Utils para Brasil (cpf, cnpj...)",

@@ -8,5 +8,8 @@ "main": "dist/index.js",

"build": "tsc",
"test": "mocha",
"watch": "onchange 'src/**/*.ts' '*.ts' -- npm run build",
"watch:test": "onchange 'src/**/*.ts' '*.ts' -- npm run test",
"test": "mocha -r ts-node/register test/**.ts",
"browserify": "browserify dist/index.js --standalone jsbrasil -o js-brasil.js",
"dist": "npm run build && npm run browserify"
"dist": "npm run build && npm run browserify",
"publish": "npm run dist && npm publish"
},

@@ -24,8 +27,13 @@ "repository": {

"dependencies": {
"randexp": "^0.5.3",
"text-mask-addons": "^3.8.0"
},
"devDependencies": {
"@types/chai": "^4.1.5",
"@types/mocha": "^5.2.5",
"chai": "^4.1.2",
"mocha": "^5.2.0"
"mocha": "^5.2.0",
"ts-node": "^7.0.1",
"typescript": "^3.0.3"
}
}

@@ -5,2 +5,12 @@ # js-brasil

[![Build Status](https://travis-ci.org/mariohmol/ng-brazil.svg?branch=master)](https://travis-ci.org/mariohmol/ng-brazil)
`npm i js-brasil`
ou
`<script src="js-brasil.js"></script>`
# Validate

@@ -24,5 +34,5 @@

```html
<script src="js-brasil.js">
<script src="js-brasil.js"></script>
<script>
var cpf = jsbrasil.validateBr.cpf('123.456.789-00')
var cpf = jsbrasil.validateBr.cpf('123.456.789-00');
</script>

@@ -50,5 +60,5 @@ ```

```html
<script src="js-brasil.js">
<script src="js-brasil.js"></script>
<script>
var cep = jsbrasil.fakerBr.cep(')
var cep = jsbrasil.fakerBr.cep();
</script>

@@ -55,0 +65,0 @@ ```

import { MASKS } from './utils';
import { create_cpf, create_cnpj, CEPRange } from './validate';
import { randexp } from 'randexp';
const makeGeneric = (val) => {
return () => {
const newData = val.textMask.map(c => {
c = c.toString();
if (c === /\d/.toString()) {
return Math.floor(Math.random() * 10)
} else if (c === /[A-Za-z]/.toString()) {
const num = Math.floor((Math.random() * 57)) + 65;
return String.fromCharCode(num);
} else if (c === /[1-9]/.toString()) {
return Math.floor(Math.random() * 9) + 1;
} else {
return c;
}
});
return newData.join('');
};
}
export const fakerBr = {
cep: makeGeneric(MASKS['cep']),
cepState: (state) => {
return randexp(CEPRange[state]);
},
cpf: () => {
const cpf = makeGeneric(MASKS['cpf'])();
const restos = create_cpf(cpf);
return cpf.substr(0, cpf.length - 2) + restos[0] + restos[1];
},
cnpj: () => {
let cnpj = makeGeneric(MASKS['cnpj'])();
cnpj = cnpj.replace(/[^\d]+/g, '');
const generateMasks = () => {
const fake = {};
for (const key in MASKS) {
if (!key) {
continue;
}
const val = MASKS[key];
let restos = create_cnpj(cnpj);
cnpj = cnpj.substr(0, cnpj.length - 2) + restos[0] + restos[0]
// cpf: {
// text: '000.000.000-00',
// textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]
// },
fake[key] = () => {
return val.textMask.map(c => {
if (c === /\d/) {
return Math.floor(Math.random() * 10)
} else if (c === /[A-Za-z]/) {
const num = Math.floor((Math.random() * 57)) + 65;
return Math.floor(Math.random() * 10)
} else if (c === /[1-9]/) {
return Math.floor(Math.random() * 9) + 1;
} else {
return c;
}
});
};
}
restos = create_cnpj(cnpj);
return cnpj.substr(0, cnpj.length - 1) + restos[1];
},
rg: makeGeneric(MASKS['rg']),
telefone: makeGeneric(MASKS['telefone']),
inscricaoestadual: makeGeneric(MASKS['inscricaoestadual']),
time: makeGeneric(MASKS['time']),
// currency: makeGeneric(MASKS['currency']),
percentage: makeGeneric(MASKS['percentage']),
placa: makeGeneric(MASKS['placa']),
titulo: makeGeneric(MASKS['titulo'])
};
export const fakerBr = generateMasks();

@@ -7,3 +7,17 @@

export function validate_cnpj(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g, '');
let tamanho = cnpj.length - 2
const digitos = cnpj.substring(tamanho);
const resultados = create_cnpj(cnpj);
if (resultados[0] !== parseInt(digitos.charAt(0), 10)) {
return false;
}
if (resultados[1] !== parseInt(digitos.charAt(1), 10)) {
return false;
}
return true;
}
export function create_cnpj(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g, '');

@@ -36,3 +50,2 @@

let numeros = cnpj.substring(0, tamanho);
const digitos = cnpj.substring(tamanho);
let soma = 0;

@@ -47,6 +60,4 @@ let pos = tamanho - 7;

}
let resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado !== parseInt(digitos.charAt(0), 10)) {
return false;
}
const resultados = [0, 0];
resultados[0] = soma % 11 < 2 ? 0 : 11 - soma % 11;

@@ -63,12 +74,22 @@ tamanho = tamanho + 1;

}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado !== parseInt(digitos.charAt(1), 10)) {
resultados[1] = soma % 11 < 2 ? 0 : 11 - soma % 11;
return resultados;
}
// http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/funcoes.js
export function validate_cpf(strCPF) {
strCPF = strCPF.replace(/[^\d]+/g, '');
const restos = create_cpf(strCPF);
if (restos[0] !== parseInt(strCPF.substring(9, 10), 10)) {
return false;
}
if (restos[1] !== parseInt(strCPF.substring(10, 11), 10)) {
return false;
}
return true;
}
// http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/funcoes.js
export function validate_cpf(strCPF) {
export function create_cpf(strCPF) {
strCPF = strCPF.replace(/[^\d]+/g, '');

@@ -91,6 +112,6 @@ let soma;

}
if (resto !== parseInt(strCPF.substring(9, 10), 10)) {
return false;
}
const restos = [];
restos.push(resto);
soma = 0;

@@ -105,10 +126,9 @@ for (let i = 1; i <= 10; i++) {

}
if (resto !== parseInt(strCPF.substring(10, 11), 10)) {
return false;
}
return true;
restos.push(resto);
return restos;
}
const CEPRange = {
export const CEPRange = {
'SP': /^([1][0-9]{3}|[01][0-9]{4})[0-9]{3}$/g,

@@ -115,0 +135,0 @@ 'RJ': /^[2][0-8][0-9]{3}[0-9]{3}$/g,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc