Utility functions for common development tasks including parsing, security, file operations, and string manipulation. AdonisJS Core provides a comprehensive set of helpers from various utility libraries.
ES module import parsing and analysis utilities.
/**
* Parse ES module imports from source code
* @param code - Source code string to parse
* @returns Promise resolving to array of import information
*/
function parseImports(code: string): Promise<Import[]>;
/**
* Import information interface
*/
interface Import {
/** Import statement type */
type: 'ImportDeclaration' | 'ExportDeclaration';
/** Module specifier (the 'from' part) */
moduleSpecifier: string;
/** Named imports */
namedImports: string[];
/** Default import name */
defaultImport?: string;
/** Namespace import name */
namespaceImport?: string;
/** Start position in source */
start: number;
/** End position in source */
end: number;
}Usage Examples:
import { parseImports } from "@adonisjs/core/helpers";
const sourceCode = `
import { Router } from '@adonisjs/core/http';
import Database from '@adonisjs/lucid/database';
import * as helpers from './helpers';
`;
const imports = await parseImports(sourceCode);
console.log(imports);
// [
// {
// type: 'ImportDeclaration',
// moduleSpecifier: '@adonisjs/core/http',
// namedImports: ['Router'],
// start: 1,
// end: 45
// },
// ...
// ]Collision-resistant unique identifier generation and validation.
/**
* Generate a new CUID
* @returns New CUID string
*/
function cuid(): string;
/**
* Check if string is a valid CUID
* @param value - String to validate
* @returns True if string is a valid CUID
*/
function isCuid(value: string): boolean;Usage Examples:
import { cuid, isCuid } from "@adonisjs/core/helpers";
// Generate unique identifiers
const userId = cuid(); // "clhqxr8vf000001s64tqf5s7n"
const sessionId = cuid(); // "clhqxr8vg000101s6h8v4j2k1"
// Validate CUIDs
console.log(isCuid(userId)); // true
console.log(isCuid('invalid')); // false
// Use in database models
class User {
static async create(data: any) {
return {
id: cuid(),
...data,
createdAt: new Date()
};
}
}Common string manipulation and formatting utilities.
/**
* Convert path separators to forward slashes
* @param path - Path string to normalize
* @returns Path with forward slashes
*/
function slash(path: string): string;
/**
* Join URL parts safely
* @param base - Base URL
* @param path - Path to join
* @returns Joined URL
*/
function joinToURL(base: string, path: string): string;
/**
* Constant-time string comparison for security
* @param a - First string
* @param b - Second string
* @returns True if strings are equal
*/
function safeEqual(a: string, b: string): boolean;
/**
* Get directory name from file path or import.meta.url
* @param url - File URL or path
* @returns Directory path
*/
function getDirname(url: string | URL): string;
/**
* Get filename from file path or import.meta.url
* @param url - File URL or path
* @returns Filename
*/
function getFilename(url: string | URL): string;Usage Examples:
import {
slash,
joinToURL,
safeEqual,
getDirname,
getFilename
} from "@adonisjs/core/helpers";
// Path normalization
const normalizedPath = slash('src\\controllers\\UserController.ts');
// Result: 'src/controllers/UserController.ts'
// URL joining
const apiUrl = joinToURL('https://api.example.com', '/users/123');
// Result: 'https://api.example.com/users/123'
// Secure string comparison
const isValidToken = safeEqual(providedToken, expectedToken);
// File path utilities
const currentDir = getDirname(import.meta.url);
const currentFile = getFilename(import.meta.url);Base64 encoding/decoding and URL-safe encoding utilities.
/**
* Base64 encoding utilities
*/
namespace base64 {
/**
* Encode string to base64
* @param input - String to encode
* @returns Base64 encoded string
*/
function encode(input: string): string;
/**
* Decode base64 string
* @param input - Base64 string to decode
* @returns Decoded string
*/
function decode(input: string): string;
/**
* URL-safe base64 encode
* @param input - String to encode
* @returns URL-safe base64 string
*/
function urlEncode(input: string): string;
/**
* URL-safe base64 decode
* @param input - URL-safe base64 string
* @returns Decoded string
*/
function urlDecode(input: string): string;
}Usage Examples:
import { base64 } from "@adonisjs/core/helpers";
// Basic base64 encoding
const encoded = base64.encode('Hello, World!');
const decoded = base64.decode(encoded);
// URL-safe encoding for tokens
const token = base64.urlEncode(JSON.stringify({ userId: 123, exp: Date.now() }));
const tokenData = JSON.parse(base64.urlDecode(token));File system operation helpers for reading and importing files.
/**
* Read all files from directory matching pattern
* @param location - Directory path
* @param options - Read options
* @returns Array of file information
*/
function fsReadAll(
location: string,
options?: FsReadAllOptions
): Promise<FileInfo[]>;
/**
* Import all files from directory matching pattern
* @param location - Directory path
* @param options - Import options
* @returns Record of imported modules
*/
function fsImportAll(
location: string,
options?: FsImportAllOptions
): Promise<Record<string, any>>;
/**
* File information interface
*/
interface FileInfo {
/** Absolute file path */
path: string;
/** Relative file path */
relativePath: string;
/** File name */
name: string;
/** File extension */
ext: string;
/** File stats */
stats: FileStats;
}
/**
* File stats interface
*/
interface FileStats {
size: number;
isFile: boolean;
isDirectory: boolean;
createdAt: Date;
modifiedAt: Date;
}Usage Examples:
import { fsReadAll, fsImportAll } from "@adonisjs/core/helpers";
// Read all TypeScript files from controllers directory
const controllerFiles = await fsReadAll('./app/controllers', {
pattern: '**/*.ts',
recursive: true
});
// Import all models dynamically
const models = await fsImportAll('./app/models', {
pattern: '**/*.ts',
recursive: true
});
// Use imported models
console.log(Object.keys(models)); // ['User', 'Post', 'Comment', ...]Secure handling of sensitive values in memory.
/**
* Secret wrapper for secure handling of sensitive data
*/
class Secret {
/**
* Create secret wrapper
* @param value - Sensitive value to wrap
*/
constructor(value: string);
/**
* Release and get the secret value
* @returns The secret value (clears internal storage)
*/
release(): string;
/**
* Check if secret has been released
* @returns True if secret has been released
*/
isReleased(): boolean;
/**
* Clone the secret
* @returns New Secret instance with same value
*/
clone(): Secret;
}Usage Examples:
import { Secret } from "@adonisjs/core/helpers";
// Store sensitive data securely
const apiKey = new Secret(process.env.API_KEY!);
const dbPassword = new Secret(process.env.DB_PASSWORD!);
// Use secrets (releases them from memory)
const client = new ApiClient({
apiKey: apiKey.release()
});
const dbConfig = {
password: dbPassword.release()
};
// Secrets are now cleared from memory
console.log(apiKey.isReleased()); // trueSecure token generation and verification for various purposes.
/**
* Verification token generator and verifier
*/
class VerificationToken {
/**
* Create verification token instance
* @param secret - Secret key for signing
* @param purpose - Token purpose/namespace
*/
constructor(secret: string, purpose: string);
/**
* Generate verification token
* @param payload - Data to include in token
* @param expiresIn - Token expiration (in seconds)
* @returns Signed verification token
*/
generate(payload: any, expiresIn?: number): string;
/**
* Verify and decode token
* @param token - Token to verify
* @returns Decoded payload if valid
* @throws Error if token is invalid or expired
*/
verify<T = any>(token: string): T;
/**
* Check if token is valid without throwing
* @param token - Token to check
* @returns True if token is valid
*/
isValid(token: string): boolean;
}Usage Examples:
import { VerificationToken } from "@adonisjs/core/helpers";
// Email verification tokens
const emailVerifier = new VerificationToken(
'email-secret-key',
'email-verification'
);
// Generate email verification token
const emailToken = emailVerifier.generate(
{ userId: 123, email: 'user@example.com' },
3600 // expires in 1 hour
);
// Verify email token
try {
const payload = emailVerifier.verify(emailToken);
console.log('Email verified for user:', payload.userId);
} catch (error) {
console.error('Invalid email verification token');
}
// Password reset tokens
const passwordVerifier = new VerificationToken(
'password-secret-key',
'password-reset'
);
const resetToken = passwordVerifier.generate(
{ userId: 123 },
1800 // expires in 30 minutes
);Utility for parsing container binding references and IoC patterns.
/**
* Parse container binding reference string
* @param bindingReference - Binding reference string
* @returns Parsed binding information
*/
function parseBindingReference(bindingReference: string): BindingReference;
/**
* Binding reference information
*/
interface BindingReference {
/** Namespace or module name */
namespace?: string;
/** Method or property name */
method?: string;
/** Full reference path */
reference: string;
/** Binding type */
type: 'class' | 'method' | 'property';
}Usage Examples:
import { parseBindingReference } from "@adonisjs/core/helpers";
// Parse controller references
const controllerRef = parseBindingReference('UsersController.store');
console.log(controllerRef);
// {
// namespace: 'UsersController',
// method: 'store',
// reference: 'UsersController.store',
// type: 'method'
// }
// Parse service references
const serviceRef = parseBindingReference('Services/UserService');
console.log(serviceRef);
// {
// namespace: 'Services/UserService',
// reference: 'Services/UserService',
// type: 'class'
// }Utility for building formatted messages and templates.
/**
* Message builder for formatted output
*/
class MessageBuilder {
/**
* Create message builder instance
* @param template - Message template
*/
constructor(template: string);
/**
* Add key-value pair to message
* @param key - Key name
* @param value - Value
* @returns This instance for chaining
*/
add(key: string, value: any): this;
/**
* Build final message string
* @returns Formatted message
*/
toString(): string;
/**
* Build message as object
* @returns Message object
*/
toObject(): Record<string, any>;
}Usage Examples:
import { MessageBuilder } from "@adonisjs/core/helpers";
// Build formatted error messages
const errorMessage = new MessageBuilder('Validation failed for {{field}}')
.add('field', 'email')
.add('rule', 'email')
.add('value', 'invalid-email')
.toString();
// Build structured log messages
const logEntry = new MessageBuilder('User action performed')
.add('userId', 123)
.add('action', 'login')
.add('timestamp', new Date())
.add('ip', '192.168.1.1')
.toObject();interface FsReadAllOptions {
/** Glob pattern for file matching */
pattern?: string;
/** Whether to read subdirectories */
recursive?: boolean;
/** File types to include */
types?: ('file' | 'directory')[];
}
interface FsImportAllOptions extends FsReadAllOptions {
/** Transform module key */
transformKey?: (key: string) => string;
/** Filter modules */
filter?: (module: any, key: string) => boolean;
}