System module resolver for script database
npm install @scriptdb/system-modulesSystem module resolver for the script database, providing built-in modules for creating, updating, removing, and saving code snippets.
- Dynamic module loading: Load system modules at runtime
- Code snippet management: Create, update, remove, and save code snippets
- Module registry: Maintain a registry of all available system modules
- Require-like functionality: Access modules using a require-like API
- Import functionality: Access modules using an import-like API
``bash`
bun add @scriptdb/system-modules
`typescript
import { SystemModuleResolver } from '@scriptdb/system-modules';
// Get the system modules context
const context = await SystemModuleResolver();
// Access the built-in modules
const create = context.create;
const update = context.update;
const remove = context.remove;
const save = context.save;
// Create a new code snippet
create('myDatabase', 'function myFunc() { return "Hello, World!"; }');
// Update an existing function
update('myDatabase', 'myFunc', () => { return "Updated function!"; });
// Save entire code to a database
save('myDatabase', 'export const PI = 3.14159;');
// Remove a function
remove('myDatabase', 'myFunc');
`
Resolves and loads all system modules, creating a context with built-in modules.
`typescript`
await SystemModuleResolver(): Promise
Returns a promise that resolves with a context object containing all system modules.
#### create(dbName, code)
Creates a new code snippet in the specified database file.
`typescript`
create(dbName: string, code: string | Function): void
- dbName (string): Name of the database file (without extension)code
- (string | Function): Code content of the snippet
#### update(dbName, fnName, code)
Updates an existing code snippet in the specified database file.
`typescript`
update(dbName: string, fnName: string, code: string | Function): string
- dbName (string): Name of the database filefnName
- (string): Name of the function to updatecode
- (string | Function): New code content
Returns a string indicating the result of the operation.
#### remove(dbName, fnName?)
Removes a code snippet from the specified database file.
`typescript`
remove(dbName: string, fnName?: string): string | boolean
- dbName (string): Name of the database filefnName
- (string, optional): Name of the function to remove. If not provided, removes the entire file.
Returns a string or boolean indicating the result of the operation.
#### save(dbName, code)
Saves code content to the specified database file, overwriting any existing content.
`typescript`
save(dbName: string, code: string | Function | any): void
- dbName (string): Name of the database filecode
- (string | Function | any): Code content to save
#### require(moduleName)
Loads a system module by name.
`typescript`
context.require(moduleName: string): any
- moduleName (string): The name of the module to load
Returns the module's default export if available, otherwise the module itself.
#### import(moduleName)
Asynchronously loads a system module by name.
`typescript`
context.import(moduleName: string): Promise<{ default: any }>
- moduleName (string): The name of the module to load
Returns a promise that resolves with an object containing the module's default export.
`typescript
import { SystemModuleResolver } from '@scriptdb/system-modules';
const context = await SystemModuleResolver();
// Create a new function in a database
context.create('math',
function add(a: number, b: number): number {
return a + b;
});
// Update an existing function
context.update('math', 'add', (a: number, b: number) => {
console.log(Adding ${a} and ${b});
return a + b;
});
// Add a new function to the same database
context.create('math',
function multiply(a: number, b: number): number {
return a * b;
});
// Save a complete module
context.save('utils',
export const formatDate = (date: Date): string => {
return date.toISOString().split('T')[0];
}
export const capitalize = (str: string): string => {
return str.charAt(0).toUpperCase() + str.slice(1);
});`
`typescript
import { SystemModuleResolver } from '@scriptdb/system-modules';
// Get the system modules context
const context = await SystemModuleResolver();
// Access modules directly
const create = context.create;
const update = context.update;
// Create a new module
create('userManagement',
class UserManager {
private users: Array<{ id: number; name: string }> = [];
addUser(name: string): void {
const id = this.users.length + 1;
this.users.push({ id, name });
}
getUser(id: number): { id: number; name: string } | undefined {
return this.users.find(user => user.id === id);
}
listUsers(): Array<{ id: number; name: string }> {
return [...this.users];
}
}
export default UserManager;);
// Use the require-like functionality
const userModule = context.require('userManagement');
// In this case, userModule will contain the user management code
`
`typescript
import { SystemModuleResolver } from '@scriptdb/system-modules';
const context = await SystemModuleResolver();
// Create a class-based module
context.create('database',
class SimpleDatabase {
private data: Record
set(key: string, value: any): void {
this.data[key] = value;
}
get(key: string): any {
return this.data[key];
}
has(key: string): boolean {
return key in this.data;
}
delete(key: string): boolean {
if (this.has(key)) {
delete this.data[key];
return true;
}
return false;
}
clear(): void {
this.data = {};
}
}
export default SimpleDatabase;);
// Create a functional module
context.create('stringUtils',
export const reverse = (str: string): string => {
return str.split('').reverse().join('');
};
export const truncate = (str: string, length: number): string => {
return str.length > length ? str.slice(0, length) + '...' : str;
};
export const slugify = (str: string): string => {
return str
.toLowerCase()
.replace(/[^a-z0-9 -]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-');
};);
// Update a specific function in a module
context.update('stringUtils', 'reverse', (str: string) => {
return Array.from(str).reverse().join('');
});
`
`typescript
import { SystemModuleResolver } from '@scriptdb/system-modules';
const context = await SystemModuleResolver();
// Create a new database file with multiple functions
context.save('api',
import { fetch } from 'bun';
// Function to make GET requests
export async function get(url: string): Promise
const response = await fetch(url);
return await response.json();
}
// Function to make POST requests
export async function post(url: string, data: any): Promise
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return await response.json();
}
// Function to make PUT requests
export async function put(url: string, data: any): Promise
const response = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return await response.json();
}
// Function to make DELETE requests
export async function del(url: string): Promise
const response = await fetch(url, {
method: 'DELETE'
});
return await response.json();
});
// Add a new function to the existing database
context.create('api',
export async function patch(url: string, data: any): Promise
const response = await fetch(url, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return await response.json();
});
// Update an existing function
context.update('api', 'get', async (url: string) => {
const response = await fetch(url);
return await response.json();
});
// Remove a specific function
context.remove('api', 'del');
// Remove the entire database file (after creating a backup)
context.remove('api');
`
The System Module Resolver will throw an error if:
- A module is not found when using require() or import()
- There are issues with file operations
`typescript
import { SystemModuleResolver } from '@scriptdb/system-modules';
try {
const context = await SystemModuleResolver();
try {
const module = context.require('non-existent-module');
} catch (error) {
console.error('Module not found:', error.message);
}
} catch (error) {
console.error('Failed to load system modules:', error.message);
}
`
System modules are stored in TypeScript files in the ./databases/system-modules directory:
```
./databases/system-modules/
├── myDatabase.ts # Database file for code snippets
├── math.ts # Mathematical functions
├── api.ts # API-related functions
└── utils.ts # Utility functions
Each file can contain TypeScript code, including functions, classes, and exports.
- Validate code content before saving to prevent injection attacks
- Consider implementing a sandboxed environment for executing code snippets
- Limit file system access to prevent unauthorized access to sensitive files
- Regularly backup your databases to prevent data loss
MIT