Core utilities for Medusa e-commerce platform including error handling, DI container, amount calculations, and configuration parsing
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
General-purpose utility functions for regular expression validation, require path creation, and type indexing operations.
Safe regular expression creation from string patterns with automatic validation.
/**
* Attempts to build a RegExp from a string if it's a valid regex pattern
* Supports common regex delimiters and flags
* @param str - String that may contain a regex pattern
* @returns RegExp object if valid pattern, undefined otherwise
*/
function buildRegexpIfValid(str: string): RegExp | undefined;Usage Examples:
import { buildRegexpIfValid } from "medusa-core-utils";
// Valid regex patterns
const emailRegex = buildRegexpIfValid("/^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/");
console.log(emailRegex); // RegExp object
const caseInsensitiveRegex = buildRegexpIfValid("/hello/i");
console.log(caseInsensitiveRegex); // RegExp with 'i' flag
const multilineRegex = buildRegexpIfValid("/^start.*end$/gm");
console.log(multilineRegex); // RegExp with 'gm' flags
// Different delimiters
const withTilde = buildRegexpIfValid("~pattern~i");
const withAt = buildRegexpIfValid("@pattern@g");
const withHash = buildRegexpIfValid("#pattern#");
// Invalid patterns
const invalid1 = buildRegexpIfValid("not a regex");
console.log(invalid1); // undefined
const invalid2 = buildRegexpIfValid("/unclosed pattern");
console.log(invalid2); // undefined
const malformed = buildRegexpIfValid("/[invalid/");
console.log(malformed); // undefined
// Practical usage in validation
function createValidator(pattern: string) {
const regex = buildRegexpIfValid(pattern);
if (!regex) {
throw new Error(`Invalid regex pattern: ${pattern}`);
}
return (value: string) => regex.test(value);
}
// Use in configuration
const validationRules = {
email: "/^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/",
phone: "/^\\+?[1-9]\\d{1,14}$/",
username: "/^[a-zA-Z0-9_]{3,20}$/"
};
const validators = Object.entries(validationRules).reduce((acc, [key, pattern]) => {
const regex = buildRegexpIfValid(pattern);
if (regex) {
acc[key] = (value: string) => regex.test(value);
}
return acc;
}, {} as Record<string, (value: string) => boolean>);
// Use in CORS origin parsing
function parsePattern(pattern: string): string | RegExp {
const regex = buildRegexpIfValid(pattern);
return regex || pattern;
}The function supports various regex pattern formats and delimiters:
Supported Delimiters:
/ - Forward slash (most common)~ - Tilde@ - At symbol; - Semicolon% - Percent# - Hash' - Single quoteSupported Flags:
g - Global matchingi - Case-insensitivem - Multilines - Dot matches newlinesu - Unicodey - Sticky matchingUsage Examples:
import { buildRegexpIfValid } from "medusa-core-utils";
// Common patterns with different delimiters
const patterns = [
"/test/g", // Forward slash with global flag
"~test~i", // Tilde with case-insensitive flag
"@test@m", // At symbol with multiline flag
"#test#gi", // Hash with multiple flags
"'test'", // Single quote, no flags
";test;u" // Semicolon with unicode flag
];
patterns.forEach(pattern => {
const regex = buildRegexpIfValid(pattern);
console.log(`${pattern} -> ${regex || 'invalid'}`);
});
// Complex patterns
const complexPatterns = [
"/^\\d{3}-\\d{2}-\\d{4}$/", // SSN format
"/^[A-Z]{2}\\d{2}\\s?\\d{4}$/i", // Postal code
"/\\b\\w+@\\w+\\.\\w+\\b/g", // Simple email extraction
"/(https?:\\/\\/)([\\w.-]+)/gi" // URL extraction
];
complexPatterns.forEach(pattern => {
const regex = buildRegexpIfValid(pattern);
if (regex) {
console.log(`Valid pattern: ${pattern}`);
console.log(`Flags: ${regex.flags}`);
console.log(`Source: ${regex.source}`);
}
});
// Error handling in pattern parsing
function safeRegexCreate(pattern: string, fallback?: RegExp): RegExp {
const regex = buildRegexpIfValid(pattern);
if (regex) {
return regex;
}
if (fallback) {
return fallback;
}
// Return a regex that matches nothing
return /(?!)/;
}
// Use in search and replace operations
function createSearchReplace(searchPattern: string, replacement: string) {
const regex = buildRegexpIfValid(searchPattern);
if (!regex) {
// Fallback to string replacement
return (text: string) => text.replace(searchPattern, replacement);
}
return (text: string) => text.replace(regex, replacement);
}Usage Examples:
import { buildRegexpIfValid } from "medusa-core-utils";
// User input validation
function validateUserInput(input: string, patterns: string[]): boolean {
return patterns.some(pattern => {
const regex = buildRegexpIfValid(pattern);
return regex ? regex.test(input) : false;
});
}
// Configuration-driven validation
interface ValidationConfig {
field: string;
pattern: string;
required: boolean;
}
function createValidationEngine(configs: ValidationConfig[]) {
const compiledValidators = configs.map(config => {
const regex = buildRegexpIfValid(config.pattern);
return {
...config,
validator: regex ? (value: string) => regex.test(value) : null
};
});
return (data: Record<string, string>) => {
const errors: string[] = [];
for (const config of compiledValidators) {
const value = data[config.field];
if (config.required && !value) {
errors.push(`${config.field} is required`);
continue;
}
if (value && config.validator && !config.validator(value)) {
errors.push(`${config.field} format is invalid`);
}
}
return { isValid: errors.length === 0, errors };
};
}
// Usage with configuration
const validationConfigs: ValidationConfig[] = [
{ field: "email", pattern: "/^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/", required: true },
{ field: "phone", pattern: "/^\\+?[1-9]\\d{1,14}$/", required: false },
{ field: "zipCode", pattern: "/^\\d{5}(-\\d{4})?$/", required: true }
];
const validator = createValidationEngine(validationConfigs);
const userData = {
email: "user@example.com",
phone: "+1234567890",
zipCode: "12345"
};
const result = validator(userData);
console.log(result); // { isValid: true, errors: [] }