yuzuha 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +3 -3
- package/VERSIONING.md +18 -5
- package/dist/commands/arguments.d.ts.map +1 -1
- package/dist/commands/arguments.js +40 -13
- package/dist/commands/arguments.js.map +1 -1
- package/dist/commands/builders.d.ts +1 -0
- package/dist/commands/builders.d.ts.map +1 -1
- package/dist/commands/builders.js +5 -0
- package/dist/commands/builders.js.map +1 -1
- package/dist/commands/context-like.d.ts +4 -0
- package/dist/commands/context-like.d.ts.map +1 -0
- package/dist/commands/context-like.js +2 -0
- package/dist/commands/context-like.js.map +1 -0
- package/dist/commands/context.d.ts +16 -2
- package/dist/commands/context.d.ts.map +1 -1
- package/dist/commands/context.js +53 -11
- package/dist/commands/context.js.map +1 -1
- package/dist/commands/definition.d.ts +1 -0
- package/dist/commands/definition.d.ts.map +1 -1
- package/dist/commands/definition.js.map +1 -1
- package/dist/commands/typed-arguments.js +2 -2
- package/dist/commands/typed-arguments.js.map +1 -1
- package/dist/domain/cdn.d.ts +23 -0
- package/dist/domain/cdn.d.ts.map +1 -0
- package/dist/domain/cdn.js +38 -0
- package/dist/domain/cdn.js.map +1 -0
- package/dist/domain/resolvers.d.ts +60 -0
- package/dist/domain/resolvers.d.ts.map +1 -0
- package/dist/domain/resolvers.js +31 -0
- package/dist/domain/resolvers.js.map +1 -0
- package/dist/domain/values.d.ts +2 -0
- package/dist/domain/values.d.ts.map +1 -1
- package/dist/domain/values.js +26 -1
- package/dist/domain/values.js.map +1 -1
- package/dist/framework/bot.d.ts +5 -0
- package/dist/framework/bot.d.ts.map +1 -1
- package/dist/framework/bot.js +44 -9
- package/dist/framework/bot.js.map +1 -1
- package/dist/framework/logging.d.ts +4 -1
- package/dist/framework/logging.d.ts.map +1 -1
- package/dist/framework/logging.js.map +1 -1
- package/dist/framework/options.d.ts +12 -0
- package/dist/framework/options.d.ts.map +1 -1
- package/dist/framework/options.js.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/fluxer/resources/channels.d.ts.map +1 -1
- package/dist/infrastructure/fluxer/resources/channels.js +62 -8
- package/dist/infrastructure/fluxer/resources/channels.js.map +1 -1
- package/dist/infrastructure/fluxer/resources/expressions.d.ts.map +1 -1
- package/dist/infrastructure/fluxer/resources/expressions.js +2 -1
- package/dist/infrastructure/fluxer/resources/expressions.js.map +1 -1
- package/dist/infrastructure/fluxer/resources/messages.d.ts +2 -1
- package/dist/infrastructure/fluxer/resources/messages.d.ts.map +1 -1
- package/dist/infrastructure/fluxer/resources/messages.js +16 -7
- package/dist/infrastructure/fluxer/resources/messages.js.map +1 -1
- package/dist/infrastructure/fluxer/resources/users.d.ts +1 -1
- package/dist/infrastructure/fluxer/resources/users.d.ts.map +1 -1
- package/dist/infrastructure/fluxer/resources/users.js +41 -9
- package/dist/infrastructure/fluxer/resources/users.js.map +1 -1
- package/dist/infrastructure/fluxer/resources.d.ts +3 -1
- package/dist/infrastructure/fluxer/resources.d.ts.map +1 -1
- package/dist/infrastructure/fluxer/resources.js +8 -3
- package/dist/infrastructure/fluxer/resources.js.map +1 -1
- package/dist/infrastructure/fluxer/transport.d.ts +4 -1
- package/dist/infrastructure/fluxer/transport.d.ts.map +1 -1
- package/dist/infrastructure/fluxer/transport.js +41 -14
- package/dist/infrastructure/fluxer/transport.js.map +1 -1
- package/dist/ports/resources/channels.d.ts +20 -1
- package/dist/ports/resources/channels.d.ts.map +1 -1
- package/dist/ports/resources/channels.js.map +1 -1
- package/dist/ports/resources/users.d.ts +5 -0
- package/dist/ports/resources/users.d.ts.map +1 -1
- package/dist/ports/resources/users.js.map +1 -1
- package/dist/services/authorization.js +9 -9
- package/dist/services/authorization.js.map +1 -1
- package/dist/services/members.d.ts +5 -0
- package/dist/services/members.d.ts.map +1 -1
- package/dist/services/members.js +75 -5
- package/dist/services/members.js.map +1 -1
- package/dist/services/moderation.js +9 -9
- package/dist/services/moderation.js.map +1 -1
- package/dist/services/resource-authorization.d.ts.map +1 -1
- package/dist/services/resource-authorization.js +31 -17
- package/dist/services/resource-authorization.js.map +1 -1
- package/dist/services/retry.d.ts +17 -0
- package/dist/services/retry.d.ts.map +1 -0
- package/dist/services/retry.js +67 -0
- package/dist/services/retry.js.map +1 -0
- package/dist/shared/errors.d.ts +4 -1
- package/dist/shared/errors.d.ts.map +1 -1
- package/dist/shared/errors.js +8 -1
- package/dist/shared/errors.js.map +1 -1
- package/dist/testing.d.ts +8 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +24 -4
- package/dist/testing.js.map +1 -1
- package/docs/API.md +11 -0
- package/docs/CANVAS.md +1 -1
- package/docs/FRAMEWORK.md +13 -0
- package/docs/IMAGES.md +9 -0
- package/docs/NATIVE.md +49 -1
- package/docs/PARITY-MATRIX.md +31 -32
- package/docs/QUICKSTART.md +2 -2
- package/docs/README.md +1 -1
- package/docs/TESTING.md +16 -0
- package/package.json +1 -1
- package/src/commands/arguments.ts +35 -13
- package/src/commands/builders.ts +4 -0
- package/src/commands/context-like.ts +7 -0
- package/src/commands/context.ts +56 -11
- package/src/commands/definition.ts +1 -0
- package/src/commands/typed-arguments.ts +2 -2
- package/src/domain/cdn.ts +55 -0
- package/src/domain/resolvers.ts +42 -0
- package/src/domain/values.ts +28 -1
- package/src/framework/bot.ts +41 -10
- package/src/framework/logging.ts +5 -1
- package/src/framework/options.ts +4 -0
- package/src/index.ts +13 -0
- package/src/infrastructure/fluxer/resources/channels.ts +53 -8
- package/src/infrastructure/fluxer/resources/expressions.ts +2 -1
- package/src/infrastructure/fluxer/resources/messages.ts +17 -6
- package/src/infrastructure/fluxer/resources/users.ts +38 -9
- package/src/infrastructure/fluxer/resources.ts +4 -3
- package/src/infrastructure/fluxer/transport.ts +42 -13
- package/src/ports/resources/channels.ts +11 -1
- package/src/ports/resources/users.ts +3 -0
- package/src/services/authorization.ts +9 -9
- package/src/services/members.ts +70 -5
- package/src/services/moderation.ts +9 -9
- package/src/services/resource-authorization.ts +31 -17
- package/src/services/retry.ts +74 -0
- package/src/shared/errors.ts +10 -1
- package/src/testing.ts +28 -4
package/docs/NATIVE.md
CHANGED
|
@@ -226,6 +226,10 @@ await ctx.reply(`${membro.displayName}: ${canais.length} canais, ${fixadas.lengt
|
|
|
226
226
|
| `threads` | `create`, `archive`, `unarchive`, `forumPost`, `addMember`, `removeMember`, `members`, `member`, `edit`, `join`, `leave`, `setLocked`, `editSelf`, `editDefaults`, `search` |
|
|
227
227
|
| `invites` | `get`, `create`, `delete`, `list`, `vanity`, `setVanity` |
|
|
228
228
|
|
|
229
|
+
Também há `ctx.deleteCommandMessage()` (degrada `reply` para `send`) e `send`/`reply` aceitam `{ ttlMs }` para mensagens temporárias excluídas pelo timer do bot.
|
|
230
|
+
|
|
231
|
+
`ctx.mod.canBan`/`canKick`/`canModerate` devolvem `false` para falhas de guarda — permissão, hierarquia, alvo inválido e membro ausente (`MEMBER_NOT_FOUND`); erros reais continuam sendo lançados.
|
|
232
|
+
|
|
229
233
|
`purgeDM` em canais de anotações pessoais (tipo 999) só pode ser chamado por
|
|
230
234
|
`bot.resources`, sem wrapper de autorização.
|
|
231
235
|
|
|
@@ -289,10 +293,54 @@ use `mockResources`, que aceita implementações parciais por método.
|
|
|
289
293
|
|
|
290
294
|
## Membros, mensagens e transações
|
|
291
295
|
|
|
292
|
-
|
|
296
|
+
## Consulta e gestão de membros e mensagens
|
|
297
|
+
|
|
298
|
+
`arg.user().anywhere()` marca um argumento `user` que pode vir em qualquer
|
|
299
|
+
posição: a menção (`<@id>`/`<@!id>`) ou ID de 17–20 dígitos é removida dos
|
|
300
|
+
tokens antes do parse posicional (`purge 2 @user` e `purge @user 2` ligam
|
|
301
|
+
`count=2`/`target=id`), e o resto (`arg.string().rest()`) recebe os tokens
|
|
302
|
+
restantes. Apenas um `anywhere()` por comando e só em `arg.user()`.
|
|
293
303
|
|
|
294
304
|
`ctx.members.search(nome, limite?, offset?)` retorna `members`, `total`, `hasMore`
|
|
295
305
|
e `indexing`. `ctx.members.setNickname(usuarioOuObjeto, apelidoOuNull, motivo)`
|
|
306
|
+
|
|
307
|
+
`ctx.members.resolve(query)` resolve um membro a partir de texto livre:
|
|
308
|
+
menção (`<@id>`), ID de snowflake, nome exato ou prefixo — sensível a nada
|
|
309
|
+
de acentuação nem caixa (normalização NFD). O resultado é `{ status }` com
|
|
310
|
+
`found` (`id`, `label` apelido > nome de exibição > nome de usuário,
|
|
311
|
+
`mention`, `via`), `ambiguous` (`candidates` com até 5 itens em ordem
|
|
312
|
+
determinística) ou `missing` (`query`). `ctx.members.resolveUser(query)`
|
|
313
|
+
resolve por menção/ID para usuários que talvez não sejam membros (só
|
|
314
|
+
`found`/`missing`). `ctx.members.resolveBan(query)` faz o mesmo sobre a
|
|
315
|
+
lista de banidos (o encontrado traz `reason`); `users.resolveBan(guildID,
|
|
316
|
+
query)` é a forma em recursos.
|
|
317
|
+
|
|
318
|
+
`cleanReason(texto, { maxLength? })` remove menções de usuário, cargo e
|
|
319
|
+
canal, colapsa espaços e trunca em 512 caracteres (o limite de motivos) —
|
|
320
|
+
use para compor o motivo a partir do resto do texto do comando.
|
|
321
|
+
|
|
322
|
+
`channels.overwrite(canal, alvo, input, { merge: true })` aplica os bits
|
|
323
|
+
de `input.allow`/`input.deny` como PATCH sobre o overwrite existente:
|
|
324
|
+
bits de allow são removidos de deny (e vice-versa), `input.neutral`
|
|
325
|
+
devolve bits ao estado herdado e qualquer outro bit é preservado. Sem
|
|
326
|
+
`merge` o comportamento é o PUT integral de sempre (`neutral` vira erro).
|
|
327
|
+
`channels.lock(canal, { permission?, targetID?, reason? })` nega a
|
|
328
|
+
permissão (padrão `SendMessages` em texto, `Connect` em voz; alvo padrão
|
|
329
|
+
`@everyone`); `channels.unlock` devolve o bit ao herdado — sem conceder
|
|
330
|
+
allow. Ambos retornam `{ channelID, targetID, permission, locked }` e são
|
|
331
|
+
idempotentes, com a mesma autorização de `overwrite` (`ManageChannels`).
|
|
332
|
+
|
|
333
|
+
`users.bannerURL(userID, guildID?, { size? })` lê o banner pelo endpoint de
|
|
334
|
+
perfil (banner de servidor primeiro quando `guildID` é dado, depois o
|
|
335
|
+
global) — hashes animados (`a_*`) viram `.gif`. `UserProfileInfo` (global e
|
|
336
|
+
de servidor) traz `bannerURL` pronto. Objetos de info (usuário, membro,
|
|
337
|
+
servidor, emoji) já saem com a extensão correta para assets animados.
|
|
338
|
+
|
|
339
|
+
`cdn` (raiz e `ctx.cdn`, sem depender do cliente) monta URLs do CDN:
|
|
340
|
+
`avatar`, `banner`, `guildIcon`, `guildBanner`, `guildSplash`,
|
|
341
|
+
`memberAvatar`, `memberBanner`, `emoji`, `sticker` e `asset(url, { size?,
|
|
342
|
+
format? })` (tamanhos de 16 a 4096 em potências de dois). A base de mídia é
|
|
343
|
+
configurável por `YuzuhaOptions.cdn.mediaBase` (URL https).
|
|
296
344
|
compartilha as verificações de `$nickname`: autor e bot precisam de permissão,
|
|
297
345
|
o bot precisa superar o alvo na hierarquia, e o dono é protegido. Para alterar
|
|
298
346
|
o próprio apelido, o autor pode usar `ChangeNickname`; `ManageNicknames` também
|
package/docs/PARITY-MATRIX.md
CHANGED
|
@@ -16,11 +16,11 @@ A cobertura é por nome: um método `send` de uma classe conta como coberto se q
|
|
|
16
16
|
|
|
17
17
|
| Status | Exports de runtime | Membros |
|
|
18
18
|
|---|---:|---:|
|
|
19
|
-
| coberto-recurso |
|
|
20
|
-
| coberto-nativo |
|
|
21
|
-
| coberto-equivalente | 0 |
|
|
22
|
-
| só-SDK |
|
|
23
|
-
| lacuna |
|
|
19
|
+
| coberto-recurso | 51 | 431 |
|
|
20
|
+
| coberto-nativo | 10 | 128 |
|
|
21
|
+
| coberto-equivalente | 0 | 55 |
|
|
22
|
+
| só-SDK | 51 | 108 |
|
|
23
|
+
| lacuna | 5 | 0 |
|
|
24
24
|
|
|
25
25
|
Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são listados, mas não contam como lacuna.
|
|
26
26
|
|
|
@@ -40,16 +40,16 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
40
40
|
| @fluxerjs/core | `BETA_CLIENT_CLUSTER_WARNING` | variable | só SDK | só-SDK | |
|
|
41
41
|
| @fluxerjs/core | `CacheController` | class | Cliente e eventos | coberto-nativo | código nativo |
|
|
42
42
|
| @fluxerjs/core | `CategoryChannel` | class | Canais | só-SDK | |
|
|
43
|
-
| @fluxerjs/core | `CDN_URL` | variable | CDN |
|
|
44
|
-
| @fluxerjs/core | `cdnAvatarURL` | function | CDN |
|
|
45
|
-
| @fluxerjs/core | `cdnBannerURL` | function | CDN |
|
|
46
|
-
| @fluxerjs/core | `cdnDefaultAvatarURL` | function | CDN |
|
|
47
|
-
| @fluxerjs/core | `cdnDisplayAvatarURL` | function | CDN |
|
|
48
|
-
| @fluxerjs/core | `cdnEmojiURL` | function | CDN |
|
|
49
|
-
| @fluxerjs/core | `cdnGuildAssetURL` | function | CDN |
|
|
50
|
-
| @fluxerjs/core | `cdnMemberAvatarURL` | function | CDN |
|
|
51
|
-
| @fluxerjs/core | `cdnMemberBannerURL` | function | CDN |
|
|
52
|
-
| @fluxerjs/core | `cdnStickerURL` | function | CDN |
|
|
43
|
+
| @fluxerjs/core | `CDN_URL` | variable | CDN | lacuna | |
|
|
44
|
+
| @fluxerjs/core | `cdnAvatarURL` | function | CDN | coberto-nativo | código nativo |
|
|
45
|
+
| @fluxerjs/core | `cdnBannerURL` | function | CDN | coberto-nativo | código nativo |
|
|
46
|
+
| @fluxerjs/core | `cdnDefaultAvatarURL` | function | CDN | lacuna | |
|
|
47
|
+
| @fluxerjs/core | `cdnDisplayAvatarURL` | function | CDN | lacuna | |
|
|
48
|
+
| @fluxerjs/core | `cdnEmojiURL` | function | CDN | coberto-nativo | código nativo |
|
|
49
|
+
| @fluxerjs/core | `cdnGuildAssetURL` | function | CDN | coberto-nativo | código nativo |
|
|
50
|
+
| @fluxerjs/core | `cdnMemberAvatarURL` | function | CDN | coberto-nativo | código nativo |
|
|
51
|
+
| @fluxerjs/core | `cdnMemberBannerURL` | function | CDN | coberto-nativo | código nativo |
|
|
52
|
+
| @fluxerjs/core | `cdnStickerURL` | function | CDN | coberto-nativo | código nativo |
|
|
53
53
|
| @fluxerjs/core | `Channel` | class | Canais | coberto-recurso | builtins |
|
|
54
54
|
| @fluxerjs/core | `ChannelManager` | class | Canais | coberto-recurso | builtins |
|
|
55
55
|
| @fluxerjs/core | `Client` | class | Cliente e eventos | coberto-recurso | builtins |
|
|
@@ -81,7 +81,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
81
81
|
| @fluxerjs/core | `INSTANCE_DISCOVERY_PATH` | variable | Instância e discovery | só-SDK | |
|
|
82
82
|
| @fluxerjs/core | `instanceDiscoveryUrl` | function | Instância e discovery | só-SDK | |
|
|
83
83
|
| @fluxerjs/core | `Invite` | class | Convites | coberto-recurso | builtins |
|
|
84
|
-
| @fluxerjs/core | `inviteUrl` | function | Convites |
|
|
84
|
+
| @fluxerjs/core | `inviteUrl` | function | Convites | lacuna | |
|
|
85
85
|
| @fluxerjs/core | `LinkChannel` | class | Canais | coberto-recurso | builtins |
|
|
86
86
|
| @fluxerjs/core | `MediaChannel` | class | Canais | só-SDK | |
|
|
87
87
|
| @fluxerjs/core | `Message` | class | Mensagens e reações | coberto-recurso | builtins |
|
|
@@ -102,7 +102,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
102
102
|
| @fluxerjs/core | `parseUserMention` | function | Texto e guards | só-SDK | |
|
|
103
103
|
| @fluxerjs/core | `PartialGuildMember` | class | Usuários e membros | coberto-recurso | builtins |
|
|
104
104
|
| @fluxerjs/core | `PartialMessage` | class | Mensagens e reações | coberto-recurso | builtins |
|
|
105
|
-
| @fluxerjs/core | `PermissionFlags` | variable | Constantes e bitfields | coberto-
|
|
105
|
+
| @fluxerjs/core | `PermissionFlags` | variable | Constantes e bitfields | coberto-recurso | builtins |
|
|
106
106
|
| @fluxerjs/core | `PermissionOverwrite` | class | Canais | coberto-recurso | builtins |
|
|
107
107
|
| @fluxerjs/core | `PermissionOverwriteManager` | class | Canais | coberto-recurso | builtins |
|
|
108
108
|
| @fluxerjs/core | `PermissionsBitField` | class | Constantes e bitfields | coberto-recurso | builtins |
|
|
@@ -113,9 +113,9 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
113
113
|
| @fluxerjs/core | `resolveKlipyToImageUrl` | function | Texto e guards | só-SDK | |
|
|
114
114
|
| @fluxerjs/core | `resolvePermissionsToBitfield` | function | Constantes e bitfields | só-SDK | |
|
|
115
115
|
| @fluxerjs/core | `Role` | class | Cargos | coberto-recurso | builtins |
|
|
116
|
-
| @fluxerjs/core | `Routes` | variable | Constantes e bitfields | só-SDK |
|
|
116
|
+
| @fluxerjs/core | `Routes` | variable | Constantes e bitfields | só-SDK | builtins |
|
|
117
117
|
| @fluxerjs/core | `serializeError` | function | Erros e logs | só-SDK | |
|
|
118
|
-
| @fluxerjs/core | `STATIC_CDN_URL` | variable | CDN |
|
|
118
|
+
| @fluxerjs/core | `STATIC_CDN_URL` | variable | CDN | lacuna | |
|
|
119
119
|
| @fluxerjs/core | `SystemChannelFlags` | variable | Constantes e bitfields | só-SDK | |
|
|
120
120
|
| @fluxerjs/core | `TextChannel` | class | Canais | coberto-recurso | builtins |
|
|
121
121
|
| @fluxerjs/core | `ThreadChannel` | class | Threads | coberto-recurso | builtins |
|
|
@@ -142,7 +142,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
142
142
|
| @fluxerjs/types | `MessageAttachmentFlags` | variable | Constantes e bitfields | só-SDK | |
|
|
143
143
|
| @fluxerjs/types | `MessageFlags` | variable | Constantes e bitfields | só-SDK | |
|
|
144
144
|
| @fluxerjs/types | `PublicUserFlags` | variable | Constantes e bitfields | só-SDK | |
|
|
145
|
-
| @fluxerjs/types | `Routes` | variable | Constantes e bitfields | só-SDK |
|
|
145
|
+
| @fluxerjs/types | `Routes` | variable | Constantes e bitfields | só-SDK | builtins |
|
|
146
146
|
| @fluxerjs/types | `SystemChannelFlags` | variable | Constantes e bitfields | só-SDK | |
|
|
147
147
|
| @fluxerjs/types | `ThreadMemberFlags` | variable | Constantes e bitfields | só-SDK | |
|
|
148
148
|
|
|
@@ -227,7 +227,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
227
227
|
| `Channel` | `isLink` | método | coberto-equivalente |
|
|
228
228
|
| `Channel` | `isMedia` | método | coberto-recurso |
|
|
229
229
|
| `Channel` | `isPersonalNotes` | método | coberto-equivalente |
|
|
230
|
-
| `Channel` | `isText` | método | coberto-
|
|
230
|
+
| `Channel` | `isText` | método | coberto-nativo |
|
|
231
231
|
| `Channel` | `isTextBased` | método | coberto-recurso |
|
|
232
232
|
| `Channel` | `isThread` | método | coberto-recurso |
|
|
233
233
|
| `Channel` | `isVoice` | método | coberto-nativo |
|
|
@@ -259,7 +259,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
259
259
|
| `Client` | `_ws` | propriedade | só-SDK |
|
|
260
260
|
| `Client` | `assertReady` | método | coberto-nativo |
|
|
261
261
|
| `Client` | `bulkFetchMessages` | método | coberto-nativo |
|
|
262
|
-
| `Client` | `cache` | propriedade | coberto-
|
|
262
|
+
| `Client` | `cache` | propriedade | coberto-recurso |
|
|
263
263
|
| `Client` | `channels` | propriedade | coberto-recurso |
|
|
264
264
|
| `Client` | `destroy` | método | coberto-nativo |
|
|
265
265
|
| `Client` | `emit` | método | coberto-nativo |
|
|
@@ -289,8 +289,8 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
289
289
|
| `Client` | `requestGuildCounts` | método | coberto-recurso |
|
|
290
290
|
| `Client` | `requestGuildMembers` | método | coberto-nativo |
|
|
291
291
|
| `Client` | `resolveEmoji` | método | coberto-recurso |
|
|
292
|
-
| `Client` | `rest` | propriedade |
|
|
293
|
-
| `Client` | `Routes` | acessor |
|
|
292
|
+
| `Client` | `rest` | propriedade | coberto-recurso |
|
|
293
|
+
| `Client` | `Routes` | acessor | coberto-recurso |
|
|
294
294
|
| `Client` | `searchMessages` | método | coberto-recurso |
|
|
295
295
|
| `Client` | `sendToGateway` | método | coberto-nativo |
|
|
296
296
|
| `Client` | `subscribeThreads` | método | coberto-nativo |
|
|
@@ -494,7 +494,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
494
494
|
| `GuildMember` | `_clone` | método | só-SDK |
|
|
495
495
|
| `GuildMember` | `_patch` | método | só-SDK |
|
|
496
496
|
| `GuildMember` | `accentColor` | propriedade | coberto-recurso |
|
|
497
|
-
| `GuildMember` | `avatar` | propriedade |
|
|
497
|
+
| `GuildMember` | `avatar` | propriedade | coberto-nativo |
|
|
498
498
|
| `GuildMember` | `avatarURL` | método | coberto-recurso |
|
|
499
499
|
| `GuildMember` | `ban` | método | coberto-recurso |
|
|
500
500
|
| `GuildMember` | `bannable` | acessor | coberto-equivalente |
|
|
@@ -533,11 +533,11 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
533
533
|
| `GuildMemberManager` | `search` | método | coberto-recurso |
|
|
534
534
|
| `GuildMemberRoleManager` | `_patch` | método | só-SDK |
|
|
535
535
|
| `GuildMemberRoleManager` | `add` | método | coberto-recurso |
|
|
536
|
-
| `GuildMemberRoleManager` | `cache` | acessor | coberto-
|
|
536
|
+
| `GuildMemberRoleManager` | `cache` | acessor | coberto-recurso |
|
|
537
537
|
| `GuildMemberRoleManager` | `has` | método | coberto-recurso |
|
|
538
538
|
| `GuildMemberRoleManager` | `remove` | método | coberto-recurso |
|
|
539
539
|
| `GuildMemberRoleManager` | `roleIds` | acessor | coberto-recurso |
|
|
540
|
-
| `GuildMemberRoleManager` | `set` | método | coberto-
|
|
540
|
+
| `GuildMemberRoleManager` | `set` | método | coberto-recurso |
|
|
541
541
|
| `GuildRoleManager` | `everyone` | acessor | coberto-equivalente |
|
|
542
542
|
| `GuildSticker` | `_patch` | método | só-SDK |
|
|
543
543
|
| `GuildSticker` | `animated` | propriedade | coberto-recurso |
|
|
@@ -683,7 +683,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
683
683
|
| `MessageReaction` | `messageId` | propriedade | coberto-recurso |
|
|
684
684
|
| `MessageReactionManager` | `_patch` | método | só-SDK |
|
|
685
685
|
| `MessageReactionManager` | `[Symbol.iterator]` | método | só-SDK |
|
|
686
|
-
| `MessageReactionManager` | `cache` | acessor | coberto-
|
|
686
|
+
| `MessageReactionManager` | `cache` | acessor | coberto-recurso |
|
|
687
687
|
| `MessageReactionManager` | `size` | acessor | coberto-recurso |
|
|
688
688
|
| `MessageSticker` | `animated` | propriedade | coberto-recurso |
|
|
689
689
|
| `MessageSticker` | `client` | propriedade | coberto-recurso |
|
|
@@ -722,7 +722,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
722
722
|
| `PermissionOverwrite` | `type` | propriedade | coberto-recurso |
|
|
723
723
|
| `PermissionOverwriteManager` | `_patch` | método | só-SDK |
|
|
724
724
|
| `PermissionOverwriteManager` | `[Symbol.iterator]` | método | só-SDK |
|
|
725
|
-
| `PermissionOverwriteManager` | `cache` | acessor | coberto-
|
|
725
|
+
| `PermissionOverwriteManager` | `cache` | acessor | coberto-recurso |
|
|
726
726
|
| `PermissionOverwriteManager` | `delete` | método | coberto-recurso |
|
|
727
727
|
| `PermissionOverwriteManager` | `edit` | método | coberto-recurso |
|
|
728
728
|
| `PermissionOverwriteManager` | `size` | acessor | coberto-recurso |
|
|
@@ -814,7 +814,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
814
814
|
| `ThreadMemberManager` | `fetchOne` | método | coberto-recurso |
|
|
815
815
|
| `ThreadMemberManager` | `remove` | método | coberto-recurso |
|
|
816
816
|
| `User` | `_patch` | método | só-SDK |
|
|
817
|
-
| `User` | `avatar` | propriedade |
|
|
817
|
+
| `User` | `avatar` | propriedade | coberto-nativo |
|
|
818
818
|
| `User` | `avatarColor` | propriedade | só-SDK |
|
|
819
819
|
| `User` | `avatarURL` | método | coberto-recurso |
|
|
820
820
|
| `User` | `banner` | propriedade | coberto-recurso |
|
|
@@ -852,7 +852,7 @@ Pacotes: @fluxerjs/core, @fluxerjs/builders, @fluxerjs/types. Tipos e enums são
|
|
|
852
852
|
| `VoiceChannel` | `topic` | propriedade | coberto-recurso |
|
|
853
853
|
| `VoiceChannel` | `userLimit` | propriedade | só-SDK |
|
|
854
854
|
| `VoiceChannel` | `voiceConnectionLimit` | propriedade | só-SDK |
|
|
855
|
-
| `Webhook` | `avatar` | propriedade |
|
|
855
|
+
| `Webhook` | `avatar` | propriedade | coberto-nativo |
|
|
856
856
|
| `Webhook` | `avatarURL` | método | coberto-recurso |
|
|
857
857
|
| `Webhook` | `channelId` | propriedade | coberto-recurso |
|
|
858
858
|
| `Webhook` | `client` | propriedade | coberto-recurso |
|
|
@@ -951,7 +951,6 @@ Eventos do function mode que o SDK não declara: nenhum.
|
|
|
951
951
|
## Exceções intencionais (só SDK)
|
|
952
952
|
|
|
953
953
|
- **Sharding e cluster** (`BETA_CLIENT_CLUSTER_WARNING`, `ClientCluster`, `ClientClusterEvents`): Fora deste lote. O Yuzuha expõe shardCount e shardIds em clientOptions; o wrapper yuzuha/sharding fica como seguimento.
|
|
954
|
-
- **CDN e helpers de URL** (`CDN_URL`, `STATIC_CDN_URL`, `cdnAvatarURL`, `cdnBannerURL`, `cdnDefaultAvatarURL`, `cdnDisplayAvatarURL`, `cdnEmojiURL`, `cdnGuildAssetURL`, `cdnMemberAvatarURL`, `cdnMemberBannerURL`, `cdnStickerURL`, `inviteUrl`): Disponível por `yuzuha/sdk` (e `SDK` na raiz); sem wrapper nativo por serem constantes, helpers puros ou classes de dados.
|
|
955
954
|
- **Constantes e bitfields puros** (`GuildMemberProfileFlags`, `GuildOperations`, `MessageAttachmentFlags`, `MessageFlags`, `MessageFlagsBitField`, `MessageFlagsBits`, `PublicUserFlags`, `Routes`, `SystemChannelFlags`, `ThreadMemberFlags`, `UserFlagsBitField`, `UserFlagsBits`, `resolvePermissionsToBitfield`, `ErrorCodes`): Disponível por `yuzuha/sdk` (e `SDK` na raiz); sem wrapper nativo por serem constantes, helpers puros ou classes de dados.
|
|
956
955
|
- **Instância, cache e logs** (`DEFAULT_INSTANCE_ENDPOINTS`, `INSTANCE_DISCOVERY_PATH`, `instanceDiscoveryUrl`, `normalizeApiOrigin`, `parseInstanceDiscovery`, `resolveInstanceEndpoints`, `DEFAULT_CACHE_LIMITS`, `normalizeCacheLimit`, `resolveCacheLimits`, `createLogger`, `serializeError`): Disponível por `yuzuha/sdk` (e `SDK` na raiz); sem wrapper nativo por serem constantes, helpers puros ou classes de dados.
|
|
957
956
|
- **Texto e parsing puros** (`parsePrefixCommand`, `parseUserMention`, `resolveKlipyToImageUrl`): Disponível por `yuzuha/sdk` (e `SDK` na raiz); sem wrapper nativo por serem constantes, helpers puros ou classes de dados.
|
package/docs/QUICKSTART.md
CHANGED
|
@@ -10,13 +10,13 @@ Use Node >=22.13 e npm. Em um projeto ESM existente, instale a versão desta
|
|
|
10
10
|
documentação:
|
|
11
11
|
|
|
12
12
|
```sh
|
|
13
|
-
npm install yuzuha@0.3.
|
|
13
|
+
npm install yuzuha@0.3.1
|
|
14
14
|
```
|
|
15
15
|
|
|
16
16
|
Para gerar um bot em uma pasta nova, execute:
|
|
17
17
|
|
|
18
18
|
```sh
|
|
19
|
-
npx yuzuha@0.3.
|
|
19
|
+
npx yuzuha@0.3.1 init ./meu-bot --ts
|
|
20
20
|
cd meu-bot
|
|
21
21
|
npm install
|
|
22
22
|
npm run check
|
package/docs/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Documentação da Yuzuha
|
|
2
2
|
|
|
3
|
-
Esta documentação cobre a Yuzuha 0.3.
|
|
3
|
+
Esta documentação cobre a Yuzuha 0.3.1, em JavaScript ESM e TypeScript, para
|
|
4
4
|
Node >=22.13. O pacote usa `@fluxerjs/core` 3.3.0.
|
|
5
5
|
|
|
6
6
|
JS/TS é o caminho principal da biblioteca. Function mode (`$...`) é opcional e
|
package/docs/TESTING.md
CHANGED
|
@@ -232,3 +232,19 @@ autorizados, com alvos de teste e um store separado.
|
|
|
232
232
|
A matriz de CI está configurada para Node 22, 24 e 26. Execução configurada
|
|
233
233
|
não equivale a execução remota concluída. Resultados efetivamente observados
|
|
234
234
|
estão em [VALIDATION.md](VALIDATION.md).
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
## Autorização em testes
|
|
238
|
+
|
|
239
|
+
`createTestBot({ authorization: 'off' })` desliga o wrapper
|
|
240
|
+
`bindAuthorizedResources` — `ctx.resources` expõe os recursos brutos do
|
|
241
|
+
mock sem precisar simular o grafo de permissões. O padrão `'on'` mantém a
|
|
242
|
+
autorização real (use para testar guards). O switch usa
|
|
243
|
+
`YuzuhaOptions.unsafeDisableResourceAuthorization`, marcado apenas para
|
|
244
|
+
testes e registrado via `onLog` `authorization.disabled`; guards de
|
|
245
|
+
comando, `ctx.mod` e `requirePermission` não são afetados.
|
|
246
|
+
|
|
247
|
+
`CommandContextLike` (export de `yuzuha`) é um `Pick` estrutural de
|
|
248
|
+
`CommandContext` (`reply`, `send`, `args`, `members`, `mod`, `resources`,
|
|
249
|
+
`cdn`, `tokens`, `command`, `executionID`, `message`, `event`...) para
|
|
250
|
+
tipar helpers que também recebem fixtures.
|
package/package.json
CHANGED
|
@@ -6,12 +6,12 @@ export type ArgumentValue = string | number | boolean;
|
|
|
6
6
|
|
|
7
7
|
function validateValue(definition: ArgumentDefinition, value: ArgumentValue): void {
|
|
8
8
|
if (definition.choices && !definition.choices.some(choice => String(choice) === String(value))) {
|
|
9
|
-
throw new GuardError(`${definition.name}: escolha ${definition.choices.join(', ')}
|
|
9
|
+
throw new GuardError(`${definition.name}: escolha ${definition.choices.join(', ')}.`, 'INVALID_ARGUMENT');
|
|
10
10
|
}
|
|
11
11
|
const size = typeof value === 'string' ? value.length : value;
|
|
12
12
|
if (typeof size === 'number') {
|
|
13
|
-
if (definition.min !== undefined && size < definition.min) throw new GuardError(`${definition.name}: mínimo ${definition.min}${typeof value === 'string' ? ' caracteres' : ''}
|
|
14
|
-
if (definition.max !== undefined && size > definition.max) throw new GuardError(`${definition.name}: máximo ${definition.max}${typeof value === 'string' ? ' caracteres' : ''}
|
|
13
|
+
if (definition.min !== undefined && size < definition.min) throw new GuardError(`${definition.name}: mínimo ${definition.min}${typeof value === 'string' ? ' caracteres' : ''}.`, 'INVALID_ARGUMENT');
|
|
14
|
+
if (definition.max !== undefined && size > definition.max) throw new GuardError(`${definition.name}: máximo ${definition.max}${typeof value === 'string' ? ' caracteres' : ''}.`, 'INVALID_ARGUMENT');
|
|
15
15
|
}
|
|
16
16
|
for (const validator of definition.validators ?? []) {
|
|
17
17
|
const accepted: unknown = validator.check(value);
|
|
@@ -19,16 +19,20 @@ function validateValue(definition: ArgumentDefinition, value: ArgumentValue): vo
|
|
|
19
19
|
void Promise.resolve(accepted).catch(() => undefined);
|
|
20
20
|
throw new YuzuhaError('COMMAND_ARGS', `Validador de ${definition.name} deve retornar um booleano síncrono.`);
|
|
21
21
|
}
|
|
22
|
-
if (!accepted) throw new GuardError(validator.message);
|
|
22
|
+
if (!accepted) throw new GuardError(validator.message, 'INVALID_ARGUMENT');
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
export function validateArgumentDefinitions(definitions: readonly ArgumentDefinition[], commandName = 'comando'): void {
|
|
27
27
|
const names = new Set<string>();
|
|
28
|
+
if (definitions.filter(definition => definition.anywhere).length > 1) {
|
|
29
|
+
throw new YuzuhaError('COMMAND_ARGS', `No máximo um argumento anywhere em ${commandName}.`);
|
|
30
|
+
}
|
|
28
31
|
for (const [index, definition] of definitions.entries()) {
|
|
29
32
|
if (typeof definition.name !== 'string' || !definition.name || names.has(definition.name)
|
|
30
33
|
|| (definition.required !== undefined && typeof definition.required !== 'boolean')
|
|
31
34
|
|| (definition.rest !== undefined && typeof definition.rest !== 'boolean')
|
|
35
|
+
|| (definition.anywhere !== undefined && (typeof definition.anywhere !== 'boolean' || definition.type !== 'user' || definition.rest === true))
|
|
32
36
|
|| (definition.description !== undefined && typeof definition.description !== 'string')
|
|
33
37
|
|| (definition.aliases !== undefined && (!Array.isArray(definition.aliases) || definition.aliases.some(alias => typeof alias !== 'string')))
|
|
34
38
|
|| (definition.rest && index !== definitions.length - 1)
|
|
@@ -70,19 +74,19 @@ function parseValue(definition: ArgumentDefinition, input: string | undefined, r
|
|
|
70
74
|
const value = definition.type === 'user' ? userID(String(definition.defaultValue)) : definition.defaultValue;
|
|
71
75
|
validateValue(definition, value);
|
|
72
76
|
return value;
|
|
73
|
-
} else if (required) throw new GuardError(`Informe o argumento ${definition.name}
|
|
77
|
+
} else if (required) throw new GuardError(`Informe o argumento ${definition.name}.`, 'INVALID_ARGUMENT');
|
|
74
78
|
return undefined;
|
|
75
79
|
}
|
|
76
80
|
let value: ArgumentValue = input;
|
|
77
81
|
if (definition.type === 'number' || definition.type === 'integer') {
|
|
78
82
|
value = Number(input);
|
|
79
83
|
if (!input.trim() || !Number.isFinite(value) || (definition.type === 'integer' && !Number.isSafeInteger(value))) {
|
|
80
|
-
throw new GuardError(`${definition.name} deve ser um número${definition.type === 'integer' ? ' inteiro' : ''}
|
|
84
|
+
throw new GuardError(`${definition.name} deve ser um número${definition.type === 'integer' ? ' inteiro' : ''}.`, 'INVALID_ARGUMENT');
|
|
81
85
|
}
|
|
82
86
|
} else if (definition.type === 'boolean') {
|
|
83
87
|
const normalized = input.toLowerCase();
|
|
84
88
|
if (!['true', 'false', 'yes', 'no', 'sim', 'não', 'nao', '1', '0'].includes(normalized)) {
|
|
85
|
-
throw new GuardError(`${definition.name} deve ser true ou false
|
|
89
|
+
throw new GuardError(`${definition.name} deve ser true ou false.`, 'INVALID_ARGUMENT');
|
|
86
90
|
}
|
|
87
91
|
value = ['true', 'yes', 'sim', '1'].includes(normalized);
|
|
88
92
|
} else if (definition.type === 'user') value = userID(input);
|
|
@@ -90,7 +94,7 @@ function parseValue(definition: ArgumentDefinition, input: string | undefined, r
|
|
|
90
94
|
try { value = parseDuration(input); }
|
|
91
95
|
catch (error) {
|
|
92
96
|
if (!(error instanceof YuzuhaError) || error.code !== 'DURATION') throw error;
|
|
93
|
-
throw new GuardError(`${definition.name}: ${error.message}
|
|
97
|
+
throw new GuardError(`${definition.name}: ${error.message}`, 'INVALID_ARGUMENT');
|
|
94
98
|
}
|
|
95
99
|
}
|
|
96
100
|
validateValue(definition, value);
|
|
@@ -99,9 +103,24 @@ function parseValue(definition: ArgumentDefinition, input: string | undefined, r
|
|
|
99
103
|
|
|
100
104
|
export function parseArguments(definitions: readonly ArgumentDefinition[], tokens: readonly string[]): Map<string, ArgumentValue> {
|
|
101
105
|
const args = new Map<string, ArgumentValue>();
|
|
106
|
+
const positional = [...tokens];
|
|
107
|
+
const matched = new Map<string, string>();
|
|
108
|
+
for (const definition of definitions) {
|
|
109
|
+
if (!definition.anywhere) continue;
|
|
110
|
+
let index = positional.findIndex(token => /^<@!?\d+>$/.test(token));
|
|
111
|
+
if (index < 0) {
|
|
112
|
+
for (let candidate = positional.length - 1; candidate >= 0; candidate--) {
|
|
113
|
+
if (/^\d{17,20}$/.test(positional[candidate]!)) { index = candidate; break; }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (index >= 0) matched.set(definition.name, positional.splice(index, 1)[0]!);
|
|
117
|
+
}
|
|
118
|
+
let position = 0;
|
|
102
119
|
for (let index = 0; index < definitions.length; index++) {
|
|
103
120
|
const definition = definitions[index]!;
|
|
104
|
-
const input = definition.rest ?
|
|
121
|
+
const input = definition.rest ? positional.slice(position).join(' ')
|
|
122
|
+
: definition.anywhere ? matched.get(definition.name)
|
|
123
|
+
: positional[position++];
|
|
105
124
|
const value = parseValue(definition, input);
|
|
106
125
|
if (value !== undefined) args.set(definition.name, value);
|
|
107
126
|
}
|
|
@@ -122,12 +141,15 @@ export function tokenize(input: string): string[] {
|
|
|
122
141
|
token = ''; last = ''; started = false;
|
|
123
142
|
} else { token += character; last = character; started = true; }
|
|
124
143
|
}
|
|
125
|
-
if (quote) throw new GuardError('Feche as aspas do argumento.');
|
|
144
|
+
if (quote) throw new GuardError('Feche as aspas do argumento.', 'INVALID_ARGUMENT');
|
|
126
145
|
if (started) result.push(token);
|
|
127
146
|
return result;
|
|
128
147
|
}
|
|
129
148
|
|
|
130
149
|
export function validateFlagDefinitions(definitions: readonly ArgumentDefinition[], commandName: string): void {
|
|
150
|
+
if (definitions.some(definition => definition.anywhere)) {
|
|
151
|
+
throw new YuzuhaError('ARGUMENT_SCHEMA', `.anywhere() só vale para argumentos posicionais de user em ${commandName}.`);
|
|
152
|
+
}
|
|
131
153
|
validateArgumentDefinitions(definitions, commandName);
|
|
132
154
|
const names = new Set<string>();
|
|
133
155
|
for (const definition of definitions) {
|
|
@@ -156,14 +178,14 @@ export function parseFlags(definitions: readonly ArgumentDefinition[] | undefine
|
|
|
156
178
|
if (!(token.startsWith('--') || /^-[^\d.]/u.test(token)) || token === '-') { positional.push(token); continue; }
|
|
157
179
|
const match = /^--?([^=]+)(?:=([\s\S]*))?$/.exec(token);
|
|
158
180
|
const definition = match && lookup.get(match[1]!);
|
|
159
|
-
if (!match || !definition) throw new GuardError(`Flag desconhecida: ${token.split('=')[0]}
|
|
160
|
-
if (values.has(definition.name)) throw new GuardError(`Flag repetida: --${definition.name}
|
|
181
|
+
if (!match || !definition) throw new GuardError(`Flag desconhecida: ${token.split('=')[0]}.`, 'INVALID_ARGUMENT');
|
|
182
|
+
if (values.has(definition.name)) throw new GuardError(`Flag repetida: --${definition.name}.`, 'INVALID_ARGUMENT');
|
|
161
183
|
let input = match[2];
|
|
162
184
|
if (input === undefined) {
|
|
163
185
|
if (definition.type === 'boolean') input = 'true';
|
|
164
186
|
else {
|
|
165
187
|
input = tokens[index + 1];
|
|
166
|
-
if (input === undefined || input.startsWith('--') || /^-[^\d.]/u.test(input)) throw new GuardError(`Informe o valor de --${definition.name}
|
|
188
|
+
if (input === undefined || input.startsWith('--') || /^-[^\d.]/u.test(input)) throw new GuardError(`Informe o valor de --${definition.name}.`, 'INVALID_ARGUMENT');
|
|
167
189
|
index++;
|
|
168
190
|
}
|
|
169
191
|
}
|
package/src/commands/builders.ts
CHANGED
|
@@ -29,6 +29,10 @@ export class ArgumentBuilder<T extends ArgumentValue, Required extends boolean =
|
|
|
29
29
|
optional(): ArgumentBuilder<T, false> { return this.copy<T, false>({ required: false, defaultValue: undefined }); }
|
|
30
30
|
default(value: T): ArgumentBuilder<T, true> { return this.copy<T, true>({ defaultValue: value, required: false }); }
|
|
31
31
|
rest(): ArgumentBuilder<T, Required> { return this.copy({ rest: true }); }
|
|
32
|
+
anywhere(): ArgumentBuilder<T, Required> {
|
|
33
|
+
if (this.definition.type !== 'user') throw new YuzuhaError('ARGUMENT_SCHEMA', '.anywhere() só vale para arg.user().');
|
|
34
|
+
return this.copy({ anywhere: true });
|
|
35
|
+
}
|
|
32
36
|
min(value: number): ArgumentBuilder<T, Required> { return this.copy({ min: value }); }
|
|
33
37
|
max(value: number): ArgumentBuilder<T, Required> { return this.copy({ max: value }); }
|
|
34
38
|
alias(...aliases: string[]): ArgumentBuilder<T, Required> { return this.copy({ aliases: [...aliases] }); }
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CommandContext } from './context.js';
|
|
2
|
+
|
|
3
|
+
/** Structural subset of CommandContext a test fixture may satisfy. */
|
|
4
|
+
export type CommandContextLike = Pick<CommandContext, 'reply' | 'send' | 'edit' | 'delete' | 'react'
|
|
5
|
+
| 'deleteCommandMessage' | 'authorID' | 'authorName' | 'channelID' | 'guildID' | 'args' | 'members'
|
|
6
|
+
| 'mod' | 'resources' | 'cdn' | 'canvas' | 'tokens' | 'command' | 'executionID' | 'input'
|
|
7
|
+
| 'message' | 'event'>;
|
package/src/commands/context.ts
CHANGED
|
@@ -22,6 +22,7 @@ import { NativeModeration } from '../services/native-moderation.js';
|
|
|
22
22
|
import { ScopedData } from '../services/native-data.js';
|
|
23
23
|
import type { NativeData } from '../services/native-data.js';
|
|
24
24
|
import { bindAuthorizedResources } from '../services/resource-authorization.js';
|
|
25
|
+
import { createCdn } from '../domain/cdn.js';
|
|
25
26
|
import { MemberService } from '../services/members.js';
|
|
26
27
|
import type { MusicManager } from '../services/music.js';
|
|
27
28
|
import type { NativeVoice } from '../ports/voice.js';
|
|
@@ -34,6 +35,8 @@ import { commandUsage } from './help.js';
|
|
|
34
35
|
import { ArgumentBag } from './typed-arguments.js';
|
|
35
36
|
import type { Command } from './definition.js';
|
|
36
37
|
|
|
38
|
+
export interface SendOptions { ttlMs?: number }
|
|
39
|
+
|
|
37
40
|
export interface ContextOptions {
|
|
38
41
|
message: IncomingMessage;
|
|
39
42
|
transport: Transport;
|
|
@@ -56,6 +59,9 @@ export interface ContextOptions {
|
|
|
56
59
|
executionID?: string;
|
|
57
60
|
event?: Readonly<ScriptEventData>;
|
|
58
61
|
messageAvailable?: boolean;
|
|
62
|
+
deleteLater?: (channelID: string, messageID: string, ttlMs: number) => void;
|
|
63
|
+
cdn?: import('../domain/cdn.js').Cdn;
|
|
64
|
+
disableResourceAuthorization?: boolean;
|
|
59
65
|
actor?: { guildID: string; authorID: string };
|
|
60
66
|
}
|
|
61
67
|
|
|
@@ -75,6 +81,9 @@ export class CommandContext {
|
|
|
75
81
|
private readonly sourceMessage: IncomingMessage;
|
|
76
82
|
readonly event?: Readonly<ScriptEventData>;
|
|
77
83
|
private readonly messageAvailable: boolean;
|
|
84
|
+
private readonly deleteLaterFn?: (channelID: string, messageID: string, ttlMs: number) => void;
|
|
85
|
+
private cdnService = createCdn();
|
|
86
|
+
private disableResourceAuthorization = false;
|
|
78
87
|
private readonly actor?: { guildID: string; authorID: string };
|
|
79
88
|
readonly transport: Transport;
|
|
80
89
|
readonly store: Store;
|
|
@@ -110,13 +119,14 @@ export class CommandContext {
|
|
|
110
119
|
this.scope = { guildID: this.guildID, authorID: this.authorID };
|
|
111
120
|
this.transport = options.transport;
|
|
112
121
|
this.store = options.store;
|
|
122
|
+
this.deleteLaterFn = options.deleteLater;
|
|
113
123
|
this.command = options.command;
|
|
114
124
|
this.lineage = options.lineage ?? [options.command];
|
|
115
125
|
this.prefix = options.prefix ?? '';
|
|
116
126
|
this.input = options.input ?? '';
|
|
117
127
|
try { this.tokens = tokenize(this.input); }
|
|
118
128
|
catch (error) {
|
|
119
|
-
if (error instanceof GuardError) throw new GuardError(`${error.message}\nUso: ${commandUsage(this.command, this.prefix)}
|
|
129
|
+
if (error instanceof GuardError) throw new GuardError(`${error.message}\nUso: ${commandUsage(this.command, this.prefix)}`, error.reason);
|
|
120
130
|
throw error;
|
|
121
131
|
}
|
|
122
132
|
this.claimCooldown = options.cooldown;
|
|
@@ -128,6 +138,8 @@ export class CommandContext {
|
|
|
128
138
|
this.httpService = options.http;
|
|
129
139
|
this.musicService = options.music;
|
|
130
140
|
this.voiceService = options.voice;
|
|
141
|
+
this.cdnService = options.cdn ?? createCdn();
|
|
142
|
+
this.disableResourceAuthorization = options.disableResourceAuthorization === true;
|
|
131
143
|
this.canvasRenderer = options.canvas?.renderer;
|
|
132
144
|
this.canvasConfig = options.canvas?.config;
|
|
133
145
|
this.nativeResources = options.resources;
|
|
@@ -152,6 +164,8 @@ export class CommandContext {
|
|
|
152
164
|
if (!this.resources.users.leaveGuild) throw new YuzuhaError('NATIVE_UNAVAILABLE', 'O recurso de servidor não implementa leaveGuild.');
|
|
153
165
|
await this.resources.users.leaveGuild(guildID);
|
|
154
166
|
}
|
|
167
|
+
get cdn() { return this.cdnService; }
|
|
168
|
+
|
|
155
169
|
get mod(): NativeModeration {
|
|
156
170
|
return this.nativeMod ??= new NativeModeration(
|
|
157
171
|
(action, target, reason, options) => this.moderate(action, target, reason, options),
|
|
@@ -167,7 +181,7 @@ export class CommandContext {
|
|
|
167
181
|
}
|
|
168
182
|
|
|
169
183
|
get message(): IncomingMessage {
|
|
170
|
-
if (!this.messageAvailable) throw new GuardError('Este evento não fornece uma mensagem completa. Use os campos de evento e um canal explícito.');
|
|
184
|
+
if (!this.messageAvailable) throw new GuardError('Este evento não fornece uma mensagem completa. Use os campos de evento e um canal explícito.', 'GENERIC');
|
|
171
185
|
return this.sourceMessage;
|
|
172
186
|
}
|
|
173
187
|
get authorID(): string { return this.actor?.authorID ?? this.sourceMessage.authorID; }
|
|
@@ -185,7 +199,9 @@ export class CommandContext {
|
|
|
185
199
|
get resources(): Resources {
|
|
186
200
|
if (!this.nativeResources) throw new YuzuhaError('NATIVE_UNAVAILABLE', 'Os recursos nativos não foram fornecidos a este contexto.');
|
|
187
201
|
if (this.scopedResources) return this.scopedResources;
|
|
188
|
-
const source =
|
|
202
|
+
const source = this.disableResourceAuthorization ? this.nativeResources
|
|
203
|
+
: bindAuthorizedResources(this.nativeResources, this.transport, { guildID: this.guildID, authorID: this.authorID });
|
|
204
|
+
const collectors = source.collectors;
|
|
189
205
|
return this.scopedResources = { users: source.users, roles: source.roles, channels: source.channels,
|
|
190
206
|
messages: source.messages, webhooks: source.webhooks, expressions: source.expressions,
|
|
191
207
|
threads: source.threads, invites: source.invites, gateway: source.gateway,
|
|
@@ -225,15 +241,37 @@ export class CommandContext {
|
|
|
225
241
|
requireGuild(): string { return requireGuild(this.guildID); }
|
|
226
242
|
|
|
227
243
|
assert(condition: unknown, message: string): void {
|
|
228
|
-
if (!condition) throw new GuardError(message);
|
|
244
|
+
if (!condition) throw new GuardError(message, 'GENERIC');
|
|
229
245
|
}
|
|
230
246
|
|
|
231
|
-
reply(payload: string | Payload): Promise<string> {
|
|
232
|
-
|
|
247
|
+
reply(payload: string | Payload, options?: SendOptions): Promise<string> {
|
|
248
|
+
if (this.commandMessageDeleted) return this.send(payload, undefined, options);
|
|
249
|
+
validateTtl(options);
|
|
250
|
+
return this.sendVia(this.transport.reply(this.message, typeof payload === 'string' ? { content: payload } : payload),
|
|
251
|
+
this.message.channelID, options);
|
|
233
252
|
}
|
|
234
253
|
|
|
235
|
-
send(payload: string | Payload, channelID = this.message.channelID): Promise<string> {
|
|
236
|
-
|
|
254
|
+
send(payload: string | Payload, channelID = this.message.channelID, options?: SendOptions): Promise<string> {
|
|
255
|
+
validateTtl(options);
|
|
256
|
+
return this.sendVia(this.transport.send(channelID, typeof payload === 'string' ? { content: payload } : payload), channelID, options);
|
|
257
|
+
}
|
|
258
|
+
private commandMessageDeleted = false;
|
|
259
|
+
async deleteCommandMessage(): Promise<void> {
|
|
260
|
+
try { await this.transport.delete(this.message.channelID, this.message.id); }
|
|
261
|
+
catch (error) {
|
|
262
|
+
const candidate = error as { status?: number; code?: number | string } | null | undefined;
|
|
263
|
+
if (candidate?.status !== 404 && candidate?.code !== 10008 && candidate?.code !== 'NOT_FOUND') throw error;
|
|
264
|
+
}
|
|
265
|
+
this.commandMessageDeleted = true;
|
|
266
|
+
}
|
|
267
|
+
private async sendVia(pending: Promise<string>, channelID: string, options?: SendOptions): Promise<string> {
|
|
268
|
+
const ttlMs = options?.ttlMs;
|
|
269
|
+
const id = await pending;
|
|
270
|
+
if (ttlMs !== undefined) this.deleteLater(channelID, id, ttlMs);
|
|
271
|
+
return id;
|
|
272
|
+
}
|
|
273
|
+
private deleteLater(channelID: string, messageID: string, ttlMs: number): void {
|
|
274
|
+
this.deleteLaterFn?.(channelID, messageID, ttlMs);
|
|
237
275
|
}
|
|
238
276
|
|
|
239
277
|
sendStream(source: ReadableStream<Uint8Array>, options: StreamAttachmentOptions, channelID = this.message.channelID): Promise<string> {
|
|
@@ -260,7 +298,7 @@ export class CommandContext {
|
|
|
260
298
|
const key = JSON.stringify([this.guildID, this.message.channelID, this.authorID, this.command.name]);
|
|
261
299
|
const remaining = this.claimCooldown(key, parseDuration(duration));
|
|
262
300
|
if (remaining > 0) throw new GuardError((message ?? 'Aguarde {remaining} antes de usar novamente.')
|
|
263
|
-
.replaceAll('{remaining}', `${Math.ceil(remaining / 1000)}s`));
|
|
301
|
+
.replaceAll('{remaining}', `${Math.ceil(remaining / 1000)}s`), 'COOLDOWN');
|
|
264
302
|
}
|
|
265
303
|
|
|
266
304
|
async prepare(): Promise<void> {
|
|
@@ -275,14 +313,14 @@ export class CommandContext {
|
|
|
275
313
|
}
|
|
276
314
|
if (this.command.args?.length) for (const [name, value] of parseArguments(this.command.args, this.tokens)) this.args.set(name, value);
|
|
277
315
|
} catch (error) {
|
|
278
|
-
if (error instanceof GuardError) throw new GuardError(`${error.message}\nUso: ${commandUsage(this.command, this.prefix)}
|
|
316
|
+
if (error instanceof GuardError) throw new GuardError(`${error.message}\nUso: ${commandUsage(this.command, this.prefix)}`, error.reason);
|
|
279
317
|
throw error;
|
|
280
318
|
}
|
|
281
319
|
for (const command of this.lineage) {
|
|
282
320
|
if (command.cooldown === undefined) continue;
|
|
283
321
|
const key = JSON.stringify([this.guildID, this.message.channelID, this.authorID, command.name]);
|
|
284
322
|
const remaining = this.claimCooldown(key, parseDuration(command.cooldown));
|
|
285
|
-
if (remaining > 0) throw new GuardError(`Aguarde ${Math.ceil(remaining / 1000)}s antes de usar novamente
|
|
323
|
+
if (remaining > 0) throw new GuardError(`Aguarde ${Math.ceil(remaining / 1000)}s antes de usar novamente.`, 'COOLDOWN');
|
|
286
324
|
}
|
|
287
325
|
}
|
|
288
326
|
|
|
@@ -312,3 +350,10 @@ export class CommandContext {
|
|
|
312
350
|
return this.variables.delete(scope, name);
|
|
313
351
|
}
|
|
314
352
|
}
|
|
353
|
+
|
|
354
|
+
function validateTtl(options?: SendOptions): void {
|
|
355
|
+
const ttlMs = options?.ttlMs;
|
|
356
|
+
if (ttlMs !== undefined && (!Number.isInteger(ttlMs) || ttlMs < 1_000 || ttlMs > 86_400_000)) {
|
|
357
|
+
throw new GuardError('ttlMs deve ser um inteiro entre 1000 e 86400000.', 'INVALID_ARGUMENT');
|
|
358
|
+
}
|
|
359
|
+
}
|
|
@@ -10,6 +10,7 @@ export interface ArgumentDefinition {
|
|
|
10
10
|
type?: 'string' | 'number' | 'integer' | 'user' | 'duration' | 'boolean';
|
|
11
11
|
required?: boolean;
|
|
12
12
|
rest?: boolean;
|
|
13
|
+
anywhere?: boolean;
|
|
13
14
|
choices?: readonly ArgumentValue[];
|
|
14
15
|
defaultValue?: ArgumentValue;
|
|
15
16
|
min?: number;
|