Skip to content
GitHub

4.3.0 changelog

Published

Entries marked Breaking change a working bot; the migration guide says what to do about them. Every release of the line is in the changelog.

Minor Changes

  • #975 906780b Thanks @l7aromeo! - @MeoCord({ answerDenied: true }) answers a guard's false on an interaction as if the guard had thrown GuardDeniedError. A command, context menu, component or modal a guard denies is told privately "You can't use this." in the user's language, from meocord.guard.denied, which an app's catalogs translate; until now a denied command got Discord's "The application did not respond". The denial takes a thrown one's path: a filter catching GuardDeniedError sees it and can answer otherwise, observers get the outcome 'denied' with deniedBy and the error, and a call with @Defer is answered into its deferral. Autocomplete still closes its menu, an event handler still skips the event, and a message command stays silent, since a false there is often a filter. A guard that throws its own GuardDeniedError keeps its words. In a testing module built from an app that sets the option, invoke rejects with that GuardDeniedError for a guard's false and sends nothing, as it does for a thrown denial, while dispatch answers it as the bot does. Nothing changes until an app sets the option. See https://meocord.dev/docs/4.3/guards.

  • #980 0510d95 Thanks @l7aromeo! - bindTheme now runs each call in the theme of the member and server it answers. A function it wraps rebuilds the theme for every call whose arguments name a server or a user, as a handler's call is themed (an interaction, a message, a reaction, a member): MeoCord's defaults and the app's theme, the @UseTheme layers of the handler that bound it, then themeFor's layers for that call's server and user, in the order a handler's call has them. A collector's collect callback answers each member who clicks in their own theme, and a client.on(...) listener bound in one server's call answers every other server in that server's theme, where both used the theme of the member whose call bound them.

    A theme themeFor is still looking up replaces the handler's once found, so the wrapped function stays synchronous: respond() waits for it, and useTheme() reads the handler's theme until then. A call whose arguments name neither, such as a collector's end, runs in the whole theme of the call that bound it, as before. Once a bot's stop or a testing module's close() has ended its shutdown, a wrapped function asks no themeFor resolver: a call whose arguments name a server or a user runs in the theme of the handler that bound it, and nothing is logged for the lookup. An app without themeFor sees no change. See Theming.

  • #979 1789503 Thanks @l7aromeo! - Under Bun, what the runtime prints itself names your source, as under Node: console.error(error) and any other inspection of an error, an uncaught error, and a rejection nothing handles. sourceMappedStacks mapped only error.stack, so a crash, the trace most worth reading, showed positions in dist/main.js.

    When the bundle maps its stacks (sourceMappedStacks is not false and the build wrote its source map), a bot running on Bun gets:

    • an inspection hook on Error.prototype (Symbol.for('nodejs.util.inspect.custom')), which inspects an error with its mapped stack and keeps its own properties, such as a DiscordAPIError's code, and its cause;
    • an uncaughtException and an unhandledRejection listener on process, which print the error with its mapped stack and end the process as Bun would: code 1 for an uncaught error, and for a rejection as Bun's --unhandled-rejections mode decides. Without the flag a rejection ends the process; under =throw it is raised as an uncaught error, which your own uncaughtException listener gets, or which ends the process when there is none.

    What Bun prints changes with it. console.error(error) and a crash print the error in Node's inspection format, Error: message followed by at lines naming src/ files and any own properties in braces, where Bun printed its own layout: the source line excerpt above the error and, for a crash, the Bun v… line below it are gone. An error whose stack is no string of its own, such as a DOMException or one with a stack getter, is printed by Bun's own formatter, so a crash still shows its name and message. Under --unhandled-rejections=warn, Bun prints its own warning for a rejection, which keeps the bundle's positions. Set sourceMappedStacks: false to keep Bun's own output.

    process.listenerCount() for each of the two events is one higher. An application that listens for either event itself, before or after MeoCord, keeps the error and the exit, also with a listener that removes itself as it runs, as process.once adds one: MeoCord's listener does nothing while another listener is there. The exception is a listener that runs ahead of MeoCord's and removes itself, as one added after MeoCord's with process.prependOnceListener does: it is gone by the time MeoCord's listener runs, so MeoCord also reports the error and exits 1. Under Node nothing changes. See Configuration.

  • #993 264b19d Thanks @l7aromeo! - MeoCord's CommonJS build bundles its ES-module-only dependencies, inversify (with its @inversifyjs/* packages) and chalk, so require('meocord/...') loads nothing that ships only as an ES module. jest, which runs tests as CommonJS, now loads meocord/testing without Node's VM modules: drop NODE_OPTIONS=--experimental-vm-modules from a jest setup that added it for MeoCord. With the flag left in, jest runs as before. The ES module build imports both packages from node_modules as before. A process that loads both builds runs two copies of inversify and of chalk: the one bundled into the CommonJS build and the one in node_modules that the ES module build imports. The two builds' Logger writes the same output under each colour setting. With them, and with the rest of 4.3, dist/cjs is 1765 KB, where 4.2.3's was 1227 KB, and THIRD_PARTY_NOTICES.md carries the bundled packages' licenses. See https://meocord.dev/docs/4.3/testing.

  • #976 77d534b Thanks @l7aromeo! - New commandMention(path, target) in meocord/common gives a clickable mention of one of your slash commands, a subcommand or a grouped subcommand, such as </settings channel:1234567890123456789>, so a help reply or an error can point at the command to run:

    TypeScript
    await respond(interaction).send(`Set a channel first with ${await commandMention('settings channel', interaction)}.`)

    target is the interaction, message, guild or client the mention is shown with. It looks the command up where the reader can use it: the target's guild first, then the global commands. The IDs come from the bot's own registration, or from one request per scope on its first mention, listed again when no scope holds it, so it works in a shard, with commands.register: false, and for commands meocord register sent. A path the app doesn't declare is a RangeError; a command that isn't registered where the reader is, or a mention before the bot is ready, is an Error that says what to do. A scope whose listing fails, such as a guild the bot lost access to, doesn't stop a mention the global scope resolves; if none does, the Error names the failure.

    In tests, a testing module answers from the commands its controllers declare, with a fixed ID per command and no request; MeoCordTestingModule.create({ … }).overrideCommandId(name, id) sets one. See Formatting.

  • #978 4d52db9 Thanks @l7aromeo! - meocord/common exports formatDuration(ms, target?, options?), which writes a length of time for people: formatDuration(3_900_000) is 1h 5m, and { style: 'long' } gives 1 hour, 5 minutes. Given an interaction or a message, it writes in that user's or server's language through your app's translator; given a Locale, through options.t. units, largest, smallest and round choose what it shows, and { style: 'param' } writes 1h30m, which a {x:duration} param reads back, for a value up to Number.MAX_SAFE_INTEGER milliseconds. See Formatting.

    Its unit words are new MeoCord texts in a meocord.duration group, the first of MeoCord's texts with plural forms, which an app's catalog translates like the others, with every plural form its language needs. defineCatalog refuses at compile time a translation of one of them without its other form, with a form that isn't a text, or with a key that is no plural category. expectCompleteCatalog now reports a translation of MeoCord's own plural texts that lacks a form its language needs, such as few in Russian, or that isn't a plural, {} included. See Localisation.

    A plural in a catalog with a form that isn't a text, as a JSON catalog may hold, reads as missing, so the next locale's catalog answers; translating it threw a TypeError.

    cooldownMessage writes its wait with formatDuration, and its output is unchanged for every finite wait. A refusal whose wait is no finite number, as a custom CooldownStore may answer, now tells the caller "Slow down: try again later.", a new MeoCord text meocord.cooldown.later that an app's catalog translates, where they were shown a timestamp Discord couldn't display; cooldownMessage gives the same text where it wrote NaNd NaNh.

  • #978 43396b2 Thanks @l7aromeo! - meocord/common exports permissionNames(permissions, target?, options?), which names permissions as a server owner reads them in Discord's role settings: permissionNames(['ManageMessages', 'BanMembers']) is ['Ban Members', 'Manage Messages'], in bit order, and { join: 'and' } gives Ban Members and Manage Messages, joined as a list in the labels' language. The labels are Discord's own wording, commas included, such as Kick, Approve, and Reject Members. Given an interaction or a message, it names them in that user's or server's language through your app's translator; given a Locale, through options.t. A bit with two flag names, such as 1 << 30, gives one label; a bit with no label gives its flag name, and a bit discord.js doesn't name gives Unknown permission (1 << n). See Formatting.

    The labels are new MeoCord texts in a meocord.permissions group, by flag name, which an app's catalog translates like the others. See Localisation.

  • #978 768018f Thanks @l7aromeo! - meocord/common exports discord.js's formatters under their own names, so a bot imports its formatting from one place: userMention, channelMention, time with TimestampStyles, bold, codeBlock, escapeMarkdown and the rest, 44 functions and constants and 4 types. They are your own discord.js's functions, not copies: userMention from meocord/common is userMention from discord.js, so code that imports them from discord.js keeps working, and their documentation is discord.js's. version and the deprecated underscore aren't exported. A new app's sample button replies with userMention(ownerId). See Formatting.

  • Breaking

    #978 7683c01 Thanks @l7aromeo! - meocord/common exports splitMessage, truncate and DiscordLimits for fitting text to what Discord accepts. splitMessage(text) splits text into messages of at most 2000 characters, or the max you give it: at line ends, a longer line at its last whitespace, never through an emoji or an accented letter. It reads code as Discord does, and closes code cut across messages at the end of one and reopens it in the next, a code block with its language and inline code with its own backticks, so each message shows its part of the text as the whole text does. truncate(text, max) shortens text to max characters with an ellipsis, closing code it cuts open. DiscordLimits names Discord's length limits, such as DiscordLimits.content and DiscordLimits.embedDescription. See Formatting.

    The help reply, MeoCord's own and a presenter.messageHelp string, splits with splitMessage. It splits as before, with these differences: a code block or inline code cut across messages is closed and reopened rather than cut through, no cut parts an escape from the character it escapes or leaves a backtick to pair with another in its message, a line longer than a message breaks at its last whitespace rather than at its last character, dropping the whitespace there, and a CR before a line end is no longer left at the end of a message. See the upgrade guide.

  • #1006 7a633ff Thanks @l7aromeo! - Two changes the next major version (5.0) makes at compile time are now announced:

    • A context menu handler that declares a second parameter is named in a startup warning, and by a testing module as it compiles. A context menu command has no options, so that argument is always {}; remove it. In 5.0 such a handler fails to compile. The check reads the method's parameter count, so a second parameter with a default value, or a rest parameter, goes unnamed. See Context menus.
    • @Autocomplete<T>(…)'s type argument is deprecated, and your editor strikes it through. It did nothing: the handler's return type is inferred. Write @Autocomplete(…); in 5.0 the type argument fails to compile. See Autocomplete.
  • #977 d8e80b3 Thanks @l7aromeo! - A testing module can answer an event handler's refusals as the bot does. With eventFallback: true in MeoCordTestingModule.create() or fromApp(), emit runs the bot's own event fallback: a guard's GuardDeniedError skips the event and the handler isn't counted as run, and a UserError is answered as a reply to the newest message among the event's arguments, with the app's presenter and replyEmoji. Neither rejects emit; any other error still does. The option applies to emit alone, not to invoke of an @On handler. With the option, emit gives each event argument's client the module's presenter, theme and translator without strict mocks too, so the reply is drawn as the bot draws it. A test can now check the reply a member gets:

    TypeScript
    const module = MeoCordTestingModule.fromApp(App, { eventFallback: true }).compile()
    const message = createMockMessage({ content: 'hello' })
    await module.emit('messageCreate', message)
    expect(message.reply).toHaveBeenCalled()

    Without the option emit rejects with both errors as before, and the first time it does, it logs one warning for the run: the next major version (5.0) answers them as the bot does (#964). Set eventFallback: false to keep the rejection without the warning. See Invoke and dispatch.

  • #984 85314bc Thanks @l7aromeo! - meocord generate controller and meocord generate observer now add the class they write to src/app.ts: its import after your last import, and its entry in @MeoCord({ controllers }) or @MeoCord({ observers }), adding observers when the options have none. A controller or observer takes no part until it is listed, and the step was easy to miss. The edit is made with your project's own typescript and inserts only those lines, following the list's layout, indentation and trailing comma; nothing else in the file changes. When your project has ESLint, found from its root as Node finds packages, including one a workspace keeps in a parent folder, the edited file is linted with it, with no fixing, as your app's lint runs it; an edit that would bring an error the file didn't have, such as an import a rule forbids or a line past Prettier's print width, is undone, and the file is left as it was, its modification time included. The file is written in place, as an editor saves it: its mode, owner and links stay, a symlinked src/app.ts edits its target, and one you can't write is refused. Because a typed ESLint config lints the file on disk, the edit is there while it is checked, so start --dev rebuilds twice for an edit that is undone, and three times for one kept in a file that already had lint errors. Ctrl+C, or a SIGTERM outside Windows, while the edit is being checked puts the file back first. When ESLint is missing, can't run or doesn't finish, the class is listed and generate says it went unchecked and why. Pass --skip-app to keep the old behaviour, which leaves src/app.ts alone and prints what to add.

    When the class can't be placed safely, generate writes its files, warns why, prints the two lines to add and changes nothing in src/app.ts: when the file or its @MeoCord({ … }) is missing; the list is not an array written in place (a variable, an import or a call) or holds a spread; the options have a spread or a computed key that may already hold the list; the class's name is already taken in src/app.ts, by a type-only import, an import from another file or a declaration of its own; the edit would fail your lint; or the project's typescript can't be loaded or has no compiler API on its main entry, as with TypeScript 7. A class already imported and listed is left alone. Other kinds, such as services and guards, are used by naming them in code and keep printing their hint. ESLint gets 60 seconds across the runs generate makes, including the one that formats the files it writes: a run still going then is stopped, and killed if it ignores the request, no further run starts, and a warning says the files went unformatted or the edit unchecked, so a config that never finishes no longer holds generate for good. Its report is read from a file of its own, so a config that prints does not leave the edit unchecked. See CLI.

  • #975 0630ee4 Thanks @l7aromeo! - @MeoCord({ globalStagesOnEvents: false }) keeps the app's global guards and interceptors that declare no types from running before @On and @Once handlers. They still run for commands, components, modals, message commands, reactions and autocomplete, so a global blocklist or maintenance guard keeps covering message commands. A stage that declares types keeps exactly what it declares, 'event' included; the guards and interceptors a controller or a handler names, and global exception filters, are unaffected. The default stays true in 4.3 and becomes false in the next major version (5.0), as meocord#502 plans.

    The startup line that named each such stage is now a warning, once per stage, shown only when the app has event handlers and leaves the option unset. To silence it, declare @Guard({ types: [...] }) or @Interceptor({ types: [...] }) on the stage, or set globalStagesOnEvents to true to keep today's behaviour or to false to take 5.0's now. See https://meocord.dev/docs/4.3/guards.

  • #1004 8c63674 Thanks @l7aromeo! - The built-in help reads what joins its lists from two new MeoCord texts: meocord.help.listJoiner, a comma and a space, joins a command's aliases, and meocord.help.paramJoiner, a middle dot with a space on each side, its params. A catalog that translates meocord.help can write them as its language writes a list, such as 、 in Chinese or Japanese. A catalog without them shows the help as before. expectCompleteCatalog(t, { meocord: true }) lists both as missing in a locale that doesn't translate them. See Localisation.

  • #977 5dd3eaf Thanks @l7aromeo! - inspectHandler() reports a handler's @Defer as defer: the options it runs with, with their defaults filled in (ephemeral: false, suppressNotifications: false, disable: 'all', mode: 'eager', and after: 1500 for mode: 'auto'), or undefined without one. A @Defer inherited from the method a handler overrides is reported as the bot applies it. A test can check that a command defers privately without dispatching it:

    TypeScript
    expect(inspectHandler(PingController, 'ping').defer).toEqual({
      ephemeral: true,
      suppressNotifications: false,
      disable: 'all',
      mode: 'eager',
    })

    toEqual on a whole inspection doesn't compare defer, so existing assertions hold. See Invoke and dispatch.

  • #1004 7046f51 Thanks @l7aromeo! - t.localizations(key, params) takes a message with {params} and fills them into each locale's translation, where that translation places them, so descriptions that differ by one word need one catalog key, not one per word. The params are typed from the default message, as t()'s are. A value is a word or a number, used in every locale, or a function of the locale for a value that is itself translated: t.localizations('lookup.user', { mode: locale => t.locale(locale)('modes.chaos') }). The function is called once for each locale whose message uses it. A value, static or from a function, is used as written: a {param} in it stays as text, as t() leaves it. A translator typed Translator<any>, or by hand with messages typed string (a JSON file's shape), takes any params for such a message. A param the default message takes and params leave out, or give as undefined, throws, naming each one. t.localizations(key) without params is unchanged; for a message that takes params, its error now names the params to give. ParamLocalizationKey, LocalizationParam and LocalizationParams are exported from meocord/common, to type a helper that takes such a key or builds its params before passing them on. On a Translator without its catalog type, t.localizations(key, params) and ParamLocalizationKey give the same "This Translator has no catalog type" error as its other methods. See Localisation.

  • #1014 c86a086 Thanks @l7aromeo! - Under useStrictMocks(), a mock answers a property its discord.js class does not have as discord.js does: it reads undefined and is not in the mock, so message.isRepliable?.() gives undefined and if (value.guild) is false for a class without a guild, as on a bot. in is true for a field the class sets on its instances, such as 'content' in message; the fields are read from the source of the discord.js the application installed. A property a test gives or assigns, one the class has, and a mock of an app's own subclass answer as before. Without useStrictMocks() a mock keeps its placeholder, and the first read of such a property by an app's or a test's code logs one warning for the run, naming the property, its class and what strict mocks answer; MeoCord's own reads and the discord.js code a mock runs stay quiet. The next major version (5.0) answers undefined without the call. See Mocks.

  • #977 de3e228 Thanks @l7aromeo! - Under useStrictMocks(), createMockClient() has a working emitter, so a test can attach a collector-style listener to the mock client and see what depends on it:

    • on(), once(), off(), emit(), listeners(), listenerCount() and the emitter's other methods stay mock functions that record each call, and call through to discord.js's, so client.on.mock.calls and toHaveBeenCalledWith work as before and a test can still set its own behaviour. client.on(...) returns the client instead of undefined, listeners() and listenerCount() answer, and emit() reaches every listener attached. discord.js's own InteractionCollector made on the client works, filtered by a message, in a server or a direct message, by a response, as createMessageComponentCollector() builds one, by a channel, a server or a component type, and it ends when its message, channel or server is deleted. For that, a message an interaction sends names it in interactionMetadata, as Discord's do, and a command's message and a message's raw channel_id and guild_id read undefined, as on discord.js's classes, where they read a placeholder. A strict test that read one of those, or a member of the placeholder, now gets undefined: a command's interaction.message.id throws a TypeError, and message.guild_id is undefined. An interaction's authorizingIntegrationOwners is discord.js's AuthorizingIntegrationOwners for an app installed to a server, keyed to the interaction's server or "0" in a direct message with the bot, as Discord sends it, where it was the mock's placeholder object; the message's interactionMetadata holds the same owners. With themeFor, a call in a direct message looks no server up, so a test that expected the guild resolver to be asked for a mock message's generated server there sees no call.
    • module.dispatch() leaves a component or modal no route takes to the mock client's interactionCreate listeners, as the bot leaves it to a collector: it delivers the interaction to them, in the order they were attached, and answers "no handler matched" only if none answered. It doesn't wait 1.5 seconds: it waits for what each listener returns, then one turn of the event loop, so a short test timeout and fake timers still hold. An answer a listener sends only after a timer of its own isn't waited for. A component a route takes isn't delivered to the listeners, unlike on a bot. dispatch() alone delivers it, so a test that also calls client.emit('interactionCreate', interaction) delivers it twice. What a listener throws or rejects with rejects dispatch() once MeoCord has answered.

    A real discord.js Client keeps the 1.5-second wait, and nothing is delivered to its listeners. Without strict mocks, the mock client's emitter attaches and reaches nothing and returns undefined, as before, and the first call an app's or a test's code makes to it logs one warning for the run; MeoCord's own read of the listeners doesn't log it. A test that asserts Logger.warn was never called fails on that warning: assert on the warnings it expects instead, or call useStrictMocks(). Reading a command's message or a message's channel_id or guild_id warns once too, where strict mocks read undefined. The next major version (5.0) has the working emitter without the call (#441). See Components.

  • #987 e2ebbca Thanks @l7aromeo! - Under useStrictMocks(), a mock message's, a mock InteractionResponse's and a mock text-based channel's createMessageComponentCollector() and awaitMessageComponent() run discord.js's own collector on the mock client, so a handler that collects clicks on its reply, or in its channel, runs in its test as it does in the bot:

    • A collector from reply()'s response, from withResponse's resource.message, from a deferral's response once the reply is edited, from update()'s or deferUpdate()'s response, from a mock message, such as a message handler's reply or a component's interaction.message, or from interaction.channel, in a server or a DM, collects a click that module.dispatch() delivers or that a test emits on the client. max, filter, componentType, time, idle and stop() work as in discord.js, and awaitMessageComponent() resolves with the click or rejects on its time. Both stay mock functions that record each call, so toHaveBeenCalledWith works and a test can still set its own behaviour.
    • A click built from a reply, such as createMockInteraction(ButtonInteraction, { customId, message: await command.fetchReply() }), is on the reply's client, so dispatch() delivers it where the collector listens; give client for a click meant for a collector on another client.
    • A component a route takes goes to the route alone, so no collector sees it. discord.js times a collector's time and idle with node:timers, so a test's fake timers don't move them: end a collector in a test with max or collector.stop(). To answer awaitMessageComponent(), start the handler without awaiting it, dispatch the click once the handler has replied, then await the handler.

    A strict test that asserted one of these returned undefined now gets a collector, or a promise of the click. A mock on a real discord.js Client is unchanged, with strict mocks or without: both stay inert with no warning. Without strict mocks both still return undefined, as before; the first call an app's or a test's code makes to one logs one warning for the run. The next major version (5.0) runs the real collector without the call (#441). See Mocks.

  • #977 88c03a4 Thanks @l7aromeo! - Under useStrictMocks(), a mock interaction's answers resolve to what discord.js's do, so a handler that uses the response works in its test:

    • reply(), deferReply(), update() and deferUpdate() resolve to a mock InteractionResponse bound to the interaction. Its edit(), delete() and fetch() reach the interaction's editReply(), deleteReply() and fetchReply(), and createMessageComponentCollector() and awaitMessageComponent() are mock functions, as on a mock message. A test there that asserts resolves.toBeUndefined() on one of them now fails: assert on the response instead, or drop the assertion.
    • With withResponse: true, each resolves to an InteractionCallbackResponse holding what Discord answers. reply()'s and deferReply()'s resource is of type ChannelMessageWithSource and holds the message as fetchReply() reads it at that moment, for deferReply() the loading message, whose id the reply keeps. update()'s is of type UpdateMessage and holds the updated message. deferUpdate() has no resource: it is null. The callback's interaction names the message, the component's for an update, with responseMessageLoading true only for deferReply().
    • A deferred reply reads as Discord shows it until it is edited: fetchReply() after deferReply() gives a message flagged Loading, and Ephemeral too for a private deferral, where it had neither flag. An edit clears Loading.
    • respond(interaction).send() resolves to the message the reply or the update sent, where it resolved to undefined.
    • With withResponse, and so through respond(), the message takes its generated id when the answer resolves, where it took one when first read, so the generated ids of mocks made after it can differ by one.

    Without strict mocks, all of these resolve as before. The first time an app's or a test's own code calls one of the four methods, one warning is logged for the run; MeoCord's own calls, such as @Defer's acknowledgement and respond()'s answers, don't log it. A test that asserts Logger.warn was never called fails on that warning the first time its own code calls one of them: assert on the warnings it expects instead, or call useStrictMocks(). The next major version (5.0) resolves them as strict mocks do, without the call (#441). See Mocks.

  • #1005 94050f2 Thanks @l7aromeo! - Under useStrictMocks(), a mock text-based channel's createMessageCollector() and awaitMessages(), and a mock message's createReactionCollector() and awaitReactions(), run discord.js's own collector on the mock client, and module.dispatch() delivers a message or a reaction to the client's listeners, so a handler that asks a question and waits for the answer, or counts reactions, runs in its test as it does in the bot:

    • dispatch(message) reaches the mock client's messageCreate listeners, and dispatch(reaction, { user }) its messageReactionAdd or messageReactionRemove listeners, routed or not, with discord.js's arguments, a reaction's with { type: ReactionType.Normal, burst: false }. They are the listeners attached before routing starts, called once the route has run to its first await, as the gateway calls them after MeoCord's: a collector a handler starts takes the next message, never the one that started it, and an answer that another command takes still reaches the collector waiting for it. What a listener throws or rejects with rejects dispatch().
    • A dispatched reaction is applied to its message first, as the gateway applies it, by discord.js's own code: an add caches it on message.reactions and counts the user into its users, count and countDetails. Where its message doesn't cache it, the add starts it from none, its users and me too, unless its state is the test's: a count, countDetails, me or users the test gave before its first dispatch, or a count or countDetails set after one. The add then counts on from what is there, count and countDetails apart, as discord.js keeps them. So the first add of a reaction given none of these counts 1, one given me: true counts 2 and keeps me, and a test that sets count to 5 between two dispatches gets 6 from the second. A remove takes the user out of users, and out of the count unless the user is the bot and me is set, as discord.js leaves that to the bot's own REST call; once neither users nor count are left the reaction leaves message.reactions. A remove of a reaction its message doesn't cache is delivered and changes nothing: a real client without Partials.Reaction emits nothing for it, and dispatch delivers it all the same, so a test doesn't show that a bot needs the partial. A partial reaction, its count null, is delivered as it is, as discord.js leaves it. A reaction's countDetails reads { burst: 0, normal: count } unless the test sets it. A dispatched reaction is a normal one, never a burst.
    • A mock MessageReaction is on its message's client, by the rule a mock interaction follows: the client given, else its message's, a real Client included, else a new one, on which its message is made when none is given. A real Client given to the reaction is its own only, and a reaction on a real Client is routed with nothing applied to it or delivered. A strict test that reads a reaction's client gets that client, where it read a placeholder, and dispatch delivers the reaction to that client's listeners.
    • max, filter, time, idle, dispose and stop() work as in discord.js, a reaction collector emits create, remove and dispose, and awaitMessages() and awaitReactions() resolve with what they collected, or reject on their time with errors: ['time']. All four stay mock functions that record each call, so toHaveBeenCalledWith works and a test can still set its own behaviour.

    A strict test that asserted one of these returned undefined, or an empty collection at once, now gets a collector, or a promise of what it collects. discord.js times a collector with node:timers, so a test's fake timers don't move it: a handler that awaits awaitMessages({ time: 60_000 }) with nothing dispatched waits that long, past a test's timeout. Dispatch the answer, give the collector max, or call collector.stop(). A test that both dispatches a message or a reaction and emits the same event on the mock client delivers it twice, and emit applies nothing to a reaction; emit() on the testing module is unchanged and reaches only @On handlers. A mock on a real discord.js Client is unchanged, with strict mocks or without: nothing is delivered and the four stay inert with no warning. Without strict mocks nothing changes: the create methods return undefined, the await methods resolve at once to an empty collection, and dispatch reaches no listener and changes no reaction; the first call an app's or a test's code makes to one of the four logs one warning for the run. The next major version (5.0) runs the real collector without the call (#441). See Mocks.

  • #977 2cad9a0 Thanks @l7aromeo! - A project can have its mocks' values type-checked. Merge typedValues: true into MockTypeOptions from meocord/testing, in a declaration file the tests compile with:

    TypeScript
    // src/types/meocord-testing.d.ts
    import 'meocord/testing'
    
    declare module 'meocord/testing' {
      interface MockTypeOptions {
        typedValues: true
      }
    }

    Every mock's mockReturnValue, mockResolvedValue and mockImplementation then take only what the mocked function returns, resolves to or is, and mock.calls, mock.lastCall, mock.results and mock.settledResults read as its own arguments and results. mockResolvedValue(undefined) stays allowed, since a mock's answers resolve to undefined by default. An overloaded method, such as guild.members.fetch, takes what any of its overloads gives. A partial fake such as mockResolvedValue({ id }) is then refused; cast it where it is intended.

    Without the declaration nothing changes: those values stay any. A project whose tests compile as both ESM and CommonJS declares it in a .d.ts and a .d.cts. MeoCord 5.0 types the values by default (meocord#561). See Mocks.

  • #975 c090957 Thanks @l7aromeo! - OwnerGuard, from meocord/common, lets only the user whose id a component's customId carries use it. Put the id in the route, @Command('card/{ownerId:snowflake}', CommandType.BUTTON), and add @UseGuard(OwnerGuard); anyone else who clicks is told privately, in their own language, "Only the user who opened this can use it." Name another route param or give your own words with @UseGuard({ provide: OwnerGuard, params: { param: 'authorId', message: '…' } }). The text is meocord.guard.notOwner, which an app's catalogs translate. Since the guard throws GuardDeniedError, a filter catching that error can answer otherwise, and observers name it in deniedBy.

    The bot refuses to start with OwnerGuard where it would deny every call: on a slash command, a context menu or an entry point, and on a component or modal handler whose routes lack the param. Written with @UseGuard on a message, reaction, autocomplete or event handler it is refused too; on a controller or in @MeoCord({ guards }) it passes over those handlers, which it never runs for, as a controller's @Cooldown passes over the handlers it never counts. Apps made with meocord create no longer get their own src/guards/owner.guard.ts: the sample button uses OwnerGuard. An app that has that file can keep it, or delete it and import OwnerGuard from meocord/common. See https://meocord.dev/docs/4.3/guards.

  • #979 eeed81e Thanks @l7aromeo! - A self-contained build (bundleDependencies) packs every installed copy of a native addon that bundled code imports, and each importer loads its own. With natpkg@1 at the top of node_modules and natpkg@2 nested under wrap, which needs it, wrap now runs against natpkg@2 from dist alone, where the build packed only natpkg@1 for everyone and warned.

    The copy your project's root resolves to keeps its place at the top of dist/node_modules; under npm, that is the copy npm hoisted to the top of node_modules. With none there, the copy your project's dependencies reach in the fewest steps takes it, the first by name on a tie, so the order the bundler meets imports in doesn't change which. Each other copy is packed with its own dependencies under dist/node_modules/.meocord/<name>-<version>-<hash>/, the hash taken from the chain of dependencies that reaches it from your project, such as wrap>natpkg, so the same installed tree, as a lockfile fixes it, builds the same dist on any machine, and under pnpm the same with its store inside the project or outside it. Its importers load its entry file from there, picked by the bundler as it resolved the import, the exports conditions of an import or a require and subpaths included. pnpm's links to one store copy count as one copy. When the other copy has no file for the request, for example an exports with no entry for require, the build stops and names the copy and the request.

    A project with one copy of each native addon builds exactly as before. See Self-contained builds.

  • #976 b7fa179 Thanks @l7aromeo! - meocord register --prune finds your app's commands left in servers the configuration no longer names, such as a test server after you moved to global commands, where members see every command twice, and removes them. It runs after a successful registration, checks every server the bot is in, and deletes, one request per command removed, only the commands this build declares by name and type, keeping and listing those not declared by this build. --prune all removes those too, asking once in a terminal or with --yes outside one. --dry-run registers nothing and only reports, --prune-guild <id> adds a server the bot isn't in, and --after <id> resumes a run that stopped early. A development run now also warns when this checkout once registered to a server the configuration no longer names. A variable left in your shell or .env file, such as MEOCORD_REGISTER_GUILD, no longer steers meocord register or meocord start: each run registers as its own flags say. See CLI.

  • #984 0d62e30 Thanks @l7aromeo! - A new app from meocord create sends without pings: its clientOptions sets allowedMentions: { parse: [] }, the default discord.js gives every message the client sends, respond()'s replies and your own message.reply and channel.send alike. A reply that echoes a member's text no longer pings whoever that text mentions, @everyone and roles included; one that should ping passes its own allowedMentions, such as { users: [id] }, and a message.reply that should ping its author adds repliedUser: true.

    An existing app whose clientOptions.allowedMentions is unset logs one warning at startup, since the next major version (5.0) makes { parse: [] } the default (#501). Set it to { parse: [] } to have that now, or to { parse: ['users', 'roles', 'everyone'], repliedUser: true } to keep every mention; setting it to anything silences the warning. Nothing else changes. See Security.

  • Breaking

    #1006 f1cfefd Thanks @l7aromeo! - A route() can now read a customId back: route('ticket/{id:int}/close').match('ticket/42/close') returns { id: 42 }, the params its handler would receive. Use it for a customId the bot did not get as a handler call, such as the other buttons on a message or an id kept in a database. A value build encoded with / or % comes back as it was given, and a typed param comes back as its value. match returns undefined for a customId that doesn't match, and an empty object for a matching route without params. It reads that one route, so a customId it matches can still go to a more specific pattern in your app. See Buttons, selects and modals.

    The new RouteMatch<T> type, from meocord/common, is what match returns: the params a customId route gives its handler. It can type a handler's params too, such as { id }: RouteMatch<typeof closeTicket.pattern>.

    Route gains the required match method. A bot that only calls route() needs nothing. Code that writes a Route object by hand no longer compiles until it adds match(customId: string), returning the params or undefined; make the object with route() instead. See the upgrade guide.

  • #993 dabaa35 Thanks @l7aromeo! - A process that loads both of MeoCord's builds, such as jest setup files written in CommonJS beside ES module specs or an ES module bot that uses a CommonJS helper package, now injects the app's own instance into a constructor typed with either build's class. Translator, ThemeCache, ExecutionContext, CooldownStore, MemoryCooldownStore, HandlerRegistry and ShardContext are one class object for both builds of a MeoCord version, so instanceof on these classes agrees between the builds, as it already does for MeoCord's error classes. MeoCord's other exported classes, such as Logger, RedisCooldownStore and MeoCordTestingModule, stay one per build: MeoCord decides nothing by their identity, and only an app's own instanceof across the builds tells them apart. A sharded bot whose memory cooldown store comes from the other build now gets the warning that its per-user and global cooldowns count in each shard alone. Previously a class typed from the other build was given an empty instance (for Translator, ThemeCache, ExecutionContext and CooldownStore) or refused at startup with "has no decorator" (for HandlerRegistry and ShardContext). Two installed versions of MeoCord still keep their classes apart. See https://meocord.dev/docs/4.3/testing.

  • #984 fed44ef Thanks @l7aromeo! - meocord start --prod and meocord register, run without --build, now warn when the build in dist is older than your source, naming the first file changed since, and then run that build as before: dist was built before src/controllers/slash/ping.slash.controller.ts changed, so start --prod runs the previous build. Add --build, or run meocord build --prod first. They also warn when dist holds a development build, as meocord start --dev and meocord build --dev leave it. The exit code and the bot are unaffected.

    Every build writes dist/meocord.build.json, recording its mode and, with their size, mtime and SHA-256, the source files it read, tsconfig.json and each file it extends, and with bundleDependencies your lockfile, whose packages the build copies in. The check reads no file whose size and mtime are unchanged and hashes the rest; it stops after about 200 ms, partway through a large file if need be, and then says nothing. A file whose mtime moved but whose content didn't, as after a checkout or a copy, gives no warning; neither does a dist with no recorded source beside it, as on a server that has only dist, or one built by an earlier MeoCord. As with git, an edit that keeps a file's size and has its old mtime put back is not seen. See CLI.

  • #1063 6503d89 Thanks @l7aromeo! - A testing module's dispatch(), invoke() or emit() made while init() is still running, which a close() then ends, no longer starts. Before, such a call went on once init() resolved: it ran its handler against the closed module, on classes close() had already shut down, logged nothing and resolved as a call that ran, with ran: true, or ran: 1 for emit(). Now it settles as a call the bot drops at a stop: no handler runs, nothing is made for it, and it reports the error "The bot stopped before this call started.". dispatch() resolves with ran: false, that error and no handlers, and invoke() with ran: false and that error. EmitResult gains an optional error, so a dropped event resolves with ran: 0 and that error. error is set only for a dropped event, so every other emit() still resolves with { ran: n }. A call made after close() is unchanged: it warns and runs. See https://meocord.dev/docs/4.3/testing.

  • #1004 726ddee Thanks @l7aromeo! - Each ValidationIssue from a @Validate schema keeps the issue the schema reported, as raw, typed StandardSchemaV1Issue. An exception filter can read the library's own fields from it, such as zod's code and minimum, to word a refusal in the user's language instead of parsing the library's English message. raw is non-enumerable, so toEqual({ message, path }) and a serialised issue are unchanged, and an issue you build yourself has none. See Validation.

  • #983 1c9036f Thanks @l7aromeo! - @MeoCord({ waitForReady: true }) holds each call until the onReady hooks of the classes it uses have settled, so a handler no longer needs a flag or a promise of its own to avoid reading a cache before it is warm. It is off unless set.

    • A call waits for the hooks of its handler's class, the guards, interceptors, filters and pipes that run for it, global ones included, the presenter, the themeFor class, and what each of them injects. It doesn't wait for a hook ordered after all of those. The hooks still run one at a time, so it also waits for a slower hook ordered before its own.
    • No server's or user's theme is looked up before the themeFor class's own hooks have settled, whether in a call, in a function bindTheme wraps, or in an answer outside any call. A lookup follows what Discord has been told of its interaction, as the call does: once Discord has an acknowledgement or an answer, it waits as long as the hooks run; while one is on its way, it waits for the outcome, neither going ahead nor warning; told nothing, as without @Defer, it waits until 2 seconds after the interaction was created, or 2 seconds from the first wait for it for one with no creation time or one ahead of the clock, which its warning then reads as "after waiting 2.0 s", then goes ahead with a warning, at once if those have passed. A call and the lookups for its interaction waiting at once go ahead together, on one decision: the call first, its warning naming the hook, and the lookups then without one of their own; a lookup that starts once that decision is made follows the rule afresh. An autocomplete's waits 1 second the same way. @Defer({ mode: 'auto' })'s acknowledgement counts as on its way from the call's start until it is sent or an answer's Discord call replaces it; an answer still waiting for its theme doesn't hold it back, and goes out after it, as an edit, the acknowledgement as private as that answer, whatever @Defer's ephemeral says. The warning: PrefsThemes looked up a theme before onReady in Prefs had settled, 2.0 s after the interaction was created, as long as an interaction Discord has been told nothing of waits. Make onReady in Prefs faster.
    • The call waits after @Defer acknowledges it and before its guards, so a deferred command is acknowledged at once and waits as long as its hooks run; @Defer({ mode: 'auto' }) keeps its timer running through the wait.
    • An interaction without @Defer waits until 2 seconds after it was created and an autocomplete 1 second, then runs, with one warning per hook naming it, whatever warnSlow says: PricesController.price ran before onReady in PriceCache had settled, 2.0 s after the interaction was created, as long as an interaction without @Defer waits. Add @Defer to PricesController.price to have it wait for the hook, or make onReady in PriceCache faster. A message, a reaction and an event wait as long as the hooks run.
    • That wait and the wait for themeFor share one deadline, 2 seconds after the interaction was created (1 second for an autocomplete), leaving the handler the last second for its answer. With a hook that runs past it, a resolver the hook holds back misses the call even when it answers quickly: the answer goes out at 2 seconds in the handler's theme, and the next call reads the theme from the cache. A call whose hook was late logs the hook's warning alone, not the theme lookup's.
    • Under @Defer({ mode: 'auto' }), with waitForReady on or off, an answer still waiting for its theme, such as from a slow themeFor resolver, no longer cancels the acknowledgement: the interaction is acknowledged on time, as privately as that answer, and the answer then edits it in. A test whose theme resolver outlasts the timer sees deferReply then editReply (deferUpdate then editReply for a component) where it saw reply or update.
    • A private answer sent as an edit of a private deferral, such as send() with MessageFlags.Ephemeral after @Defer({ ephemeral: true }) or a raw deferReply({ flags: MessageFlags.Ephemeral }), no longer logs "Dropped flags Ephemeral, which an edit cannot take", as a followUp() already didn't: the deferral is already private.
    • A hook that throws counts as settled.
    • A stop (app.stop(), a signal's shutdown, or MeoCordTestingModule.close()) decides every call still waiting where it stops waiting for the calls under way, before the onShutdown hooks: by the end of the event loop iteration's timers and I/O, before its immediates. A call whose hooks have settled by then, or whose bound is due, runs first; any other never starts, nor does one held for a hook the stop keeps from running, which is dropped as soon as the hooks' pass ends. A dropped call runs no guard, handler, filter or fallback, and nothing more is sent to Discord for it: an acknowledgement @Defer made stays, @Defer({ mode: 'auto' })'s timer is cancelled without acknowledging, and an answer an observer began in onStart goes out once, in the handler's theme.
    • Observers get onSettled for a dropped call with the outcome 'error', handled: false and an error saying The bot stopped before this call started. The onShutdown hooks wait for that, and for an answer an observer made in onStart, only as long as the calls have, shutdownTimeout less the hooks' reserve, so the hooks always get their reserve and the stop resolves after them. A dropped call whose answer to Discord, or in a testing module an observer's onStart, is still running then tells its observers when that settles, which can be after the stop. A dropped call still finishing then is warned about: Calls dropped at the stop still had an answer to Discord or an observer under way after 7500 ms; running the onShutdown hooks in the 2500 ms left. (with the default shutdownTimeout). A testing module's dispatch() and invoke() resolve with ran: false and that error; emit() doesn't count the handler.
    • The bot names dropped calls in a warning of their own: Calls dropped before they started, as the stop came while they waited: interaction "/quote" for onReady in Cache. A start whose login fails while the gate holds calls drops them the same way, and names them as Calls dropped before they started, as the login failed while they waited: interaction "/quote" for onReady in Cache. A dropped call still finishing then is warned about as Calls dropped at the failed login still had an answer to Discord or an observer under way after …. A dropped call is not running: the drain's Calls still running warning leaves it out, and a drain that waited only on dropped calls counts as finished, so a cooldown store's operations settle before its onShutdown.
    • With it on, the slow onReady warning says that the calls using the hook wait for it, where it says calls are already being handled.
    • A MeoCordTestingModule takes it from the app: a dispatch, invoke or emit made while init({ ready: true }) runs the hooks waits for them, under useStrictMocks() for the same hooks as the bot's. Without init({ ready: true }) no hook runs and nothing waits. A mock interaction was created when it was made, or at its id's time when the test gives one, so a bound counts from there. With the option on, an invoke whose argument its @Command handler can't take is refused at once rather than after the wait, so its guards, interceptors and pipes don't run first, and an outcome a filter handles reads ran: false; with it off, or once the hooks have settled, nothing changes.

    See Lifecycle hooks.

  • #983 3e69d04 Thanks @l7aromeo! - @MeoCord({ warnSlow }) names work slow enough to cost a member something, and is on unless set to false; a MeoCordTestingModule turns it on only when the app sets it to true, since a test's fake clock can pass these times inside a handler.

    • An @Autocomplete handler that takes 2 seconds or more of Discord's 3 is named once per run, with the time, counted from the earlier of the interaction's creation and its arrival. One whose interaction.respond() Discord refuses as expired is named with its time and "the member saw no suggestions", at warn, where it was logged as Error handling … at error; a close of its menu Discord refuses as expired is logged at warn too, where it was at debug. Other Discord errors are logged as before.
    • A slow onReady warning now names the hook, how long it has run, how many hooks wait behind it, and what to do: onReady in ReportService has run for 10.0 s, holding back 3 hooks after it; calls are already being handled. Start long work without awaiting it in onReady, and stop it in onShutdown.
    • messages.slowHandlerWarning follows warnSlow when unset, so one warnSlow: false silences every slow warning, and wins for message handlers when set.

    One behaviour changes for a handler that is already broken: an @Autocomplete handler that returns without calling interaction.respond() now has its menu closed with no choices, where the member saw it fail to load, and is named once per run in production too, whatever warnSlow says: SearchController.query returned without answering its autocomplete, so MeoCord closed the menu with no choices. With warnUnanswered on, this warning takes the place of its warning for that handler. A testing module does the same under useStrictMocks(); without them it leaves the interaction untouched, as before, still names the handler, and warns once a run that the bot closes the menu. A handler that calls interaction.respond(choices) without awaiting it counts as answering: MeoCord waits for each such answer and reports each one that fails, also when the handler then throws, unless the handler reads its outcome itself, with await, then, catch, finally or Promise.all. The promise respond() gives the handler is a Promise subclass that notes those reads, so it is not the promise the interaction's own respond returned. Since MeoCord waits for each such answer, one that never settles holds its call, and a stop waits for that call up to its shutdown time. Answer within the three seconds. See Autocomplete and Lifecycle hooks.

Patch Changes

  • #1025 303e623 Thanks @l7aromeo! - A handler under @Defer({ mode: 'auto' }) whose interaction was answered with a raw discord.js call logged the development warning "An interaction under @Defer was answered with a raw discord.js call" twice for one answer, once when the timer fired and again when the handler returned. It now logs it once, when MeoCord first finds the answer: at the timer, at the next answer made through respond(), or when the handler returns. A raw answer followed by one through respond() before the timer, which logged nothing, now logs it too.

  • #1025 2f4d2c5 Thanks @l7aromeo! - A test using fake timers, such as Vitest's vi.useFakeTimers(), now draws the loading view of a lock() that is pending when @Defer({ mode: 'auto' })'s timer fires in the handler's theme: its @UseTheme layers and the server's and user's themes from themeFor. Before, fake timers ran the timer outside the call, so the view showed the app's theme. Nothing changes in a running bot, where the timer already ran inside the call. A timer your own handler arms still runs outside the call under fake timers; wrap its callback in bindTheme() to keep the handler's theme.

  • #1006 c174735 Thanks @l7aromeo! - CheckedParams and PIPED_BRAND, exported from meocord/interface, are marked deprecated. Both are internal, and the next major version (5.0) stops exporting them; nothing replaces them. Code that imports either keeps compiling, with the name struck through in your editor.

  • #979 62c0fa2 Thanks @l7aromeo! - meocord/eslint now names the packages it needs as optional peer dependencies: eslint, typescript, prettier, typescript-eslint, @typescript-eslint/parser, eslint-plugin-import-x, eslint-plugin-prettier, eslint-config-prettier, eslint-import-resolver-typescript and globals. A project that adopts the config by hand, rather than through meocord create, found each of them only through a Cannot find package error.

    The peers constrain no version, so installing or upgrading meocord changes nothing in a project, whichever versions of these packages it has, prereleases included. To use the config, install them at least at the versions it works with:

    npm install --save-dev "eslint@>=8.57.0" "typescript@>=4.8.4 <6.1" "prettier@>=3.0.0" "typescript-eslint@>=8.0.0" "@typescript-eslint/parser@>=8.0.0" "eslint-plugin-import-x@>=4.13.2" "eslint-plugin-prettier@>=5.0.0" "eslint-config-prettier@>=7.0.0" "eslint-import-resolver-typescript@>=4.0.0" globals
    bun add -d "eslint@>=8.57.0" "typescript@>=4.8.4 <6.1" "prettier@>=3.0.0" "typescript-eslint@>=8.0.0" "@typescript-eslint/parser@>=8.0.0" "eslint-plugin-import-x@>=4.13.2" "eslint-plugin-prettier@>=5.0.0" "eslint-config-prettier@>=7.0.0" "eslint-import-resolver-typescript@>=4.0.0" globals
    pnpm add -D "eslint@>=8.57.0" "typescript@>=4.8.4 <6.1" "prettier@>=3.0.0" "typescript-eslint@>=8.0.0" "@typescript-eslint/parser@>=8.0.0" "eslint-plugin-import-x@>=4.13.2" "eslint-plugin-prettier@>=5.0.0" "eslint-config-prettier@>=7.0.0" "eslint-import-resolver-typescript@>=4.0.0" globals
    yarn add -D "eslint@>=8.57.0" "typescript@>=4.8.4 <6.1" "prettier@>=3.0.0" "typescript-eslint@>=8.0.0" "@typescript-eslint/parser@>=8.0.0" "eslint-plugin-import-x@>=4.13.2" "eslint-plugin-prettier@>=5.0.0" "eslint-config-prettier@>=7.0.0" "eslint-import-resolver-typescript@>=4.0.0" globals

    typescript stays below 6.1 until typescript-eslint supports TypeScript 7. See ESLint.

  • #1034 7526809 Thanks @l7aromeo! - An interaction Discord has been told nothing of no longer misses its 3 seconds waiting for its themes. Its wait for themeFor now ends 2 seconds after the interaction was created (1 second for an autocomplete). Once it passes, the call goes on in its handler's theme and keeps it to its end. The lookup goes on within themeForTimeoutMs, and its result is kept for later calls.

    • Before, a command without @Defer waited for the whole lookup, up to themeForTimeoutMs, so a themeForTimeoutMs of 3 seconds or more missed the window by itself.
    • A cut is not a failure: it starts no backoff. One warning names each lookup in flight, the server or user and the first call cut, and says the lookup goes on.
    • With @Defer, nothing changes while the acknowledgement goes through. If it fails after the deadline, the call goes on at once: a @Defer({ mode: 'auto' }) acknowledgement failing at its latest, 2.5 seconds after creation, leaves the first answer that late.
    • When a bot's stop or a testing module's close ends its shutdown, the lookups still in flight end with it. A call still waiting on one goes on in its handler's theme, and whatever the lookup gives later is not logged, counted or kept.
    • Messages, reactions and events have no deadline. See https://meocord.dev/docs/4.3/theming and https://meocord.dev/docs/4.3/lifecycle-hooks.
  • #1030 d82bd12 Thanks @l7aromeo! - A translator whose catalog type is written by hand in either of two shapes now translates. Each refused every key, with "Argument of type '"greet"' is not assignable to parameter of type 'never'" or "Expected 2 arguments, but got 1.":

    • Record<string, string | { one: string; other: string }>, a type for JSON files that hold plurals. Every key is taken, with optional params, count among them, since a key may be a text or a plural. t.localizations takes none of its keys, as it needs a single text.
    • An interface that extends CatalogShape and names its messages. Its named keys are taken, and a message written as literal text has its params checked, as in a literal catalog.

    A message typed string takes any params, which only expectCompleteCatalog checks. Translators that compiled before still do, and assign as they did. See Localisation.

  • #1046 033e257 Thanks @l7aromeo! - A provider whose factory settles after a stop stopped waiting for it now has its value shut down. A stop while the bot starts waits for the factory under way at most shutdownTimeout, then shuts down without it, as before. When that factory returns a value later, its own onShutdown now runs as it arrives, within shutdownTimeout, and start() rejects after that. A value with an onReady hook is the exception: that hook never ran, so by the rule for onShutdown at any stop, it gets none. Before, the value was left open: a connection or a timer it held kept a stopped bot's process running. What the value injects was shut down by the stop already, so its onShutdown may find that closed.

    The testing module follows the bot. A close() while init() makes the providers waits for the factory under way at most shutdownTimeout, then warns, naming that factory, and shuts down without it; before, it waited for as long as the factory took, so a factory that never settles left close() pending. A value the factory returns later is shut down once it arrives and close() is done with the rest, within shutdownTimeout, with or without an onReady hook, as close() shuts down any value it made.

    Once close() has begun, init() makes nothing after the factory under way: no other factory, no listed service, and no onReady hook runs. It still resolves. Before, it went on to make all of them, and close() shut them down afterwards. A test that calls close() while init() runs and then reads something init() would have made after that point finds it not made by init(), and not shut down by close(). A get(), dispatch(), invoke() or emit() that needs the value of a factory init() skipped doesn't run that factory: get() throws and a call rejects, naming the token: "close() ended init() before it made 'TOKEN'; its factory doesn't run after close().". An emit() made after that close() runs its handlers, as dispatch() and invoke() do, listing the event sources from the classes and provided values init() made, without running a factory.

    After close(), get() returns what was shut down as before, without a word. When get(), dispatch(), invoke() or emit() makes an instance with an onShutdown only then, such as a listed service an init() that close() ended did not make, it now warns once, naming it, since nothing shuts that instance down. See https://meocord.dev/docs/4.3/testing.

  • #1036 f216132 Thanks @l7aromeo! - Logger no longer throws when it is given a value whose inspection throws, such as an object whose own [util.inspect.custom] throws. That value prints as [value could not be inspected: <reason>], and the rest of the line prints as before. Such a value, thrown by your own code, could end a running bot: an observer's onStart rejecting with it or its onSettled throwing it left a rejection nothing handled, so the process exited 1, and an onShutdown hook throwing it kept a stop by signal from destroying the client and exiting cleanly.

    A bot also no longer depends on its reports to keep going in those places:

    • An observer whose failure can't be reported, as a class whose name getter throws, is reported in its place, and the other observers still run.
    • A stop by signal destroys the client and exits even when something in the stop fails: with 0 when an onShutdown hook failed, as before, and with 1 when the stop itself failed, as when reporting a hook's failure throws.
    • A cooldown store's failure is logged as failed, without the reason, when what it failed with can't be read as text, and the policy you set still decides the call.

    Nothing changes for a value that prints today.

  • #995 abf867f Thanks @l7aromeo! - The examples your editor shows on hover for these members now compile as written: TestingModule's init, close, themeCache, invoke, dispatch and emit; TestingModuleBuilder's overrideProvider, overrideGuard, overrideInterceptor, overrideFilter, overrideTheme and overrideThemeFor; HandlerRegistry.messageHelp; ExecutionContext.getHandlerParams; RedisCooldownStore.using; and the messages.handlers option. Each declares the controllers, guards and services it uses instead of naming ones it never shows, and messages.handlers' gives @MeoCord the clientOptions it requires. RedisCooldownStore.using shows node-redis and ioredis as two examples, so either can be copied alone, and TestingModule.close's shows a factory's value closed after the class that injects it. Nothing changes at runtime.

  • #977 9c317b3 Thanks @l7aromeo! - The JSDoc of createMockInteraction() and useStrictMocks() now says that a mock interaction's fetchReply(), editReply() and followUp() each resolve to a new message object, the message as it stands then, never one an earlier call gave, with or without strict mocks. discord.js does the same: fetchReply() and followUp() return a copy or a new object, never its cached Message, and editReply() returns a copy of a message it has cached. So two fetchReply() calls are not ===, and a message held from before an edit keeps its old content. Compare messages by id, and tell two edits apart by editedTimestamp. Nothing the mocks return changes. See Mocks.

  • #1012 dd4c05d Thanks @l7aromeo! - The mocks meocord/testing makes with its own mock function no longer stay in memory until a test yields to the event loop. A test that made thousands of mock interactions in one loop, awaiting only promises, kept about 290 KB for each, and could run out of heap. clearAllMocks() and resetAllMocks() now reach each of meocord's own mocks the next time it is used: called, read through fn.mock or a matcher, or set. One difference: an array a test read before the clear, as in const calls = fn.mock.calls, keeps its entries until the mock is next used, then empties in place. Reading fn.mock.calls again, or a matcher, sees the cleared state at once. With useMockFn(vi.fn), Vitest holds each of its mocks until the test yields, so a test making thousands of them yields between batches with await new Promise(resolve => setTimeout(resolve, 0)). See Mocks.

  • #987 12203df Thanks @l7aromeo! - Under useStrictMocks(), a mock interaction or message is now on one client with what it holds, as in discord.js: its user, member, channel and server, a message's author and the users it mentions, the channel of an interaction's reply, the users, members, roles and channels an interaction's options or a select menu resolve to, and a user context menu's targetUser. A user its options or a select menu resolve to is cached on the mock client it is on unless one with its id is there already, as discord.js keeps the one cached first, and options.getUser() still returns the user the test gave; a targetUser given is the one cached on the interaction's client. Each takes the client given, else the mock client that a message or a message context menu's targetMessage, a channel or a guild given to it already holds, in that order, else a new one, so createMockMessage({ channel }) is on the channel's client. A structure given that is already on another client keeps it. A real Client given as client is the mock's own client, which caches an interaction's user, server and channel and a targetUser given; what the mock holds keeps mock clients of its own, except the server and channel a message makes for itself, and a real Client a structure given holds is never taken nor written to. One client means a collector made on interaction.channel.client, as channel.createMessageComponentCollector() makes one, hears a click on the interaction's reply. Without strict mocks each keeps a client of its own, as before, and code that reads one where strict mocks would give another warns once; the next major version (5.0) shares them without the call. See Mocks.

  • #1045 d70532c Thanks @l7aromeo! - An onShutdown hook that awaits app.stop(), or a testing module's close(), no longer waits for itself. Before, the shutdown under way waited for the hook, the hook waited for the shutdown, and nothing moved until shutdownTimeout gave up on the hooks with a warning: the hooks after it then ran after stop() had resolved, against a destroyed client, and after a Ctrl+C or a SIGTERM they never ran, as the process exited 0. Now the stop the hook awaits resolves for it at once, the hooks after it run in order, and the shutdown ends with no wait and no warning. This holds whether the hook calls stop() before or after its first await, or through code it calls, and whether or not it awaits it. The stop it asks for still runs as any stop does: in a shard, it asks the manager to stop every shard. A stop() called by work the hook started counts as the hook's while the hook runs; once the hook has returned, a stop() from work it left running waits for the whole shutdown, as does a hook awaiting another app's stop(). See https://meocord.dev/docs/4.3/lifecycle-hooks.

  • #1025 cf4932c Thanks @l7aromeo! - An answer an observer's onStart sends through respond(), including an error or a component's loading view, now has the server's and user's themes from @MeoCord({ themeFor }), as the handler's answers do; it went out in the handler's theme alone. It waits for those themes to be found, so with a slow resolver it goes out later than before, still ahead of the handler's answers; under @Defer the acknowledgement does not wait for it and goes first. The resolver is asked where it was, after onStart has started; a value it returns, rather than a promise, is applied as soon as it returns instead of a few ticks later, as a theme already cached is, so nothing waits and the calls Discord gets are the same as before. A test asserting the order of what runs after the lookup may notice the earlier settling. useTheme() in onStart reads the handler's theme until they are found, as the JSDoc of DispatchObserver.onStart now says.

  • #976 d0be101 Thanks @l7aromeo! - meocord register and a process-sharding manager now register through your clientOptions.rest, as the bot's own requests always have, so a REST proxy, another api or a timeout set there applies to registration too. A bot that sets no rest option registers exactly as before.

  • #1062 7145a7f Thanks @l7aromeo! - Two component calls holding one message with @Defer's lock no longer leave it locked wrongly when one finishes as the other locks it. Until now, depending on which edit reached Discord last, the call still running could have its control enabled again with no loading view, letting the user click it twice, or the call that had finished could keep its control disabled until the other one ended. Edits to a locked message now go out one after another, each drawn as the lock stands when it is sent, so the message always shows the calls still holding it. While several calls hold a message, it shows the loading view of the call that locked it last, also once another call releases it.

  • #1051 04f3c48 Thanks @l7aromeo! - A production build made on a fresh install starts again. @rspack/core 2.3.2 minifies a class that names itself in a static field, such as static instance = new Registry(), into code that stops at startup with ReferenceError: Cannot access '…' before initialization. discord.js has such classes, so every self-contained build (bundleDependencies) stopped there, and so did an ordinary build of an app with such a class of its own. An app installed while @rspack/core 2.3.2 was current may hold it in its lockfile beside @rsbuild/core 2.3.0 to 2.3.2, so MeoCord now asks for @rsbuild/core 2.2, or 2.3.3 and later, which needs @rspack/core 2.3.3 or later, where the minifier keeps such a class working. Upgrading and installing is enough: the package manager moves both packages off the broken releases by itself.

  • #1079 b29df91 Thanks @l7aromeo! - A MeoCord decorator run as a standard (TC39) decorator now throws at once, naming the decorator, what it was applied to and what to change: set "experimentalDecorators": true and "emitDecoratorMetadata": true in tsconfig.json. A runtime that strips types without checking them, such as Bun, applies decorators that way when the tsconfig.json it reads doesn't set experimentalDecorators. Such a decorator used to warn that it was on a method named [object Object] and apply nothing, so the bot failed later, far from the cause; on a method, it threw a TypeError from inside MeoCord. A new app from meocord create sets both options already.

  • #975 7cc2b86 Thanks @l7aromeo! - An observer's DispatchResult.startedAt follows the system clock, as its documentation says. It was read from the monotonic clock offset by the process's start, which drifts from the system clock by about half a second a day, and by more after the host sleeps, so a bot that had run for a week reported calls several seconds early. durationMs is still measured with performance.now(). Nothing to change in your code.

  • #1043 a31543f Thanks @l7aromeo! - A stopped app no longer asks its theme resolver, and a stop no longer leaves a slow onReady warning behind.

    • Once a bot's stop or a testing module's close() has ended its shutdown, a theme lookup asks no themeFor resolver: an answer outside any call and a testing module's dispatch() after close() answer in the handler's theme, or the app's outside a call, and nothing is logged for the lookup. The onShutdown hooks have closed what a resolver uses by then, and in a test its timeout warning landed in a later test. A start that fails and is retried looks themes up as before.
    • A stop that gives up on an onReady still running ends that hook's 10-second slow warning. It used to fire after the stop had resolved, and its timer kept a process with nothing else left alive. A stop that waits the hook out still warns.

    See https://meocord.dev/docs/4.3/lifecycle-hooks.

  • #1040 a692cda Thanks @l7aromeo! - A start that stop() ends now rejects only once the stop is done with the onShutdown hooks of what the start made, and stop() resolves after it, on every runtime. Done means the hooks have finished, or shutdownTimeout has ended the wait for them. Before, the order came from promise timing: on Node it was usually this one, but on Bun start() rejected before the values it made were closed, and on Node too when an onShutdown hook awaited anything. Code that awaits start() and acts on its rejection now finds what the start made shut down. One start is the exception: one still awaiting a provider's factory when the stop's shutdownTimeout wait for it ends. The stop resolves without it, and that start rejects once the factory settles. A stop() that an onShutdown hook calls while a failed start shuts down what it made joins that shutdown, which closes everything in order before the start rejects; the promise the hook gets resolves at once, as for any hook that stops its own app. See https://meocord.dev/docs/4.3/lifecycle-hooks.

  • #983 691c718 Thanks @l7aromeo! - Under useStrictMocks(), MeoCordTestingModule's init({ ready: true }) and close() run the lifecycle hooks of a class that only a guard, an interceptor, a pipe, a filter or the presenter injects in the bot's order: its onReady after the controllers' and observers', and its onShutdown before theirs. Without strict mocks, the order is unchanged. The one change is a warning, once per run, naming the first class whose hooks would run in another order; it is logged only when such a class has the hook that is about to run. MeoCord 5.0 uses the bot's order without the call. See Mocks.

  • #1024 f462750 Thanks @l7aromeo! - t(key, params), t.default, t.locale(l), t.for(…) and t.forGuild(…) take params for a message typed string, as in a translator typed Translator<any> or typed by hand from a JSON file's shape, and a plural whose forms are typed string takes params besides its count. Such a call failed to compile, though it fills its params at run time. A translator now also assigns to one typed with a catalog of plurals written by hand, such as Record<string, { one: string; other: string }>, whose forms typed string take any params beside count. Params stay optional for a message typed string, and a plural still requires its count. Translator<never>, as createTranslator(… as never) gives, takes any params on any key, where the published types refused the call. So does Translator<Record<string, never>>. Neither is a catalog type anyone writes, and every assignment of either, and every reader of their key types, compiles as before. Translator<Record<string, never>>, a translator of an empty catalog and one of a union of catalogs that share no key also assign to a translator typed with any catalog, since they take any params; none of the three has a message a call could read. Calls that compiled before still do. MessageParams of a message typed string is any params, so a type reading keyof MessageParams<string> sees string. See Localisation.

  • #1051 ba6da50 Thanks @l7aromeo! - A new app from meocord create starts on the latest stable releases of its dependencies and tools that are at least a day old: discord.js 14.28.1, dotenv 18.0.10, @types/node 26.6.6, eslint 10.15.0, typescript-eslint and @typescript-eslint/parser 8.73.0, prettier 3.10.1, eslint-plugin-import-x 4.18.1 and globals 17.14.0. TypeScript stays at 6.0.3, as typescript-eslint supports no later version, and vitest at 5.1.0, so an app runs its tests on Bun without Node.js. An existing app is unchanged.

  • #1056 8176265 Thanks @l7aromeo! - A new app from meocord create runs its tests on a machine with Bun and no Node.js again. vitest 5.1.1 starts each test worker in a way Bun can't yet run (oven-sh/bun#33593), so test and test:coverage stopped before any test with TypeError: child.channel?.unref is not a function. The template now asks for vitest and @vitest/coverage-istanbul at exactly 5.1.0, unlike its other dependencies, which take the latest release. That holds until a vitest release carries vitest-dev/vitest#12039 or a Bun release ships channel.unref. An existing app with vitest 5.1.1 can set both packages to 5.1.0 in its package.json, or run its tests with Node.js installed.

  • #1058 e7cebda Thanks @l7aromeo! - A testing module's close() called from a call it is running, such as a command handler that awaits module.close(), no longer waits for that call. Before, in a module whose cooldown store has an onShutdown, the close drained the calls under way, the handler awaiting it among them, so it waited out shutdownTimeout less the hooks' reserve, warned Calls still running after … ms, and only then ran the onShutdown hooks and resolved. Now it leaves that call out, as the bot's app.stop() does for a handler that awaits it: the close goes on at once and the other calls still drain. See https://meocord.dev/docs/4.3/testing.

  • #1074 1cdbd95 Thanks @l7aromeo! - The declarations of TestingModule and TestingModuleBuilder, from meocord/testing, no longer name the internal types MeoCord makes a module from, such as ProviderMap and LifecycleUnit. Each constructor parameter is declared unknown, so your editor's hover shows none of them. Nothing stops compiling: code that calls new on either class, extends it or passes it as a constructor type compiles as before. The constructors stay undocumented: make a module with MeoCordTestingModule.create(…).compile() or MeoCordTestingModule.fromApp(…).compile(). See https://meocord.dev/docs/4.3/testing.

  • #1074 ff1485b Thanks @l7aromeo! - A testing module closed during init({ ready: true }) now runs the onReady and onShutdown hooks as the bot does when it stops before or during its ready hooks. Once init({ ready: true }) is asked, close() lets no further onReady start, and runs no onShutdown for a unit whose onReady hasn't settled when close() lists what it shuts down, such as one still running or one that never started because close() came first, nor for anything that depends on it. A unit whose onReady failed has settled and is shut down. Before, the module went on with the onReady hooks after close(). Once close() stopped waiting for them, at its shutdownTimeout less the hooks' reserve, it ran onShutdown for every unit it had made, one still in its onReady included, and the units the later hooks made had nothing to shut them down. A close() before the hooks started, while init() made the providers, waited for every factory, then did the same. A test that calls close() before the onReady hooks finish now sees the bot's shutdown: if it expected the later hooks to run, or a unit whose onReady hasn't settled to be shut down, await init({ ready: true }) before close(). Without init({ ready: true }), nothing changes: close() still shuts down every unit the module made. See https://meocord.dev/docs/4.3/testing.

  • #976 379365f Thanks @l7aromeo! - meocord/testing no longer loads cli-table3. A test file that imports the testing toolkit loads only what testing needs, so a test environment that bundles or stubs its dependencies, such as an in-browser sandbox, works without cli-table3, which only the startup table of registered commands uses.

  • #1024 1ba4a77 Thanks @l7aromeo! - A Translator injected without its catalog type, as constructor(private readonly t: Translator), still translates no key, and its compile error now says what to write: "This Translator has no catalog type: type it as Translator, with your default catalog, to translate with it". It said "Expected 2 arguments, but got 1." for a key alone in t.default, t.locale(l), t.for(…) and t.forGuild(…), and "… is not assignable to parameter of type 'never'" for t.localizations and for a key given params. Every method that takes a key gives that sentence: t.default, t.locale(l), t.for(…), t.forGuild(…) and t.localizations. Such a translator passes on as before, as to translateError, and typed translators assign to and from it as before. MessageKey and LocalizationKey of CatalogShape, a bare Translator's catalog type, or of an index signature with no keys that takes any catalog, are that sentence instead of never. See Localisation.

  • #1019 527f4e8 Thanks @l7aromeo! - useMockFn() now always refuses once a mock has been made, whether or not that mock is still in use. Before, a mock made before it and then dropped made it throw until the garbage collector took the mock, and pass after, so the same setup could pass on one run and fail on the next. If a setup file throws useMockFn() goes before any mock is made, move the call ahead of anything that makes a mock, such as a helper that builds a mock interaction when it is imported: call useMockFn() first, in the test runner's setup file. See Mocks.