commandkit 0.1.10-dev.20240131174628 → 0.1.10-dev.20240202061201
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/CommandKit.js.map +1 -1
- package/dist/CommandKit.mjs +1 -1
- package/dist/bootstrap/client.js.map +1 -1
- package/dist/bootstrap/client.mjs +1 -1
- package/dist/bootstrap/loadEnv.js.map +1 -1
- package/dist/bootstrap/loadEnv.mjs +1 -1
- package/dist/chunk-5AIBE2QR.mjs +2 -0
- package/dist/{chunk-KWPUAQ7H.mjs → chunk-6CLMSPNA.mjs} +1 -1
- package/dist/chunk-6CLMSPNA.mjs.map +1 -0
- package/dist/{chunk-GLH4FCGA.mjs → chunk-77LPS2WP.mjs} +1 -1
- package/dist/chunk-77LPS2WP.mjs.map +1 -0
- package/dist/{chunk-4M5YKUGX.mjs → chunk-BCQP4DZP.mjs} +1 -1
- package/dist/chunk-BCQP4DZP.mjs.map +1 -0
- package/dist/{chunk-XFI3OAJH.mjs → chunk-BJCWVCAY.mjs} +2 -2
- package/dist/chunk-BJCWVCAY.mjs.map +1 -0
- package/dist/{chunk-YVVGY7EA.mjs → chunk-BXBLPEWT.mjs} +2 -2
- package/dist/chunk-BXBLPEWT.mjs.map +1 -0
- package/dist/{chunk-UWPC5P4C.mjs → chunk-CHI4NRSH.mjs} +2 -2
- package/dist/chunk-CHI4NRSH.mjs.map +1 -0
- package/dist/{chunk-6I5SY5IL.mjs → chunk-DEB7FLUS.mjs} +2 -2
- package/dist/chunk-DEB7FLUS.mjs.map +1 -0
- package/dist/{chunk-DJGEQTVH.mjs → chunk-FQGSVSCT.mjs} +1 -1
- package/dist/chunk-FQGSVSCT.mjs.map +1 -0
- package/dist/{chunk-3RMN5A5C.mjs → chunk-KATLDJ7Z.mjs} +1 -1
- package/dist/chunk-KATLDJ7Z.mjs.map +1 -0
- package/dist/{chunk-NAGAOZDU.mjs → chunk-KUU3KDAE.mjs} +1 -1
- package/dist/chunk-KUU3KDAE.mjs.map +1 -0
- package/dist/{chunk-47OCM32X.mjs → chunk-Q7UFCVZL.mjs} +2 -2
- package/dist/chunk-Q7UFCVZL.mjs.map +1 -0
- package/dist/{chunk-QVM3SASI.mjs → chunk-QC2F7O3S.mjs} +2 -2
- package/dist/chunk-QC2F7O3S.mjs.map +1 -0
- package/dist/{chunk-BWCE2PU3.mjs → chunk-QYJ4DE3N.mjs} +1 -1
- package/dist/chunk-QYJ4DE3N.mjs.map +1 -0
- package/dist/{chunk-5A7S2KUP.mjs → chunk-R6PIHRXD.mjs} +1 -1
- package/dist/chunk-R6PIHRXD.mjs.map +1 -0
- package/dist/{chunk-5NCNVJD5.mjs → chunk-RQQKHSL6.mjs} +2 -2
- package/dist/chunk-RQQKHSL6.mjs.map +1 -0
- package/dist/{chunk-CCTUTTKF.mjs → chunk-S4LYVMED.mjs} +2 -2
- package/dist/chunk-S4LYVMED.mjs.map +1 -0
- package/dist/{chunk-ZBUBSPF6.mjs → chunk-SXUJOOQY.mjs} +1 -1
- package/dist/chunk-SXUJOOQY.mjs.map +1 -0
- package/dist/{chunk-RWJJP4OR.mjs → chunk-SYOEMO4R.mjs} +2 -2
- package/dist/chunk-SYOEMO4R.mjs.map +1 -0
- package/dist/{chunk-R4SUPDLH.mjs → chunk-TZXZ3UZS.mjs} +2 -2
- package/dist/chunk-TZXZ3UZS.mjs.map +1 -0
- package/dist/{chunk-P22KPISA.mjs → chunk-UV2LVAQV.mjs} +1 -1
- package/dist/chunk-UV2LVAQV.mjs.map +1 -0
- package/dist/{chunk-67SR2RRV.mjs → chunk-WXW36EYF.mjs} +2 -2
- package/dist/chunk-WXW36EYF.mjs.map +1 -0
- package/dist/{chunk-WTRDOPQV.mjs → chunk-ZJRAI4W5.mjs} +1 -1
- package/dist/chunk-ZJRAI4W5.mjs.map +1 -0
- package/dist/components/ButtonKit.js.map +1 -1
- package/dist/components/ButtonKit.mjs +1 -1
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +1 -1
- package/dist/config.js.map +1 -1
- package/dist/config.mjs +1 -1
- package/dist/environment/actions/development.js +1 -1
- package/dist/environment/actions/development.js.map +1 -1
- package/dist/environment/actions/development.mjs +1 -1
- package/dist/environment/bundler/bundle.js.map +1 -1
- package/dist/environment/bundler/bundle.mjs +1 -1
- package/dist/environment/bundler/shims.js.map +1 -1
- package/dist/environment/bundler/shims.mjs.map +1 -1
- package/dist/environment/cli.js +1 -1
- package/dist/environment/cli.js.map +1 -1
- package/dist/environment/cli.mjs +1 -1
- package/dist/environment/cli.mjs.map +1 -1
- package/dist/environment/common/config.js.map +1 -1
- package/dist/environment/common/config.mjs +1 -1
- package/dist/environment/common/logger.js.map +1 -1
- package/dist/environment/common/logger.mjs +1 -1
- package/dist/handlers/command-handler/CommandHandler.js.map +1 -1
- package/dist/handlers/command-handler/CommandHandler.mjs +1 -1
- package/dist/handlers/command-handler/functions/loadCommandsWithRest.js.map +1 -1
- package/dist/handlers/command-handler/functions/loadCommandsWithRest.mjs +1 -1
- package/dist/handlers/command-handler/functions/registerCommands.js.map +1 -1
- package/dist/handlers/command-handler/functions/registerCommands.mjs +1 -1
- package/dist/handlers/command-handler/typings.js.map +1 -1
- package/dist/handlers/command-handler/utils/areSlashCommandsDifferent.js.map +1 -1
- package/dist/handlers/command-handler/utils/areSlashCommandsDifferent.mjs +1 -1
- package/dist/handlers/command-handler/validations/devOnly.d.mts +1 -1
- package/dist/handlers/command-handler/validations/devOnly.d.ts +1 -1
- package/dist/handlers/command-handler/validations/devOnly.js.map +1 -1
- package/dist/handlers/command-handler/validations/devOnly.mjs +1 -1
- package/dist/handlers/command-handler/validations/index.js.map +1 -1
- package/dist/handlers/command-handler/validations/index.mjs +1 -1
- package/dist/handlers/command-handler/validations/permissions.d.mts +1 -1
- package/dist/handlers/command-handler/validations/permissions.d.ts +1 -1
- package/dist/handlers/command-handler/validations/permissions.js.map +1 -1
- package/dist/handlers/command-handler/validations/permissions.mjs +1 -1
- package/dist/handlers/event-handler/EventHandler.js.map +1 -1
- package/dist/handlers/event-handler/EventHandler.mjs +1 -1
- package/dist/handlers/event-handler/typings.js.map +1 -1
- package/dist/handlers/index.js.map +1 -1
- package/dist/handlers/index.mjs +1 -1
- package/dist/handlers/validation-handler/ValidationHandler.js.map +1 -1
- package/dist/handlers/validation-handler/ValidationHandler.mjs +1 -1
- package/dist/handlers/validation-handler/typings.js.map +1 -1
- package/dist/hooks/common.js.map +1 -1
- package/dist/hooks/common.mjs +1 -1
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +1 -1
- package/dist/hooks/response.js.map +1 -1
- package/dist/hooks/response.mjs +1 -1
- package/dist/hooks/useChannel.js.map +1 -1
- package/dist/hooks/useChannel.mjs +1 -1
- package/dist/hooks/useClient.js.map +1 -1
- package/dist/hooks/useClient.mjs +1 -1
- package/dist/hooks/useCommandData.js.map +1 -1
- package/dist/hooks/useCommandData.mjs +1 -1
- package/dist/hooks/useCommandKit.js.map +1 -1
- package/dist/hooks/useCommandKit.mjs +1 -1
- package/dist/hooks/useGuild.js.map +1 -1
- package/dist/hooks/useGuild.mjs +1 -1
- package/dist/hooks/useInteraction.js.map +1 -1
- package/dist/hooks/useInteraction.mjs +1 -1
- package/dist/hooks/useMember.js.map +1 -1
- package/dist/hooks/useMember.mjs +1 -1
- package/dist/hooks/useUser.js.map +1 -1
- package/dist/hooks/useUser.mjs +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/index.mjs.map +1 -1
- package/dist/typings.js.map +1 -1
- package/dist/utils/colors.js.map +1 -1
- package/dist/utils/colors.mjs +1 -1
- package/dist/utils/get-paths.js.map +1 -1
- package/dist/utils/get-paths.mjs +1 -1
- package/dist/utils/resolve-file-url.js.map +1 -1
- package/dist/utils/resolve-file-url.mjs +1 -1
- package/dist/utils/signal.js.map +1 -1
- package/dist/utils/signal.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-3RMN5A5C.mjs.map +0 -1
- package/dist/chunk-47OCM32X.mjs.map +0 -1
- package/dist/chunk-4M5YKUGX.mjs.map +0 -1
- package/dist/chunk-5A7S2KUP.mjs.map +0 -1
- package/dist/chunk-5NCNVJD5.mjs.map +0 -1
- package/dist/chunk-67SR2RRV.mjs.map +0 -1
- package/dist/chunk-6I5SY5IL.mjs.map +0 -1
- package/dist/chunk-BWCE2PU3.mjs.map +0 -1
- package/dist/chunk-CCTUTTKF.mjs.map +0 -1
- package/dist/chunk-DJGEQTVH.mjs.map +0 -1
- package/dist/chunk-GLH4FCGA.mjs.map +0 -1
- package/dist/chunk-KWPUAQ7H.mjs.map +0 -1
- package/dist/chunk-LVMZYYYQ.mjs +0 -2
- package/dist/chunk-NAGAOZDU.mjs.map +0 -1
- package/dist/chunk-P22KPISA.mjs.map +0 -1
- package/dist/chunk-QVM3SASI.mjs.map +0 -1
- package/dist/chunk-R4SUPDLH.mjs.map +0 -1
- package/dist/chunk-RWJJP4OR.mjs.map +0 -1
- package/dist/chunk-UWPC5P4C.mjs.map +0 -1
- package/dist/chunk-WTRDOPQV.mjs.map +0 -1
- package/dist/chunk-XFI3OAJH.mjs.map +0 -1
- package/dist/chunk-YVVGY7EA.mjs.map +0 -1
- package/dist/chunk-ZBUBSPF6.mjs.map +0 -1
- /package/dist/{chunk-LVMZYYYQ.mjs.map → chunk-5AIBE2QR.mjs.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{validations_default}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{validations_default}from"./chunk-5AIBE2QR.mjs";import{loadCommandsWithRest}from"./chunk-RQQKHSL6.mjs";import{registerCommands}from"./chunk-BXBLPEWT.mjs";import{getFilePaths}from"./chunk-77LPS2WP.mjs";import{toFileURL}from"./chunk-KATLDJ7Z.mjs";import{clone}from"./chunk-VURGPMLB.mjs";import{colors_default}from"./chunk-FQGSVSCT.mjs";import{__name,__require}from"./chunk-7KD7ZCH6.mjs";import{AsyncLocalStorage}from"async_hooks";var CommandHandler=class{static{__name(this,"CommandHandler")}#data;context=null;constructor({...options}){this.#data={...options,builtInValidations:[],commands:[]}}async init(){this.#data.enableHooks&&!this.context&&(this.context=new AsyncLocalStorage),await this.#buildCommands(),this.#buildBuiltInValidations();let devOnlyCommands=this.#data.commands.filter(cmd=>cmd.options?.devOnly);devOnlyCommands.length&&!this.#data.devGuildIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devGuildIds" have not been set.')),devOnlyCommands.length&&!this.#data.devUserIds.length&&!this.#data.devRoleIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devUserIds" or "devRoleIds" have not been set.')),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}),this.handleCommands()}async#buildCommands(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,commandFilePaths=(await getFilePaths(this.#data.commandsPath,!0)).filter(path=>allowedExtensions.test(path));for(let commandFilePath of commandFilePaths){let importedObj=await import(`${toFileURL(commandFilePath)}?t=${Date.now()}`),commandObj=clone(importedObj);typeof module<"u"&&typeof __require<"u"&&delete __require.cache[__require.resolve(commandFilePath)];let compactFilePath=commandFilePath.split(process.cwd())[1]||commandFilePath;if(commandObj.default&&(commandObj=commandObj.default),importedObj.default?commandObj.data=importedObj.default.data:commandObj.data=importedObj.data,!commandObj.data){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data".`));continue}if(!commandObj.data.name){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data.name".`));continue}if(!commandObj.run){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run".`));continue}if(typeof commandObj.run!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run" as a function.`));continue}commandObj.filePath=commandFilePath;let commandCategory=commandFilePath.split(this.#data.commandsPath)[1]?.replace(/\\\\|\\/g,"/").split("/")[1]||null;commandCategory&&allowedExtensions.test(commandCategory)?commandObj.category=null:commandObj.category=commandCategory,this.#data.commands.push(commandObj)}}#buildBuiltInValidations(){for(let builtInValidationFunction of validations_default)this.#data.builtInValidations.push(builtInValidationFunction)}handleCommands(){let areHooksEnabled=this.#data.enableHooks;this.#data.client.on("interactionCreate",async interaction=>{if(!interaction.isChatInputCommand()&&!interaction.isContextMenuCommand()&&!interaction.isAutocomplete())return;let isAutocomplete=interaction.isAutocomplete(),targetCommand=this.#data.commands.find(cmd=>cmd.data.name===interaction.commandName);if(!targetCommand)return;let{data,options,run,autocomplete,...rest}=targetCommand;if(isAutocomplete&&!autocomplete)return;let executor=__name(async()=>{let commandObj={data:targetCommand.data,options:targetCommand.options,...rest};if(this.#data.validationHandler){let canRun2=!0;for(let validationFunction of this.#data.validationHandler.validations)if(await validationFunction({interaction,commandObj,client:this.#data.client,handler:this.#data.commandkitInstance})){canRun2=!1;break}if(!canRun2)return}let canRun=!0;if(!this.#data.skipBuiltInValidations){for(let validation of this.#data.builtInValidations)if(validation({targetCommand,interaction,handlerData:this.#data})){canRun=!1;break}}if(!canRun)return;let command=targetCommand[isAutocomplete?"autocomplete":"run"];if(!areHooksEnabled){let context={interaction,client:this.#data.client,handler:this.#data.commandkitInstance};return await command(context)}return command()},"executor");return this.context?this.context.run({command:targetCommand.data,interaction},executor):executor()})}get commands(){return this.#data.commands}async reloadCommands(type){if(!this.#data.commandsPath)throw new Error(colors_default.red('Cannot reload commands as "commandsPath" was not provided when instantiating CommandKit.'));this.#data.commands=[],await this.#buildCommands(),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type})}};export{CommandHandler};
|
|
2
|
+
//# sourceMappingURL=chunk-Q7UFCVZL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/handlers/command-handler/CommandHandler.ts"],"sourcesContent":["import type {\n CommandHandlerData,\n CommandHandlerOptions,\n CommandKitInteraction,\n} from './typings';\nimport type { CommandFileObject, ReloadOptions } from '../../typings';\n\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { getFilePaths } from '../../utils/get-paths';\nimport { clone } from '../../utils/clone';\n\nimport loadCommandsWithRest from './functions/loadCommandsWithRest';\nimport registerCommands from './functions/registerCommands';\nimport builtInValidationsFunctions from './validations';\nimport colors from '../../utils/colors';\nimport { AsyncLocalStorage } from 'async_hooks';\nimport type { CommandData } from '../../types';\n\nexport interface hCommandContext {\n interaction: CommandKitInteraction;\n command: CommandData;\n}\n\n/**\n * A handler for client application commands.\n */\nexport class CommandHandler {\n #data: CommandHandlerData;\n context: AsyncLocalStorage<hCommandContext> | null = null;\n\n constructor({ ...options }: CommandHandlerOptions) {\n this.#data = {\n ...options,\n builtInValidations: [],\n commands: [],\n };\n }\n\n async init() {\n if (this.#data.enableHooks && !this.context) {\n this.context = new AsyncLocalStorage();\n }\n await this.#buildCommands();\n\n this.#buildBuiltInValidations();\n\n const devOnlyCommands = this.#data.commands.filter(\n (cmd) => cmd.options?.devOnly,\n );\n\n if (devOnlyCommands.length && !this.#data.devGuildIds.length) {\n process.emitWarning(\n colors.yellow(\n 'You have commands marked as \"devOnly\", but \"devGuildIds\" have not been set.',\n ),\n );\n }\n\n if (\n devOnlyCommands.length &&\n !this.#data.devUserIds.length &&\n !this.#data.devRoleIds.length\n ) {\n process.emitWarning(\n colors.yellow(\n 'You have commands marked as \"devOnly\", but \"devUserIds\" or \"devRoleIds\" have not been set.',\n ),\n );\n }\n\n if (this.#data.bulkRegister) {\n await loadCommandsWithRest({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n });\n } else {\n await registerCommands({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n });\n }\n\n this.handleCommands();\n }\n\n async #buildCommands() {\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n const paths = await getFilePaths(this.#data.commandsPath, true);\n\n const commandFilePaths = paths.filter((path) =>\n allowedExtensions.test(path),\n );\n\n for (const commandFilePath of commandFilePaths) {\n const modulePath = toFileURL(commandFilePath);\n\n const importedObj = await import(`${modulePath}?t=${Date.now()}`);\n let commandObj: CommandFileObject = clone(importedObj); // Make commandObj extensible\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(commandFilePath)];\n }\n\n const compactFilePath =\n commandFilePath.split(process.cwd())[1] || commandFilePath;\n\n if (commandObj.default)\n commandObj = commandObj.default as CommandFileObject;\n\n // Ensure builder properties\n if (importedObj.default) {\n commandObj.data = importedObj.default.data;\n } else {\n commandObj.data = importedObj.data;\n }\n\n if (!commandObj.data) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${compactFilePath} does not export \"data\".`,\n ),\n );\n continue;\n }\n\n if (!commandObj.data.name) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${compactFilePath} does not export \"data.name\".`,\n ),\n );\n continue;\n }\n\n if (!commandObj.run) {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${commandObj.data.name} does not export \"run\".`,\n ),\n );\n continue;\n }\n\n if (typeof commandObj.run !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Command file ${commandObj.data.name} does not export \"run\" as a function.`,\n ),\n );\n continue;\n }\n\n commandObj.filePath = commandFilePath;\n\n let commandCategory =\n commandFilePath\n .split(this.#data.commandsPath)[1]\n ?.replace(/\\\\\\\\|\\\\/g, '/')\n .split('/')[1] || null;\n\n if (commandCategory && allowedExtensions.test(commandCategory)) {\n commandObj.category = null;\n } else {\n commandObj.category = commandCategory;\n }\n\n this.#data.commands.push(commandObj);\n }\n }\n\n #buildBuiltInValidations() {\n for (const builtInValidationFunction of builtInValidationsFunctions) {\n this.#data.builtInValidations.push(builtInValidationFunction);\n }\n }\n\n handleCommands() {\n const areHooksEnabled = this.#data.enableHooks;\n\n this.#data.client.on('interactionCreate', async (interaction) => {\n if (\n !interaction.isChatInputCommand() &&\n !interaction.isContextMenuCommand() &&\n !interaction.isAutocomplete()\n )\n return;\n\n const isAutocomplete = interaction.isAutocomplete();\n\n const targetCommand = this.#data.commands.find(\n (cmd) => cmd.data.name === interaction.commandName,\n );\n\n if (!targetCommand) return;\n\n const { data, options, run, autocomplete, ...rest } = targetCommand;\n\n // Skip if autocomplete handler is not defined\n if (isAutocomplete && !autocomplete) return;\n\n const executor = async () => {\n const commandObj = {\n data: targetCommand.data,\n options: targetCommand.options,\n ...rest,\n };\n\n if (this.#data.validationHandler) {\n let canRun = true;\n\n for (const validationFunction of this.#data.validationHandler\n .validations) {\n const stopValidationLoop = await validationFunction({\n interaction,\n commandObj,\n client: this.#data.client,\n handler: this.#data.commandkitInstance,\n });\n\n if (stopValidationLoop) {\n canRun = false;\n break;\n }\n }\n\n if (!canRun) return;\n }\n\n let canRun = true;\n\n // If custom validations pass and !skipBuiltInValidations, run built-in CommandKit validation functions\n if (!this.#data.skipBuiltInValidations) {\n for (const validation of this.#data.builtInValidations) {\n const stopValidationLoop = validation({\n targetCommand,\n interaction,\n handlerData: this.#data,\n });\n\n if (stopValidationLoop) {\n canRun = false;\n break;\n }\n }\n }\n\n if (!canRun) return;\n\n const command = targetCommand[isAutocomplete ? 'autocomplete' : 'run']!;\n\n // if hooks are not enabled, pass the context to the command via its arguments\n if (!areHooksEnabled) {\n const context = {\n interaction,\n client: this.#data.client,\n handler: this.#data.commandkitInstance,\n };\n return await command(context);\n }\n\n // @ts-expect-error - context data is not passed when hooks are enabled\n return command();\n };\n\n if (this.context)\n return this.context.run(\n {\n command: targetCommand.data,\n interaction,\n },\n executor,\n );\n return executor();\n });\n }\n\n get commands() {\n return this.#data.commands;\n }\n\n async reloadCommands(type?: ReloadOptions) {\n if (!this.#data.commandsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload commands as \"commandsPath\" was not provided when instantiating CommandKit.',\n ),\n );\n }\n\n this.#data.commands = [];\n\n // Re-build commands tree\n await this.#buildCommands();\n\n if (this.#data.bulkRegister) {\n await loadCommandsWithRest({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n reloading: true,\n type,\n });\n } else {\n await registerCommands({\n client: this.#data.client,\n devGuildIds: this.#data.devGuildIds,\n commands: this.#data.commands,\n reloading: true,\n type,\n });\n }\n }\n}\n"],"mappings":"uYAeA,OAAS,sBAAyB,cAW3B,IAAM,eAAN,KAAqB,CA1B5B,MA0B4B,+BAC1B,MACA,QAAqD,KAErD,YAAY,CAAE,GAAG,OAAQ,EAA0B,CACjD,KAAK,MAAQ,CACX,GAAG,QACH,mBAAoB,CAAC,EACrB,SAAU,CAAC,CACb,CACF,CAEA,MAAM,MAAO,CACP,KAAK,MAAM,aAAe,CAAC,KAAK,UAClC,KAAK,QAAU,IAAI,mBAErB,MAAM,KAAK,eAAe,EAE1B,KAAK,yBAAyB,EAE9B,IAAM,gBAAkB,KAAK,MAAM,SAAS,OACzC,KAAQ,IAAI,SAAS,OACxB,EAEI,gBAAgB,QAAU,CAAC,KAAK,MAAM,YAAY,QACpD,QAAQ,YACN,eAAO,OACL,6EACF,CACF,EAIA,gBAAgB,QAChB,CAAC,KAAK,MAAM,WAAW,QACvB,CAAC,KAAK,MAAM,WAAW,QAEvB,QAAQ,YACN,eAAO,OACL,4FACF,CACF,EAGE,KAAK,MAAM,aACb,MAAM,qBAAqB,CACzB,OAAQ,KAAK,MAAM,OACnB,YAAa,KAAK,MAAM,YACxB,SAAU,KAAK,MAAM,QACvB,CAAC,EAED,MAAM,iBAAiB,CACrB,OAAQ,KAAK,MAAM,OACnB,YAAa,KAAK,MAAM,YACxB,SAAU,KAAK,MA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AAO,MAAM,QAAQ,OAAO,CAC9B,CAGA,OAAO,QAAQ,CACjB,EA9DiB,YAgEjB,OAAI,KAAK,QACA,KAAK,QAAQ,IAClB,CACE,QAAS,cAAc,KACvB,WACF,EACA,QACF,EACK,SAAS,CAClB,CAAC,CACH,CAEA,IAAI,UAAW,CACb,OAAO,KAAK,MAAM,QACpB,CAEA,MAAM,eAAe,KAAsB,CACzC,GAAI,CAAC,KAAK,MAAM,aACd,MAAM,IAAI,MACR,eAAO,IACL,0FACF,CACF,EAGF,KAAK,MAAM,SAAW,CAAC,EAGvB,MAAM,KAAK,eAAe,EAEtB,KAAK,MAAM,aACb,MAAM,qBAAqB,CACzB,OAAQ,KAAK,MAAM,OACnB,YAAa,KAAK,MAAM,YACxB,SAAU,KAAK,MAAM,SACrB,UAAW,GACX,IACF,CAAC,EAED,MAAM,iBAAiB,CACrB,OAAQ,KAAK,MAAM,OACnB,YAAa,KAAK,MAAM,YACxB,SAAU,KAAK,MAAM,SACrB,UAAW,GACX,IACF,CAAC,CAEL,CACF","names":["canRun"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getConfig}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{getConfig}from"./chunk-QYJ4DE3N.mjs";import{__name}from"./chunk-7KD7ZCH6.mjs";import{build}from"tsup";import{join}from"path";function bundle(mode){switch(mode){case"development":return buildDevelopment();default:throw new Error("Not implemented")}}__name(bundle,"bundle");function buildDevelopment(){let{watch}=getConfig(),outDir=join(process.cwd(),".commandkit");return build({clean:!0,format:["esm"],bundle:!1,dts:!1,skipNodeModulesBundle:!0,minify:!1,shims:!0,sourcemap:"inline",keepNames:!0,outDir:".commandkit",silent:!0,entry:["src"],watch,async onSuccess(){}}).then(()=>join(outDir,"client.mjs"))}__name(buildDevelopment,"buildDevelopment");export{bundle};
|
|
2
|
+
//# sourceMappingURL=chunk-QC2F7O3S.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/environment/bundler/bundle.ts"],"sourcesContent":["import { build } from 'tsup';\nimport { getConfig } from '../../config';\nimport { join } from 'path';\n\nexport function bundle(mode: 'development' | 'production') {\n switch (mode) {\n case 'development':\n return buildDevelopment();\n default:\n throw new Error('Not implemented');\n }\n}\n\nfunction buildDevelopment() {\n const { watch } = getConfig();\n\n const outDir = join(process.cwd(), '.commandkit');\n\n return build({\n clean: true,\n format: ['esm'],\n bundle: false,\n dts: false,\n skipNodeModulesBundle: true,\n minify: false,\n shims: true,\n sourcemap: 'inline',\n keepNames: true,\n outDir: '.commandkit',\n silent: true,\n entry: ['src'],\n watch,\n async onSuccess() {\n // return await injectShims('.commandkit', main, false, requirePolyfill);\n },\n }).then(() => {\n return join(outDir, 'client.mjs');\n });\n}\n"],"mappings":"qFAAA,OAAS,UAAa,OAEtB,OAAS,SAAY,OAEd,SAAS,OAAO,KAAoC,CACzD,OAAQ,KAAM,CACZ,IAAK,cACH,OAAO,iBAAiB,EAC1B,QACE,MAAM,IAAI,MAAM,iBAAiB,CACrC,CACF,CAPgB,wBAShB,SAAS,kBAAmB,CAC1B,GAAM,CAAE,KAAM,EAAI,UAAU,EAEtB,OAAS,KAAK,QAAQ,IAAI,EAAG,aAAa,EAEhD,OAAO,MAAM,CACX,MAAO,GACP,OAAQ,CAAC,KAAK,EACd,OAAQ,GACR,IAAK,GACL,sBAAuB,GACvB,OAAQ,GACR,MAAO,GACP,UAAW,SACX,UAAW,GACX,OAAQ,cACR,OAAQ,GACR,MAAO,CAAC,KAAK,EACb,MACA,MAAM,WAAY,CAElB,CACF,CAAC,EAAE,KAAK,IACC,KAAK,OAAQ,YAAY,CACjC,CACH,CAzBS","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{__name}from"./chunk-7KD7ZCH6.mjs";var globalConfig={envExtra:!0,outDir:"dist",watch:!0,clearRestartLogs:!0,minify:!1,sourcemap:!1,nodeOptions:[],antiCrash:!0,requirePolyfill:!0,token:process.env.DISCORD_TOKEN};function getConfig(){return globalConfig}__name(getConfig,"getConfig");var requiredProps=["clientOptions"];function defineConfig(config){for(let prop of requiredProps)if(!config[prop])throw new Error(`[CommandKit Config] Missing required config property: ${prop}`);return globalConfig={...globalConfig,...config},globalConfig}__name(defineConfig,"defineConfig");export{getConfig,defineConfig};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-QYJ4DE3N.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["import type { ClientOptions } from 'discord.js';\n\nexport interface CommandKitConfig {\n /**\n * The Discord client options.\n */\n clientOptions: ClientOptions;\n /**\n * The Discord bot token. Defaults to `process.env.DISCORD_TOKEN`.\n */\n token?: string;\n /**\n * Whether or not to use the watch mode. Defaults to `true`.\n */\n watch: boolean;\n /**\n * The output directory of the project. Defaults to `dist`.\n */\n outDir: string;\n /**\n * Whether or not to include extra env utilities. Defaults to `true`.\n */\n envExtra: boolean;\n /**\n * Node.js cli options.\n */\n nodeOptions: string[];\n /**\n * Whether or not to clear default restart logs. Defaults to `true`.\n */\n clearRestartLogs: boolean;\n /**\n * Whether or not to minify the output. Defaults to `false`.\n */\n minify: boolean;\n /**\n * Whether or not to include sourcemaps in production build. Defaults to `false`.\n */\n sourcemap: boolean | 'inline';\n /**\n * Whether or not to include anti-crash handler in production. Defaults to `true`.\n */\n antiCrash: boolean;\n /**\n * Whether or not to polyfill `require` function. Defaults to `true`.\n */\n requirePolyfill: boolean;\n}\n\nlet globalConfig: Partial<CommandKitConfig> = {\n envExtra: true,\n outDir: 'dist',\n watch: true,\n clearRestartLogs: true,\n minify: false,\n sourcemap: false,\n nodeOptions: [],\n antiCrash: true,\n requirePolyfill: true,\n token: process.env.DISCORD_TOKEN,\n};\n\nexport function getConfig(): CommandKitConfig {\n return globalConfig as CommandKitConfig;\n}\n\nconst requiredProps = ['clientOptions'] as const;\n\ntype R = (typeof requiredProps)[number];\n\ntype PartialConfig<T extends CommandKitConfig> = Partial<Omit<T, R>> &\n Pick<T, R>;\n\nexport function defineConfig(config: PartialConfig<CommandKitConfig>) {\n for (const prop of requiredProps) {\n if (!config[prop]) {\n throw new Error(\n `[CommandKit Config] Missing required config property: ${prop}`,\n );\n }\n }\n\n globalConfig = {\n ...globalConfig,\n ...config,\n };\n\n return globalConfig;\n}\n"],"mappings":"yCAiDA,IAAI,aAA0C,CAC5C,SAAU,GACV,OAAQ,OACR,MAAO,GACP,iBAAkB,GAClB,OAAQ,GACR,UAAW,GACX,YAAa,CAAC,EACd,UAAW,GACX,gBAAiB,GACjB,MAAO,QAAQ,IAAI,aACrB,EAEO,SAAS,WAA8B,CAC5C,OAAO,YACT,CAFgB,8BAIhB,IAAM,cAAgB,CAAC,eAAe,EAO/B,SAAS,aAAa,OAAyC,CACpE,QAAW,QAAQ,cACjB,GAAI,CAAC,OAAO,IAAI,EACd,MAAM,IAAI,MACR,yDAAyD,IAAI,EAC/D,EAIJ,oBAAe,CACb,GAAG,aACH,GAAG,MACL,EAEO,YACT,CAfgB","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{__name}from"./chunk-7KD7ZCH6.mjs";function devOnly_default({interaction,targetCommand,handlerData}){if(!interaction.isAutocomplete()&&targetCommand.options?.devOnly){if(interaction.inGuild()&&!handlerData.devGuildIds.includes(interaction.guildId))return interaction.reply({content:"\u274C This command can only be used inside development servers.",ephemeral:!0}),!0;let memberRoles=interaction.guild?.members.cache.get(interaction.user.id)?.roles.cache,hasDevRole=!1;if(memberRoles?.forEach(role=>{handlerData.devRoleIds.includes(role.id)&&(hasDevRole=!0)}),!(handlerData.devUserIds.includes(interaction.user.id)||hasDevRole))return interaction.reply({content:"\u274C This command can only be used by developers.",ephemeral:!0}),!0}}__name(devOnly_default,"default");export{devOnly_default};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-R6PIHRXD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/handlers/command-handler/validations/devOnly.ts"],"sourcesContent":["import type { BuiltInValidationParams } from '../typings';\n\nexport default function ({\n interaction,\n targetCommand,\n handlerData,\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n\n if (targetCommand.options?.devOnly) {\n if (\n interaction.inGuild() &&\n !handlerData.devGuildIds.includes(interaction.guildId)\n ) {\n interaction.reply({\n content: '❌ This command can only be used inside development servers.',\n ephemeral: true,\n });\n\n return true;\n }\n\n const guildMember = interaction.guild?.members.cache.get(\n interaction.user.id,\n );\n const memberRoles = guildMember?.roles.cache;\n\n let hasDevRole = false;\n\n memberRoles?.forEach((role) => {\n if (handlerData.devRoleIds.includes(role.id)) {\n hasDevRole = true;\n }\n });\n\n const isDevUser =\n handlerData.devUserIds.includes(interaction.user.id) || hasDevRole;\n\n if (!isDevUser) {\n interaction.reply({\n content: '❌ This command can only be used by developers.',\n ephemeral: true,\n });\n\n return true;\n }\n }\n}\n"],"mappings":"yCAEe,SAAR,gBAAkB,CACvB,YACA,cACA,WACF,EAA4B,CAC1B,GAAI,aAAY,eAAe,GAE3B,cAAc,SAAS,QAAS,CAClC,GACE,YAAY,QAAQ,GACpB,CAAC,YAAY,YAAY,SAAS,YAAY,OAAO,EAErD,mBAAY,MAAM,CAChB,QAAS,mEACT,UAAW,EACb,CAAC,EAEM,GAMT,IAAM,YAHc,YAAY,OAAO,QAAQ,MAAM,IACnD,YAAY,KAAK,EACnB,GACiC,MAAM,MAEnC,WAAa,GAWjB,GATA,aAAa,QAAS,MAAS,CACzB,YAAY,WAAW,SAAS,KAAK,EAAE,IACzC,WAAa,GAEjB,CAAC,EAKG,EAFF,YAAY,WAAW,SAAS,YAAY,KAAK,EAAE,GAAK,YAGxD,mBAAY,MAAM,CAChB,QAAS,sDACT,UAAW,EACb,CAAC,EAEM,EAEX,CACF,CA7CO","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{colors_default}from"./chunk-
|
|
1
|
+
import{colors_default}from"./chunk-FQGSVSCT.mjs";import{__name}from"./chunk-7KD7ZCH6.mjs";async function loadCommandsWithRest(props){if(props.reloading)if(props.client.isReady())await handleLoading(props.client,props.commands,props.devGuildIds,props.reloading,props.type);else throw new Error(colors_default.red("Cannot reload commands when client is not ready."));else props.client.once("ready",async c=>{await handleLoading(c,props.commands,props.devGuildIds,props.reloading,props.type)})}__name(loadCommandsWithRest,"loadCommandsWithRest");async function handleLoading(client,commands,devGuildIds,reloading,type){commands=commands.filter(cmd=>!cmd.options?.deleted);let devOnlyCommands=commands.filter(cmd=>cmd.options?.devOnly),globalCommands=commands.filter(cmd=>!cmd.options?.devOnly);type==="dev"?await loadDevCommands(client,devOnlyCommands,devGuildIds,reloading):type==="global"?await loadGlobalCommands(client,globalCommands,reloading):(await loadDevCommands(client,devOnlyCommands,devGuildIds,reloading),await loadGlobalCommands(client,globalCommands,reloading))}__name(handleLoading,"handleLoading");async function loadGlobalCommands(client,commands,reloading){let requestBody=commands.map(cmd=>cmd.data);await client.application.commands.set(requestBody).catch(error=>{throw new Error(colors_default.red(`Error ${reloading?"reloading":"loading"} global application commands.
|
|
2
2
|
`),error)}),console.log(colors_default.green(`${reloading?"Reloaded":"Loaded"} ${requestBody.length} global commands.`))}__name(loadGlobalCommands,"loadGlobalCommands");async function loadDevCommands(client,commands,guildIds,reloading){let requestBody=commands.map(cmd=>cmd.data);for(let guildId of guildIds){let targetGuild=client.guilds.cache.get(guildId)||await client.guilds.fetch(guildId);if(!targetGuild){process.emitWarning(`Cannot ${reloading?"reload":"load"} commands in guild "${guildId}" - guild doesn't exist or client isn't part of the guild.`);continue}await targetGuild.commands.set(requestBody).catch(error=>{throw new Error(colors_default.red(`Error ${reloading?"reloading":"loading"} developer application commands in guild "${targetGuild?.name||guildId}".
|
|
3
3
|
`),error)}),console.log(colors_default.green(`${reloading?"Reloaded":"Loaded"} ${requestBody.length} developer commands in guild "${targetGuild.name}".`))}}__name(loadDevCommands,"loadDevCommands");export{loadCommandsWithRest};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-RQQKHSL6.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/handlers/command-handler/functions/loadCommandsWithRest.ts"],"sourcesContent":["import type { ApplicationCommandDataResolvable, Client } from 'discord.js';\nimport type { CommandFileObject, ReloadOptions } from '../../../typings';\n\nimport colors from '../../../utils/colors';\n\ntype LoadCommandsWithRestProps = {\n /**\n * The main client.\n */\n client: Client;\n\n /**\n * An array of command objects.\n */\n commands: CommandFileObject[];\n\n /**\n * An array of developer guild IDs.\n */\n devGuildIds: string[];\n\n /**\n * A boolean indicating whether these commands are reloading.\n */\n reloading?: boolean;\n\n /**\n * A type for reloading the commands (if this is reloading).\n */\n type?: ReloadOptions;\n};\n\n/**\n * Use REST to load commands.\n * @param props - Options for loading commands.\n */\nexport default async function loadCommandsWithRest(\n props: LoadCommandsWithRestProps,\n) {\n if (props.reloading) {\n if (props.client.isReady()) {\n await handleLoading(\n props.client,\n props.commands,\n props.devGuildIds,\n props.reloading,\n props.type,\n );\n } else {\n throw new Error(\n colors.red(`Cannot reload commands when client is not ready.`),\n );\n }\n } else {\n props.client.once('ready', async (c) => {\n await handleLoading(\n c,\n props.commands,\n props.devGuildIds,\n props.reloading,\n props.type,\n );\n });\n }\n}\n\n/**\n * Handles loading commands.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param devGuildIds - An array of developer guild IDs.\n * @param reloading - A boolean indicating whether this is reloading.\n * @param type - A type for reloading the commands (if this is reloading).\n */\nasync function handleLoading(\n client: Client<true>,\n commands: CommandFileObject[],\n devGuildIds: string[],\n reloading?: boolean,\n type?: ReloadOptions,\n) {\n commands = commands.filter((cmd) => !cmd.options?.deleted);\n const devOnlyCommands = commands.filter((cmd) => cmd.options?.devOnly);\n const globalCommands = commands.filter((cmd) => !cmd.options?.devOnly);\n\n if (type === 'dev') {\n await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);\n } else if (type === 'global') {\n await loadGlobalCommands(client, globalCommands, reloading);\n } else {\n await loadDevCommands(client, devOnlyCommands, devGuildIds, reloading);\n await loadGlobalCommands(client, globalCommands, reloading);\n }\n}\n\n/**\n * Load commands globally.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param reloading - A boolean indicating whether the commands are reloading.\n */\nasync function loadGlobalCommands(\n client: Client<true>,\n commands: CommandFileObject[],\n reloading?: boolean,\n) {\n const requestBody = commands.map((cmd) => cmd.data);\n\n await client.application.commands\n .set(requestBody as ApplicationCommandDataResolvable[])\n .catch((error) => {\n throw new Error(\n colors.red(\n `Error ${\n reloading ? 'reloading' : 'loading'\n } global application commands.\\n`,\n ),\n error,\n );\n });\n\n console.log(\n colors.green(\n `${reloading ? 'Reloaded' : 'Loaded'} ${\n requestBody.length\n } global commands.`,\n ),\n );\n}\n\n/**\n * Load commands for dev guilds.\n * @param client - The discord.js client instance.\n * @param commands - An array of command file objects.\n * @param guildIds - An array of developer guild IDs.\n * @param reloading - A boolean indicating whether the commands are reloading.\n */\nasync function loadDevCommands(\n client: Client<true>,\n commands: CommandFileObject[],\n guildIds: string[],\n reloading?: boolean,\n) {\n const requestBody = commands.map((cmd) => cmd.data);\n\n for (const guildId of guildIds) {\n const targetGuild =\n client.guilds.cache.get(guildId) || (await client.guilds.fetch(guildId));\n\n if (!targetGuild) {\n process.emitWarning(\n `Cannot ${\n reloading ? 'reload' : 'load'\n } commands in guild \"${guildId}\" - guild doesn't exist or client isn't part of the guild.`,\n );\n\n continue;\n }\n\n await targetGuild.commands\n .set(requestBody as ApplicationCommandDataResolvable[])\n .catch((error) => {\n throw new Error(\n colors.red(\n `Error ${\n reloading ? 'reloading' : 'loading'\n } developer application commands in guild \"${\n targetGuild?.name || guildId\n }\".\\n`,\n ),\n error,\n );\n });\n\n console.log(\n colors.green(\n `${reloading ? 'Reloaded' : 'Loaded'} ${\n requestBody.length\n } developer commands in guild \"${targetGuild.name}\".`,\n ),\n );\n }\n}\n"],"mappings":"0FAoCA,eAAO,qBACL,MACA,CACA,GAAI,MAAM,UACR,GAAI,MAAM,OAAO,QAAQ,EACvB,MAAM,cACJ,MAAM,OACN,MAAM,SACN,MAAM,YACN,MAAM,UACN,MAAM,IACR,MAEA,OAAM,IAAI,MACR,eAAO,IAAI,kDAAkD,CAC/D,OAGF,MAAM,OAAO,KAAK,QAAS,MAAO,GAAM,CACtC,MAAM,cACJ,EACA,MAAM,SACN,MAAM,YACN,MAAM,UACN,MAAM,IACR,CACF,CAAC,CAEL,CA5B8B,oDAsC9B,eAAe,cACb,OACA,SACA,YACA,UACA,KACA,CACA,SAAW,SAAS,OAAQ,KAAQ,CAAC,IAAI,SAAS,OAAO,EACzD,IAAM,gBAAkB,SAAS,OAAQ,KAAQ,IAAI,SAAS,OAAO,EAC/D,eAAiB,SAAS,OAAQ,KAAQ,CAAC,IAAI,SAAS,OAAO,EAEjE,OAAS,MACX,MAAM,gBAAgB,OAAQ,gBAAiB,YAAa,SAAS,EAC5D,OAAS,SAClB,MAAM,mBAAmB,OAAQ,eAAgB,SAAS,GAE1D,MAAM,gBAAgB,OAAQ,gBAAiB,YAAa,SAAS,EACrE,MAAM,mBAAmB,OAAQ,eAAgB,SAAS,EAE9D,CAnBe,sCA2Bf,eAAe,mBACb,OACA,SACA,UACA,CACA,IAAM,YAAc,SAAS,IAAK,KAAQ,IAAI,IAAI,EAElD,MAAM,OAAO,YAAY,SACtB,IAAI,WAAiD,EACrD,MAAO,OAAU,CAChB,MAAM,IAAI,MACR,eAAO,IACL,SACE,UAAY,YAAc,SAC5B;AAAA,CACF,EACA,KACF,CACF,CAAC,EAEH,QAAQ,IACN,eAAO,MACL,GAAG,UAAY,WAAa,QAAQ,IAClC,YAAY,MACd,mBACF,CACF,CACF,CA3Be,gDAoCf,eAAe,gBACb,OACA,SACA,SACA,UACA,CACA,IAAM,YAAc,SAAS,IAAK,KAAQ,IAAI,IAAI,EAElD,QAAW,WAAW,SAAU,CAC9B,IAAM,YACJ,OAAO,OAAO,MAAM,IAAI,OAAO,GAAM,MAAM,OAAO,OAAO,MAAM,OAAO,EAExE,GAAI,CAAC,YAAa,CAChB,QAAQ,YACN,UACE,UAAY,SAAW,MACzB,uBAAuB,OAAO,4DAChC,EAEA,QACF,CAEA,MAAM,YAAY,SACf,IAAI,WAAiD,EACrD,MAAO,OAAU,CAChB,MAAM,IAAI,MACR,eAAO,IACL,SACE,UAAY,YAAc,SAC5B,6CACE,aAAa,MAAQ,OACvB;AAAA,CACF,EACA,KACF,CACF,CAAC,EAEH,QAAQ,IACN,eAAO,MACL,GAAG,UAAY,WAAa,QAAQ,IAClC,YAAY,MACd,iCAAiC,YAAY,IAAI,IACnD,CACF,CACF,CACF,CA7Ce","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CommandKit}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{CommandKit}from"./chunk-CHI4NRSH.mjs";import{__name}from"./chunk-7KD7ZCH6.mjs";function useCommandKit(){let kit=getCommandKit();if(!kit)throw new Error("CommandKit is not initialized.");return kit}__name(useCommandKit,"useCommandKit");function useClient(){return useCommandKit().client}__name(useClient,"useClient");function useInteraction(){let data=getContext().getStore();if(!data)throw prepareHookInvocationError("useInteraction");return data.interaction}__name(useInteraction,"useInteraction");async function response(data){let interaction=useInteraction();interaction.isAutocomplete()||(interaction.replied||interaction.deferred?await interaction.editReply(data):interaction.isMessageComponent()?await interaction.update(data):await interaction.reply(data))}__name(response,"response");function useChannel(){let data=getContext().getStore();if(!data)throw prepareHookInvocationError("useChannel");return data.interaction.channel}__name(useChannel,"useChannel");function useCommandData(){let data=getContext().getStore();if(!data)throw prepareHookInvocationError("useCommandData");return data.command}__name(useCommandData,"useCommandData");function useGuild(){let data=getContext().getStore();if(!data)throw prepareHookInvocationError("useGuild");return data.interaction.guild}__name(useGuild,"useGuild");function useMember(){let data=getContext().getStore();if(!data)throw prepareHookInvocationError("useMember");return data.interaction.member}__name(useMember,"useMember");function useUser(){let data=getContext().getStore();if(!data)throw prepareHookInvocationError("useUser");return data.interaction.user}__name(useUser,"useUser");var version="0.1.10-dev.20240202061201";function getCommandKit(){return CommandKit._instance}__name(getCommandKit,"getCommandKit");function getCommandHandler(){let handler=getCommandKit()?.commandHandler;if(!handler)throw new Error("CommandKit is not initialized.");return handler}__name(getCommandHandler,"getCommandHandler");function getContext(){let info=getCommandHandler().context;if(!info)throw new Error("Context is not available, did you forget to enable hooks?");return info}__name(getContext,"getContext");function prepareHookInvocationError(name){return new Error(`Cannot invoke hook "${name}" outside of a command.`)}__name(prepareHookInvocationError,"prepareHookInvocationError");export{getCommandKit,getCommandHandler,getContext,prepareHookInvocationError,useCommandKit,useClient,useInteraction,response,useChannel,useCommandData,useGuild,useMember,useUser,version};
|
|
2
|
+
//# sourceMappingURL=chunk-S4LYVMED.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/useCommandKit.ts","../src/hooks/useClient.ts","../src/hooks/useInteraction.ts","../src/hooks/response.ts","../src/hooks/useChannel.ts","../src/hooks/useCommandData.ts","../src/hooks/useGuild.ts","../src/hooks/useMember.ts","../src/hooks/useUser.ts","../src/index.ts","../src/hooks/common.ts"],"sourcesContent":["import { getCommandKit } from './common';\n\nexport function useCommandKit() {\n const kit = getCommandKit();\n if (!kit) throw new Error('CommandKit is not initialized.');\n\n return kit;\n}\n","import { useCommandKit } from './useCommandKit';\n\nexport function useClient() {\n return useCommandKit().client;\n}\n","import { getContext, prepareHookInvocationError } from './common';\nimport { CommandKitInteraction } from '../handlers/command-handler/typings';\n\nexport function useInteraction<\n T extends CommandKitInteraction = CommandKitInteraction,\n>(): T {\n const data = getContext().getStore();\n\n if (!data) throw prepareHookInvocationError('useInteraction');\n\n return data.interaction as T;\n}\n","// this is partially based on sapphire's safelyReplyToInteraction helper\n\nimport type {\n ChatInputCommandInteraction,\n MessageComponentInteraction,\n PartialTextBasedChannelFields,\n} from 'discord.js';\nimport { useInteraction } from './useInteraction';\nimport { CommandKitInteraction } from '../handlers/command-handler/typings';\n\ntype ChatInputReplyData = Parameters<ChatInputCommandInteraction['reply']>[0];\ntype UpdateData = Parameters<MessageComponentInteraction['update']>[0];\ntype MessageData =\n | Parameters<PartialTextBasedChannelFields['send']>[0]\n | ChatInputReplyData;\n\nexport async function response(data: MessageData) {\n const interaction = useInteraction() as\n | CommandKitInteraction\n | MessageComponentInteraction;\n\n if (interaction.isAutocomplete()) return;\n\n if (interaction.replied || interaction.deferred) {\n await interaction.editReply(data);\n } else if (interaction.isMessageComponent()) {\n // TODO: this is not yet allowed in command handler\n await interaction.update(data as UpdateData);\n } else {\n await interaction.reply(data as ChatInputReplyData);\n }\n\n // TODO: handle message based commands\n}\n","import type { TextBasedChannel } from 'discord.js';\nimport { getContext, prepareHookInvocationError } from './common';\n\nexport function useChannel(): TextBasedChannel | null {\n const data = getContext().getStore();\n\n if (!data) throw prepareHookInvocationError('useChannel');\n\n return data.interaction.channel;\n}\n","import { getContext, prepareHookInvocationError } from './common';\n\nexport function useCommandData() {\n const data = getContext().getStore();\n\n if (!data) throw prepareHookInvocationError('useCommandData');\n\n return data.command;\n}\n","import type { Guild } from 'discord.js';\nimport { getContext, prepareHookInvocationError } from './common';\n\nexport function useGuild(): Guild | null {\n const data = getContext().getStore();\n\n if (!data) throw prepareHookInvocationError('useGuild');\n\n return data.interaction.guild;\n}\n","import type { APIInteractionGuildMember, GuildMember } from 'discord.js';\nimport { getContext, prepareHookInvocationError } from './common';\n\nexport function useMember(): GuildMember | APIInteractionGuildMember | null {\n const data = getContext().getStore();\n\n if (!data) throw prepareHookInvocationError('useMember');\n\n return data.interaction.member;\n}\n","import type { User } from 'discord.js';\nimport { getContext, prepareHookInvocationError } from './common';\n\nexport function useUser(): User {\n const data = getContext().getStore();\n\n if (!data) throw prepareHookInvocationError('useUser');\n\n return data.interaction.user;\n}\n","export * from './CommandKit';\nexport * from './components';\nexport * from './config';\nexport * from './utils/signal';\nexport * from './hooks';\nexport { client } from './bootstrap/client';\nexport type * from './types';\n\n/**\n * The current version of CommandKit.\n */\n// Note to developers: This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '0.1.10-dev.20240202061201';\n","import { CommandKit } from '..';\n\nexport function getCommandKit() {\n return CommandKit._instance;\n}\n\nexport function getCommandHandler() {\n const handler = getCommandKit()?.commandHandler;\n\n if (!handler) {\n throw new Error('CommandKit is not initialized.');\n }\n\n return handler;\n}\n\nexport function getContext() {\n const info = getCommandHandler().context;\n if (!info) {\n throw new Error(\n 'Context is not available, did you forget to enable hooks?',\n );\n }\n\n return info;\n}\n\nexport function prepareHookInvocationError(name: string) {\n return new Error(`Cannot invoke hook \"${name}\" outside of a command.`);\n}\n"],"mappings":"sFAEO,SAAS,eAAgB,CAC9B,IAAM,IAAM,cAAc,EAC1B,GAAI,CAAC,IAAK,MAAM,IAAI,MAAM,gCAAgC,EAE1D,OAAO,GACT,CALgB,sCCAT,SAAS,WAAY,CAC1B,OAAO,cAAc,EAAE,MACzB,CAFgB,8BCCT,SAAS,gBAET,CACL,IAAM,KAAO,WAAW,EAAE,SAAS,EAEnC,GAAI,CAAC,KAAM,MAAM,2BAA2B,gBAAgB,EAE5D,OAAO,KAAK,WACd,CARgB,wCCahB,eAAsB,SAAS,KAAmB,CAChD,IAAM,YAAc,eAAe,EAI/B,YAAY,eAAe,IAE3B,YAAY,SAAW,YAAY,SACrC,MAAM,YAAY,UAAU,IAAI,EACvB,YAAY,mBAAmB,EAExC,MAAM,YAAY,OAAO,IAAkB,EAE3C,MAAM,YAAY,MAAM,IAA0B,EAItD,CAjBsB,4BCbf,SAAS,YAAsC,CACpD,IAAM,KAAO,WAAW,EAAE,SAAS,EAEnC,GAAI,CAAC,KAAM,MAAM,2BAA2B,YAAY,EAExD,OAAO,KAAK,YAAY,OAC1B,CANgB,gCCDT,SAAS,gBAAiB,CAC/B,IAAM,KAAO,WAAW,EAAE,SAAS,EAEnC,GAAI,CAAC,KAAM,MAAM,2BAA2B,gBAAgB,EAE5D,OAAO,KAAK,OACd,CANgB,wCCCT,SAAS,UAAyB,CACvC,IAAM,KAAO,WAAW,EAAE,SAAS,EAEnC,GAAI,CAAC,KAAM,MAAM,2BAA2B,UAAU,EAEtD,OAAO,KAAK,YAAY,KAC1B,CANgB,4BCAT,SAAS,WAA4D,CAC1E,IAAM,KAAO,WAAW,EAAE,SAAS,EAEnC,GAAI,CAAC,KAAM,MAAM,2BAA2B,WAAW,EAEvD,OAAO,KAAK,YAAY,MAC1B,CANgB,8BCAT,SAAS,SAAgB,CAC9B,IAAM,KAAO,WAAW,EAAE,SAAS,EAEnC,GAAI,CAAC,KAAM,MAAM,2BAA2B,SAAS,EAErD,OAAO,KAAK,YAAY,IAC1B,CANgB,0BCUT,IAAM,QAAkB,4BCXxB,SAAS,eAAgB,CAC9B,OAAO,WAAW,SACpB,CAFgB,sCAIT,SAAS,mBAAoB,CAClC,IAAM,QAAU,cAAc,GAAG,eAEjC,GAAI,CAAC,QACH,MAAM,IAAI,MAAM,gCAAgC,EAGlD,OAAO,OACT,CARgB,8CAUT,SAAS,YAAa,CAC3B,IAAM,KAAO,kBAAkB,EAAE,QACjC,GAAI,CAAC,KACH,MAAM,IAAI,MACR,2DACF,EAGF,OAAO,IACT,CATgB,gCAWT,SAAS,2BAA2B,KAAc,CACvD,OAAO,IAAI,MAAM,uBAAuB,IAAI,yBAAyB,CACvE,CAFgB","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{__name}from"./chunk-7KD7ZCH6.mjs";import{EmbedBuilder}from"discord.js";function permissions_default({interaction,targetCommand}){if(interaction.isAutocomplete())return;let userPermissions=interaction.memberPermissions,userPermissionsRequired=targetCommand.options?.userPermissions,missingUserPermissions=[];typeof userPermissionsRequired=="string"&&(userPermissionsRequired=[userPermissionsRequired]);let botPermissions=interaction.guild?.members.me?.permissions,botPermissionsRequired=targetCommand.options?.botPermissions,missingBotPermissions=[];if(typeof botPermissionsRequired=="string"&&(botPermissionsRequired=[botPermissionsRequired]),!userPermissionsRequired?.length&&!botPermissionsRequired?.length)return;if(userPermissions&&userPermissionsRequired)for(let permission of userPermissionsRequired)userPermissions.has(permission)||missingUserPermissions.push(permission);if(botPermissions&&botPermissionsRequired)for(let permission of botPermissionsRequired)botPermissions.has(permission)||missingBotPermissions.push(permission);if(!missingUserPermissions.length&&!missingBotPermissions.length)return;let pattern=/([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;missingUserPermissions=missingUserPermissions.map(str=>str.replace(pattern,"$1$3 $2$4")),missingBotPermissions=missingBotPermissions.map(str=>str.replace(pattern,"$1$3 $2$4"));let embedDescription="",formatter=new Intl.ListFormat("en",{style:"long",type:"conjunction"}),getPermissionWord=__name(permissions=>permissions.length===1?"permission":"permissions","getPermissionWord");if(missingUserPermissions.length){let formattedPermissions=missingUserPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- You must have the ${permissionsString} ${getPermissionWord(missingUserPermissions)} to be able to run this command.
|
|
2
2
|
`}if(missingBotPermissions.length){let formattedPermissions=missingBotPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- I must have the ${permissionsString} ${getPermissionWord(missingBotPermissions)} to be able to execute this command.
|
|
3
3
|
`}let embed=new EmbedBuilder().setTitle(":x: Missing permissions!").setDescription(embedDescription).setColor("Red");return interaction.reply({embeds:[embed],ephemeral:!0}),!0}__name(permissions_default,"default");export{permissions_default};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-SXUJOOQY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/handlers/command-handler/validations/permissions.ts"],"sourcesContent":["import type { BuiltInValidationParams } from '../typings';\nimport { EmbedBuilder } from 'discord.js';\n\nexport default function ({\n interaction,\n targetCommand,\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n const userPermissions = interaction.memberPermissions;\n let userPermissionsRequired = targetCommand.options?.userPermissions;\n let missingUserPermissions: string[] = [];\n\n if (typeof userPermissionsRequired === 'string') {\n userPermissionsRequired = [userPermissionsRequired];\n }\n\n const botPermissions = interaction.guild?.members.me?.permissions;\n let botPermissionsRequired = targetCommand.options?.botPermissions;\n let missingBotPermissions: string[] = [];\n\n if (typeof botPermissionsRequired === 'string') {\n botPermissionsRequired = [botPermissionsRequired];\n }\n\n if (!userPermissionsRequired?.length && !botPermissionsRequired?.length) {\n return;\n }\n\n if (userPermissions && userPermissionsRequired) {\n for (const permission of userPermissionsRequired) {\n const hasPermission = userPermissions.has(permission);\n\n if (!hasPermission) {\n missingUserPermissions.push(permission);\n }\n }\n }\n\n if (botPermissions && botPermissionsRequired) {\n for (const permission of botPermissionsRequired) {\n const hasPermission = botPermissions.has(permission);\n\n if (!hasPermission) {\n missingBotPermissions.push(permission);\n }\n }\n }\n\n if (!missingUserPermissions.length && !missingBotPermissions.length) {\n return;\n }\n\n // Fix casing. e.g. KickMembers -> Kick Members\n const pattern = /([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;\n\n missingUserPermissions = missingUserPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4'),\n );\n missingBotPermissions = missingBotPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4'),\n );\n\n let embedDescription = '';\n\n const formatter = new Intl.ListFormat('en', {\n style: 'long',\n type: 'conjunction',\n });\n\n const getPermissionWord = (permissions: string[]) =>\n permissions.length === 1 ? 'permission' : 'permissions';\n\n if (missingUserPermissions.length) {\n const formattedPermissions = missingUserPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- You must have the ${permissionsString} ${getPermissionWord(\n missingUserPermissions,\n )} to be able to run this command.\\n`;\n }\n\n if (missingBotPermissions.length) {\n const formattedPermissions = missingBotPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- I must have the ${permissionsString} ${getPermissionWord(\n missingBotPermissions,\n )} to be able to execute this command.\\n`;\n }\n\n const embed = new EmbedBuilder()\n .setTitle(`:x: Missing permissions!`)\n .setDescription(embedDescription)\n .setColor('Red');\n\n interaction.reply({ embeds: [embed], ephemeral: true });\n return true;\n}\n"],"mappings":"yCACA,OAAS,iBAAoB,aAEd,SAAR,oBAAkB,CACvB,YACA,aACF,EAA4B,CAC1B,GAAI,YAAY,eAAe,EAAG,OAClC,IAAM,gBAAkB,YAAY,kBAChC,wBAA0B,cAAc,SAAS,gBACjD,uBAAmC,CAAC,EAEpC,OAAO,yBAA4B,WACrC,wBAA0B,CAAC,uBAAuB,GAGpD,IAAM,eAAiB,YAAY,OAAO,QAAQ,IAAI,YAClD,uBAAyB,cAAc,SAAS,eAChD,sBAAkC,CAAC,EAMvC,GAJI,OAAO,wBAA2B,WACpC,uBAAyB,CAAC,sBAAsB,GAG9C,CAAC,yBAAyB,QAAU,CAAC,wBAAwB,OAC/D,OAGF,GAAI,iBAAmB,wBACrB,QAAW,cAAc,wBACD,gBAAgB,IAAI,UAAU,GAGlD,uBAAuB,KAAK,UAAU,EAK5C,GAAI,gBAAkB,uBACpB,QAAW,cAAc,uBACD,eAAe,IAAI,UAAU,GAGjD,sBAAsB,KAAK,UAAU,EAK3C,GAAI,CAAC,uBAAuB,QAAU,CAAC,sBAAsB,OAC3D,OAIF,IAAM,QAAU,uCAEhB,uBAAyB,uBAAuB,IAAK,KACnD,IAAI,QAAQ,QAAS,WAAW,CAClC,EACA,sBAAwB,sBAAsB,IAAK,KACjD,IAAI,QAAQ,QAAS,WAAW,CAClC,EAEA,IAAI,iBAAmB,GAEjB,UAAY,IAAI,KAAK,WAAW,KAAM,CAC1C,MAAO,OACP,KAAM,aACR,CAAC,EAEK,kBAAoB,OAAC,aACzB,YAAY,SAAW,EAAI,aAAe,cADlB,qBAG1B,GAAI,uBAAuB,OAAQ,CACjC,IAAM,qBAAuB,uBAAuB,IAAK,GAAM,KAAK,CAAC,IAAI,EACnE,kBAAoB,UAAU,OAAO,oBAAoB,EAE/D,kBAAoB,uBAAuB,iBAAiB,IAAI,kBAC9D,sBACF,CAAC;AAAA,CACH,CAEA,GAAI,sBAAsB,OAAQ,CAChC,IAAM,qBAAuB,sBAAsB,IAAK,GAAM,KAAK,CAAC,IAAI,EAClE,kBAAoB,UAAU,OAAO,oBAAoB,EAE/D,kBAAoB,qBAAqB,iBAAiB,IAAI,kBAC5D,qBACF,CAAC;AAAA,CACH,CAEA,IAAM,MAAQ,IAAI,aAAa,EAC5B,SAAS,0BAA0B,EACnC,eAAe,gBAAgB,EAC/B,SAAS,KAAK,EAEjB,mBAAY,MAAM,CAAE,OAAQ,CAAC,KAAK,EAAG,UAAW,EAAK,CAAC,EAC/C,EACT,CA9FO","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFilePaths,getFolderPaths}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{getFilePaths,getFolderPaths}from"./chunk-77LPS2WP.mjs";import{toFileURL}from"./chunk-KATLDJ7Z.mjs";import{clone}from"./chunk-VURGPMLB.mjs";import{colors_default}from"./chunk-FQGSVSCT.mjs";import{__name,__require}from"./chunk-7KD7ZCH6.mjs";var EventHandler=class{static{__name(this,"EventHandler")}#data;constructor({...options}){this.#data={...options,events:[]}}async init(){await this.#buildEvents(),this.#registerEvents()}async#buildEvents(){let eventFolderPaths=await getFolderPaths(this.#data.eventsPath);for(let eventFolderPath of eventFolderPaths){let eventName=eventFolderPath.replace(/\\\\|\\/g,"/").split("/").pop(),allowedExtensions=/\.(js|mjs|cjs|ts)$/i,eventFilePaths=(await getFilePaths(eventFolderPath,!0)).filter(path=>allowedExtensions.test(path)),eventObj={name:eventName,functions:[]};this.#data.events.push(eventObj);for(let eventFilePath of eventFilePaths){let importedFunction=(await import(`${toFileURL(eventFilePath)}?t=${Date.now()}`)).default,eventFunction=clone(importedFunction);typeof module<"u"&&typeof __require<"u"&&delete __require.cache[__require.resolve(eventFilePath)],eventFunction?.default&&(eventFunction=eventFunction.default);let compactFilePath=eventFilePath.split(process.cwd())[1]||eventFilePath;if(typeof eventFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Event file ${compactFilePath} does not export a function.`));continue}eventObj.functions.push(eventFunction)}}}#registerEvents(){let client=this.#data.client,handler=this.#data.commandKitInstance;for(let eventObj of this.#data.events)client.on(eventObj.name,async(...params)=>{for(let eventFunction of eventObj.functions)if(await eventFunction(...params,client,handler))break})}get events(){return this.#data.events}async reloadEvents(commandHandler){if(!this.#data.eventsPath)throw new Error(colors_default.red('Cannot reload events as "eventsPath" was not provided when instantiating CommandKit.'));this.#data.events=[],await this.#buildEvents(),this.#data.client.removeAllListeners(),this.#registerEvents(),commandHandler?.handleCommands()}};export{EventHandler};
|
|
2
|
+
//# sourceMappingURL=chunk-SYOEMO4R.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/handlers/event-handler/EventHandler.ts"],"sourcesContent":["import type { EventHandlerOptions, EventHandlerData } from './typings';\nimport type { CommandHandler } from '../command-handler/CommandHandler';\nimport { getFilePaths, getFolderPaths } from '../../utils/get-paths';\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { clone } from '../../utils/clone';\nimport colors from '../../utils/colors';\n\n/**\n * A handler for client events.\n */\nexport class EventHandler {\n #data: EventHandlerData;\n\n constructor({ ...options }: EventHandlerOptions) {\n this.#data = {\n ...options,\n events: [],\n };\n }\n\n async init() {\n await this.#buildEvents();\n this.#registerEvents();\n }\n\n async #buildEvents() {\n const eventFolderPaths = await getFolderPaths(this.#data.eventsPath);\n\n for (const eventFolderPath of eventFolderPaths) {\n const eventName = eventFolderPath\n .replace(/\\\\\\\\|\\\\/g, '/')\n .split('/')\n .pop() as string;\n\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n const eventPaths = await getFilePaths(eventFolderPath, true);\n\n const eventFilePaths = eventPaths.filter((path) =>\n allowedExtensions.test(path),\n );\n\n const eventObj = {\n name: eventName,\n functions: [] as Function[],\n };\n\n this.#data.events.push(eventObj);\n\n for (const eventFilePath of eventFilePaths) {\n const modulePath = toFileURL(eventFilePath);\n\n let importedFunction = (await import(`${modulePath}?t=${Date.now()}`))\n .default;\n let eventFunction = clone(importedFunction);\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(eventFilePath)];\n }\n\n if (eventFunction?.default) {\n eventFunction = eventFunction.default;\n }\n\n const compactFilePath =\n eventFilePath.split(process.cwd())[1] || eventFilePath;\n\n if (typeof eventFunction !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Event file ${compactFilePath} does not export a function.`,\n ),\n );\n continue;\n }\n\n eventObj.functions.push(eventFunction);\n }\n }\n }\n\n #registerEvents() {\n const client = this.#data.client;\n const handler = this.#data.commandKitInstance;\n\n for (const eventObj of this.#data.events) {\n client.on(eventObj.name, async (...params) => {\n for (const eventFunction of eventObj.functions) {\n const stopEventLoop = await eventFunction(...params, client, handler);\n\n if (stopEventLoop) {\n break;\n }\n }\n });\n }\n }\n\n get events() {\n return this.#data.events;\n }\n\n async reloadEvents(commandHandler?: CommandHandler) {\n if (!this.#data.eventsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload events as \"eventsPath\" was not provided when instantiating CommandKit.',\n ),\n );\n }\n\n this.#data.events = [];\n\n await this.#buildEvents();\n\n this.#data.client.removeAllListeners();\n\n this.#registerEvents();\n\n // Re-register \"interactionCreate\" event for application commands.\n commandHandler?.handleCommands();\n }\n}\n"],"mappings":"sPAUO,IAAM,aAAN,KAAmB,CAV1B,MAU0B,6BACxB,MAEA,YAAY,CAAE,GAAG,OAAQ,EAAwB,CAC/C,K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O,KAAK,MAAM,MACpB,CAEA,MAAM,aAAa,eAAiC,CAClD,GAAI,CAAC,KAAK,MAAM,WACd,MAAM,IAAI,MACR,eAAO,IACL,sFACF,CACF,EAGF,KAAK,MAAM,OAAS,CAAC,EAErB,MAAM,KAAK,aAAa,EAExB,KAAK,MAAM,OAAO,mBAAmB,EAErC,KAAK,gBAAgB,EAGrB,gBAAgB,eAAe,CACjC,CACF","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFilePaths}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{getFilePaths}from"./chunk-77LPS2WP.mjs";import{toFileURL}from"./chunk-KATLDJ7Z.mjs";import{clone}from"./chunk-VURGPMLB.mjs";import{colors_default}from"./chunk-FQGSVSCT.mjs";import{__name,__require}from"./chunk-7KD7ZCH6.mjs";var ValidationHandler=class{static{__name(this,"ValidationHandler")}#data;constructor({...options}){this.#data={...options,validations:[]}}async init(){this.#data.validations=await this.#buildValidations()}async#buildValidations(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,validationFilePaths=(await getFilePaths(this.#data.validationsPath,!0)).filter(path=>allowedExtensions.test(path)),validationFunctions=[];for(let validationFilePath of validationFilePaths){let importedFunction=(await import(`${toFileURL(validationFilePath)}?t=${Date.now()}`)).default,validationFunction=clone(importedFunction);typeof module<"u"&&typeof __require<"u"&&delete __require.cache[__require.resolve(validationFilePath)],validationFunction?.default&&(validationFunction=validationFunction.default);let compactFilePath=validationFilePath.split(process.cwd())[1]||validationFilePath;if(typeof validationFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Validation file ${compactFilePath} does not export a function.`));continue}validationFunctions.push(validationFunction)}return validationFunctions}get validations(){return this.#data.validations}async reloadValidations(){if(!this.#data.validationsPath)throw new Error(colors_default.red('Cannot reload validations as "validationsPath" was not provided when instantiating CommandKit.'));let newValidations=await this.#buildValidations();this.#data.validations=newValidations}};export{ValidationHandler};
|
|
2
|
+
//# sourceMappingURL=chunk-TZXZ3UZS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/handlers/validation-handler/ValidationHandler.ts"],"sourcesContent":["import type {\n ValidationHandlerData,\n ValidationHandlerOptions,\n} from './typings';\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { getFilePaths } from '../../utils/get-paths';\nimport { clone } from '../../utils/clone';\nimport colors from '../../utils/colors';\n\n/**\n * A handler for command validations.\n */\nexport class ValidationHandler {\n #data: ValidationHandlerData;\n\n constructor({ ...options }: ValidationHandlerOptions) {\n this.#data = {\n ...options,\n validations: [],\n };\n }\n\n async init() {\n this.#data.validations = await this.#buildValidations();\n }\n\n async #buildValidations() {\n const allowedExtensions = /\\.(js|mjs|cjs|ts)$/i;\n\n const validationPaths = await getFilePaths(\n this.#data.validationsPath,\n true,\n );\n const validationFilePaths = validationPaths.filter((path) =>\n allowedExtensions.test(path),\n );\n\n const validationFunctions: Function[] = [];\n\n for (const validationFilePath of validationFilePaths) {\n const modulePath = toFileURL(validationFilePath);\n\n let importedFunction = (await import(`${modulePath}?t=${Date.now()}`))\n .default;\n let validationFunction = clone(importedFunction);\n\n // If it's CommonJS, invalidate the import cache\n if (typeof module !== 'undefined' && typeof require !== 'undefined') {\n delete require.cache[require.resolve(validationFilePath)];\n }\n\n if (validationFunction?.default) {\n validationFunction = validationFunction.default;\n }\n\n const compactFilePath =\n validationFilePath.split(process.cwd())[1] || validationFilePath;\n\n if (typeof validationFunction !== 'function') {\n process.emitWarning(\n colors.yellow(\n `Ignoring: Validation file ${compactFilePath} does not export a function.`,\n ),\n );\n continue;\n }\n\n validationFunctions.push(validationFunction);\n }\n\n return validationFunctions;\n }\n\n get validations() {\n return this.#data.validations;\n }\n\n async reloadValidations() {\n if (!this.#data.validationsPath) {\n throw new Error(\n colors.red(\n 'Cannot reload validations as \"validationsPath\" was not provided when instantiating CommandKit.',\n ),\n );\n }\n\n const newValidations = await this.#buildValidations();\n\n this.#data.validations = new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node:path";var ConfigLookupPaths=["js","cjs","mjs"];async function findConfigPath(relative){for(let extension of ConfigLookupPaths){let path=join(relative,`commandkit.${extension}`);if(existsSync(path))return path}return null}__name(findConfigPath,"findConfigPath");async function importConfig(path){let config=await import(`file://${path}`);return config?.default??config}__name(importConfig,"importConfig");export{findConfigPath,importConfig};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-UV2LVAQV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/environment/common/config.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { CommandKitConfig } from '../../config';\n\nconst ConfigLookupPaths = [\n // javascript\n 'js',\n 'cjs',\n 'mjs',\n];\n\nexport async function findConfigPath(relative: string) {\n for (const extension of ConfigLookupPaths) {\n const path = join(relative, `commandkit.${extension}`);\n if (existsSync(path)) return path;\n }\n\n return null;\n}\n\nexport async function importConfig(path: string): Promise<CommandKitConfig> {\n const config = await import(`file://${path}`);\n return config?.default ?? config;\n}\n"],"mappings":"yCAAA,OAAS,eAAkB,UAC3B,OAAS,SAAY,YAGrB,IAAM,kBAAoB,CAExB,KACA,MACA,KACF,EAEA,eAAsB,eAAe,SAAkB,CACrD,QAAW,aAAa,kBAAmB,CACzC,IAAM,KAAO,KAAK,SAAU,cAAc,SAAS,EAAE,EACrD,GAAI,WAAW,IAAI,EAAG,OAAO,IAC/B,CAEA,OAAO,IACT,CAPsB,wCAStB,eAAsB,aAAa,KAAyC,CAC1E,IAAM,OAAS,MAAM,OAAO,UAAU,IAAI,IAC1C,OAAO,QAAQ,SAAW,MAC5B,CAHsB","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{bundle}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{bundle}from"./chunk-QC2F7O3S.mjs";import{findConfigPath,importConfig}from"./chunk-UV2LVAQV.mjs";import{Logger}from"./chunk-BJCWVCAY.mjs";import{colors_default}from"./chunk-FQGSVSCT.mjs";import{createClient,getClient}from"./chunk-DEB7FLUS.mjs";import{loadEnv}from"./chunk-ZJRAI4W5.mjs";import{__name}from"./chunk-7KD7ZCH6.mjs";var commandkitVersion="0.1.10-dev.20240202061201";function printBanner(){let banner=colors_default.magenta(`\u25C6 CommandKit ${commandkitVersion}`);Logger.Log(banner),Logger.Info("Initializing the development environment...")}__name(printBanner,"printBanner");async function initializeDevelopmentEnvironment(args){if(printBanner(),getClient()){Logger.Fatal("The development environment is already initialized.");return}let envErr=loadEnv("development");envErr?Logger.Warning("Failed to load .env",envErr):Logger.Debug("Loaded .env");let configPath=await findConfigPath(args.config??process.cwd());if(!configPath){let msg=`Could not locate the commandkit config file${args.config?" at "+args.config:" in the current working directory"}.`;Logger.Fatal(msg);return}try{var config=await importConfig(configPath);Logger.Debug("Loaded config from",colors_default.yellow(configPath))}catch(e){Logger.Warning("Failed to load config"),Logger.Fatal(colors_default.red(e.stack??`${e}`));return}let client=createClient(),entrypoint=await bundle("development");try{await import(`file://${entrypoint}`),await client.login(config.token)}catch(e){Logger.Fatal("Failed to load the client entrypoint",e)}}__name(initializeDevelopmentEnvironment,"initializeDevelopmentEnvironment");export{initializeDevelopmentEnvironment};
|
|
2
|
+
//# sourceMappingURL=chunk-WXW36EYF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/environment/actions/development.ts"],"sourcesContent":["import type yargs from 'yargs';\nimport { findConfigPath, importConfig } from '../common/config';\nimport colors from '../../utils/colors';\nimport { Logger } from '../common/logger';\nimport { loadEnv } from '../../bootstrap/loadEnv';\nimport { createClient, getClient } from '../../bootstrap/client';\nimport { bundle } from '../bundler/bundle';\n\nconst commandkitVersion = '0.1.10-dev.20240202061201';\n\nfunction printBanner() {\n const banner = colors.magenta(\n `${String.fromCharCode(9670)} CommandKit ${commandkitVersion}`,\n );\n Logger.Log(banner);\n Logger.Info('Initializing the development environment...');\n}\n\nexport async function initializeDevelopmentEnvironment(\n args: yargs.ArgumentsCamelCase<{\n config?: string | undefined;\n nodeOptions?: string | undefined;\n }>,\n) {\n printBanner();\n\n if (getClient()) {\n Logger.Fatal('The development environment is already initialized.');\n return;\n }\n\n const envErr = loadEnv('development');\n\n if (envErr) {\n Logger.Warning('Failed to load .env', envErr);\n } else {\n Logger.Debug('Loaded .env');\n }\n\n const configPath = await findConfigPath(args.config ?? process.cwd());\n if (!configPath) {\n const msg = `Could not locate the commandkit config file${\n args.config ? ' at ' + args.config : ' in the current working directory'\n }.`;\n Logger.Fatal(msg);\n return;\n }\n\n try {\n var config = await importConfig(configPath);\n Logger.Debug('Loaded config from', colors.yellow(configPath));\n } catch (e) {\n Logger.Warning('Failed to load config');\n Logger.Fatal(colors.red((e as Error).stack ?? `${e}`));\n return;\n }\n\n const client = createClient();\n\n // build the project\n const entrypoint = await bundle('development');\n\n try {\n // load the client entrypoint\n await import(`file://${entrypoint}`);\n await client.login(config.token);\n } catch (e) {\n Logger.Fatal('Failed to load the client entrypoint', e);\n }\n}\n"],"mappings":"6UAQA,IAAM,kBAAoB,4BAE1B,SAAS,aAAc,CACrB,IAAM,OAAS,eAAO,QACpB,qBAA2C,iBAAiB,EAC9D,EACA,OAAO,IAAI,MAAM,EACjB,OAAO,KAAK,6CAA6C,CAC3D,CANS,kCAQT,eAAsB,iCACpB,KAIA,CAGA,GAFA,YAAY,EAER,UAAU,EAAG,CACf,OAAO,MAAM,qDAAqD,EAClE,MACF,CAEA,IAAM,OAAS,QAAQ,aAAa,EAEhC,OACF,OAAO,QAAQ,sBAAuB,MAAM,EAE5C,OAAO,MAAM,aAAa,EAG5B,IAAM,WAAa,MAAM,eAAe,KAAK,QAAU,QAAQ,IAAI,CAAC,EACpE,GAAI,CAAC,WAAY,CACf,IAAM,IAAM,8CACV,KAAK,OAAS,OAAS,KAAK,OAAS,mCACvC,IACA,OAAO,MAAM,GAAG,EAChB,MACF,CAEA,GAAI,CACF,IAAI,OAAS,MAAM,aAAa,UAAU,EAC1C,OAAO,MAAM,qBAAsB,eAAO,OAAO,UAAU,CAAC,CAC9D,OAAS,EAAG,CACV,OAAO,QAAQ,uBAAuB,EACtC,OAAO,MAAM,eAAO,IAAK,EAAY,OAAS,GAAG,CAAC,EAAE,CAAC,EACrD,MACF,CAEA,IAAM,OAAS,aAAa,EAGtB,WAAa,MAAM,OAAO,aAAa,EAE7C,GAAI,CAEF,MAAM,OAAO,UAAU,UAAU,IACjC,MAAM,OAAO,MAAM,OAAO,KAAK,CACjC,OAAS,EAAG,CACV,OAAO,MAAM,uCAAwC,CAAC,CACxD,CACF,CAnDsB","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{__name}from"./chunk-7KD7ZCH6.mjs";import{config}from"dotenv-cra";function loadEnv(type){return process.env.NODE_ENV=type,config().error?.message}__name(loadEnv,"loadEnv");export{loadEnv};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-ZJRAI4W5.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bootstrap/loadEnv.ts"],"sourcesContent":["import { config } from 'dotenv-cra';\n\nexport function loadEnv(type: 'development' | 'production') {\n process.env.NODE_ENV = type;\n\n const result = config();\n\n return result.error?.message;\n}\n"],"mappings":"yCAAA,OAAS,WAAc,aAEhB,SAAS,QAAQ,KAAoC,CAC1D,eAAQ,IAAI,SAAW,KAER,OAAO,EAER,OAAO,OACvB,CANgB","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/ButtonKit.ts"],"sourcesContent":["import {\n
|
|
1
|
+
{"version":3,"sources":["../../src/components/ButtonKit.ts"],"sourcesContent":["import {\n type Message,\n type Awaitable,\n type ButtonInteraction,\n type InteractionCollector,\n type InteractionCollectorOptions,\n type APIButtonComponentWithCustomId,\n ButtonStyle,\n ButtonBuilder,\n ComponentType,\n} from 'discord.js';\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitButtonBuilderInteractionCollectorDispatch = (\n interaction: ButtonInteraction,\n) => Awaitable<void>;\n\nexport type CommandKitButtonBuilderOnEnd = () => Awaitable<void>;\n\nexport type CommandKitButtonBuilderInteractionCollectorDispatchContextData = {\n /**\n * The message to listen for button interactions on.\n */\n message: Message;\n /**\n * The duration (in ms) that the collector should run for.\n */\n time?: number;\n /**\n * If the collector should automatically reset the timer when a button is clicked.\n */\n autoReset?: boolean;\n} & Omit<\n InteractionCollectorOptions<ButtonInteraction>,\n 'filter' | 'componentType'\n>;\n\nexport class ButtonKit extends ButtonBuilder {\n #onClickHandler: CommandKitButtonBuilderInteractionCollectorDispatch | null =\n null;\n #onEndHandler: CommandKitButtonBuilderOnEnd | null = null;\n #contextData: CommandKitButtonBuilderInteractionCollectorDispatchContextData | null =\n null;\n #collector: InteractionCollector<ButtonInteraction> | null = null;\n\n /**\n * Sets up an inline interaction collector for this button. This collector by default allows as many interactions as possible if it is actively used.\n * If unused, this expires after 24 hours or custom time if specified.\n * @param handler The handler to run when the button is clicked\n * @param data The context data to use for the interaction collector\n * @returns This button\n * @example\n * ```ts\n * const button = new ButtonKit()\n * .setLabel('Click me')\n * .setStyle(ButtonStyle.Primary)\n * .setCustomId('click_me');\n *\n * const row = new ActionRowBuilder().addComponents(button);\n *\n * const message = await channel.send({ content: 'Click the button', components: [row] });\n *\n * button.onClick(async (interaction) => {\n * await interaction.reply('You clicked me!');\n * }, { message });\n *\n * // Remove onClick handler and destroy the interaction collector\n * button.onClick(null);\n * ```\n */\n public onClick(\n handler: CommandKitButtonBuilderInteractionCollectorDispatch,\n data?: CommandKitButtonBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onClick\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n this.#destroyCollector();\n\n this.#onClickHandler = handler;\n if (data) this.#contextData = data;\n\n this.#setupInteractionCollector();\n\n return this;\n }\n\n public onEnd(handler: CommandKitButtonBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#onEndHandler = handler;\n\n return this;\n }\n\n #setupInteractionCollector() {\n if (!this.#contextData || !this.#onClickHandler) return;\n\n const message = this.#contextData.message;\n\n if (!message) {\n throw new TypeError(\n 'Cannot setup \"onClick\" handler without a message in the context data.',\n );\n }\n\n if ('customId' in this.data && !this.data.customId) {\n throw new TypeError(\n 'Cannot setup \"onClick\" handler on a button without a custom id.',\n );\n }\n\n const data = {\n time: 86_400_000,\n autoReset: true,\n ...this.#contextData,\n };\n\n const collector = (this.#collector =\n message.createMessageComponentCollector({\n filter: (interaction) =>\n interaction.customId ===\n (<APIButtonComponentWithCustomId>this.data).custom_id &&\n interaction.message.id === message.id,\n componentType: ComponentType.Button,\n ...data,\n }));\n\n this.#collector.on('collect', (interaction) => {\n const handler = this.#onClickHandler;\n\n if (!handler) return this.#destroyCollector();\n\n if (!this.#collector) {\n return collector.stop('destroyed');\n }\n\n if (data.autoReset) {\n this.#collector.resetTimer();\n }\n\n return handler(interaction);\n });\n\n this.#collector.on('end', () => {\n this.#destroyCollector();\n this.#onEndHandler?.();\n });\n }\n\n public dispose() {\n this.#destroyCollector();\n this.#onEndHandler?.();\n return this;\n }\n\n #destroyCollector() {\n this.#collector?.stop('end');\n this.#collector?.removeAllListeners();\n this.#collector = null;\n this.#contextData = null;\n this.#onClickHandler = null;\n }\n}\n"],"mappings":"ouBAAA,8HAAA,mBAUO,sBA8BA,IAAM,UAAN,cAAwB,4BAAc,CAxC7C,MAwC6C,0BAC3C,gBACE,KACF,cAAqD,KACrD,aACE,KACF,WAA6D,KA2BtD,QACL,QACA,KACM,CACN,GAAI,KAAK,KAAK,QAAU,2BAAY,KAClC,M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 @@
|
|
|
1
|
-
import{ButtonKit}from"../chunk-
|
|
1
|
+
import{ButtonKit}from"../chunk-6CLMSPNA.mjs";import"../chunk-7KD7ZCH6.mjs";export{ButtonKit};
|
|
2
2
|
//# sourceMappingURL=ButtonKit.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/index.ts","../../src/components/ButtonKit.ts"],"sourcesContent":["export * from './ButtonKit';\n","import {\n
|
|
1
|
+
{"version":3,"sources":["../../src/components/index.ts","../../src/components/ButtonKit.ts"],"sourcesContent":["export * from './ButtonKit';\n","import {\n type Message,\n type Awaitable,\n type ButtonInteraction,\n type InteractionCollector,\n type InteractionCollectorOptions,\n type APIButtonComponentWithCustomId,\n ButtonStyle,\n ButtonBuilder,\n ComponentType,\n} from 'discord.js';\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitButtonBuilderInteractionCollectorDispatch = (\n interaction: ButtonInteraction,\n) => Awaitable<void>;\n\nexport type CommandKitButtonBuilderOnEnd = () => Awaitable<void>;\n\nexport type CommandKitButtonBuilderInteractionCollectorDispatchContextData = {\n /**\n * The message to listen for button interactions on.\n */\n message: Message;\n /**\n * The duration (in ms) that the collector should run for.\n */\n time?: number;\n /**\n * If the collector should automatically reset the timer when a button is clicked.\n */\n autoReset?: boolean;\n} & Omit<\n InteractionCollectorOptions<ButtonInteraction>,\n 'filter' | 'componentType'\n>;\n\nexport class ButtonKit extends ButtonBuilder {\n #onClickHandler: CommandKitButtonBuilderInteractionCollectorDispatch | null =\n null;\n #onEndHandler: CommandKitButtonBuilderOnEnd | null = null;\n #contextData: CommandKitButtonBuilderInteractionCollectorDispatchContextData | null =\n null;\n #collector: InteractionCollector<ButtonInteraction> | null = null;\n\n /**\n * Sets up an inline interaction collector for this button. This collector by default allows as many interactions as possible if it is actively used.\n * If unused, this expires after 24 hours or custom time if specified.\n * @param handler The handler to run when the button is clicked\n * @param data The context data to use for the interaction collector\n * @returns This button\n * @example\n * ```ts\n * const button = new ButtonKit()\n * .setLabel('Click me')\n * .setStyle(ButtonStyle.Primary)\n * .setCustomId('click_me');\n *\n * const row = new ActionRowBuilder().addComponents(button);\n *\n * const message = await channel.send({ content: 'Click the button', components: [row] });\n *\n * button.onClick(async (interaction) => {\n * await interaction.reply('You clicked me!');\n * }, { message });\n *\n * // Remove onClick handler and destroy the interaction collector\n * button.onClick(null);\n * ```\n */\n public onClick(\n handler: CommandKitButtonBuilderInteractionCollectorDispatch,\n data?: CommandKitButtonBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onClick\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n this.#destroyCollector();\n\n this.#onClickHandler = handler;\n if (data) this.#contextData = data;\n\n this.#setupInteractionCollector();\n\n return this;\n }\n\n public onEnd(handler: CommandKitButtonBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#onEndHandler = handler;\n\n return this;\n }\n\n #setupInteractionCollector() {\n if (!this.#contextData || !this.#onClickHandler) return;\n\n const message = this.#contextData.message;\n\n if (!message) {\n throw new TypeError(\n 'Cannot setup \"onClick\" handler without a message in the context data.',\n );\n }\n\n if ('customId' in this.data && !this.data.customId) {\n throw new TypeError(\n 'Cannot setup \"onClick\" handler on a button without a custom id.',\n );\n }\n\n const data = {\n time: 86_400_000,\n autoReset: true,\n ...this.#contextData,\n };\n\n const collector = (this.#collector =\n message.createMessageComponentCollector({\n filter: (interaction) =>\n interaction.customId ===\n (<APIButtonComponentWithCustomId>this.data).custom_id &&\n interaction.message.id === message.id,\n componentType: ComponentType.Button,\n ...data,\n }));\n\n this.#collector.on('collect', (interaction) => {\n const handler = this.#onClickHandler;\n\n if (!handler) return this.#destroyCollector();\n\n if (!this.#collector) {\n return collector.stop('destroyed');\n }\n\n if (data.autoReset) {\n this.#collector.resetTimer();\n }\n\n return handler(interaction);\n });\n\n this.#collector.on('end', () => {\n this.#destroyCollector();\n this.#onEndHandler?.();\n });\n }\n\n public dispose() {\n this.#destroyCollector();\n this.#onEndHandler?.();\n return this;\n }\n\n #destroyCollector() {\n this.#collector?.stop('end');\n this.#collector?.removeAllListeners();\n this.#collector = null;\n this.#contextData = null;\n this.#onClickHandler = null;\n }\n}\n"],"mappings":"ouBAAA,iICAA,mBAUO,sBA8BA,IAAM,UAAN,cAAwB,4BAAc,CAxC7C,MAwC6C,0BAC3C,gBACE,KACF,cAAqD,KACrD,aACE,KACF,WAA6D,KA2BtD,QACL,QACA,KACM,CACN,GAAI,KAAK,KAAK,QAAU,2BAAY,KAClC,MAAM,IAAI,UAAU,iDAAiD,EAGvE,GAAI,CAAC,QACH,MAAM,IAAI,UACR,8DACF,EAGF,YAAK,kBAAkB,EAEvB,KAAK,gBAAkB,QACnB,OAAM,KAAK,aAAe,MAE9B,KAAK,2BAA2B,EAEzB,IACT,CAEO,MAAM,QAA6C,CACxD,GAAI,CAAC,QACH,MAAM,IAAI,UACR,4DACF,EAGF,YAAK,cAAgB,QAEd,IACT,CAEA,4BAA6B,CAC3B,GAAI,CAAC,KAAK,cAAgB,CAAC,KAAK,gBAAiB,OAEjD,IAAM,QAAU,KAAK,aAAa,QAElC,GAAI,CAAC,QACH,MAAM,IAAI,UACR,uEACF,EAGF,GAAI,aAAc,KAAK,MAAQ,CAAC,KAAK,KAAK,SACxC,MAAM,IAAI,UACR,iEACF,EAGF,IAAM,KAAO,CACX,KAAM,MACN,UAAW,GACX,GAAG,KAAK,YACV,EAEM,UAAa,KAAK,WACtB,QAAQ,gCAAgC,CACtC,OAAS,aACP,YAAY,WACuB,KAAK,KAAM,WAC9C,YAAY,QAAQ,KAAO,QAAQ,GACrC,cAAe,6BAAc,OAC7B,GAAG,IACL,CAAC,EAEH,KAAK,WAAW,GAAG,UAAY,aAAgB,CAC7C,IAAM,QAAU,KAAK,gBAErB,OAAK,QAEA,KAAK,YAIN,KAAK,WACP,KAAK,WAAW,WAAW,EAGtB,QAAQ,WAAW,GAPjB,UAAU,KAAK,WAAW,EAHd,KAAK,kBAAkB,CAW9C,CAAC,EAED,KAAK,WAAW,GAAG,MAAO,IAAM,CAC9B,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,CACvB,CAAC,CACH,CAEO,SAAU,CACf,YAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACd,IACT,CAEA,mBAAoB,CAClB,KAAK,YAAY,KAAK,KAAK,EAC3B,KAAK,YAAY,mBAAmB,EACpC,KAAK,WAAa,KAClB,KAAK,aAAe,KACpB,KAAK,gBAAkB,IACzB,CACF","names":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"../chunk-M5FMJETI.mjs";import{ButtonKit}from"../chunk-
|
|
1
|
+
import"../chunk-M5FMJETI.mjs";import{ButtonKit}from"../chunk-6CLMSPNA.mjs";import"../chunk-7KD7ZCH6.mjs";export{ButtonKit};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["import type { ClientOptions } from 'discord.js';\n\nexport interface CommandKitConfig {\n
|
|
1
|
+
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["import type { ClientOptions } from 'discord.js';\n\nexport interface CommandKitConfig {\n /**\n * The Discord client options.\n */\n clientOptions: ClientOptions;\n /**\n * The Discord bot token. Defaults to `process.env.DISCORD_TOKEN`.\n */\n token?: string;\n /**\n * Whether or not to use the watch mode. Defaults to `true`.\n */\n watch: boolean;\n /**\n * The output directory of the project. Defaults to `dist`.\n */\n outDir: string;\n /**\n * Whether or not to include extra env utilities. Defaults to `true`.\n */\n envExtra: boolean;\n /**\n * Node.js cli options.\n */\n nodeOptions: string[];\n /**\n * Whether or not to clear default restart logs. Defaults to `true`.\n */\n clearRestartLogs: boolean;\n /**\n * Whether or not to minify the output. Defaults to `false`.\n */\n minify: boolean;\n /**\n * Whether or not to include sourcemaps in production build. Defaults to `false`.\n */\n sourcemap: boolean | 'inline';\n /**\n * Whether or not to include anti-crash handler in production. Defaults to `true`.\n */\n antiCrash: boolean;\n /**\n * Whether or not to polyfill `require` function. Defaults to `true`.\n */\n requirePolyfill: boolean;\n}\n\nlet globalConfig: Partial<CommandKitConfig> = {\n envExtra: true,\n outDir: 'dist',\n watch: true,\n clearRestartLogs: true,\n minify: false,\n sourcemap: false,\n nodeOptions: [],\n antiCrash: true,\n requirePolyfill: true,\n token: process.env.DISCORD_TOKEN,\n};\n\nexport function getConfig(): CommandKitConfig {\n return globalConfig as CommandKitConfig;\n}\n\nconst requiredProps = ['clientOptions'] as const;\n\ntype R = (typeof requiredProps)[number];\n\ntype PartialConfig<T extends CommandKitConfig> = Partial<Omit<T, R>> &\n Pick<T, R>;\n\nexport function defineConfig(config: PartialConfig<CommandKitConfig>) {\n for (const prop of requiredProps) {\n if (!config[prop]) {\n throw new Error(\n `[CommandKit Config] Missing required config property: ${prop}`,\n );\n }\n }\n\n globalConfig = {\n ...globalConfig,\n ...config,\n };\n\n return globalConfig;\n}\n"],"mappings":"ouBAAA,mJAiDA,IAAI,aAA0C,CAC5C,SAAU,GACV,OAAQ,OACR,MAAO,GACP,iBAAkB,GAClB,OAAQ,GACR,UAAW,GACX,YAAa,CAAC,EACd,UAAW,GACX,gBAAiB,GACjB,MAAO,QAAQ,IAAI,aACrB,EAEO,SAAS,WAA8B,CAC5C,OAAO,YACT,CAFgB,8BAIhB,IAAM,cAAgB,CAAC,eAAe,EAO/B,SAAS,aAAa,OAAyC,CACpE,QAAW,QAAQ,cACjB,GAAI,CAAC,OAAO,IAAI,EACd,MAAM,IAAI,MACR,yDAAyD,IAAI,EAC/D,EAIJ,oBAAe,CACb,GAAG,aACH,GAAG,MACL,EAEO,YACT,CAfgB","names":[]}
|
package/dist/config.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defineConfig,getConfig}from"./chunk-
|
|
1
|
+
import{defineConfig,getConfig}from"./chunk-QYJ4DE3N.mjs";import"./chunk-7KD7ZCH6.mjs";export{defineConfig,getConfig};
|
|
2
2
|
//# sourceMappingURL=config.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var development_exports={};__export(development_exports,{initializeDevelopmentEnvironment:()=>initializeDevelopmentEnvironment});module.exports=__toCommonJS(development_exports);var import_node_fs=require("fs"),import_node_path=require("path");var ConfigLookupPaths=["js","cjs","mjs"];async function findConfigPath(relative){for(let extension of ConfigLookupPaths){let path=(0,import_node_path.join)(relative,`commandkit.${extension}`);if((0,import_node_fs.existsSync)(path))return path}return null}__name(findConfigPath,"findConfigPath");async function importConfig(path){let config2=await import(`file://${path}`);return config2?.default??config2}__name(importConfig,"importConfig");var resetColor="\x1B[0m",colors_default={reset:text=>`${text}${resetColor}`,bright:text=>`\x1B[1m${text}${resetColor}`,dim:text=>`\x1B[2m${text}${resetColor}`,underscore:text=>`\x1B[4m${text}${resetColor}`,blink:text=>`\x1B[5m${text}${resetColor}`,reverse:text=>`\x1B[7m${text}${resetColor}`,hidden:text=>`\x1B[8m${text}${resetColor}`,black:text=>`\x1B[30m${text}${resetColor}`,red:text=>`\x1B[31m${text}${resetColor}`,green:text=>`\x1B[32m${text}${resetColor}`,yellow:text=>`\x1B[33m${text}${resetColor}`,blue:text=>`\x1B[34m${text}${resetColor}`,magenta:text=>`\x1B[35m${text}${resetColor}`,cyan:text=>`\x1B[36m${text}${resetColor}`,white:text=>`\x1B[37m${text}${resetColor}`,bgBlack:text=>`\x1B[40m${text}${resetColor}`,bgRed:text=>`\x1B[41m${text}${resetColor}`,bgGreen:text=>`\x1B[42m${text}${resetColor}`,bgYellow:text=>`\x1B[43m${text}${resetColor}`,bgBlue:text=>`\x1B[44m${text}${resetColor}`,bgMagenta:text=>`\x1B[45m${text}${resetColor}`,bgCyan:text=>`\x1B[46m${text}${resetColor}`,bgWhite:text=>`\x1B[47m${text}${resetColor}`};var Logger={Fatal:(...message)=>{console.log(colors_default.red("[FATAL ERROR]"),...message),process.exit(1)},Warning:(...message)=>{console.log(colors_default.yellow("[WARNING]"),...message)},Info:(...message)=>{console.log(colors_default.green("[INFO]"),...message)},Debug:(...message)=>{console.log(colors_default.blue("[DEBUG]"),...message)},Log:(...message)=>{console.log(...message)}};var import_dotenv_cra=require("dotenv-cra");function loadEnv(type){return process.env.NODE_ENV=type,(0,import_dotenv_cra.config)().error?.message}__name(loadEnv,"loadEnv");var import_discord=require("discord.js");var globalConfig={envExtra:!0,outDir:"dist",watch:!0,clearRestartLogs:!0,minify:!1,sourcemap:!1,nodeOptions:[],antiCrash:!0,requirePolyfill:!0,token:process.env.DISCORD_TOKEN};function getConfig(){return globalConfig}__name(getConfig,"getConfig");var discord_client;function getClient(){return discord_client}__name(getClient,"getClient");function createClient(){let config2=getConfig();return discord_client=new import_discord.Client(config2.clientOptions),discord_client}__name(createClient,"createClient");var import_tsup=require("tsup");var import_path=require("path");function bundle(mode){switch(mode){case"development":return buildDevelopment();default:throw new Error("Not implemented")}}__name(bundle,"bundle");function buildDevelopment(){let{watch}=getConfig(),outDir=(0,import_path.join)(process.cwd(),".commandkit");return(0,import_tsup.build)({clean:!0,format:["esm"],bundle:!1,dts:!1,skipNodeModulesBundle:!0,minify:!1,shims:!0,sourcemap:"inline",keepNames:!0,outDir:".commandkit",silent:!0,entry:["src"],watch,async onSuccess(){}}).then(()=>(0,import_path.join)(outDir,"client.mjs"))}__name(buildDevelopment,"buildDevelopment");var commandkitVersion="0.1.10-dev.
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var development_exports={};__export(development_exports,{initializeDevelopmentEnvironment:()=>initializeDevelopmentEnvironment});module.exports=__toCommonJS(development_exports);var import_node_fs=require("fs"),import_node_path=require("path");var ConfigLookupPaths=["js","cjs","mjs"];async function findConfigPath(relative){for(let extension of ConfigLookupPaths){let path=(0,import_node_path.join)(relative,`commandkit.${extension}`);if((0,import_node_fs.existsSync)(path))return path}return null}__name(findConfigPath,"findConfigPath");async function importConfig(path){let config2=await import(`file://${path}`);return config2?.default??config2}__name(importConfig,"importConfig");var resetColor="\x1B[0m",colors_default={reset:text=>`${text}${resetColor}`,bright:text=>`\x1B[1m${text}${resetColor}`,dim:text=>`\x1B[2m${text}${resetColor}`,underscore:text=>`\x1B[4m${text}${resetColor}`,blink:text=>`\x1B[5m${text}${resetColor}`,reverse:text=>`\x1B[7m${text}${resetColor}`,hidden:text=>`\x1B[8m${text}${resetColor}`,black:text=>`\x1B[30m${text}${resetColor}`,red:text=>`\x1B[31m${text}${resetColor}`,green:text=>`\x1B[32m${text}${resetColor}`,yellow:text=>`\x1B[33m${text}${resetColor}`,blue:text=>`\x1B[34m${text}${resetColor}`,magenta:text=>`\x1B[35m${text}${resetColor}`,cyan:text=>`\x1B[36m${text}${resetColor}`,white:text=>`\x1B[37m${text}${resetColor}`,bgBlack:text=>`\x1B[40m${text}${resetColor}`,bgRed:text=>`\x1B[41m${text}${resetColor}`,bgGreen:text=>`\x1B[42m${text}${resetColor}`,bgYellow:text=>`\x1B[43m${text}${resetColor}`,bgBlue:text=>`\x1B[44m${text}${resetColor}`,bgMagenta:text=>`\x1B[45m${text}${resetColor}`,bgCyan:text=>`\x1B[46m${text}${resetColor}`,bgWhite:text=>`\x1B[47m${text}${resetColor}`};var Logger={Fatal:(...message)=>{console.log(colors_default.red("[FATAL ERROR]"),...message),process.exit(1)},Warning:(...message)=>{console.log(colors_default.yellow("[WARNING]"),...message)},Info:(...message)=>{console.log(colors_default.green("[INFO]"),...message)},Debug:(...message)=>{console.log(colors_default.blue("[DEBUG]"),...message)},Log:(...message)=>{console.log(...message)}};var import_dotenv_cra=require("dotenv-cra");function loadEnv(type){return process.env.NODE_ENV=type,(0,import_dotenv_cra.config)().error?.message}__name(loadEnv,"loadEnv");var import_discord=require("discord.js");var globalConfig={envExtra:!0,outDir:"dist",watch:!0,clearRestartLogs:!0,minify:!1,sourcemap:!1,nodeOptions:[],antiCrash:!0,requirePolyfill:!0,token:process.env.DISCORD_TOKEN};function getConfig(){return globalConfig}__name(getConfig,"getConfig");var discord_client;function getClient(){return discord_client}__name(getClient,"getClient");function createClient(){let config2=getConfig();return discord_client=new import_discord.Client(config2.clientOptions),discord_client}__name(createClient,"createClient");var import_tsup=require("tsup");var import_path=require("path");function bundle(mode){switch(mode){case"development":return buildDevelopment();default:throw new Error("Not implemented")}}__name(bundle,"bundle");function buildDevelopment(){let{watch}=getConfig(),outDir=(0,import_path.join)(process.cwd(),".commandkit");return(0,import_tsup.build)({clean:!0,format:["esm"],bundle:!1,dts:!1,skipNodeModulesBundle:!0,minify:!1,shims:!0,sourcemap:"inline",keepNames:!0,outDir:".commandkit",silent:!0,entry:["src"],watch,async onSuccess(){}}).then(()=>(0,import_path.join)(outDir,"client.mjs"))}__name(buildDevelopment,"buildDevelopment");var commandkitVersion="0.1.10-dev.20240202061201";function printBanner(){let banner=colors_default.magenta(`\u25C6 CommandKit ${commandkitVersion}`);Logger.Log(banner),Logger.Info("Initializing the development environment...")}__name(printBanner,"printBanner");async function initializeDevelopmentEnvironment(args){if(printBanner(),getClient()){Logger.Fatal("The development environment is already initialized.");return}let envErr=loadEnv("development");envErr?Logger.Warning("Failed to load .env",envErr):Logger.Debug("Loaded .env");let configPath=await findConfigPath(args.config??process.cwd());if(!configPath){let msg=`Could not locate the commandkit config file${args.config?" at "+args.config:" in the current working directory"}.`;Logger.Fatal(msg);return}try{var config2=await importConfig(configPath);Logger.Debug("Loaded config from",colors_default.yellow(configPath))}catch(e){Logger.Warning("Failed to load config"),Logger.Fatal(colors_default.red(e.stack??`${e}`));return}let client=createClient(),entrypoint=await bundle("development");try{await import(`file://${entrypoint}`),await client.login(config2.token)}catch(e){Logger.Fatal("Failed to load the client entrypoint",e)}}__name(initializeDevelopmentEnvironment,"initializeDevelopmentEnvironment");0&&(module.exports={initializeDevelopmentEnvironment});
|
|
2
2
|
//# sourceMappingURL=development.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/environment/actions/development.ts","../../../src/environment/common/config.ts","../../../src/utils/colors.ts","../../../src/environment/common/logger.ts","../../../src/bootstrap/loadEnv.ts","../../../src/bootstrap/client.ts","../../../src/config.ts","../../../src/environment/bundler/bundle.ts"],"sourcesContent":["import type yargs from 'yargs';\nimport { findConfigPath, importConfig } from '../common/config';\nimport colors from '../../utils/colors';\nimport { Logger } from '../common/logger';\nimport { loadEnv } from '../../bootstrap/loadEnv';\nimport { createClient, getClient } from '../../bootstrap/client';\nimport { bundle } from '../bundler/bundle';\n\nconst commandkitVersion = '0.1.10-dev.20240131174628';\n\nfunction printBanner() {\n const banner = colors.magenta(`${String.fromCharCode(9670)} CommandKit ${commandkitVersion}`);\n Logger.Log(banner);\n Logger.Info('Initializing the development environment...');\n}\n\nexport async function initializeDevelopmentEnvironment(\n args: yargs.ArgumentsCamelCase<{\n config?: string | undefined;\n nodeOptions?: string | undefined;\n }>,\n) {\n printBanner();\n\n if (getClient()) {\n Logger.Fatal('The development environment is already initialized.');\n return;\n }\n\n const envErr = loadEnv('development');\n\n if (envErr) {\n Logger.Warning('Failed to load .env', envErr);\n } else {\n Logger.Debug('Loaded .env');\n }\n\n const configPath = await findConfigPath(args.config ?? process.cwd());\n if (!configPath) {\n const msg = `Could not locate the commandkit config file${\n args.config ? ' at ' + args.config : ' in the current working directory'\n }.`;\n Logger.Fatal(msg);\n return;\n }\n\n try {\n var config = await importConfig(configPath);\n Logger.Debug('Loaded config from', colors.yellow(configPath));\n } catch (e) {\n Logger.Warning('Failed to load config');\n Logger.Fatal(colors.red((e as Error).stack ?? `${e}`));\n return;\n }\n\n const client = createClient();\n\n // build the project\n const entrypoint = await bundle('development');\n\n try {\n // load the client entrypoint\n await import(`file://${entrypoint}`);\n await client.login(config.token);\n } catch (e) {\n Logger.Fatal('Failed to load the client entrypoint', e);\n }\n}\n","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { CommandKitConfig } from '../../config';\n\nconst ConfigLookupPaths = [\n // javascript\n 'js',\n 'cjs',\n 'mjs',\n];\n\nexport async function findConfigPath(relative: string) {\n for (const extension of ConfigLookupPaths) {\n const path = join(relative, `commandkit.${extension}`);\n if (existsSync(path)) return path;\n }\n\n return null;\n}\n\nexport async function importConfig(path: string): Promise<CommandKitConfig> {\n const config = await import(`file://${path}`);\n return config?.default ?? config;\n}\n","const resetColor = '\\x1b[0m';\n\nexport default {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`,\n};\n","import colors from '../../utils/colors';\n\nexport const Logger = {\n Fatal: (...message: unknown[]) => {\n console.log(colors.red('[FATAL ERROR]'), ...message);\n process.exit(1);\n },\n Warning: (...message: unknown[]) => {\n console.log(colors.yellow('[WARNING]'), ...message);\n },\n Info: (...message: unknown[]) => {\n console.log(colors.green('[INFO]'), ...message);\n },\n Debug: (...message: unknown[]) => {\n console.log(colors.blue('[DEBUG]'), ...message);\n },\n Log: (...message: unknown[]) => {\n console.log(...message);\n },\n};\n","import { config } from 'dotenv-cra';\n\nexport function loadEnv(type: 'development' | 'production') {\n process.env.NODE_ENV = type;\n\n const result = config();\n\n return result.error?.message;\n}\n","import { Client } from 'discord.js';\nimport { getConfig } from '../config';\n\nlet discord_client: Client;\n\n/**\n * @internal\n */\nexport function getClient() {\n return discord_client;\n}\n\n/**\n * Fetches the client instance. If the client instance is not initialized, an error will be thrown.\n */\nexport function client<T extends boolean = boolean>() {\n if (!discord_client) {\n throw new Error(\n 'Client was not initialized. Make sure to run \"commandkit dev\" to bootstrap the client.',\n );\n }\n\n return discord_client as Client<T>;\n}\n\nexport function createClient() {\n const config = getConfig();\n\n discord_client = new Client(config.clientOptions);\n\n return discord_client;\n}\n","import type { ClientOptions } from 'discord.js';\n\nexport interface CommandKitConfig {\n /**\n * The Discord client options.\n */\n clientOptions: ClientOptions;\n /**\n * The Discord bot token. Defaults to `process.env.DISCORD_TOKEN`.\n */\n token?: string;\n /**\n * Whether or not to use the watch mode. Defaults to `true`.\n */\n watch: boolean;\n /**\n * The output directory of the project. Defaults to `dist`.\n */\n outDir: string;\n /**\n * Whether or not to include extra env utilities. Defaults to `true`.\n */\n envExtra: boolean;\n /**\n * Node.js cli options.\n */\n nodeOptions: string[];\n /**\n * Whether or not to clear default restart logs. Defaults to `true`.\n */\n clearRestartLogs: boolean;\n /**\n * Whether or not to minify the output. Defaults to `false`.\n */\n minify: boolean;\n /**\n * Whether or not to include sourcemaps in production build. Defaults to `false`.\n */\n sourcemap: boolean | 'inline';\n /**\n * Whether or not to include anti-crash handler in production. Defaults to `true`.\n */\n antiCrash: boolean;\n /**\n * Whether or not to polyfill `require` function. Defaults to `true`.\n */\n requirePolyfill: boolean;\n}\n\nlet globalConfig: Partial<CommandKitConfig> = {\n envExtra: true,\n outDir: 'dist',\n watch: true,\n clearRestartLogs: true,\n minify: false,\n sourcemap: false,\n nodeOptions: [],\n antiCrash: true,\n requirePolyfill: true,\n token: process.env.DISCORD_TOKEN,\n};\n\nexport function getConfig(): CommandKitConfig {\n return globalConfig as CommandKitConfig;\n}\n\nconst requiredProps = ['clientOptions'] as const;\n\ntype R = (typeof requiredProps)[number];\n\ntype PartialConfig<T extends CommandKitConfig> = Partial<Omit<T, R>> & Pick<T, R>;\n\nexport function defineConfig(config: PartialConfig<CommandKitConfig>) {\n for (const prop of requiredProps) {\n if (!config[prop]) {\n throw new Error(`[CommandKit Config] Missing required config property: ${prop}`);\n }\n }\n\n globalConfig = {\n ...globalConfig,\n ...config,\n };\n\n return globalConfig;\n}\n","import { build } from 'tsup';\nimport { getConfig } from '../../config';\nimport { join } from 'path';\n\nexport function bundle(mode: 'development' | 'production') {\n switch (mode) {\n case 'development':\n return buildDevelopment();\n default:\n throw new Error('Not implemented');\n }\n}\n\nfunction buildDevelopment() {\n const { watch } = getConfig();\n\n const outDir = join(process.cwd(), '.commandkit');\n\n return build({\n clean: true,\n format: ['esm'],\n bundle: false,\n dts: false,\n skipNodeModulesBundle: true,\n minify: false,\n shims: true,\n sourcemap: 'inline',\n keepNames: true,\n outDir: '.commandkit',\n silent: true,\n entry: ['src'],\n watch,\n async onSuccess() {\n // return await injectShims('.commandkit', main, false, requirePolyfill);\n },\n }).then(() => {\n return join(outDir, 'client.mjs');\n });\n}\n"],"mappings":"ouBAAA,kLCAA,mBAA2B,cAC3B,iBAAqB,gBAGrB,IAAM,kBAAoB,CAEtB,KACA,MACA,KACJ,EAEA,eAAsB,eAAe,SAAkB,CACnD,QAAW,aAAa,kBAAmB,CACvC,IAAM,QAAO,uBAAK,SAAU,cAAc,SAAS,EAAE,EACrD,MAAI,2BAAW,IAAI,EAAG,OAAO,IACjC,CAEA,OAAO,IACX,CAPsB,wCAStB,eAAsB,aAAa,KAAyC,CACxE,IAAMA,QAAS,MAAM,OAAO,UAAU,IAAI,IAC1C,OAAOA,SAAQ,SAAWA,OAC9B,CAHsB,oCCpBtB,IAAM,WAAa,UAEZ,eAAQ,CACX,MAAQ,MAAiB,GAAG,IAAI,GAAG,UAAU,GAC7C,OAAS,MAAiB,UAAU,IAAI,GAAG,UAAU,GACrD,IAAM,MAAiB,UAAU,IAAI,GAAG,UAAU,GAClD,WAAa,M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AiB,EAAE,EAC5F,OAAO,IAAI,MAAM,EACjB,OAAO,KAAK,6CAA6C,CAC7D,CAJS,kCAMT,eAAsB,iCAClB,KAIF,CAGE,GAFA,YAAY,EAER,UAAU,EAAG,CACb,OAAO,MAAM,qDAAqD,EAClE,MACJ,CAEA,IAAM,OAAS,QAAQ,aAAa,EAEhC,OACA,OAAO,QAAQ,sBAAuB,MAAM,EAE5C,OAAO,MAAM,aAAa,EAG9B,IAAM,WAAa,MAAM,eAAe,KAAK,QAAU,QAAQ,IAAI,CAAC,EACpE,GAAI,CAAC,WAAY,CACb,IAAM,IAAM,8CACR,KAAK,OAAS,OAAS,KAAK,OAAS,mCACzC,IACA,OAAO,MAAM,GAAG,EAChB,MACJ,CAEA,GAAI,CACA,IAAIC,QAAS,MAAM,aAAa,UAAU,EAC1C,OAAO,MAAM,qBAAsB,eAAO,OAAO,UAAU,CAAC,CAChE,OAAS,EAAG,CACR,OAAO,QAAQ,uBAAuB,EACtC,OAAO,MAAM,eAAO,IAAK,EAAY,OAAS,GAAG,CAAC,EAAE,CAAC,EACrD,MACJ,CAEA,IAAM,OAAS,aAAa,EAGtB,WAAa,MAAM,OAAO,aAAa,EAE7C,GAAI,CAEA,MAAM,OAAO,UAAU,UAAU,IACjC,MAAM,OAAO,MAAMA,QAAO,KAAK,CACnC,OAAS,EAAG,CACR,OAAO,MAAM,uCAAwC,CAAC,CAC1D,CACJ,CAnDsB","names":["config","config","config"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/environment/actions/development.ts","../../../src/environment/common/config.ts","../../../src/utils/colors.ts","../../../src/environment/common/logger.ts","../../../src/bootstrap/loadEnv.ts","../../../src/bootstrap/client.ts","../../../src/config.ts","../../../src/environment/bundler/bundle.ts"],"sourcesContent":["import type yargs from 'yargs';\nimport { findConfigPath, importConfig } from '../common/config';\nimport colors from '../../utils/colors';\nimport { Logger } from '../common/logger';\nimport { loadEnv } from '../../bootstrap/loadEnv';\nimport { createClient, getClient } from '../../bootstrap/client';\nimport { bundle } from '../bundler/bundle';\n\nconst commandkitVersion = '0.1.10-dev.20240202061201';\n\nfunction printBanner() {\n const banner = colors.magenta(\n `${String.fromCharCode(9670)} CommandKit ${commandkitVersion}`,\n );\n Logger.Log(banner);\n Logger.Info('Initializing the development environment...');\n}\n\nexport async function initializeDevelopmentEnvironment(\n args: yargs.ArgumentsCamelCase<{\n config?: string | undefined;\n nodeOptions?: string | undefined;\n }>,\n) {\n printBanner();\n\n if (getClient()) {\n Logger.Fatal('The development environment is already initialized.');\n return;\n }\n\n const envErr = loadEnv('development');\n\n if (envErr) {\n Logger.Warning('Failed to load .env', envErr);\n } else {\n Logger.Debug('Loaded .env');\n }\n\n const configPath = await findConfigPath(args.config ?? process.cwd());\n if (!configPath) {\n const msg = `Could not locate the commandkit config file${\n args.config ? ' at ' + args.config : ' in the current working directory'\n }.`;\n Logger.Fatal(msg);\n return;\n }\n\n try {\n var config = await importConfig(configPath);\n Logger.Debug('Loaded config from', colors.yellow(configPath));\n } catch (e) {\n Logger.Warning('Failed to load config');\n Logger.Fatal(colors.red((e as Error).stack ?? `${e}`));\n return;\n }\n\n const client = createClient();\n\n // build the project\n const entrypoint = await bundle('development');\n\n try {\n // load the client entrypoint\n await import(`file://${entrypoint}`);\n await client.login(config.token);\n } catch (e) {\n Logger.Fatal('Failed to load the client entrypoint', e);\n }\n}\n","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { CommandKitConfig } from '../../config';\n\nconst ConfigLookupPaths = [\n // javascript\n 'js',\n 'cjs',\n 'mjs',\n];\n\nexport async function findConfigPath(relative: string) {\n for (const extension of ConfigLookupPaths) {\n const path = join(relative, `commandkit.${extension}`);\n if (existsSync(path)) return path;\n }\n\n return null;\n}\n\nexport async function importConfig(path: string): Promise<CommandKitConfig> {\n const config = await import(`file://${path}`);\n return config?.default ?? config;\n}\n","const resetColor = '\\x1b[0m';\n\nexport default {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`,\n};\n","import colors from '../../utils/colors';\n\nexport const Logger = {\n Fatal: (...message: unknown[]) => {\n console.log(colors.red('[FATAL ERROR]'), ...message);\n process.exit(1);\n },\n Warning: (...message: unknown[]) => {\n console.log(colors.yellow('[WARNING]'), ...message);\n },\n Info: (...message: unknown[]) => {\n console.log(colors.green('[INFO]'), ...message);\n },\n Debug: (...message: unknown[]) => {\n console.log(colors.blue('[DEBUG]'), ...message);\n },\n Log: (...message: unknown[]) => {\n console.log(...message);\n },\n};\n","import { config } from 'dotenv-cra';\n\nexport function loadEnv(type: 'development' | 'production') {\n process.env.NODE_ENV = type;\n\n const result = config();\n\n return result.error?.message;\n}\n","import { Client } from 'discord.js';\nimport { getConfig } from '../config';\n\nlet discord_client: Client;\n\n/**\n * @internal\n */\nexport function getClient() {\n return discord_client;\n}\n\n/**\n * Fetches the client instance. If the client instance is not initialized, an error will be thrown.\n */\nexport function client<T extends boolean = boolean>() {\n if (!discord_client) {\n throw new Error(\n 'Client was not initialized. Make sure to run \"commandkit dev\" to bootstrap the client.',\n );\n }\n\n return discord_client as Client<T>;\n}\n\nexport function createClient() {\n const config = getConfig();\n\n discord_client = new Client(config.clientOptions);\n\n return discord_client;\n}\n","import type { ClientOptions } from 'discord.js';\n\nexport interface CommandKitConfig {\n /**\n * The Discord client options.\n */\n clientOptions: ClientOptions;\n /**\n * The Discord bot token. Defaults to `process.env.DISCORD_TOKEN`.\n */\n token?: string;\n /**\n * Whether or not to use the watch mode. Defaults to `true`.\n */\n watch: boolean;\n /**\n * The output directory of the project. Defaults to `dist`.\n */\n outDir: string;\n /**\n * Whether or not to include extra env utilities. Defaults to `true`.\n */\n envExtra: boolean;\n /**\n * Node.js cli options.\n */\n nodeOptions: string[];\n /**\n * Whether or not to clear default restart logs. Defaults to `true`.\n */\n clearRestartLogs: boolean;\n /**\n * Whether or not to minify the output. Defaults to `false`.\n */\n minify: boolean;\n /**\n * Whether or not to include sourcemaps in production build. Defaults to `false`.\n */\n sourcemap: boolean | 'inline';\n /**\n * Whether or not to include anti-crash handler in production. Defaults to `true`.\n */\n antiCrash: boolean;\n /**\n * Whether or not to polyfill `require` function. Defaults to `true`.\n */\n requirePolyfill: boolean;\n}\n\nlet globalConfig: Partial<CommandKitConfig> = {\n envExtra: true,\n outDir: 'dist',\n watch: true,\n clearRestartLogs: true,\n minify: false,\n sourcemap: false,\n nodeOptions: [],\n antiCrash: true,\n requirePolyfill: true,\n token: process.env.DISCORD_TOKEN,\n};\n\nexport function getConfig(): CommandKitConfig {\n return globalConfig as CommandKitConfig;\n}\n\nconst requiredProps = ['clientOptions'] as const;\n\ntype R = (typeof requiredProps)[number];\n\ntype PartialConfig<T extends CommandKitConfig> = Partial<Omit<T, R>> &\n Pick<T, R>;\n\nexport function defineConfig(config: PartialConfig<CommandKitConfig>) {\n for (const prop of requiredProps) {\n if (!config[prop]) {\n throw new Error(\n `[CommandKit Config] Missing required config property: ${prop}`,\n );\n }\n }\n\n globalConfig = {\n ...globalConfig,\n ...config,\n };\n\n return globalConfig;\n}\n","import { build } from 'tsup';\nimport { getConfig } from '../../config';\nimport { join } from 'path';\n\nexport function bundle(mode: 'development' | 'production') {\n switch (mode) {\n case 'development':\n return buildDevelopment();\n default:\n throw new Error('Not implemented');\n }\n}\n\nfunction buildDevelopment() {\n const { watch } = getConfig();\n\n const outDir = join(process.cwd(), '.commandkit');\n\n return build({\n clean: true,\n format: ['esm'],\n bundle: false,\n dts: false,\n skipNodeModulesBundle: true,\n minify: false,\n shims: true,\n sourcemap: 'inline',\n keepNames: true,\n outDir: '.commandkit',\n silent: true,\n entry: ['src'],\n watch,\n async onSuccess() {\n // return await injectShims('.commandkit', main, false, requirePolyfill);\n },\n }).then(() => {\n return join(outDir, 'client.mjs');\n });\n}\n"],"mappings":"ouBAAA,kLCAA,mBAA2B,cAC3B,iBAAqB,gBAGrB,IAAM,kBAAoB,CAExB,KACA,MACA,KACF,EAEA,eAAsB,eAAe,SAAkB,CACrD,QAAW,aAAa,kBAAmB,CACzC,IAAM,QAAO,uBAAK,SAAU,cAAc,SAAS,EAAE,EACrD,MAAI,2BAAW,IAAI,EAAG,OAAO,IAC/B,CAEA,OAAO,IACT,CAPsB,wCAStB,eAAsB,aAAa,KAAyC,CAC1E,IAAMA,QAAS,MAAM,OAAO,UAAU,IAAI,IAC1C,OAAOA,SAAQ,SAAWA,OAC5B,CAHsB,oCCpBtB,IAAM,WAAa,UAEZ,eAAQ,CACb,MAAQ,MAAiB,GAAG,IAAI,GAAG,UAAU,GAC7C,OAAS,MAAiB,UAAU,IAAI,GAAG,UAAU,GACrD,IAAM,MAAiB,UAAU,IAAI,GAAG,UAAU,GAClD,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BAAiB,EAC9D,EACA,OAAO,IAAI,MAAM,EACjB,OAAO,KAAK,6CAA6C,CAC3D,CANS,kCAQT,eAAsB,iCACpB,KAIA,CAGA,GAFA,YAAY,EAER,UAAU,EAAG,CACf,OAAO,MAAM,qDAAqD,EAClE,MACF,CAEA,IAAM,OAAS,QAAQ,aAAa,EAEhC,OACF,OAAO,QAAQ,sBAAuB,MAAM,EAE5C,OAAO,MAAM,aAAa,EAG5B,IAAM,WAAa,MAAM,eAAe,KAAK,QAAU,QAAQ,IAAI,CAAC,EACpE,GAAI,CAAC,WAAY,CACf,IAAM,IAAM,8CACV,KAAK,OAAS,OAAS,KAAK,OAAS,mCACvC,IACA,OAAO,MAAM,GAAG,EAChB,MACF,CAEA,GAAI,CACF,IAAIC,QAAS,MAAM,aAAa,UAAU,EAC1C,OAAO,MAAM,qBAAsB,eAAO,OAAO,UAAU,CAAC,CAC9D,OAAS,EAAG,CACV,OAAO,QAAQ,uBAAuB,EACtC,OAAO,MAAM,eAAO,IAAK,EAAY,OAAS,GAAG,CAAC,EAAE,CAAC,EACrD,MACF,CAEA,IAAM,OAAS,aAAa,EAGtB,WAAa,MAAM,OAAO,aAAa,EAE7C,GAAI,CAEF,MAAM,OAAO,UAAU,UAAU,IACjC,MAAM,OAAO,MAAMA,QAAO,KAAK,CACjC,OAAS,EAAG,CACV,OAAO,MAAM,uCAAwC,CAAC,CACxD,CACF,CAnDsB","names":["config","config","config"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{initializeDevelopmentEnvironment}from"../../chunk-
|
|
1
|
+
import{initializeDevelopmentEnvironment}from"../../chunk-WXW36EYF.mjs";import"../../chunk-QC2F7O3S.mjs";import"../../chunk-UV2LVAQV.mjs";import"../../chunk-BJCWVCAY.mjs";import"../../chunk-FQGSVSCT.mjs";import"../../chunk-DEB7FLUS.mjs";import"../../chunk-QYJ4DE3N.mjs";import"../../chunk-ZJRAI4W5.mjs";import"../../chunk-7KD7ZCH6.mjs";export{initializeDevelopmentEnvironment};
|
|
2
2
|
//# sourceMappingURL=development.mjs.map
|