@wolfstar/decorators 0.1.0
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/LICENSE +201 -0
- package/README.md +190 -0
- package/dist/esm/index.d.ts +253 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +346 -0
- package/dist/esm/index.js.map +1 -0
- package/package.json +68 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2022 Wolfstar Project
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<img src="https://cdn.wolfstar.rocks/assets/stars-components/wordmark.webp" alt="Stars Components" width="440" />
|
|
4
|
+
</picture>
|
|
5
|
+
|
|
6
|
+
# @wolfstar/decorators
|
|
7
|
+
|
|
8
|
+
**Useful TypeScript decorators for `@wolfstar/http-framework`, in the spirit of `@sapphire/decorators`.**
|
|
9
|
+
|
|
10
|
+
[](https://npmx.dev/package/@wolfstar/decorators)
|
|
11
|
+
[](https://npmx.dev/package/@wolfstar/decorators)
|
|
12
|
+
[](https://github.com/wolfstar-project/stars-components/blob/main/LICENSE)
|
|
13
|
+
|
|
14
|
+
</div>
|
|
15
|
+
|
|
16
|
+
## Description
|
|
17
|
+
|
|
18
|
+
A set of decorators for configuring [`@wolfstar/http-framework`] pieces and gating their methods, modelled after
|
|
19
|
+
[`@sapphire/decorators`]. They used to ship with the framework itself; the framework now only keeps the `Register*`
|
|
20
|
+
decorators that are part of command registration.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pnpm add @wolfstar/decorators @wolfstar/http-framework
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`@wolfstar/http-framework` is a peer dependency. The decorators use the legacy (`experimentalDecorators`) decorator
|
|
29
|
+
semantics, like the `Register*` decorators of the framework.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
### `ApplyOptions`
|
|
34
|
+
|
|
35
|
+
Sets the options of any `Piece` — `Command`, `Listener`, or `InteractionHandler` — without writing a constructor. The
|
|
36
|
+
decorator's values are merged on top of the options the piece is constructed with, so they win on conflicting keys.
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
import { ApplyOptions } from '@wolfstar/decorators';
|
|
40
|
+
import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
41
|
+
|
|
42
|
+
@ApplyOptions<Command.Options>({ name: 'ping', enabled: true })
|
|
43
|
+
@RegisterCommand({ name: 'ping', description: 'A simple ping pong command' })
|
|
44
|
+
export class UserCommand extends Command {
|
|
45
|
+
public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
46
|
+
return interaction.reply({ content: 'Pong!' });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
It also accepts a function, which receives the loader context:
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
@ApplyOptions<Command.Options>(({ name }) => ({ name: name.toLowerCase() }))
|
|
55
|
+
export class UserCommand extends Command {}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
> **Note**: `ApplyOptions` returns a `Proxy` wrapping the class, so it must be applied above (outside of) any other class
|
|
59
|
+
> decorator that keys metadata by class identity, such as `RegisterCommand` — as in the example above. A decorator
|
|
60
|
+
> applied above `ApplyOptions` would run after it and register against the proxy, but instances constructed from the
|
|
61
|
+
> exported class still resolve `.constructor` to the original, unproxied class, so that metadata could never be found.
|
|
62
|
+
> The `wolfstar/apply-options-decorator-order` rule of `@wolfstar/eslint-plugin-http-framework` enforces this.
|
|
63
|
+
|
|
64
|
+
### `RequiresGuildContext` / `RequiresDMContext`
|
|
65
|
+
|
|
66
|
+
Restrict a method to interactions received from a guild, or to interactions received outside of one (DMs and
|
|
67
|
+
user-installed app contexts). Both take an optional fallback that receives the same arguments as the decorated method;
|
|
68
|
+
without one, the method is silently skipped and resolves to `undefined`.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
import { RequiresGuildContext } from '@wolfstar/decorators';
|
|
72
|
+
import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
73
|
+
|
|
74
|
+
@RegisterCommand({ name: 'kick', description: 'Kicks a member' })
|
|
75
|
+
export class UserCommand extends Command {
|
|
76
|
+
@RequiresGuildContext((interaction: Command.ChatInputInteraction) => interaction.reply({ content: 'This command can only be used in a server.' }))
|
|
77
|
+
public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
78
|
+
return interaction.reply({ content: `Hello from ${interaction.guildId}!` });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### `RequiresUserPermissions` / `RequiresClientPermissions`
|
|
84
|
+
|
|
85
|
+
Check the permissions of the invoking user (`member.permissions`) or of the application (`app_permissions`) in the
|
|
86
|
+
channel the interaction was sent from. Permissions are given as `PermissionFlagsBits` values, as flag names, or as any
|
|
87
|
+
nested array of both.
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
import { RequiresClientPermissions, RequiresUserPermissions } from '@wolfstar/decorators';
|
|
91
|
+
import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
92
|
+
import { PermissionFlagsBits } from 'discord-api-types/v10';
|
|
93
|
+
|
|
94
|
+
@RegisterCommand({ name: 'purge', description: 'Deletes messages' })
|
|
95
|
+
export class UserCommand extends Command {
|
|
96
|
+
@RequiresUserPermissions('ManageMessages')
|
|
97
|
+
@RequiresClientPermissions(PermissionFlagsBits.ManageMessages, 'ReadMessageHistory')
|
|
98
|
+
public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
99
|
+
return interaction.reply({ content: 'Purging!' });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
When the check fails, a `PreconditionError` is thrown, identified by `Identifiers.PreconditionUserPermissions` or
|
|
105
|
+
`Identifiers.PreconditionClientPermissions`, with `context: { missing, missingNames }` describing the missing
|
|
106
|
+
permissions. Errors thrown from a command are emitted as `commandError` (and as `interactionHandlerError` for
|
|
107
|
+
interaction handlers), which is the idiomatic place to turn them into a user-facing reply:
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
import { ApplyOptions } from '@wolfstar/decorators';
|
|
111
|
+
import { Identifiers, Listener, PreconditionError, type ClientEventCommandContext } from '@wolfstar/http-framework';
|
|
112
|
+
|
|
113
|
+
@ApplyOptions<Listener.Options>({ emitter: 'client', event: 'commandError' })
|
|
114
|
+
export class UserListener extends Listener {
|
|
115
|
+
public run(error: unknown, context: ClientEventCommandContext) {
|
|
116
|
+
if (
|
|
117
|
+
error instanceof PreconditionError &&
|
|
118
|
+
(error.identifier === Identifiers.PreconditionUserPermissions || error.identifier === Identifiers.PreconditionClientPermissions)
|
|
119
|
+
) {
|
|
120
|
+
const { missingNames } = error.context as { missingNames: string[] };
|
|
121
|
+
this.container.logger.warn(`${context.command.name}: missing ${error.precondition}: ${missingNames.join(', ')}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Notes on the semantics:
|
|
128
|
+
|
|
129
|
+
- Members with `Administrator` implicitly satisfy every check.
|
|
130
|
+
- `RequiresUserPermissions` passes for interactions received outside of a guild, since there are no guild permissions to
|
|
131
|
+
check. Combine it with `RequiresGuildContext` when the method must be guild-only.
|
|
132
|
+
- `RequiresClientPermissions` passes when `app_permissions` is absent from the payload, since there is nothing to check
|
|
133
|
+
against.
|
|
134
|
+
|
|
135
|
+
### `Enumerable` / `EnumerableMethod`
|
|
136
|
+
|
|
137
|
+
Control whether a field or a method shows up in `Object.keys`, `JSON.stringify`, and console output.
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import { Enumerable } from '@wolfstar/decorators';
|
|
141
|
+
import { Command } from '@wolfstar/http-framework';
|
|
142
|
+
|
|
143
|
+
export class UserCommand extends Command {
|
|
144
|
+
@Enumerable(false)
|
|
145
|
+
declare public cache: Map<string, string>;
|
|
146
|
+
|
|
147
|
+
public constructor(context: Command.LoaderContext, options: Command.Options) {
|
|
148
|
+
super(context, options);
|
|
149
|
+
this.cache = new Map();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
> **Note**: `Enumerable` installs a setter on the prototype, which is bypassed by the `Object.defineProperty` call that
|
|
155
|
+
> `useDefineForClassFields` (enabled by `@sapphire/ts-config`, and the default from `ES2022` onwards) emits for class
|
|
156
|
+
> fields. Mark the field as `declare` so no field definition is emitted, and assign it in the constructor.
|
|
157
|
+
|
|
158
|
+
### Building your own decorators
|
|
159
|
+
|
|
160
|
+
`createClassDecorator`, `createMethodDecorator`, `createProxy`, and `createFunctionPrecondition` are the primitives the
|
|
161
|
+
decorators above are built on, and are exported so you can build your own.
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
import { createFunctionPrecondition } from '@wolfstar/decorators';
|
|
165
|
+
import type { Command } from '@wolfstar/http-framework';
|
|
166
|
+
|
|
167
|
+
export const RequiresOwner = createFunctionPrecondition(
|
|
168
|
+
(interaction: Command.ChatInputInteraction) => interaction.user.id === process.env.OWNER_ID,
|
|
169
|
+
(interaction: Command.ChatInputInteraction) => interaction.reply({ content: 'Owner only.' })
|
|
170
|
+
);
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
> **Note**: `createFunctionPrecondition` replaces the decorated method with an `async` one, so a decorated method always
|
|
174
|
+
> returns a `Promise`, even when both the precondition and the method are synchronous.
|
|
175
|
+
|
|
176
|
+
## Migrating from `@wolfstar/http-framework` 5.x
|
|
177
|
+
|
|
178
|
+
Install `@wolfstar/decorators` and move the imports of the utility decorators over; nothing else changes:
|
|
179
|
+
|
|
180
|
+
```diff
|
|
181
|
+
-import { ApplyOptions, Command, RegisterCommand, RequiresGuildContext } from '@wolfstar/http-framework';
|
|
182
|
+
+import { ApplyOptions, RequiresGuildContext } from '@wolfstar/decorators';
|
|
183
|
+
+import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Projects using the `stars` CLI's auto imports pick them up without an explicit import, since `@wolfstar/decorators` is
|
|
187
|
+
one of the default `imports.presets`.
|
|
188
|
+
|
|
189
|
+
[`@wolfstar/http-framework`]: https://npmx.dev/package/@wolfstar/http-framework
|
|
190
|
+
[`@sapphire/decorators`]: https://www.npmjs.com/package/@sapphire/decorators
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { LoaderPieceContext, PermissionResolvable, PieceOptions } from "@wolfstar/http-framework";
|
|
2
|
+
//#region src/ApplyOptions.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The constructor signature shared by every `Piece` of `@wolfstar/http-framework`, such as `Command`, `Listener`, and
|
|
5
|
+
* `InteractionHandler`.
|
|
6
|
+
*/
|
|
7
|
+
export type PieceConstructor<Options extends PieceOptions = PieceOptions> = new (context: LoaderPieceContext, options?: Options) => unknown;
|
|
8
|
+
/**
|
|
9
|
+
* Decorator that sets the options of a `Piece`, such as a `Command`, a `Listener`, or an `InteractionHandler`.
|
|
10
|
+
*
|
|
11
|
+
* @remarks The options are merged on top of the ones the piece was constructed with, so a piece that also passes
|
|
12
|
+
* options through `super(context, options)` will have the decorator's values win on conflicting keys.
|
|
13
|
+
* @remarks Apply this decorator above (outside of) any other class decorator that keys metadata by class identity,
|
|
14
|
+
* such as `RegisterCommand` from `@wolfstar/http-framework` — as in the example below. This decorator returns a `Proxy` wrapping the class,
|
|
15
|
+
* so a decorator applied above it (running after it, and therefore registering against the proxy) would register
|
|
16
|
+
* metadata that instances constructed from the exported class — whose `.constructor` still resolves to the original,
|
|
17
|
+
* unproxied class — can never be looked up by.
|
|
18
|
+
* @param optionsOrFn The options to pass to the piece's constructor, or a function that builds them from the loader
|
|
19
|
+
* context.
|
|
20
|
+
* @returns A class decorator.
|
|
21
|
+
* @example
|
|
22
|
+
* ```typescript
|
|
23
|
+
* import { ApplyOptions } from '@wolfstar/decorators';
|
|
24
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
25
|
+
*
|
|
26
|
+
* (at)ApplyOptions<Command.Options>({ name: 'ping', enabled: true })
|
|
27
|
+
* (at)RegisterCommand({ name: 'ping', description: 'A simple ping pong command' })
|
|
28
|
+
* export class UserCommand extends Command {
|
|
29
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
30
|
+
* return interaction.reply({ content: 'Pong!' });
|
|
31
|
+
* }
|
|
32
|
+
* }
|
|
33
|
+
* ```
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* (at)ApplyOptions<Command.Options>(({ name }) => ({ name: name.toLowerCase() }))
|
|
37
|
+
* export class UserCommand extends Command {}
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare function ApplyOptions<Options extends PieceOptions = PieceOptions>(optionsOrFn: Options | ((context: LoaderPieceContext) => Options)): ClassDecorator;
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/Enumerable.d.ts
|
|
43
|
+
/**
|
|
44
|
+
* Decorator that sets the `enumerable` property of a class field to the given value.
|
|
45
|
+
*
|
|
46
|
+
* @remarks The decorator installs a setter on the prototype, which is bypassed by the `Object.defineProperty` call
|
|
47
|
+
* that `useDefineForClassFields` (enabled by `@sapphire/ts-config`, and the default from `ES2022` onwards) emits for
|
|
48
|
+
* class fields. Mark the field as `declare` so no field definition is emitted, and assign it in the constructor.
|
|
49
|
+
* @param value Whether the property should be enumerable or not.
|
|
50
|
+
* @returns A property decorator.
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* import { Enumerable } from '@wolfstar/decorators';
|
|
54
|
+
* import { Command } from '@wolfstar/http-framework';
|
|
55
|
+
*
|
|
56
|
+
* export class UserCommand extends Command {
|
|
57
|
+
* (at)Enumerable(false)
|
|
58
|
+
* declare public cache: Map<string, string>;
|
|
59
|
+
*
|
|
60
|
+
* public constructor(context: Command.LoaderContext, options: Command.Options) {
|
|
61
|
+
* super(context, options);
|
|
62
|
+
* this.cache = new Map();
|
|
63
|
+
* }
|
|
64
|
+
* }
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export declare function Enumerable(value: boolean): (target: unknown, key: string) => void;
|
|
68
|
+
/**
|
|
69
|
+
* Decorator that sets the `enumerable` property of a class method to the given value.
|
|
70
|
+
*
|
|
71
|
+
* @param value Whether the method should be enumerable or not.
|
|
72
|
+
* @returns A method decorator.
|
|
73
|
+
* @example
|
|
74
|
+
* ```typescript
|
|
75
|
+
* import { EnumerableMethod } from '@wolfstar/decorators';
|
|
76
|
+
* import { Command } from '@wolfstar/http-framework';
|
|
77
|
+
*
|
|
78
|
+
* export class UserCommand extends Command {
|
|
79
|
+
* (at)EnumerableMethod(true)
|
|
80
|
+
* public getCacheKey(id: string) {
|
|
81
|
+
* return `user:${id}`;
|
|
82
|
+
* }
|
|
83
|
+
* }
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export declare function EnumerableMethod(value: boolean): (_target: unknown, _key: string, descriptor: PropertyDescriptor) => void;
|
|
87
|
+
//#endregion
|
|
88
|
+
//#region src/RequiresContext.d.ts
|
|
89
|
+
/**
|
|
90
|
+
* The fallback invoked when a context precondition is not met. It receives the same arguments as the decorated method.
|
|
91
|
+
*/
|
|
92
|
+
export type ContextFallback = (...args: any[]) => unknown;
|
|
93
|
+
/**
|
|
94
|
+
* Decorator that only runs the decorated method when the interaction was received from a guild.
|
|
95
|
+
*
|
|
96
|
+
* @param fallback The fallback to run when the interaction did not come from a guild. Defaults to a no-op, which
|
|
97
|
+
* silently skips the method.
|
|
98
|
+
* @returns A method decorator.
|
|
99
|
+
* @example
|
|
100
|
+
* ```typescript
|
|
101
|
+
* import { RequiresGuildContext } from '@wolfstar/decorators';
|
|
102
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
103
|
+
*
|
|
104
|
+
* (at)RegisterCommand({ name: 'kick', description: 'Kicks a member' })
|
|
105
|
+
* export class UserCommand extends Command {
|
|
106
|
+
* (at)RequiresGuildContext((interaction: Command.ChatInputInteraction) =>
|
|
107
|
+
* interaction.reply({ content: 'This command can only be used in a server.' })
|
|
108
|
+
* )
|
|
109
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
110
|
+
* return interaction.reply({ content: `Hello from ${interaction.guildId}!` });
|
|
111
|
+
* }
|
|
112
|
+
* }
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
export declare function RequiresGuildContext(fallback?: ContextFallback): MethodDecorator;
|
|
116
|
+
/**
|
|
117
|
+
* Decorator that only runs the decorated method when the interaction was **not** received from a guild, that is, from a
|
|
118
|
+
* DM or from a user-installed app context.
|
|
119
|
+
*
|
|
120
|
+
* @param fallback The fallback to run when the interaction came from a guild. Defaults to a no-op, which silently skips
|
|
121
|
+
* the method.
|
|
122
|
+
* @returns A method decorator.
|
|
123
|
+
* @example
|
|
124
|
+
* ```typescript
|
|
125
|
+
* import { RequiresDMContext } from '@wolfstar/decorators';
|
|
126
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
127
|
+
*
|
|
128
|
+
* (at)RegisterCommand({ name: 'private', description: 'Only usable outside of servers' })
|
|
129
|
+
* export class UserCommand extends Command {
|
|
130
|
+
* (at)RequiresDMContext((interaction: Command.ChatInputInteraction) =>
|
|
131
|
+
* interaction.reply({ content: 'This command cannot be used in a server.' })
|
|
132
|
+
* )
|
|
133
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
134
|
+
* return interaction.reply({ content: 'Hello!' });
|
|
135
|
+
* }
|
|
136
|
+
* }
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
export declare function RequiresDMContext(fallback?: ContextFallback): MethodDecorator;
|
|
140
|
+
//#endregion
|
|
141
|
+
//#region src/RequiresPermissions.d.ts
|
|
142
|
+
/**
|
|
143
|
+
* Decorator that only runs the decorated method when the application has all of the given permissions in the channel
|
|
144
|
+
* the interaction was sent from, as reported by the interaction's `app_permissions` field.
|
|
145
|
+
*
|
|
146
|
+
* @remarks When the fallback is omitted, a {@linkcode PreconditionError} identified by
|
|
147
|
+
* {@linkcode Identifiers.PreconditionClientPermissions} is thrown, which the client emits as `commandError` (or
|
|
148
|
+
* `interactionHandlerError`) for a `Listener` to turn into a user-facing reply.
|
|
149
|
+
* @param permissions The permissions the application must have.
|
|
150
|
+
* @returns A method decorator.
|
|
151
|
+
* @example
|
|
152
|
+
* ```typescript
|
|
153
|
+
* import { RequiresClientPermissions } from '@wolfstar/decorators';
|
|
154
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
155
|
+
*
|
|
156
|
+
* (at)RegisterCommand({ name: 'purge', description: 'Deletes messages' })
|
|
157
|
+
* export class UserCommand extends Command {
|
|
158
|
+
* (at)RequiresClientPermissions('ManageMessages')
|
|
159
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
160
|
+
* return interaction.reply({ content: 'Purging!' });
|
|
161
|
+
* }
|
|
162
|
+
* }
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
export declare function RequiresClientPermissions(...permissions: PermissionResolvable[]): MethodDecorator;
|
|
166
|
+
/**
|
|
167
|
+
* Decorator that only runs the decorated method when the invoking user has all of the given permissions in the channel
|
|
168
|
+
* the interaction was sent from.
|
|
169
|
+
*
|
|
170
|
+
* @remarks Interactions received outside of a guild carry no member permissions, so the check passes for them. Pair
|
|
171
|
+
* this decorator with {@linkcode RequiresGuildContext} when the method must also be guild-only.
|
|
172
|
+
* @remarks When the fallback is omitted, a {@linkcode PreconditionError} identified by
|
|
173
|
+
* {@linkcode Identifiers.PreconditionUserPermissions} is thrown, which the client emits as `commandError` (or
|
|
174
|
+
* `interactionHandlerError`) for a `Listener` to turn into a user-facing reply.
|
|
175
|
+
* @param permissions The permissions the invoking user must have.
|
|
176
|
+
* @returns A method decorator.
|
|
177
|
+
* @example
|
|
178
|
+
* ```typescript
|
|
179
|
+
* import { RequiresUserPermissions } from '@wolfstar/decorators';
|
|
180
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
181
|
+
*
|
|
182
|
+
* (at)RegisterCommand({ name: 'ban', description: 'Bans a member' })
|
|
183
|
+
* export class UserCommand extends Command {
|
|
184
|
+
* (at)RequiresUserPermissions('BanMembers')
|
|
185
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
186
|
+
* return interaction.reply({ content: 'Banned!' });
|
|
187
|
+
* }
|
|
188
|
+
* }
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
export declare function RequiresUserPermissions(...permissions: PermissionResolvable[]): MethodDecorator;
|
|
192
|
+
//#endregion
|
|
193
|
+
//#region src/utils.d.ts
|
|
194
|
+
/**
|
|
195
|
+
* Utility to make a method decorator from a function.
|
|
196
|
+
*
|
|
197
|
+
* @remarks The decorator is returned with the signature it was given, rather than widened to `MethodDecorator`, so a
|
|
198
|
+
* decorator built on top of this keeps whatever constraint it declares on its target.
|
|
199
|
+
* @param fn The method to decorate.
|
|
200
|
+
* @returns The decorator.
|
|
201
|
+
* @example
|
|
202
|
+
* ```typescript
|
|
203
|
+
* // Enumerable function that will not append the property to the prototype:
|
|
204
|
+
* function enumerableMethod(value: boolean) {
|
|
205
|
+
* return createMethodDecorator((_target: unknown, _propertyKey: string, descriptor: PropertyDescriptor) => {
|
|
206
|
+
* descriptor.enumerable = value;
|
|
207
|
+
* });
|
|
208
|
+
* }
|
|
209
|
+
* ```
|
|
210
|
+
*/
|
|
211
|
+
export declare function createMethodDecorator<TFunction extends (...args: any[]) => unknown>(fn: TFunction): TFunction;
|
|
212
|
+
/**
|
|
213
|
+
* Utility to make a class decorator from a function.
|
|
214
|
+
*
|
|
215
|
+
* @remarks The decorator is returned with the signature it was given, rather than widened to `ClassDecorator`, so a
|
|
216
|
+
* decorator built on top of this keeps whatever constraint it declares on its target, such as only accepting a
|
|
217
|
+
* `Command` subclass.
|
|
218
|
+
* @param fn The class to decorate.
|
|
219
|
+
* @returns The decorator.
|
|
220
|
+
* @see {@linkcode ApplyOptions}
|
|
221
|
+
*/
|
|
222
|
+
export declare function createClassDecorator<TFunction extends (...args: any[]) => unknown>(fn: TFunction): TFunction;
|
|
223
|
+
/**
|
|
224
|
+
* Creates a new proxy to efficiently add properties to a class without creating subclasses.
|
|
225
|
+
*
|
|
226
|
+
* @param target The constructor of the class to modify.
|
|
227
|
+
* @param handler The handler function to modify the constructor behavior for the target.
|
|
228
|
+
* @returns The proxy.
|
|
229
|
+
*/
|
|
230
|
+
export declare function createProxy<T extends object>(target: T, handler: Omit<ProxyHandler<T>, 'get'>): T;
|
|
231
|
+
/**
|
|
232
|
+
* Utility to make a method decorator with lighter syntax and inferred types.
|
|
233
|
+
*
|
|
234
|
+
* @remarks The decorated method is replaced by an `async` one, so it always returns a `Promise`, even when both the
|
|
235
|
+
* precondition and the original method are synchronous.
|
|
236
|
+
* @param precondition The predicate to run before the decorated method. It receives the same arguments as the method
|
|
237
|
+
* and is called with the same `this`.
|
|
238
|
+
* @param fallback The fallback to run when the precondition is not met. Defaults to a no-op returning `undefined`.
|
|
239
|
+
* @returns The decorator.
|
|
240
|
+
* @example
|
|
241
|
+
* ```typescript
|
|
242
|
+
* import { createFunctionPrecondition } from '@wolfstar/decorators';
|
|
243
|
+
* import type { Command } from '@wolfstar/http-framework';
|
|
244
|
+
*
|
|
245
|
+
* const RequiresOwner = createFunctionPrecondition(
|
|
246
|
+
* (interaction: Command.ChatInputInteraction) => interaction.user.id === process.env.OWNER_ID,
|
|
247
|
+
* (interaction: Command.ChatInputInteraction) => interaction.reply({ content: 'Owner only.' })
|
|
248
|
+
* );
|
|
249
|
+
* ```
|
|
250
|
+
*/
|
|
251
|
+
export declare function createFunctionPrecondition(precondition: (...args: any[]) => boolean | Promise<boolean>, fallback?: (...args: any[]) => unknown): MethodDecorator;
|
|
252
|
+
//#endregion
|
|
253
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/ApplyOptions.ts","../../src/Enumerable.ts","../../src/RequiresContext.ts","../../src/RequiresPermissions.ts","../../src/utils.ts"],"mappings":";;;;;;YAOY,iBAAiB,gBAAgB,eAAe,qBAAqB,SAAS,oBAAoB,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkCxG,aAAa,gBAAgB,eAAe,cAC3D,aAAa,YAAY,SAAS,uBAAuB,WACvD;;;;;;;;;;;;;;;;;;;;;;;;;;;wBCnBa,WAAW,kBAAc,iBACjB;;;;;;;;;;;;;;;;;;;wBAiCR,iBAAiB,kBAAc,kBACtB,cAAc,YAAc;;;;;;YCrDzC,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;wBAwBlB,qBAAqB,WAAU,kBAAoC;;;;;;;;;;;;;;;;;;;;;;;;wBA2BnE,kBAAkB,WAAU,kBAAoC;;;;;;;;;;;;;;;;;;;;;;;;;;wBCXhE,6BAA6B,aAAa,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;wBA+CnE,2BAA2B,aAAa,yBAAyB;;;;;;;;;;;;;;;;;;;;wBC5EjE,sBAAsB,sBAAsB,yBAAyB,IAAI,YAAY;;;;;;;;;;;wBAcrF,qBAAqB,sBAAsB,yBAAyB,IAAI,YAAY;;;;;;;;wBAWpF,YAAY,kBAAkB,QAAQ,GAAG,SAAS,KAAK,aAAa,aAAa;;;;;;;;;;;;;;;;;;;;;wBA8BjF,2BACf,kBAAkB,0BAA0B,kBAC5C,eAAc,0BACZ"}
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import { Identifiers, PreconditionError, getMissingPermissions, resolvePermissions, toPermissionNames } from "@wolfstar/http-framework";
|
|
2
|
+
|
|
3
|
+
//#region src/utils.ts
|
|
4
|
+
/**
|
|
5
|
+
* Utility to make a method decorator from a function.
|
|
6
|
+
*
|
|
7
|
+
* @remarks The decorator is returned with the signature it was given, rather than widened to `MethodDecorator`, so a
|
|
8
|
+
* decorator built on top of this keeps whatever constraint it declares on its target.
|
|
9
|
+
* @param fn The method to decorate.
|
|
10
|
+
* @returns The decorator.
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* // Enumerable function that will not append the property to the prototype:
|
|
14
|
+
* function enumerableMethod(value: boolean) {
|
|
15
|
+
* return createMethodDecorator((_target: unknown, _propertyKey: string, descriptor: PropertyDescriptor) => {
|
|
16
|
+
* descriptor.enumerable = value;
|
|
17
|
+
* });
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
function createMethodDecorator(fn) {
|
|
22
|
+
return fn;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Utility to make a class decorator from a function.
|
|
26
|
+
*
|
|
27
|
+
* @remarks The decorator is returned with the signature it was given, rather than widened to `ClassDecorator`, so a
|
|
28
|
+
* decorator built on top of this keeps whatever constraint it declares on its target, such as only accepting a
|
|
29
|
+
* `Command` subclass.
|
|
30
|
+
* @param fn The class to decorate.
|
|
31
|
+
* @returns The decorator.
|
|
32
|
+
* @see {@linkcode ApplyOptions}
|
|
33
|
+
*/
|
|
34
|
+
function createClassDecorator(fn) {
|
|
35
|
+
return fn;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Creates a new proxy to efficiently add properties to a class without creating subclasses.
|
|
39
|
+
*
|
|
40
|
+
* @param target The constructor of the class to modify.
|
|
41
|
+
* @param handler The handler function to modify the constructor behavior for the target.
|
|
42
|
+
* @returns The proxy.
|
|
43
|
+
*/
|
|
44
|
+
function createProxy(target, handler) {
|
|
45
|
+
return new Proxy(target, {
|
|
46
|
+
...handler,
|
|
47
|
+
get: (proxyTarget, property) => {
|
|
48
|
+
const value = Reflect.get(proxyTarget, property);
|
|
49
|
+
return typeof value === "function" ? (...args) => value.apply(proxyTarget, args) : value;
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Utility to make a method decorator with lighter syntax and inferred types.
|
|
55
|
+
*
|
|
56
|
+
* @remarks The decorated method is replaced by an `async` one, so it always returns a `Promise`, even when both the
|
|
57
|
+
* precondition and the original method are synchronous.
|
|
58
|
+
* @param precondition The predicate to run before the decorated method. It receives the same arguments as the method
|
|
59
|
+
* and is called with the same `this`.
|
|
60
|
+
* @param fallback The fallback to run when the precondition is not met. Defaults to a no-op returning `undefined`.
|
|
61
|
+
* @returns The decorator.
|
|
62
|
+
* @example
|
|
63
|
+
* ```typescript
|
|
64
|
+
* import { createFunctionPrecondition } from '@wolfstar/decorators';
|
|
65
|
+
* import type { Command } from '@wolfstar/http-framework';
|
|
66
|
+
*
|
|
67
|
+
* const RequiresOwner = createFunctionPrecondition(
|
|
68
|
+
* (interaction: Command.ChatInputInteraction) => interaction.user.id === process.env.OWNER_ID,
|
|
69
|
+
* (interaction: Command.ChatInputInteraction) => interaction.reply({ content: 'Owner only.' })
|
|
70
|
+
* );
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
function createFunctionPrecondition(precondition, fallback = () => void 0) {
|
|
74
|
+
return createMethodDecorator((_target, _propertyKey, descriptor) => {
|
|
75
|
+
const method = descriptor.value;
|
|
76
|
+
if (!method) throw new Error("Function preconditions require a [[value]].");
|
|
77
|
+
if (typeof method !== "function") throw new Error("Function preconditions can only be applied to functions.");
|
|
78
|
+
descriptor.value = async function value(...args) {
|
|
79
|
+
return await precondition.apply(this, args) ? method.apply(this, args) : fallback.apply(this, args);
|
|
80
|
+
};
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/ApplyOptions.ts
|
|
86
|
+
/**
|
|
87
|
+
* Decorator that sets the options of a `Piece`, such as a `Command`, a `Listener`, or an `InteractionHandler`.
|
|
88
|
+
*
|
|
89
|
+
* @remarks The options are merged on top of the ones the piece was constructed with, so a piece that also passes
|
|
90
|
+
* options through `super(context, options)` will have the decorator's values win on conflicting keys.
|
|
91
|
+
* @remarks Apply this decorator above (outside of) any other class decorator that keys metadata by class identity,
|
|
92
|
+
* such as `RegisterCommand` from `@wolfstar/http-framework` — as in the example below. This decorator returns a `Proxy` wrapping the class,
|
|
93
|
+
* so a decorator applied above it (running after it, and therefore registering against the proxy) would register
|
|
94
|
+
* metadata that instances constructed from the exported class — whose `.constructor` still resolves to the original,
|
|
95
|
+
* unproxied class — can never be looked up by.
|
|
96
|
+
* @param optionsOrFn The options to pass to the piece's constructor, or a function that builds them from the loader
|
|
97
|
+
* context.
|
|
98
|
+
* @returns A class decorator.
|
|
99
|
+
* @example
|
|
100
|
+
* ```typescript
|
|
101
|
+
* import { ApplyOptions } from '@wolfstar/decorators';
|
|
102
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
103
|
+
*
|
|
104
|
+
* (at)ApplyOptions<Command.Options>({ name: 'ping', enabled: true })
|
|
105
|
+
* (at)RegisterCommand({ name: 'ping', description: 'A simple ping pong command' })
|
|
106
|
+
* export class UserCommand extends Command {
|
|
107
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
108
|
+
* return interaction.reply({ content: 'Pong!' });
|
|
109
|
+
* }
|
|
110
|
+
* }
|
|
111
|
+
* ```
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* (at)ApplyOptions<Command.Options>(({ name }) => ({ name: name.toLowerCase() }))
|
|
115
|
+
* export class UserCommand extends Command {}
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
function ApplyOptions(optionsOrFn) {
|
|
119
|
+
return createClassDecorator((target) => createProxy(target, { construct: (ctor, [context, baseOptions], newTarget) => Reflect.construct(ctor, [context, {
|
|
120
|
+
...baseOptions,
|
|
121
|
+
...typeof optionsOrFn === "function" ? optionsOrFn(context) : optionsOrFn
|
|
122
|
+
}], newTarget) }));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region src/Enumerable.ts
|
|
127
|
+
/**
|
|
128
|
+
* Decorator that sets the `enumerable` property of a class field to the given value.
|
|
129
|
+
*
|
|
130
|
+
* @remarks The decorator installs a setter on the prototype, which is bypassed by the `Object.defineProperty` call
|
|
131
|
+
* that `useDefineForClassFields` (enabled by `@sapphire/ts-config`, and the default from `ES2022` onwards) emits for
|
|
132
|
+
* class fields. Mark the field as `declare` so no field definition is emitted, and assign it in the constructor.
|
|
133
|
+
* @param value Whether the property should be enumerable or not.
|
|
134
|
+
* @returns A property decorator.
|
|
135
|
+
* @example
|
|
136
|
+
* ```typescript
|
|
137
|
+
* import { Enumerable } from '@wolfstar/decorators';
|
|
138
|
+
* import { Command } from '@wolfstar/http-framework';
|
|
139
|
+
*
|
|
140
|
+
* export class UserCommand extends Command {
|
|
141
|
+
* (at)Enumerable(false)
|
|
142
|
+
* declare public cache: Map<string, string>;
|
|
143
|
+
*
|
|
144
|
+
* public constructor(context: Command.LoaderContext, options: Command.Options) {
|
|
145
|
+
* super(context, options);
|
|
146
|
+
* this.cache = new Map();
|
|
147
|
+
* }
|
|
148
|
+
* }
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
function Enumerable(value) {
|
|
152
|
+
return (target, key) => {
|
|
153
|
+
Reflect.defineProperty(target, key, {
|
|
154
|
+
enumerable: value,
|
|
155
|
+
set(val) {
|
|
156
|
+
Reflect.defineProperty(this, key, {
|
|
157
|
+
configurable: true,
|
|
158
|
+
enumerable: value,
|
|
159
|
+
value: val,
|
|
160
|
+
writable: true
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Decorator that sets the `enumerable` property of a class method to the given value.
|
|
168
|
+
*
|
|
169
|
+
* @param value Whether the method should be enumerable or not.
|
|
170
|
+
* @returns A method decorator.
|
|
171
|
+
* @example
|
|
172
|
+
* ```typescript
|
|
173
|
+
* import { EnumerableMethod } from '@wolfstar/decorators';
|
|
174
|
+
* import { Command } from '@wolfstar/http-framework';
|
|
175
|
+
*
|
|
176
|
+
* export class UserCommand extends Command {
|
|
177
|
+
* (at)EnumerableMethod(true)
|
|
178
|
+
* public getCacheKey(id: string) {
|
|
179
|
+
* return `user:${id}`;
|
|
180
|
+
* }
|
|
181
|
+
* }
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
184
|
+
function EnumerableMethod(value) {
|
|
185
|
+
return (_target, _key, descriptor) => {
|
|
186
|
+
descriptor.enumerable = value;
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/RequiresContext.ts
|
|
192
|
+
/**
|
|
193
|
+
* Decorator that only runs the decorated method when the interaction was received from a guild.
|
|
194
|
+
*
|
|
195
|
+
* @param fallback The fallback to run when the interaction did not come from a guild. Defaults to a no-op, which
|
|
196
|
+
* silently skips the method.
|
|
197
|
+
* @returns A method decorator.
|
|
198
|
+
* @example
|
|
199
|
+
* ```typescript
|
|
200
|
+
* import { RequiresGuildContext } from '@wolfstar/decorators';
|
|
201
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
202
|
+
*
|
|
203
|
+
* (at)RegisterCommand({ name: 'kick', description: 'Kicks a member' })
|
|
204
|
+
* export class UserCommand extends Command {
|
|
205
|
+
* (at)RequiresGuildContext((interaction: Command.ChatInputInteraction) =>
|
|
206
|
+
* interaction.reply({ content: 'This command can only be used in a server.' })
|
|
207
|
+
* )
|
|
208
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
209
|
+
* return interaction.reply({ content: `Hello from ${interaction.guildId}!` });
|
|
210
|
+
* }
|
|
211
|
+
* }
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
function RequiresGuildContext(fallback = () => void 0) {
|
|
215
|
+
return createFunctionPrecondition((interaction) => interaction.inGuild(), fallback);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Decorator that only runs the decorated method when the interaction was **not** received from a guild, that is, from a
|
|
219
|
+
* DM or from a user-installed app context.
|
|
220
|
+
*
|
|
221
|
+
* @param fallback The fallback to run when the interaction came from a guild. Defaults to a no-op, which silently skips
|
|
222
|
+
* the method.
|
|
223
|
+
* @returns A method decorator.
|
|
224
|
+
* @example
|
|
225
|
+
* ```typescript
|
|
226
|
+
* import { RequiresDMContext } from '@wolfstar/decorators';
|
|
227
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
228
|
+
*
|
|
229
|
+
* (at)RegisterCommand({ name: 'private', description: 'Only usable outside of servers' })
|
|
230
|
+
* export class UserCommand extends Command {
|
|
231
|
+
* (at)RequiresDMContext((interaction: Command.ChatInputInteraction) =>
|
|
232
|
+
* interaction.reply({ content: 'This command cannot be used in a server.' })
|
|
233
|
+
* )
|
|
234
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
235
|
+
* return interaction.reply({ content: 'Hello!' });
|
|
236
|
+
* }
|
|
237
|
+
* }
|
|
238
|
+
* ```
|
|
239
|
+
*/
|
|
240
|
+
function RequiresDMContext(fallback = () => void 0) {
|
|
241
|
+
return createFunctionPrecondition((interaction) => !interaction.inGuild(), fallback);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
//#endregion
|
|
245
|
+
//#region src/RequiresPermissions.ts
|
|
246
|
+
/**
|
|
247
|
+
* Reads the permissions the invoking user has in the channel the interaction was sent from.
|
|
248
|
+
*
|
|
249
|
+
* @param interaction The interaction to read from.
|
|
250
|
+
* @returns The bitfield of the user's permissions, or `null` when the interaction did not come from a guild and there
|
|
251
|
+
* are therefore no guild permissions to check.
|
|
252
|
+
*/
|
|
253
|
+
function getUserPermissions(interaction) {
|
|
254
|
+
const permissions = interaction.member?.permissions;
|
|
255
|
+
return permissions === void 0 ? null : BigInt(permissions);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Decorator that only runs the decorated method when the application has all of the given permissions in the channel
|
|
259
|
+
* the interaction was sent from, as reported by the interaction's `app_permissions` field.
|
|
260
|
+
*
|
|
261
|
+
* @remarks When the fallback is omitted, a {@linkcode PreconditionError} identified by
|
|
262
|
+
* {@linkcode Identifiers.PreconditionClientPermissions} is thrown, which the client emits as `commandError` (or
|
|
263
|
+
* `interactionHandlerError`) for a `Listener` to turn into a user-facing reply.
|
|
264
|
+
* @param permissions The permissions the application must have.
|
|
265
|
+
* @returns A method decorator.
|
|
266
|
+
* @example
|
|
267
|
+
* ```typescript
|
|
268
|
+
* import { RequiresClientPermissions } from '@wolfstar/decorators';
|
|
269
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
270
|
+
*
|
|
271
|
+
* (at)RegisterCommand({ name: 'purge', description: 'Deletes messages' })
|
|
272
|
+
* export class UserCommand extends Command {
|
|
273
|
+
* (at)RequiresClientPermissions('ManageMessages')
|
|
274
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
275
|
+
* return interaction.reply({ content: 'Purging!' });
|
|
276
|
+
* }
|
|
277
|
+
* }
|
|
278
|
+
* ```
|
|
279
|
+
*/
|
|
280
|
+
function RequiresClientPermissions(...permissions) {
|
|
281
|
+
const required = resolvePermissions(permissions);
|
|
282
|
+
return createFunctionPrecondition((interaction) => {
|
|
283
|
+
const granted = interaction.applicationPermissions;
|
|
284
|
+
return granted === void 0 || getMissingPermissions(granted, required) === 0n;
|
|
285
|
+
}, (interaction) => {
|
|
286
|
+
const missing = getMissingPermissions(interaction.applicationPermissions ?? 0n, required);
|
|
287
|
+
const missingNames = toPermissionNames(missing);
|
|
288
|
+
throw new PreconditionError({
|
|
289
|
+
precondition: "ClientPermissions",
|
|
290
|
+
identifier: Identifiers.PreconditionClientPermissions,
|
|
291
|
+
message: `Sorry, but I am not allowed to do that. I am missing the permissions: ${missingNames.join(", ")}`,
|
|
292
|
+
context: {
|
|
293
|
+
missing,
|
|
294
|
+
missingNames
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Decorator that only runs the decorated method when the invoking user has all of the given permissions in the channel
|
|
301
|
+
* the interaction was sent from.
|
|
302
|
+
*
|
|
303
|
+
* @remarks Interactions received outside of a guild carry no member permissions, so the check passes for them. Pair
|
|
304
|
+
* this decorator with {@linkcode RequiresGuildContext} when the method must also be guild-only.
|
|
305
|
+
* @remarks When the fallback is omitted, a {@linkcode PreconditionError} identified by
|
|
306
|
+
* {@linkcode Identifiers.PreconditionUserPermissions} is thrown, which the client emits as `commandError` (or
|
|
307
|
+
* `interactionHandlerError`) for a `Listener` to turn into a user-facing reply.
|
|
308
|
+
* @param permissions The permissions the invoking user must have.
|
|
309
|
+
* @returns A method decorator.
|
|
310
|
+
* @example
|
|
311
|
+
* ```typescript
|
|
312
|
+
* import { RequiresUserPermissions } from '@wolfstar/decorators';
|
|
313
|
+
* import { Command, RegisterCommand } from '@wolfstar/http-framework';
|
|
314
|
+
*
|
|
315
|
+
* (at)RegisterCommand({ name: 'ban', description: 'Bans a member' })
|
|
316
|
+
* export class UserCommand extends Command {
|
|
317
|
+
* (at)RequiresUserPermissions('BanMembers')
|
|
318
|
+
* public override chatInputRun(interaction: Command.ChatInputInteraction) {
|
|
319
|
+
* return interaction.reply({ content: 'Banned!' });
|
|
320
|
+
* }
|
|
321
|
+
* }
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
function RequiresUserPermissions(...permissions) {
|
|
325
|
+
const required = resolvePermissions(permissions);
|
|
326
|
+
return createFunctionPrecondition((interaction) => {
|
|
327
|
+
const granted = getUserPermissions(interaction);
|
|
328
|
+
return granted === null || getMissingPermissions(granted, required) === 0n;
|
|
329
|
+
}, (interaction) => {
|
|
330
|
+
const missing = getMissingPermissions(getUserPermissions(interaction) ?? 0n, required);
|
|
331
|
+
const missingNames = toPermissionNames(missing);
|
|
332
|
+
throw new PreconditionError({
|
|
333
|
+
precondition: "UserPermissions",
|
|
334
|
+
identifier: Identifiers.PreconditionUserPermissions,
|
|
335
|
+
message: `Sorry, but you are not allowed to do that. You are missing the permissions: ${missingNames.join(", ")}`,
|
|
336
|
+
context: {
|
|
337
|
+
missing,
|
|
338
|
+
missingNames
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
//#endregion
|
|
345
|
+
export { ApplyOptions, Enumerable, EnumerableMethod, RequiresClientPermissions, RequiresDMContext, RequiresGuildContext, RequiresUserPermissions, createClassDecorator, createFunctionPrecondition, createMethodDecorator, createProxy };
|
|
346
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/utils.ts","../../src/ApplyOptions.ts","../../src/Enumerable.ts","../../src/RequiresContext.ts","../../src/RequiresPermissions.ts"],"sourcesContent":["/**\n * Utility to make a method decorator from a function.\n *\n * @remarks The decorator is returned with the signature it was given, rather than widened to `MethodDecorator`, so a\n * decorator built on top of this keeps whatever constraint it declares on its target.\n * @param fn The method to decorate.\n * @returns The decorator.\n * @example\n * ```typescript\n * // Enumerable function that will not append the property to the prototype:\n * function enumerableMethod(value: boolean) {\n * \treturn createMethodDecorator((_target: unknown, _propertyKey: string, descriptor: PropertyDescriptor) => {\n * \t\tdescriptor.enumerable = value;\n * \t});\n * }\n * ```\n */\nexport function createMethodDecorator<TFunction extends (...args: any[]) => unknown>(fn: TFunction): TFunction {\n\treturn fn;\n}\n\n/**\n * Utility to make a class decorator from a function.\n *\n * @remarks The decorator is returned with the signature it was given, rather than widened to `ClassDecorator`, so a\n * decorator built on top of this keeps whatever constraint it declares on its target, such as only accepting a\n * `Command` subclass.\n * @param fn The class to decorate.\n * @returns The decorator.\n * @see {@linkcode ApplyOptions}\n */\nexport function createClassDecorator<TFunction extends (...args: any[]) => unknown>(fn: TFunction): TFunction {\n\treturn fn;\n}\n\n/**\n * Creates a new proxy to efficiently add properties to a class without creating subclasses.\n *\n * @param target The constructor of the class to modify.\n * @param handler The handler function to modify the constructor behavior for the target.\n * @returns The proxy.\n */\nexport function createProxy<T extends object>(target: T, handler: Omit<ProxyHandler<T>, 'get'>): T {\n\treturn new Proxy(target, {\n\t\t...handler,\n\t\tget: (proxyTarget, property) => {\n\t\t\tconst value = Reflect.get(proxyTarget, property);\n\t\t\treturn typeof value === 'function' ? (...args: readonly unknown[]) => value.apply(proxyTarget, args) : value;\n\t\t}\n\t});\n}\n\n/**\n * Utility to make a method decorator with lighter syntax and inferred types.\n *\n * @remarks The decorated method is replaced by an `async` one, so it always returns a `Promise`, even when both the\n * precondition and the original method are synchronous.\n * @param precondition The predicate to run before the decorated method. It receives the same arguments as the method\n * and is called with the same `this`.\n * @param fallback The fallback to run when the precondition is not met. Defaults to a no-op returning `undefined`.\n * @returns The decorator.\n * @example\n * ```typescript\n * import { createFunctionPrecondition } from '@wolfstar/decorators';\n * import type { Command } from '@wolfstar/http-framework';\n *\n * const RequiresOwner = createFunctionPrecondition(\n * \t(interaction: Command.ChatInputInteraction) => interaction.user.id === process.env.OWNER_ID,\n * \t(interaction: Command.ChatInputInteraction) => interaction.reply({ content: 'Owner only.' })\n * );\n * ```\n */\nexport function createFunctionPrecondition(\n\tprecondition: (...args: any[]) => boolean | Promise<boolean>,\n\tfallback: (...args: any[]) => unknown = () => undefined\n): MethodDecorator {\n\treturn createMethodDecorator((_target: unknown, _propertyKey: string | symbol, descriptor: PropertyDescriptor) => {\n\t\tconst method = descriptor.value;\n\t\tif (!method) throw new Error('Function preconditions require a [[value]].');\n\t\tif (typeof method !== 'function') throw new Error('Function preconditions can only be applied to functions.');\n\n\t\tdescriptor.value = async function value(this: unknown, ...args: any[]) {\n\t\t\treturn (await precondition.apply(this, args)) ? method.apply(this, args) : fallback.apply(this, args);\n\t\t};\n\t}) as MethodDecorator;\n}\n","import type { LoaderPieceContext, PieceOptions } from '@wolfstar/http-framework';\nimport { createClassDecorator, createProxy } from './utils.js';\n\n/**\n * The constructor signature shared by every `Piece` of `@wolfstar/http-framework`, such as `Command`, `Listener`, and\n * `InteractionHandler`.\n */\nexport type PieceConstructor<Options extends PieceOptions = PieceOptions> = new (context: LoaderPieceContext, options?: Options) => unknown;\n\n/**\n * Decorator that sets the options of a `Piece`, such as a `Command`, a `Listener`, or an `InteractionHandler`.\n *\n * @remarks The options are merged on top of the ones the piece was constructed with, so a piece that also passes\n * options through `super(context, options)` will have the decorator's values win on conflicting keys.\n * @remarks Apply this decorator above (outside of) any other class decorator that keys metadata by class identity,\n * such as `RegisterCommand` from `@wolfstar/http-framework` — as in the example below. This decorator returns a `Proxy` wrapping the class,\n * so a decorator applied above it (running after it, and therefore registering against the proxy) would register\n * metadata that instances constructed from the exported class — whose `.constructor` still resolves to the original,\n * unproxied class — can never be looked up by.\n * @param optionsOrFn The options to pass to the piece's constructor, or a function that builds them from the loader\n * context.\n * @returns A class decorator.\n * @example\n * ```typescript\n * import { ApplyOptions } from '@wolfstar/decorators';\n * import { Command, RegisterCommand } from '@wolfstar/http-framework';\n *\n * (at)ApplyOptions<Command.Options>({ name: 'ping', enabled: true })\n * (at)RegisterCommand({ name: 'ping', description: 'A simple ping pong command' })\n * export class UserCommand extends Command {\n * \tpublic override chatInputRun(interaction: Command.ChatInputInteraction) {\n * \t\treturn interaction.reply({ content: 'Pong!' });\n * \t}\n * }\n * ```\n * @example\n * ```typescript\n * (at)ApplyOptions<Command.Options>(({ name }) => ({ name: name.toLowerCase() }))\n * export class UserCommand extends Command {}\n * ```\n */\nexport function ApplyOptions<Options extends PieceOptions = PieceOptions>(\n\toptionsOrFn: Options | ((context: LoaderPieceContext) => Options)\n): ClassDecorator {\n\treturn createClassDecorator((target: PieceConstructor<Options>) =>\n\t\tcreateProxy(target, {\n\t\t\tconstruct: (ctor, [context, baseOptions]: [LoaderPieceContext, Options | undefined], newTarget) =>\n\t\t\t\tReflect.construct(\n\t\t\t\t\tctor,\n\t\t\t\t\t[\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...baseOptions,\n\t\t\t\t\t\t\t...(typeof optionsOrFn === 'function' ? optionsOrFn(context) : optionsOrFn)\n\t\t\t\t\t\t}\n\t\t\t\t\t],\n\t\t\t\t\tnewTarget\n\t\t\t\t) as object\n\t\t})\n\t) as ClassDecorator;\n}\n","/**\n * Decorator that sets the `enumerable` property of a class field to the given value.\n *\n * @remarks The decorator installs a setter on the prototype, which is bypassed by the `Object.defineProperty` call\n * that `useDefineForClassFields` (enabled by `@sapphire/ts-config`, and the default from `ES2022` onwards) emits for\n * class fields. Mark the field as `declare` so no field definition is emitted, and assign it in the constructor.\n * @param value Whether the property should be enumerable or not.\n * @returns A property decorator.\n * @example\n * ```typescript\n * import { Enumerable } from '@wolfstar/decorators';\n * import { Command } from '@wolfstar/http-framework';\n *\n * export class UserCommand extends Command {\n * \t(at)Enumerable(false)\n * \tdeclare public cache: Map<string, string>;\n *\n * \tpublic constructor(context: Command.LoaderContext, options: Command.Options) {\n * \t\tsuper(context, options);\n * \t\tthis.cache = new Map();\n * \t}\n * }\n * ```\n */\nexport function Enumerable(value: boolean) {\n\treturn (target: unknown, key: string) => {\n\t\tReflect.defineProperty(target as object, key, {\n\t\t\tenumerable: value,\n\t\t\tset(this: unknown, val: unknown) {\n\t\t\t\tReflect.defineProperty(this as object, key, {\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\tenumerable: value,\n\t\t\t\t\tvalue: val,\n\t\t\t\t\twritable: true\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t};\n}\n\n/**\n * Decorator that sets the `enumerable` property of a class method to the given value.\n *\n * @param value Whether the method should be enumerable or not.\n * @returns A method decorator.\n * @example\n * ```typescript\n * import { EnumerableMethod } from '@wolfstar/decorators';\n * import { Command } from '@wolfstar/http-framework';\n *\n * export class UserCommand extends Command {\n * \t(at)EnumerableMethod(true)\n * \tpublic getCacheKey(id: string) {\n * \t\treturn `user:${id}`;\n * \t}\n * }\n * ```\n */\nexport function EnumerableMethod(value: boolean) {\n\treturn (_target: unknown, _key: string, descriptor: PropertyDescriptor) => {\n\t\tdescriptor.enumerable = value;\n\t};\n}\n","import type { BaseInteraction } from '@wolfstar/http-framework';\nimport { createFunctionPrecondition } from './utils.js';\n\n/**\n * The fallback invoked when a context precondition is not met. It receives the same arguments as the decorated method.\n */\nexport type ContextFallback = (...args: any[]) => unknown;\n\n/**\n * Decorator that only runs the decorated method when the interaction was received from a guild.\n *\n * @param fallback The fallback to run when the interaction did not come from a guild. Defaults to a no-op, which\n * silently skips the method.\n * @returns A method decorator.\n * @example\n * ```typescript\n * import { RequiresGuildContext } from '@wolfstar/decorators';\n * import { Command, RegisterCommand } from '@wolfstar/http-framework';\n *\n * (at)RegisterCommand({ name: 'kick', description: 'Kicks a member' })\n * export class UserCommand extends Command {\n * \t(at)RequiresGuildContext((interaction: Command.ChatInputInteraction) =>\n * \t\tinteraction.reply({ content: 'This command can only be used in a server.' })\n * \t)\n * \tpublic override chatInputRun(interaction: Command.ChatInputInteraction) {\n * \t\treturn interaction.reply({ content: `Hello from ${interaction.guildId}!` });\n * \t}\n * }\n * ```\n */\nexport function RequiresGuildContext(fallback: ContextFallback = () => undefined): MethodDecorator {\n\treturn createFunctionPrecondition((interaction: BaseInteraction) => interaction.inGuild(), fallback);\n}\n\n/**\n * Decorator that only runs the decorated method when the interaction was **not** received from a guild, that is, from a\n * DM or from a user-installed app context.\n *\n * @param fallback The fallback to run when the interaction came from a guild. Defaults to a no-op, which silently skips\n * the method.\n * @returns A method decorator.\n * @example\n * ```typescript\n * import { RequiresDMContext } from '@wolfstar/decorators';\n * import { Command, RegisterCommand } from '@wolfstar/http-framework';\n *\n * (at)RegisterCommand({ name: 'private', description: 'Only usable outside of servers' })\n * export class UserCommand extends Command {\n * \t(at)RequiresDMContext((interaction: Command.ChatInputInteraction) =>\n * \t\tinteraction.reply({ content: 'This command cannot be used in a server.' })\n * \t)\n * \tpublic override chatInputRun(interaction: Command.ChatInputInteraction) {\n * \t\treturn interaction.reply({ content: 'Hello!' });\n * \t}\n * }\n * ```\n */\nexport function RequiresDMContext(fallback: ContextFallback = () => undefined): MethodDecorator {\n\treturn createFunctionPrecondition((interaction: BaseInteraction) => !interaction.inGuild(), fallback);\n}\n","import {\n\tgetMissingPermissions,\n\tIdentifiers,\n\tPreconditionError,\n\tresolvePermissions,\n\ttoPermissionNames,\n\ttype BaseInteraction,\n\ttype PermissionResolvable\n} from '@wolfstar/http-framework';\nimport { createFunctionPrecondition } from './utils.js';\n\n/**\n * Reads the permissions the invoking user has in the channel the interaction was sent from.\n *\n * @param interaction The interaction to read from.\n * @returns The bitfield of the user's permissions, or `null` when the interaction did not come from a guild and there\n * are therefore no guild permissions to check.\n */\nfunction getUserPermissions(interaction: BaseInteraction): bigint | null {\n\tconst permissions = interaction.member?.permissions;\n\treturn permissions === undefined ? null : BigInt(permissions);\n}\n\n/**\n * Decorator that only runs the decorated method when the application has all of the given permissions in the channel\n * the interaction was sent from, as reported by the interaction's `app_permissions` field.\n *\n * @remarks When the fallback is omitted, a {@linkcode PreconditionError} identified by\n * {@linkcode Identifiers.PreconditionClientPermissions} is thrown, which the client emits as `commandError` (or\n * `interactionHandlerError`) for a `Listener` to turn into a user-facing reply.\n * @param permissions The permissions the application must have.\n * @returns A method decorator.\n * @example\n * ```typescript\n * import { RequiresClientPermissions } from '@wolfstar/decorators';\n * import { Command, RegisterCommand } from '@wolfstar/http-framework';\n *\n * (at)RegisterCommand({ name: 'purge', description: 'Deletes messages' })\n * export class UserCommand extends Command {\n * \t(at)RequiresClientPermissions('ManageMessages')\n * \tpublic override chatInputRun(interaction: Command.ChatInputInteraction) {\n * \t\treturn interaction.reply({ content: 'Purging!' });\n * \t}\n * }\n * ```\n */\nexport function RequiresClientPermissions(...permissions: PermissionResolvable[]): MethodDecorator {\n\tconst required = resolvePermissions(permissions);\n\treturn createFunctionPrecondition(\n\t\t(interaction: BaseInteraction) => {\n\t\t\tconst granted = interaction.applicationPermissions;\n\t\t\t// `app_permissions` is always sent by Discord, but the field is optional in the typings; when it is absent\n\t\t\t// there is nothing to check against, so the method is allowed to run.\n\t\t\treturn granted === undefined || getMissingPermissions(granted, required) === 0n;\n\t\t},\n\t\t(interaction: BaseInteraction) => {\n\t\t\tconst missing = getMissingPermissions(interaction.applicationPermissions ?? 0n, required);\n\t\t\tconst missingNames = toPermissionNames(missing);\n\t\t\tthrow new PreconditionError({\n\t\t\t\tprecondition: 'ClientPermissions',\n\t\t\t\tidentifier: Identifiers.PreconditionClientPermissions,\n\t\t\t\tmessage: `Sorry, but I am not allowed to do that. I am missing the permissions: ${missingNames.join(', ')}`,\n\t\t\t\tcontext: { missing, missingNames }\n\t\t\t});\n\t\t}\n\t);\n}\n\n/**\n * Decorator that only runs the decorated method when the invoking user has all of the given permissions in the channel\n * the interaction was sent from.\n *\n * @remarks Interactions received outside of a guild carry no member permissions, so the check passes for them. Pair\n * this decorator with {@linkcode RequiresGuildContext} when the method must also be guild-only.\n * @remarks When the fallback is omitted, a {@linkcode PreconditionError} identified by\n * {@linkcode Identifiers.PreconditionUserPermissions} is thrown, which the client emits as `commandError` (or\n * `interactionHandlerError`) for a `Listener` to turn into a user-facing reply.\n * @param permissions The permissions the invoking user must have.\n * @returns A method decorator.\n * @example\n * ```typescript\n * import { RequiresUserPermissions } from '@wolfstar/decorators';\n * import { Command, RegisterCommand } from '@wolfstar/http-framework';\n *\n * (at)RegisterCommand({ name: 'ban', description: 'Bans a member' })\n * export class UserCommand extends Command {\n * \t(at)RequiresUserPermissions('BanMembers')\n * \tpublic override chatInputRun(interaction: Command.ChatInputInteraction) {\n * \t\treturn interaction.reply({ content: 'Banned!' });\n * \t}\n * }\n * ```\n */\nexport function RequiresUserPermissions(...permissions: PermissionResolvable[]): MethodDecorator {\n\tconst required = resolvePermissions(permissions);\n\treturn createFunctionPrecondition(\n\t\t(interaction: BaseInteraction) => {\n\t\t\tconst granted = getUserPermissions(interaction);\n\t\t\treturn granted === null || getMissingPermissions(granted, required) === 0n;\n\t\t},\n\t\t(interaction: BaseInteraction) => {\n\t\t\tconst missing = getMissingPermissions(getUserPermissions(interaction) ?? 0n, required);\n\t\t\tconst missingNames = toPermissionNames(missing);\n\t\t\tthrow new PreconditionError({\n\t\t\t\tprecondition: 'UserPermissions',\n\t\t\t\tidentifier: Identifiers.PreconditionUserPermissions,\n\t\t\t\tmessage: `Sorry, but you are not allowed to do that. You are missing the permissions: ${missingNames.join(', ')}`,\n\t\t\t\tcontext: { missing, missingNames }\n\t\t\t});\n\t\t}\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,sBAAqE,IAA0B;CAC9G,OAAO;AACR;;;;;;;;;;;AAYA,SAAgB,qBAAoE,IAA0B;CAC7G,OAAO;AACR;;;;;;;;AASA,SAAgB,YAA8B,QAAW,SAA0C;CAClG,OAAO,IAAI,MAAM,QAAQ;EACxB,GAAG;EACH,MAAM,aAAa,aAAa;GAC/B,MAAM,QAAQ,QAAQ,IAAI,aAAa,QAAQ;GAC/C,OAAO,OAAO,UAAU,cAAc,GAAG,SAA6B,MAAM,MAAM,aAAa,IAAI,IAAI;EACxG;CACD,CAAC;AACF;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,2BACf,cACA,iBAA8C,QAC5B;CAClB,OAAO,uBAAuB,SAAkB,cAA+B,eAAmC;EACjH,MAAM,SAAS,WAAW;EAC1B,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,6CAA6C;EAC1E,IAAI,OAAO,WAAW,YAAY,MAAM,IAAI,MAAM,0DAA0D;EAE5G,WAAW,QAAQ,eAAe,MAAqB,GAAG,MAAa;GACtE,OAAQ,MAAM,aAAa,MAAM,MAAM,IAAI,IAAK,OAAO,MAAM,MAAM,IAAI,IAAI,SAAS,MAAM,MAAM,IAAI;EACrG;CACD,CAAC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5CA,SAAgB,aACf,aACiB;CACjB,OAAO,sBAAsB,WAC5B,YAAY,QAAQ,EACnB,YAAY,MAAM,CAAC,SAAS,cAAyD,cACpF,QAAQ,UACP,MACA,CACC,SACA;EACC,GAAG;EACH,GAAI,OAAO,gBAAgB,aAAa,YAAY,OAAO,IAAI;CAChE,CACD,GACA,SACD,EACF,CAAC,CACF;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpCA,SAAgB,WAAW,OAAgB;CAC1C,QAAQ,QAAiB,QAAgB;EACxC,QAAQ,eAAe,QAAkB,KAAK;GAC7C,YAAY;GACZ,IAAmB,KAAc;IAChC,QAAQ,eAAe,MAAgB,KAAK;KAC3C,cAAc;KACd,YAAY;KACZ,OAAO;KACP,UAAU;IACX,CAAC;GACF;EACD,CAAC;CACF;AACD;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBAAiB,OAAgB;CAChD,QAAQ,SAAkB,MAAc,eAAmC;EAC1E,WAAW,aAAa;CACzB;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;AChCA,SAAgB,qBAAqB,iBAAkC,QAA4B;CAClG,OAAO,4BAA4B,gBAAiC,YAAY,QAAQ,GAAG,QAAQ;AACpG;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,kBAAkB,iBAAkC,QAA4B;CAC/F,OAAO,4BAA4B,gBAAiC,CAAC,YAAY,QAAQ,GAAG,QAAQ;AACrG;;;;;;;;;;;ACzCA,SAAS,mBAAmB,aAA6C;CACxE,MAAM,cAAc,YAAY,QAAQ;CACxC,OAAO,gBAAgB,SAAY,OAAO,OAAO,WAAW;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,0BAA0B,GAAG,aAAsD;CAClG,MAAM,WAAW,mBAAmB,WAAW;CAC/C,OAAO,4BACL,gBAAiC;EACjC,MAAM,UAAU,YAAY;EAG5B,OAAO,YAAY,UAAa,sBAAsB,SAAS,QAAQ,MAAM;CAC9E,IACC,gBAAiC;EACjC,MAAM,UAAU,sBAAsB,YAAY,0BAA0B,IAAI,QAAQ;EACxF,MAAM,eAAe,kBAAkB,OAAO;EAC9C,MAAM,IAAI,kBAAkB;GAC3B,cAAc;GACd,YAAY,YAAY;GACxB,SAAS,yEAAyE,aAAa,KAAK,IAAI;GACxG,SAAS;IAAE;IAAS;GAAa;EAClC,CAAC;CACF,CACD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,wBAAwB,GAAG,aAAsD;CAChG,MAAM,WAAW,mBAAmB,WAAW;CAC/C,OAAO,4BACL,gBAAiC;EACjC,MAAM,UAAU,mBAAmB,WAAW;EAC9C,OAAO,YAAY,QAAQ,sBAAsB,SAAS,QAAQ,MAAM;CACzE,IACC,gBAAiC;EACjC,MAAM,UAAU,sBAAsB,mBAAmB,WAAW,KAAK,IAAI,QAAQ;EACrF,MAAM,eAAe,kBAAkB,OAAO;EAC9C,MAAM,IAAI,kBAAkB;GAC3B,cAAc;GACd,YAAY,YAAY;GACxB,SAAS,+EAA+E,aAAa,KAAK,IAAI;GAC9G,SAAS;IAAE;IAAS;GAAa;EAClC,CAAC;CACF,CACD;AACD"}
|
package/package.json
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@wolfstar/decorators",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Useful TypeScript decorators for @wolfstar/http-framework",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"decorators",
|
|
7
|
+
"discord",
|
|
8
|
+
"http",
|
|
9
|
+
"pnpm",
|
|
10
|
+
"ts",
|
|
11
|
+
"typescript",
|
|
12
|
+
"wolfstar"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/wolfstar-project/stars-components/tree/main/packages/decorators",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/wolfstar-project/stars-components/issues"
|
|
17
|
+
},
|
|
18
|
+
"license": "Apache-2.0",
|
|
19
|
+
"author": "@wolfstar",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/wolfstar-project/stars-components.git",
|
|
23
|
+
"directory": "packages/decorators"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist/"
|
|
27
|
+
],
|
|
28
|
+
"type": "module",
|
|
29
|
+
"sideEffects": false,
|
|
30
|
+
"main": "dist/esm/index.js",
|
|
31
|
+
"module": "dist/esm/index.js",
|
|
32
|
+
"types": "dist/esm/index.d.ts",
|
|
33
|
+
"exports": {
|
|
34
|
+
".": {
|
|
35
|
+
"import": {
|
|
36
|
+
"types": "./dist/esm/index.d.ts",
|
|
37
|
+
"default": "./dist/esm/index.js"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"provenance": true
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@vitest/coverage-v8": "^5.0.1",
|
|
48
|
+
"@wolfstar/http-framework": "^6.0.0",
|
|
49
|
+
"discord-api-types": "^0.38.8",
|
|
50
|
+
"golar": "^0.1.10",
|
|
51
|
+
"tsdown": "^0.23.0",
|
|
52
|
+
"typescript": "~7.0.2",
|
|
53
|
+
"vitest": "^5.0.1"
|
|
54
|
+
},
|
|
55
|
+
"peerDependencies": {
|
|
56
|
+
"@wolfstar/http-framework": "^6.0.0"
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=20"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"test": "vitest run",
|
|
63
|
+
"build": "tsdown --config-loader unrun",
|
|
64
|
+
"watch": "tsdown --config-loader unrun --watch",
|
|
65
|
+
"typecheck": "golar tsc -p ../../tsconfig.json",
|
|
66
|
+
"lint": "oxlint src --fix"
|
|
67
|
+
}
|
|
68
|
+
}
|