safelinkify
Version:
NodeJS anonymizer external links into outbound page. Anonymize external links to outbound page redirector for SEO.
72 lines (71 loc) • 2.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.escapeRegex = escapeRegex;
exports.capitalizer = capitalizer;
exports.streamToString = streamToString;
exports.bufferToString = bufferToString;
/**
* escape regex string
* @param string
* @returns
*/
function escapeRegex(string, method) {
if (method === void 0) { method = '1'; }
if (method === '1' || !method)
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Escape characters with special meaning either inside or outside character sets.
// Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
if (method === '2')
return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
}
/**
* capitalize string first letter of each word which mixed with symbols
* @param str
* @param moreSymbols add more symbols
* @returns
*/
function capitalizer(str, moreSymbols) {
if (moreSymbols === void 0) { moreSymbols = []; }
var symbols = ['-', ' '];
if (Array.isArray(moreSymbols)) {
// concatenate more symbols
symbols = symbols.concat(moreSymbols).filter(function (x, i, a) {
return a.indexOf(x) === i;
});
}
symbols.forEach(function (symbol) {
str = str
.split(symbol)
.map(function (str) { return str.charAt(0).toUpperCase() + str.slice(1); })
.join(symbol);
});
return str;
}
/**
* Stream to string
* @param stream
* @returns
*/
function streamToString(stream) {
var chunks = [];
return new Promise(function (resolve, reject) {
stream.on('data', function (chunk) { return chunks.push(Buffer.from(chunk)); });
stream.on('error', function (err) { return reject(err); });
stream.on('end', function () { return resolve(Buffer.concat(chunks).toString('utf8')); });
});
}
/**
* Buffer to string
* @param array
* @returns
*/
function bufferToString(array) {
if (typeof Uint8Array !== 'undefined' && typeof TextDecoder !== 'undefined') {
var td = new TextDecoder();
var ua = new Uint8Array(array);
return td.decode(ua);
}
else {
return array.toString();
}
}