Package Exports
- @salespark/toolkit
- @salespark/toolkit/node
- @salespark/toolkit/package.json
- @salespark/toolkit/react
- @salespark/toolkit/web
Readme
SalesPark Toolkit v2 - Documentation
@salespark/toolkit
Shared toolkit of helpers and utilities for Node.js, React, and browser environments.
Tree-shakeable, TypeScript-first, ESM + CJS outputs.
π¦ Installation
yarn add @salespark/toolkit
# or
npm i @salespark/toolkit⨠Features
- Array utilities: chunk, uniqBy, deep equality, flatten, groupBy, etc.
- Object utilities: pick, omit, clean objects, deep merge, etc.
- String utilities: slugify, template fill, deburr, sanitize, etc.
- Number utilities: clamp, round, safe parse, random digits, etc.
- Function utilities: debounce, throttle, formatCurrency, parseName, currency conversions, etc.
- Boolean utilities: safe boolean conversion with common representations
- Validation utilities: IBAN validator (ISO 13616), Portuguese tax ID validator
- Security utilities: Markdown XSS protection, content sanitization, risk assessment
- Environment detection:
isBrowser,isNoderuntime checks
π Usage
Get started in seconds with a few common utilities:
Named Imports (Tree-shakeable)
import {
debounce,
delay,
chunk,
slugify,
clamp,
isBrowser,
toBool,
} from "@salespark/toolkit";
// Debounce a function
const debouncedFn = debounce(() => {
/* ... */
}, 200);
// Delay execution
await delay(1000); // Wait 1 second
// Chunk an array
const chunks = chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
// Slugify a string
const slug = slugify("OlΓ‘ mundo!"); // "ola-mundo"
// Clamp a number
const safe = clamp(15, 0, 10); // 10
// Convert to boolean
const bool = toBool("yes"); // true
// Check environment
if (isBrowser) {
/* browser-specific code */
}Lodash-style Import (Alternative)
import * as _ from "@salespark/toolkit";
// Debounce a function
const debouncedFn = _.debounce(() => {
/* ... */
}, 200);
// Chunk an array
const chunks = _.chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
// Slugify a string
const slug = _.slugify("OlΓ‘ mundo!"); // "ola-mundo"
// Clamp a number
const safe = _.clamp(15, 0, 10); // 10
// Convert to boolean
const bool = _.toBool("yes"); // true
// Check environment
if (_.isBrowser) {
/* browser-specific code */
}π API Reference
π Array Utilities
chunk<T>(arr: T[], size: number): T[][] β Splits an array into equally sized pieces.
chunk([1, 2, 3, 4, 5], 2);
// Result: [[1, 2], [3, 4], [5]]uniq<T>(arr: T[]): T[] β Removes duplicate values from an array.
uniq([1, 2, 2, 3, 3, 3]);
// Result: [1, 2, 3]uniqBy<T, K>(arr: T[], key: (v: T) => K): T[] β Returns unique items based on a computed key.
uniqBy(
[
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 1, name: "John" },
],
(x) => x.id
);
// Result: [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}]areArraysEqual<T>(arr1: T[], arr2: T[]): boolean β Deeply compares two arrays for equality.
areArraysEqual([1, 2, 3], [1, 2, 3]);
// Result: trueflatten<T>(arr: any[]): T[] β Flattens nested arrays into a single array (1 level deep).
flatten([1, [2, 3], [4, [5]]]);
// Result: [1, 2, 3, 4, [5]]flattenOnce<T>(array): T[] β Flattens array a single level deep.
flattenOnce([1, [2, 3], [4, 5]]);
// Result: [1, 2, 3, 4, 5]flattenDepth<T>(array, depth?, options?): T[] β Flattens array up to specified depth.
flattenDepth([1, [2, [3, [4]]]], 2);
// Result: [1, 2, 3, [4]]groupBy<T, K>(arr: T[], key: ((item: T) => K) | K): Record<string, T[]> β Groups array items by a key or function.
groupBy(
[
{ type: "fruit", name: "apple" },
{ type: "fruit", name: "banana" },
{ type: "veggie", name: "carrot" },
],
"type"
);
// Result: {fruit: [{type: 'fruit', name: 'apple'}, {type: 'fruit', name: 'banana'}], veggie: [{type: 'veggie', name: 'carrot'}]}sortBy<T>(arr: T[], key: ((item: T) => any) | keyof T): T[] β Sorts array by a key or function.
sortBy([{ age: 30 }, { age: 20 }, { age: 25 }], "age");
// Result: [{age: 20}, {age: 25}, {age: 30}]difference<T>(arr1: T[], arr2: T[]): T[] β Returns elements in arr1 not present in arr2.
difference([1, 2, 3, 4], [2, 4, 6]);
// Result: [1, 3]intersection<T>(arr1: T[], arr2: T[]): T[] β Returns elements common to both arrays.
intersection([1, 2, 3], [2, 3, 4]);
// Result: [2, 3]compact<T>(arr: T[]): T[] β Removes falsy values from array.
compact([0, 1, false, 2, "", 3, null, undefined, 4]);
// Result: [1, 2, 3, 4]pluck<T, K>(arr: T[], key: K): Array<T[K]> β Extracts a property from each object in array.
pluck(
[
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
],
"name"
);
// Result: ['John', 'Jane']shuffle<T>(arr: T[]): T[] β Shuffles array elements randomly.
shuffle([1, 2, 3, 4, 5]);
// Result: [3, 1, 5, 2, 4] (random order)isFlattenable(value: unknown): boolean β Checks if a value can be flattened.
isFlattenable([1, 2, 3]);
// Result: truepushAll<T>(array: T[], values: readonly T[]): T[] β Appends all values into array in-place.
const arr = [1, 2];
pushAll(arr, [3, 4, 5]);
// Result: arr is now [1, 2, 3, 4, 5]π¦ Object Utilities
pick<T, K>(obj: T, keys: K[]): Pick<T, K> β Picks specified properties from an object.
pick({ name: "John", age: 30, city: "NYC" }, ["name", "age"]);
// Result: {name: 'John', age: 30}omit<T, K>(obj: T, keys: K[]): Omit<T, K> β Omits specified properties from an object.
omit({ name: "John", age: 30, city: "NYC" }, ["age"]);
// Result: {name: 'John', city: 'NYC'}objectToString(obj: unknown): string β Converts an object to a clean string without JSON braces.
objectToString({ name: "John", age: 30 });
// Result: "name=John_age=30"cleanObject<T>(obj: T): any β Deep-cleans an object by removing null/undefined values.
cleanObject({
name: "John",
age: null,
city: undefined,
data: { valid: true, invalid: null },
});
// Result: {name: 'John', data: {valid: true}}π€ String Utilities
slugify(input: string): string β Converts a string to a URL-friendly slug.
slugify("OlΓ‘ Mundo! Como estΓ‘?");
// Result: "ola-mundo-como-esta"fill(template: string, values: Record<string, string|number>): string β Fills a template string with values.
fill("Hello {name}, you are {age} years old!", { name: "John", age: 30 });
// Result: "Hello John, you are 30 years old!"deburr(str: string): string β Removes diacritic marks from a string.
deburr("cafΓ© rΓ©sumΓ© naΓ―ve");
// Result: "cafe resume naive"sanitize(input: unknown, maxLength?: number): string β Sanitizes input by removing dangerous content.
sanitize("<script>alert('hack')</script>Hello World!", 20);
// Result: "Hello World!"π’ Number Utilities
clamp(n: number, min: number, max: number): number β Restricts a number to be within the min and max bounds.
clamp(10, 0, 5); // 5
clamp(-5, 0, 10); // 0round(n: number, decimals?: number): number β Rounds a number to a fixed number of decimals without floating point surprises.
round(1.2345, 2); // 1.23
round(1.235, 2); // 1.24safeParseInt(value: unknown, defaultValue?: number): number β Safely converts a value to an integer with fallback.
safeParseInt("42"); // 42
safeParseInt("abc", 10); // 10
safeParseInt(3.9); // 3safeParseFloat(value: unknown, decimals?: number): number β Safely parses a value into a number with decimal precision and comma/dot normalization.
safeParseFloat("123.45"); // 123.45
safeParseFloat("123,45"); // 123.45
safeParseFloat("1,234.56"); // 1234.56
safeParseFloat("abc"); // 0randomDigits(length?: number, options?: { charset?: string; noLeadingZero?: boolean }): string β Generates a random string of digits with secure randomness when available.
randomDigits(6);
// Result: "482751" (random)randomDigits(length?: number, options?: { charset?: string; noLeadingZero?: boolean }): string β Generates a random string of digits with secure randomness when available.
randomDigits(6); // "847293"
randomDigits(4, { noLeadingZero: true }); // "3847" (no leading zero)
randomDigits(6, { charset: "ABCDEF0123456789" }); // "3F2A9D" (hex)formatDecimalNumber(value: number | string | null | undefined, decimals?: number): string β Formats a number with specified decimal places, intelligently handling European (1.234,56) and US (1,234.56) number formats.
formatDecimalNumber(value: number | string | null | undefined, decimals?: number): string β Formats a number with specified decimal places, intelligently handling European (1.234,56) and US (1,234.56) number formats.
formatDecimalNumber(1234.5678); // "1234.57"
formatDecimalNumber("1.234,56", 2); // "1234.56" (European format)
formatDecimalNumber("1,234.56", 2); // "1234.56" (US format)
formatDecimalNumber("1234,56", 3); // "1234.560"
formatDecimalNumber(null, 2); // "0.00"
formatDecimalNumber("invalid", 2); // "0.00"ποΈ Deprecated (Number Utilities)
toIntegerβ UsesafeParseIntinsteadtoNumberβ UsesafeParseFloatinsteadparseToNumberβ UsesafeParseFloatinsteadotpβ UserandomDigitsinstead
β Boolean Utilities
toBool(value: unknown, def?: boolean): boolean β Converts a value to boolean, supporting common string/number representations.
toBool("yes");
// Result: true
toBool("0");
// Result: falseβ‘ Function Utilities
debounce<T>(fn: T, wait?: number): T β Returns a debounced version of a function.
const debouncedFn = debounce(() => console.log("Called!"), 300);
debouncedFn(); // Will only execute after 300ms of no further callsthrottle<T>(fn: T, wait?: number): T β Returns a throttled version of a function.
const throttledFn = throttle(() => console.log("Called!"), 1000);
throttledFn(); // Will execute at most once per 1000msdelay(ms: number): Promise<void> β Creates a promise that resolves after specified milliseconds.
await delay(1000); // Wait 1 second
await delay(500); // Wait 500msisNil(value: unknown): boolean β Checks if a value is null or undefined.
isNilTextOrEmpty(value: unknown): boolean β Strict check for null, undefined, empty string "", or textual values "null" / "undefined" (case-insensitive, trims spaces). Returns true in those cases, otherwise false.
isNilTextOrEmpty(null); // true
isNilTextOrEmpty("undefined"); // true
isNilTextOrEmpty(" UNDEFINED "); // true
isNilTextOrEmpty("null"); // true
isNilTextOrEmpty(""); // true
isNilTextOrEmpty("abc"); // false
isNilTextOrEmpty(0); // falseDeprecated:
isNullUndefinedOrEmptyEnforced(useisNilTextOrEmpty).
isNil(null);
// Result: true
isNil(undefined);
// Result: true
isNil(0);
// Result: falseisNilText(value: unknown): boolean β Checks if value is null/undefined or the text "null"/"undefined".
isNilText("null");
// Result: true
isNilText("undefined");
// Result: trueisNilOrEmpty(value: unknown): boolean β Checks if value is null/undefined or an empty string (trimmed).
isNilOrEmpty("");
// Result: true
isNilOrEmpty(" ");
// Result: true
isNilOrEmpty(null);
// Result: true
isNilOrEmpty(undefined);
// Result: truehasNilOrEmpty(array: unknown): boolean β Checks if any element in array is nil or empty.
hasNilOrEmpty([1, "", 3]);
// Result: true
hasNilOrEmpty([1, 2, 3]);
// Result: falseisNilEmptyOrZeroLen(value: unknown): boolean β Checks if value is nil, empty string, or has zero length.
isNilEmptyOrZeroLen([]);
// Result: true
isNilEmptyOrZeroLen("");
// Result: trueisNilEmptyOrZeroLength(value: unknown): boolean
isNilEmptyOrZeroLength([]);
// Result: true
isNilEmptyOrZeroLength("");
// Result: trueisNilOrNaN(value: unknown): boolean β Checks if value is nil or NaN.
isNilOrNaN(NaN);
// Result: true
isNilOrNaN("abc");
// Result: true (coerced to NaN)formatBytes(bytes: number, si?: boolean, dp?: number): string β Formats bytes as human-readable text.
formatBytes(1024);
// Result: "1.0 KiB"
formatBytes(1000, true);
// Result: "1.0 kB"stringSimilarity(s1: string, s2: string): number β Returns the similarity between two strings (0..1).
stringSimilarity("hello", "hallo");
// Result: 0.8addThousandsSpace(value: number | string): string β Adds spaces between thousands in a number.
addThousandsSpace(1234567);
// Result: "1 234 567"formatCurrency(value: number | string | null | undefined, withoutCurrencySymbol?: boolean, currency?: string, locale?: string): string β Formats currency values with configurable currency and locale. Uses modern Intl.NumberFormat with automatic thousands separators, proper decimal handling, and graceful fallback for errors.
// Default: EUR currency with Portuguese locale
formatCurrency(1234.56);
// Result: "1234,56 β¬"
formatCurrency(1000000.123);
// Result: "1 000 000,12 β¬"
formatCurrency(999.9, true);
// Result: "999,90" (without symbol)
// Different currencies
formatCurrency(1234.56, false, "USD", "en-US");
// Result: "$1,234.56"
formatCurrency(1234.56, false, "GBP", "en-GB");
// Result: "Β£1,234.56"
formatCurrency(1234.56, false, "USD", "pt-PT");
// Result: "1234,56 US$"
formatCurrency(null);
// Result: "0,00 β¬"parseName(name: string | null | undefined): {firstName: string, lastName: string} β Extracts first and last name from a full name string. Handles single names, empty inputs, and multi-word names intelligently.
parseName("JoΓ£o Silva");
// Result: { firstName: "JoΓ£o", lastName: "Silva" }
parseName("Maria JosΓ© Santos Costa");
// Result: { firstName: "Maria", lastName: "Costa" }
parseName("Ana");
// Result: { firstName: "Ana", lastName: "" }
parseName(" JosΓ© MarΓa GarcΓa ");
// Result: { firstName: "JosΓ©", lastName: "GarcΓa" }
parseName(null);
// Result: { firstName: "", lastName: "" }symbolToCurrency(symbol: string | null | undefined): string β Converts currency symbols to ISO 4217 currency codes. Supports 50+ currency symbols including β¬, Β£, $, Β₯, βΉ, β½, β©, βͺ, and many others.
symbolToCurrency("β¬");
// Result: "EUR"
symbolToCurrency("$");
// Result: "USD"
symbolToCurrency("β©");
// Result: "KRW"
symbolToCurrency("R$");
// Result: "BRL"
symbolToCurrency("unknown");
// Result: "EUR" (fallback)currencyToSymbol(currency: string | null | undefined): string β Converts ISO 4217 currency codes to their corresponding symbols. Supports 50+ currencies with intelligent fallbacks.
currencyToSymbol("EUR");
// Result: "β¬"
currencyToSymbol("USD");
// Result: "$"
currencyToSymbol("KRW");
// Result: "β©"
currencyToSymbol("BRL");
// Result: "R$"
currencyToSymbol("UNKNOWN");
// Result: "β¬" (fallback)π Security Utilities
checkMarkdownSecurity(text: string | null | undefined): SecurityCheckResult β Comprehensive markdown security validation with XSS protection, threat detection, and automatic sanitization.
import { checkMarkdownSecurity } from "@salespark/toolkit";
// Safe content
checkMarkdownSecurity("# Hello World\n\nThis is **bold** text.");
// Result: { isValid: true, text: "...", risks: [], sanitized: false }
// Dangerous content with script
checkMarkdownSecurity('<script>alert("xss")</script>');
// Result: {
// isValid: false,
// text: "",
// risks: [{ type: "scriptTags", severity: "critical", description: "..." }],
// sanitized: true
// }
// Content with multiple threats
checkMarkdownSecurity(
'<iframe src="evil.com"></iframe><div onclick="bad()">test</div>'
);
// Result: Multiple risks detected, sorted by severitysanitizeMarkdown(text: string | null | undefined): string β Aggressive markdown sanitization removing all HTML tags, scripts, and suspicious content.
import { sanitizeMarkdown } from "@salespark/toolkit";
sanitizeMarkdown("<p>Hello <strong>World</strong></p>");
// Result: "Hello World"
sanitizeMarkdown('javascript:alert("xss")');
// Result: "alert(\"xss\")"
sanitizeMarkdown("<script>alert(1)</script>Safe text");
// Result: "Safe text"assessSecurityRisks(risks: SecurityRisk[]): SecurityAssessment β Risk assessment and scoring system with actionable recommendations.
import { assessSecurityRisks } from "@salespark/toolkit";
const risks = [
{
type: "scriptTags",
severity: "critical",
description: "Script injection detected",
},
];
assessSecurityRisks(risks);
// Result: {
// score: 100,
// level: "critical",
// recommendations: [
// "URGENT: Critical security risks detected - do not render this content",
// "Always validate content from untrusted sources",
// "Consider implementing Content Security Policy (CSP)"
// ]
// }
// Safe content
assessSecurityRisks([]);
// Result: { score: 0, level: "safe", recommendations: ["Content appears safe to use"] }β Validation Utilities
isPTTaxId(value: string | number): boolean β Validates Portuguese Tax ID (NIF) with MOD-11 algorithm and format checking.
import { isPTTaxId } from "@salespark/toolkit";
isPTTaxId("123456789"); // false (invalid check digit)
isPTTaxId("123 456 789"); // false (spaces stripped automatically)
isPTTaxId("513183504"); // true (valid NIF)
isPTTaxId("423456789"); // false (invalid prefix - 4 not allowed)
// Deprecated alias (use isPTTaxId instead)
// isValidPTTaxId("513183504"); // trueisValidIBAN(value: string): boolean β Validates International Bank Account Numbers (IBAN) according to ISO 13616 standard with country-specific rules.
import { isValidIBAN } from "@salespark/toolkit";
isValidIBAN("NL91ABNA0417164300"); // true (valid Dutch IBAN)
isValidIBAN("NL91 ABNA 0417 1643 00"); // true (spaces stripped automatically)
isValidIBAN("GB29NWBK60161331926819"); // true (valid UK IBAN)
isValidIBAN("DE89370400440532013000"); // true (valid German IBAN)
isValidIBAN("NL91ABNA0417164301"); // false (invalid checksum)
isValidIBAN("XX1234567890"); // false (invalid country code)π Environment Detection
isBrowser: boolean β True if running in browser.
if (isBrowser) {
console.log("Running in browser");
}isNode: boolean β True if running in Node.js.
if (isNode) {
console.log("Running in Node.js");
}β οΈ Deprecated Functions
The following functions are deprecated but maintained for backward compatibility:
π Array Utilities (Deprecated)
areArraysDeepEqualUnorderedβ UseareArraysEqualinstead.
β Boolean Utilities (Deprecated)
parseToBoolβ UsetoBoolinstead.
β‘ Function Utilities (Deprecated)
isNullOrUndefinedβ UseisNilinstead.isNullOrUndefinedTextIncβ UseisNilTextinstead.isNullUndefinedOrEmptyβ UseisNilOrEmptyinstead.isNullOrUndefinedInArrayβ UsehasNilOrEmptyinstead.isNullOrUndefinedEmptyOrZeroβ UseisNilEmptyOrZeroLengthinstead.isNilEmptyOrZeroLenβ UseisNilEmptyOrZeroLengthinstead.isNullUndefinedOrZeroβ UseisNilEmptyOrZeroLengthinstead.isNilOrZeroLenβ UseisNilEmptyOrZeroLengthinstead.isNullOrUndefinedOrNaNβ UseisNilOrNaNinstead.humanFileSizeβ UseformatBytesinstead.getStringSimilarityβ UsestringSimilarityinstead.addSpaceBetweenNumbersβ UseaddThousandsSpaceinstead.
β Validation Utilities (Deprecated)
These functions are now in the main API but their legacy aliases are deprecated:
isValidPTTaxIdβ UseisPTTaxIdinstead.
π’ Number Utilities (Deprecated)
parseToNumberβ UsetoNumberinstead.otpβ UserandomDigitsinstead.
π€ String Utilities (Deprecated)
removeDiacriticsβ Usedeburrinstead.basicSanitizeβ Usesanitizeinstead.
π·οΈ TypeScript
All functions are fully typed for best developer experience.
π οΈ Support
Got stuck? Donβt panic β weβve got you covered.
π€ AI Assistant
We built a custom AI Assistant trained only on @salespark/toolkit.
It answers implementation and troubleshooting questions in real time:
π Ask the Toolkit GPT:
https://chatgpt.com/g/g-68a9bf25537081918c3b76ae8f353e70-salespark-toolkit-v2
(Free to use with a ChatGPT account)
π Internal Usage Notice
This package is primarily designed and maintained for internal use within the SalesPark ecosystem. While it can technically be used in other Node.js/Mongoose projects, no official support or guarantees are provided outside of SalesPark-managed projects.
All code follows the same engineering standards applied across the SalesPark platform, ensuring consistency, reliability, and long-term maintainability of our internal systems.
β‘ Note: This package is most efficient and works best when used together with other official SalesPark packages, where interoperability and optimizations are fully leveraged.
Disclaimer: This software is provided "as is", without warranties of any kind, express or implied. SalesPark shall not be held liable for any issues, damages, or losses arising from its use outside the intended SalesPark environment.
Organization packages: https://www.npmjs.com/org/salespark
π License
MIT Β© SalesPark
Document version: 7
Last update: 08-11-2025