reciple 10.0.6 → 10.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_virtual/{_@oxc-project_runtime@0.110.0 → _@oxc-project_runtime@0.108.0}/helpers/decorate.mjs +1 -1
- package/dist/bin/commands/start.mjs +23 -23
- package/dist/bin/commands/start.mjs.map +1 -1
- package/dist/bin/commands/startSharding.mjs +18 -18
- package/dist/bin/commands/startSharding.mjs.map +1 -1
- package/dist/classes/cli/CLI.mjs +1 -1
- package/dist/classes/client/ModuleLoader.mjs +18 -18
- package/dist/classes/client/ModuleLoader.mjs.map +1 -1
- package/dist/classes/managers/ModuleManager.mjs +1 -1
- package/dist/classes/modules/PostconditionModule.mjs +1 -1
- package/dist/classes/modules/PreconditionModule.mjs +1 -1
- package/dist/classes/modules/commands/ContextMenuCommandModule.mjs +1 -1
- package/dist/classes/modules/commands/MessageCommandModule.mjs +1 -1
- package/dist/classes/modules/commands/SlashCommandModule.mjs +1 -1
- package/dist/classes/templates/ModuleTemplateBuilder.mjs +19 -19
- package/dist/classes/templates/ModuleTemplateBuilder.mjs.map +1 -1
- package/dist/classes/templates/TemplateBuilder.mjs +3 -2
- package/dist/classes/templates/TemplateBuilder.mjs.map +1 -1
- package/dist/classes/validation/BaseModuleValidator.d.mts +11 -11
- package/dist/classes/validation/CommandModuleValidator.d.mts +17 -17
- package/dist/classes/validation/EventModuleValidator.d.mts +9 -9
- package/dist/classes/validation/PostconditionModule.d.mts +9 -9
- package/dist/package.mjs +7 -7
- package/package.json +5 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region \0@oxc-project+runtime@0.
|
|
1
|
+
//#region \0@oxc-project+runtime@0.108.0/helpers/decorate.js
|
|
2
2
|
function __decorate(decorators, target, key, desc) {
|
|
3
3
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
4
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -20,17 +20,17 @@ var StartSubcommand = class extends CLISubcommand {
|
|
|
20
20
|
const flags = this.subcommand.opts();
|
|
21
21
|
await this.cli.setCurrentDirectory(this.subcommand.args[0]);
|
|
22
22
|
const { client, config, build: buildConfig } = await new ConfigReader(await ConfigReader.find() ?? ConfigReader.createConfigFilename("js")).read();
|
|
23
|
-
const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);
|
|
23
|
+
const logger$1 = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);
|
|
24
24
|
let token = flags.token || config.token || "";
|
|
25
25
|
token = resolveEnvProtocol(token) || token;
|
|
26
26
|
function handleProcessError(err) {
|
|
27
|
-
logger.error(err);
|
|
27
|
+
logger$1.error(err);
|
|
28
28
|
process.exit(1);
|
|
29
29
|
}
|
|
30
30
|
process.once("uncaughtException", handleProcessError);
|
|
31
31
|
process.once("unhandledRejection", handleProcessError);
|
|
32
|
-
process.on("warning", (warn) => logger.warn(warn));
|
|
33
|
-
logger.log(colors.magenta(`⚡ Initializing reciple!`));
|
|
32
|
+
process.on("warning", (warn) => logger$1.warn(warn));
|
|
33
|
+
logger$1.log(colors.magenta(`⚡ Initializing reciple!`));
|
|
34
34
|
if (flags.build) {
|
|
35
35
|
let plugins = buildConfig.plugins ? Array.isArray(buildConfig.plugins) ? buildConfig.plugins : [buildConfig.plugins] : [];
|
|
36
36
|
plugins.push(CLI.createTsdownLogger());
|
|
@@ -41,7 +41,7 @@ var StartSubcommand = class extends CLISubcommand {
|
|
|
41
41
|
});
|
|
42
42
|
}
|
|
43
43
|
Object.assign(client, {
|
|
44
|
-
logger,
|
|
44
|
+
logger: logger$1,
|
|
45
45
|
cli: this.cli,
|
|
46
46
|
config
|
|
47
47
|
});
|
|
@@ -51,12 +51,12 @@ var StartSubcommand = class extends CLISubcommand {
|
|
|
51
51
|
eventListeners: new EventListeners()
|
|
52
52
|
});
|
|
53
53
|
Reflect.set(global, "useClient", () => client);
|
|
54
|
-
Reflect.set(global, "useLogger", () => logger);
|
|
54
|
+
Reflect.set(global, "useLogger", () => logger$1);
|
|
55
55
|
EventListeners.registerLoggerEventListeners(client);
|
|
56
|
-
logger.log(colors.green(`📦 Version Info:`));
|
|
57
|
-
logger.log(` ├─ ${colors.cyan(`reciple`)}\t\t${colors.yellow(`${this.cli.version}`)}`);
|
|
58
|
-
logger.log(` ├─ ${colors.cyan(`@reciple/
|
|
59
|
-
logger.log(` └─ ${colors.cyan(`discord.js`)}\t${colors.yellow(`${version}`)}`);
|
|
56
|
+
logger$1.log(colors.green(`📦 Version Info:`));
|
|
57
|
+
logger$1.log(` ├─ ${colors.cyan(`reciple`)}\t\t${colors.yellow(`${this.cli.version}`)}`);
|
|
58
|
+
logger$1.log(` ├─ ${colors.cyan(`@reciple/core`)}\t${colors.yellow(`${Client.version}`)}`);
|
|
59
|
+
logger$1.log(` └─ ${colors.cyan(`discord.js`)}\t${colors.yellow(`${version}`)}`);
|
|
60
60
|
const modules = await client.moduleLoader.findModules();
|
|
61
61
|
Object.assign(client, {
|
|
62
62
|
_onBeforeLogin: async () => {
|
|
@@ -64,14 +64,14 @@ var StartSubcommand = class extends CLISubcommand {
|
|
|
64
64
|
client.once("clientReady", async () => {
|
|
65
65
|
if (!client.isReady()) return;
|
|
66
66
|
EventListeners.registerCommandsEventListeners(client);
|
|
67
|
-
logger.debug(`Client is ready!`);
|
|
67
|
+
logger$1.debug(`Client is ready!`);
|
|
68
68
|
process.removeListener("uncaughtException", handleProcessError);
|
|
69
69
|
process.removeListener("unhandledRejection", handleProcessError);
|
|
70
70
|
const notEnabledModules = modules.length - enabledModules.length;
|
|
71
|
-
logger.log(colors.green(`✅ ${enabledModules.length} ${Format.plural(enabledModules.length, "module")} ${Format.plural(enabledModules.length, "is", "are")} enabled.${notEnabledModules > 0 ? colors.red(` (${notEnabledModules} not enabled)`) : ""}`));
|
|
71
|
+
logger$1.log(colors.green(`✅ ${enabledModules.length} ${Format.plural(enabledModules.length, "module")} ${Format.plural(enabledModules.length, "is", "are")} enabled.${notEnabledModules > 0 ? colors.red(` (${notEnabledModules} not enabled)`) : ""}`));
|
|
72
72
|
const readyModules = await client.modules.readyModules();
|
|
73
73
|
const notReadyModules = readyModules.length - enabledModules.length;
|
|
74
|
-
logger.log(colors.green(`✅ ${readyModules.length} ${Format.plural(readyModules.length, "module")} ${Format.plural(readyModules.length, "is", "are")} ready.${notReadyModules > 0 ? colors.red(` (${notReadyModules} not ready)`) : ""}`));
|
|
74
|
+
logger$1.log(colors.green(`✅ ${readyModules.length} ${Format.plural(readyModules.length, "module")} ${Format.plural(readyModules.length, "is", "are")} ready.${notReadyModules > 0 ? colors.red(` (${notReadyModules} not ready)`) : ""}`));
|
|
75
75
|
await client.commands.registerApplicationCommands({
|
|
76
76
|
...config.applicationCommandsRegister,
|
|
77
77
|
commands: client.commands.applicationCommands
|
|
@@ -82,21 +82,21 @@ var StartSubcommand = class extends CLISubcommand {
|
|
|
82
82
|
message: client.commands.cache.filter((c) => c.type === CommandType.Message).size,
|
|
83
83
|
slash: client.commands.cache.filter((c) => c.type === CommandType.Slash).size
|
|
84
84
|
};
|
|
85
|
-
logger.log(`🔑 Logged in as ${colors.bold(colors.cyan(client.user.displayName))} ${colors.magenta(`(${client.user.id})`)}`);
|
|
86
|
-
logger.log(` ├─ Loaded ${colors.green(modules.length.toLocaleString())} ${Format.plural(modules.length, "module")}.`);
|
|
87
|
-
logger.log(` ├─ Loaded ${colors.green(commands.contextMenus.toLocaleString())} context menu ${Format.plural(commands.contextMenus, "command")}.`);
|
|
88
|
-
logger.log(` ├─ Loaded ${colors.green(commands.message.toLocaleString())} message ${Format.plural(commands.message, "command")}.`);
|
|
89
|
-
logger.log(` ├─ Loaded ${colors.green(commands.slash.toLocaleString())} slash ${Format.plural(commands.slash, "command")}.`);
|
|
90
|
-
logger.log(` ├─ Loaded ${colors.green(client.preconditions.cache.size.toLocaleString())} global ${Format.plural(client.preconditions.cache.size, "precondition")}.`);
|
|
91
|
-
logger.log(` └─ Loaded ${colors.green(client.postconditions.cache.size.toLocaleString())} global ${Format.plural(client.postconditions.cache.size, "postcondition")}.`);
|
|
85
|
+
logger$1.log(`🔑 Logged in as ${colors.bold(colors.cyan(client.user.displayName))} ${colors.magenta(`(${client.user.id})`)}`);
|
|
86
|
+
logger$1.log(` ├─ Loaded ${colors.green(modules.length.toLocaleString())} ${Format.plural(modules.length, "module")}.`);
|
|
87
|
+
logger$1.log(` ├─ Loaded ${colors.green(commands.contextMenus.toLocaleString())} context menu ${Format.plural(commands.contextMenus, "command")}.`);
|
|
88
|
+
logger$1.log(` ├─ Loaded ${colors.green(commands.message.toLocaleString())} message ${Format.plural(commands.message, "command")}.`);
|
|
89
|
+
logger$1.log(` ├─ Loaded ${colors.green(commands.slash.toLocaleString())} slash ${Format.plural(commands.slash, "command")}.`);
|
|
90
|
+
logger$1.log(` ├─ Loaded ${colors.green(client.preconditions.cache.size.toLocaleString())} global ${Format.plural(client.preconditions.cache.size, "precondition")}.`);
|
|
91
|
+
logger$1.log(` └─ Loaded ${colors.green(client.postconditions.cache.size.toLocaleString())} global ${Format.plural(client.postconditions.cache.size, "postcondition")}.`);
|
|
92
92
|
});
|
|
93
93
|
client.eventListeners.registerProcessExitEvents(async (signal) => RuntimeEnvironment.handleExitSignal(client, signal));
|
|
94
94
|
},
|
|
95
|
-
_onBeforeDestroy: async (client) => {
|
|
96
|
-
await client.modules.disableModules();
|
|
95
|
+
_onBeforeDestroy: async (client$1) => {
|
|
96
|
+
await client$1.modules.disableModules();
|
|
97
97
|
}
|
|
98
98
|
});
|
|
99
|
-
logger.debug(`Logging in...`);
|
|
99
|
+
logger$1.debug(`Logging in...`);
|
|
100
100
|
await client.login(token);
|
|
101
101
|
}
|
|
102
102
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.mjs","names":["DiscordJsVersion"],"sources":["../../../src/bin/commands/start.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { Logger } from '@prtty/print';\nimport { Format, resolveEnvProtocol } from '@reciple/utils';\nimport { Client, CommandType } from '@reciple/core';\nimport { ModuleLoader } from '../../classes/client/ModuleLoader.js';\nimport { ModuleManager } from '../../classes/managers/ModuleManager.js';\nimport { version as DiscordJsVersion } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\nimport { RuntimeEnvironment } from '../../classes/cli/RuntimeEnvironment.js';\nimport { build } from 'tsdown';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { colors } from '@prtty/prtty';\n\nexport default class StartSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('start')\n .description('Start the reciple client')\n .argument('[project]', 'The root directory of your project')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-b, --build', 'Build the modules before starting the client')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n const flags = this.subcommand.opts<StartSubcommand.Flags>();\n\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const configReader = new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { client, config, build: buildConfig } = await configReader.read();\n\n const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);\n\n let token = flags.token || config.token || '';\n token = resolveEnvProtocol(token) || token;\n\n function handleProcessError(err: unknown) {\n logger.error(err);\n process.exit(1);\n }\n\n process.once('uncaughtException', handleProcessError);\n process.once('unhandledRejection', handleProcessError);\n process.on('warning', warn => logger.warn(warn));\n\n logger.log(colors.magenta(`⚡ Initializing reciple!`));\n\n if (flags.build) {\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger());\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n\n Object.assign(client, {\n logger,\n cli: this.cli,\n config\n });\n\n Object.assign(client, {\n modules: new ModuleManager(client),\n moduleLoader: new ModuleLoader(client),\n eventListeners: new EventListeners()\n });\n\n Reflect.set(global, 'useClient', () => client);\n Reflect.set(global, 'useLogger', () => logger);\n\n EventListeners.registerLoggerEventListeners(client);\n\n logger.log(colors.green(`📦 Version Info:`));\n logger.log(` ├─ ${colors.cyan(`reciple`)}\\t\\t${colors.yellow(`${this.cli.version}`)}`);\n logger.log(` ├─ ${colors.cyan(`@reciple/client`)}\\t${colors.yellow(`${Client.version}`)}`);\n logger.log(` └─ ${colors.cyan(`discord.js`)}\\t${colors.yellow(`${DiscordJsVersion}`)}`);\n\n const modules = await client.moduleLoader.findModules();\n\n Object.assign(client, {\n _onBeforeLogin: async() => {\n const enabledModules = await client.modules.enableModules({ modules });\n\n client.once('clientReady', async() => {\n if (!client.isReady()) return;\n\n EventListeners.registerCommandsEventListeners(client);\n\n logger.debug(`Client is ready!`);\n process.removeListener('uncaughtException', handleProcessError);\n process.removeListener('unhandledRejection', handleProcessError);\n\n const notEnabledModules = modules.length - enabledModules.length;\n logger.log(colors.green(`✅ ${enabledModules.length} ${Format.plural(enabledModules.length, 'module')} ${Format.plural(enabledModules.length, 'is', 'are')} enabled.${notEnabledModules > 0 ? colors.red(` (${notEnabledModules} not enabled)`) : ''}`));\n\n const readyModules = await client.modules.readyModules();\n const notReadyModules = readyModules.length - enabledModules.length;\n\n logger.log(colors.green(`✅ ${readyModules.length} ${Format.plural(readyModules.length, 'module')} ${Format.plural(readyModules.length, 'is', 'are')} ready.${notReadyModules > 0 ? colors.red(` (${notReadyModules} not ready)`) : ''}`));\n\n await client.commands.registerApplicationCommands({\n ...config.applicationCommandsRegister,\n commands: client.commands.applicationCommands,\n });\n\n process.stdin.resume();\n\n const commands = {\n contextMenus: client.commands.cache.filter(c => c.type === CommandType.ContextMenu).size,\n message: client.commands.cache.filter(c => c.type === CommandType.Message).size,\n slash: client.commands.cache.filter(c => c.type === CommandType.Slash).size\n };\n\n logger.log(`🔑 Logged in as ${colors.bold(colors.cyan(client.user.displayName))} ${colors.magenta(`(${client.user.id})`)}`);\n logger.log(` ├─ Loaded ${colors.green(modules.length.toLocaleString())} ${Format.plural(modules.length, 'module')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.contextMenus.toLocaleString())} context menu ${Format.plural(commands.contextMenus, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.message.toLocaleString())} message ${Format.plural(commands.message, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.slash.toLocaleString())} slash ${Format.plural(commands.slash, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(client.preconditions.cache.size.toLocaleString())} global ${Format.plural(client.preconditions.cache.size, 'precondition')}.`);\n logger.log(` └─ Loaded ${colors.green(client.postconditions.cache.size.toLocaleString())} global ${Format.plural(client.postconditions.cache.size, 'postcondition')}.`);\n });\n\n client.eventListeners.registerProcessExitEvents(async signal => RuntimeEnvironment.handleExitSignal(client, signal));\n },\n _onBeforeDestroy: async (client: Client) => {\n await client.modules.disableModules();\n }\n })\n\n logger.debug(`Logging in...`);\n await client.login(token);\n }\n}\n\nexport namespace StartSubcommand {\n export interface Flags {\n token?: string;\n build?: boolean;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAqB,kBAArB,cAA6C,cAAc;CACvD,AAAO,aAAsB,IAAI,QAAQ,QAAQ,CAC5C,YAAY,2BAA2B,CACvC,SAAS,aAAa,qCAAqC,CAC3D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,eAAe,+CAA+C,CACrE,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;EAClC,MAAM,QAAQ,KAAK,WAAW,MAA6B;AAE3D,QAAM,KAAK,IAAI,oBAAoB,KAAK,WAAW,KAAK,GAAG;EAO3D,MAAM,EAAE,QAAQ,QAAQ,OAAO,gBAAgB,MAL1B,IAAI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AAgB;AAC7B,QAAM,OAAO,MAAM,MAAM"}
|
|
1
|
+
{"version":3,"file":"start.mjs","names":["logger","DiscordJsVersion","client"],"sources":["../../../src/bin/commands/start.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { Logger } from '@prtty/print';\nimport { Format, resolveEnvProtocol } from '@reciple/utils';\nimport { Client, CommandType } from '@reciple/core';\nimport { ModuleLoader } from '../../classes/client/ModuleLoader.js';\nimport { ModuleManager } from '../../classes/managers/ModuleManager.js';\nimport { version as DiscordJsVersion } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\nimport { RuntimeEnvironment } from '../../classes/cli/RuntimeEnvironment.js';\nimport { build } from 'tsdown';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { colors } from '@prtty/prtty';\n\nexport default class StartSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('start')\n .description('Start the reciple client')\n .argument('[project]', 'The root directory of your project')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-b, --build', 'Build the modules before starting the client')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n const flags = this.subcommand.opts<StartSubcommand.Flags>();\n\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const configReader = new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { client, config, build: buildConfig } = await configReader.read();\n\n const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);\n\n let token = flags.token || config.token || '';\n token = resolveEnvProtocol(token) || token;\n\n function handleProcessError(err: unknown) {\n logger.error(err);\n process.exit(1);\n }\n\n process.once('uncaughtException', handleProcessError);\n process.once('unhandledRejection', handleProcessError);\n process.on('warning', warn => logger.warn(warn));\n\n logger.log(colors.magenta(`⚡ Initializing reciple!`));\n\n if (flags.build) {\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger());\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n\n Object.assign(client, {\n logger,\n cli: this.cli,\n config\n });\n\n Object.assign(client, {\n modules: new ModuleManager(client),\n moduleLoader: new ModuleLoader(client),\n eventListeners: new EventListeners()\n });\n\n Reflect.set(global, 'useClient', () => client);\n Reflect.set(global, 'useLogger', () => logger);\n\n EventListeners.registerLoggerEventListeners(client);\n\n logger.log(colors.green(`📦 Version Info:`));\n logger.log(` ├─ ${colors.cyan(`reciple`)}\\t\\t${colors.yellow(`${this.cli.version}`)}`);\n logger.log(` ├─ ${colors.cyan(`@reciple/core`)}\\t${colors.yellow(`${Client.version}`)}`);\n logger.log(` └─ ${colors.cyan(`discord.js`)}\\t${colors.yellow(`${DiscordJsVersion}`)}`);\n\n const modules = await client.moduleLoader.findModules();\n\n Object.assign(client, {\n _onBeforeLogin: async() => {\n const enabledModules = await client.modules.enableModules({ modules });\n\n client.once('clientReady', async() => {\n if (!client.isReady()) return;\n\n EventListeners.registerCommandsEventListeners(client);\n\n logger.debug(`Client is ready!`);\n process.removeListener('uncaughtException', handleProcessError);\n process.removeListener('unhandledRejection', handleProcessError);\n\n const notEnabledModules = modules.length - enabledModules.length;\n logger.log(colors.green(`✅ ${enabledModules.length} ${Format.plural(enabledModules.length, 'module')} ${Format.plural(enabledModules.length, 'is', 'are')} enabled.${notEnabledModules > 0 ? colors.red(` (${notEnabledModules} not enabled)`) : ''}`));\n\n const readyModules = await client.modules.readyModules();\n const notReadyModules = readyModules.length - enabledModules.length;\n\n logger.log(colors.green(`✅ ${readyModules.length} ${Format.plural(readyModules.length, 'module')} ${Format.plural(readyModules.length, 'is', 'are')} ready.${notReadyModules > 0 ? colors.red(` (${notReadyModules} not ready)`) : ''}`));\n\n await client.commands.registerApplicationCommands({\n ...config.applicationCommandsRegister,\n commands: client.commands.applicationCommands,\n });\n\n process.stdin.resume();\n\n const commands = {\n contextMenus: client.commands.cache.filter(c => c.type === CommandType.ContextMenu).size,\n message: client.commands.cache.filter(c => c.type === CommandType.Message).size,\n slash: client.commands.cache.filter(c => c.type === CommandType.Slash).size\n };\n\n logger.log(`🔑 Logged in as ${colors.bold(colors.cyan(client.user.displayName))} ${colors.magenta(`(${client.user.id})`)}`);\n logger.log(` ├─ Loaded ${colors.green(modules.length.toLocaleString())} ${Format.plural(modules.length, 'module')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.contextMenus.toLocaleString())} context menu ${Format.plural(commands.contextMenus, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.message.toLocaleString())} message ${Format.plural(commands.message, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.slash.toLocaleString())} slash ${Format.plural(commands.slash, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(client.preconditions.cache.size.toLocaleString())} global ${Format.plural(client.preconditions.cache.size, 'precondition')}.`);\n logger.log(` └─ Loaded ${colors.green(client.postconditions.cache.size.toLocaleString())} global ${Format.plural(client.postconditions.cache.size, 'postcondition')}.`);\n });\n\n client.eventListeners.registerProcessExitEvents(async signal => RuntimeEnvironment.handleExitSignal(client, signal));\n },\n _onBeforeDestroy: async (client: Client) => {\n await client.modules.disableModules();\n }\n })\n\n logger.debug(`Logging in...`);\n await client.login(token);\n }\n}\n\nexport namespace StartSubcommand {\n export interface Flags {\n token?: string;\n build?: boolean;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAqB,kBAArB,cAA6C,cAAc;CACvD,AAAO,aAAsB,IAAI,QAAQ,QAAQ,CAC5C,YAAY,2BAA2B,CACvC,SAAS,aAAa,qCAAqC,CAC3D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,eAAe,+CAA+C,CACrE,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;EAClC,MAAM,QAAQ,KAAK,WAAW,MAA6B;AAE3D,QAAM,K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,CAAC;;GAExH,kBAAkB,OAAO,aAAmB;AACxC,UAAMC,SAAO,QAAQ,gBAAgB;;GAE5C,CAAC;AAEF,WAAO,MAAM,gBAAgB;AAC7B,QAAM,OAAO,MAAM,MAAM"}
|
|
@@ -25,18 +25,18 @@ var StartShardingSubcommand = class extends CLISubcommand {
|
|
|
25
25
|
...CLI.stringifyFlags(flags, this.command)
|
|
26
26
|
];
|
|
27
27
|
const { config, build: buildConfig, sharding } = await new ConfigReader(await ConfigReader.find() ?? ConfigReader.createConfigFilename("js")).read();
|
|
28
|
-
const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);
|
|
29
|
-
logger.label = "ShardingManager";
|
|
28
|
+
const logger$1 = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);
|
|
29
|
+
logger$1.label = "ShardingManager";
|
|
30
30
|
let token = flags.token || config.token || "";
|
|
31
31
|
token = resolveEnvProtocol(token) || token;
|
|
32
|
-
logger.log(colors.magenta(`⚡ Initializing reciple sharding manager!`));
|
|
32
|
+
logger$1.log(colors.magenta(`⚡ Initializing reciple sharding manager!`));
|
|
33
33
|
const processErrorLogger = (err) => {
|
|
34
|
-
logger?.error(err);
|
|
34
|
+
logger$1?.error(err);
|
|
35
35
|
process.exit(1);
|
|
36
36
|
};
|
|
37
37
|
process.once("uncaughtException", processErrorLogger);
|
|
38
38
|
process.once("unhandledRejection", processErrorLogger);
|
|
39
|
-
process.on("warning", (warn) => logger.warn(warn));
|
|
39
|
+
process.on("warning", (warn) => logger$1.warn(warn));
|
|
40
40
|
if (flags.build) {
|
|
41
41
|
let plugins = buildConfig.plugins ? Array.isArray(buildConfig.plugins) ? buildConfig.plugins : [buildConfig.plugins] : [];
|
|
42
42
|
plugins.push(CLI.createTsdownLogger());
|
|
@@ -47,10 +47,10 @@ var StartShardingSubcommand = class extends CLISubcommand {
|
|
|
47
47
|
});
|
|
48
48
|
}
|
|
49
49
|
if (!sharding) {
|
|
50
|
-
logger.error("Sharding is not enabled in the config file");
|
|
50
|
+
logger$1.error("Sharding is not enabled in the config file");
|
|
51
51
|
process.exit(1);
|
|
52
52
|
}
|
|
53
|
-
Reflect.set(global, "useLogger", () => logger);
|
|
53
|
+
Reflect.set(global, "useLogger", () => logger$1);
|
|
54
54
|
const eventListeners = new EventListeners();
|
|
55
55
|
const manager = new ShardingManager(CLI.bin, {
|
|
56
56
|
...sharding,
|
|
@@ -58,25 +58,25 @@ var StartShardingSubcommand = class extends CLISubcommand {
|
|
|
58
58
|
shardArgs
|
|
59
59
|
});
|
|
60
60
|
manager.on("shardCreate", (shard) => {
|
|
61
|
-
logger.log(colors.magenta(`🚀 Launched shard ${colors.green(String(shard.id))}`));
|
|
61
|
+
logger$1.log(colors.magenta(`🚀 Launched shard ${colors.green(String(shard.id))}`));
|
|
62
62
|
shard.on("ready", () => {
|
|
63
|
-
logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} is ready!`));
|
|
63
|
+
logger$1.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} is ready!`));
|
|
64
64
|
if (process.env.RECIPLE_FIRST_SHARD === "true") process.env.RECIPLE_FIRST_SHARD = "false";
|
|
65
65
|
});
|
|
66
66
|
shard.on("reconnecting", () => {
|
|
67
|
-
logger.log(colors.magenta(`🔄 Shard ${colors.green(String(shard.id))} is reconnecting...`));
|
|
67
|
+
logger$1.log(colors.magenta(`🔄 Shard ${colors.green(String(shard.id))} is reconnecting...`));
|
|
68
68
|
});
|
|
69
69
|
shard.on("resume", () => {
|
|
70
|
-
logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} has resumed!`));
|
|
70
|
+
logger$1.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} has resumed!`));
|
|
71
71
|
});
|
|
72
72
|
shard.on("disconnect", () => {
|
|
73
|
-
logger.log(colors.magenta(`🛑 Shard ${colors.green(String(shard.id))} is disconnected!`));
|
|
73
|
+
logger$1.log(colors.magenta(`🛑 Shard ${colors.green(String(shard.id))} is disconnected!`));
|
|
74
74
|
});
|
|
75
75
|
shard.on("death", () => {
|
|
76
|
-
logger.error(`🛑 Shard ${colors.green(String(shard.id))} has died!`);
|
|
76
|
+
logger$1.error(`🛑 Shard ${colors.green(String(shard.id))} has died!`);
|
|
77
77
|
});
|
|
78
78
|
shard.on("error", (error) => {
|
|
79
|
-
logger.error(`❌ Shard ${colors.green(String(shard.id))} encountered an error:`, error);
|
|
79
|
+
logger$1.error(`❌ Shard ${colors.green(String(shard.id))} encountered an error:`, error);
|
|
80
80
|
});
|
|
81
81
|
shard.on("message", (message) => {});
|
|
82
82
|
});
|
|
@@ -85,14 +85,14 @@ var StartShardingSubcommand = class extends CLISubcommand {
|
|
|
85
85
|
await manager.spawn();
|
|
86
86
|
}
|
|
87
87
|
destroyShardingManager(manager) {
|
|
88
|
-
const logger = useLogger();
|
|
88
|
+
const logger$1 = useLogger();
|
|
89
89
|
manager.shards.map((s) => {
|
|
90
|
-
logger.log(colors.magenta(`🚧 Destroying shard ${s.id}`));
|
|
90
|
+
logger$1.log(colors.magenta(`🚧 Destroying shard ${s.id}`));
|
|
91
91
|
if (s.process) s.process.kill();
|
|
92
92
|
else s.kill();
|
|
93
|
-
logger.log(colors.magenta(`🛑 Destroyed shard ${s.id}`));
|
|
93
|
+
logger$1.log(colors.magenta(`🛑 Destroyed shard ${s.id}`));
|
|
94
94
|
});
|
|
95
|
-
logger.log(colors.magenta(`🚨 Destroyed all shards`));
|
|
95
|
+
logger$1.log(colors.magenta(`🚨 Destroyed all shards`));
|
|
96
96
|
setTimeout(() => process.exit(0), 500);
|
|
97
97
|
}
|
|
98
98
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"startSharding.mjs","names":[],"sources":["../../../src/bin/commands/startSharding.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport type { StartSubcommand } from './start.js';\nimport { Logger } from '@prtty/print';\nimport { resolveEnvProtocol } from '@reciple/utils';\nimport { colors } from '@prtty/prtty';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { build } from 'tsdown';\nimport { ShardingManager } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\n\nexport default class StartShardingSubcommand extends CLISubcommand {\n public parent?: string = 'start';\n\n public subcommand: Command = new Command('sharding')\n .description('Start the reciple client in sharding mode')\n .argument('[project]', 'The root directory of your project')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-b, --build', 'Build the modules before starting the client')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n process.env.RECIPLE_SHARDING = 'true';\n process.env.RECIPLE_FIRST_SHARD = 'true';\n\n const recipleFlags = this.cli.getFlags();\n const flags = this.subcommand.opts<ShardingSubcommand.Flags>();\n\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const shardArgs: string[] = [\n ...CLI.stringifyFlags(recipleFlags, this.cli.command),\n 'start',\n ...CLI.stringifyFlags(flags, this.command)\n ];\n\n const configReader = new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { config, build: buildConfig, sharding } = await configReader.read();\n const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);\n\n logger.label = 'ShardingManager';\n\n let token = flags.token || config.token || '';\n token = resolveEnvProtocol(token) || token;\n\n logger.log(colors.magenta(`⚡ Initializing reciple sharding manager!`));\n\n const processErrorLogger = (err: any) => {\n logger?.error(err);\n process.exit(1);\n };\n\n process.once('uncaughtException', processErrorLogger);\n process.once('unhandledRejection', processErrorLogger);\n process.on('warning', warn => logger.warn(warn));\n\n if (flags.build) {\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger());\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n\n if (!sharding) {\n logger.error('Sharding is not enabled in the config file');\n process.exit(1);\n }\n\n Reflect.set(global, 'useLogger', () => logger);\n\n const eventListeners = new EventListeners();\n const manager = new ShardingManager(CLI.bin, {\n ...sharding,\n token: token,\n shardArgs\n });\n\n manager.on('shardCreate', shard => {\n logger.log(colors.magenta(`🚀 Launched shard ${colors.green(String(shard.id))}`));\n\n shard.on('ready', () => {\n logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} is ready!`));\n\n if (process.env.RECIPLE_FIRST_SHARD === 'true') {\n process.env.RECIPLE_FIRST_SHARD = 'false';\n }\n });\n\n shard.on('reconnecting', () => {\n logger.log(colors.magenta(`🔄 Shard ${colors.green(String(shard.id))} is reconnecting...`));\n });\n\n shard.on('resume', () => {\n logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} has resumed!`));\n });\n\n shard.on('disconnect', () => {\n logger.log(colors.magenta(`🛑 Shard ${colors.green(String(shard.id))} is disconnected!`));\n });\n\n shard.on('death', () => {\n logger.error(`🛑 Shard ${colors.green(String(shard.id))} has died!`);\n });\n\n shard.on('error', error => {\n logger.error(`❌ Shard ${colors.green(String(shard.id))} encountered an error:`, error);\n });\n\n shard.on('message', message => {\n // TODO: Handle shard messages\n });\n });\n\n eventListeners.registerProcessExitEvents(signal => this.destroyShardingManager(manager));\n process.stdin.resume();\n\n await manager.spawn();\n }\n\n public destroyShardingManager(manager: ShardingManager): void {\n const logger = useLogger();\n\n manager.shards.map(s => {\n logger.log(colors.magenta(`🚧 Destroying shard ${s.id}`));\n\n if (s.process) {\n s.process.kill();\n } else {\n s.kill();\n }\n\n logger.log(colors.magenta(`🛑 Destroyed shard ${s.id}`));\n });\n\n logger.log(colors.magenta(`🚨 Destroyed all shards`));\n setTimeout(() => process.exit(0), 500);\n }\n}\n\nexport namespace ShardingSubcommand {\n export interface Flags extends StartSubcommand.Flags {}\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAqB,0BAArB,cAAqD,cAAc;CAC/D,AAAO,SAAkB;CAEzB,AAAO,aAAsB,IAAI,QAAQ,WAAW,CAC/C,YAAY,4CAA4C,CACxD,SAAS,aAAa,qCAAqC,CAC3D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,eAAe,+CAA+C,CACrE,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;AAClC,UAAQ,IAAI,mBAAmB;AAC/B,UAAQ,IAAI,sBAAsB;EAElC,MAAM,eAAe,KAAK,IAAI,UAAU;EACxC,MAAM,QAAQ,KAAK,WAAW,MAAgC;AAE9D,QAAM,KAAK,IAAI,oBAAoB,KAAK,WAAW,KAAK,GAAG;EAE3D,MAAM,YAAsB;GACxB,GAAG,IAAI,eAAe,cAAc,KAAK,IAAI,QAAQ;GACrD;GACA,GAAG,IAAI,eAAe,OAAO,KAAK,QAAQ;GAC7C;EAOD,MAAM,EAAE,QAAQ,OAAO,aAAa,aAAa,MAL5B,IAAI,aACrB,MAAM,aAAa,MAAM,IACtB,aAAa,qBAAqB,KAAK,CAC7C,CAEmE,MAAM;EAC1E,
|
|
1
|
+
{"version":3,"file":"startSharding.mjs","names":["logger"],"sources":["../../../src/bin/commands/startSharding.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport type { StartSubcommand } from './start.js';\nimport { Logger } from '@prtty/print';\nimport { resolveEnvProtocol } from '@reciple/utils';\nimport { colors } from '@prtty/prtty';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { build } from 'tsdown';\nimport { ShardingManager } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\n\nexport default class StartShardingSubcommand extends CLISubcommand {\n public parent?: string = 'start';\n\n public subcommand: Command = new Command('sharding')\n .description('Start the reciple client in sharding mode')\n .argument('[project]', 'The root directory of your project')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-b, --build', 'Build the modules before starting the client')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n process.env.RECIPLE_SHARDING = 'true';\n process.env.RECIPLE_FIRST_SHARD = 'true';\n\n const recipleFlags = this.cli.getFlags();\n const flags = this.subcommand.opts<ShardingSubcommand.Flags>();\n\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const shardArgs: string[] = [\n ...CLI.stringifyFlags(recipleFlags, this.cli.command),\n 'start',\n ...CLI.stringifyFlags(flags, this.command)\n ];\n\n const configReader = new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { config, build: buildConfig, sharding } = await configReader.read();\n const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);\n\n logger.label = 'ShardingManager';\n\n let token = flags.token || config.token || '';\n token = resolveEnvProtocol(token) || token;\n\n logger.log(colors.magenta(`⚡ Initializing reciple sharding manager!`));\n\n const processErrorLogger = (err: any) => {\n logger?.error(err);\n process.exit(1);\n };\n\n process.once('uncaughtException', processErrorLogger);\n process.once('unhandledRejection', processErrorLogger);\n process.on('warning', warn => logger.warn(warn));\n\n if (flags.build) {\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger());\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n\n if (!sharding) {\n logger.error('Sharding is not enabled in the config file');\n process.exit(1);\n }\n\n Reflect.set(global, 'useLogger', () => logger);\n\n const eventListeners = new EventListeners();\n const manager = new ShardingManager(CLI.bin, {\n ...sharding,\n token: token,\n shardArgs\n });\n\n manager.on('shardCreate', shard => {\n logger.log(colors.magenta(`🚀 Launched shard ${colors.green(String(shard.id))}`));\n\n shard.on('ready', () => {\n logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} is ready!`));\n\n if (process.env.RECIPLE_FIRST_SHARD === 'true') {\n process.env.RECIPLE_FIRST_SHARD = 'false';\n }\n });\n\n shard.on('reconnecting', () => {\n logger.log(colors.magenta(`🔄 Shard ${colors.green(String(shard.id))} is reconnecting...`));\n });\n\n shard.on('resume', () => {\n logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} has resumed!`));\n });\n\n shard.on('disconnect', () => {\n logger.log(colors.magenta(`🛑 Shard ${colors.green(String(shard.id))} is disconnected!`));\n });\n\n shard.on('death', () => {\n logger.error(`🛑 Shard ${colors.green(String(shard.id))} has died!`);\n });\n\n shard.on('error', error => {\n logger.error(`❌ Shard ${colors.green(String(shard.id))} encountered an error:`, error);\n });\n\n shard.on('message', message => {\n // TODO: Handle shard messages\n });\n });\n\n eventListeners.registerProcessExitEvents(signal => this.destroyShardingManager(manager));\n process.stdin.resume();\n\n await manager.spawn();\n }\n\n public destroyShardingManager(manager: ShardingManager): void {\n const logger = useLogger();\n\n manager.shards.map(s => {\n logger.log(colors.magenta(`🚧 Destroying shard ${s.id}`));\n\n if (s.process) {\n s.process.kill();\n } else {\n s.kill();\n }\n\n logger.log(colors.magenta(`🛑 Destroyed shard ${s.id}`));\n });\n\n logger.log(colors.magenta(`🚨 Destroyed all shards`));\n setTimeout(() => process.exit(0), 500);\n }\n}\n\nexport namespace ShardingSubcommand {\n export interface Flags extends StartSubcommand.Flags {}\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAqB,0BAArB,cAAqD,cAAc;CAC/D,AAAO,SAAkB;CAEzB,AAAO,aAAsB,IAAI,QAAQ,WAAW,CAC/C,YAAY,4CAA4C,CACxD,SAAS,aAAa,qCAAqC,CAC3D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,eAAe,+CAA+C,CACrE,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;AAClC,UAAQ,IAAI,mBAAmB;AAC/B,UAAQ,IAAI,sBAAsB;EAElC,MAAM,eAAe,KAAK,IAAI,UAAU;EACxC,MAAM,QAAQ,KAAK,WAAW,MAAgC;AAE9D,QAAM,KAA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OAEhB,GAAE,MAAM;AAGZ,YAAO,IAAI,OAAO,QAAQ,sBAAsB,EAAE,KAAK,CAAC;IAC1D;AAEF,WAAO,IAAI,OAAO,QAAQ,0BAA0B,CAAC;AACrD,mBAAiB,QAAQ,KAAK,EAAE,EAAE,IAAI"}
|
package/dist/classes/cli/CLI.mjs
CHANGED
|
@@ -95,7 +95,7 @@ var CLI = class {
|
|
|
95
95
|
(function(_CLI) {
|
|
96
96
|
_CLI.root = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../");
|
|
97
97
|
_CLI.bin = path.join(CLI.root, "dist/bin/reciple.mjs");
|
|
98
|
-
_CLI.version = "10.0.
|
|
98
|
+
_CLI.version = "10.0.8";
|
|
99
99
|
function stringifyFlags(flags, command, ignored = []) {
|
|
100
100
|
let arr = [];
|
|
101
101
|
for (const [key, value] of Object.entries(flags)) {
|
|
@@ -11,14 +11,14 @@ import { CommandModuleValidator } from "../validation/CommandModuleValidator.mjs
|
|
|
11
11
|
import { EventModuleValidator } from "../validation/EventModuleValidator.mjs";
|
|
12
12
|
import { PreconditionModuleValidator } from "../validation/PreconditionModule.mjs";
|
|
13
13
|
import { PostconditionModuleValidator } from "../validation/PostconditionModule.mjs";
|
|
14
|
-
import path
|
|
14
|
+
import path from "node:path";
|
|
15
15
|
import { recursiveDefaults } from "@reciple/utils";
|
|
16
16
|
import { mkdir, readdir, stat } from "node:fs/promises";
|
|
17
17
|
import { colors } from "@prtty/prtty";
|
|
18
18
|
import { CommandType, RecipleError } from "@reciple/core";
|
|
19
19
|
import "discord.js";
|
|
20
20
|
import micromatch from "micromatch";
|
|
21
|
-
import { globby
|
|
21
|
+
import { globby, isDynamicPattern } from "globby";
|
|
22
22
|
import { EventEmitter } from "node:events";
|
|
23
23
|
|
|
24
24
|
//#region src/classes/client/ModuleLoader.ts
|
|
@@ -33,19 +33,19 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
33
33
|
const modulePaths = await ModuleLoader.scanForModulePaths(this.client.config?.modules);
|
|
34
34
|
const modules = [];
|
|
35
35
|
this.emit("modulesResolving", modulePaths);
|
|
36
|
-
for (const path of modulePaths) try {
|
|
37
|
-
this.emit("moduleResolving", path);
|
|
38
|
-
const resolved = await ModuleLoader.resolveModuleFromPath(path);
|
|
36
|
+
for (const path$1 of modulePaths) try {
|
|
37
|
+
this.emit("moduleResolving", path$1);
|
|
38
|
+
const resolved = await ModuleLoader.resolveModuleFromPath(path$1);
|
|
39
39
|
Object.assign(resolved, {
|
|
40
40
|
client: this.client,
|
|
41
|
-
__$filepath: path
|
|
41
|
+
__$filepath: path$1
|
|
42
42
|
});
|
|
43
43
|
modules.push(resolved);
|
|
44
44
|
this.emit("moduleResolved", resolved);
|
|
45
45
|
} catch (error) {
|
|
46
46
|
if (ignoreErrors) continue;
|
|
47
47
|
this.emitOrThrow("moduleResolveError", new RecipleError({
|
|
48
|
-
message: `Failed to load module: ${colors.cyan(path)}`,
|
|
48
|
+
message: `Failed to load module: ${colors.cyan(path$1)}`,
|
|
49
49
|
cause: error
|
|
50
50
|
}));
|
|
51
51
|
}
|
|
@@ -58,7 +58,7 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
58
58
|
let directories = [];
|
|
59
59
|
for (const directory of config?.directories ?? []) {
|
|
60
60
|
if (isDynamicPattern(directory, { cwd })) {
|
|
61
|
-
const matches = await globby
|
|
61
|
+
const matches = await globby(directory, {
|
|
62
62
|
cwd,
|
|
63
63
|
ignore: config?.ignore,
|
|
64
64
|
onlyDirectories: true,
|
|
@@ -68,7 +68,7 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
68
68
|
scanned.push(...matches);
|
|
69
69
|
continue;
|
|
70
70
|
}
|
|
71
|
-
scanned.push(path
|
|
71
|
+
scanned.push(path.join(cwd, directory));
|
|
72
72
|
}
|
|
73
73
|
for (const directory of scanned) {
|
|
74
74
|
if (!await stat(directory).catch(() => void 0) && config?.createDirectories !== false) await mkdir(directory, { recursive: true });
|
|
@@ -86,7 +86,7 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
86
86
|
matchBase: true,
|
|
87
87
|
dot: true
|
|
88
88
|
});
|
|
89
|
-
files = files.map((f) => path
|
|
89
|
+
files = files.map((f) => path.join(directory, f));
|
|
90
90
|
for (const file of files) {
|
|
91
91
|
if (config?.filter ? !await config?.filter(file) : ModuleLoader.fileTypes.every((type) => !file.endsWith(`.${type}`))) continue;
|
|
92
92
|
modules.push(file);
|
|
@@ -97,7 +97,7 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
97
97
|
}
|
|
98
98
|
static async resolveModuleFromPath(filepath, options) {
|
|
99
99
|
if (!await stat(filepath).catch(() => void 0)) throw new RecipleError(`Module not found: ${filepath}`);
|
|
100
|
-
const data = recursiveDefaults(await import(`file://${path
|
|
100
|
+
const data = recursiveDefaults(await import(`file://${path.resolve(options?.cwd ?? process.cwd(), filepath)}`));
|
|
101
101
|
if (BaseModule.isModule(data)) return data;
|
|
102
102
|
if (data && "moduleType" in data) switch (data?.moduleType) {
|
|
103
103
|
case ModuleType.Command:
|
|
@@ -125,10 +125,10 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
125
125
|
return BaseModule.from(data);
|
|
126
126
|
}
|
|
127
127
|
static async resolveSourceDirectories(options) {
|
|
128
|
-
const dir = path
|
|
129
|
-
const root = path
|
|
130
|
-
const out = path
|
|
131
|
-
return options.directories.map((directory) => path
|
|
128
|
+
const dir = path.isAbsolute(options.baseUrl) ? options.baseUrl : path.resolve(path.join(options.cwd ?? process.cwd(), options.baseUrl));
|
|
129
|
+
const root = path.resolve(path.join(dir, options.rootDir));
|
|
130
|
+
const out = path.resolve(path.join(dir, options.outDir));
|
|
131
|
+
return options.directories.map((directory) => path.resolve(directory).replace(out, root));
|
|
132
132
|
}
|
|
133
133
|
emitOrThrow(event, error) {
|
|
134
134
|
if (this.client.listenerCount(event) > 0) return this.emit(event, error);
|
|
@@ -136,15 +136,15 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
136
136
|
}
|
|
137
137
|
};
|
|
138
138
|
(function(_ModuleLoader) {
|
|
139
|
-
let globby = _ModuleLoader.globby = null;
|
|
139
|
+
let globby$1 = _ModuleLoader.globby = null;
|
|
140
140
|
_ModuleLoader.fileTypes = [
|
|
141
141
|
"js",
|
|
142
142
|
"mjs",
|
|
143
143
|
"jsx"
|
|
144
144
|
];
|
|
145
145
|
async function getGlobby() {
|
|
146
|
-
if (globby) return globby;
|
|
147
|
-
return globby = await import("globby");
|
|
146
|
+
if (globby$1) return globby$1;
|
|
147
|
+
return globby$1 = await import("globby");
|
|
148
148
|
}
|
|
149
149
|
_ModuleLoader.getGlobby = getGlobby;
|
|
150
150
|
})(ModuleLoader || (ModuleLoader = {}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModuleLoader.mjs","names":["globby","path"],"sources":["../../../src/classes/client/ModuleLoader.ts"],"sourcesContent":["import { type Awaitable } from 'discord.js';\nimport path from 'node:path';\nimport { mkdir, readdir, stat } from 'node:fs/promises';\nimport micromatch from 'micromatch';\nimport { globby, isDynamicPattern } from 'globby';\nimport { CommandType, RecipleError, type Client } from '@reciple/core';\nimport type { AnyModule, AnyModuleData } from '../../helpers/types.js';\nimport { recursiveDefaults } from '@reciple/utils';\nimport { BaseModule } from '../modules/BaseModule.js';\nimport { BaseModuleValidator } from '../validation/BaseModuleValidator.js';\nimport { ModuleType } from '../../helpers/constants.js';\nimport { PostconditionModule } from '../modules/PostconditionModule.js';\nimport { PreconditionModule } from '../modules/PreconditionModule.js';\nimport { EventModule } from '../modules/events/EventModule.js';\nimport { MessageCommandModule } from '../modules/commands/MessageCommandModule.js';\nimport { SlashCommandModule } from '../modules/commands/SlashCommandModule.js';\nimport { ContextMenuCommandModule } from '../modules/commands/ContextMenuCommandModule.js';\nimport { CommandModuleValidator } from '../validation/CommandModuleValidator.js';\nimport { EventModuleValidator } from '../validation/EventModuleValidator.js';\nimport { PreconditionModuleValidator } from '../validation/PreconditionModule.js';\nimport { PostconditionModuleValidator } from '../validation/PostconditionModule.js';\nimport type { Logger } from '@prtty/print';\nimport { EventEmitter } from 'node:events';\nimport { colors } from '@prtty/prtty';\n\nexport class ModuleLoader extends EventEmitter<ModuleLoader.Events> {\n public readonly logger: Logger;\n\n constructor(public readonly client: Client) {\n super();\n\n this.logger = this.client.logger.clone({\n label: 'ModuleLoader'\n });\n }\n\n public async findModules(ignoreErrors: boolean = false): Promise<AnyModule[]> {\n const modulePaths = await ModuleLoader.scanForModulePaths(this.client.config?.modules);\n const modules: AnyModule[] = [];\n\n this.emit('modulesResolving', modulePaths);\n\n for (const path of modulePaths) {\n try {\n this.emit('moduleResolving', path);\n const resolved = await ModuleLoader.resolveModuleFromPath(path);\n\n Object.assign(resolved, { client: this.client, __$filepath: path });\n modules.push(resolved);\n\n this.emit('moduleResolved', resolved);\n } catch (error) {\n if (ignoreErrors) continue;\n\n this.emitOrThrow('moduleResolveError', new RecipleError({\n message: `Failed to load module: ${colors.cyan(path)}`,\n cause: error\n }));\n }\n }\n\n this.emit('modulesResolved', modules);\n return modules;\n }\n\n public static async scanForDirectories(config?: Pick<ModuleLoader.Config, 'directories'|'ignore'> & { cwd?: string; createDirectories?: boolean; }) {\n const cwd = config?.cwd ?? process.cwd();\n\n let scanned: string[] = [];\n let directories: string[] = [];\n\n for (const directory of config?.directories ?? []) {\n if (isDynamicPattern(directory, { cwd })) {\n const matches = await globby(directory, {\n cwd,\n ignore: config?.ignore,\n onlyDirectories: true,\n baseNameMatch: true,\n absolute: true\n });\n\n scanned.push(...matches);\n continue;\n }\n\n scanned.push(path.join(cwd, directory));\n }\n\n for (const directory of scanned) {\n const stats = await stat(directory).catch(() => undefined);\n\n if (!stats && config?.createDirectories !== false) {\n await mkdir(directory, { recursive: true });\n }\n\n directories.push(directory);\n }\n\n return directories;\n }\n\n public static async scanForModulePaths(config?: ModuleLoader.Config & { cwd?: string; createDirectories?: boolean; }): Promise<string[]> {\n const directories = await ModuleLoader.scanForDirectories(config);\n\n let modules: string[] = [];\n\n for (const directory of directories) {\n let files = await readdir(directory);\n\n if (config?.ignore?.length) {\n files = micromatch.not(files, config.ignore, {\n cwd: directory,\n matchBase: true,\n dot: true\n });\n }\n\n files = files.map(f => path.join(directory, f));\n\n for (const file of files) {\n if (config?.filter ? !(await config?.filter(file)) : ModuleLoader.fileTypes.every(type => !file.endsWith(`.${type}`))) continue;\n modules.push(file);\n }\n }\n\n if (config?.sort) modules.sort(config.sort);\n\n return modules;\n }\n\n public static async resolveModuleFromPath(filepath: string, options?: { cwd?: string; }): Promise<AnyModule> {\n const stats = await stat(filepath).catch(() => undefined);\n if (!stats) throw new RecipleError(`Module not found: ${filepath}`);\n\n const data = recursiveDefaults<AnyModule|AnyModuleData|undefined>(await import(`file://${path.resolve(options?.cwd ?? process.cwd(), filepath)}`));\n if (BaseModule.isModule(data)) return data;\n\n if (data && 'moduleType' in data) {\n switch (data?.moduleType) {\n case ModuleType.Command:\n CommandModuleValidator.isValid(data);\n switch (data.type) {\n case CommandType.Message: return MessageCommandModule.from(data);\n case CommandType.Slash: return SlashCommandModule.from(data);\n case CommandType.ContextMenu: return ContextMenuCommandModule.from(data);\n default: throw new RecipleError(`Unknown command type from module: ${colors.cyan(filepath)}`);\n }\n case ModuleType.Event:\n EventModuleValidator.isValid(data);\n return EventModule.from(data);\n case ModuleType.Precondition:\n PreconditionModuleValidator.isValid(data);\n return PreconditionModule.from(data);\n case ModuleType.Postcondition:\n PostconditionModuleValidator.isValid(data);\n return PostconditionModule.from(data);\n default:\n BaseModuleValidator.isValid(data);\n return BaseModule.from(data);\n }\n }\n\n BaseModuleValidator.isValid(data);\n return BaseModule.from(data);\n }\n\n public static async resolveSourceDirectories(options: ModuleLoader.ResolveSourceDirectoryOptions): Promise<string[]> {\n const dir = path.isAbsolute(options.baseUrl) ? options.baseUrl : path.resolve(path.join(options.cwd ?? process.cwd(), options.baseUrl));\n\n const root = path.resolve(path.join(dir, options.rootDir));\n const out = path.resolve(path.join(dir, options.outDir));\n\n return options.directories.map(directory => path.resolve(directory).replace(out, root));\n }\n\n private emitOrThrow<K extends keyof Pick<ModuleLoader.Events, 'moduleResolveError'>>(event: K, error: RecipleError) {\n if (this.client.listenerCount(event) > 0) {\n // @ts-expect-error\n return this.emit(event, error);\n }\n\n throw error;\n }\n}\n\nexport namespace ModuleLoader {\n export let globby: typeof import('globby')|null = null;\n\n export const fileTypes = [\n 'js',\n 'mjs',\n 'jsx'\n ];\n\n export interface Config {\n directories?: string[];\n ignore?: string[];\n filter?: (filepath: string) => Awaitable<boolean>;\n sort?: (a: string, b: string) => number;\n }\n\n export interface Events {\n moduleResolveError: [error: RecipleError];\n moduleResolved: [module: AnyModule];\n moduleResolving: [filepath: string];\n modulesResolved: [modules: AnyModule[]];\n modulesResolving: [files: string[]];\n }\n\n export interface ResolveSourceDirectoryOptions {\n directories: string[];\n baseUrl: string;\n rootDir: string;\n outDir: string;\n cwd?: string;\n }\n\n export async function getGlobby(): Promise<typeof import('globby')> {\n if (globby) return globby;\n\n return globby = await import('globby');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,eAAb,MAAa,qBAAqB,aAAkC;CAChE,AAAgB;CAEhB,YAAY,AAAgB,QAAgB;AACxC,SAAO;EADiB;AAGxB,OAAK,SAAS,KAAK,OAAO,OAAO,MAAM,EACnC,OAAO,gBACV,CAAC;;CAGN,MAAa,YAAY,eAAwB,OAA6B;EAC1E,MAAM,cAAc,MAAM,aAAa,mBAAmB,KAAK,OAAO,QAAQ,QAAQ;EACtF,MAAM,UAAuB,EAAE;AAE/B,OAAK,KAAK,oBAAoB,YAAY;AAE1C,OAAK,MAAM,QAAQ,YACf,KAAI;AACA,QAAK,KAAK,mBAAmB,KAAK;GAClC,MAAM,WAAW,MAAM,aAAa,sBAAsB,KAAK;AAE/D,UAAO,OAAO,UAAU;IAAE,QAAQ,KAAK;IAAQ,aAAa;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CAGhC,aAAoB,yBAAyB,SAAwE;EACjH,MAAM,MAAMA,OAAK,WAAW,QAAQ,QAAQ,GAAG,QAAQ,UAAUA,OAAK,QAAQA,OAAK,KAAK,QAAQ,OAAO,QAAQ,KAAK,EAAE,QAAQ,QAAQ,CAAC;EAEvI,MAAM,OAAOA,OAAK,QAAQA,OAAK,KAAK,KAAK,QAAQ,QAAQ,CAAC;EAC1D,MAAM,MAAMA,OAAK,QAAQA,OAAK,KAAK,KAAK,QAAQ,OAAO,CAAC;AAExD,SAAO,QAAQ,YAAY,KAAI,cAAaA,OAAK,QAAQ,UAAU,CAAC,QAAQ,KAAK,KAAK,CAAC;;CAG3F,AAAQ,YAA6E,OAAU,OAAqB;AAChH,MAAI,KAAK,OAAO,cAAc,MAAM,GAAG,EAEnC,QAAO,KAAK,KAAK,OAAO,MAAM;AAGlC,QAAM;;;;CAKH,IAAI,gCAAuC;2BAEzB;EACrB;EACA;EACA;EACH;CAyBM,eAAe,YAA8C;AAChE,MAAI,OAAQ,QAAO;AAEnB,SAAO,SAAS,MAAM,OAAO"}
|
|
1
|
+
{"version":3,"file":"ModuleLoader.mjs","names":["path","globby"],"sources":["../../../src/classes/client/ModuleLoader.ts"],"sourcesContent":["import { type Awaitable } from 'discord.js';\nimport path from 'node:path';\nimport { mkdir, readdir, stat } from 'node:fs/promises';\nimport micromatch from 'micromatch';\nimport { globby, isDynamicPattern } from 'globby';\nimport { CommandType, RecipleError, type Client } from '@reciple/core';\nimport type { AnyModule, AnyModuleData } from '../../helpers/types.js';\nimport { recursiveDefaults } from '@reciple/utils';\nimport { BaseModule } from '../modules/BaseModule.js';\nimport { BaseModuleValidator } from '../validation/BaseModuleValidator.js';\nimport { ModuleType } from '../../helpers/constants.js';\nimport { PostconditionModule } from '../modules/PostconditionModule.js';\nimport { PreconditionModule } from '../modules/PreconditionModule.js';\nimport { EventModule } from '../modules/events/EventModule.js';\nimport { MessageCommandModule } from '../modules/commands/MessageCommandModule.js';\nimport { SlashCommandModule } from '../modules/commands/SlashCommandModule.js';\nimport { ContextMenuCommandModule } from '../modules/commands/ContextMenuCommandModule.js';\nimport { CommandModuleValidator } from '../validation/CommandModuleValidator.js';\nimport { EventModuleValidator } from '../validation/EventModuleValidator.js';\nimport { PreconditionModuleValidator } from '../validation/PreconditionModule.js';\nimport { PostconditionModuleValidator } from '../validation/PostconditionModule.js';\nimport type { Logger } from '@prtty/print';\nimport { EventEmitter } from 'node:events';\nimport { colors } from '@prtty/prtty';\n\nexport class ModuleLoader extends EventEmitter<ModuleLoader.Events> {\n public readonly logger: Logger;\n\n constructor(public readonly client: Client) {\n super();\n\n this.logger = this.client.logger.clone({\n label: 'ModuleLoader'\n });\n }\n\n public async findModules(ignoreErrors: boolean = false): Promise<AnyModule[]> {\n const modulePaths = await ModuleLoader.scanForModulePaths(this.client.config?.modules);\n const modules: AnyModule[] = [];\n\n this.emit('modulesResolving', modulePaths);\n\n for (const path of modulePaths) {\n try {\n this.emit('moduleResolving', path);\n const resolved = await ModuleLoader.resolveModuleFromPath(path);\n\n Object.assign(resolved, { client: this.client, __$filepath: path });\n modules.push(resolved);\n\n this.emit('moduleResolved', resolved);\n } catch (error) {\n if (ignoreErrors) continue;\n\n this.emitOrThrow('moduleResolveError', new RecipleError({\n message: `Failed to load module: ${colors.cyan(path)}`,\n cause: error\n }));\n }\n }\n\n this.emit('modulesResolved', modules);\n return modules;\n }\n\n public static async scanForDirectories(config?: Pick<ModuleLoader.Config, 'directories'|'ignore'> & { cwd?: string; createDirectories?: boolean; }) {\n const cwd = config?.cwd ?? process.cwd();\n\n let scanned: string[] = [];\n let directories: string[] = [];\n\n for (const directory of config?.directories ?? []) {\n if (isDynamicPattern(directory, { cwd })) {\n const matches = await globby(directory, {\n cwd,\n ignore: config?.ignore,\n onlyDirectories: true,\n baseNameMatch: true,\n absolute: true\n });\n\n scanned.push(...matches);\n continue;\n }\n\n scanned.push(path.join(cwd, directory));\n }\n\n for (const directory of scanned) {\n const stats = await stat(directory).catch(() => undefined);\n\n if (!stats && config?.createDirectories !== false) {\n await mkdir(directory, { recursive: true });\n }\n\n directories.push(directory);\n }\n\n return directories;\n }\n\n public static async scanForModulePaths(config?: ModuleLoader.Config & { cwd?: string; createDirectories?: boolean; }): Promise<string[]> {\n const directories = await ModuleLoader.scanForDirectories(config);\n\n let modules: string[] = [];\n\n for (const directory of directories) {\n let files = await readdir(directory);\n\n if (config?.ignore?.length) {\n files = micromatch.not(files, config.ignore, {\n cwd: directory,\n matchBase: true,\n dot: true\n });\n }\n\n files = files.map(f => path.join(directory, f));\n\n for (const file of files) {\n if (config?.filter ? !(await config?.filter(file)) : ModuleLoader.fileTypes.every(type => !file.endsWith(`.${type}`))) continue;\n modules.push(file);\n }\n }\n\n if (config?.sort) modules.sort(config.sort);\n\n return modules;\n }\n\n public static async resolveModuleFromPath(filepath: string, options?: { cwd?: string; }): Promise<AnyModule> {\n const stats = await stat(filepath).catch(() => undefined);\n if (!stats) throw new RecipleError(`Module not found: ${filepath}`);\n\n const data = recursiveDefaults<AnyModule|AnyModuleData|undefined>(await import(`file://${path.resolve(options?.cwd ?? process.cwd(), filepath)}`));\n if (BaseModule.isModule(data)) return data;\n\n if (data && 'moduleType' in data) {\n switch (data?.moduleType) {\n case ModuleType.Command:\n CommandModuleValidator.isValid(data);\n switch (data.type) {\n case CommandType.Message: return MessageCommandModule.from(data);\n case CommandType.Slash: return SlashCommandModule.from(data);\n case CommandType.ContextMenu: return ContextMenuCommandModule.from(data);\n default: throw new RecipleError(`Unknown command type from module: ${colors.cyan(filepath)}`);\n }\n case ModuleType.Event:\n EventModuleValidator.isValid(data);\n return EventModule.from(data);\n case ModuleType.Precondition:\n PreconditionModuleValidator.isValid(data);\n return PreconditionModule.from(data);\n case ModuleType.Postcondition:\n PostconditionModuleValidator.isValid(data);\n return PostconditionModule.from(data);\n default:\n BaseModuleValidator.isValid(data);\n return BaseModule.from(data);\n }\n }\n\n BaseModuleValidator.isValid(data);\n return BaseModule.from(data);\n }\n\n public static async resolveSourceDirectories(options: ModuleLoader.ResolveSourceDirectoryOptions): Promise<string[]> {\n const dir = path.isAbsolute(options.baseUrl) ? options.baseUrl : path.resolve(path.join(options.cwd ?? process.cwd(), options.baseUrl));\n\n const root = path.resolve(path.join(dir, options.rootDir));\n const out = path.resolve(path.join(dir, options.outDir));\n\n return options.directories.map(directory => path.resolve(directory).replace(out, root));\n }\n\n private emitOrThrow<K extends keyof Pick<ModuleLoader.Events, 'moduleResolveError'>>(event: K, error: RecipleError) {\n if (this.client.listenerCount(event) > 0) {\n // @ts-expect-error\n return this.emit(event, error);\n }\n\n throw error;\n }\n}\n\nexport namespace ModuleLoader {\n export let globby: typeof import('globby')|null = null;\n\n export const fileTypes = [\n 'js',\n 'mjs',\n 'jsx'\n ];\n\n export interface Config {\n directories?: string[];\n ignore?: string[];\n filter?: (filepath: string) => Awaitable<boolean>;\n sort?: (a: string, b: string) => number;\n }\n\n export interface Events {\n moduleResolveError: [error: RecipleError];\n moduleResolved: [module: AnyModule];\n moduleResolving: [filepath: string];\n modulesResolved: [modules: AnyModule[]];\n modulesResolving: [files: string[]];\n }\n\n export interface ResolveSourceDirectoryOptions {\n directories: string[];\n baseUrl: string;\n rootDir: string;\n outDir: string;\n cwd?: string;\n }\n\n export async function getGlobby(): Promise<typeof import('globby')> {\n if (globby) return globby;\n\n return globby = await import('globby');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,eAAb,MAAa,qBAAqB,aAAkC;CAChE,AAAgB;CAEhB,YAAY,AAAgB,QAAgB;AACxC,SAAO;EADiB;AAGxB,OAAK,SAAS,KAAK,OAAO,OAAO,MAAM,EACnC,OAAO,gBACV,CAAC;;CAGN,MAAa,YAAY,eAAwB,OAA6B;EAC1E,MAAM,cAAc,MAAM,aAAa,mBAAmB,KAAK,OAAO,QAAQ,QAAQ;EACtF,MAAM,UAAuB,EAAE;AAE/B,OAAK,KAAK,oBAAoB,YAAY;AAE1C,OAAK,MAAMA,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,WAAO,oBAAoB,KAAK,KAAK;GACzC;AACI,wBAAoB,QAAQ,KAAK;AACjC,WAAO,WAAW,KAAK,KAAK;;AAIxC,sBAAoB,QAAQ,KAAK;AACjC,SAAO,WAAW,KAAK,KAAK;;CAGhC,aAAoB,yBAAyB,SAAwE;EACjH,MAAM,MAAM,KAAK,WAAW,QAAQ,QAAQ,GAAG,QAAQ,UAAU,KAAK,QAAQ,KAAK,KAAK,QAAQ,OAAO,QAAQ,KAAK,EAAE,QAAQ,QAAQ,CAAC;EAEvI,MAAM,OAAO,KAAK,QAAQ,KAAK,KAAK,KAAK,QAAQ,QAAQ,CAAC;EAC1D,MAAM,MAAM,KAAK,QAAQ,KAAK,KAAK,KAAK,QAAQ,OAAO,CAAC;AAExD,SAAO,QAAQ,YAAY,KAAI,cAAa,KAAK,QAAQ,UAAU,CAAC,QAAQ,KAAK,KAAK,CAAC;;CAG3F,AAAQ,YAA6E,OAAU,OAAqB;AAChH,MAAI,KAAK,OAAO,cAAc,MAAM,GAAG,EAEnC,QAAO,KAAK,KAAK,OAAO,MAAM;AAGlC,QAAM;;;;CAKH,IAAIC,kCAAuC;2BAEzB;EACrB;EACA;EACA;EACH;CAyBM,eAAe,YAA8C;AAChE,MAAIA,SAAQ,QAAOA;AAEnB,SAAO,WAAS,MAAM,OAAO"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BaseModule } from "../modules/BaseModule.mjs";
|
|
2
2
|
import { ModuleType } from "../../helpers/constants.mjs";
|
|
3
|
-
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.
|
|
3
|
+
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.mjs";
|
|
4
4
|
import { BaseManager, RecipleError } from "@reciple/core";
|
|
5
5
|
import { mix } from "ts-mixer";
|
|
6
6
|
import { EventEmitter } from "node:events";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BaseModule } from "./BaseModule.mjs";
|
|
2
2
|
import { ModuleType } from "../../helpers/constants.mjs";
|
|
3
|
-
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.
|
|
3
|
+
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.mjs";
|
|
4
4
|
import { CommandPostcondition } from "@reciple/core";
|
|
5
5
|
import { hasMixin, mix } from "ts-mixer";
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BaseModule } from "./BaseModule.mjs";
|
|
2
2
|
import { ModuleType } from "../../helpers/constants.mjs";
|
|
3
|
-
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.
|
|
3
|
+
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.mjs";
|
|
4
4
|
import { CommandPrecondition } from "@reciple/core";
|
|
5
5
|
import { hasMixin, mix } from "ts-mixer";
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BaseModule } from "../BaseModule.mjs";
|
|
2
2
|
import { ModuleType } from "../../../helpers/constants.mjs";
|
|
3
|
-
import { __decorate } from "../../../_virtual/_@oxc-project_runtime@0.
|
|
3
|
+
import { __decorate } from "../../../_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.mjs";
|
|
4
4
|
import { ContextMenuCommand } from "@reciple/core";
|
|
5
5
|
import { DiscordSnowflake } from "@sapphire/snowflake";
|
|
6
6
|
import { hasMixin, mix } from "ts-mixer";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BaseModule } from "../BaseModule.mjs";
|
|
2
2
|
import { ModuleType } from "../../../helpers/constants.mjs";
|
|
3
|
-
import { __decorate } from "../../../_virtual/_@oxc-project_runtime@0.
|
|
3
|
+
import { __decorate } from "../../../_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.mjs";
|
|
4
4
|
import { MessageCommand, MessageCommandBuilder } from "@reciple/core";
|
|
5
5
|
import { DiscordSnowflake } from "@sapphire/snowflake";
|
|
6
6
|
import { hasMixin, mix } from "ts-mixer";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BaseModule } from "../BaseModule.mjs";
|
|
2
2
|
import { ModuleType } from "../../../helpers/constants.mjs";
|
|
3
|
-
import { __decorate } from "../../../_virtual/_@oxc-project_runtime@0.
|
|
3
|
+
import { __decorate } from "../../../_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.mjs";
|
|
4
4
|
import { SlashCommand } from "@reciple/core";
|
|
5
5
|
import { DiscordSnowflake } from "@sapphire/snowflake";
|
|
6
6
|
import { hasMixin, mix } from "ts-mixer";
|
|
@@ -71,11 +71,11 @@ var ModuleTemplateBuilder = class ModuleTemplateBuilder {
|
|
|
71
71
|
if (!template) {
|
|
72
72
|
const templateName = typeof options?.template === "string" ? options.template : void 0;
|
|
73
73
|
const templates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? "ts" : "js");
|
|
74
|
-
const selectedTemplate = this.defaultAll ? templateName ? templates.find((template) => template.name === templateName) : templates.at(0) : await select({
|
|
74
|
+
const selectedTemplate = this.defaultAll ? templateName ? templates.find((template$1) => template$1.name === templateName) : templates.at(0) : await select({
|
|
75
75
|
message: "Select a module template",
|
|
76
|
-
options: templates.map((template) => ({
|
|
77
|
-
label: template.name,
|
|
78
|
-
value: template
|
|
76
|
+
options: templates.map((template$1) => ({
|
|
77
|
+
label: template$1.name,
|
|
78
|
+
value: template$1
|
|
79
79
|
}))
|
|
80
80
|
});
|
|
81
81
|
if (isCancel(selectedTemplate)) throw new NotAnError("Operation cancelled");
|
|
@@ -102,9 +102,9 @@ var ModuleTemplateBuilder = class ModuleTemplateBuilder {
|
|
|
102
102
|
initialValue: defaultValue,
|
|
103
103
|
placeholder: defaultValue,
|
|
104
104
|
defaultValue,
|
|
105
|
-
validate: (value) => {
|
|
106
|
-
if (!value) return "Please enter a value";
|
|
107
|
-
if (value.includes(" ")) return "Please enter a value without spaces";
|
|
105
|
+
validate: (value$1) => {
|
|
106
|
+
if (!value$1) return "Please enter a value";
|
|
107
|
+
if (value$1.includes(" ")) return "Please enter a value without spaces";
|
|
108
108
|
}
|
|
109
109
|
});
|
|
110
110
|
break;
|
|
@@ -162,9 +162,9 @@ var ModuleTemplateBuilder = class ModuleTemplateBuilder {
|
|
|
162
162
|
});
|
|
163
163
|
const selectedDirectory = this.defaultAll ? directories.at(0) : await select({
|
|
164
164
|
message: "Select a directory",
|
|
165
|
-
options: directories.map((directory) => ({
|
|
166
|
-
label: path.relative(cwd, directory),
|
|
167
|
-
value: directory
|
|
165
|
+
options: directories.map((directory$1) => ({
|
|
166
|
+
label: path.relative(cwd, directory$1),
|
|
167
|
+
value: directory$1
|
|
168
168
|
}))
|
|
169
169
|
});
|
|
170
170
|
if (isCancel(selectedDirectory)) throw new NotAnError("Operation cancelled");
|
|
@@ -203,15 +203,15 @@ var ModuleTemplateBuilder = class ModuleTemplateBuilder {
|
|
|
203
203
|
}
|
|
204
204
|
};
|
|
205
205
|
(function(_ModuleTemplateBuilder) {
|
|
206
|
-
let Placeholder = /* @__PURE__ */ function(Placeholder) {
|
|
207
|
-
Placeholder["ModuleName"] = "$MODULE_NAME$";
|
|
208
|
-
Placeholder["CommandName"] = "$COMMAND_NAME$";
|
|
209
|
-
Placeholder["CommandDescription"] = "$COMMAND_DESCRIPTION$";
|
|
210
|
-
Placeholder["CommandContextMenuType"] = "$COMMAND_CONTEXT_MENU_TYPE$";
|
|
211
|
-
Placeholder["EventEmitter"] = "$EVENT_EMITTER$";
|
|
212
|
-
Placeholder["EventName"] = "$EVENT_NAME$";
|
|
213
|
-
Placeholder["EventOnce"] = "$EVENT_ONCE$";
|
|
214
|
-
return Placeholder;
|
|
206
|
+
let Placeholder = /* @__PURE__ */ function(Placeholder$1) {
|
|
207
|
+
Placeholder$1["ModuleName"] = "$MODULE_NAME$";
|
|
208
|
+
Placeholder$1["CommandName"] = "$COMMAND_NAME$";
|
|
209
|
+
Placeholder$1["CommandDescription"] = "$COMMAND_DESCRIPTION$";
|
|
210
|
+
Placeholder$1["CommandContextMenuType"] = "$COMMAND_CONTEXT_MENU_TYPE$";
|
|
211
|
+
Placeholder$1["EventEmitter"] = "$EVENT_EMITTER$";
|
|
212
|
+
Placeholder$1["EventName"] = "$EVENT_NAME$";
|
|
213
|
+
Placeholder$1["EventOnce"] = "$EVENT_ONCE$";
|
|
214
|
+
return Placeholder$1;
|
|
215
215
|
}({});
|
|
216
216
|
_ModuleTemplateBuilder.Placeholder = Placeholder;
|
|
217
217
|
_ModuleTemplateBuilder.PlaceholderDefaultValues = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModuleTemplateBuilder.mjs","names":[],"sources":["../../../src/classes/templates/ModuleTemplateBuilder.ts"],"sourcesContent":["import path from 'node:path';\nimport { CLI } from '../cli/CLI.js';\nimport { ModuleType } from '../../helpers/constants.js';\nimport { BaseModule } from '../modules/BaseModule.js';\nimport { MessageCommandModule } from '../modules/commands/MessageCommandModule.js';\nimport { SlashCommandModule } from '../modules/commands/SlashCommandModule.js';\nimport { ContextMenuCommandModule } from '../modules/commands/ContextMenuCommandModule.js';\nimport { ClientEventModule } from '../modules/events/ClientEventModule.js';\nimport { EventModule } from '../modules/events/EventModule.js';\nimport { RESTEventModule } from '../modules/events/RESTEventModule.js';\nimport { PostconditionModule } from '../modules/PostconditionModule.js';\nimport { PreconditionModule } from '../modules/PreconditionModule.js';\nimport { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';\nimport { ConfigReader } from '../cli/ConfigReader.js';\nimport { confirm, intro, isCancel, outro, select, text } from '@clack/prompts';\nimport { NotAnError } from '../NotAnError.js';\nimport { ApplicationCommandType } from 'discord.js';\nimport { ModuleLoader } from '../client/ModuleLoader.js';\nimport { existsSync } from 'node:fs';\nimport { readTSConfig } from 'pkg-types';\nimport { colors } from '@prtty/prtty';\n\nexport class ModuleTemplateBuilder {\n public _directory?: string;\n\n public readonly cli: CLI;\n public readonly config: ConfigReader;\n\n public template?: ModuleTemplateBuilder.Data;\n public typescript?: boolean;\n public filename?: string;\n public defaultAll: boolean;\n\n get content() {\n return this.template?.content ?? '';\n }\n\n get directory() {\n return this._directory ?? process.cwd();\n }\n\n get filepath() {\n return path.join(this.directory, this.filename ?? '');\n }\n\n constructor(options: ModuleTemplateBuilder.Options) {\n this.cli = options.cli;\n this.config = options.config;\n this.template = options?.template;\n this.typescript = options?.typescript;\n this._directory = options?.directory;\n this.filename = options?.filename;\n this.defaultAll = options?.defaultAll ?? false;\n }\n\n public async init(): Promise<this> {\n intro(colors.bold().black().bgCyan(` ${this.cli.command.name()} create module - v${this.cli.build} `));\n return this;\n }\n\n public async setupLanguage(options?: ModuleTemplateBuilder.SetupLanguageOptions): Promise<this> {\n this.typescript = options?.typescript ?? this.typescript;\n\n if (!this.typescript) {\n const isTypeScriptDefault = (await ConfigReader.getProjectLang(this.directory)) === 'ts';\n const isTypeScript = this.defaultAll\n ? isTypeScriptDefault\n : await confirm({\n message: 'Would you like to use TypeScript?',\n active: 'Yes',\n inactive: 'No',\n initialValue: isTypeScriptDefault\n });\n\n if (isCancel(isTypeScript)) throw new NotAnError('Operation cancelled');\n this.typescript = isTypeScript;\n }\n\n return this;\n }\n\n public async setupTemplate(options?: ModuleTemplateBuilder.SetupTemplateOptions): Promise<this> {\n let template = typeof options?.template === 'object' ? options.template : undefined;\n\n if (!template) {\n const templateName = typeof options?.template === 'string' ? options.template : undefined;\n const templates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? 'ts' : 'js');\n\n const selectedTemplate = this.defaultAll\n ? templateName ? templates.find(template => template.name === templateName) : templates.at(0)\n : await select({\n message: 'Select a module template',\n options: templates.map(template => ({\n label: template.name,\n value: template\n }))\n });\n\n if (isCancel(selectedTemplate)) throw new NotAnError('Operation cancelled');\n template = selectedTemplate;\n }\n\n this.template = template;\n if (!this.template) throw new NotAnError('No template selected');\n\n return this;\n }\n\n public async setupPlaceholders(): Promise<this> {\n const placeholders = Object.keys(ModuleTemplateBuilder.Placeholder).filter(k => !k.startsWith('$')) as (keyof typeof ModuleTemplateBuilder.Placeholder)[];\n\n for (const placeholderKey of placeholders) {\n if (!ModuleTemplateBuilder.hasPlaceholder(ModuleTemplateBuilder.Placeholder[placeholderKey], this.content)) continue;\n const placeholder = ModuleTemplateBuilder.Placeholder[placeholderKey];\n const defaultValue = ModuleTemplateBuilder.PlaceholderDefaultValues[placeholder];\n\n let value: string|symbol;\n\n if (this.defaultAll) {\n value = defaultValue;\n } else {\n switch (placeholder) {\n case ModuleTemplateBuilder.Placeholder.ModuleName:\n case ModuleTemplateBuilder.Placeholder.CommandName:\n case ModuleTemplateBuilder.Placeholder.EventName:\n value = this.defaultAll\n ? defaultValue\n : await text({\n message: `What would you like to name the ${placeholderKey.replace('Name', '').toLowerCase()}?`,\n initialValue: defaultValue,\n placeholder: defaultValue,\n defaultValue,\n validate: (value) => {\n if (!value) return 'Please enter a value';\n if (value.includes(' ')) return 'Please enter a value without spaces';\n }\n });\n break;\n case ModuleTemplateBuilder.Placeholder.CommandContextMenuType:\n const type = await select({\n message: 'Select a command context menu type',\n options: [\n { label: 'Message', value: ApplicationCommandType.Message },\n { label: 'User', value: ApplicationCommandType.User }\n ],\n initialValue: ApplicationCommandType.Message\n });\n\n value = isCancel(type) ? type : `${type}`;\n break;\n case ModuleTemplateBuilder.Placeholder.EventOnce:\n const once = await confirm({\n message: `Would you like to use the event once?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n value = isCancel(once) ? once : `${once}`;\n break;\n case ModuleTemplateBuilder.Placeholder.EventEmitter:\n default:\n value = await text({\n message: `What would you like to use for the ${ModuleTemplateBuilder.toTextCase(placeholder)}?`,\n initialValue: defaultValue,\n placeholder: defaultValue,\n defaultValue\n });\n break;\n }\n }\n\n if (isCancel(value)) throw new NotAnError('Operation cancelled');\n if (!this.template) throw new NotAnError('No template selected');\n this.template.content = ModuleTemplateBuilder.removeExpectedErrorComments(this.content.replaceAll(placeholder, value));\n }\n\n return this;\n }\n\n public async setupDirectory(options?: ModuleTemplateBuilder.SetupDirectoryOptions): Promise<this> {\n let directory = options?.directory;\n\n if (!directory) {\n const cwd = process.cwd();\n const tsconfig = this.config.build.tsconfig\n ? await readTSConfig(typeof this.config.build.tsconfig == 'string' ? this.config.build.tsconfig : cwd, { try: true })\n : undefined;\n\n let directories = await ModuleLoader.scanForDirectories(this.config.config.modules);\n directories = await ModuleLoader.resolveSourceDirectories({\n directories,\n baseUrl: tsconfig?.compilerOptions?.baseUrl ?? '.',\n rootDir: tsconfig?.compilerOptions?.rootDir ?? 'src',\n outDir: tsconfig?.compilerOptions?.outDir ?? 'modules',\n cwd\n });\n\n const selectedDirectory = this.defaultAll\n ? directories.at(0)\n : await select({\n message: 'Select a directory',\n options: directories.map(directory => ({\n label: path.relative(cwd, directory),\n value: directory\n }))\n });\n\n if (isCancel(selectedDirectory)) throw new NotAnError('Operation cancelled');\n directory = selectedDirectory;\n }\n\n if (!directory) throw new NotAnError('No directory selected');\n this._directory = directory;\n\n return this;\n }\n\n public async setupFilename(options?: ModuleTemplateBuilder.SetupFilenameOptions): Promise<this> {\n let filename = options?.filename;\n\n if (!filename) {\n const defaultFilename = `${this.template?.name}.${this.typescript ? 'ts' : 'js'}`;\n const selectedFilename = this.defaultAll\n ? defaultFilename\n : await text({\n message: 'What would you like to name the module file?',\n initialValue: defaultFilename,\n placeholder: defaultFilename,\n defaultValue: defaultFilename,\n validate: (value) => {\n if (!value) return 'Please enter a value';\n if (existsSync(path.join(this.directory, value))) return 'File already exists';\n }\n });\n\n if (isCancel(selectedFilename)) throw new NotAnError('Operation cancelled');\n filename = selectedFilename;\n }\n\n if (!filename) throw new NotAnError('No filename selected');\n this.filename = filename;\n\n return this;\n }\n\n public async build({ overwrite, silent }: ModuleTemplateBuilder.BuildOptions = {}): Promise<this> {\n await mkdir(this.directory, { recursive: true });\n await writeFile(this.filepath, this.content, { flag: overwrite === false ? 'wx' : undefined });\n if (!silent) outro(`Module ${colors.green(this.template?.name!)} created in ${colors.cyan(path.relative(process.cwd(), this.filepath))}`);\n return this;\n }\n}\n\nexport namespace ModuleTemplateBuilder {\n export interface Options {\n cli: CLI;\n config: ConfigReader;\n template?: ModuleTemplateBuilder.Data;\n typescript?: boolean;\n directory?: string;\n filename?: string;\n defaultAll?: boolean;\n }\n\n export interface SetupLanguageOptions {\n typescript?: boolean;\n }\n\n export interface SetupTemplateOptions {\n template?: ModuleTemplateBuilder.Data|string;\n }\n\n export interface SetupDirectoryOptions {\n directory?: string;\n }\n\n export interface SetupFilenameOptions {\n filename?: string;\n }\n\n export interface BuildOptions {\n overwrite?: boolean;\n silent?: boolean;\n }\n\n export enum Placeholder {\n ModuleName = '$MODULE_NAME$',\n CommandName = '$COMMAND_NAME$',\n CommandDescription = '$COMMAND_DESCRIPTION$',\n CommandContextMenuType = '$COMMAND_CONTEXT_MENU_TYPE$',\n EventEmitter = '$EVENT_EMITTER$',\n EventName = '$EVENT_NAME$',\n EventOnce = '$EVENT_ONCE$'\n }\n\n export const PlaceholderDefaultValues: Record<Placeholder, string> = {\n [Placeholder.ModuleName]: 'MyModule',\n [Placeholder.CommandName]: 'my-command',\n [Placeholder.CommandDescription]: 'My command',\n [Placeholder.CommandContextMenuType]: `${ApplicationCommandType.Message}`,\n [Placeholder.EventEmitter]: 'null',\n [Placeholder.EventName]: 'my-event',\n [Placeholder.EventOnce]: 'false'\n }\n\n export const SourceDirectory = {\n js: path.join(CLI.root, './assets/modules/javascript'),\n ts: path.join(CLI.root, './assets/modules/typescript')\n };\n\n export const ModuleTypeClassName: Record<ModuleType, string[]> = {\n [ModuleType.Base]: [BaseModule.name],\n [ModuleType.Command]: [MessageCommandModule.name, SlashCommandModule.name, ContextMenuCommandModule.name],\n [ModuleType.Event]: [ClientEventModule.name, EventModule.name, RESTEventModule.name],\n [ModuleType.Postcondition]: [PostconditionModule.name],\n [ModuleType.Precondition]: [PreconditionModule.name]\n };\n\n export interface Data {\n src: string;\n name: string;\n content: string;\n moduleType: ModuleType|null;\n }\n\n export async function resolveModuleTemplates(source: keyof typeof SourceDirectory): Promise<ModuleTemplateBuilder.Data[]> {\n const src = ModuleTemplateBuilder.SourceDirectory[source];\n const files: string[] = await readdir(src);\n const templates: ModuleTemplateBuilder.Data[] = [];\n\n for (const file of files) {\n const filepath = path.join(src, file);\n const content = await readFile(filepath, 'utf-8');\n const moduleType = ModuleTemplateBuilder.getModuleTemplateContentType(content);\n\n templates.push({ src: filepath, name: path.parse(filepath).name, content, moduleType });\n }\n\n return templates;\n }\n\n export function getModuleTemplateContentType(content: string): ModuleType|null {\n const createExtendStatement = (name: string) => `export class ${Placeholder.ModuleName} extends ${name}`;\n\n for (const type of Object.keys(ModuleTypeClassName).map(Number) as ModuleType[]) {\n const statements = ModuleTypeClassName[type].map(createExtendStatement);\n\n for (const statement of statements) {\n if (content.includes(statement)) return type;\n }\n }\n\n return null;\n }\n\n export function hasPlaceholder(placeholder: Placeholder, content: string): boolean {\n return content.includes(placeholder);\n }\n\n export function removeExpectedErrorComments(content: string): string {\n const lines = content.split('\\n');\n\n return lines\n .filter(line => !line.trim().includes('// @ts-expect-error'))\n .join('\\n');\n }\n\n export function toTextCase(string: string): string {\n return String(string)\n .replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g, '')\n .replace(/([a-z])([A-Z])/g, (m, a, b) => a + '_' + b.toLowerCase())\n .replace(/[^A-Za-z0-9]+|_+/g, ' ')\n .toLowerCase();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,wBAAb,MAAa,sBAAsB;CAC/B,AAAO;CAEP,AAAgB;CAChB,AAAgB;CAEhB,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,IAAI,UAAU;AACV,SAAO,KAAK,UAAU,WAAW;;CAGrC,IAAI,YAAY;AACZ,SAAO,KAAK,cAAc,QAAQ,KAAK;;CAG3C,IAAI,WAAW;AACX,SAAO,KAAK,KAAK,KAAK,WAAW,KAAK,YAAY,GAAG;;CAGzD,YAAY,SAAwC;AAChD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der.mjs","names":["template","value","directory"],"sources":["../../../src/classes/templates/ModuleTemplateBuilder.ts"],"sourcesContent":["import path from 'node:path';\nimport { CLI } from '../cli/CLI.js';\nimport { ModuleType } from '../../helpers/constants.js';\nimport { BaseModule } from '../modules/BaseModule.js';\nimport { MessageCommandModule } from '../modules/commands/MessageCommandModule.js';\nimport { SlashCommandModule } from '../modules/commands/SlashCommandModule.js';\nimport { ContextMenuCommandModule } from '../modules/commands/ContextMenuCommandModule.js';\nimport { ClientEventModule } from '../modules/events/ClientEventModule.js';\nimport { EventModule } from '../modules/events/EventModule.js';\nimport { RESTEventModule } from '../modules/events/RESTEventModule.js';\nimport { PostconditionModule } from '../modules/PostconditionModule.js';\nimport { PreconditionModule } from '../modules/PreconditionModule.js';\nimport { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';\nimport { ConfigReader } from '../cli/ConfigReader.js';\nimport { confirm, intro, isCancel, outro, select, text } from '@clack/prompts';\nimport { NotAnError } from '../NotAnError.js';\nimport { ApplicationCommandType } from 'discord.js';\nimport { ModuleLoader } from '../client/ModuleLoader.js';\nimport { existsSync } from 'node:fs';\nimport { readTSConfig } from 'pkg-types';\nimport { colors } from '@prtty/prtty';\n\nexport class ModuleTemplateBuilder {\n public _directory?: string;\n\n public readonly cli: CLI;\n public readonly config: ConfigReader;\n\n public template?: ModuleTemplateBuilder.Data;\n public typescript?: boolean;\n public filename?: string;\n public defaultAll: boolean;\n\n get content() {\n return this.template?.content ?? '';\n }\n\n get directory() {\n return this._directory ?? process.cwd();\n }\n\n get filepath() {\n return path.join(this.directory, this.filename ?? '');\n }\n\n constructor(options: ModuleTemplateBuilder.Options) {\n this.cli = options.cli;\n this.config = options.config;\n this.template = options?.template;\n this.typescript = options?.typescript;\n this._directory = options?.directory;\n this.filename = options?.filename;\n this.defaultAll = options?.defaultAll ?? false;\n }\n\n public async init(): Promise<this> {\n intro(colors.bold().black().bgCyan(` ${this.cli.command.name()} create module - v${this.cli.build} `));\n return this;\n }\n\n public async setupLanguage(options?: ModuleTemplateBuilder.SetupLanguageOptions): Promise<this> {\n this.typescript = options?.typescript ?? this.typescript;\n\n if (!this.typescript) {\n const isTypeScriptDefault = (await ConfigReader.getProjectLang(this.directory)) === 'ts';\n const isTypeScript = this.defaultAll\n ? isTypeScriptDefault\n : await confirm({\n message: 'Would you like to use TypeScript?',\n active: 'Yes',\n inactive: 'No',\n initialValue: isTypeScriptDefault\n });\n\n if (isCancel(isTypeScript)) throw new NotAnError('Operation cancelled');\n this.typescript = isTypeScript;\n }\n\n return this;\n }\n\n public async setupTemplate(options?: ModuleTemplateBuilder.SetupTemplateOptions): Promise<this> {\n let template = typeof options?.template === 'object' ? options.template : undefined;\n\n if (!template) {\n const templateName = typeof options?.template === 'string' ? options.template : undefined;\n const templates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? 'ts' : 'js');\n\n const selectedTemplate = this.defaultAll\n ? templateName ? templates.find(template => template.name === templateName) : templates.at(0)\n : await select({\n message: 'Select a module template',\n options: templates.map(template => ({\n label: template.name,\n value: template\n }))\n });\n\n if (isCancel(selectedTemplate)) throw new NotAnError('Operation cancelled');\n template = selectedTemplate;\n }\n\n this.template = template;\n if (!this.template) throw new NotAnError('No template selected');\n\n return this;\n }\n\n public async setupPlaceholders(): Promise<this> {\n const placeholders = Object.keys(ModuleTemplateBuilder.Placeholder).filter(k => !k.startsWith('$')) as (keyof typeof ModuleTemplateBuilder.Placeholder)[];\n\n for (const placeholderKey of placeholders) {\n if (!ModuleTemplateBuilder.hasPlaceholder(ModuleTemplateBuilder.Placeholder[placeholderKey], this.content)) continue;\n const placeholder = ModuleTemplateBuilder.Placeholder[placeholderKey];\n const defaultValue = ModuleTemplateBuilder.PlaceholderDefaultValues[placeholder];\n\n let value: string|symbol;\n\n if (this.defaultAll) {\n value = defaultValue;\n } else {\n switch (placeholder) {\n case ModuleTemplateBuilder.Placeholder.ModuleName:\n case ModuleTemplateBuilder.Placeholder.CommandName:\n case ModuleTemplateBuilder.Placeholder.EventName:\n value = this.defaultAll\n ? defaultValue\n : await text({\n message: `What would you like to name the ${placeholderKey.replace('Name', '').toLowerCase()}?`,\n initialValue: defaultValue,\n placeholder: defaultValue,\n defaultValue,\n validate: (value) => {\n if (!value) return 'Please enter a value';\n if (value.includes(' ')) return 'Please enter a value without spaces';\n }\n });\n break;\n case ModuleTemplateBuilder.Placeholder.CommandContextMenuType:\n const type = await select({\n message: 'Select a command context menu type',\n options: [\n { label: 'Message', value: ApplicationCommandType.Message },\n { label: 'User', value: ApplicationCommandType.User }\n ],\n initialValue: ApplicationCommandType.Message\n });\n\n value = isCancel(type) ? type : `${type}`;\n break;\n case ModuleTemplateBuilder.Placeholder.EventOnce:\n const once = await confirm({\n message: `Would you like to use the event once?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n value = isCancel(once) ? once : `${once}`;\n break;\n case ModuleTemplateBuilder.Placeholder.EventEmitter:\n default:\n value = await text({\n message: `What would you like to use for the ${ModuleTemplateBuilder.toTextCase(placeholder)}?`,\n initialValue: defaultValue,\n placeholder: defaultValue,\n defaultValue\n });\n break;\n }\n }\n\n if (isCancel(value)) throw new NotAnError('Operation cancelled');\n if (!this.template) throw new NotAnError('No template selected');\n this.template.content = ModuleTemplateBuilder.removeExpectedErrorComments(this.content.replaceAll(placeholder, value));\n }\n\n return this;\n }\n\n public async setupDirectory(options?: ModuleTemplateBuilder.SetupDirectoryOptions): Promise<this> {\n let directory = options?.directory;\n\n if (!directory) {\n const cwd = process.cwd();\n const tsconfig = this.config.build.tsconfig\n ? await readTSConfig(typeof this.config.build.tsconfig == 'string' ? this.config.build.tsconfig : cwd, { try: true })\n : undefined;\n\n let directories = await ModuleLoader.scanForDirectories(this.config.config.modules);\n directories = await ModuleLoader.resolveSourceDirectories({\n directories,\n baseUrl: tsconfig?.compilerOptions?.baseUrl ?? '.',\n rootDir: tsconfig?.compilerOptions?.rootDir ?? 'src',\n outDir: tsconfig?.compilerOptions?.outDir ?? 'modules',\n cwd\n });\n\n const selectedDirectory = this.defaultAll\n ? directories.at(0)\n : await select({\n message: 'Select a directory',\n options: directories.map(directory => ({\n label: path.relative(cwd, directory),\n value: directory\n }))\n });\n\n if (isCancel(selectedDirectory)) throw new NotAnError('Operation cancelled');\n directory = selectedDirectory;\n }\n\n if (!directory) throw new NotAnError('No directory selected');\n this._directory = directory;\n\n return this;\n }\n\n public async setupFilename(options?: ModuleTemplateBuilder.SetupFilenameOptions): Promise<this> {\n let filename = options?.filename;\n\n if (!filename) {\n const defaultFilename = `${this.template?.name}.${this.typescript ? 'ts' : 'js'}`;\n const selectedFilename = this.defaultAll\n ? defaultFilename\n : await text({\n message: 'What would you like to name the module file?',\n initialValue: defaultFilename,\n placeholder: defaultFilename,\n defaultValue: defaultFilename,\n validate: (value) => {\n if (!value) return 'Please enter a value';\n if (existsSync(path.join(this.directory, value))) return 'File already exists';\n }\n });\n\n if (isCancel(selectedFilename)) throw new NotAnError('Operation cancelled');\n filename = selectedFilename;\n }\n\n if (!filename) throw new NotAnError('No filename selected');\n this.filename = filename;\n\n return this;\n }\n\n public async build({ overwrite, silent }: ModuleTemplateBuilder.BuildOptions = {}): Promise<this> {\n await mkdir(this.directory, { recursive: true });\n await writeFile(this.filepath, this.content, { flag: overwrite === false ? 'wx' : undefined });\n if (!silent) outro(`Module ${colors.green(this.template?.name!)} created in ${colors.cyan(path.relative(process.cwd(), this.filepath))}`);\n return this;\n }\n}\n\nexport namespace ModuleTemplateBuilder {\n export interface Options {\n cli: CLI;\n config: ConfigReader;\n template?: ModuleTemplateBuilder.Data;\n typescript?: boolean;\n directory?: string;\n filename?: string;\n defaultAll?: boolean;\n }\n\n export interface SetupLanguageOptions {\n typescript?: boolean;\n }\n\n export interface SetupTemplateOptions {\n template?: ModuleTemplateBuilder.Data|string;\n }\n\n export interface SetupDirectoryOptions {\n directory?: string;\n }\n\n export interface SetupFilenameOptions {\n filename?: string;\n }\n\n export interface BuildOptions {\n overwrite?: boolean;\n silent?: boolean;\n }\n\n export enum Placeholder {\n ModuleName = '$MODULE_NAME$',\n CommandName = '$COMMAND_NAME$',\n CommandDescription = '$COMMAND_DESCRIPTION$',\n CommandContextMenuType = '$COMMAND_CONTEXT_MENU_TYPE$',\n EventEmitter = '$EVENT_EMITTER$',\n EventName = '$EVENT_NAME$',\n EventOnce = '$EVENT_ONCE$'\n }\n\n export const PlaceholderDefaultValues: Record<Placeholder, string> = {\n [Placeholder.ModuleName]: 'MyModule',\n [Placeholder.CommandName]: 'my-command',\n [Placeholder.CommandDescription]: 'My command',\n [Placeholder.CommandContextMenuType]: `${ApplicationCommandType.Message}`,\n [Placeholder.EventEmitter]: 'null',\n [Placeholder.EventName]: 'my-event',\n [Placeholder.EventOnce]: 'false'\n }\n\n export const SourceDirectory = {\n js: path.join(CLI.root, './assets/modules/javascript'),\n ts: path.join(CLI.root, './assets/modules/typescript')\n };\n\n export const ModuleTypeClassName: Record<ModuleType, string[]> = {\n [ModuleType.Base]: [BaseModule.name],\n [ModuleType.Command]: [MessageCommandModule.name, SlashCommandModule.name, ContextMenuCommandModule.name],\n [ModuleType.Event]: [ClientEventModule.name, EventModule.name, RESTEventModule.name],\n [ModuleType.Postcondition]: [PostconditionModule.name],\n [ModuleType.Precondition]: [PreconditionModule.name]\n };\n\n export interface Data {\n src: string;\n name: string;\n content: string;\n moduleType: ModuleType|null;\n }\n\n export async function resolveModuleTemplates(source: keyof typeof SourceDirectory): Promise<ModuleTemplateBuilder.Data[]> {\n const src = ModuleTemplateBuilder.SourceDirectory[source];\n const files: string[] = await readdir(src);\n const templates: ModuleTemplateBuilder.Data[] = [];\n\n for (const file of files) {\n const filepath = path.join(src, file);\n const content = await readFile(filepath, 'utf-8');\n const moduleType = ModuleTemplateBuilder.getModuleTemplateContentType(content);\n\n templates.push({ src: filepath, name: path.parse(filepath).name, content, moduleType });\n }\n\n return templates;\n }\n\n export function getModuleTemplateContentType(content: string): ModuleType|null {\n const createExtendStatement = (name: string) => `export class ${Placeholder.ModuleName} extends ${name}`;\n\n for (const type of Object.keys(ModuleTypeClassName).map(Number) as ModuleType[]) {\n const statements = ModuleTypeClassName[type].map(createExtendStatement);\n\n for (const statement of statements) {\n if (content.includes(statement)) return type;\n }\n }\n\n return null;\n }\n\n export function hasPlaceholder(placeholder: Placeholder, content: string): boolean {\n return content.includes(placeholder);\n }\n\n export function removeExpectedErrorComments(content: string): string {\n const lines = content.split('\\n');\n\n return lines\n .filter(line => !line.trim().includes('// @ts-expect-error'))\n .join('\\n');\n }\n\n export function toTextCase(string: string): string {\n return String(string)\n .replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g, '')\n .replace(/([a-z])([A-Z])/g, (m, a, b) => a + '_' + b.toLowerCase())\n .replace(/[^A-Za-z0-9]+|_+/g, ' ')\n .toLowerCase();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,wBAAb,MAAa,sBAAsB;CAC/B,AAAO;CAEP,AAAgB;CAChB,AAAgB;CAEhB,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,IAAI,UAAU;AACV,SAAO,KAAK,UAAU,WAAW;;CAGrC,IAAI,YAAY;AACZ,SAAO,KAAK,cAAc,QAAQ,KAAK;;CAG3C,IAAI,WAAW;AACX,SAAO,KAAK,KAAK,KAAK,WAAW,KAAK,YAAY,GAAG;;CAGzD,YAAY,SAAwC;AAChD,OAAK,MAAM,QAAQ;AACnB,OAAK,SAAS,QAAQ;AACtB,OAAK,WAAW,SAAS;AACzB,OAAK,aAAa,SAAS;AAC3B,OAAK,aAAa,SAAS;AAC3B,OAAK,WAAW,SAAS;AACzB,OAAK,aAAa,SAAS,cAAc;;CAG7C,MAAa,OAAsB;AAC/B,QAAM,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,KAAK,IAAI,QAAQ,MAAM,CAAC,oBAAoB,KAAK,IAAI,MAAM,GAAG,CAAC;AACtG,SAAO;;CAGX,MAAa,cAAc,SAAqE;AAC5F,OAA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Aa,sBAAsB,6BAA6B,QAAQ;AAE9E,aAAU,KAAK;IAAE,KAAK;IAAU,MAAM,KAAK,MAAM,SAAS,CAAC;IAAM;IAAS;IAAY,CAAC;;AAG3F,SAAO;;;CAGJ,SAAS,6BAA6B,SAAkC;EAC3E,MAAM,yBAAyB,SAAiB,gBAAgB,YAAY,WAAW,WAAW;AAElG,OAAK,MAAM,QAAQ,OAAO,KAAK,oBAAoB,CAAC,IAAI,OAAO,EAAkB;GAC7E,MAAM,aAAa,oBAAoB,MAAM,IAAI,sBAAsB;AAEvE,QAAK,MAAM,aAAa,WACpB,KAAI,QAAQ,SAAS,UAAU,CAAE,QAAO;;AAIhD,SAAO;;;CAGJ,SAAS,eAAe,aAA0B,SAA0B;AAC/E,SAAO,QAAQ,SAAS,YAAY;;;CAGjC,SAAS,4BAA4B,SAAyB;AAGjE,SAFc,QAAQ,MAAM,KAAK,CAG5B,QAAO,SAAQ,CAAC,KAAK,MAAM,CAAC,SAAS,sBAAsB,CAAC,CAC5D,KAAK,KAAK;;;CAGZ,SAAS,WAAW,QAAwB;AAC/C,SAAO,OAAO,OAAO,CAChB,QAAQ,kCAAkC,GAAG,CAC7C,QAAQ,oBAAoB,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,aAAa,CAAC,CAClE,QAAQ,qBAAqB,IAAI,CACjC,aAAa"}
|
|
@@ -320,6 +320,7 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
320
320
|
dependencies: {
|
|
321
321
|
"@reciple/core": packageJSON.dependencies?.["@reciple/core"],
|
|
322
322
|
"@reciple/jsx": packageJSON.dependencies?.["@reciple/jsx"],
|
|
323
|
+
"discord.js": packageJSON.peerDependencies?.["discord.js"],
|
|
323
324
|
"reciple": `^${packageJSON.version}`
|
|
324
325
|
},
|
|
325
326
|
devDependencies: {
|
|
@@ -350,12 +351,12 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
350
351
|
if (fromStats.isDirectory()) {
|
|
351
352
|
const files = await readdir(from);
|
|
352
353
|
for (const file of files) {
|
|
353
|
-
const data = {
|
|
354
|
+
const data$1 = {
|
|
354
355
|
basename: file,
|
|
355
356
|
src: path.join(from, file),
|
|
356
357
|
dest: to
|
|
357
358
|
};
|
|
358
|
-
await copy(data.src, path.join(to, options?.rename ? options.rename(data) : file), options);
|
|
359
|
+
await copy(data$1.src, path.join(to, options?.rename ? options.rename(data$1) : file), options);
|
|
359
360
|
}
|
|
360
361
|
return;
|
|
361
362
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TemplateBuilder.mjs","names":["parseDotenv"],"sources":["../../../src/classes/templates/TemplateBuilder.ts"],"sourcesContent":["import { isDebugging, PackageJsonBuilder } from '@reciple/utils';\nimport { ConfigReader } from '../cli/ConfigReader.js';\nimport { copyFile, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { confirm, intro, isCancel, outro, select, text, log } from '@clack/prompts';\nimport micromatch from 'micromatch';\nimport { CLI } from '../cli/CLI.js';\nimport path from 'node:path';\nimport { existsSync, statSync } from 'node:fs';\nimport { NotAnError } from '../NotAnError.js';\nimport { slug } from 'github-slugger';\nimport { packageJSON } from '../../helpers/constants.js';\nimport { parse as parseDotenv } from '@dotenvx/dotenvx';\nimport { ModuleTemplateBuilder } from './ModuleTemplateBuilder.js';\nimport { detectPackageManager, installDependencies, installDependenciesCommand, runScript, runScriptCommand, type PackageManagerName } from 'nypm';\nimport { colors } from '@prtty/prtty';\n\nexport class TemplateBuilder {\n public originalCwd: string = process.cwd();\n\n public cli: CLI;\n public typescript?: boolean;\n public token?: string;\n public defaultAll: boolean;\n\n public config?: ConfigReader;\n public packageJson?: PackageJsonBuilder;\n\n public packageManager?: PackageManagerName;\n public dependenciesInstalled: boolean = false;\n\n get relativeDirectory() {\n return path.relative(this.originalCwd, process.cwd());\n }\n\n get packageJsonPath() {\n return path.join(process.cwd(), 'package.json');\n }\n\n get name() {\n return slug(path.basename(process.cwd()));\n }\n\n constructor(options: TemplateBuilder.Options) {\n this.cli = options.cli;\n this.typescript = options.typescript;\n this.defaultAll = options.defaultAll ?? false;\n this.packageManager = options.packageManager;\n this.token = options.token;\n }\n\n public async init(): Promise<this> {\n intro(colors.bold().black().bgCyan(` ${this.cli.command.name()} create - v${this.cli.build} `));\n return this;\n }\n\n public async createDirectory(options?: TemplateBuilder.CreateDirectoryOptions): Promise<this> {\n let cwd: string = this.originalCwd;\n\n if (!options?.directory) {\n const dir = this.defaultAll\n ? process.cwd()\n : await text({\n message: `Enter project directory`,\n placeholder: `Leave empty to use current directory`,\n defaultValue: process.cwd(),\n validate: value => {\n value = path.resolve(value);\n if (existsSync(value) && !statSync(value).isDirectory()) return 'Invalid folder directory';\n }\n });\n\n if (isCancel(dir)) throw new NotAnError('Operation cancelled');\n\n cwd = path.resolve(dir);\n } else {\n cwd = path.resolve(options.directory);\n }\n\n const stats = await stat(cwd).catch(() => undefined);\n const relative = path.relative(process.cwd(), cwd);\n\n if (stats) {\n let files = await readdir(cwd);\n files = micromatch.not(files, options?.ignoredFiles ?? TemplateBuilder.ignoredDirectoryFiles, { dot: true });\n\n if (files.length) {\n switch (options?.onNotEmpty) {\n case 'throw':\n throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);\n case 'ignore':\n return this;\n default:\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Directory ${colors.cyan(relative)} is not empty. Would you like to continue?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n break;\n }\n }\n }\n\n await mkdir(cwd, { recursive: true });\n process.chdir(cwd);\n return this;\n }\n\n public async setupLanguage(options?: TemplateBuilder.SetupLanguageOptions): Promise<this> {\n this.typescript = options?.typescript ?? this.typescript;\n\n if (!this.typescript) {\n const isTypeScript = this.defaultAll\n ? false\n : await confirm({\n message: 'Would you like to use TypeScript?',\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (isCancel(isTypeScript)) throw new NotAnError('Operation cancelled');\n this.typescript = isTypeScript;\n }\n\n return this;\n }\n\n public async createEnvFile(options?: TemplateBuilder.CreateEnvFileOptions): Promise<this> {\n const tokenKey = options?.tokenKey ?? 'DISCORD_TOKEN';\n const envFile = options?.envFile ? path.resolve(options.envFile) : '.env';\n const stats = await stat(envFile).catch(() => undefined);\n\n let env = options?.env ?? {};\n env = stats\n ? parseDotenv(await readFile(envFile, 'utf-8'), {\n processEnv: env\n })\n : env;\n\n if (env[tokenKey]) {\n const skip = this.defaultAll || await confirm({\n message: 'Discord bot token already exists in .env file, do you want to skip?',\n initialValue: true,\n active: 'Yes',\n inactive: 'No'\n });\n\n if (isCancel(skip)) throw new NotAnError('Operation cancelled');\n if (skip) return this;\n }\n\n const token = await text({\n message: 'Enter Discord Bot Token',\n placeholder: 'Bot Token from Discord Developer Portal',\n defaultValue: env[tokenKey]\n });\n\n if (isCancel(token)) throw new NotAnError('Operation cancelled');\n env[tokenKey] = token;\n\n await writeFile(envFile, `\\n${tokenKey}=\"${token}\"\\n`, {\n encoding: 'utf-8',\n flag: 'a'\n });\n\n return this;\n }\n\n public async createConfig(options?: TemplateBuilder.CreateConfigOptions): Promise<this> {\n let filepath = options?.path;\n\n filepath ??= await ConfigReader.find({\n lang: this.typescript ? 'ts' : this.typescript === false ? 'js' : undefined\n }) ?? ConfigReader.createConfigFilename(this.typescript ? 'ts' : 'js');\n\n const exists = await ConfigReader.exists(filepath);\n\n if (exists) {\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Config file already exists at ${colors.green(path.relative(process.cwd(), filepath))}. Would you like to overwrite it?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) return this;\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n }\n\n this.config = await ConfigReader.create({\n ...options,\n path: filepath,\n type: this.typescript ? 'ts' : 'js',\n overwrite: true,\n readOptions: false\n });\n\n return this;\n }\n\n public async createTemplate(options?: TemplateBuilder.CreateModulesOptions): Promise<this> {\n const source = path.join(CLI.root, './assets/templates/', this.typescript ? 'typescript' : 'javascript');\n const globals = path.join(CLI.root, './assets/global/');\n\n function rename(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return '.gitignore';\n default:\n return options?.rename?.(data) ?? data.basename;\n }\n }\n\n function overwrite(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return false;\n case 'tsconfig.json':\n case 'jsconfig.json':\n return true;\n default:\n return (typeof options?.overwrite === 'boolean' ? options.overwrite : options?.overwrite?.(data)) ?? true;\n }\n }\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n TemplateBuilder.copy(source, process.cwd(), { ...options, rename, overwrite }),\n TemplateBuilder.copy(globals, process.cwd(), { ...options, rename, overwrite })\n ]),\n message: 'Copying template files',\n successMessage: 'Files copied successfully',\n errorMessage: 'Failed to copy files'\n });\n\n await template;\n return this;\n }\n\n public async setPackageManager(options?: TemplateBuilder.SetPackageManagerOptions) {\n this.packageManager = options?.packageManager ?? this.packageManager;\n\n if (!this.packageManager) {\n const defaultPackageManager = await detectPackageManager(process.cwd()).then(pm => pm?.name ?? 'npm');\n const packageManager: PackageManagerName|symbol = this.defaultAll\n ? defaultPackageManager\n : await select({\n message: 'Select package manager',\n options: [\n { value: defaultPackageManager, label: defaultPackageManager },\n ...[\n { value: 'npm', label: 'npm' },\n { value: 'yarn', label: 'yarn' },\n { value: 'pnpm', label: 'pnpm' },\n { value: 'bun', label: 'bun' },\n { value: 'deno', label: 'deno' }\n ].filter(o => o.value !== defaultPackageManager) as { value: PackageManagerName; label: string; }[]\n ],\n initialValue: defaultPackageManager\n });\n\n if (isCancel(packageManager)) throw new NotAnError('Operation cancelled');\n this.packageManager = packageManager;\n }\n\n this.packageJson = await PackageJsonBuilder.read(this.packageJsonPath, true);\n this.packageJson.merge({\n name: this.name,\n private: true,\n type: 'module',\n scripts: {\n build: `reciple build`,\n start: 'reciple start',\n dev: 'nodemon',\n },\n ...TemplateBuilder.createDependencyRecord(this.typescript ? 'ts' : 'js'),\n });\n\n await this.packageJson?.write(this.packageJsonPath, true);\n\n return this;\n }\n\n public async installDependencies(options?: TemplateBuilder.InstallDependenciesOptions): Promise<this> {\n if (options?.value !== false) {\n if (options?.value === undefined) {\n const install = this.defaultAll\n ? true\n : await confirm({\n message: `Would you like to install dependencies?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: true\n });\n\n if (isCancel(install)) throw new NotAnError('Operation cancelled');\n if (!install) return this;\n }\n\n await CLI.createSpinnerPromise({\n promise: installDependencies({\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to install dependencies`,\n successMessage: `${colors.bold().green('✔')} Dependencies installed successfully`,\n message: `${colors.bold().dim('$')} Installing dependencies`\n })[0];\n\n this.dependenciesInstalled = true;\n }\n\n return this;\n }\n\n public async createModules(): Promise<this> {\n const moduleTemplates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? 'ts' : 'js');\n\n await mkdir('src', { recursive: true });\n\n if (!this.dependenciesInstalled) {\n log.warn('Dependencies not installed. Skipping module creation.');\n return this;\n }\n\n const moduleOptions: ModuleTemplateBuilder.Options = {\n cli: this.cli,\n config: await this.config?.read()!,\n defaultAll: true,\n typescript: this.typescript,\n };\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: 'src/commands',\n filename: `SlashCommand.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'SlashCommand')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true })),\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: 'src/events',\n filename: `ClientEvent.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'ClientEvent')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true }))\n ]),\n message: 'Creating module templates',\n successMessage: 'Module templates created successfully',\n errorMessage: 'Failed to create module templates'\n });\n\n await template;\n return this;\n }\n\n public async build(options?: TemplateBuilder.BuildOptions): Promise<this> {\n if (!options?.skipBuild && this.dependenciesInstalled) await CLI.createSpinnerPromise({\n promise: runScript('build', {\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to build project`,\n successMessage: `${colors.bold().green('✔')} Project built successfully`,\n message: `${colors.bold().dim('$')} Building project`\n })[0];\n\n outro(`Project created in ${colors.cyan(this.relativeDirectory)}`);\n\n console.log(`\\n${colors.bold().green('✔')} Start developing:`);\n\n if (this.relativeDirectory !== './') {\n console.log(` • ${colors.cyan().bold(`cd ${this.relativeDirectory}`)}`);\n }\n\n console.log(` • ${colors.cyan().bold(installDependenciesCommand(this.packageManager ?? 'npm'))} ${colors.dim('(Install dependencies)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'build'))} ${colors.dim('(Build)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'dev'))} ${colors.dim('(Development)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'start'))} ${colors.dim('(Production)')}`);\n\n\n return this;\n }\n}\n\nexport namespace TemplateBuilder {\n export interface Options {\n cli: CLI;\n typescript?: boolean;\n packageManager?: PackageManagerName;\n defaultAll?: boolean;\n token?: string;\n }\n\n export const ignoredDirectoryFiles = ['.*', 'LICENSE'];\n\n export const dependencies: Record<'ts'|'js'|'both', Partial<Record<'dependencies'|'devDependencies', Record<string, string>>>> = {\n both: {\n dependencies: {\n '@reciple/core': packageJSON.dependencies?.['@reciple/core']!,\n '@reciple/jsx': packageJSON.dependencies?.['@reciple/jsx']!,\n 'reciple': `^${packageJSON.version}`,\n },\n devDependencies: {\n '@types/node': packageJSON.devDependencies?.['@types/node']!,\n nodemon: packageJSON.devDependencies?.nodemon!,\n typescript: packageJSON.devDependencies?.['typescript']!,\n }\n },\n ts: {},\n js: {}\n };\n\n export function createDependencyRecord(type: 'ts'|'js'): Partial<Record<'dependencies'|'devDependencies', Record<string, string>>> {\n const record = type === 'ts'\n ? dependencies.ts\n : type === 'js'\n ? dependencies.js\n : {};\n\n record.dependencies = { ...record.dependencies, ...dependencies.both.dependencies };\n record.devDependencies = { ...record.devDependencies, ...dependencies.both.devDependencies };\n\n return record;\n }\n\n export interface CreateDirectoryOptions {\n directory?: string;\n ignoredFiles?: string[];\n onNotEmpty?: 'prompt'|'throw'|'ignore';\n }\n\n export interface SetupLanguageOptions {\n typescript?: boolean;\n }\n\n export interface CreateConfigOptions extends Partial<ConfigReader.CreateOptions> {}\n\n export interface CreateModulesOptions extends Partial<CopyOptions> {}\n\n export interface SetPackageManagerOptions {\n packageManager?: PackageManagerName;\n }\n\n export interface InstallDependenciesOptions {\n value?: boolean;\n }\n\n export interface CreateEnvFileOptions {\n envFile?: string;\n tokenKey?: string;\n env?: Record<string, string>;\n }\n\n export interface BuildOptions {\n skipBuild?: boolean;\n }\n\n export interface CopyOptions {\n overwrite?: boolean|((data: CopyMetadata) => boolean);\n filter?: (data: CopyMetadata) => boolean;\n rename?: (data: CopyMetadata) => string;\n }\n\n export interface CopyMetadata {\n basename: string;\n src: string;\n dest: string;\n }\n\n export async function copy(from: string, to: string, options?: CopyOptions): Promise<void> {\n const fromStats = await stat(from).catch(() => undefined);\n if (!fromStats) return;\n\n if (fromStats.isDirectory()) {\n const files = await readdir(from);\n\n for (const file of files) {\n const data: CopyMetadata = {\n basename: file,\n src: path.join(from, file),\n dest: to\n };\n\n await copy(\n data.src,\n path.join(to,\n options?.rename\n ? options.rename(data)\n : file\n ),\n options\n );\n }\n return;\n }\n\n const data: CopyMetadata = {\n basename: path.basename(from),\n src: from,\n dest: to\n };\n\n if (options?.filter && !options.filter(data)) return;\n\n const toStats = await stat(to).catch(() => undefined);\n const overwrite = typeof options?.overwrite === 'function'\n ? options.overwrite(data)\n : options?.overwrite ?? true;\n\n if (toStats && overwrite) return;\n\n await mkdir(path.dirname(to), { recursive: true });\n await copyFile(from, to);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,IAAa,kBAAb,MAAa,gBAAgB;CACzB,AAAO,cAAsB,QAAQ,KAAK;CAE1C,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,AAAO;CACP,AAAO;CAEP,AAAO;CACP,AAAO,wBAAiC;CAExC,IAAI,oBAAoB;AACpB,SAAO,KAAK,SAAS,KAAK,aAAa,QAAQ,KAAK,CAAC;;CAGzD,IAAI,kBAAkB;AAClB,SAAO,KAAK,KAAK,QAAQ,KAAK,EAAE,eAAe;;CAGnD,IAAI,OAAO;AACP,SAAO,KAAK,KAAK,SAAS,QAAQ,KAAK,CAAC,CAAC;;CAG7C,YAAY,SAAkC;AAC1C,OAAK,MAAM,QAAQ;AACnB,OAAK,aAAa,QAAQ;AAC1B,OAAK,aAAa,QAAQ,cAAc;AACxC,OAAK,iBAAiB,QAAQ;AAC9B,OAAK,QAAQ,QAAQ;;CAGzB,MAAa,OAAsB;AAC/B,QAAM,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,KAAK,IAAI,QAAQ,MAAM,CAAC,aAAa,KAAK,IAAI,MAAM,GAAG,CAAC;AAC/F,SAAO;;CAGX,MAAa,gBAAgB,SAAiE;EAC1F,IAAI,MAAc,KAAK;AAEvB,MAAI,CAAC,SAAS,WAAW;GACrB,MAAM,MAAM,KAAK,aACX,QAAQ,KAAK,GACb,MAAM,KAAK;IACT,SAAS;IACT,aAAa;IACb,cAAc,QAAQ,KAAK;IAC3B,WAAU,UAAS;AACf,aAAQ,KAAK,QAAQ,MAAM;AAC3B,SAAI,WAAW,MAAM,IAAI,CAAC,SAAS,MAAM,CAAC,aAAa,CAAE,QAAO;;IAEvE,CAAC;AAEN,OAAI,SAAS,IAA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,OAAO;GAAc,GAAG,aAAa,KAAK;GAAc;AACnF,SAAO,kBAAkB;GAAE,GAAG,OAAO;GAAiB,GAAG,aAAa,KAAK;GAAiB;AAE5F,SAAO;;;CA+CJ,eAAe,KAAK,MAAc,IAAY,SAAsC;EACvF,MAAM,YAAY,MAAM,KAAK,KAAK,CAAC,YAAY,OAAU;AACzD,MAAI,CAAC,UAAW;AAEhB,MAAI,UAAU,aAAa,EAAE;GACzB,MAAM,QAAQ,MAAM,QAAQ,KAAK;AAEjC,QAAK,MAAM,QAAQ,OAAO;IACtB,MAAM,OAAqB;KACvB,UAAU;KACV,KAAK,KAAK,KAAK,MAAM,KAAK;KAC1B,MAAM;KACT;AAED,UAAM,KACF,KAAK,KACL,KAAK,KAAK,IACN,SAAS,SACH,QAAQ,OAAO,KAAK,GACpB,KACT,EACD,QACH;;AAEL;;EAGJ,MAAM,OAAqB;GACvB,UAAU,KAAK,SAAS,KAAK;GAC7B,KAAK;GACL,MAAM;GACT;AAED,MAAI,SAAS,UAAU,CAAC,QAAQ,OAAO,KAAK,CAAE;EAE9C,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,YAAY,OAAU;EACrD,MAAM,YAAY,OAAO,SAAS,cAAc,aAC1C,QAAQ,UAAU,KAAK,GACvB,SAAS,aAAa;AAE5B,MAAI,WAAW,UAAW;AAE1B,QAAM,MAAM,KAAK,QAAQ,GAAG,EAAE,EAAE,WAAW,MAAM,CAAC;AAClD,QAAM,SAAS,MAAM,GAAG"}
|
|
1
|
+
{"version":3,"file":"TemplateBuilder.mjs","names":["parseDotenv","data"],"sources":["../../../src/classes/templates/TemplateBuilder.ts"],"sourcesContent":["import { isDebugging, PackageJsonBuilder } from '@reciple/utils';\nimport { ConfigReader } from '../cli/ConfigReader.js';\nimport { copyFile, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { confirm, intro, isCancel, outro, select, text, log } from '@clack/prompts';\nimport micromatch from 'micromatch';\nimport { CLI } from '../cli/CLI.js';\nimport path from 'node:path';\nimport { existsSync, statSync } from 'node:fs';\nimport { NotAnError } from '../NotAnError.js';\nimport { slug } from 'github-slugger';\nimport { packageJSON } from '../../helpers/constants.js';\nimport { parse as parseDotenv } from '@dotenvx/dotenvx';\nimport { ModuleTemplateBuilder } from './ModuleTemplateBuilder.js';\nimport { detectPackageManager, installDependencies, installDependenciesCommand, runScript, runScriptCommand, type PackageManagerName } from 'nypm';\nimport { colors } from '@prtty/prtty';\n\nexport class TemplateBuilder {\n public originalCwd: string = process.cwd();\n\n public cli: CLI;\n public typescript?: boolean;\n public token?: string;\n public defaultAll: boolean;\n\n public config?: ConfigReader;\n public packageJson?: PackageJsonBuilder;\n\n public packageManager?: PackageManagerName;\n public dependenciesInstalled: boolean = false;\n\n get relativeDirectory() {\n return path.relative(this.originalCwd, process.cwd());\n }\n\n get packageJsonPath() {\n return path.join(process.cwd(), 'package.json');\n }\n\n get name() {\n return slug(path.basename(process.cwd()));\n }\n\n constructor(options: TemplateBuilder.Options) {\n this.cli = options.cli;\n this.typescript = options.typescript;\n this.defaultAll = options.defaultAll ?? false;\n this.packageManager = options.packageManager;\n this.token = options.token;\n }\n\n public async init(): Promise<this> {\n intro(colors.bold().black().bgCyan(` ${this.cli.command.name()} create - v${this.cli.build} `));\n return this;\n }\n\n public async createDirectory(options?: TemplateBuilder.CreateDirectoryOptions): Promise<this> {\n let cwd: string = this.originalCwd;\n\n if (!options?.directory) {\n const dir = this.defaultAll\n ? process.cwd()\n : await text({\n message: `Enter project directory`,\n placeholder: `Leave empty to use current directory`,\n defaultValue: process.cwd(),\n validate: value => {\n value = path.resolve(value);\n if (existsSync(value) && !statSync(value).isDirectory()) return 'Invalid folder directory';\n }\n });\n\n if (isCancel(dir)) throw new NotAnError('Operation cancelled');\n\n cwd = path.resolve(dir);\n } else {\n cwd = path.resolve(options.directory);\n }\n\n const stats = await stat(cwd).catch(() => undefined);\n const relative = path.relative(process.cwd(), cwd);\n\n if (stats) {\n let files = await readdir(cwd);\n files = micromatch.not(files, options?.ignoredFiles ?? TemplateBuilder.ignoredDirectoryFiles, { dot: true });\n\n if (files.length) {\n switch (options?.onNotEmpty) {\n case 'throw':\n throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);\n case 'ignore':\n return this;\n default:\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Directory ${colors.cyan(relative)} is not empty. Would you like to continue?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n break;\n }\n }\n }\n\n await mkdir(cwd, { recursive: true });\n process.chdir(cwd);\n return this;\n }\n\n public async setupLanguage(options?: TemplateBuilder.SetupLanguageOptions): Promise<this> {\n this.typescript = options?.typescript ?? this.typescript;\n\n if (!this.typescript) {\n const isTypeScript = this.defaultAll\n ? false\n : await confirm({\n message: 'Would you like to use TypeScript?',\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (isCancel(isTypeScript)) throw new NotAnError('Operation cancelled');\n this.typescript = isTypeScript;\n }\n\n return this;\n }\n\n public async createEnvFile(options?: TemplateBuilder.CreateEnvFileOptions): Promise<this> {\n const tokenKey = options?.tokenKey ?? 'DISCORD_TOKEN';\n const envFile = options?.envFile ? path.resolve(options.envFile) : '.env';\n const stats = await stat(envFile).catch(() => undefined);\n\n let env = options?.env ?? {};\n env = stats\n ? parseDotenv(await readFile(envFile, 'utf-8'), {\n processEnv: env\n })\n : env;\n\n if (env[tokenKey]) {\n const skip = this.defaultAll || await confirm({\n message: 'Discord bot token already exists in .env file, do you want to skip?',\n initialValue: true,\n active: 'Yes',\n inactive: 'No'\n });\n\n if (isCancel(skip)) throw new NotAnError('Operation cancelled');\n if (skip) return this;\n }\n\n const token = await text({\n message: 'Enter Discord Bot Token',\n placeholder: 'Bot Token from Discord Developer Portal',\n defaultValue: env[tokenKey]\n });\n\n if (isCancel(token)) throw new NotAnError('Operation cancelled');\n env[tokenKey] = token;\n\n await writeFile(envFile, `\\n${tokenKey}=\"${token}\"\\n`, {\n encoding: 'utf-8',\n flag: 'a'\n });\n\n return this;\n }\n\n public async createConfig(options?: TemplateBuilder.CreateConfigOptions): Promise<this> {\n let filepath = options?.path;\n\n filepath ??= await ConfigReader.find({\n lang: this.typescript ? 'ts' : this.typescript === false ? 'js' : undefined\n }) ?? ConfigReader.createConfigFilename(this.typescript ? 'ts' : 'js');\n\n const exists = await ConfigReader.exists(filepath);\n\n if (exists) {\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Config file already exists at ${colors.green(path.relative(process.cwd(), filepath))}. Would you like to overwrite it?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) return this;\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n }\n\n this.config = await ConfigReader.create({\n ...options,\n path: filepath,\n type: this.typescript ? 'ts' : 'js',\n overwrite: true,\n readOptions: false\n });\n\n return this;\n }\n\n public async createTemplate(options?: TemplateBuilder.CreateModulesOptions): Promise<this> {\n const source = path.join(CLI.root, './assets/templates/', this.typescript ? 'typescript' : 'javascript');\n const globals = path.join(CLI.root, './assets/global/');\n\n function rename(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return '.gitignore';\n default:\n return options?.rename?.(data) ?? data.basename;\n }\n }\n\n function overwrite(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return false;\n case 'tsconfig.json':\n case 'jsconfig.json':\n return true;\n default:\n return (typeof options?.overwrite === 'boolean' ? options.overwrite : options?.overwrite?.(data)) ?? true;\n }\n }\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n TemplateBuilder.copy(source, process.cwd(), { ...options, rename, overwrite }),\n TemplateBuilder.copy(globals, process.cwd(), { ...options, rename, overwrite })\n ]),\n message: 'Copying template files',\n successMessage: 'Files copied successfully',\n errorMessage: 'Failed to copy files'\n });\n\n await template;\n return this;\n }\n\n public async setPackageManager(options?: TemplateBuilder.SetPackageManagerOptions) {\n this.packageManager = options?.packageManager ?? this.packageManager;\n\n if (!this.packageManager) {\n const defaultPackageManager = await detectPackageManager(process.cwd()).then(pm => pm?.name ?? 'npm');\n const packageManager: PackageManagerName|symbol = this.defaultAll\n ? defaultPackageManager\n : await select({\n message: 'Select package manager',\n options: [\n { value: defaultPackageManager, label: defaultPackageManager },\n ...[\n { value: 'npm', label: 'npm' },\n { value: 'yarn', label: 'yarn' },\n { value: 'pnpm', label: 'pnpm' },\n { value: 'bun', label: 'bun' },\n { value: 'deno', label: 'deno' }\n ].filter(o => o.value !== defaultPackageManager) as { value: PackageManagerName; label: string; }[]\n ],\n initialValue: defaultPackageManager\n });\n\n if (isCancel(packageManager)) throw new NotAnError('Operation cancelled');\n this.packageManager = packageManager;\n }\n\n this.packageJson = await PackageJsonBuilder.read(this.packageJsonPath, true);\n this.packageJson.merge({\n name: this.name,\n private: true,\n type: 'module',\n scripts: {\n build: `reciple build`,\n start: 'reciple start',\n dev: 'nodemon',\n },\n ...TemplateBuilder.createDependencyRecord(this.typescript ? 'ts' : 'js'),\n });\n\n await this.packageJson?.write(this.packageJsonPath, true);\n\n return this;\n }\n\n public async installDependencies(options?: TemplateBuilder.InstallDependenciesOptions): Promise<this> {\n if (options?.value !== false) {\n if (options?.value === undefined) {\n const install = this.defaultAll\n ? true\n : await confirm({\n message: `Would you like to install dependencies?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: true\n });\n\n if (isCancel(install)) throw new NotAnError('Operation cancelled');\n if (!install) return this;\n }\n\n await CLI.createSpinnerPromise({\n promise: installDependencies({\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to install dependencies`,\n successMessage: `${colors.bold().green('✔')} Dependencies installed successfully`,\n message: `${colors.bold().dim('$')} Installing dependencies`\n })[0];\n\n this.dependenciesInstalled = true;\n }\n\n return this;\n }\n\n public async createModules(): Promise<this> {\n const moduleTemplates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? 'ts' : 'js');\n\n await mkdir('src', { recursive: true });\n\n if (!this.dependenciesInstalled) {\n log.warn('Dependencies not installed. Skipping module creation.');\n return this;\n }\n\n const moduleOptions: ModuleTemplateBuilder.Options = {\n cli: this.cli,\n config: await this.config?.read()!,\n defaultAll: true,\n typescript: this.typescript,\n };\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: 'src/commands',\n filename: `SlashCommand.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'SlashCommand')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true })),\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: 'src/events',\n filename: `ClientEvent.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'ClientEvent')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true }))\n ]),\n message: 'Creating module templates',\n successMessage: 'Module templates created successfully',\n errorMessage: 'Failed to create module templates'\n });\n\n await template;\n return this;\n }\n\n public async build(options?: TemplateBuilder.BuildOptions): Promise<this> {\n if (!options?.skipBuild && this.dependenciesInstalled) await CLI.createSpinnerPromise({\n promise: runScript('build', {\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to build project`,\n successMessage: `${colors.bold().green('✔')} Project built successfully`,\n message: `${colors.bold().dim('$')} Building project`\n })[0];\n\n outro(`Project created in ${colors.cyan(this.relativeDirectory)}`);\n\n console.log(`\\n${colors.bold().green('✔')} Start developing:`);\n\n if (this.relativeDirectory !== './') {\n console.log(` • ${colors.cyan().bold(`cd ${this.relativeDirectory}`)}`);\n }\n\n console.log(` • ${colors.cyan().bold(installDependenciesCommand(this.packageManager ?? 'npm'))} ${colors.dim('(Install dependencies)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'build'))} ${colors.dim('(Build)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'dev'))} ${colors.dim('(Development)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'start'))} ${colors.dim('(Production)')}`);\n\n\n return this;\n }\n}\n\nexport namespace TemplateBuilder {\n export interface Options {\n cli: CLI;\n typescript?: boolean;\n packageManager?: PackageManagerName;\n defaultAll?: boolean;\n token?: string;\n }\n\n export const ignoredDirectoryFiles = ['.*', 'LICENSE'];\n\n export const dependencies: Record<'ts'|'js'|'both', Partial<Record<'dependencies'|'devDependencies', Record<string, string>>>> = {\n both: {\n dependencies: {\n '@reciple/core': packageJSON.dependencies?.['@reciple/core']!,\n '@reciple/jsx': packageJSON.dependencies?.['@reciple/jsx']!,\n 'discord.js': packageJSON.peerDependencies?.['discord.js']!,\n 'reciple': `^${packageJSON.version}`,\n },\n devDependencies: {\n '@types/node': packageJSON.devDependencies?.['@types/node']!,\n nodemon: packageJSON.devDependencies?.nodemon!,\n typescript: packageJSON.devDependencies?.['typescript']!,\n }\n },\n ts: {},\n js: {}\n };\n\n export function createDependencyRecord(type: 'ts'|'js'): Partial<Record<'dependencies'|'devDependencies', Record<string, string>>> {\n const record = type === 'ts'\n ? dependencies.ts\n : type === 'js'\n ? dependencies.js\n : {};\n\n record.dependencies = { ...record.dependencies, ...dependencies.both.dependencies };\n record.devDependencies = { ...record.devDependencies, ...dependencies.both.devDependencies };\n\n return record;\n }\n\n export interface CreateDirectoryOptions {\n directory?: string;\n ignoredFiles?: string[];\n onNotEmpty?: 'prompt'|'throw'|'ignore';\n }\n\n export interface SetupLanguageOptions {\n typescript?: boolean;\n }\n\n export interface CreateConfigOptions extends Partial<ConfigReader.CreateOptions> {}\n\n export interface CreateModulesOptions extends Partial<CopyOptions> {}\n\n export interface SetPackageManagerOptions {\n packageManager?: PackageManagerName;\n }\n\n export interface InstallDependenciesOptions {\n value?: boolean;\n }\n\n export interface CreateEnvFileOptions {\n envFile?: string;\n tokenKey?: string;\n env?: Record<string, string>;\n }\n\n export interface BuildOptions {\n skipBuild?: boolean;\n }\n\n export interface CopyOptions {\n overwrite?: boolean|((data: CopyMetadata) => boolean);\n filter?: (data: CopyMetadata) => boolean;\n rename?: (data: CopyMetadata) => string;\n }\n\n export interface CopyMetadata {\n basename: string;\n src: string;\n dest: string;\n }\n\n export async function copy(from: string, to: string, options?: CopyOptions): Promise<void> {\n const fromStats = await stat(from).catch(() => undefined);\n if (!fromStats) return;\n\n if (fromStats.isDirectory()) {\n const files = await readdir(from);\n\n for (const file of files) {\n const data: CopyMetadata = {\n basename: file,\n src: path.join(from, file),\n dest: to\n };\n\n await copy(\n data.src,\n path.join(to,\n options?.rename\n ? options.rename(data)\n : file\n ),\n options\n );\n }\n return;\n }\n\n const data: CopyMetadata = {\n basename: path.basename(from),\n src: from,\n dest: to\n };\n\n if (options?.filter && !options.filter(data)) return;\n\n const toStats = await stat(to).catch(() => undefined);\n const overwrite = typeof options?.overwrite === 'function'\n ? options.overwrite(data)\n : options?.overwrite ?? true;\n\n if (toStats && overwrite) return;\n\n await mkdir(path.dirname(to), { recursive: true });\n await copyFile(from, to);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,IAAa,kBAAb,MAAa,gBAAgB;CACzB,AAAO,cAAsB,QAAQ,KAAK;CAE1C,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,AAAO;CACP,AAAO;CAEP,AAAO;CACP,AAAO,wBAAiC;CAExC,IAAI,oBAAoB;AACpB,SAAO,KAAK,SAAS,KAAK,aAAa,QAAQ,KAAK,CAAC;;CAGzD,IAAI,kBAAkB;AAClB,SAAO,KAAK,KAAK,QAAQ,KAAK,EAAE,eAAe;;CAGnD,IAAI,OAAO;AACP,SAAO,KAAK,KAAK,SAAS,QAAQ,KAAK,CAAC,CAAC;;CAG7C,YAAY,SAA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;GACvB,UAAU,KAAK,SAAS,KAAK;GAC7B,KAAK;GACL,MAAM;GACT;AAED,MAAI,SAAS,UAAU,CAAC,QAAQ,OAAO,KAAK,CAAE;EAE9C,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,YAAY,OAAU;EACrD,MAAM,YAAY,OAAO,SAAS,cAAc,aAC1C,QAAQ,UAAU,KAAK,GACvB,SAAS,aAAa;AAE5B,MAAI,WAAW,UAAW;AAE1B,QAAM,MAAM,KAAK,QAAQ,GAAG,EAAE,EAAE,WAAW,MAAM,CAAC;AAClD,QAAM,SAAS,MAAM,GAAG"}
|
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
import { ModuleType } from "../../helpers/constants.mjs";
|
|
2
2
|
import { AnyModuleData } from "../../helpers/types.mjs";
|
|
3
3
|
import { Validator } from "@reciple/core";
|
|
4
|
-
import * as
|
|
4
|
+
import * as _sapphire_shapeshift24 from "@sapphire/shapeshift";
|
|
5
5
|
|
|
6
6
|
//#region src/classes/validation/BaseModuleValidator.d.ts
|
|
7
7
|
declare class BaseModuleValidator extends Validator {
|
|
8
|
-
static id:
|
|
9
|
-
static moduleType:
|
|
10
|
-
static onEnable:
|
|
11
|
-
static onReady:
|
|
12
|
-
static onDisable:
|
|
13
|
-
static object:
|
|
8
|
+
static id: _sapphire_shapeshift24.StringValidator<string>;
|
|
9
|
+
static moduleType: _sapphire_shapeshift24.NativeEnumValidator<typeof ModuleType>;
|
|
10
|
+
static onEnable: _sapphire_shapeshift24.UnionValidator<Function | undefined>;
|
|
11
|
+
static onReady: _sapphire_shapeshift24.UnionValidator<Function | undefined>;
|
|
12
|
+
static onDisable: _sapphire_shapeshift24.UnionValidator<Function | undefined>;
|
|
13
|
+
static object: _sapphire_shapeshift24.ObjectValidator<{
|
|
14
14
|
id: string | undefined;
|
|
15
15
|
moduleType: ModuleType | undefined;
|
|
16
16
|
onEnable: Function | undefined;
|
|
17
17
|
onReady: Function | undefined;
|
|
18
18
|
onDisable: Function | undefined;
|
|
19
|
-
},
|
|
19
|
+
}, _sapphire_shapeshift24.UndefinedToOptional<{
|
|
20
20
|
id: string | undefined;
|
|
21
21
|
moduleType: ModuleType | undefined;
|
|
22
22
|
onEnable: Function | undefined;
|
|
23
23
|
onReady: Function | undefined;
|
|
24
24
|
onDisable: Function | undefined;
|
|
25
25
|
}>>;
|
|
26
|
-
static resolvable:
|
|
26
|
+
static resolvable: _sapphire_shapeshift24.UnionValidator<_sapphire_shapeshift24.UndefinedToOptional<{
|
|
27
|
+
toJSON: Function;
|
|
28
|
+
}> | _sapphire_shapeshift24.UndefinedToOptional<{
|
|
27
29
|
id: string | undefined;
|
|
28
30
|
moduleType: ModuleType | undefined;
|
|
29
31
|
onEnable: Function | undefined;
|
|
30
32
|
onReady: Function | undefined;
|
|
31
33
|
onDisable: Function | undefined;
|
|
32
|
-
}> | _sapphire_shapeshift0.UndefinedToOptional<{
|
|
33
|
-
toJSON: Function;
|
|
34
34
|
}>>;
|
|
35
35
|
static isValidId(id: unknown): asserts id is string;
|
|
36
36
|
static isValidModuleType(moduleType: unknown): asserts moduleType is ModuleType;
|
|
@@ -3,11 +3,11 @@ import { AnyCommandModuleData } from "../../helpers/types.mjs";
|
|
|
3
3
|
import "../../index.mjs";
|
|
4
4
|
import * as _reciple_core0 from "@reciple/core";
|
|
5
5
|
import { Validator } from "@reciple/core";
|
|
6
|
-
import * as
|
|
6
|
+
import * as _sapphire_shapeshift7 from "@sapphire/shapeshift";
|
|
7
7
|
|
|
8
8
|
//#region src/classes/validation/CommandModuleValidator.d.ts
|
|
9
9
|
declare class CommandModuleValidator extends Validator {
|
|
10
|
-
static object:
|
|
10
|
+
static object: _sapphire_shapeshift7.ObjectValidator<{
|
|
11
11
|
id: string | undefined;
|
|
12
12
|
moduleType: ModuleType | undefined;
|
|
13
13
|
onEnable: Function | undefined;
|
|
@@ -16,23 +16,23 @@ declare class CommandModuleValidator extends Validator {
|
|
|
16
16
|
} & {
|
|
17
17
|
id: string;
|
|
18
18
|
type: _reciple_core0.CommandType;
|
|
19
|
-
data:
|
|
19
|
+
data: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
20
20
|
name: any;
|
|
21
21
|
description: any;
|
|
22
22
|
aliases: any;
|
|
23
23
|
options: any;
|
|
24
24
|
flags: any;
|
|
25
|
-
}> |
|
|
25
|
+
}> | _sapphire_shapeshift7.UndefinedToOptional<{
|
|
26
26
|
type: any;
|
|
27
27
|
name: any;
|
|
28
28
|
}>;
|
|
29
29
|
cooldown: number | undefined;
|
|
30
|
-
preconditions:
|
|
30
|
+
preconditions: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
31
31
|
id: any;
|
|
32
32
|
scope: any;
|
|
33
33
|
execute: any;
|
|
34
34
|
}>[] | undefined;
|
|
35
|
-
postconditions:
|
|
35
|
+
postconditions: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
36
36
|
id: any;
|
|
37
37
|
scope: any;
|
|
38
38
|
execute: any;
|
|
@@ -40,7 +40,7 @@ declare class CommandModuleValidator extends Validator {
|
|
|
40
40
|
disabledPreconditions: string[] | undefined;
|
|
41
41
|
disabledPostconditions: string[] | undefined;
|
|
42
42
|
execute: Function;
|
|
43
|
-
},
|
|
43
|
+
}, _sapphire_shapeshift7.UndefinedToOptional<{
|
|
44
44
|
id: string | undefined;
|
|
45
45
|
moduleType: ModuleType | undefined;
|
|
46
46
|
onEnable: Function | undefined;
|
|
@@ -49,23 +49,23 @@ declare class CommandModuleValidator extends Validator {
|
|
|
49
49
|
} & {
|
|
50
50
|
id: string;
|
|
51
51
|
type: _reciple_core0.CommandType;
|
|
52
|
-
data:
|
|
52
|
+
data: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
53
53
|
name: any;
|
|
54
54
|
description: any;
|
|
55
55
|
aliases: any;
|
|
56
56
|
options: any;
|
|
57
57
|
flags: any;
|
|
58
|
-
}> |
|
|
58
|
+
}> | _sapphire_shapeshift7.UndefinedToOptional<{
|
|
59
59
|
type: any;
|
|
60
60
|
name: any;
|
|
61
61
|
}>;
|
|
62
62
|
cooldown: number | undefined;
|
|
63
|
-
preconditions:
|
|
63
|
+
preconditions: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
64
64
|
id: any;
|
|
65
65
|
scope: any;
|
|
66
66
|
execute: any;
|
|
67
67
|
}>[] | undefined;
|
|
68
|
-
postconditions:
|
|
68
|
+
postconditions: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
69
69
|
id: any;
|
|
70
70
|
scope: any;
|
|
71
71
|
execute: any;
|
|
@@ -74,9 +74,9 @@ declare class CommandModuleValidator extends Validator {
|
|
|
74
74
|
disabledPostconditions: string[] | undefined;
|
|
75
75
|
execute: Function;
|
|
76
76
|
}>>;
|
|
77
|
-
static resolvable:
|
|
77
|
+
static resolvable: _sapphire_shapeshift7.UnionValidator<_sapphire_shapeshift7.UndefinedToOptional<{
|
|
78
78
|
toJSON: Function;
|
|
79
|
-
}> |
|
|
79
|
+
}> | _sapphire_shapeshift7.UndefinedToOptional<{
|
|
80
80
|
id: string | undefined;
|
|
81
81
|
moduleType: ModuleType | undefined;
|
|
82
82
|
onEnable: Function | undefined;
|
|
@@ -85,23 +85,23 @@ declare class CommandModuleValidator extends Validator {
|
|
|
85
85
|
} & {
|
|
86
86
|
id: string;
|
|
87
87
|
type: _reciple_core0.CommandType;
|
|
88
|
-
data:
|
|
88
|
+
data: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
89
89
|
name: any;
|
|
90
90
|
description: any;
|
|
91
91
|
aliases: any;
|
|
92
92
|
options: any;
|
|
93
93
|
flags: any;
|
|
94
|
-
}> |
|
|
94
|
+
}> | _sapphire_shapeshift7.UndefinedToOptional<{
|
|
95
95
|
type: any;
|
|
96
96
|
name: any;
|
|
97
97
|
}>;
|
|
98
98
|
cooldown: number | undefined;
|
|
99
|
-
preconditions:
|
|
99
|
+
preconditions: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
100
100
|
id: any;
|
|
101
101
|
scope: any;
|
|
102
102
|
execute: any;
|
|
103
103
|
}>[] | undefined;
|
|
104
|
-
postconditions:
|
|
104
|
+
postconditions: _sapphire_shapeshift7.UndefinedToOptional<{
|
|
105
105
|
id: any;
|
|
106
106
|
scope: any;
|
|
107
107
|
execute: any;
|
|
@@ -3,19 +3,19 @@ import { EventModule } from "../modules/events/EventModule.mjs";
|
|
|
3
3
|
import "../../index.mjs";
|
|
4
4
|
import { Validator } from "@reciple/core";
|
|
5
5
|
import { EventEmitter } from "node:events";
|
|
6
|
-
import * as
|
|
6
|
+
import * as _sapphire_shapeshift34 from "@sapphire/shapeshift";
|
|
7
7
|
|
|
8
8
|
//#region src/classes/validation/EventModuleValidator.d.ts
|
|
9
9
|
declare class EventModuleValidator extends Validator {
|
|
10
|
-
static emitter:
|
|
10
|
+
static emitter: _sapphire_shapeshift34.InstanceValidator<EventEmitter<{
|
|
11
11
|
[x: string]: any[];
|
|
12
12
|
[x: number]: any[];
|
|
13
13
|
[x: symbol]: any[];
|
|
14
14
|
}>>;
|
|
15
|
-
static event:
|
|
16
|
-
static once:
|
|
17
|
-
static onEvent:
|
|
18
|
-
static object:
|
|
15
|
+
static event: _sapphire_shapeshift34.StringValidator<string>;
|
|
16
|
+
static once: _sapphire_shapeshift34.UnionValidator<boolean | undefined>;
|
|
17
|
+
static onEvent: _sapphire_shapeshift34.InstanceValidator<Function>;
|
|
18
|
+
static object: _sapphire_shapeshift34.ObjectValidator<{
|
|
19
19
|
id: string | undefined;
|
|
20
20
|
moduleType: ModuleType | undefined;
|
|
21
21
|
onEnable: Function | undefined;
|
|
@@ -30,7 +30,7 @@ declare class EventModuleValidator extends Validator {
|
|
|
30
30
|
event: string;
|
|
31
31
|
once: boolean | undefined;
|
|
32
32
|
onEvent: Function;
|
|
33
|
-
},
|
|
33
|
+
}, _sapphire_shapeshift34.UndefinedToOptional<{
|
|
34
34
|
id: string | undefined;
|
|
35
35
|
moduleType: ModuleType | undefined;
|
|
36
36
|
onEnable: Function | undefined;
|
|
@@ -46,9 +46,9 @@ declare class EventModuleValidator extends Validator {
|
|
|
46
46
|
once: boolean | undefined;
|
|
47
47
|
onEvent: Function;
|
|
48
48
|
}>>;
|
|
49
|
-
static resolvable:
|
|
49
|
+
static resolvable: _sapphire_shapeshift34.UnionValidator<_sapphire_shapeshift34.UndefinedToOptional<{
|
|
50
50
|
toJSON: Function;
|
|
51
|
-
}> |
|
|
51
|
+
}> | _sapphire_shapeshift34.UndefinedToOptional<{
|
|
52
52
|
id: string | undefined;
|
|
53
53
|
moduleType: ModuleType | undefined;
|
|
54
54
|
onEnable: Function | undefined;
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
import { PostconditionModule } from "../modules/PostconditionModule.mjs";
|
|
2
2
|
import { CommandPostconditionReason, CommandType, Validator } from "@reciple/core";
|
|
3
|
-
import * as
|
|
3
|
+
import * as _sapphire_shapeshift0 from "@sapphire/shapeshift";
|
|
4
4
|
|
|
5
5
|
//#region src/classes/validation/PostconditionModule.d.ts
|
|
6
6
|
declare class PostconditionModuleValidator extends Validator {
|
|
7
|
-
static scope:
|
|
8
|
-
static accepts:
|
|
9
|
-
static execute:
|
|
10
|
-
static object:
|
|
7
|
+
static scope: _sapphire_shapeshift0.UnionValidator<CommandType[] | undefined>;
|
|
8
|
+
static accepts: _sapphire_shapeshift0.UnionValidator<CommandPostconditionReason[] | undefined>;
|
|
9
|
+
static execute: _sapphire_shapeshift0.InstanceValidator<Function>;
|
|
10
|
+
static object: _sapphire_shapeshift0.ObjectValidator<{
|
|
11
11
|
scope: CommandType[] | undefined;
|
|
12
12
|
execute: Function;
|
|
13
|
-
},
|
|
13
|
+
}, _sapphire_shapeshift0.UndefinedToOptional<{
|
|
14
14
|
scope: CommandType[] | undefined;
|
|
15
15
|
execute: Function;
|
|
16
16
|
}>>;
|
|
17
|
-
static resolvable:
|
|
18
|
-
toJSON: Function;
|
|
19
|
-
}> | _sapphire_shapeshift35.UndefinedToOptional<{
|
|
17
|
+
static resolvable: _sapphire_shapeshift0.UnionValidator<_sapphire_shapeshift0.UndefinedToOptional<{
|
|
20
18
|
scope: CommandType[] | undefined;
|
|
21
19
|
execute: Function;
|
|
20
|
+
}> | _sapphire_shapeshift0.UndefinedToOptional<{
|
|
21
|
+
toJSON: Function;
|
|
22
22
|
}>>;
|
|
23
23
|
static isValidScope(scope: unknown): asserts scope is CommandType[];
|
|
24
24
|
static isValidAccepts(accepts: unknown): asserts accepts is CommandPostconditionReason[];
|
package/dist/package.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region package.json
|
|
2
2
|
var package_default = {
|
|
3
3
|
name: "reciple",
|
|
4
|
-
version: "10.0.
|
|
4
|
+
version: "10.0.8",
|
|
5
5
|
license: "LGPL-3.0-only",
|
|
6
6
|
description: "The CLI for reciple",
|
|
7
7
|
module: "./dist/index.mjs",
|
|
@@ -38,8 +38,8 @@ var package_default = {
|
|
|
38
38
|
dependencies: {
|
|
39
39
|
"@clack/prompts": "^0.11.0",
|
|
40
40
|
"@dotenvx/dotenvx": "^1.52.0",
|
|
41
|
-
"@prtty/print": "
|
|
42
|
-
"@prtty/prtty": "
|
|
41
|
+
"@prtty/print": "catalog:",
|
|
42
|
+
"@prtty/prtty": "catalog:",
|
|
43
43
|
"@reciple/utils": "^10.0.1",
|
|
44
44
|
"@sapphire/shapeshift": "^4.0.0",
|
|
45
45
|
"@sapphire/snowflake": "^3.5.5",
|
|
@@ -57,15 +57,15 @@ var package_default = {
|
|
|
57
57
|
devDependencies: {
|
|
58
58
|
"@reciple/jsx": "^10.0.1",
|
|
59
59
|
"@types/micromatch": "^4.0.10",
|
|
60
|
-
"@types/node": "
|
|
60
|
+
"@types/node": "catalog:",
|
|
61
61
|
"@types/semver": "^7.7.1",
|
|
62
62
|
"nodemon": "^3.1.11",
|
|
63
63
|
"rolldown": "^1.0.0-rc.1",
|
|
64
|
-
"typescript": "
|
|
64
|
+
"typescript": "catalog:"
|
|
65
65
|
},
|
|
66
66
|
peerDependencies: {
|
|
67
|
-
"@reciple/core": "
|
|
68
|
-
"discord.js": "
|
|
67
|
+
"@reciple/core": "workspace:^",
|
|
68
|
+
"discord.js": "catalog:"
|
|
69
69
|
},
|
|
70
70
|
peerDependenciesMeta: {
|
|
71
71
|
"@reciple/core": { "optional": false },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "reciple",
|
|
3
|
-
"version": "10.0.
|
|
3
|
+
"version": "10.0.8",
|
|
4
4
|
"license": "LGPL-3.0-only",
|
|
5
5
|
"description": "The CLI for reciple",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -56,15 +56,15 @@
|
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@reciple/jsx": "^10.0.1",
|
|
58
58
|
"@types/micromatch": "^4.0.10",
|
|
59
|
-
"@types/node": "
|
|
59
|
+
"@types/node": "^25.0.9",
|
|
60
60
|
"@types/semver": "^7.7.1",
|
|
61
61
|
"nodemon": "^3.1.11",
|
|
62
62
|
"rolldown": "^1.0.0-rc.1",
|
|
63
|
-
"typescript": "
|
|
63
|
+
"typescript": "^5.9.3"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
|
-
"@reciple/core": "
|
|
67
|
-
"discord.js": "
|
|
66
|
+
"@reciple/core": "^10.0.1",
|
|
67
|
+
"discord.js": "^14.25.1"
|
|
68
68
|
},
|
|
69
69
|
"peerDependenciesMeta": {
|
|
70
70
|
"@reciple/core": {
|