UNPKG

scriptable-testlab

Version:

A lightweight, efficient tool designed to manage and update scripts for Scriptable.

100 lines (88 loc) 2.39 kB
/** * Global functions implementation */ import moduleAlias from 'module-alias'; // Add base directory for module resolution moduleAlias.addPath(process.cwd()); /** * Type guard to check if a value is error-like (has message property) */ function isErrorLike(value: unknown): value is {message: string} { return ( typeof value === 'object' && value !== null && 'message' in value && typeof (value as {message: unknown}).message === 'string' ); } /** * Logs a message to the console */ export function log(message: any): void { console.log(message); } /** * Logs a warning message to the console */ export function logWarning(message: any): void { console.warn(message); } /** * Logs an error message to the console */ export function logError(message: any): void { console.error(message); } /** * Converts base64 string to ascii */ export function atob(str: string): string { if (!/^[A-Za-z0-9+/]*={0,2}$/.test(str)) { throw new Error('Invalid base64 string'); } try { return Buffer.from(str, 'base64').toString('ascii'); } catch { throw new Error('Invalid base64 string'); } } /** * Converts ascii string to base64 */ export function btoa(str: string): string { try { return Buffer.from(str, 'ascii').toString('base64'); } catch { throw new Error('Invalid ascii string'); } } /** * Imports a module from the specified path * * @param modulePath - Path to the module to import * @returns The imported module * @throws {Error} When module cannot be found or imported */ export function importModule(modulePath: string): unknown { try { // Remove extensions and relative path prefixes const normalizedPath = modulePath.replace(/\.(js|ts)$/, '').replace(/^(\.\/|\.\.\/)/g, ''); try { return require(normalizedPath); } catch (error) { const errorMessage = isErrorLike(error) ? error.message : String(error); if (errorMessage.includes('Cannot find module')) { throw new Error(`Module not found: ${modulePath}`); } throw error; } } catch (error) { if (isErrorLike(error)) { if ('name' in error && error.name === 'SyntaxError') { throw new Error(`Syntax error in module: ${modulePath}`); } throw new Error(`Failed to import module ${modulePath}: ${error.message}`); } throw new Error(String(error)); } }