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
906780bThanks @l7aromeo! -@MeoCord({ answerDenied: true })answers a guard'sfalseon an interaction as if the guard had thrownGuardDeniedError. A command, context menu, component or modal a guard denies is told privately "You can't use this." in the user's language, frommeocord.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 catchingGuardDeniedErrorsees it and can answer otherwise, observers get the outcome'denied'withdeniedByand the error, and a call with@Deferis answered into its deferral. Autocomplete still closes its menu, an event handler still skips the event, and a message command stays silent, since afalsethere is often a filter. A guard that throws its ownGuardDeniedErrorkeeps its words. In a testing module built from an app that sets the option,invokerejects with thatGuardDeniedErrorfor a guard'sfalseand sends nothing, as it does for a thrown denial, whiledispatchanswers it as the bot does. Nothing changes until an app sets the option. See https://meocord.dev/docs/4.3/guards.#980
0510d95Thanks @l7aromeo! -bindThemenow 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@UseThemelayers of the handler that bound it, thenthemeFor's layers for that call's server and user, in the order a handler's call has them. A collector'scollectcallback answers each member who clicks in their own theme, and aclient.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
themeForis still looking up replaces the handler's once found, so the wrapped function stays synchronous:respond()waits for it, anduseTheme()reads the handler's theme until then. A call whose arguments name neither, such as a collector'send, runs in the whole theme of the call that bound it, as before. Once a bot's stop or a testing module'sclose()has ended its shutdown, a wrapped function asks nothemeForresolver: 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 withoutthemeForsees no change. See Theming.#979
1789503Thanks @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.sourceMappedStacksmapped onlyerror.stack, so a crash, the trace most worth reading, showed positions indist/main.js.When the bundle maps its stacks (
sourceMappedStacksis notfalseand 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 aDiscordAPIError'scode, and itscause; - an
uncaughtExceptionand anunhandledRejectionlistener onprocess, 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-rejectionsmode decides. Without the flag a rejection ends the process; under=throwit is raised as an uncaught error, which your ownuncaughtExceptionlistener 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: messagefollowed byatlines namingsrc/files and any own properties in braces, where Bun printed its own layout: the source line excerpt above the error and, for a crash, theBun v…line below it are gone. An error whosestackis no string of its own, such as aDOMExceptionor one with astackgetter, 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. SetsourceMappedStacks: falseto 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, asprocess.onceadds 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 withprocess.prependOnceListenerdoes: 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.- an inspection hook on
#993
264b19dThanks @l7aromeo! - MeoCord's CommonJS build bundles its ES-module-only dependencies,inversify(with its@inversifyjs/*packages) andchalk, sorequire('meocord/...')loads nothing that ships only as an ES module. jest, which runs tests as CommonJS, now loadsmeocord/testingwithout Node's VM modules: dropNODE_OPTIONS=--experimental-vm-modulesfrom a jest setup that added it for MeoCord. With the flag left in, jest runs as before. The ES module build imports both packages fromnode_modulesas before. A process that loads both builds runs two copies ofinversifyand ofchalk: the one bundled into the CommonJS build and the one innode_modulesthat the ES module build imports. The two builds'Loggerwrites the same output under each colour setting. With them, and with the rest of 4.3,dist/cjsis 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
77d534bThanks @l7aromeo! - NewcommandMention(path, target)inmeocord/commongives 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)}.`)targetis 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, withcommands.register: false, and for commandsmeocord registersent. A path the app doesn't declare is aRangeError; a command that isn't registered where the reader is, or a mention before the bot is ready, is anErrorthat 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, theErrornames 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
4d52db9Thanks @l7aromeo! -meocord/commonexportsformatDuration(ms, target?, options?), which writes a length of time for people:formatDuration(3_900_000)is1h 5m, and{ style: 'long' }gives1 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 aLocale, throughoptions.t.units,largest,smallestandroundchoose what it shows, and{ style: 'param' }writes1h30m, which a{x:duration}param reads back, for a value up toNumber.MAX_SAFE_INTEGERmilliseconds. See Formatting.Its unit words are new MeoCord texts in a
meocord.durationgroup, 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.defineCatalogrefuses at compile time a translation of one of them without itsotherform, with a form that isn't a text, or with a key that is no plural category.expectCompleteCatalognow reports a translation of MeoCord's own plural texts that lacks a form its language needs, such asfewin 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.cooldownMessagewrites its wait withformatDuration, and its output is unchanged for every finite wait. A refusal whose wait is no finite number, as a customCooldownStoremay answer, now tells the caller "Slow down: try again later.", a new MeoCord textmeocord.cooldown.laterthat an app's catalog translates, where they were shown a timestamp Discord couldn't display;cooldownMessagegives the same text where it wroteNaNd NaNh.#978
43396b2Thanks @l7aromeo! -meocord/commonexportspermissionNames(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' }givesBan Members and Manage Messages, joined as a list in the labels' language. The labels are Discord's own wording, commas included, such asKick, 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 aLocale, throughoptions.t. A bit with two flag names, such as1 << 30, gives one label; a bit with no label gives its flag name, and a bit discord.js doesn't name givesUnknown permission (1 << n). See Formatting.The labels are new MeoCord texts in a
meocord.permissionsgroup, by flag name, which an app's catalog translates like the others. See Localisation.#978
768018fThanks @l7aromeo! -meocord/commonexports discord.js's formatters under their own names, so a bot imports its formatting from one place:userMention,channelMention,timewithTimestampStyles,bold,codeBlock,escapeMarkdownand the rest, 44 functions and constants and 4 types. They are your own discord.js's functions, not copies:userMentionfrommeocord/commonisuserMentionfromdiscord.js, so code that imports them from discord.js keeps working, and their documentation is discord.js's.versionand the deprecatedunderscorearen't exported. A new app's sample button replies withuserMention(ownerId). See Formatting.- Breaking
#978
7683c01Thanks @l7aromeo! -meocord/commonexportssplitMessage,truncateandDiscordLimitsfor fitting text to what Discord accepts.splitMessage(text)splits text into messages of at most 2000 characters, or themaxyou 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 tomaxcharacters with an ellipsis, closing code it cuts open.DiscordLimitsnames Discord's length limits, such asDiscordLimits.contentandDiscordLimits.embedDescription. See Formatting.The help reply, MeoCord's own and a
presenter.messageHelpstring, splits withsplitMessage. 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
7a633ffThanks @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.
- 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
#977
d8e80b3Thanks @l7aromeo! - A testing module can answer an event handler's refusals as the bot does. WitheventFallback: trueinMeoCordTestingModule.create()orfromApp(),emitruns the bot's own event fallback: a guard'sGuardDeniedErrorskips the event and the handler isn't counted as run, and aUserErroris answered as a reply to the newest message among the event's arguments, with the app's presenter andreplyEmoji. Neither rejectsemit; any other error still does. The option applies toemitalone, not toinvokeof an@Onhandler. With the option,emitgives 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
emitrejects 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). SeteventFallback: falseto keep the rejection without the warning. See Invoke and dispatch.#984
85314bcThanks @l7aromeo! -meocord generate controllerandmeocord generate observernow add the class they write tosrc/app.ts: its import after your last import, and its entry in@MeoCord({ controllers })or@MeoCord({ observers }), addingobserverswhen 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 owntypescriptand 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 symlinkedsrc/app.tsedits 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, sostart --devrebuilds 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 andgeneratesays it went unchecked and why. Pass--skip-appto keep the old behaviour, which leavessrc/app.tsalone and prints what to add.When the class can't be placed safely,
generatewrites its files, warns why, prints the two lines to add and changes nothing insrc/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 insrc/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'stypescriptcan'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 runsgeneratemakes, 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 holdsgeneratefor 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
0630ee4Thanks @l7aromeo! -@MeoCord({ globalStagesOnEvents: false })keeps the app's global guards and interceptors that declare notypesfrom running before@Onand@Oncehandlers. 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 declarestypeskeeps exactly what it declares,'event'included; the guards and interceptors a controller or a handler names, and global exception filters, are unaffected. The default staystruein 4.3 and becomesfalsein 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 setglobalStagesOnEventstotrueto keep today's behaviour or tofalseto take 5.0's now. See https://meocord.dev/docs/4.3/guards.#1004
8c63674Thanks @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, andmeocord.help.paramJoiner, a middle dot with a space on each side, its params. A catalog that translatesmeocord.helpcan 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
5dd3eafThanks @l7aromeo! -inspectHandler()reports a handler's@Deferasdefer: the options it runs with, with their defaults filled in (ephemeral: false,suppressNotifications: false,disable: 'all',mode: 'eager', andafter: 1500formode: 'auto'), orundefinedwithout one. A@Deferinherited 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', })toEqualon a whole inspection doesn't comparedefer, so existing assertions hold. See Invoke and dispatch.#1004
7046f51Thanks @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, ast()'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, ast()leaves it. A translator typedTranslator<any>, or by hand with messages typedstring(a JSON file's shape), takes any params for such a message. A param the default message takes andparamsleave out, or give asundefined, 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,LocalizationParamandLocalizationParamsare exported frommeocord/common, to type a helper that takes such a key or builds its params before passing them on. On aTranslatorwithout its catalog type,t.localizations(key, params)andParamLocalizationKeygive the same "This Translator has no catalog type" error as its other methods. See Localisation.#1014
c86a086Thanks @l7aromeo! - UnderuseStrictMocks(), a mock answers a property its discord.js class does not have as discord.js does: it readsundefinedand is notinthe mock, somessage.isRepliable?.()givesundefinedandif (value.guild)is false for a class without aguild, as on a bot.inis 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. WithoutuseStrictMocks()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) answersundefinedwithout the call. See Mocks.#977
de3e228Thanks @l7aromeo! - UnderuseStrictMocks(),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, soclient.on.mock.callsandtoHaveBeenCalledWithwork as before and a test can still set its own behaviour.client.on(...)returns the client instead ofundefined,listeners()andlistenerCount()answer, andemit()reaches every listener attached. discord.js's ownInteractionCollectormade on the client works, filtered by a message, in a server or a direct message, by a response, ascreateMessageComponentCollector()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 ininteractionMetadata, as Discord's do, and a command'smessageand a message's rawchannel_idandguild_idreadundefined, 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 getsundefined: a command'sinteraction.message.idthrows aTypeError, andmessage.guild_idisundefined. An interaction'sauthorizingIntegrationOwnersis discord.js'sAuthorizingIntegrationOwnersfor 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'sinteractionMetadataholds the same owners. WiththemeFor, 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'sinteractionCreatelisteners, 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 callsclient.emit('interactionCreate', interaction)delivers it twice. What a listener throws or rejects with rejectsdispatch()once MeoCord has answered.
A real discord.js
Clientkeeps 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 returnsundefined, 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 assertsLogger.warnwas never called fails on that warning: assert on the warnings it expects instead, or calluseStrictMocks(). Reading a command'smessageor a message'schannel_idorguild_idwarns once too, where strict mocks readundefined. The next major version (5.0) has the working emitter without the call (#441). See Components.#987
e2ebbcaThanks @l7aromeo! - UnderuseStrictMocks(), a mock message's, a mockInteractionResponse's and a mock text-based channel'screateMessageComponentCollector()andawaitMessageComponent()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, fromwithResponse'sresource.message, from a deferral's response once the reply is edited, fromupdate()'s ordeferUpdate()'s response, from a mock message, such as a message handler's reply or a component'sinteraction.message, or frominteraction.channel, in a server or a DM, collects a click thatmodule.dispatch()delivers or that a test emits on the client.max,filter,componentType,time,idleandstop()work as in discord.js, andawaitMessageComponent()resolves with the click or rejects on itstime. Both stay mock functions that record each call, sotoHaveBeenCalledWithworks 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, sodispatch()delivers it where the collector listens; giveclientfor 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
timeandidlewithnode:timers, so a test's fake timers don't move them: end a collector in a test withmaxorcollector.stop(). To answerawaitMessageComponent(), 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
undefinednow gets a collector, or a promise of the click. A mock on a real discord.jsClientis unchanged, with strict mocks or without: both stay inert with no warning. Without strict mocks both still returnundefined, 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.- A collector from
#977
88c03a4Thanks @l7aromeo! - UnderuseStrictMocks(), 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()anddeferUpdate()resolve to a mockInteractionResponsebound to the interaction. Itsedit(),delete()andfetch()reach the interaction'seditReply(),deleteReply()andfetchReply(), andcreateMessageComponentCollector()andawaitMessageComponent()are mock functions, as on a mock message. A test there that assertsresolves.toBeUndefined()on one of them now fails: assert on the response instead, or drop the assertion.- With
withResponse: true, each resolves to anInteractionCallbackResponseholding what Discord answers.reply()'s anddeferReply()'sresourceis of typeChannelMessageWithSourceand holds the message asfetchReply()reads it at that moment, fordeferReply()the loading message, whose id the reply keeps.update()'s is of typeUpdateMessageand holds the updated message.deferUpdate()has noresource: it isnull. The callback'sinteractionnames the message, the component's for an update, withresponseMessageLoadingtrueonly fordeferReply(). - A deferred reply reads as Discord shows it until it is edited:
fetchReply()afterdeferReply()gives a message flaggedLoading, andEphemeraltoo for a private deferral, where it had neither flag. An edit clearsLoading. respond(interaction).send()resolves to the message the reply or the update sent, where it resolved toundefined.- With
withResponse, and so throughrespond(), 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 andrespond()'s answers, don't log it. A test that assertsLogger.warnwas never called fails on that warning the first time its own code calls one of them: assert on the warnings it expects instead, or calluseStrictMocks(). The next major version (5.0) resolves them as strict mocks do, without the call (#441). See Mocks.#1005
94050f2Thanks @l7aromeo! - UnderuseStrictMocks(), a mock text-based channel'screateMessageCollector()andawaitMessages(), and a mock message'screateReactionCollector()andawaitReactions(), run discord.js's own collector on the mock client, andmodule.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'smessageCreatelisteners, anddispatch(reaction, { user })itsmessageReactionAddormessageReactionRemovelisteners, 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 firstawait, 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 rejectsdispatch().- 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.reactionsand counts the user into itsusers,countandcountDetails. Where its message doesn't cache it, the add starts it from none, itsusersandmetoo, unless its state is the test's: acount,countDetails,meor users the test gave before its first dispatch, or acountorcountDetailsset after one. The add then counts on from what is there,countandcountDetailsapart, as discord.js keeps them. So the first add of a reaction given none of these counts 1, one givenme: truecounts 2 and keepsme, and a test that setscountto 5 between two dispatches gets 6 from the second. A remove takes the user out ofusers, and out of the count unless the user is the bot andmeis set, as discord.js leaves that to the bot's own REST call; once neither users nor count are left the reaction leavesmessage.reactions. A remove of a reaction its message doesn't cache is delivered and changes nothing: a real client withoutPartials.Reactionemits nothing for it, anddispatchdelivers it all the same, so a test doesn't show that a bot needs the partial. A partial reaction, itscountnull, is delivered as it is, as discord.js leaves it. A reaction'scountDetailsreads{ burst: 0, normal: count }unless the test sets it. A dispatched reaction is a normal one, never a burst. - A mock
MessageReactionis on its message's client, by the rule a mock interaction follows: theclientgiven, else itsmessage's, a realClientincluded, else a new one, on which its message is made when none is given. A realClientgiven to the reaction is its own only, and a reaction on a realClientis routed with nothing applied to it or delivered. A strict test that reads a reaction'sclientgets that client, where it read a placeholder, anddispatchdelivers the reaction to that client's listeners. max,filter,time,idle,disposeandstop()work as in discord.js, a reaction collector emitscreate,removeanddispose, andawaitMessages()andawaitReactions()resolve with what they collected, or reject on theirtimewitherrors: ['time']. All four stay mock functions that record each call, sotoHaveBeenCalledWithworks 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 withnode:timers, so a test's fake timers don't move it: a handler that awaitsawaitMessages({ time: 60_000 })with nothing dispatched waits that long, past a test's timeout. Dispatch the answer, give the collectormax, or callcollector.stop(). A test that both dispatches a message or a reaction and emits the same event on the mock client delivers it twice, andemitapplies nothing to a reaction;emit()on the testing module is unchanged and reaches only@Onhandlers. A mock on a real discord.jsClientis 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 returnundefined, 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
2cad9a0Thanks @l7aromeo! - A project can have its mocks' values type-checked. MergetypedValues: trueintoMockTypeOptionsfrommeocord/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,mockResolvedValueandmockImplementationthen take only what the mocked function returns, resolves to or is, andmock.calls,mock.lastCall,mock.resultsandmock.settledResultsread as its own arguments and results.mockResolvedValue(undefined)stays allowed, since a mock's answers resolve toundefinedby default. An overloaded method, such asguild.members.fetch, takes what any of its overloads gives. A partial fake such asmockResolvedValue({ 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.tsand a.d.cts. MeoCord 5.0 types the values by default (meocord#561). See Mocks.#975
c090957Thanks @l7aromeo! -OwnerGuard, frommeocord/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 ismeocord.guard.notOwner, which an app's catalogs translate. Since the guard throwsGuardDeniedError, a filter catching that error can answer otherwise, and observers name it indeniedBy.The bot refuses to start with
OwnerGuardwhere 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@UseGuardon 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@Cooldownpasses over the handlers it never counts. Apps made withmeocord createno longer get their ownsrc/guards/owner.guard.ts: the sample button usesOwnerGuard. An app that has that file can keep it, or delete it and importOwnerGuardfrommeocord/common. See https://meocord.dev/docs/4.3/guards.#979
eeed81eThanks @l7aromeo! - A self-contained build (bundleDependencies) packs every installed copy of a native addon that bundled code imports, and each importer loads its own. Withnatpkg@1at the top ofnode_modulesandnatpkg@2nested underwrap, which needs it,wrapnow runs againstnatpkg@2fromdistalone, where the build packed onlynatpkg@1for 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 ofnode_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 underdist/node_modules/.meocord/<name>-<version>-<hash>/, the hash taken from the chain of dependencies that reaches it from your project, such aswrap>natpkg, so the same installed tree, as a lockfile fixes it, builds the samediston 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, theexportsconditions of animportor arequireand 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 anexportswith no entry forrequire, 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
b7fa179Thanks @l7aromeo! -meocord register --prunefinds 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 allremoves those too, asking once in a terminal or with--yesoutside one.--dry-runregisters 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.envfile, such asMEOCORD_REGISTER_GUILD, no longer steersmeocord registerormeocord start: each run registers as its own flags say. See CLI.#984
0d62e30Thanks @l7aromeo! - A new app frommeocord createsends without pings: itsclientOptionssetsallowedMentions: { parse: [] }, the default discord.js gives every message the client sends,respond()'s replies and your ownmessage.replyandchannel.sendalike. A reply that echoes a member's text no longer pings whoever that text mentions,@everyoneand roles included; one that should ping passes its ownallowedMentions, such as{ users: [id] }, and amessage.replythat should ping its author addsrepliedUser: true.An existing app whose
clientOptions.allowedMentionsis 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
f1cfefdThanks @l7aromeo! - Aroute()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 valuebuildencoded with/or%comes back as it was given, and a typed param comes back as its value.matchreturnsundefinedfor 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, frommeocord/common, is whatmatchreturns: the params a customId route gives its handler. It can type a handler's params too, such as{ id }: RouteMatch<typeof closeTicket.pattern>.Routegains the requiredmatchmethod. A bot that only callsroute()needs nothing. Code that writes aRouteobject by hand no longer compiles until it addsmatch(customId: string), returning the params orundefined; make the object withroute()instead. See the upgrade guide. #993
dabaa35Thanks @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,HandlerRegistryandShardContextare one class object for both builds of a MeoCord version, soinstanceofon these classes agrees between the builds, as it already does for MeoCord's error classes. MeoCord's other exported classes, such asLogger,RedisCooldownStoreandMeoCordTestingModule, stay one per build: MeoCord decides nothing by their identity, and only an app's owninstanceofacross 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 (forTranslator,ThemeCache,ExecutionContextandCooldownStore) or refused at startup with "has no decorator" (forHandlerRegistryandShardContext). Two installed versions of MeoCord still keep their classes apart. See https://meocord.dev/docs/4.3/testing.#984
fed44efThanks @l7aromeo! -meocord start --prodandmeocord register, run without--build, now warn when the build indistis 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 whendistholds a development build, asmeocord start --devandmeocord build --devleave 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.jsonand each file it extends, and withbundleDependenciesyour 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 adistwith no recorded source beside it, as on a server that has onlydist, 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
6503d89Thanks @l7aromeo! - A testing module'sdispatch(),invoke()oremit()made whileinit()is still running, which aclose()then ends, no longer starts. Before, such a call went on onceinit()resolved: it ran its handler against the closed module, on classesclose()had already shut down, logged nothing and resolved as a call that ran, withran: true, orran: 1foremit(). 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 withran: false, that error and no handlers, andinvoke()withran: falseand that error.EmitResultgains an optionalerror, so a dropped event resolves withran: 0and that error.erroris set only for a dropped event, so every otheremit()still resolves with{ ran: n }. A call made afterclose()is unchanged: it warns and runs. See https://meocord.dev/docs/4.3/testing.#1004
726ddeeThanks @l7aromeo! - EachValidationIssuefrom a@Validateschema keeps the issue the schema reported, asraw, typedStandardSchemaV1Issue. An exception filter can read the library's own fields from it, such as zod'scodeandminimum, to word a refusal in the user's language instead of parsing the library's English message.rawis non-enumerable, sotoEqual({ message, path })and a serialised issue are unchanged, and an issue you build yourself has none. See Validation.#983
1c9036fThanks @l7aromeo! -@MeoCord({ waitForReady: true })holds each call until theonReadyhooks 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
themeForclass, 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
themeForclass's own hooks have settled, whether in a call, in a functionbindThemewraps, 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'sephemeralsays. 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
@Deferacknowledges 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
@Deferwaits until 2 seconds after it was created and an autocomplete 1 second, then runs, with one warning per hook naming it, whateverwarnSlowsays: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
themeForshare 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' }), withwaitForReadyon or off, an answer still waiting for its theme, such as from a slowthemeForresolver, 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 seesdeferReplytheneditReply(deferUpdatetheneditReplyfor a component) where it sawreplyorupdate. - A private answer sent as an edit of a private deferral, such as
send()withMessageFlags.Ephemeralafter@Defer({ ephemeral: true })or a rawdeferReply({ flags: MessageFlags.Ephemeral }), no longer logs "Dropped flags Ephemeral, which an edit cannot take", as afollowUp()already didn't: the deferral is already private. - A hook that throws counts as settled.
- A stop (
app.stop(), a signal's shutdown, orMeoCordTestingModule.close()) decides every call still waiting where it stops waiting for the calls under way, before theonShutdownhooks: 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@Defermade stays,@Defer({ mode: 'auto' })'s timer is cancelled without acknowledging, and an answer an observer began inonStartgoes out once, in the handler's theme. - Observers get
onSettledfor a dropped call with the outcome'error',handled: falseand an error sayingThe bot stopped before this call started.TheonShutdownhooks wait for that, and for an answer an observer made inonStart, only as long as the calls have,shutdownTimeoutless 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'sonStart, 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 defaultshutdownTimeout). A testing module'sdispatch()andinvoke()resolve withran: falseand 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 asCalls 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 asCalls 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'sCalls still runningwarning leaves it out, and a drain that waited only on dropped calls counts as finished, so a cooldown store's operations settle before itsonShutdown. - With it on, the slow
onReadywarning says that the calls using the hook wait for it, where it says calls are already being handled. - A
MeoCordTestingModuletakes it from the app: adispatch,invokeoremitmade whileinit({ ready: true })runs the hooks waits for them, underuseStrictMocks()for the same hooks as the bot's. Withoutinit({ 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, aninvokewhose argument its@Commandhandler 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 readsran: false; with it off, or once the hooks have settled, nothing changes.
See Lifecycle hooks.
- 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
#983
3e69d04Thanks @l7aromeo! -@MeoCord({ warnSlow })names work slow enough to cost a member something, and is on unless set tofalse; aMeoCordTestingModuleturns it on only when the app sets it totrue, since a test's fake clock can pass these times inside a handler.- An
@Autocompletehandler 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 whoseinteraction.respond()Discord refuses as expired is named with its time and "the member saw no suggestions", at warn, where it was logged asError 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
onReadywarning 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.slowHandlerWarningfollowswarnSlowwhen unset, so onewarnSlow: falsesilences every slow warning, and wins for message handlers when set.
One behaviour changes for a handler that is already broken: an
@Autocompletehandler that returns without callinginteraction.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, whateverwarnSlowsays:SearchController.query returned without answering its autocomplete, so MeoCord closed the menu with no choices.WithwarnUnansweredon, this warning takes the place of its warning for that handler. A testing module does the same underuseStrictMocks(); 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 callsinteraction.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, withawait,then,catch,finallyorPromise.all. The promiserespond()gives the handler is aPromisesubclass that notes those reads, so it is not the promise the interaction's ownrespondreturned. 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.- An
Patch Changes
#1025
303e623Thanks @l7aromeo! - A handler under@Defer({ mode: 'auto' })whose interaction was answered with a raw discord.js call logged the development warning "An interaction under@Deferwas 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 throughrespond(), or when the handler returns. A raw answer followed by one throughrespond()before the timer, which logged nothing, now logs it too.#1025
2f4d2c5Thanks @l7aromeo! - A test using fake timers, such as Vitest'svi.useFakeTimers(), now draws the loading view of alock()that is pending when@Defer({ mode: 'auto' })'s timer fires in the handler's theme: its@UseThemelayers and the server's and user's themes fromthemeFor. 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 inbindTheme()to keep the handler's theme.#1006
c174735Thanks @l7aromeo! -CheckedParamsandPIPED_BRAND, exported frommeocord/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
62c0fa2Thanks @l7aromeo! -meocord/eslintnow 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-typescriptandglobals. A project that adopts the config by hand, rather than throughmeocord create, found each of them only through aCannot find packageerror.The peers constrain no version, so installing or upgrading
meocordchanges 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" globalsbun 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" globalspnpm 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" globalsyarn 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" globalstypescriptstays below 6.1 until typescript-eslint supports TypeScript 7. See ESLint.#1034
7526809Thanks @l7aromeo! - An interaction Discord has been told nothing of no longer misses its 3 seconds waiting for its themes. Its wait forthemeFornow 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 withinthemeForTimeoutMs, and its result is kept for later calls.- Before, a command without
@Deferwaited for the whole lookup, up tothemeForTimeoutMs, so athemeForTimeoutMsof 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.
- Before, a command without
#1030
d82bd12Thanks @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,countamong them, since a key may be a text or a plural.t.localizationstakes none of its keys, as it needs a single text.- An interface that extends
CatalogShapeand 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
stringtakes any params, which onlyexpectCompleteCatalogchecks. Translators that compiled before still do, and assign as they did. See Localisation.#1046
033e257Thanks @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 mostshutdownTimeout, then shuts down without it, as before. When that factory returns a value later, its ownonShutdownnow runs as it arrives, withinshutdownTimeout, andstart()rejects after that. A value with anonReadyhook is the exception: that hook never ran, so by the rule foronShutdownat 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 itsonShutdownmay find that closed.The testing module follows the bot. A
close()whileinit()makes the providers waits for the factory under way at mostshutdownTimeout, 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 leftclose()pending. A value the factory returns later is shut down once it arrives andclose()is done with the rest, withinshutdownTimeout, with or without anonReadyhook, asclose()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 noonReadyhook runs. It still resolves. Before, it went on to make all of them, andclose()shut them down afterwards. A test that callsclose()whileinit()runs and then reads somethinginit()would have made after that point finds it not made byinit(), and not shut down byclose(). Aget(),dispatch(),invoke()oremit()that needs the value of a factoryinit()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().". Anemit()made after thatclose()runs its handlers, asdispatch()andinvoke()do, listing the event sources from the classes and provided valuesinit()made, without running a factory.After
close(),get()returns what was shut down as before, without a word. Whenget(),dispatch(),invoke()oremit()makes an instance with anonShutdownonly then, such as a listed service aninit()thatclose()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
f216132Thanks @l7aromeo! -Loggerno 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'sonStartrejecting with it or itsonSettledthrowing it left a rejection nothing handled, so the process exited 1, and anonShutdownhook 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
namegetter 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
onShutdownhook 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.
- An observer whose failure can't be reported, as a class whose
#995
abf867fThanks @l7aromeo! - The examples your editor shows on hover for these members now compile as written:TestingModule'sinit,close,themeCache,invoke,dispatchandemit;TestingModuleBuilder'soverrideProvider,overrideGuard,overrideInterceptor,overrideFilter,overrideThemeandoverrideThemeFor;HandlerRegistry.messageHelp;ExecutionContext.getHandlerParams;RedisCooldownStore.using; and themessages.handlersoption. Each declares the controllers, guards and services it uses instead of naming ones it never shows, andmessages.handlers' gives@MeoCordtheclientOptionsit requires.RedisCooldownStore.usingshows node-redis and ioredis as two examples, so either can be copied alone, andTestingModule.close's shows a factory's value closed after the class that injects it. Nothing changes at runtime.#977
9c317b3Thanks @l7aromeo! - The JSDoc ofcreateMockInteraction()anduseStrictMocks()now says that a mock interaction'sfetchReply(),editReply()andfollowUp()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()andfollowUp()return a copy or a new object, never its cachedMessage, andeditReply()returns a copy of a message it has cached. So twofetchReply()calls are not===, and a message held from before an edit keeps its old content. Compare messages byid, and tell two edits apart byeditedTimestamp. Nothing the mocks return changes. See Mocks.#1012
dd4c05dThanks @l7aromeo! - The mocksmeocord/testingmakes 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()andresetAllMocks()now reach each of meocord's own mocks the next time it is used: called, read throughfn.mockor a matcher, or set. One difference: an array a test read before the clear, as inconst calls = fn.mock.calls, keeps its entries until the mock is next used, then empties in place. Readingfn.mock.callsagain, or a matcher, sees the cleared state at once. WithuseMockFn(vi.fn), Vitest holds each of its mocks until the test yields, so a test making thousands of them yields between batches withawait new Promise(resolve => setTimeout(resolve, 0)). See Mocks.#987
12203dfThanks @l7aromeo! - UnderuseStrictMocks(), 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'stargetUser. 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, andoptions.getUser()still returns the user the test gave; atargetUsergiven is the one cached on the interaction's client. Each takes theclientgiven, else the mock client that a message or a message context menu'stargetMessage, a channel or a guild given to it already holds, in that order, else a new one, socreateMockMessage({ channel })is on the channel's client. A structure given that is already on another client keeps it. A realClientgiven asclientis the mock's own client, which caches an interaction's user, server and channel and atargetUsergiven; what the mock holds keeps mock clients of its own, except the server and channel a message makes for itself, and a realClienta structure given holds is never taken nor written to. One client means a collector made oninteraction.channel.client, aschannel.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
d70532cThanks @l7aromeo! - AnonShutdownhook that awaitsapp.stop(), or a testing module'sclose(), no longer waits for itself. Before, the shutdown under way waited for the hook, the hook waited for the shutdown, and nothing moved untilshutdownTimeoutgave up on the hooks with a warning: the hooks after it then ran afterstop()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 callsstop()before or after its firstawait, 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. Astop()called by work the hook started counts as the hook's while the hook runs; once the hook has returned, astop()from work it left running waits for the whole shutdown, as does a hook awaiting another app'sstop(). See https://meocord.dev/docs/4.3/lifecycle-hooks.#1025
cf4932cThanks @l7aromeo! - An answer an observer'sonStartsends throughrespond(), 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@Deferthe acknowledgement does not wait for it and goes first. The resolver is asked where it was, afteronStarthas 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()inonStartreads the handler's theme until they are found, as the JSDoc ofDispatchObserver.onStartnow says.#976
d0be101Thanks @l7aromeo! -meocord registerand a process-sharding manager now register through yourclientOptions.rest, as the bot's own requests always have, so a REST proxy, anotherapior atimeoutset there applies to registration too. A bot that sets norestoption registers exactly as before.#1062
7145a7fThanks @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
04f3c48Thanks @l7aromeo! - A production build made on a fresh install starts again.@rspack/core2.3.2 minifies a class that names itself in a static field, such asstatic instance = new Registry(), into code that stops at startup withReferenceError: 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/core2.3.2 was current may hold it in its lockfile beside@rsbuild/core2.3.0 to 2.3.2, so MeoCord now asks for@rsbuild/core2.2, or 2.3.3 and later, which needs@rspack/core2.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
b29df91Thanks @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": trueand"emitDecoratorMetadata": truein 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 setexperimentalDecorators. 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 frommeocord createsets both options already.#975
7cc2b86Thanks @l7aromeo! - An observer'sDispatchResult.startedAtfollows 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.durationMsis still measured withperformance.now(). Nothing to change in your code.#1043
a31543fThanks @l7aromeo! - A stopped app no longer asks its theme resolver, and a stop no longer leaves a slowonReadywarning behind.- Once a bot's stop or a testing module's
close()has ended its shutdown, a theme lookup asks nothemeForresolver: an answer outside any call and a testing module'sdispatch()afterclose()answer in the handler's theme, or the app's outside a call, and nothing is logged for the lookup. TheonShutdownhooks 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
onReadystill 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.
- Once a bot's stop or a testing module's
#1040
a692cdaThanks @l7aromeo! - A start thatstop()ends now rejects only once the stop is done with theonShutdownhooks of what the start made, andstop()resolves after it, on every runtime. Done means the hooks have finished, orshutdownTimeouthas ended the wait for them. Before, the order came from promise timing: on Node it was usually this one, but on Bunstart()rejected before the values it made were closed, and on Node too when anonShutdownhook awaited anything. Code that awaitsstart()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'sshutdownTimeoutwait for it ends. The stop resolves without it, and that start rejects once the factory settles. Astop()that anonShutdownhook 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
691c718Thanks @l7aromeo! - UnderuseStrictMocks(),MeoCordTestingModule'sinit({ ready: true })andclose()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: itsonReadyafter the controllers' and observers', and itsonShutdownbefore 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
f462750Thanks @l7aromeo! -t(key, params),t.default,t.locale(l),t.for(…)andt.forGuild(…)take params for a message typedstring, as in a translator typedTranslator<any>or typed by hand from a JSON file's shape, and a plural whose forms are typedstringtakes params besides itscount. 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 asRecord<string, { one: string; other: string }>, whose forms typedstringtake any params besidecount. Params stay optional for a message typedstring, and a plural still requires itscount.Translator<never>, ascreateTranslator(… as never)gives, takes any params on any key, where the published types refused the call. So doesTranslator<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.MessageParamsof a message typedstringis any params, so a type readingkeyof MessageParams<string>seesstring. See Localisation.#1051
ba6da50Thanks @l7aromeo! - A new app frommeocord createstarts 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/node26.6.6, eslint 10.15.0, typescript-eslint and@typescript-eslint/parser8.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
8176265Thanks @l7aromeo! - A new app frommeocord createruns 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), sotestandtest:coveragestopped before any test withTypeError: child.channel?.unref is not a function. The template now asks for vitest and@vitest/coverage-istanbulat 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 shipschannel.unref. An existing app with vitest 5.1.1 can set both packages to5.1.0in itspackage.json, or run its tests with Node.js installed.#1058
e7cebdaThanks @l7aromeo! - A testing module'sclose()called from a call it is running, such as a command handler that awaitsmodule.close(), no longer waits for that call. Before, in a module whose cooldown store has anonShutdown, the close drained the calls under way, the handler awaiting it among them, so it waited outshutdownTimeoutless the hooks' reserve, warnedCalls still running after … ms, and only then ran theonShutdownhooks and resolved. Now it leaves that call out, as the bot'sapp.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
1cdbd95Thanks @l7aromeo! - The declarations ofTestingModuleandTestingModuleBuilder, frommeocord/testing, no longer name the internal types MeoCord makes a module from, such asProviderMapandLifecycleUnit. Each constructor parameter is declaredunknown, so your editor's hover shows none of them. Nothing stops compiling: code that callsnewon either class, extends it or passes it as a constructor type compiles as before. The constructors stay undocumented: make a module withMeoCordTestingModule.create(…).compile()orMeoCordTestingModule.fromApp(…).compile(). See https://meocord.dev/docs/4.3/testing.#1074
ff1485bThanks @l7aromeo! - A testing module closed duringinit({ ready: true })now runs theonReadyandonShutdownhooks as the bot does when it stops before or during its ready hooks. Onceinit({ ready: true })is asked,close()lets no furtheronReadystart, and runs noonShutdownfor a unit whoseonReadyhasn't settled whenclose()lists what it shuts down, such as one still running or one that never started becauseclose()came first, nor for anything that depends on it. A unit whoseonReadyfailed has settled and is shut down. Before, the module went on with theonReadyhooks afterclose(). Onceclose()stopped waiting for them, at itsshutdownTimeoutless the hooks' reserve, it ranonShutdownfor every unit it had made, one still in itsonReadyincluded, and the units the later hooks made had nothing to shut them down. Aclose()before the hooks started, whileinit()made the providers, waited for every factory, then did the same. A test that callsclose()before theonReadyhooks finish now sees the bot's shutdown: if it expected the later hooks to run, or a unit whoseonReadyhasn't settled to be shut down, awaitinit({ ready: true })beforeclose(). Withoutinit({ ready: true }), nothing changes:close()still shuts down every unit the module made. See https://meocord.dev/docs/4.3/testing.#976
379365fThanks @l7aromeo! -meocord/testingno longer loadscli-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 withoutcli-table3, which only the startup table of registered commands uses.#1024
1ba4a77Thanks @l7aromeo! - ATranslatorinjected without its catalog type, asconstructor(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 int.default,t.locale(l),t.for(…)andt.forGuild(…), and "… is not assignable to parameter of type 'never'" fort.localizationsand for a key given params. Every method that takes a key gives that sentence:t.default,t.locale(l),t.for(…),t.forGuild(…)andt.localizations. Such a translator passes on as before, as totranslateError, and typed translators assign to and from it as before.MessageKeyandLocalizationKeyofCatalogShape, a bareTranslator's catalog type, or of an index signature with no keys that takes any catalog, are that sentence instead ofnever. See Localisation.#1019
527f4e8Thanks @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 throwsuseMockFn() 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: calluseMockFn()first, in the test runner's setup file. See Mocks.