commandkit 1.2.0-rc.5 → 1.2.0-rc.7
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/{ActionRow-CmTHbo2t.js → ActionRow-CbdGFWMT.js} +3 -2
- package/dist/{ActionRow-CmTHbo2t.js.map → ActionRow-CbdGFWMT.js.map} +1 -1
- package/dist/{CommandKitEventsChannel-Bgw0XCOl.js → CommandKitEventsChannel-B5vbINtP.js} +3 -2
- package/dist/{CommandKitEventsChannel-Bgw0XCOl.js.map → CommandKitEventsChannel-B5vbINtP.js.map} +1 -1
- package/dist/{CommandsRouter-tMAivEfv.js → CommandsRouter-DZAeB2v_.js} +10 -7
- package/dist/{CommandsRouter-tMAivEfv.js.map → CommandsRouter-DZAeB2v_.js.map} +1 -1
- package/dist/{CompilerPlugin-CjoZAAR8.js → CompilerPlugin-M8r3yNAl.js} +2 -2
- package/dist/{CompilerPlugin-CjoZAAR8.js.map → CompilerPlugin-M8r3yNAl.js.map} +1 -1
- package/dist/{EventInterceptor-CQ4PBpBJ.js → EventInterceptor-CQEXyUTp.js} +3 -5
- package/dist/{EventInterceptor-CQ4PBpBJ.js.map → EventInterceptor-CQEXyUTp.js.map} +1 -1
- package/dist/{EventWorkerContext-TZIKxVCu.js → EventWorkerContext-Dq29tieI.js} +3 -2
- package/dist/{EventWorkerContext-TZIKxVCu.js.map → EventWorkerContext-Dq29tieI.js.map} +1 -1
- package/dist/{EventWorkerContext-D9frVhVe.d.ts → EventWorkerContext-xgEc2N2T.d.ts} +2 -2
- package/dist/{EventsRouter-C_J0M3uO.js → EventsRouter-Dzpm7ubq.js} +9 -5
- package/dist/{EventsRouter-C_J0M3uO.js.map → EventsRouter-Dzpm7ubq.js.map} +1 -1
- package/dist/{MessageCommandParser-TPEPhjvx.js → MessageCommandParser-CEuO6Ex3.js} +3 -2
- package/dist/{MessageCommandParser-TPEPhjvx.js.map → MessageCommandParser-CEuO6Ex3.js.map} +1 -1
- package/dist/{PluginCommon-Di1xIa8d.js → PluginCommon-Cvl5yYM_.js} +3 -2
- package/dist/{PluginCommon-Di1xIa8d.js.map → PluginCommon-Cvl5yYM_.js.map} +1 -1
- package/dist/{RuntimePlugin-eTdFJwGd.js → RuntimePlugin-BUecuBIU.js} +2 -2
- package/dist/{RuntimePlugin-eTdFJwGd.js.map → RuntimePlugin-BUecuBIU.js.map} +1 -1
- package/dist/analytics/analytics-engine.d.ts +1 -1
- package/dist/analytics/analytics-engine.js +24 -24
- package/dist/analytics/analytics-provider.d.ts +1 -1
- package/dist/analytics/constants.js +1 -1
- package/dist/analytics/utils.js +24 -24
- package/dist/{analytics-engine-CtMbeudW.d.ts → analytics-engine-6_M8tCeD.d.ts} +16 -4
- package/dist/app/commands/AppCommandRunner.d.ts +1 -1
- package/dist/app/commands/AppCommandRunner.js +24 -24
- package/dist/app/commands/Context.d.ts +1 -1
- package/dist/app/commands/Context.js +24 -24
- package/dist/app/commands/MessageCommandParser.js +1 -1
- package/dist/app/commands/helpers.js +1 -1
- package/dist/app/events/EventWorkerContext.d.ts +2 -2
- package/dist/app/events/EventWorkerContext.js +1 -1
- package/dist/app/handlers/AppCommandHandler.d.ts +1 -1
- package/dist/app/handlers/AppCommandHandler.js +24 -24
- package/dist/app/handlers/AppEventsHandler.d.ts +1 -1
- package/dist/app/handlers/AppEventsHandler.js +24 -24
- package/dist/app/index.d.ts +1 -1
- package/dist/app/index.js +25 -25
- package/dist/app/interrupt/signals.js +2 -2
- package/dist/app/middlewares/permissions.d.ts +1 -1
- package/dist/app/middlewares/permissions.js +24 -24
- package/dist/app/register/CommandRegistrar.d.ts +1 -1
- package/dist/app/register/CommandRegistrar.js +24 -24
- package/dist/app/router/CommandsRouter.js +1 -1
- package/dist/app/router/EventsRouter.js +1 -1
- package/dist/app/router/index.js +2 -2
- package/dist/{app-process-CjMovpoZ.js → app-process-u2DXakNv.js} +8 -5
- package/dist/{app-process-CjMovpoZ.js.map → app-process-u2DXakNv.js.map} +1 -1
- package/dist/{build-D52II1qS.js → build-e6PlVFfe.js} +15 -11
- package/dist/{build-D52II1qS.js.map → build-e6PlVFfe.js.map} +1 -1
- package/dist/cli/app-process.js +4 -4
- package/dist/cli/build.d.ts +1 -1
- package/dist/cli/build.js +26 -26
- package/dist/cli/common.d.ts +1 -1
- package/dist/cli/common.js +3 -3
- package/dist/cli/development.js +39 -39
- package/dist/cli/development.js.map +1 -1
- package/dist/cli/generators.js +9 -6
- package/dist/cli/generators.js.map +1 -1
- package/dist/cli/information.js +14 -19
- package/dist/cli/information.js.map +1 -1
- package/dist/cli/init.js +25 -25
- package/dist/cli/production.js +29 -28
- package/dist/cli/production.js.map +1 -1
- package/dist/cli/type-checker.js +4 -4
- package/dist/{colors-Cd4Oz-r-.js → colors-DL3ucTiT.js} +3 -2
- package/dist/{colors-Cd4Oz-r-.js.map → colors-DL3ucTiT.js.map} +1 -1
- package/dist/{commandkit-BPtNCbV8.js → commandkit-Dy4V-Rk2.js} +143 -156
- package/dist/commandkit-Dy4V-Rk2.js.map +1 -0
- package/dist/commandkit.d.ts +1 -1
- package/dist/commandkit.js +24 -24
- package/dist/{common-DNADUU3_.js → common-DVM_onKu.js} +15 -15
- package/dist/{common-DNADUU3_.js.map → common-DVM_onKu.js.map} +1 -1
- package/dist/common-vnMIelAE.js.map +1 -1
- package/dist/components/common/EventInterceptor.js +1 -1
- package/dist/components/index.js +24 -24
- package/dist/components/v1/action-row/ActionRow.js +1 -1
- package/dist/components/v1/button/Button.js +24 -24
- package/dist/components/v1/button/ButtonKit.js +24 -24
- package/dist/components/v1/modal/Modal.js +24 -24
- package/dist/components/v1/modal/ModalKit.js +24 -24
- package/dist/components/v1/select-menu/ChannelSelectMenuKit.js +24 -24
- package/dist/components/v1/select-menu/MentionableSelectMenuKit.js +24 -24
- package/dist/components/v1/select-menu/RoleSelectMenuKit.js +24 -24
- package/dist/components/v1/select-menu/SelectMenu.js +24 -24
- package/dist/components/v1/select-menu/StringSelectMenuKit.js +24 -24
- package/dist/components/v1/select-menu/UserSelectMenuKit.js +24 -24
- package/dist/components/v2/container.js +1 -1
- package/dist/components/v2/file.js +1 -1
- package/dist/components/v2/index.js +6 -6
- package/dist/components/v2/media-gallery.js +1 -1
- package/dist/components/v2/section.js +1 -1
- package/dist/components/v2/separator.js +1 -1
- package/dist/components/v2/text-display.js +1 -1
- package/dist/config/config.d.ts +2 -2
- package/dist/config/config.js +24 -24
- package/dist/config/default.d.ts +1 -1
- package/dist/config/default.js +24 -24
- package/dist/config/loader.d.ts +1 -1
- package/dist/config/loader.js +24 -24
- package/dist/config/types.d.ts +1 -1
- package/dist/config/utils.d.ts +1 -1
- package/dist/{config-E42bG1RK.d.ts → config-nD7V_D7G.d.ts} +2 -2
- package/dist/constants-B5_Ta7PR.js.map +1 -1
- package/dist/{constants-DxfYtA6t.js → constants-BOOGN85p.js} +3 -2
- package/dist/{constants-DxfYtA6t.js.map → constants-BOOGN85p.js.map} +1 -1
- package/dist/{container-z621KfH5.js → container-C6GtfAPW.js} +3 -2
- package/dist/{container-z621KfH5.js.map → container-C6GtfAPW.js.map} +1 -1
- package/dist/context/async-context.d.ts +2 -2
- package/dist/context/async-context.js +26 -25
- package/dist/context/environment.d.ts +1 -1
- package/dist/context/environment.js +24 -24
- package/dist/{dotprops-C_4L7RPD.js → dotprops-tnhpnszJ.js} +2 -2
- package/dist/{dotprops-C_4L7RPD.js.map → dotprops-tnhpnszJ.js.map} +1 -1
- package/dist/element-Bak9llw_.js.map +1 -1
- package/dist/env-_68PRRoA.js.map +1 -1
- package/dist/error-codes-Ds0bnPvT.js.map +1 -1
- package/dist/events/CommandKitEventsChannel.d.ts +1 -1
- package/dist/events/CommandKitEventsChannel.js +1 -1
- package/dist/{feature-flags-BZ3mW1xe.js → feature-flags-3TQSPAVn.js} +10 -15
- package/dist/{feature-flags-BZ3mW1xe.js.map → feature-flags-3TQSPAVn.js.map} +1 -1
- package/dist/{file-DVZC0QXI.js → file-DVOELoNv.js} +3 -2
- package/dist/{file-DVZC0QXI.js.map → file-DVOELoNv.js.map} +1 -1
- package/dist/flags/FlagProvider.d.ts +1 -1
- package/dist/flags/FlagProvider.js.map +1 -1
- package/dist/flags/feature-flags.d.ts +1 -1
- package/dist/flags/feature-flags.js +25 -25
- package/dist/flags/store.d.ts +1 -1
- package/dist/flags/store.js +1 -1
- package/dist/{helpers-BUlN3lIz.js → helpers-CiuN7y5B.js} +3 -2
- package/dist/{helpers-BUlN3lIz.js.map → helpers-CiuN7y5B.js.map} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +31 -29
- package/dist/index.js.map +1 -1
- package/dist/{init-BjFLN5XX.js → init-Bo01I_h_.js} +11 -8
- package/dist/{init-BjFLN5XX.js.map → init-Bo01I_h_.js.map} +1 -1
- package/dist/kv/dotprops.js +1 -1
- package/dist/kv/kv.js +8 -10
- package/dist/kv/kv.js.map +1 -1
- package/dist/kv/serde.js +1 -1
- package/dist/logger/DefaultLogger.js +24 -24
- package/dist/logger/Logger.js +24 -24
- package/dist/{media-gallery-CIKypjbJ.js → media-gallery-zDtJ3kxb.js} +3 -2
- package/dist/{media-gallery-CIKypjbJ.js.map → media-gallery-zDtJ3kxb.js.map} +1 -1
- package/dist/plugins/CompilerPlugin.d.ts +1 -1
- package/dist/plugins/CompilerPlugin.js +2 -2
- package/dist/plugins/PluginCommon.d.ts +1 -1
- package/dist/plugins/PluginCommon.js +1 -1
- package/dist/plugins/RuntimePlugin.d.ts +1 -1
- package/dist/plugins/RuntimePlugin.js +2 -2
- package/dist/plugins/index.d.ts +1 -1
- package/dist/plugins/index.js +24 -24
- package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.d.ts +1 -1
- package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.js +24 -24
- package/dist/plugins/plugin-runtime/CompilerPluginRuntime.d.ts +1 -1
- package/dist/plugins/plugin-runtime/CompilerPluginRuntime.js +24 -24
- package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.d.ts +1 -1
- package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.js +24 -24
- package/dist/plugins/plugin-runtime/builtin/MacroPlugin.d.ts +1 -1
- package/dist/plugins/plugin-runtime/builtin/MacroPlugin.js +24 -24
- package/dist/plugins/plugin-runtime/runtime.d.ts +1 -1
- package/dist/plugins/types.d.ts +1 -1
- package/dist/{resolve-file-url-DYjaxg_S.js → resolve-file-url-ChIyw-Vf.js} +4 -4
- package/dist/{resolve-file-url-DYjaxg_S.js.map → resolve-file-url-ChIyw-Vf.js.map} +1 -1
- package/dist/{section-CuYr0Inu.js → section-DlvrDoJK.js} +4 -4
- package/dist/{section-CuYr0Inu.js.map → section-DlvrDoJK.js.map} +1 -1
- package/dist/{separator-DLdWBjSN.js → separator-DL6QH5H1.js} +4 -4
- package/dist/{separator-DLdWBjSN.js.map → separator-DL6QH5H1.js.map} +1 -1
- package/dist/{serde-CHySNpFr.js → serde-Cc8iUa9J.js} +2 -2
- package/dist/{serde-CHySNpFr.js.map → serde-Cc8iUa9J.js.map} +1 -1
- package/dist/{signals-r7qPAvOR.js → signals-ChFMD7mB.js} +2 -2
- package/dist/{signals-r7qPAvOR.js.map → signals-ChFMD7mB.js.map} +1 -1
- package/dist/{store-CiqLHedg.js → store-Hcgz7DSt.js} +3 -2
- package/dist/{store-CiqLHedg.js.map → store-Hcgz7DSt.js.map} +1 -1
- package/dist/{text-display--p2-BoUa.js → text-display-DbMumig_.js} +3 -2
- package/dist/{text-display--p2-BoUa.js.map → text-display-DbMumig_.js.map} +1 -1
- package/dist/{type-checker-1Iu1jJcy.js → type-checker-M1NIIoWL.js} +7 -5
- package/dist/{type-checker-1Iu1jJcy.js.map → type-checker-M1NIIoWL.js.map} +1 -1
- package/dist/{types-package-DrnIdWLg.js → types-package-BWArjyBF.js} +7 -4
- package/dist/{types-package-DrnIdWLg.js.map → types-package-BWArjyBF.js.map} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/utils/colors.js +1 -1
- package/dist/utils/dev-hooks.d.ts +1 -1
- package/dist/utils/dev-hooks.js +24 -24
- package/dist/utils/resolve-file-url.js +1 -1
- package/dist/utils/types-package.js +1 -1
- package/dist/utils/useful-stuff/async-queue.js.map +1 -1
- package/dist/utils/useful-stuff/mutex.js +1 -2
- package/dist/utils/useful-stuff/mutex.js.map +1 -1
- package/dist/utils/useful-stuff/ratelimiter.js +2 -4
- package/dist/utils/useful-stuff/ratelimiter.js.map +1 -1
- package/dist/utils/useful-stuff/semaphore.js +2 -4
- package/dist/utils/useful-stuff/semaphore.js.map +1 -1
- package/dist/utils/utilities.js +24 -24
- package/dist/utils/warn-unstable.js.map +1 -1
- package/dist/utils-DCSnVAZ6.js.map +1 -1
- package/dist/utils-KsNof0Xz.js.map +1 -1
- package/dist/{version-DBXZ4wRb.js → version-CphQqt4J.js} +2 -2
- package/dist/{version-DBXZ4wRb.js.map → version-CphQqt4J.js.map} +1 -1
- package/dist/version.js +1 -1
- package/hooks.cjs +2 -0
- package/package.json +2 -2
- package/dist/commandkit-BPtNCbV8.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store-
|
|
1
|
+
{"version":3,"file":"store-Hcgz7DSt.js","names":[],"sources":["../src/flags/store.ts"],"sourcesContent":["import type { FeatureFlag } from './feature-flags';\nimport { Collection } from 'discord.js';\n\n/**\n * Represents a store for feature flags.\n * This store extends the Collection class to manage feature flags by their keys.\n */\nexport class FlagStore extends Collection<string, FeatureFlag<any, any>> {}\n"],"mappings":";;;;;;;;;AAOA,IAAa,YAAb,cAA+B,sBAA0C"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const require_chunk = require('./chunk-nOFOJqeH.js');
|
|
2
|
-
|
|
2
|
+
let discord_js = require("discord.js");
|
|
3
|
+
discord_js = require_chunk.__toESM(discord_js);
|
|
3
4
|
|
|
4
5
|
//#region src/components/v2/text-display.ts
|
|
5
6
|
/**
|
|
@@ -28,4 +29,4 @@ Object.defineProperty(exports, 'TextDisplay', {
|
|
|
28
29
|
return TextDisplay;
|
|
29
30
|
}
|
|
30
31
|
});
|
|
31
|
-
//# sourceMappingURL=text-display
|
|
32
|
+
//# sourceMappingURL=text-display-DbMumig_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text-display
|
|
1
|
+
{"version":3,"file":"text-display-DbMumig_.js","names":[],"sources":["../src/components/v2/text-display.ts"],"sourcesContent":["import { TextDisplayBuilder, TextDisplayComponentData } from 'discord.js';\n\n/**\n * Represents a type that can be encoded as a string.\n */\nexport type StringEncodable = string | number | boolean;\n\n/**\n * Represents the properties for a text display component.\n * This interface extends the TextDisplayComponentData type from discord.js,\n * excluding the 'type' and 'content' properties.\n */\nexport interface TextDisplayProps\n extends Omit<TextDisplayComponentData, 'type' | 'content'> {\n children?: StringEncodable | StringEncodable[];\n content?: string;\n}\n\n/**\n * The components v2 text display component\n * @param props The properties for the text display component.\n * @returns The text display builder instance.\n * @example ```tsx\n * import { TextDisplay } from 'commandkit';\n *\n * const textDisplay = <TextDisplay content=\"Hello, world!\" />;\n * // or\n * const textDisplay = <TextDisplay>Some text content</TextDisplay>;\n * ```\n */\nexport function TextDisplay(props: TextDisplayProps) {\n const textDisplay = new TextDisplayBuilder(props);\n\n if (!props.content && props.children) {\n if (Array.isArray(props.children)) {\n textDisplay.setContent(props.children.join(' '));\n } else {\n textDisplay.setContent(\n typeof props.children === 'string'\n ? props.children\n : String(props.children),\n );\n }\n }\n\n return textDisplay;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8BA,SAAgB,YAAY,OAAyB;CACnD,MAAM,cAAc,IAAI,8BAAmB,MAAM;AAEjD,KAAI,CAAC,MAAM,WAAW,MAAM,SAC1B,KAAI,MAAM,QAAQ,MAAM,SAAS,CAC/B,aAAY,WAAW,MAAM,SAAS,KAAK,IAAI,CAAC;KAEhD,aAAY,WACV,OAAO,MAAM,aAAa,WAC1B,MAAM,WACN,OAAO,MAAM,SAAS,CACvB;AAIL,QAAO"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
const require_chunk = require('./chunk-nOFOJqeH.js');
|
|
2
|
-
const require_colors = require('./colors-
|
|
3
|
-
const require_common = require('./common-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
const require_colors = require('./colors-DL3ucTiT.js');
|
|
3
|
+
const require_common = require('./common-DVM_onKu.js');
|
|
4
|
+
let node_fs = require("node:fs");
|
|
5
|
+
node_fs = require_chunk.__toESM(node_fs);
|
|
6
|
+
let node_path = require("node:path");
|
|
7
|
+
node_path = require_chunk.__toESM(node_path);
|
|
6
8
|
|
|
7
9
|
//#region src/cli/type-checker.ts
|
|
8
10
|
const TS_NOT_FOUND_ERR = `TypeScript must be installed in order to use the type checker. Please install it using \`npm install typescript\` or \`yarn add typescript\``;
|
|
@@ -85,4 +87,4 @@ Object.defineProperty(exports, 'performTypeCheck', {
|
|
|
85
87
|
return performTypeCheck;
|
|
86
88
|
}
|
|
87
89
|
});
|
|
88
|
-
//# sourceMappingURL=type-checker-
|
|
90
|
+
//# sourceMappingURL=type-checker-M1NIIoWL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type-checker-
|
|
1
|
+
{"version":3,"file":"type-checker-M1NIIoWL.js","names":[],"sources":["../src/cli/type-checker.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { loadTypeScript } from './common';\nimport { join, relative } from 'node:path';\nimport colors from '../utils/colors';\n\nconst TS_NOT_FOUND_ERR = `TypeScript must be installed in order to use the type checker. Please install it using \\`npm install typescript\\` or \\`yarn add typescript\\``;\n\n/**\n * Formats a TypeScript diagnostic message in a pretty, readable format\n * @private\n * @internal\n */\nfunction formatDiagnostic(\n ts: typeof import('typescript'),\n diagnostic: import('typescript').Diagnostic,\n cwd: string,\n): string {\n const messageText = ts.flattenDiagnosticMessageText(\n diagnostic.messageText,\n '\\n',\n );\n\n if (!diagnostic.file) {\n return `${colors.red('error')}: ${messageText}`;\n }\n\n const { line, character } = ts.getLineAndCharacterOfPosition(\n diagnostic.file,\n diagnostic.start!,\n );\n const fileName = relative(cwd, diagnostic.file.fileName);\n const position = `${line + 1}:${character + 1}`;\n const errorCode = diagnostic.code ? `TS${diagnostic.code}` : '';\n\n // Format the error message nicely\n return [\n `${colors.bold(colors.cyan(fileName))}:${colors.bold(colors.yellow(position))} - ${colors.red('error')} ${colors.gray(errorCode)}`,\n `${messageText}`,\n ].join('\\n');\n}\n\n/**\n * Performs a type check on the project using TypeScript.\n * @param path The project root or cwd\n * @private\n * @internal\n */\nexport async function performTypeCheck(path: string) {\n const tsconfigPath = join(path, 'tsconfig.json');\n\n if (!existsSync(tsconfigPath)) return;\n\n const ts = await loadTypeScript(TS_NOT_FOUND_ERR);\n\n // Format host for error reporting\n const formatHost = {\n getCanonicalFileName: (path: string) => path,\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getNewLine: () => ts.sys.newLine,\n };\n\n // Read tsconfig.json\n const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n\n if (configFile.error) {\n console.error(\n colors.red(\n `Error reading tsconfig.json: ${ts.formatDiagnostic(configFile.error, formatHost)}`,\n ),\n );\n process.exit(1);\n }\n\n // Parse the config file\n const parsedConfig = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n path,\n );\n\n // Force noEmit to true as we only want type checking\n parsedConfig.options.noEmit = true;\n\n // Create a program\n const program = ts.createProgram({\n rootNames: parsedConfig.fileNames,\n options: parsedConfig.options,\n projectReferences: parsedConfig.projectReferences,\n });\n\n // Get the diagnostics\n const diagnostics = [\n ...program.getOptionsDiagnostics(),\n ...program.getGlobalDiagnostics(),\n ...program.getSyntacticDiagnostics(),\n ...program.getSemanticDiagnostics(),\n ];\n\n // Report any errors\n if (diagnostics.length > 0) {\n console.log('');\n console.error(\n colors.bold(\n colors.red('Type checking failed with the following errors:'),\n ),\n );\n console.log('');\n\n // Group diagnostics by file for better readability\n const byFile = new Map<string, import('typescript').Diagnostic[]>();\n\n for (const diagnostic of diagnostics) {\n const fileName = diagnostic.file ? diagnostic.file.fileName : 'Global';\n if (!byFile.has(fileName)) {\n byFile.set(fileName, []);\n }\n byFile.get(fileName)!.push(diagnostic);\n }\n\n // Pretty-print each diagnostic\n const totalErrors = diagnostics.length;\n let counter = 0;\n\n for (const [_, fileDiags] of byFile) {\n for (const diagnostic of fileDiags) {\n counter++;\n console.log(formatDiagnostic(ts, diagnostic, path));\n // Add separator between errors for better readability, except for the last one\n if (counter < totalErrors) {\n console.log('');\n }\n }\n }\n\n console.log('');\n console.error(\n colors.bold(\n colors.red(`Found ${totalErrors} error${totalErrors > 1 ? 's' : ''}`),\n ),\n );\n console.log('');\n\n process.exit(1);\n }\n\n console.log(colors.green('✓ Type checking completed successfully.'));\n}\n"],"mappings":";;;;;;;;;AAKA,MAAM,mBAAmB;;;;;;AAOzB,SAAS,iBACT,IACA,YACA,KACS;CACP,MAAM,cAAc,GAAG,6BACrB,WAAW,aACX,KACD;AAED,KAAI,CAAC,WAAW,KACd,QAAO,GAAG,8BAAO,IAAI,QAAQ,CAAC,IAAI;CAGpC,MAAM,EAAE,MAAM,cAAc,GAAG,8BAC7B,WAAW,MACX,WAAW,MACZ;CACD,MAAM,mCAAoB,KAAK,WAAW,KAAK,SAAS;CACxD,MAAM,WAAW,GAAG,OAAO,EAAE,GAAG,YAAY;CAC5C,MAAM,YAAY,WAAW,OAAO,KAAK,WAAW,SAAS;AAG7D,QAAO,CACP,GAAG,8BAAO,KAAK,8BAAO,KAAK,SAAS,CAAC,CAAC,GAAG,8BAAO,KAAK,8BAAO,OAAO,SAAS,CAAC,CAAC,KAAK,8BAAO,IAAI,QAAQ,CAAC,GAAG,8BAAO,KAAK,UAAU,IAChI,GAAG,cAAc,CACjB,KAAK,KAAK;;;;;;;;AASZ,eAAsB,iBAAiB,MAAc;CACnD,MAAM,mCAAoB,MAAM,gBAAgB;AAEhD,KAAI,yBAAY,aAAa,CAAE;CAE/B,MAAM,KAAK,MAAM,8BAAe,iBAAiB;CAGjD,MAAM,aAAa;EACjB,uBAAuB,WAAiB;EACxC,qBAAqB,GAAG,IAAI;EAC5B,kBAAkB,GAAG,IAAI;EAC1B;CAGD,MAAM,aAAa,GAAG,eAAe,cAAc,GAAG,IAAI,SAAS;AAEnE,KAAI,WAAW,OAAO;AACpB,UAAQ,MACN,8BAAO,IACL,gCAAgC,GAAG,iBAAiB,WAAW,OAAO,WAAW,GAClF,CACF;AACD,UAAQ,KAAK,EAAE;;CAIjB,MAAM,eAAe,GAAG,2BACtB,WAAW,QACX,GAAG,KACH,KACD;AAGD,cAAa,QAAQ,SAAS;CAG9B,MAAM,UAAU,GAAG,cAAc;EAC/B,WAAW,aAAa;EACxB,SAAS,aAAa;EACtB,mBAAmB,aAAa;EACjC,CAAC;CAGF,MAAM,cAAc;EACpB,GAAG,QAAQ,uBAAuB;EAClC,GAAG,QAAQ,sBAAsB;EACjC,GAAG,QAAQ,yBAAyB;EACpC,GAAG,QAAQ,wBAAwB;EAAC;AAIpC,KAAI,YAAY,SAAS,GAAG;AAC1B,UAAQ,IAAI,GAAG;AACf,UAAQ,MACN,8BAAO,KACL,8BAAO,IAAI,kDAAkD,CAC9D,CACF;AACD,UAAQ,IAAI,GAAG;EAGf,MAAM,yBAAS,IAAI,KAAgD;AAEnE,OAAK,MAAM,cAAc,aAAa;GACpC,MAAM,WAAW,WAAW,OAAO,WAAW,KAAK,WAAW;AAC9D,OAAI,CAAC,OAAO,IAAI,SAAS,CACvB,QAAO,IAAI,UAAU,EAAE,CAAC;AAE1B,UAAO,IAAI,SAAS,CAAE,KAAK,WAAW;;EAIxC,MAAM,cAAc,YAAY;EAChC,IAAI,UAAU;AAEd,OAAK,MAAM,CAAC,GAAG,cAAc,OAC3B,MAAK,MAAM,cAAc,WAAW;AAClC;AACA,WAAQ,IAAI,iBAAiB,IAAI,YAAY,KAAK,CAAC;AAEnD,OAAI,UAAU,YACZ,SAAQ,IAAI,GAAG;;AAKrB,UAAQ,IAAI,GAAG;AACf,UAAQ,MACN,8BAAO,KACL,8BAAO,IAAI,SAAS,YAAY,QAAQ,cAAc,IAAI,MAAM,KAAK,CACtE,CACF;AACD,UAAQ,IAAI,GAAG;AAEf,UAAQ,KAAK,EAAE;;AAGjB,SAAQ,IAAI,8BAAO,MAAM,0CAA0C,CAAC"}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
const require_chunk = require('./chunk-nOFOJqeH.js');
|
|
2
2
|
const require_constants = require('./constants-B5_Ta7PR.js');
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
let node_fs = require("node:fs");
|
|
4
|
+
node_fs = require_chunk.__toESM(node_fs);
|
|
5
|
+
let node_path = require("node:path");
|
|
6
|
+
node_path = require_chunk.__toESM(node_path);
|
|
7
|
+
let node_fs_promises = require("node:fs/promises");
|
|
8
|
+
node_fs_promises = require_chunk.__toESM(node_fs_promises);
|
|
6
9
|
|
|
7
10
|
//#region src/utils/types-package.ts
|
|
8
11
|
/**
|
|
@@ -69,4 +72,4 @@ Object.defineProperty(exports, 'rewriteCommandDeclaration', {
|
|
|
69
72
|
return rewriteCommandDeclaration;
|
|
70
73
|
}
|
|
71
74
|
});
|
|
72
|
-
//# sourceMappingURL=types-package-
|
|
75
|
+
//# sourceMappingURL=types-package-BWArjyBF.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-package-
|
|
1
|
+
{"version":3,"file":"types-package-BWArjyBF.js","names":[],"sources":["../src/utils/types-package.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { COMMANDKIT_CWD, COMMANDKIT_IS_DEV } from './constants';\nimport { existsSync } from 'node:fs';\n\n/**\n * @private\n */\nexport async function generateTypesPackage(force = false) {\n const location = join(COMMANDKIT_CWD, 'node_modules', 'commandkit-types');\n if (!COMMANDKIT_IS_DEV && !force) return location;\n const packageJSON = join(location, 'package.json');\n const index = join(location, 'index.js');\n const types = join(location, 'index.d.ts');\n const command = join(location, 'command.d.ts');\n\n const packageJSONContent = {\n name: 'commandkit-types',\n version: '1.0.0',\n description: 'CommandKit types package',\n type: 'commonjs',\n main: 'index.js',\n types: 'index.d.ts',\n };\n\n const indexContent = `module.exports = {};`;\n\n // Restructuring the type declarations to properly extend rather than replace types\n const typesContent = `// Main types index file - imports all type declarations\nimport './command';\nexport {};\n`;\n\n // Properly set up command types to extend the CommandTypeData interface\n const commandTypesContent = `// Auto-generated command types\n export {};\ndeclare module 'commandkit' {\n type CommandTypeData = string\n}`;\n\n await mkdir(location, { recursive: true }).catch(() => {});\n await writeFile(packageJSON, JSON.stringify(packageJSONContent, null, 2));\n await writeFile(index, indexContent);\n await writeFile(types, typesContent);\n await writeFile(command, commandTypesContent);\n\n return location;\n}\n\n/**\n * @private\n */\nexport async function rewriteCommandDeclaration(data: string) {\n const commandTypesContent = `// Auto-generated command types\n declare module 'commandkit' {\n ${data}\n}\n export {};\n`;\n\n const location = join(COMMANDKIT_CWD, 'node_modules', 'commandkit-types');\n\n if (!existsSync(location)) return;\n\n const type = join(location, 'command.d.ts');\n\n await writeFile(type, commandTypesContent, { encoding: 'utf-8' });\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,eAAsB,qBAAqB,QAAQ,OAAO;CACxD,MAAM,+BAAgB,kCAAgB,gBAAgB,mBAAmB;AACzE,KAAI,CAAC,uCAAqB,CAAC,MAAO,QAAO;CACzC,MAAM,kCAAmB,UAAU,eAAe;CAClD,MAAM,4BAAa,UAAU,WAAW;CACxC,MAAM,4BAAa,UAAU,aAAa;CAC1C,MAAM,8BAAe,UAAU,eAAe;CAE9C,MAAM,qBAAqB;EACzB,MAAM;EACN,SAAS;EACT,aAAa;EACb,MAAM;EACN,MAAM;EACN,OAAO;EACR;CAED,MAAM,eAAe;CAGrB,MAAM,eAAe;;;;CAMrB,MAAM,sBAAsB;;;;;AAM5B,mCAAY,UAAU,EAAE,WAAW,MAAM,CAAC,CAAC,YAAY,GAAG;AAC1D,uCAAgB,aAAa,KAAK,UAAU,oBAAoB,MAAM,EAAE,CAAC;AACzE,uCAAgB,OAAO,aAAa;AACpC,uCAAgB,OAAO,aAAa;AACpC,uCAAgB,SAAS,oBAAoB;AAE7C,QAAO;;;;;AAMT,eAAsB,0BAA0B,MAAc;CAC5D,MAAM,sBAAsB;;MAExB,KAAI;;;;CAKR,MAAM,+BAAgB,kCAAgB,gBAAgB,mBAAmB;AAEzE,KAAI,yBAAY,SAAS,CAAE;CAE3B,MAAM,2BAAY,UAAU,eAAe;AAE3C,uCAAgB,MAAM,qBAAqB,EAAE,UAAU,SAAS,CAAC"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CommandContext, CommandData, CommandKitOptions, CommandMetadata, CommandMetadataFunction, EventHandler, LegacyCommandMetadata } from "./analytics-engine-
|
|
1
|
+
import { CommandContext, CommandData, CommandKitOptions, CommandMetadata, CommandMetadataFunction, EventHandler, LegacyCommandMetadata } from "./analytics-engine-6_M8tCeD.js";
|
|
2
2
|
import "./EventInterceptor-x-R2qshQ.js";
|
|
3
3
|
import "./ButtonKit-C7r7RPNf.js";
|
|
4
4
|
import "./ModalKit-Btz58KYn.js";
|
package/dist/utils/colors.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CommandKitHMREvent, IpcMessageCommand, registerDevHooks } from "../analytics-engine-
|
|
1
|
+
import { CommandKitHMREvent, IpcMessageCommand, registerDevHooks } from "../analytics-engine-6_M8tCeD.js";
|
|
2
2
|
import "../EventInterceptor-x-R2qshQ.js";
|
|
3
3
|
import "../ButtonKit-C7r7RPNf.js";
|
|
4
4
|
import "../ModalKit-Btz58KYn.js";
|
package/dist/utils/dev-hooks.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
require('../colors-
|
|
2
|
-
require('../ActionRow-
|
|
1
|
+
require('../colors-DL3ucTiT.js');
|
|
2
|
+
require('../ActionRow-CbdGFWMT.js');
|
|
3
3
|
require('../error-codes-Ds0bnPvT.js');
|
|
4
|
-
const require_commandkit = require('../commandkit-
|
|
4
|
+
const require_commandkit = require('../commandkit-Dy4V-Rk2.js');
|
|
5
5
|
require('../common-CcfjYnPG.js');
|
|
6
6
|
require('../common-vnMIelAE.js');
|
|
7
|
-
require('../container-
|
|
8
|
-
require('../file-
|
|
9
|
-
require('../media-gallery-
|
|
10
|
-
require('../section-
|
|
11
|
-
require('../separator-
|
|
12
|
-
require('../text-display
|
|
7
|
+
require('../container-C6GtfAPW.js');
|
|
8
|
+
require('../file-DVOELoNv.js');
|
|
9
|
+
require('../media-gallery-zDtJ3kxb.js');
|
|
10
|
+
require('../section-DlvrDoJK.js');
|
|
11
|
+
require('../separator-DL6QH5H1.js');
|
|
12
|
+
require('../text-display-DbMumig_.js');
|
|
13
13
|
require('../v2-DofkPKHs.js');
|
|
14
14
|
require('../element-Bak9llw_.js');
|
|
15
15
|
require('../types-CUZOquUl.js');
|
|
16
|
-
require('../EventInterceptor-
|
|
16
|
+
require('../EventInterceptor-CQEXyUTp.js');
|
|
17
17
|
require('../constants-B5_Ta7PR.js');
|
|
18
|
-
require('../PluginCommon-
|
|
19
|
-
require('../CompilerPlugin-
|
|
20
|
-
require('../RuntimePlugin-
|
|
18
|
+
require('../PluginCommon-Cvl5yYM_.js');
|
|
19
|
+
require('../CompilerPlugin-M8r3yNAl.js');
|
|
20
|
+
require('../RuntimePlugin-BUecuBIU.js');
|
|
21
21
|
require('../types-q0Nm882H.js');
|
|
22
|
-
require('../resolve-file-url-
|
|
22
|
+
require('../resolve-file-url-ChIyw-Vf.js');
|
|
23
23
|
require('../runtime-DB9CiPfe.js');
|
|
24
24
|
require('../utils-KsNof0Xz.js');
|
|
25
|
-
require('../types-package-
|
|
26
|
-
require('../constants-
|
|
27
|
-
require('../EventWorkerContext-
|
|
28
|
-
require('../signals-
|
|
29
|
-
require('../MessageCommandParser-
|
|
30
|
-
require('../CommandsRouter-
|
|
31
|
-
require('../EventsRouter-
|
|
25
|
+
require('../types-package-BWArjyBF.js');
|
|
26
|
+
require('../constants-BOOGN85p.js');
|
|
27
|
+
require('../EventWorkerContext-Dq29tieI.js');
|
|
28
|
+
require('../signals-ChFMD7mB.js');
|
|
29
|
+
require('../MessageCommandParser-CEuO6Ex3.js');
|
|
30
|
+
require('../CommandsRouter-DZAeB2v_.js');
|
|
31
|
+
require('../EventsRouter-Dzpm7ubq.js');
|
|
32
32
|
require('../router-DHnFRADH.js');
|
|
33
|
-
require('../common-
|
|
34
|
-
require('../CommandKitEventsChannel-
|
|
35
|
-
require('../store-
|
|
33
|
+
require('../common-DVM_onKu.js');
|
|
34
|
+
require('../CommandKitEventsChannel-B5vbINtP.js');
|
|
35
|
+
require('../store-Hcgz7DSt.js');
|
|
36
36
|
|
|
37
37
|
exports.registerDevHooks = require_commandkit.registerDevHooks;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
require('../constants-B5_Ta7PR.js');
|
|
2
|
-
const require_types_package = require('../types-package-
|
|
2
|
+
const require_types_package = require('../types-package-BWArjyBF.js');
|
|
3
3
|
|
|
4
4
|
exports.generateTypesPackage = require_types_package.generateTypesPackage;
|
|
5
5
|
exports.rewriteCommandDeclaration = require_types_package.rewriteCommandDeclaration;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-queue.js","names":[],"sources":["../../../src/utils/useful-stuff/async-queue.ts"],"sourcesContent":["/**\n * Async queue implementation for processing tasks sequentially or with limited concurrency.\n * Useful for rate-limiting, batching, or controlling resource usage.\n */\n\nexport interface AsyncQueueOptions {\n /** Maximum number of concurrent tasks. Default: 1 (sequential) */\n concurrency?: number;\n /** Optional callback invoked when all tasks are completed */\n onDrain?: () => void | Promise<void>;\n /** Optional AbortSignal for cancelling the queue */\n signal?: AbortSignal;\n}\n\nexport type AsyncQueueTask<T> = () => Promise<T>;\n\nexport class AsyncQueue {\n private readonly concurrency: number;\n private readonly onDrain?: () => void | Promise<void>;\n private readonly signal?: AbortSignal;\n private running = 0;\n private paused = false;\n private aborted = false;\n private queue: Array<() => void> = [];\n\n constructor(options: AsyncQueueOptions = {}) {\n this.concurrency = options.concurrency ?? 1;\n this.onDrain = options.onDrain;\n this.signal = options.signal;\n\n if (this.signal) {\n this.signal.addEventListener('abort', () => {\n this.abort();\n });\n }\n }\n\n /**\n * Adds a task to the queue.\n * @param task - The async function to execute.\n * @param signal - Optional AbortSignal for cancelling this specific task.\n * @returns Promise resolving to the result of the task.\n */\n public add<T>(task: AsyncQueueTask<T>, signal?: AbortSignal): Promise<T> {\n if (this.aborted) {\n return Promise.reject(new Error('Queue has been aborted'));\n }\n\n return new Promise<T>((resolve, reject) => {\n const run = async () => {\n if (this.paused || this.aborted) {\n if (this.aborted) {\n reject(new Error('Queue has been aborted'));\n } else {\n this.queue.push(run);\n }\n return;\n }\n\n // Check if task-specific signal is aborted\n if (signal?.aborted) {\n reject(new Error('Task was aborted'));\n return;\n }\n\n this.running++;\n try {\n const result = await task();\n resolve(result);\n } catch (err) {\n reject(err);\n } finally {\n this.running--;\n this.next();\n }\n };\n\n if (this.running < this.concurrency && !this.paused && !this.aborted) {\n run();\n } else {\n this.queue.push(run);\n }\n });\n }\n\n /**\n * Pauses the queue. No new tasks will be started until resumed.\n */\n public pause() {\n this.paused = true;\n }\n\n /**\n * Resumes the queue and processes pending tasks.\n */\n public resume() {\n if (!this.paused) return;\n this.paused = false;\n this.next();\n }\n\n /**\n * Aborts the queue, rejecting all pending tasks.\n */\n public abort() {\n this.aborted = true;\n this.clear();\n }\n\n /**\n * Clears all pending tasks from the queue.\n */\n public clear() {\n this.queue = [];\n }\n\n /**\n * Returns the number of running tasks.\n */\n public getRunning(): number {\n return this.running;\n }\n\n /**\n * Returns the number of pending tasks in the queue.\n */\n public getPending(): number {\n return this.queue.length;\n }\n\n /**\n * Returns true if the queue is currently paused.\n */\n public isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Returns true if the queue has been aborted.\n */\n public isAborted(): boolean {\n return this.aborted;\n }\n\n private next() {\n if (this.paused || this.aborted) return;\n while (this.running < this.concurrency && this.queue.length > 0) {\n const fn = this.queue.shift();\n if (fn) fn();\n }\n if (this.running === 0 && this.queue.length === 0 && this.onDrain) {\n this.onDrain();\n }\n }\n}\n\n/**\n * Creates a new async queue instance with the specified configuration.\n * @param options - Configuration options for the async queue.\n * @returns New AsyncQueue instance.\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const queue = createAsyncQueue({\n * concurrency: 2,\n * signal: controller.signal\n * });\n * queue.add(async () => await doSomething());\n * controller.abort(); // Aborts the queue\n * ```\n */\nexport function createAsyncQueue(options?: AsyncQueueOptions): AsyncQueue {\n return new AsyncQueue(options);\n}\n"],"mappings":";;AAgBA,IAAa,aAAb,MAAwB;CACtB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAQ,UAAU;CAClB,AAAQ,SAAS;CACjB,AAAQ,UAAU;CAClB,AAAQ,QAA2B;
|
|
1
|
+
{"version":3,"file":"async-queue.js","names":[],"sources":["../../../src/utils/useful-stuff/async-queue.ts"],"sourcesContent":["/**\n * Async queue implementation for processing tasks sequentially or with limited concurrency.\n * Useful for rate-limiting, batching, or controlling resource usage.\n */\n\nexport interface AsyncQueueOptions {\n /** Maximum number of concurrent tasks. Default: 1 (sequential) */\n concurrency?: number;\n /** Optional callback invoked when all tasks are completed */\n onDrain?: () => void | Promise<void>;\n /** Optional AbortSignal for cancelling the queue */\n signal?: AbortSignal;\n}\n\nexport type AsyncQueueTask<T> = () => Promise<T>;\n\nexport class AsyncQueue {\n private readonly concurrency: number;\n private readonly onDrain?: () => void | Promise<void>;\n private readonly signal?: AbortSignal;\n private running = 0;\n private paused = false;\n private aborted = false;\n private queue: Array<() => void> = [];\n\n constructor(options: AsyncQueueOptions = {}) {\n this.concurrency = options.concurrency ?? 1;\n this.onDrain = options.onDrain;\n this.signal = options.signal;\n\n if (this.signal) {\n this.signal.addEventListener('abort', () => {\n this.abort();\n });\n }\n }\n\n /**\n * Adds a task to the queue.\n * @param task - The async function to execute.\n * @param signal - Optional AbortSignal for cancelling this specific task.\n * @returns Promise resolving to the result of the task.\n */\n public add<T>(task: AsyncQueueTask<T>, signal?: AbortSignal): Promise<T> {\n if (this.aborted) {\n return Promise.reject(new Error('Queue has been aborted'));\n }\n\n return new Promise<T>((resolve, reject) => {\n const run = async () => {\n if (this.paused || this.aborted) {\n if (this.aborted) {\n reject(new Error('Queue has been aborted'));\n } else {\n this.queue.push(run);\n }\n return;\n }\n\n // Check if task-specific signal is aborted\n if (signal?.aborted) {\n reject(new Error('Task was aborted'));\n return;\n }\n\n this.running++;\n try {\n const result = await task();\n resolve(result);\n } catch (err) {\n reject(err);\n } finally {\n this.running--;\n this.next();\n }\n };\n\n if (this.running < this.concurrency && !this.paused && !this.aborted) {\n run();\n } else {\n this.queue.push(run);\n }\n });\n }\n\n /**\n * Pauses the queue. No new tasks will be started until resumed.\n */\n public pause() {\n this.paused = true;\n }\n\n /**\n * Resumes the queue and processes pending tasks.\n */\n public resume() {\n if (!this.paused) return;\n this.paused = false;\n this.next();\n }\n\n /**\n * Aborts the queue, rejecting all pending tasks.\n */\n public abort() {\n this.aborted = true;\n this.clear();\n }\n\n /**\n * Clears all pending tasks from the queue.\n */\n public clear() {\n this.queue = [];\n }\n\n /**\n * Returns the number of running tasks.\n */\n public getRunning(): number {\n return this.running;\n }\n\n /**\n * Returns the number of pending tasks in the queue.\n */\n public getPending(): number {\n return this.queue.length;\n }\n\n /**\n * Returns true if the queue is currently paused.\n */\n public isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Returns true if the queue has been aborted.\n */\n public isAborted(): boolean {\n return this.aborted;\n }\n\n private next() {\n if (this.paused || this.aborted) return;\n while (this.running < this.concurrency && this.queue.length > 0) {\n const fn = this.queue.shift();\n if (fn) fn();\n }\n if (this.running === 0 && this.queue.length === 0 && this.onDrain) {\n this.onDrain();\n }\n }\n}\n\n/**\n * Creates a new async queue instance with the specified configuration.\n * @param options - Configuration options for the async queue.\n * @returns New AsyncQueue instance.\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const queue = createAsyncQueue({\n * concurrency: 2,\n * signal: controller.signal\n * });\n * queue.add(async () => await doSomething());\n * controller.abort(); // Aborts the queue\n * ```\n */\nexport function createAsyncQueue(options?: AsyncQueueOptions): AsyncQueue {\n return new AsyncQueue(options);\n}\n"],"mappings":";;AAgBA,IAAa,aAAb,MAAwB;CACtB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAQ,UAAU;CAClB,AAAQ,SAAS;CACjB,AAAQ,UAAU;CAClB,AAAQ,QAA2B,EAAE;CAErC,YAAY,UAA6B,EAAE,EAAE;AAC3C,OAAK,cAAc,QAAQ,eAAe;AAC1C,OAAK,UAAU,QAAQ;AACvB,OAAK,SAAS,QAAQ;AAEtB,MAAI,KAAK,OACP,MAAK,OAAO,iBAAiB,eAAe;AAC1C,QAAK,OAAO;IACZ;;;;;;;;CAUN,AAAO,IAAO,MAAyB,QAAkC;AACvE,MAAI,KAAK,QACP,QAAO,QAAQ,uBAAO,IAAI,MAAM,yBAAyB,CAAC;AAG5D,SAAO,IAAI,SAAY,SAAS,WAAW;GACzC,MAAM,MAAM,YAAY;AACtB,QAAI,KAAK,UAAU,KAAK,SAAS;AAC/B,SAAI,KAAK,QACP,wBAAO,IAAI,MAAM,yBAAyB,CAAC;SAE3C,MAAK,MAAM,KAAK,IAAI;AAEtB;;AAIF,wDAAI,OAAQ,SAAS;AACnB,4BAAO,IAAI,MAAM,mBAAmB,CAAC;AACrC;;AAGF,SAAK;AACL,QAAI;KACF,MAAM,SAAS,MAAM,MAAM;AAC3B,aAAQ,OAAO;aACR,KAAK;AACZ,YAAO,IAAI;cACH;AACR,UAAK;AACL,UAAK,MAAM;;;AAIf,OAAI,KAAK,UAAU,KAAK,eAAe,CAAC,KAAK,UAAU,CAAC,KAAK,QAC3D,MAAK;OAEL,MAAK,MAAM,KAAK,IAAI;IAEtB;;;;;CAMJ,AAAO,QAAQ;AACb,OAAK,SAAS;;;;;CAMhB,AAAO,SAAS;AACd,MAAI,CAAC,KAAK,OAAQ;AAClB,OAAK,SAAS;AACd,OAAK,MAAM;;;;;CAMb,AAAO,QAAQ;AACb,OAAK,UAAU;AACf,OAAK,OAAO;;;;;CAMd,AAAO,QAAQ;AACb,OAAK,QAAQ,EAAE;;;;;CAMjB,AAAO,aAAqB;AAC1B,SAAO,KAAK;;;;;CAMd,AAAO,aAAqB;AAC1B,SAAO,KAAK,MAAM;;;;;CAMpB,AAAO,WAAoB;AACzB,SAAO,KAAK;;;;;CAMd,AAAO,YAAqB;AAC1B,SAAO,KAAK;;CAGd,AAAQ,OAAO;AACb,MAAI,KAAK,UAAU,KAAK,QAAS;AACjC,SAAO,KAAK,UAAU,KAAK,eAAe,KAAK,MAAM,SAAS,GAAG;GAC/D,MAAM,KAAK,KAAK,MAAM,OAAO;AAC7B,OAAI,GAAI,KAAI;;AAEd,MAAI,KAAK,YAAY,KAAK,KAAK,MAAM,WAAW,KAAK,KAAK,QACxD,MAAK,SAAS;;;;;;;;;;;;;;;;;;;AAqBpB,SAAgB,iBAAiB,SAAyC;AACxE,QAAO,IAAI,WAAW,QAAQ"}
|
|
@@ -117,8 +117,7 @@ var Mutex = class {
|
|
|
117
117
|
* @throws Error if lock acquisition fails or function execution fails
|
|
118
118
|
*/
|
|
119
119
|
async withLock(key, fn, timeout, signal) {
|
|
120
|
-
|
|
121
|
-
if (!acquired) throw new Error(`Failed to acquire lock for key: ${key}`);
|
|
120
|
+
if (!await this.acquire(key, timeout, signal)) throw new Error(`Failed to acquire lock for key: ${key}`);
|
|
122
121
|
try {
|
|
123
122
|
return await fn();
|
|
124
123
|
} finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutex.js","names":[],"sources":["../../../src/utils/useful-stuff/mutex.ts"],"sourcesContent":["/**\n * Async mutex implementation for coordinating access to shared resources.\n * Provides mutual exclusion to ensure only one task can access a resource at a time.\n */\n\n/**\n * Interface for mutex storage implementations.\n * Provides methods to store, retrieve, and delete mutex lock data.\n */\nexport interface MutexStorage {\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n isLocked(key: string): Promise<boolean>;\n}\n\n/**\n * Configuration options for mutex\n */\nexport interface MutexOptions {\n /** Default timeout in milliseconds for lock acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting mutex data. Default: {@link MemoryMutexStorage} */\n storage?: MutexStorage;\n}\n\n/**\n * In-memory storage implementation for mutex locks.\n * Suitable for single-instance applications.\n */\nexport class MemoryMutexStorage implements MutexStorage {\n private readonly locks = new Map<\n string,\n { holder: string; acquiredAt: number }\n >();\n\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const holder = this.generateHolderId();\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Lock acquisition was aborted');\n }\n\n if (!this.locks.has(key)) {\n this.locks.set(key, { holder, acquiredAt: Date.now() });\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n async release(key: string): Promise<void> {\n this.locks.delete(key);\n }\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n async isLocked(key: string): Promise<boolean> {\n return this.locks.has(key);\n }\n\n private generateHolderId(): string {\n return `holder_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async mutex implementation that provides mutual exclusion for shared resources.\n * Ensures only one task can access a protected resource at a time.\n */\nexport class Mutex {\n private storage: MutexStorage;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new mutex instance\n * @param options - Configuration options for the mutex\n */\n public constructor(options: MutexOptions = {}) {\n this.storage = options.storage || new MemoryMutexStorage();\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the mutex\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: MutexStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the mutex\n * @returns The storage implementation\n */\n public getStorage(): MutexStorage {\n return this.storage;\n }\n\n /**\n * Acquires a lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases the lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Checks if a lock is currently held for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n public async isLocked(key: string): Promise<boolean> {\n return this.storage.isLocked(key);\n }\n\n /**\n * Executes a function with exclusive access to the resource\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if lock acquisition fails or function execution fails\n */\n public async withLock<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire lock for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the mutex\n * @returns Object containing the current timeout value\n */\n public getConfig(): Omit<MutexOptions, 'storage'> {\n return {\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default mutex instance for global use\n */\nexport const defaultMutex = new Mutex();\n\n/**\n * Convenience function to execute a function with exclusive access using the default mutex.\n *\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withMutex('shared-resource', async () => {\n * // This code runs with exclusive access\n * return await updateSharedResource();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the lock acquisition\n * ```\n */\nexport async function withMutex<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultMutex.withLock(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new mutex instance with the specified configuration\n * @param options - Configuration options for the mutex\n * @returns New Mutex instance\n *\n * @example\n * ```typescript\n * const mutex = createMutex({\n * timeout: 60000,\n * storage: new RedisMutexStorage()\n * });\n * ```\n */\nexport function createMutex(options: MutexOptions): Mutex {\n return new Mutex(options);\n}\n\n/**\n * Acquires a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\nexport async function acquireLock(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultMutex.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\nexport async function releaseLock(key: string): Promise<void> {\n return defaultMutex.release(key);\n}\n\n/**\n * Checks if a lock is held using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\nexport async function isLocked(key: string): Promise<boolean> {\n return defaultMutex.isLocked(key);\n}\n"],"mappings":";;;;;;AAoDA,IAAa,qBAAb,MAAwD;CACtD,AAAiB,wBAAQ,IAAI;;;;;;;;CAY7B,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,SAAS,KAAK;EACpB,MAAM,YAAY,KAAK;AAEvB,SAAO,KAAK,QAAQ,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM;AAGlB,OAAI,CAAC,KAAK,MAAM,IAAI,MAAM;AACxB,SAAK,MAAM,IAAI,KAAK;KAAE;KAAQ,YAAY,KAAK;;AAC/C,WAAO;;AAET,SAAM,KAAK,MAAM;;AAGnB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;AACxC,OAAK,MAAM,OAAO;;;;;;;CAQpB,MAAM,SAAS,KAA+B;AAC5C,SAAO,KAAK,MAAM,IAAI;;CAGxB,AAAQ,mBAA2B;AACjC,SAAO,UAAU,KAAK,MAAM,GAAG,KAAK,SAAS,SAAS,IAAI,OAAO,GAAG;;CAGtE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS;;;;;;;AAQxD,IAAa,QAAb,MAAmB;CACjB,AAAQ;CACR,AAAiB;;;;;CAMjB,AAAO,YAAY,UAAwB,IAAI;AAC7C,OAAK,UAAU,QAAQ,WAAW,IAAI;AACtC,OAAK,iBAAiB,QAAQ,WAAW;;;;;;CAO3C,AAAO,WAAW,SAAuB;AACvC,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA2B;AAChC,SAAO,KAAK;;;;;;;;;CAUd,MAAa,QACb,KACA,SACA,QACmB;AACjB,SAAO,KAAK,QAAQ,QAAQ,KAAK,WAAW,KAAK,gBAAgB;;;;;;;CAQnE,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ;;;;;;;CAQ9B,MAAa,SAAS,KAA+B;AACnD,SAAO,KAAK,QAAQ,SAAS;;;;;;;;;;;CAY/B,MAAa,SACb,KACA,IACA,SACA,QACa;EACX,MAAM,WAAW,MAAM,KAAK,QAAQ,KAAK,SAAS;AAClD,MAAI,CAAC,SACH,OAAM,IAAI,MAAM,mCAAmC;AAGrD,MAAI;AACF,UAAO,MAAM;YACL;AACR,SAAM,KAAK,QAAQ;;;;;;;CAQvB,AAAO,YAA2C;AAChD,SAAO,EACL,SAAS,KAAK;;;;;;AAQpB,MAAa,eAAe,IAAI;;;;;;;;;;;;;;;;;;;;AAqBhC,eAAsB,UACtB,KACA,IACA,SACA,QACa;AACX,QAAO,aAAa,SAAS,KAAK,IAAI,SAAS;;;;;;;;;;;;;;;AAgBjD,SAAgB,YAAY,SAA8B;AACxD,QAAO,IAAI,MAAM;;;;;;;;;AAUnB,eAAsB,YACtB,KACA,SACA,QACmB;AACjB,QAAO,aAAa,QAAQ,KAAK,SAAS;;;;;;;AAQ5C,eAAsB,YAAY,KAA4B;AAC5D,QAAO,aAAa,QAAQ;;;;;;;AAQ9B,eAAsB,SAAS,KAA+B;AAC5D,QAAO,aAAa,SAAS"}
|
|
1
|
+
{"version":3,"file":"mutex.js","names":[],"sources":["../../../src/utils/useful-stuff/mutex.ts"],"sourcesContent":["/**\n * Async mutex implementation for coordinating access to shared resources.\n * Provides mutual exclusion to ensure only one task can access a resource at a time.\n */\n\n/**\n * Interface for mutex storage implementations.\n * Provides methods to store, retrieve, and delete mutex lock data.\n */\nexport interface MutexStorage {\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n isLocked(key: string): Promise<boolean>;\n}\n\n/**\n * Configuration options for mutex\n */\nexport interface MutexOptions {\n /** Default timeout in milliseconds for lock acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting mutex data. Default: {@link MemoryMutexStorage} */\n storage?: MutexStorage;\n}\n\n/**\n * In-memory storage implementation for mutex locks.\n * Suitable for single-instance applications.\n */\nexport class MemoryMutexStorage implements MutexStorage {\n private readonly locks = new Map<\n string,\n { holder: string; acquiredAt: number }\n >();\n\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const holder = this.generateHolderId();\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Lock acquisition was aborted');\n }\n\n if (!this.locks.has(key)) {\n this.locks.set(key, { holder, acquiredAt: Date.now() });\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n async release(key: string): Promise<void> {\n this.locks.delete(key);\n }\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n async isLocked(key: string): Promise<boolean> {\n return this.locks.has(key);\n }\n\n private generateHolderId(): string {\n return `holder_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async mutex implementation that provides mutual exclusion for shared resources.\n * Ensures only one task can access a protected resource at a time.\n */\nexport class Mutex {\n private storage: MutexStorage;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new mutex instance\n * @param options - Configuration options for the mutex\n */\n public constructor(options: MutexOptions = {}) {\n this.storage = options.storage || new MemoryMutexStorage();\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the mutex\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: MutexStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the mutex\n * @returns The storage implementation\n */\n public getStorage(): MutexStorage {\n return this.storage;\n }\n\n /**\n * Acquires a lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases the lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Checks if a lock is currently held for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n public async isLocked(key: string): Promise<boolean> {\n return this.storage.isLocked(key);\n }\n\n /**\n * Executes a function with exclusive access to the resource\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if lock acquisition fails or function execution fails\n */\n public async withLock<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire lock for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the mutex\n * @returns Object containing the current timeout value\n */\n public getConfig(): Omit<MutexOptions, 'storage'> {\n return {\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default mutex instance for global use\n */\nexport const defaultMutex = new Mutex();\n\n/**\n * Convenience function to execute a function with exclusive access using the default mutex.\n *\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withMutex('shared-resource', async () => {\n * // This code runs with exclusive access\n * return await updateSharedResource();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the lock acquisition\n * ```\n */\nexport async function withMutex<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultMutex.withLock(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new mutex instance with the specified configuration\n * @param options - Configuration options for the mutex\n * @returns New Mutex instance\n *\n * @example\n * ```typescript\n * const mutex = createMutex({\n * timeout: 60000,\n * storage: new RedisMutexStorage()\n * });\n * ```\n */\nexport function createMutex(options: MutexOptions): Mutex {\n return new Mutex(options);\n}\n\n/**\n * Acquires a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\nexport async function acquireLock(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultMutex.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\nexport async function releaseLock(key: string): Promise<void> {\n return defaultMutex.release(key);\n}\n\n/**\n * Checks if a lock is held using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\nexport async function isLocked(key: string): Promise<boolean> {\n return defaultMutex.isLocked(key);\n}\n"],"mappings":";;;;;;AAoDA,IAAa,qBAAb,MAAwD;CACtD,AAAiB,wBAAQ,IAAI,KAG5B;;;;;;;;CASD,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,SAAS,KAAK,kBAAkB;EACtC,MAAM,YAAY,KAAK,KAAK;AAE5B,SAAO,KAAK,KAAK,GAAG,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM,+BAA+B;AAGjD,OAAI,CAAC,KAAK,MAAM,IAAI,IAAI,EAAE;AACxB,SAAK,MAAM,IAAI,KAAK;KAAE;KAAQ,YAAY,KAAK,KAAK;KAAE,CAAC;AACvD,WAAO;;AAET,SAAM,KAAK,MAAM,GAAG;;AAGtB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;AACxC,OAAK,MAAM,OAAO,IAAI;;;;;;;CAQxB,MAAM,SAAS,KAA+B;AAC5C,SAAO,KAAK,MAAM,IAAI,IAAI;;CAG5B,AAAQ,mBAA2B;AACjC,SAAO,UAAU,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,OAAO,GAAG,EAAE;;CAGxE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;AAQ5D,IAAa,QAAb,MAAmB;CACjB,AAAQ;CACR,AAAiB;;;;;CAMjB,AAAO,YAAY,UAAwB,EAAE,EAAE;AAC7C,OAAK,UAAU,QAAQ,WAAW,IAAI,oBAAoB;AAC1D,OAAK,iBAAiB,QAAQ,WAAW;;;;;;CAO3C,AAAO,WAAW,SAAuB;AACvC,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA2B;AAChC,SAAO,KAAK;;;;;;;;;CAUd,MAAa,QACb,KACA,SACA,QACmB;AACjB,SAAO,KAAK,QAAQ,QAAQ,KAAK,WAAW,KAAK,gBAAgB,OAAO;;;;;;;CAQ1E,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ,IAAI;;;;;;;CAQlC,MAAa,SAAS,KAA+B;AACnD,SAAO,KAAK,QAAQ,SAAS,IAAI;;;;;;;;;;;CAYnC,MAAa,SACb,KACA,IACA,SACA,QACa;AAEX,MAAI,CADa,MAAM,KAAK,QAAQ,KAAK,SAAS,OAAO,CAEvD,OAAM,IAAI,MAAM,mCAAmC,MAAM;AAG3D,MAAI;AACF,UAAO,MAAM,IAAI;YACT;AACR,SAAM,KAAK,QAAQ,IAAI;;;;;;;CAQ3B,AAAO,YAA2C;AAChD,SAAO,EACL,SAAS,KAAK,gBACf;;;;;;AAOL,MAAa,eAAe,IAAI,OAAO;;;;;;;;;;;;;;;;;;;;AAqBvC,eAAsB,UACtB,KACA,IACA,SACA,QACa;AACX,QAAO,aAAa,SAAS,KAAK,IAAI,SAAS,OAAO;;;;;;;;;;;;;;;AAgBxD,SAAgB,YAAY,SAA8B;AACxD,QAAO,IAAI,MAAM,QAAQ;;;;;;;;;AAU3B,eAAsB,YACtB,KACA,SACA,QACmB;AACjB,QAAO,aAAa,QAAQ,KAAK,SAAS,OAAO;;;;;;;AAQnD,eAAsB,YAAY,KAA4B;AAC5D,QAAO,aAAa,QAAQ,IAAI;;;;;;;AAQlC,eAAsB,SAAS,KAA+B;AAC5D,QAAO,aAAa,SAAS,IAAI"}
|
|
@@ -82,8 +82,7 @@ var RateLimiter = class {
|
|
|
82
82
|
async limit(key) {
|
|
83
83
|
const now = Date.now();
|
|
84
84
|
const lastReset = this.lastReset.get(key) || 0;
|
|
85
|
-
|
|
86
|
-
if (timeSinceReset > this.resetInterval) {
|
|
85
|
+
if (now - lastReset > this.resetInterval) {
|
|
87
86
|
await this.storage.delete(key);
|
|
88
87
|
this.lastReset.set(key, now);
|
|
89
88
|
this.limits.set(key, 0);
|
|
@@ -111,8 +110,7 @@ var RateLimiter = class {
|
|
|
111
110
|
*/
|
|
112
111
|
async getResetTime(key) {
|
|
113
112
|
const lastReset = this.lastReset.get(key) || 0;
|
|
114
|
-
const
|
|
115
|
-
const timeSinceReset = now - lastReset;
|
|
113
|
+
const timeSinceReset = Date.now() - lastReset;
|
|
116
114
|
if (timeSinceReset >= this.resetInterval) return 0;
|
|
117
115
|
return this.resetInterval - timeSinceReset;
|
|
118
116
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ratelimiter.js","names":[],"sources":["../../../src/utils/useful-stuff/ratelimiter.ts"],"sourcesContent":["/**\n * Default timeout interval for rate limiting in milliseconds\n */\nexport const DEFAULT_TIMEOUT = 60000;\n\n/**\n * Default maximum number of requests allowed per interval\n */\nexport const DEFAULT_MAX_REQUESTS = 10;\n\n/**\n * Interface for rate limit storage implementations.\n * Provides methods to store, retrieve, and delete rate limit data.\n */\nexport interface RateLimitStorage {\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count\n */\n get(key: string): Promise<number>;\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves when the value is stored\n */\n set(key: string, value: number): Promise<void>;\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the entry is deleted\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Configuration options for rate limiting\n */\nexport interface RateLimitOptions {\n /** Maximum number of requests allowed per interval. Default: 10 */\n maxRequests?: number;\n /** Time interval in milliseconds for the rate limit window. Default: 60000 */\n interval?: number;\n /** Storage implementation for persisting rate limit data. Default: {@link MemoryRateLimitStorage} */\n storage?: RateLimitStorage;\n}\n\n/**\n * In-memory storage implementation for rate limiting.\n * Suitable for single-instance applications.\n */\nexport class MemoryRateLimitStorage implements RateLimitStorage {\n private readonly store = new Map<string, number>();\n\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count or 0 if not found\n */\n async get(key: string): Promise<number> {\n return this.store.get(key) || 0;\n }\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves immediately\n */\n async set(key: string, value: number): Promise<void> {\n this.store.set(key, value);\n }\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves immediately\n */\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n}\n\n/**\n * Rate limiter implementation that enforces request limits per key.\n * Supports configurable request limits and time intervals.\n */\nexport class RateLimiter {\n private readonly limits: Map<string, number> = new Map();\n private readonly lastReset: Map<string, number> = new Map();\n private readonly resetInterval: number;\n\n /**\n * Creates a new rate limiter instance\n * @param maxRequests - Maximum number of requests allowed per interval (default: 10)\n * @param interval - Time interval in milliseconds for the rate limit window (default: 60000)\n * @param storage - Optional storage implementation (default: MemoryRateLimitStorage)\n */\n public constructor(\n private readonly maxRequests: number = DEFAULT_MAX_REQUESTS,\n private readonly interval: number = DEFAULT_TIMEOUT,\n private storage: RateLimitStorage = new MemoryRateLimitStorage(),\n ) {\n this.resetInterval = interval;\n }\n\n /**\n * Sets the storage implementation for the rate limiter\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: RateLimitStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the rate limiter\n * @returns The storage implementation\n */\n public getStorage(): RateLimitStorage {\n return this.storage;\n }\n\n /**\n * Checks if a request is allowed for the given key and increments the counter if allowed\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n */\n public async limit(key: string): Promise<boolean> {\n const now = Date.now();\n const lastReset = this.lastReset.get(key) || 0;\n const timeSinceReset = now - lastReset;\n\n // Reset counter if interval has passed\n if (timeSinceReset > this.resetInterval) {\n await this.storage.delete(key);\n this.lastReset.set(key, now);\n this.limits.set(key, 0);\n }\n\n // Get current count from storage\n const currentCount = await this.storage.get(key);\n\n // Check if limit exceeded\n if (currentCount >= this.maxRequests) {\n return false;\n }\n\n // Increment counter\n const newCount = currentCount + 1;\n await this.storage.set(key, newCount);\n this.limits.set(key, newCount);\n\n return true;\n }\n\n /**\n * Gets the remaining requests allowed for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\n public async getRemaining(key: string): Promise<number> {\n const currentCount = await this.storage.get(key);\n return Math.max(0, this.maxRequests - currentCount);\n }\n\n /**\n * Gets the time until the rate limit resets for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset, or 0 if no limit is active\n */\n public async getResetTime(key: string): Promise<number> {\n const lastReset = this.lastReset.get(key) || 0;\n const now = Date.now();\n const timeSinceReset = now - lastReset;\n\n if (timeSinceReset >= this.resetInterval) {\n return 0;\n }\n\n return this.resetInterval - timeSinceReset;\n }\n\n /**\n * Resets the rate limit for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\n public async reset(key: string): Promise<void> {\n await this.storage.delete(key);\n this.limits.delete(key);\n this.lastReset.delete(key);\n }\n\n /**\n * Gets the current configuration of the rate limiter\n * @returns Object containing the current maxRequests and interval values\n */\n public getConfig(): Omit<RateLimitOptions, 'storage'> {\n return {\n maxRequests: this.maxRequests,\n interval: this.interval,\n };\n }\n}\n\n/**\n * Default rate limiter instance for global use\n */\nexport const defaultRateLimiter = new RateLimiter();\n\n/**\n * Convenience function to check if a request is allowed for a given key.\n * Uses the default rate limiter instance.\n *\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n *\n * @example\n * ```typescript\n * const allowed = await ratelimit('user:123');\n * // update the default rate limiter config\n * import { defaultRateLimiter } from 'commandkit/ratelimit';\n *\n * // update max allowed requests\n * defaultRateLimiter.setMaxRequests(10);\n *\n * // update the timeout interval\n * defaultRateLimiter.setInterval(30000);\n *\n * // update the storage implementation\n * defaultRateLimiter.setStorage(new RedisStorage());\n * ```\n */\nexport async function ratelimit(key: string): Promise<boolean> {\n return defaultRateLimiter.limit(key);\n}\n\n/**\n * Creates a new rate limiter instance with the specified configuration\n * @param options - Configuration options for the rate limiter\n * @returns New RateLimiter instance\n *\n * @example\n * ```typescript\n * const limiter = createRateLimiter({\n * maxRequests: 5,\n * interval: 30000,\n * storage: new CustomStorage()\n * });\n * ```\n */\nexport function createRateLimiter(options: RateLimitOptions): RateLimiter {\n return new RateLimiter(\n options.maxRequests,\n options.interval,\n options.storage,\n );\n}\n\n/**\n * Gets the remaining requests for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\nexport async function getRemainingRequests(key: string): Promise<number> {\n return defaultRateLimiter.getRemaining(key);\n}\n\n/**\n * Gets the reset time for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset\n */\nexport async function getResetTime(key: string): Promise<number> {\n return defaultRateLimiter.getResetTime(key);\n}\n\n/**\n * Resets the rate limit for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\nexport async function resetRateLimit(key: string): Promise<void> {\n return defaultRateLimiter.reset(key);\n}\n"],"mappings":";;;;;AAGA,MAAa,kBAAkB;;;;AAK/B,MAAa,uBAAuB;;;;;AA8CpC,IAAa,yBAAb,MAAgE;CAC9D,AAAiB,wBAAQ,IAAI;;;;;;CAO7B,MAAM,IAAI,KAA8B;AACtC,SAAO,KAAK,MAAM,IAAI,QAAQ;;;;;;;;CAShC,MAAM,IAAI,KAAa,OAA8B;AACnD,OAAK,MAAM,IAAI,KAAK;;;;;;;CAQtB,MAAM,OAAO,KAA4B;AACvC,OAAK,MAAM,OAAO;;;;;;;AAQtB,IAAa,cAAb,MAAyB;CACvB,AAAiB,yBAA8B,IAAI;CACnD,AAAiB,4BAAiC,IAAI;CACtD,AAAiB;;;;;;;CAQjB,AAAO,YACP,AAAiB,cAAsB,sBACvC,AAAiB,WAAmB,iBACpC,AAAQ,UAA4B,IAAI,0BACxC;EAHiB;EACA;EACT;AAEN,OAAK,gBAAgB;;;;;;CAOvB,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA+B;AACpC,SAAO,KAAK;;;;;;;CAQd,MAAa,MAAM,KAA+B;EAChD,MAAM,MAAM,KAAK;EACjB,MAAM,YAAY,KAAK,UAAU,IAAI,QAAQ;EAC7C,MAAM,iBAAiB,MAAM;AAG7B,MAAI,iBAAiB,KAAK,eAAe;AACvC,SAAM,KAAK,QAAQ,OAAO;AAC1B,QAAK,UAAU,IAAI,KAAK;AACxB,QAAK,OAAO,IAAI,KAAK;;EAIvB,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI;AAG5C,MAAI,gBAAgB,KAAK,YACvB,QAAO;EAIT,MAAM,WAAW,eAAe;AAChC,QAAM,KAAK,QAAQ,IAAI,KAAK;AAC5B,OAAK,OAAO,IAAI,KAAK;AAErB,SAAO;;;;;;;CAQT,MAAa,aAAa,KAA8B;EACtD,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI;AAC5C,SAAO,KAAK,IAAI,GAAG,KAAK,cAAc;;;;;;;CAQxC,MAAa,aAAa,KAA8B;EACtD,MAAM,YAAY,KAAK,UAAU,IAAI,QAAQ;EAC7C,MAAM,MAAM,KAAK;EACjB,MAAM,iBAAiB,MAAM;AAE7B,MAAI,kBAAkB,KAAK,cACzB,QAAO;AAGT,SAAO,KAAK,gBAAgB;;;;;;;CAQ9B,MAAa,MAAM,KAA4B;AAC7C,QAAM,KAAK,QAAQ,OAAO;AAC1B,OAAK,OAAO,OAAO;AACnB,OAAK,UAAU,OAAO;;;;;;CAOxB,AAAO,YAA+C;AACpD,SAAO;GACL,aAAa,KAAK;GAClB,UAAU,KAAK;;;;;;;AAQrB,MAAa,qBAAqB,IAAI;;;;;;;;;;;;;;;;;;;;;;;;AAyBtC,eAAsB,UAAU,KAA+B;AAC7D,QAAO,mBAAmB,MAAM;;;;;;;;;;;;;;;;AAiBlC,SAAgB,kBAAkB,SAAwC;AACxE,QAAO,IAAI,YACT,QAAQ,aACR,QAAQ,UACR,QAAQ;;;;;;;AASZ,eAAsB,qBAAqB,KAA8B;AACvE,QAAO,mBAAmB,aAAa;;;;;;;AAQzC,eAAsB,aAAa,KAA8B;AAC/D,QAAO,mBAAmB,aAAa;;;;;;;AAQzC,eAAsB,eAAe,KAA4B;AAC/D,QAAO,mBAAmB,MAAM"}
|
|
1
|
+
{"version":3,"file":"ratelimiter.js","names":[],"sources":["../../../src/utils/useful-stuff/ratelimiter.ts"],"sourcesContent":["/**\n * Default timeout interval for rate limiting in milliseconds\n */\nexport const DEFAULT_TIMEOUT = 60000;\n\n/**\n * Default maximum number of requests allowed per interval\n */\nexport const DEFAULT_MAX_REQUESTS = 10;\n\n/**\n * Interface for rate limit storage implementations.\n * Provides methods to store, retrieve, and delete rate limit data.\n */\nexport interface RateLimitStorage {\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count\n */\n get(key: string): Promise<number>;\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves when the value is stored\n */\n set(key: string, value: number): Promise<void>;\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the entry is deleted\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Configuration options for rate limiting\n */\nexport interface RateLimitOptions {\n /** Maximum number of requests allowed per interval. Default: 10 */\n maxRequests?: number;\n /** Time interval in milliseconds for the rate limit window. Default: 60000 */\n interval?: number;\n /** Storage implementation for persisting rate limit data. Default: {@link MemoryRateLimitStorage} */\n storage?: RateLimitStorage;\n}\n\n/**\n * In-memory storage implementation for rate limiting.\n * Suitable for single-instance applications.\n */\nexport class MemoryRateLimitStorage implements RateLimitStorage {\n private readonly store = new Map<string, number>();\n\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count or 0 if not found\n */\n async get(key: string): Promise<number> {\n return this.store.get(key) || 0;\n }\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves immediately\n */\n async set(key: string, value: number): Promise<void> {\n this.store.set(key, value);\n }\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves immediately\n */\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n}\n\n/**\n * Rate limiter implementation that enforces request limits per key.\n * Supports configurable request limits and time intervals.\n */\nexport class RateLimiter {\n private readonly limits: Map<string, number> = new Map();\n private readonly lastReset: Map<string, number> = new Map();\n private readonly resetInterval: number;\n\n /**\n * Creates a new rate limiter instance\n * @param maxRequests - Maximum number of requests allowed per interval (default: 10)\n * @param interval - Time interval in milliseconds for the rate limit window (default: 60000)\n * @param storage - Optional storage implementation (default: MemoryRateLimitStorage)\n */\n public constructor(\n private readonly maxRequests: number = DEFAULT_MAX_REQUESTS,\n private readonly interval: number = DEFAULT_TIMEOUT,\n private storage: RateLimitStorage = new MemoryRateLimitStorage(),\n ) {\n this.resetInterval = interval;\n }\n\n /**\n * Sets the storage implementation for the rate limiter\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: RateLimitStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the rate limiter\n * @returns The storage implementation\n */\n public getStorage(): RateLimitStorage {\n return this.storage;\n }\n\n /**\n * Checks if a request is allowed for the given key and increments the counter if allowed\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n */\n public async limit(key: string): Promise<boolean> {\n const now = Date.now();\n const lastReset = this.lastReset.get(key) || 0;\n const timeSinceReset = now - lastReset;\n\n // Reset counter if interval has passed\n if (timeSinceReset > this.resetInterval) {\n await this.storage.delete(key);\n this.lastReset.set(key, now);\n this.limits.set(key, 0);\n }\n\n // Get current count from storage\n const currentCount = await this.storage.get(key);\n\n // Check if limit exceeded\n if (currentCount >= this.maxRequests) {\n return false;\n }\n\n // Increment counter\n const newCount = currentCount + 1;\n await this.storage.set(key, newCount);\n this.limits.set(key, newCount);\n\n return true;\n }\n\n /**\n * Gets the remaining requests allowed for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\n public async getRemaining(key: string): Promise<number> {\n const currentCount = await this.storage.get(key);\n return Math.max(0, this.maxRequests - currentCount);\n }\n\n /**\n * Gets the time until the rate limit resets for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset, or 0 if no limit is active\n */\n public async getResetTime(key: string): Promise<number> {\n const lastReset = this.lastReset.get(key) || 0;\n const now = Date.now();\n const timeSinceReset = now - lastReset;\n\n if (timeSinceReset >= this.resetInterval) {\n return 0;\n }\n\n return this.resetInterval - timeSinceReset;\n }\n\n /**\n * Resets the rate limit for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\n public async reset(key: string): Promise<void> {\n await this.storage.delete(key);\n this.limits.delete(key);\n this.lastReset.delete(key);\n }\n\n /**\n * Gets the current configuration of the rate limiter\n * @returns Object containing the current maxRequests and interval values\n */\n public getConfig(): Omit<RateLimitOptions, 'storage'> {\n return {\n maxRequests: this.maxRequests,\n interval: this.interval,\n };\n }\n}\n\n/**\n * Default rate limiter instance for global use\n */\nexport const defaultRateLimiter = new RateLimiter();\n\n/**\n * Convenience function to check if a request is allowed for a given key.\n * Uses the default rate limiter instance.\n *\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n *\n * @example\n * ```typescript\n * const allowed = await ratelimit('user:123');\n * // update the default rate limiter config\n * import { defaultRateLimiter } from 'commandkit/ratelimit';\n *\n * // update max allowed requests\n * defaultRateLimiter.setMaxRequests(10);\n *\n * // update the timeout interval\n * defaultRateLimiter.setInterval(30000);\n *\n * // update the storage implementation\n * defaultRateLimiter.setStorage(new RedisStorage());\n * ```\n */\nexport async function ratelimit(key: string): Promise<boolean> {\n return defaultRateLimiter.limit(key);\n}\n\n/**\n * Creates a new rate limiter instance with the specified configuration\n * @param options - Configuration options for the rate limiter\n * @returns New RateLimiter instance\n *\n * @example\n * ```typescript\n * const limiter = createRateLimiter({\n * maxRequests: 5,\n * interval: 30000,\n * storage: new CustomStorage()\n * });\n * ```\n */\nexport function createRateLimiter(options: RateLimitOptions): RateLimiter {\n return new RateLimiter(\n options.maxRequests,\n options.interval,\n options.storage,\n );\n}\n\n/**\n * Gets the remaining requests for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\nexport async function getRemainingRequests(key: string): Promise<number> {\n return defaultRateLimiter.getRemaining(key);\n}\n\n/**\n * Gets the reset time for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset\n */\nexport async function getResetTime(key: string): Promise<number> {\n return defaultRateLimiter.getResetTime(key);\n}\n\n/**\n * Resets the rate limit for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\nexport async function resetRateLimit(key: string): Promise<void> {\n return defaultRateLimiter.reset(key);\n}\n"],"mappings":";;;;;AAGA,MAAa,kBAAkB;;;;AAK/B,MAAa,uBAAuB;;;;;AA8CpC,IAAa,yBAAb,MAAgE;CAC9D,AAAiB,wBAAQ,IAAI,KAAqB;;;;;;CAOlD,MAAM,IAAI,KAA8B;AACtC,SAAO,KAAK,MAAM,IAAI,IAAI,IAAI;;;;;;;;CAShC,MAAM,IAAI,KAAa,OAA8B;AACnD,OAAK,MAAM,IAAI,KAAK,MAAM;;;;;;;CAQ5B,MAAM,OAAO,KAA4B;AACvC,OAAK,MAAM,OAAO,IAAI;;;;;;;AAQ1B,IAAa,cAAb,MAAyB;CACvB,AAAiB,yBAA8B,IAAI,KAAK;CACxD,AAAiB,4BAAiC,IAAI,KAAK;CAC3D,AAAiB;;;;;;;CAQjB,AAAO,YACP,AAAiB,cAAsB,sBACvC,AAAiB,WAAmB,iBACpC,AAAQ,UAA4B,IAAI,wBAAwB,EAChE;EAHiB;EACA;EACT;AAEN,OAAK,gBAAgB;;;;;;CAOvB,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA+B;AACpC,SAAO,KAAK;;;;;;;CAQd,MAAa,MAAM,KAA+B;EAChD,MAAM,MAAM,KAAK,KAAK;EACtB,MAAM,YAAY,KAAK,UAAU,IAAI,IAAI,IAAI;AAI7C,MAHuB,MAAM,YAGR,KAAK,eAAe;AACvC,SAAM,KAAK,QAAQ,OAAO,IAAI;AAC9B,QAAK,UAAU,IAAI,KAAK,IAAI;AAC5B,QAAK,OAAO,IAAI,KAAK,EAAE;;EAIzB,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI,IAAI;AAGhD,MAAI,gBAAgB,KAAK,YACvB,QAAO;EAIT,MAAM,WAAW,eAAe;AAChC,QAAM,KAAK,QAAQ,IAAI,KAAK,SAAS;AACrC,OAAK,OAAO,IAAI,KAAK,SAAS;AAE9B,SAAO;;;;;;;CAQT,MAAa,aAAa,KAA8B;EACtD,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI,IAAI;AAChD,SAAO,KAAK,IAAI,GAAG,KAAK,cAAc,aAAa;;;;;;;CAQrD,MAAa,aAAa,KAA8B;EACtD,MAAM,YAAY,KAAK,UAAU,IAAI,IAAI,IAAI;EAE7C,MAAM,iBADM,KAAK,KAAK,GACO;AAE7B,MAAI,kBAAkB,KAAK,cACzB,QAAO;AAGT,SAAO,KAAK,gBAAgB;;;;;;;CAQ9B,MAAa,MAAM,KAA4B;AAC7C,QAAM,KAAK,QAAQ,OAAO,IAAI;AAC9B,OAAK,OAAO,OAAO,IAAI;AACvB,OAAK,UAAU,OAAO,IAAI;;;;;;CAO5B,AAAO,YAA+C;AACpD,SAAO;GACL,aAAa,KAAK;GAClB,UAAU,KAAK;GAChB;;;;;;AAOL,MAAa,qBAAqB,IAAI,aAAa;;;;;;;;;;;;;;;;;;;;;;;;AAyBnD,eAAsB,UAAU,KAA+B;AAC7D,QAAO,mBAAmB,MAAM,IAAI;;;;;;;;;;;;;;;;AAiBtC,SAAgB,kBAAkB,SAAwC;AACxE,QAAO,IAAI,YACT,QAAQ,aACR,QAAQ,UACR,QAAQ,QACT;;;;;;;AAQH,eAAsB,qBAAqB,KAA8B;AACvE,QAAO,mBAAmB,aAAa,IAAI;;;;;;;AAQ7C,eAAsB,aAAa,KAA8B;AAC/D,QAAO,mBAAmB,aAAa,IAAI;;;;;;;AAQ7C,eAAsB,eAAe,KAA4B;AAC/D,QAAO,mBAAmB,MAAM,IAAI"}
|
|
@@ -108,8 +108,7 @@ var Semaphore = class {
|
|
|
108
108
|
*/
|
|
109
109
|
async acquire(key, timeout, signal) {
|
|
110
110
|
if (this.storage instanceof MemorySemaphoreStorage) {
|
|
111
|
-
|
|
112
|
-
if (totalPermits === 0) this.storage.initialize(key, this.defaultPermits);
|
|
111
|
+
if (await this.storage.getTotalPermits(key) === 0) this.storage.initialize(key, this.defaultPermits);
|
|
113
112
|
}
|
|
114
113
|
return this.storage.acquire(key, timeout || this.defaultTimeout, signal);
|
|
115
114
|
}
|
|
@@ -157,8 +156,7 @@ var Semaphore = class {
|
|
|
157
156
|
* @throws Error if permit acquisition fails or function execution fails
|
|
158
157
|
*/
|
|
159
158
|
async withPermit(key, fn, timeout, signal) {
|
|
160
|
-
|
|
161
|
-
if (!acquired) throw new Error(`Failed to acquire permit for key: ${key}`);
|
|
159
|
+
if (!await this.acquire(key, timeout, signal)) throw new Error(`Failed to acquire permit for key: ${key}`);
|
|
162
160
|
try {
|
|
163
161
|
return await fn();
|
|
164
162
|
} finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"semaphore.js","names":[],"sources":["../../../src/utils/useful-stuff/semaphore.ts"],"sourcesContent":["/**\n * Async semaphore implementation for controlling access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\n\n/**\n * Interface for semaphore storage implementations.\n * Provides methods to store, retrieve, and manage semaphore permit data.\n */\nexport interface SemaphoreStorage {\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n getAvailablePermits(key: string): Promise<number>;\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n getTotalPermits(key: string): Promise<number>;\n}\n\n/**\n * Configuration options for semaphore\n */\nexport interface SemaphoreOptions {\n /** Maximum number of concurrent permits allowed. Default: 1 */\n permits?: number;\n /** Default timeout in milliseconds for permit acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting semaphore data. Default: {@link MemorySemaphoreStorage} */\n storage?: SemaphoreStorage;\n}\n\n/**\n * In-memory storage implementation for semaphore permits.\n * Suitable for single-instance applications.\n */\nexport class MemorySemaphoreStorage implements SemaphoreStorage {\n private readonly semaphores = new Map<\n string,\n { total: number; available: number }\n >();\n\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Permit acquisition was aborted');\n }\n\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available > 0) {\n semaphore.available--;\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n async release(key: string): Promise<void> {\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available < semaphore.total) {\n semaphore.available++;\n }\n }\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n async getAvailablePermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.available : 0;\n }\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n async getTotalPermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.total : 0;\n }\n\n /**\n * Initializes a semaphore with the specified number of permits\n * @param key - The unique identifier for the semaphore\n * @param permits - The total number of permits to allocate\n */\n initialize(key: string, permits: number): void {\n this.semaphores.set(key, { total: permits, available: permits });\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async semaphore implementation that controls access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\nexport class Semaphore {\n private storage: SemaphoreStorage;\n private readonly defaultPermits: number;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new semaphore instance\n * @param options - Configuration options for the semaphore\n */\n public constructor(options: SemaphoreOptions = {}) {\n this.storage = options.storage || new MemorySemaphoreStorage();\n this.defaultPermits = options.permits || 1;\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the semaphore\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: SemaphoreStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the semaphore\n * @returns The storage implementation\n */\n public getStorage(): SemaphoreStorage {\n return this.storage;\n }\n\n /**\n * Acquires a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n // Initialize semaphore if it doesn't exist\n if (this.storage instanceof MemorySemaphoreStorage) {\n const totalPermits = await this.storage.getTotalPermits(key);\n if (totalPermits === 0) {\n (this.storage as MemorySemaphoreStorage).initialize(\n key,\n this.defaultPermits,\n );\n }\n }\n\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Gets the number of available permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n public async getAvailablePermits(key: string): Promise<number> {\n return this.storage.getAvailablePermits(key);\n }\n\n /**\n * Gets the total number of permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n public async getTotalPermits(key: string): Promise<number> {\n return this.storage.getTotalPermits(key);\n }\n\n /**\n * Gets the number of acquired permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\n public async getAcquiredPermits(key: string): Promise<number> {\n const total = await this.getTotalPermits(key);\n const available = await this.getAvailablePermits(key);\n return total - available;\n }\n\n /**\n * Executes a function with a permit from the semaphore\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if permit acquisition fails or function execution fails\n */\n public async withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire permit for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the semaphore\n * @returns Object containing the current permits and timeout values\n */\n public getConfig(): Omit<SemaphoreOptions, 'storage'> {\n return {\n permits: this.defaultPermits,\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default semaphore instance for global use\n */\nexport const defaultSemaphore = new Semaphore();\n\n/**\n * Convenience function to execute a function with a permit using the default semaphore.\n *\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withPermit('database-connection', async () => {\n * // This code runs with a permit from the semaphore\n * return await executeDatabaseQuery();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the permit acquisition\n * ```\n */\nexport async function withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultSemaphore.withPermit(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new semaphore instance with the specified configuration\n * @param options - Configuration options for the semaphore\n * @returns New Semaphore instance\n *\n * @example\n * ```typescript\n * const semaphore = createSemaphore({\n * permits: 5,\n * timeout: 60000,\n * storage: new RedisSemaphoreStorage()\n * });\n * ```\n */\nexport function createSemaphore(options: SemaphoreOptions): Semaphore {\n return new Semaphore(options);\n}\n\n/**\n * Acquires a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\nexport async function acquirePermit(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultSemaphore.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\nexport async function releasePermit(key: string): Promise<void> {\n return defaultSemaphore.release(key);\n}\n\n/**\n * Gets the number of available permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\nexport async function getAvailablePermits(key: string): Promise<number> {\n return defaultSemaphore.getAvailablePermits(key);\n}\n\n/**\n * Gets the number of acquired permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\nexport async function getAcquiredPermits(key: string): Promise<number> {\n return defaultSemaphore.getAcquiredPermits(key);\n}\n"],"mappings":";;;;;;AA6DA,IAAa,yBAAb,MAAgE;CAC9D,AAAiB,6BAAa,IAAI;;;;;;;;CAYlC,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,YAAY,KAAK;AAEvB,SAAO,KAAK,QAAQ,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM;GAGlB,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,OAAI,aAAa,UAAU,YAAY,GAAG;AACxC,cAAU;AACV,WAAO;;AAET,SAAM,KAAK,MAAM;;AAGnB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;EACxC,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,MAAI,aAAa,UAAU,YAAY,UAAU,MAC/C,WAAU;;;;;;;CASd,MAAM,oBAAoB,KAA8B;EACtD,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,SAAO,YAAY,UAAU,YAAY;;;;;;;CAQ3C,MAAM,gBAAgB,KAA8B;EAClD,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,SAAO,YAAY,UAAU,QAAQ;;;;;;;CAQvC,WAAW,KAAa,SAAuB;AAC7C,OAAK,WAAW,IAAI,KAAK;GAAE,OAAO;GAAS,WAAW;;;CAGxD,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS;;;;;;;AAQxD,IAAa,YAAb,MAAuB;CACrB,AAAQ;CACR,AAAiB;CACjB,AAAiB;;;;;CAMjB,AAAO,YAAY,UAA4B,IAAI;AACjD,OAAK,UAAU,QAAQ,WAAW,IAAI;AACtC,OAAK,iBAAiB,QAAQ,WAAW;AACzC,OAAK,iBAAiB,QAAQ,WAAW;;;;;;CAO3C,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA+B;AACpC,SAAO,KAAK;;;;;;;;;CAUd,MAAa,QACb,KACA,SACA,QACmB;AAEjB,MAAI,KAAK,mBAAmB,wBAAwB;GAClD,MAAM,eAAe,MAAM,KAAK,QAAQ,gBAAgB;AACxD,OAAI,iBAAiB,EACnB,CAAC,KAAK,QAAmC,WACvC,KACA,KAAK;;AAKX,SAAO,KAAK,QAAQ,QAAQ,KAAK,WAAW,KAAK,gBAAgB;;;;;;;CAQnE,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ;;;;;;;CAQ9B,MAAa,oBAAoB,KAA8B;AAC7D,SAAO,KAAK,QAAQ,oBAAoB;;;;;;;CAQ1C,MAAa,gBAAgB,KAA8B;AACzD,SAAO,KAAK,QAAQ,gBAAgB;;;;;;;CAQtC,MAAa,mBAAmB,KAA8B;EAC5D,MAAM,QAAQ,MAAM,KAAK,gBAAgB;EACzC,MAAM,YAAY,MAAM,KAAK,oBAAoB;AACjD,SAAO,QAAQ;;;;;;;;;;;CAYjB,MAAa,WACb,KACA,IACA,SACA,QACa;EACX,MAAM,WAAW,MAAM,KAAK,QAAQ,KAAK,SAAS;AAClD,MAAI,CAAC,SACH,OAAM,IAAI,MAAM,qCAAqC;AAGvD,MAAI;AACF,UAAO,MAAM;YACL;AACR,SAAM,KAAK,QAAQ;;;;;;;CAQvB,AAAO,YAA+C;AACpD,SAAO;GACL,SAAS,KAAK;GACd,SAAS,KAAK;;;;;;;AAQpB,MAAa,mBAAmB,IAAI;;;;;;;;;;;;;;;;;;;;AAqBpC,eAAsB,WACtB,KACA,IACA,SACA,QACa;AACX,QAAO,iBAAiB,WAAW,KAAK,IAAI,SAAS;;;;;;;;;;;;;;;;AAiBvD,SAAgB,gBAAgB,SAAsC;AACpE,QAAO,IAAI,UAAU;;;;;;;;;AAUvB,eAAsB,cACtB,KACA,SACA,QACmB;AACjB,QAAO,iBAAiB,QAAQ,KAAK,SAAS;;;;;;;AAQhD,eAAsB,cAAc,KAA4B;AAC9D,QAAO,iBAAiB,QAAQ;;;;;;;AAQlC,eAAsB,oBAAoB,KAA8B;AACtE,QAAO,iBAAiB,oBAAoB;;;;;;;AAQ9C,eAAsB,mBAAmB,KAA8B;AACrE,QAAO,iBAAiB,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"semaphore.js","names":[],"sources":["../../../src/utils/useful-stuff/semaphore.ts"],"sourcesContent":["/**\n * Async semaphore implementation for controlling access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\n\n/**\n * Interface for semaphore storage implementations.\n * Provides methods to store, retrieve, and manage semaphore permit data.\n */\nexport interface SemaphoreStorage {\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n getAvailablePermits(key: string): Promise<number>;\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n getTotalPermits(key: string): Promise<number>;\n}\n\n/**\n * Configuration options for semaphore\n */\nexport interface SemaphoreOptions {\n /** Maximum number of concurrent permits allowed. Default: 1 */\n permits?: number;\n /** Default timeout in milliseconds for permit acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting semaphore data. Default: {@link MemorySemaphoreStorage} */\n storage?: SemaphoreStorage;\n}\n\n/**\n * In-memory storage implementation for semaphore permits.\n * Suitable for single-instance applications.\n */\nexport class MemorySemaphoreStorage implements SemaphoreStorage {\n private readonly semaphores = new Map<\n string,\n { total: number; available: number }\n >();\n\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Permit acquisition was aborted');\n }\n\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available > 0) {\n semaphore.available--;\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n async release(key: string): Promise<void> {\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available < semaphore.total) {\n semaphore.available++;\n }\n }\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n async getAvailablePermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.available : 0;\n }\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n async getTotalPermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.total : 0;\n }\n\n /**\n * Initializes a semaphore with the specified number of permits\n * @param key - The unique identifier for the semaphore\n * @param permits - The total number of permits to allocate\n */\n initialize(key: string, permits: number): void {\n this.semaphores.set(key, { total: permits, available: permits });\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async semaphore implementation that controls access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\nexport class Semaphore {\n private storage: SemaphoreStorage;\n private readonly defaultPermits: number;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new semaphore instance\n * @param options - Configuration options for the semaphore\n */\n public constructor(options: SemaphoreOptions = {}) {\n this.storage = options.storage || new MemorySemaphoreStorage();\n this.defaultPermits = options.permits || 1;\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the semaphore\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: SemaphoreStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the semaphore\n * @returns The storage implementation\n */\n public getStorage(): SemaphoreStorage {\n return this.storage;\n }\n\n /**\n * Acquires a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n // Initialize semaphore if it doesn't exist\n if (this.storage instanceof MemorySemaphoreStorage) {\n const totalPermits = await this.storage.getTotalPermits(key);\n if (totalPermits === 0) {\n (this.storage as MemorySemaphoreStorage).initialize(\n key,\n this.defaultPermits,\n );\n }\n }\n\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Gets the number of available permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n public async getAvailablePermits(key: string): Promise<number> {\n return this.storage.getAvailablePermits(key);\n }\n\n /**\n * Gets the total number of permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n public async getTotalPermits(key: string): Promise<number> {\n return this.storage.getTotalPermits(key);\n }\n\n /**\n * Gets the number of acquired permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\n public async getAcquiredPermits(key: string): Promise<number> {\n const total = await this.getTotalPermits(key);\n const available = await this.getAvailablePermits(key);\n return total - available;\n }\n\n /**\n * Executes a function with a permit from the semaphore\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if permit acquisition fails or function execution fails\n */\n public async withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire permit for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the semaphore\n * @returns Object containing the current permits and timeout values\n */\n public getConfig(): Omit<SemaphoreOptions, 'storage'> {\n return {\n permits: this.defaultPermits,\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default semaphore instance for global use\n */\nexport const defaultSemaphore = new Semaphore();\n\n/**\n * Convenience function to execute a function with a permit using the default semaphore.\n *\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withPermit('database-connection', async () => {\n * // This code runs with a permit from the semaphore\n * return await executeDatabaseQuery();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the permit acquisition\n * ```\n */\nexport async function withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultSemaphore.withPermit(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new semaphore instance with the specified configuration\n * @param options - Configuration options for the semaphore\n * @returns New Semaphore instance\n *\n * @example\n * ```typescript\n * const semaphore = createSemaphore({\n * permits: 5,\n * timeout: 60000,\n * storage: new RedisSemaphoreStorage()\n * });\n * ```\n */\nexport function createSemaphore(options: SemaphoreOptions): Semaphore {\n return new Semaphore(options);\n}\n\n/**\n * Acquires a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\nexport async function acquirePermit(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultSemaphore.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\nexport async function releasePermit(key: string): Promise<void> {\n return defaultSemaphore.release(key);\n}\n\n/**\n * Gets the number of available permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\nexport async function getAvailablePermits(key: string): Promise<number> {\n return defaultSemaphore.getAvailablePermits(key);\n}\n\n/**\n * Gets the number of acquired permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\nexport async function getAcquiredPermits(key: string): Promise<number> {\n return defaultSemaphore.getAcquiredPermits(key);\n}\n"],"mappings":";;;;;;AA6DA,IAAa,yBAAb,MAAgE;CAC9D,AAAiB,6BAAa,IAAI,KAGjC;;;;;;;;CASD,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,YAAY,KAAK,KAAK;AAE5B,SAAO,KAAK,KAAK,GAAG,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM,iCAAiC;GAGnD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,OAAI,aAAa,UAAU,YAAY,GAAG;AACxC,cAAU;AACV,WAAO;;AAET,SAAM,KAAK,MAAM,GAAG;;AAGtB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;EACxC,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,MAAI,aAAa,UAAU,YAAY,UAAU,MAC/C,WAAU;;;;;;;CASd,MAAM,oBAAoB,KAA8B;EACtD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,SAAO,YAAY,UAAU,YAAY;;;;;;;CAQ3C,MAAM,gBAAgB,KAA8B;EAClD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,SAAO,YAAY,UAAU,QAAQ;;;;;;;CAQvC,WAAW,KAAa,SAAuB;AAC7C,OAAK,WAAW,IAAI,KAAK;GAAE,OAAO;GAAS,WAAW;GAAS,CAAC;;CAGlE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;AAQ5D,IAAa,YAAb,MAAuB;CACrB,AAAQ;CACR,AAAiB;CACjB,AAAiB;;;;;CAMjB,AAAO,YAAY,UAA4B,EAAE,EAAE;AACjD,OAAK,UAAU,QAAQ,WAAW,IAAI,wBAAwB;AAC9D,OAAK,iBAAiB,QAAQ,WAAW;AACzC,OAAK,iBAAiB,QAAQ,WAAW;;;;;;CAO3C,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA+B;AACpC,SAAO,KAAK;;;;;;;;;CAUd,MAAa,QACb,KACA,SACA,QACmB;AAEjB,MAAI,KAAK,mBAAmB,wBAE1B;OADqB,MAAM,KAAK,QAAQ,gBAAgB,IAAI,KACvC,EACnB,CAAC,KAAK,QAAmC,WACvC,KACA,KAAK,eACN;;AAIL,SAAO,KAAK,QAAQ,QAAQ,KAAK,WAAW,KAAK,gBAAgB,OAAO;;;;;;;CAQ1E,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ,IAAI;;;;;;;CAQlC,MAAa,oBAAoB,KAA8B;AAC7D,SAAO,KAAK,QAAQ,oBAAoB,IAAI;;;;;;;CAQ9C,MAAa,gBAAgB,KAA8B;AACzD,SAAO,KAAK,QAAQ,gBAAgB,IAAI;;;;;;;CAQ1C,MAAa,mBAAmB,KAA8B;EAC5D,MAAM,QAAQ,MAAM,KAAK,gBAAgB,IAAI;EAC7C,MAAM,YAAY,MAAM,KAAK,oBAAoB,IAAI;AACrD,SAAO,QAAQ;;;;;;;;;;;CAYjB,MAAa,WACb,KACA,IACA,SACA,QACa;AAEX,MAAI,CADa,MAAM,KAAK,QAAQ,KAAK,SAAS,OAAO,CAEvD,OAAM,IAAI,MAAM,qCAAqC,MAAM;AAG7D,MAAI;AACF,UAAO,MAAM,IAAI;YACT;AACR,SAAM,KAAK,QAAQ,IAAI;;;;;;;CAQ3B,AAAO,YAA+C;AACpD,SAAO;GACL,SAAS,KAAK;GACd,SAAS,KAAK;GACf;;;;;;AAOL,MAAa,mBAAmB,IAAI,WAAW;;;;;;;;;;;;;;;;;;;;AAqB/C,eAAsB,WACtB,KACA,IACA,SACA,QACa;AACX,QAAO,iBAAiB,WAAW,KAAK,IAAI,SAAS,OAAO;;;;;;;;;;;;;;;;AAiB9D,SAAgB,gBAAgB,SAAsC;AACpE,QAAO,IAAI,UAAU,QAAQ;;;;;;;;;AAU/B,eAAsB,cACtB,KACA,SACA,QACmB;AACjB,QAAO,iBAAiB,QAAQ,KAAK,SAAS,OAAO;;;;;;;AAQvD,eAAsB,cAAc,KAA4B;AAC9D,QAAO,iBAAiB,QAAQ,IAAI;;;;;;;AAQtC,eAAsB,oBAAoB,KAA8B;AACtE,QAAO,iBAAiB,oBAAoB,IAAI;;;;;;;AAQlD,eAAsB,mBAAmB,KAA8B;AACrE,QAAO,iBAAiB,mBAAmB,IAAI"}
|
package/dist/utils/utilities.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
require('../colors-
|
|
2
|
-
require('../ActionRow-
|
|
1
|
+
require('../colors-DL3ucTiT.js');
|
|
2
|
+
require('../ActionRow-CbdGFWMT.js');
|
|
3
3
|
require('../error-codes-Ds0bnPvT.js');
|
|
4
|
-
const require_commandkit = require('../commandkit-
|
|
4
|
+
const require_commandkit = require('../commandkit-Dy4V-Rk2.js');
|
|
5
5
|
require('../common-CcfjYnPG.js');
|
|
6
6
|
require('../common-vnMIelAE.js');
|
|
7
|
-
require('../container-
|
|
8
|
-
require('../file-
|
|
9
|
-
require('../media-gallery-
|
|
10
|
-
require('../section-
|
|
11
|
-
require('../separator-
|
|
12
|
-
require('../text-display
|
|
7
|
+
require('../container-C6GtfAPW.js');
|
|
8
|
+
require('../file-DVOELoNv.js');
|
|
9
|
+
require('../media-gallery-zDtJ3kxb.js');
|
|
10
|
+
require('../section-DlvrDoJK.js');
|
|
11
|
+
require('../separator-DL6QH5H1.js');
|
|
12
|
+
require('../text-display-DbMumig_.js');
|
|
13
13
|
require('../v2-DofkPKHs.js');
|
|
14
14
|
require('../element-Bak9llw_.js');
|
|
15
15
|
require('../types-CUZOquUl.js');
|
|
16
|
-
require('../EventInterceptor-
|
|
16
|
+
require('../EventInterceptor-CQEXyUTp.js');
|
|
17
17
|
require('../constants-B5_Ta7PR.js');
|
|
18
|
-
require('../PluginCommon-
|
|
19
|
-
require('../CompilerPlugin-
|
|
20
|
-
require('../RuntimePlugin-
|
|
18
|
+
require('../PluginCommon-Cvl5yYM_.js');
|
|
19
|
+
require('../CompilerPlugin-M8r3yNAl.js');
|
|
20
|
+
require('../RuntimePlugin-BUecuBIU.js');
|
|
21
21
|
require('../types-q0Nm882H.js');
|
|
22
|
-
require('../resolve-file-url-
|
|
22
|
+
require('../resolve-file-url-ChIyw-Vf.js');
|
|
23
23
|
require('../runtime-DB9CiPfe.js');
|
|
24
24
|
require('../utils-KsNof0Xz.js');
|
|
25
|
-
require('../types-package-
|
|
26
|
-
require('../constants-
|
|
27
|
-
require('../EventWorkerContext-
|
|
28
|
-
require('../signals-
|
|
29
|
-
require('../MessageCommandParser-
|
|
30
|
-
require('../CommandsRouter-
|
|
31
|
-
require('../EventsRouter-
|
|
25
|
+
require('../types-package-BWArjyBF.js');
|
|
26
|
+
require('../constants-BOOGN85p.js');
|
|
27
|
+
require('../EventWorkerContext-Dq29tieI.js');
|
|
28
|
+
require('../signals-ChFMD7mB.js');
|
|
29
|
+
require('../MessageCommandParser-CEuO6Ex3.js');
|
|
30
|
+
require('../CommandsRouter-DZAeB2v_.js');
|
|
31
|
+
require('../EventsRouter-Dzpm7ubq.js');
|
|
32
32
|
require('../router-DHnFRADH.js');
|
|
33
|
-
require('../common-
|
|
34
|
-
require('../CommandKitEventsChannel-
|
|
35
|
-
require('../store-
|
|
33
|
+
require('../common-DVM_onKu.js');
|
|
34
|
+
require('../CommandKitEventsChannel-B5vbINtP.js');
|
|
35
|
+
require('../store-Hcgz7DSt.js');
|
|
36
36
|
|
|
37
37
|
exports.JsonSerialize = require_commandkit.JsonSerialize;
|
|
38
38
|
exports.createProxy = require_commandkit.createProxy;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"warn-unstable.js","names":[],"sources":["../../src/utils/warn-unstable.ts"],"sourcesContent":["const WARNED_KEYS = new Set<string>();\n\n/**\n * Emit a warning message to the console as a CommandKitWarning.\n * @param message - The warning message to emit.\n * @param code - The warning code (default is 'CommandKitWarning').\n */\nexport function emitWarning(message: string, code = 'CommandKitWarning') {\n process.emitWarning(message, { code });\n}\n\n/**\n * Emit a warning for unstable features in CommandKit.\n * @param name - The name of the unstable feature.\n * @example warnUnstable('MyUnstableFeature');\n */\nexport function warnUnstable(name: string) {\n if (WARNED_KEYS.has(name)) return;\n\n WARNED_KEYS.add(name);\n\n emitWarning(\n `${name} is unstable and may change in future versions.`,\n 'CommandKitUnstableWarning',\n );\n}\n"],"mappings":";;AAAA,MAAM,8BAAc,IAAI;;;;;;
|
|
1
|
+
{"version":3,"file":"warn-unstable.js","names":[],"sources":["../../src/utils/warn-unstable.ts"],"sourcesContent":["const WARNED_KEYS = new Set<string>();\n\n/**\n * Emit a warning message to the console as a CommandKitWarning.\n * @param message - The warning message to emit.\n * @param code - The warning code (default is 'CommandKitWarning').\n */\nexport function emitWarning(message: string, code = 'CommandKitWarning') {\n process.emitWarning(message, { code });\n}\n\n/**\n * Emit a warning for unstable features in CommandKit.\n * @param name - The name of the unstable feature.\n * @example warnUnstable('MyUnstableFeature');\n */\nexport function warnUnstable(name: string) {\n if (WARNED_KEYS.has(name)) return;\n\n WARNED_KEYS.add(name);\n\n emitWarning(\n `${name} is unstable and may change in future versions.`,\n 'CommandKitUnstableWarning',\n );\n}\n"],"mappings":";;AAAA,MAAM,8BAAc,IAAI,KAAa;;;;;;AAOrC,SAAgB,YAAY,SAAiB,OAAO,qBAAqB;AACvE,SAAQ,YAAY,SAAS,EAAE,MAAM,CAAC;;;;;;;AAQxC,SAAgB,aAAa,MAAc;AACzC,KAAI,YAAY,IAAI,KAAK,CAAE;AAE3B,aAAY,IAAI,KAAK;AAErB,aACE,GAAG,KAAK,kDACR,4BACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils-DCSnVAZ6.js","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["import type { Ora } from 'ora';\n\nlet ora: typeof import('ora') | undefined;\n\n/**\n * @private\n * @internal\n */\nexport async function createSpinner(text: string): Promise<Ora> {\n if (!ora) {\n ora = await import('ora');\n }\n\n return (ora.default || ora)({\n text,\n color: 'cyan',\n });\n}\n"],"mappings":";;AAEA,IAAI;;;;;AAMJ,eAAsB,cAAc,MAA4B;AAC9D,KAAI,CAAC,IACH,OAAM,MAAM,OAAO;AAGrB,SAAQ,IAAI,WAAW,KAAK;EAC1B;EACA,OAAO"}
|
|
1
|
+
{"version":3,"file":"utils-DCSnVAZ6.js","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["import type { Ora } from 'ora';\n\nlet ora: typeof import('ora') | undefined;\n\n/**\n * @private\n * @internal\n */\nexport async function createSpinner(text: string): Promise<Ora> {\n if (!ora) {\n ora = await import('ora');\n }\n\n return (ora.default || ora)({\n text,\n color: 'cyan',\n });\n}\n"],"mappings":";;AAEA,IAAI;;;;;AAMJ,eAAsB,cAAc,MAA4B;AAC9D,KAAI,CAAC,IACH,OAAM,MAAM,OAAO;AAGrB,SAAQ,IAAI,WAAW,KAAK;EAC1B;EACA,OAAO;EACR,CAAC"}
|