
Security News
npm Adopts OIDC for Trusted Publishing in CI/CD Workflows
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
@d3vtool/utils
Advanced tools
A collection of utility functions designed to simplify common tasks in your application.
A collection of utility functions designed to simplify common tasks in your application
You can install the package using npm or yarn:
npm install @d3vtool/utils
yarn add @d3vtool/utils
import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";
const usernameSchema = Validator.string().minLength(5);
type Username = VInfer<typeof usernameSchema>;
const username: Username = "popHero83";
const errors = usernameSchema.validateSafely(username)
console.log(errors);
// or
try {
usernameSchema.validate(username);
} catch(err: unknown) {
if(err instanceof ValidationError) {
// do something with it
console.log(err);
}
}
import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";
const phoneSchema = Validator.number().requiredLength(10);
type Phone = VInfer<typeof phoneSchema>;
const phone: Phone = 1234567890;
const errors = phoneSchema.validateSafely(phone)
console.log(errors);
// or
try {
phoneSchema.validate(phone);
} catch(err: unknown) {
if(err instanceof ValidationError) {
// do something with it
console.log(err);
}
}
import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";
const vSchema = Validator.boolean(
"Custom error message" // Optional argument for a custom error message.
);
type vSchema = VInfer<typeof vSchema>;
// Performs strict type validation to ensure the value is a boolean.
// If strict mode is not enabled, any truthy value will be considered true.
vSchema.strict();
const errors = vSchema.validateSafely("string"); // false
console.log(errors);
// or
try {
vSchema.validate(phone);
} catch(err: unknown) {
if(err instanceof ValidationError) {
// do something with it
console.log(err);
}
}
import { Validator, ValidationError, type VInfer } from "@d3vtool/utils";
const arraySchema = Validator.array<string[]>() // type must be provided for type inference later.
.minLength(2)
.maxLength(5)
.requiredLength(3)
.notEmpty()
.includes([1, 2, 3]);
type ArrayType = VInfer<typeof arraySchema>;
const myArray: ArrayType = [1, 2, 3];
const errors = arraySchema.validateSafely(myArray);
console.log(errors);
// or
try {
arraySchema.validate(myArray);
} catch (err: unknown) {
if (err instanceof ValidationError) {
// do something with it
console.log(err);
}
}
minLength(length: number, error: string)
Ensures the array has a minimum length.
length
- The minimum length the array must have.error
- The error message to return if validation fails (default: 'The length of the array passed does not have min-length: '${length}'.'
).maxLength(length: number, error: string)
Ensures the array has a maximum length.
length
- The maximum length the array can have.error
- The error message to return if validation fails (default: 'The length of the array passed does not have max-length: '${length}'.'
).requiredLength(length: number, error: string)
Ensures the array has an exact length.
length
- The exact length the array must have.error
- The error message to return if validation fails (default: 'The length of the array passed does not have required-length: '${length}'.'
).notEmpty(error: string)
Ensures the array is not empty.
error
- The error message to return if validation fails (default: 'Array passed in is empty'
).transform<F>(fn: transformerFn<T[], F>)
Transforms the array before validation.
fn
- The transformer function to apply to the array.includes(oneOfvalue: T | T[], strict: boolean, error: string)
Ensures the array includes a specified value or values.
oneOfvalue
- A single value or an array of values to check for inclusion.strict
- If true
, all values must be included (every
); if false
, only one must be included (some
).error
- The error message to return if validation fails (default: 'The provided value is not present in the one-of-value/s: '${oneOfvalue}'.'
).optional()
Makes the array optional.
ref(propertyName: string, error: string)
References another property for validation.
propertyName
- The name of the property to reference.error
- The error message to return if validation fails (default: 'The provided value is invalid or does not meet the expected criteria.'
).custom(fn: ValidatorFn, error: string)
Adds a custom validation function.
fn
- The custom validation function which passes a value and must return boolean.error
- The error message to return if validation fails.import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";
const schema = Validator.object({
name: Validator.string().minLength(5),
email: Validator.string().email(),
});
type schema = VInfer<typeof schema>;
const schemaObj: schema = {
name: "Sudhanshu",
email: "email@email.abc"
}
const errors = schema.validateSafely(schemaObj);
console.log(errors);
// or
try {
schema.validate(schemaObj);
} catch(err: unknown) {
if(err instanceof ObjectValidationError) {
// do something with it
console.log(err);
}
}
The Validator.tuple()
function is used to validate a tuple, ensuring that each element of the tuple meets the specified schema. This is useful when you want to validate a structured collection of values with specific rules for each element.
import { Validator, ValidationError } from "@d3vtool/utils";
// Define a tuple schema with two elements: a string and a number.
const tupleV = Validator.tuple([
Validator.string().minLength(5), // First element: String with a minimum length of 5
Validator.number().lessThanOrEqual(101) // Second element: Number less than or equal to 101
]);
// Validate a tuple with the correct values
const errors = tupleV.validateSafely(["hello", 100]);
console.log(errors); // Outputs: [] (no errors)
// Validate a tuple with incorrect values
const errors2 = tupleV.validateSafely(["hi", 102]);
console.log(errors2); // Outputs: [Error Msg From respective validation fn, Error Msg From respective validation fn]
Incorrect Tuple Length:
When the tuple schema expects a specific number of elements (e.g., 1 element), providing more or fewer elements results in an error.
Example:
const tupleV = Validator.tuple([Validator.string().minLength(5)]);
const errors = tupleV.validateSafely(["hello", 100]);
console.log(errors); // Outputs: ["Provided tuple 'value' length is equivalent to 'validator-tuple'"]
Invalid Values Inside Tuple:
If the values inside the tuple don't meet the validation rules, such as a string being too short or a number exceeding the specified range, an error is returned.
Example:
const tupleV = Validator.tuple([
Validator.string().minLength(5),
Validator.number().lessThanOrEqual(101)
]);
const errors = tupleV.validateSafely(["hi", 102]);
console.log(errors); // Outputs: [Error Msg From respective validation fn, Error Msg From respective validation fn]
Invalid Type (Not a Tuple):
If the value provided is not an array or tuple, an error is raised indicating that the provided value is not a tuple.
Example:
const tupleV = Validator.tuple([
Validator.string().minLength(5)
]);
const errors = tupleV.validateSafely("not a tuple");
console.log(errors); // Outputs: ["Provided 'value' is not tuple"]
Edge Case Handling (undefined, null, NaN):
If the value is undefined
, null
, or NaN
, validation will throw an error indicating that the provided value is not a valid tuple.
Example:
const tupleV = Validator.tuple([Validator.string().minLength(5)]);
const errors = tupleV.validateSafely(undefined);
console.log(errors); // Outputs: ["Provided 'value' is not tuple"]
optional()
: To skip validation checks, as 'value' might be undefined or null.validateSafely(value: any)
: Returns an array of errors if the value is invalid or an empty array if the value is valid.validate(value: any)
: Throws a ValidationError
if the value is invalid, otherwise, it passes silently.optional()
import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";
const schema = Validator.object({
name: Validator.string().minLength(5), // name is required with a minimum length of 5
email: Validator.string().email().optional(), // email is optional
});
type schema = VInfer<typeof schema>;
const schemaObj: schema = {
name: "Sudhanshu",
email: "email@email.abc", // This is valid, but email can also be omitted
};
const errors = schema.validateSafely(schemaObj);
console.log(errors); // Should show no errors
// or
try {
schema.validate(schemaObj);
} catch(err: unknown) {
if(err instanceof ObjectValidationError) {
// do something with it
console.log(err);
}
}
// Example with email missing
const schemaObjWithoutEmail: schema = {
name: "Sudhanshu",
// email is omitted, which is allowed because it's optional
};
const errorsWithoutEmail = schema.validateSafely(schemaObjWithoutEmail);
console.log(errorsWithoutEmail); // Should show no errors as email is optional
// or
try {
schema.validate(schemaObjWithoutEmail);
} catch(err: unknown) {
if(err instanceof ObjectValidationError) {
// do something with it
console.log(err);
}
}
name
field: This field is required, and it must be a string with a minimum length of 5 characters.email
field: This field is optional due to .optional()
. If it's provided, it must be a valid email address; if not, the validation will still pass without errors.name
and email
are provided, the validation will pass.name
is provided and email
is omitted, the validation will still pass because email
is marked as optional..custom(fn) Function [ string | number | array ] validators
import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";
const schema = Validator.object({
name: Validator.string().custom((value: string) => {
return value.length >= 5
}, "minimum length of 5 required"), // name is required with a minimum length of 5
email: Validator.string().email()
});
type schema = VInfer<typeof schema>;
const schemaObj: schema = {
name: "Sudhanshu",
email: "email@email.abc", // This is valid, but email can also be omitted
};
const errors = schema.validateSafely(schemaObj);
console.log(errors); // Should show no errors
// or
try {
schema.validate(schemaObj);
} catch(err: unknown) {
if(err instanceof ObjectValidationError) {
// do something with it
console.log(err);
}
}
name
field: This field is required, and it must be a string with a minimum length of 5 characters, the .custom(fn) fn takes a 'function' as an arg and should return boolean value.import { Validator, ObjectValidationError, type VInfer } from "@d3vtool/utils";
const schema = Validator.object({
name: Validator.number().custom((value: string) => {
return value.length >= 5
}, "minimum length of 5 required"),
email: Validator.string().email(),
password: Validator.string().password().minLength(8),
confirmPassword: Validator.string().optional().ref("password"),
});
type schema = VInfer<typeof schema>;
const schemaObj: schema = {
name: 12345,
email: "email@email.abc",
password: "securepassword123",
confirmPassword: "securepassword123", // Optional, but must match password if provided
}
const errors = schema.validateSafely(schemaObj);
// or
try {
schema.validate(schemaObj);
} catch(err: unknown) {
if(err instanceof ObjectValidationError) {
// do something with it
console.log(err);
}
}
name
: The name
field must be a number and have a minimum value of 5.email
: The email
field must be a valid email address.password
: The password
field must be at least 8 characters long and a valid password format.confirmPassword
: The confirmPassword
field is optional but, if provided, must match the value of the password
field (using ref("password")
).In this example, the validateSafely
function will check the provided schemaObj
and return any validation errors, ensuring that confirmPassword
(if present) matches password
.
toTitleCase(input: string): string
Converts the input string to title case (each word starts with an uppercase letter and the rest are lowercase).
import { StringUtils } from "@d3vtool/utils";
const input = "hello world from chatgpt";
const titleCase = StringUtils.toTitleCase(input);
console.log(titleCase); // "Hello World From Chatgpt"
toCamelCase(input: string): string
Converts the input string to camelCase (first word in lowercase and each subsequent word capitalized).
import { StringUtils } from "@d3vtool/utils";
const input = "hello world from chatgpt";
const camelCase = StringUtils.toCamelCase(input);
console.log(camelCase); // "helloWorldFromChatgpt"
toPascalCase(input: string): string
Converts the input string to PascalCase (each word capitalized without spaces).
import { StringUtils } from "@d3vtool/utils";
const input = "hello world from chatgpt";
const pascalCase = StringUtils.toPascalCase(input);
console.log(pascalCase); // "HelloWorldFromChatgpt"
toKebabCase(input: string): string
Converts the input string to kebab-case (words separated by hyphens with lowercase letters).
import { StringUtils } from "@d3vtool/utils";
const input = "hello world from chatgpt";
const kebabCase = StringUtils.toKebabCase(input);
console.log(kebabCase); // "hello-world-from-chatgpt"
isUpperCase(input: string): boolean
Checks if the input string is entirely in uppercase.
import { StringUtils } from "@d3vtool/utils";
const input1 = "HELLO WORLD";
const input2 = "Hello World";
const isUpper1 = StringUtils.isUpperCase(input1);
const isUpper2 = StringUtils.isUpperCase(input2);
console.log(isUpper1); // true
console.log(isUpper2); // false
isLowerCase(input: string): boolean
Checks if the input string is entirely in lowercase.
import { StringUtils } from "@d3vtool/utils";
const input1 = "hello world";
const input2 = "Hello World";
const isLower1 = StringUtils.isLowerCase(input1);
const isLower2 = StringUtils.isLowerCase(input2);
console.log(isLower1); // true
console.log(isLower2); // false
toAlternateCasing(input: string): string
Converts the input string to alternate casing, where the characters alternate between uppercase and lowercase.
import { StringUtils } from "@d3vtool/utils";
const input = "hello world";
const alternateCasing = StringUtils.toAlternateCasing(input);
console.log(alternateCasing); // "HeLlO wOrLd"
signJwt
Signs a JWT (JSON Web Token) with the provided claims, custom claims, secret key, and options.
import { signJwt, createIssueAt, createExpiry } from "@d3vtool/utils";
const claims = {
aud: "http://localhost:4000",
iat: createIssueAt(new Date(Date.now())),
exp: createExpiry("1h"),
iss: "server-x",
sub: "user123"
};
const customClaims = {
role: "admin",
name: "John Doe"
};
const secret = "itsasecret";
// Sign the JWT with default algorithm (HS256)
const token = await signJwt(claims, customClaims, secret);
console.log(token); // Signed JWT token as a string
The following signing algorithms are supported by the signJwt
function:
You can specify which algorithm to use by passing the alg
option when calling signJwt
.
import { signJwt, createIssueAt, createExpiry } from "@d3vtool/utils";
const claims = {
aud: "http://localhost:4000",
iat: createIssueAt(new Date()),
exp: createExpiry("2h"), // 2hr from now
iss: "server-x",
sub: "user123"
};
const customClaims = {
role: "admin",
name: "John Doe"
};
const secret = "itsasecret";
// Sign the JWT with HS384 algorithm
const token = await signJwt(claims, customClaims, secret, { alg: "HS384" });
console.log(token); // Signed JWT token using HS384
When using a custom algorithm, ensure that the algorithm is one of the supported ones: HS256, HS384, or HS512. If an unsupported algorithm is passed, an error will be thrown:
import { signJwt, createIssueAt, createExpiry } from "@d3vtool/utils";
const secret = "itsasecret";
const claims = {
aud: "http://localhost:4000",
iat: createIssueAt(new Date()),
exp: createExpiry('1m'),
iss: "server-x",
sub: "testing"
}
try {
const token = await signJwt(claims, { name: "John Doe" }, secret, { alg: "RS256" }); // Unsupported algorithm
} catch (error) {
if (error instanceof BadJwtHeader) {
console.error("Error: Unsupported signing algorithm.");
} else {
console.error("Unexpected error:", error);
}
}
verifyJwt
Verifies a JWT and decodes its claims, including both standard JWT claims (like iat
, exp
, iss
) and any custom claims included in the token.
import { verifyJwt } from "@d3vtool/utils";
// Example token (replace with a real token)
const jwt = "your.jwt.token";
const secret = "itsasecret";
// Verify the JWT
const verifiedClaims = await verifyJwt(jwt, secret);
console.log(verifiedClaims); // Decoded claims, including standard and custom claims
The verifyJwt
function may throw the following errors:
exp
claim).import { verifyJwt } from "@d3vtool/utils";
const jwt = "your.jwt.token";
const secret = "itsasecret";
try {
const verifiedClaims = await verifyJwt(jwt, secret);
console.log(verifiedClaims);
} catch (error) {
if (error instanceof DirtyJwtSignature) {
console.error("Error: JWT signature is invalid or has been tampered with.");
} else if (error instanceof ExpiredJwt) {
console.error("Error: JWT has expired.");
} else if (error instanceof InvalidJwt) {
console.error("Error: JWT is malformed or cannot be decoded.");
} else {
console.error("Unexpected error:", error);
}
}
getMimeType
Retrieves the MIME type for a given file extension.
import { getMimeType } from "@d3vtool/utils";
const extension1 = "html"; // Example file extension
const extension2 = "jpg"; // Example file extension
const extension3 = "md"; // Example file extension
// Get MIME type for the given file extensions
const mimeType1 = getMimeType(extension1); // Returns the MIME type for HTML, e.g. "text/html"
const mimeType2 = getMimeType(extension2); // Returns the MIME type for JPG, e.g. "image/jpeg"
const mimeType3 = getMimeType(extension3); // Returns the MIME type for Markdown, e.g. "text/markdown"
// Fallback to default MIME type for unsupported extensions
const unknownMimeType = getMimeType("unknown"); // Returns the default MIME type "text/plain"
console.log(mimeType1); // "text/html"
console.log(mimeType2); // "image/jpeg"
console.log(mimeType3); // "text/markdown"
console.log(unknownMimeType); // "text/plain"
This package is open-source and licensed under the MIT License.
FAQs
A collection of utility functions designed to simplify common tasks in your application.
We found that @d3vtool/utils demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
Research
/Security News
A RubyGems malware campaign used 60 malicious packages posing as automation tools to steal credentials from social media and marketing tool users.
Security News
The CNA Scorecard ranks CVE issuers by data completeness, revealing major gaps in patch info and software identifiers across thousands of vulnerabilities.