serverline-sim/src/commands/create.ts

41 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-12-12 22:43:24 -05:00
import { system, autoColorString } from '@kernel:base';
2021-12-12 23:26:22 -05:00
import chalk from 'chalk';
2021-12-12 22:43:24 -05:00
import * as uuid from 'uuid';
2021-12-11 23:03:55 -05:00
2021-12-12 22:43:24 -05:00
export default async function create(module: string, name: string, id: string) {
if(!module || typeof module !== 'string' || module.trim() === '') {
throw new Error('INVALID_MODULE_NAME');
2021-12-11 23:03:55 -05:00
}
2021-12-12 22:43:24 -05:00
if(name && (typeof name !== 'string' || name.trim() === '')) {
throw new Error('IVALID_MODULE_ALIAS');
}
2021-12-12 23:03:51 -05:00
// undefined means no paramter given. this is treated as a default alias
// otherise, null should be to create anonymous instances. only addressable
// by their creator or by discovery protocols to come soon...
2021-12-12 23:26:22 -05:00
name = name === undefined ? module : name;
2021-12-12 22:43:24 -05:00
if(system.aliases.has(name)) {
if(name === module) {
throw new Error('DEFAULT_MODULE_ALREADY_EXISTS');
} else {
throw new Error('MODULE_ALIAS_TAKEN');
}
}
const imported = (await import('@builtin:' + module));
const functions = 'default' in imported ? imported.default : imported;
id ??= uuid.v4().replace(/-/g, '').toUpperCase();
system.instances.set(id, {
config: {},
ram: {},
module: module,
functions
});
if(name) {
system.aliases.set(name, id);
}
2021-12-12 23:26:22 -05:00
console.log('Created instance of', autoColorString(module));
if(name) {
console.log(' Alias:', autoColorString(name));
}
console.log(' Id:', chalk.ansi256(242)(id));
2021-12-12 22:43:24 -05:00
return id;
}