cordo 2.12.3 → 2.14.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/package.json +5 -5
- package/src/core/files/command.ts +302 -0
- package/src/core/files/config.ts +24 -17
- package/src/core/files/lockfile.ts +4 -1
- package/src/core/files/route.ts +2 -2
- package/src/core/gateway.ts +30 -4
- package/src/core/index.ts +7 -4
- package/src/core/interaction.ts +5 -1
- package/src/core/routing/filesystem.ts +38 -5
- package/src/core/routing/resolve.ts +1 -1
- package/src/lib/constants.ts +1 -0
- package/src/lib/localization.ts +37 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cordo",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.14.0",
|
|
4
4
|
"description": "A framework for handling complex discord api interactions",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./src/index.ts",
|
|
@@ -26,19 +26,18 @@
|
|
|
26
26
|
},
|
|
27
27
|
"repository": {
|
|
28
28
|
"type": "git",
|
|
29
|
-
"url": "
|
|
29
|
+
"url": "https://github.com/maanex/cordo.git"
|
|
30
30
|
},
|
|
31
31
|
"author": "Andreas May <andreas@maanex.me>",
|
|
32
32
|
"license": "ISC",
|
|
33
33
|
"bugs": {
|
|
34
|
-
"url": "https://github.com/
|
|
34
|
+
"url": "https://github.com/maanex/cordo/issues"
|
|
35
35
|
},
|
|
36
|
-
"homepage": "https://github.com/
|
|
36
|
+
"homepage": "https://github.com/maanex/cordo#readme",
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@types/bun": "^1.2.10",
|
|
39
39
|
"axios": "^0.21.4",
|
|
40
40
|
"defu": "^6.1.4",
|
|
41
|
-
"discord-api-types": "^0.38.42",
|
|
42
41
|
"discord-interactions": "^2.4.1",
|
|
43
42
|
"type-fest": "^4.34.1"
|
|
44
43
|
},
|
|
@@ -48,6 +47,7 @@
|
|
|
48
47
|
"@types/node": "^17.0.8",
|
|
49
48
|
"@typescript-eslint/eslint-plugin": "^4.28.3",
|
|
50
49
|
"@typescript-eslint/parser": "^4.28.3",
|
|
50
|
+
"discord-api-types": "^0.38.53",
|
|
51
51
|
"discord.js": "^14.18.0",
|
|
52
52
|
"eslint": "^7.30.0",
|
|
53
53
|
"eslint-config-maanex": "^1.1.2",
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import type { Permissions } from 'discord-api-types/globals'
|
|
2
|
+
import { ChannelType, ApplicationCommandOptionType, ApplicationCommandType, type APIApplicationCommandOption } from 'discord-api-types/v10'
|
|
3
|
+
import type { LocalizedString } from '../../lib/localization'
|
|
4
|
+
import { CordoGateway } from '../gateway'
|
|
5
|
+
import { RoutingResolve } from '../routing/resolve'
|
|
6
|
+
import type { CordoInteraction } from '../interaction'
|
|
7
|
+
import type { CordoRoute } from './route'
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
type CommandOption = {
|
|
11
|
+
name: string | LocalizedString
|
|
12
|
+
description: string | LocalizedString
|
|
13
|
+
required?: boolean
|
|
14
|
+
} & ({
|
|
15
|
+
type: 'string'
|
|
16
|
+
minLength?: number
|
|
17
|
+
maxLength?: number
|
|
18
|
+
choices: Array<{
|
|
19
|
+
name: string | LocalizedString
|
|
20
|
+
value: string
|
|
21
|
+
}>
|
|
22
|
+
} | {
|
|
23
|
+
type: 'integer'
|
|
24
|
+
minValue?: number
|
|
25
|
+
maxValue?: number
|
|
26
|
+
autocomplete?: boolean
|
|
27
|
+
choices?: Array<{
|
|
28
|
+
name: string | LocalizedString
|
|
29
|
+
value: number
|
|
30
|
+
}>
|
|
31
|
+
} | {
|
|
32
|
+
type: 'boolean'
|
|
33
|
+
} | {
|
|
34
|
+
type: 'user'
|
|
35
|
+
} | {
|
|
36
|
+
type: 'channel'
|
|
37
|
+
channelTypes?: ChannelType[]
|
|
38
|
+
} | {
|
|
39
|
+
type: 'role'
|
|
40
|
+
} | {
|
|
41
|
+
type: 'mentionable'
|
|
42
|
+
} | {
|
|
43
|
+
type: 'number'
|
|
44
|
+
minValue?: number
|
|
45
|
+
maxValue?: number
|
|
46
|
+
autocomplete?: boolean
|
|
47
|
+
choices: Array<{
|
|
48
|
+
name: string | LocalizedString
|
|
49
|
+
value: number
|
|
50
|
+
}>
|
|
51
|
+
} | {
|
|
52
|
+
type: 'attachment'
|
|
53
|
+
fileTypes?: Array<'image' | 'video' | 'audio' | `.${string}`>
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const CordoCommandSymbol = Symbol.for('CordoCommand')
|
|
57
|
+
|
|
58
|
+
type CommandInput = {
|
|
59
|
+
type: 'chat' | 'message' | 'user' | 'entrypoint'
|
|
60
|
+
name?: string | LocalizedString
|
|
61
|
+
description?: string | LocalizedString
|
|
62
|
+
defaultMemberPermissions?: Permissions
|
|
63
|
+
nsfw?: boolean
|
|
64
|
+
limitInstallTypes?: Array<'guild' | 'user'>
|
|
65
|
+
limitContexts?: Array<'guild' | 'dm' | 'group'>
|
|
66
|
+
options?: CommandOption[]
|
|
67
|
+
route: CordoRoute | 'launch_activity'
|
|
68
|
+
private?: boolean | ((r: CordoInteraction) => boolean)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export type CordoCommand = {
|
|
72
|
+
[CordoCommandSymbol]: typeof CordoCommandSymbol
|
|
73
|
+
} & CommandInput
|
|
74
|
+
|
|
75
|
+
export function defineCordoCommand(command: CommandInput): CordoCommand {
|
|
76
|
+
return {
|
|
77
|
+
[CordoCommandSymbol]: CordoCommandSymbol,
|
|
78
|
+
...command
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export namespace CommandInternals {
|
|
83
|
+
export async function readCommand(filePath: string): Promise<CordoCommand | null> {
|
|
84
|
+
const content = await import(filePath)
|
|
85
|
+
|
|
86
|
+
if (!content || !content.default)
|
|
87
|
+
return null
|
|
88
|
+
|
|
89
|
+
if (!content.default[CordoCommandSymbol])
|
|
90
|
+
return null
|
|
91
|
+
|
|
92
|
+
return content.default
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const optionTypeMap: Record<string, ApplicationCommandOptionType> = {
|
|
96
|
+
string: ApplicationCommandOptionType.String,
|
|
97
|
+
integer: ApplicationCommandOptionType.Integer,
|
|
98
|
+
boolean: ApplicationCommandOptionType.Boolean,
|
|
99
|
+
user: ApplicationCommandOptionType.User,
|
|
100
|
+
channel: ApplicationCommandOptionType.Channel,
|
|
101
|
+
role: ApplicationCommandOptionType.Role,
|
|
102
|
+
mentionable: ApplicationCommandOptionType.Mentionable,
|
|
103
|
+
number: ApplicationCommandOptionType.Number,
|
|
104
|
+
attachment: ApplicationCommandOptionType.Attachment
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const commandTypeMap: Record<string, ApplicationCommandType> = {
|
|
108
|
+
chat: ApplicationCommandType.ChatInput,
|
|
109
|
+
user: ApplicationCommandType.User,
|
|
110
|
+
message: ApplicationCommandType.Message,
|
|
111
|
+
entrypoint: 4 // ApplicationCommandType.PrimaryEntryPoint
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function resolveLocalizedText(input: string | LocalizedString | undefined, fallback: string = ''): { value: string, localizations: Record<string, string> | undefined } {
|
|
115
|
+
if (typeof input === 'string') {
|
|
116
|
+
return { value: input, localizations: undefined }
|
|
117
|
+
} else if (input && typeof input === 'object') {
|
|
118
|
+
const localizations = { ...input }
|
|
119
|
+
delete (localizations as any).default
|
|
120
|
+
return { value: input.default, localizations }
|
|
121
|
+
}
|
|
122
|
+
return { value: fallback, localizations: undefined }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function mapCommandOptionToApiOption(opt: any): APIApplicationCommandOption {
|
|
126
|
+
const { value: name, localizations: name_localizations } = resolveLocalizedText(opt.name)
|
|
127
|
+
const { value: description, localizations: description_localizations } = resolveLocalizedText(opt.description)
|
|
128
|
+
|
|
129
|
+
const res: any = {
|
|
130
|
+
type: optionTypeMap[opt.type] || ApplicationCommandOptionType.String,
|
|
131
|
+
name,
|
|
132
|
+
name_localizations,
|
|
133
|
+
description,
|
|
134
|
+
description_localizations,
|
|
135
|
+
required: opt.required,
|
|
136
|
+
autocomplete: opt.autocomplete,
|
|
137
|
+
min_value: opt.minValue,
|
|
138
|
+
max_value: opt.maxValue,
|
|
139
|
+
min_length: opt.minLength,
|
|
140
|
+
max_length: opt.maxLength,
|
|
141
|
+
file_types: opt.fileTypes,
|
|
142
|
+
channel_types: opt.channelTypes,
|
|
143
|
+
choices: opt.choices?.map((c: any) => {
|
|
144
|
+
const { value: name, localizations: name_localizations } = resolveLocalizedText(c.name)
|
|
145
|
+
return { name, name_localizations, value: c.value }
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return res
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
interface CommandTree {
|
|
153
|
+
command?: CordoCommand
|
|
154
|
+
subcommands: Map<string, CommandTree>
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function buildApiOption(rawName: string, tree: CommandTree): APIApplicationCommandOption {
|
|
158
|
+
const { value: name, localizations: name_localizations } = resolveLocalizedText(tree.command?.name, rawName)
|
|
159
|
+
const { value: description, localizations: description_localizations } = resolveLocalizedText(tree.command?.description, 'No description provided')
|
|
160
|
+
|
|
161
|
+
const isGroup = tree.subcommands.size > 0
|
|
162
|
+
|
|
163
|
+
const options: any[] = []
|
|
164
|
+
if (isGroup) {
|
|
165
|
+
for (const [ subName, subTree ] of tree.subcommands.entries())
|
|
166
|
+
options.push(buildApiOption(subName, subTree))
|
|
167
|
+
} else if (tree.command?.options) {
|
|
168
|
+
options.push(...tree.command.options.map(mapCommandOptionToApiOption))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
type: isGroup
|
|
173
|
+
? ApplicationCommandOptionType.SubcommandGroup
|
|
174
|
+
: ApplicationCommandOptionType.Subcommand,
|
|
175
|
+
name,
|
|
176
|
+
name_localizations,
|
|
177
|
+
description,
|
|
178
|
+
description_localizations,
|
|
179
|
+
options: options.length > 0 ? options : undefined
|
|
180
|
+
} as any
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export async function syncCommands(commands: Map<string, CordoCommand>, guild?: string, options?: { maxRetries?: number }) {
|
|
184
|
+
if (!commands || commands.size === 0) {
|
|
185
|
+
console.warn('No commands to sync. Is cordo initialized and commands defined?')
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const rootCommands = new Map<string, CommandTree>()
|
|
190
|
+
|
|
191
|
+
for (const [ route, command ] of commands.entries()) {
|
|
192
|
+
const parts = route.split('/')
|
|
193
|
+
let currentLevel = rootCommands
|
|
194
|
+
|
|
195
|
+
for (let i = 0; i < parts.length; i++) {
|
|
196
|
+
const part = parts[i]
|
|
197
|
+
if (!currentLevel.has(part))
|
|
198
|
+
currentLevel.set(part, { subcommands: new Map() })
|
|
199
|
+
|
|
200
|
+
const node = currentLevel.get(part)!
|
|
201
|
+
if (i === parts.length - 1)
|
|
202
|
+
node.command = command
|
|
203
|
+
|
|
204
|
+
currentLevel = node.subcommands
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const apiCommands: any[] = []
|
|
209
|
+
|
|
210
|
+
for (const [ rootName, tree ] of rootCommands.entries()) {
|
|
211
|
+
let { value: name, localizations: nameLocalizations } = resolveLocalizedText(tree.command?.name, rootName)
|
|
212
|
+
|
|
213
|
+
if (tree.command) {
|
|
214
|
+
const commandTypeStr = tree.command.type === 'chat' ? 'slash' : tree.command.type
|
|
215
|
+
if (commandTypeStr === 'slash' || commandTypeStr === 'message' || commandTypeStr === 'user') {
|
|
216
|
+
const expectedRoute = RoutingResolve.getRouteForCommand(name, commandTypeStr as any).path.split('/').pop()
|
|
217
|
+
if (expectedRoute !== rootName) {
|
|
218
|
+
console.error(`Command name '${name}' resolves to route '${expectedRoute}' which does not match actual route '${rootName}'. Using route name instead.`)
|
|
219
|
+
name = rootName
|
|
220
|
+
nameLocalizations = undefined
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const { value: description, localizations: descriptionLocalizations } = resolveLocalizedText(
|
|
226
|
+
tree.command?.description,
|
|
227
|
+
tree.subcommands.size > 0 ? 'Command group' : 'No description provided'
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
const cmdType = tree.command ? (commandTypeMap[tree.command.type] || ApplicationCommandType.ChatInput) : ApplicationCommandType.ChatInput
|
|
231
|
+
|
|
232
|
+
const apiOptions: any[] = []
|
|
233
|
+
if (tree.subcommands.size > 0) {
|
|
234
|
+
for (const [ subName, subTree ] of tree.subcommands.entries())
|
|
235
|
+
apiOptions.push(buildApiOption(subName, subTree))
|
|
236
|
+
|
|
237
|
+
} else if (tree.command?.options) {
|
|
238
|
+
apiOptions.push(...tree.command.options.map(mapCommandOptionToApiOption))
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const apiCmd: any = {
|
|
242
|
+
name,
|
|
243
|
+
name_localizations: nameLocalizations,
|
|
244
|
+
description,
|
|
245
|
+
description_localizations: descriptionLocalizations,
|
|
246
|
+
type: cmdType,
|
|
247
|
+
options: apiOptions.length > 0 ? apiOptions : undefined
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (tree.command) {
|
|
251
|
+
apiCmd.default_member_permissions = tree.command.defaultMemberPermissions?.toString()
|
|
252
|
+
apiCmd.nsfw = tree.command.nsfw
|
|
253
|
+
apiCmd.contexts = tree.command.limitContexts ? tree.command.limitContexts.map(c => c === 'guild' ? 0 : c === 'dm' ? 1 : 2) : undefined
|
|
254
|
+
apiCmd.integration_types = tree.command.limitInstallTypes ? tree.command.limitInstallTypes.map(i => i === 'guild' ? 0 : 1) : undefined
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
apiCommands.push(apiCmd)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const maxRetries = options?.maxRetries ?? 3
|
|
261
|
+
|
|
262
|
+
for (const apiCmd of apiCommands.values()) {
|
|
263
|
+
let retries = 0
|
|
264
|
+
|
|
265
|
+
while (true) {
|
|
266
|
+
const res = await CordoGateway.upsertCommand(apiCmd, guild)
|
|
267
|
+
|
|
268
|
+
if (res.status === 429) {
|
|
269
|
+
const retryAfter = res.headers['retry-after'] || res.data?.retry_after
|
|
270
|
+
const waitTime = retryAfter ? parseFloat(retryAfter) * 1000 : 5000
|
|
271
|
+
console.warn(`Rate limited (429) when syncing command '${apiCmd.name}'. Waiting ${waitTime}ms...`)
|
|
272
|
+
await new Promise(resolve => setTimeout(resolve, waitTime))
|
|
273
|
+
continue
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (res.status >= 400) {
|
|
277
|
+
console.error(`Error syncing command '${apiCmd.name}' [HTTP ${res.status}]: ${JSON.stringify(res.data)}`)
|
|
278
|
+
if (retries < maxRetries) {
|
|
279
|
+
retries++
|
|
280
|
+
const backoffTime = 1000 * retries
|
|
281
|
+
console.log(`Retrying (${retries}/${maxRetries}) in ${backoffTime}ms...`)
|
|
282
|
+
await new Promise(resolve => setTimeout(resolve, backoffTime))
|
|
283
|
+
continue
|
|
284
|
+
} else {
|
|
285
|
+
console.error(`Max retries reached for command '${apiCmd.name}'. Skipping.`)
|
|
286
|
+
break
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const remaining = res.headers['x-ratelimit-remaining']
|
|
291
|
+
const resetAfter = res.headers['x-ratelimit-reset-after']
|
|
292
|
+
if (remaining !== undefined && parseInt(remaining, 10) === 0 && resetAfter) {
|
|
293
|
+
const waitTime = parseFloat(resetAfter) * 1000
|
|
294
|
+
console.log(`Rate limit bucket depleted. Waiting ${waitTime}ms before next command...`)
|
|
295
|
+
await new Promise(resolve => setTimeout(resolve, waitTime))
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
break
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
package/src/core/files/config.ts
CHANGED
|
@@ -16,9 +16,15 @@ type HookFor<T, Context = never> = null | ((value: T, context: Context) => Promi
|
|
|
16
16
|
type TransformHookFor<T, Context = never> = null | ((value: T, context: Context) => T)
|
|
17
17
|
|
|
18
18
|
export type CordoConfig = {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
paths: {
|
|
20
|
+
root: string
|
|
21
|
+
routes: string
|
|
22
|
+
lockfile: string
|
|
23
|
+
types: string | null
|
|
24
|
+
}
|
|
25
|
+
defaults: {
|
|
26
|
+
commandRoutePrefix?: string
|
|
27
|
+
}
|
|
22
28
|
upstream: {
|
|
23
29
|
baseUrl: string
|
|
24
30
|
/** if an interaction was not replied to within X millis, cordo will send the appropriate defer/ack response. Set to 0 to disable */
|
|
@@ -28,9 +34,6 @@ export type CordoConfig = {
|
|
|
28
34
|
id: string
|
|
29
35
|
publicKey: string
|
|
30
36
|
}
|
|
31
|
-
paths: {
|
|
32
|
-
routes: string
|
|
33
|
-
}
|
|
34
37
|
/** hooks allow you to process certain data at certain points during cordo's internals. you can always return null to stop the flow of data at that point. */
|
|
35
38
|
hooks: {
|
|
36
39
|
/** gets called before cordo does anything with the interaction */
|
|
@@ -77,9 +80,15 @@ export function defineCordoConfig(conf: PartialDeep<CordoConfig> = {}): PartialD
|
|
|
77
80
|
export namespace ConfigInternals {
|
|
78
81
|
|
|
79
82
|
const defaultConfig: CordoConfig = {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
+
paths: {
|
|
84
|
+
root: '.',
|
|
85
|
+
routes: './routes',
|
|
86
|
+
lockfile: './cordo.lock',
|
|
87
|
+
types: null,
|
|
88
|
+
},
|
|
89
|
+
defaults: {
|
|
90
|
+
commandRoutePrefix: 'command'
|
|
91
|
+
},
|
|
83
92
|
upstream: {
|
|
84
93
|
baseUrl: 'https://discord.com/api/v10',
|
|
85
94
|
autoDeferMs: 50
|
|
@@ -88,9 +97,6 @@ export namespace ConfigInternals {
|
|
|
88
97
|
id: '',
|
|
89
98
|
publicKey: ''
|
|
90
99
|
},
|
|
91
|
-
paths: {
|
|
92
|
-
routes: './routes'
|
|
93
|
-
},
|
|
94
100
|
hooks: {
|
|
95
101
|
onRawInteraction: null,
|
|
96
102
|
onBeforeHandle: null,
|
|
@@ -147,13 +153,14 @@ export namespace ConfigInternals {
|
|
|
147
153
|
export async function readAndParseConfig(): Promise<ParsedCordoConfig> {
|
|
148
154
|
const config = await readConfig()
|
|
149
155
|
|
|
150
|
-
config.
|
|
151
|
-
|
|
152
|
-
config.
|
|
153
|
-
|
|
156
|
+
config.paths.root = resolveRelativePath(config.paths.root)
|
|
157
|
+
|
|
158
|
+
config.paths.lockfile = resolveRelativePath(config.paths.lockfile, config.paths.root)
|
|
159
|
+
config.paths.types = config.paths.types
|
|
160
|
+
? resolveRelativePath(config.paths.types, config.paths.root)
|
|
154
161
|
: null
|
|
155
162
|
|
|
156
|
-
config.paths.routes = resolveRelativePath(config.paths.routes, config.
|
|
163
|
+
config.paths.routes = resolveRelativePath(config.paths.routes, config.paths.root)
|
|
157
164
|
|
|
158
165
|
return {
|
|
159
166
|
...config,
|
|
@@ -2,6 +2,7 @@ import { promises as fs } from 'node:fs'
|
|
|
2
2
|
import { LibIds } from '../../lib/ids'
|
|
3
3
|
import type { RouteInternals } from './route'
|
|
4
4
|
import type { ErrorBoundaryInternals } from './error-boundary'
|
|
5
|
+
import type { CordoCommand } from './command'
|
|
5
6
|
|
|
6
7
|
|
|
7
8
|
export namespace LockfileInternals {
|
|
@@ -17,6 +18,7 @@ export namespace LockfileInternals {
|
|
|
17
18
|
$runtime: {
|
|
18
19
|
routeImpls: Map<string, RouteInternals.ParsedRoute>
|
|
19
20
|
errorBoundaries: Array<ErrorBoundaryInternals.ParsedBoundary>
|
|
21
|
+
registeredCommands: Map<string, CordoCommand>
|
|
20
22
|
}
|
|
21
23
|
}
|
|
22
24
|
|
|
@@ -35,7 +37,8 @@ export namespace LockfileInternals {
|
|
|
35
37
|
lut: [],
|
|
36
38
|
$runtime: {
|
|
37
39
|
routeImpls: new Map(),
|
|
38
|
-
errorBoundaries: []
|
|
40
|
+
errorBoundaries: [],
|
|
41
|
+
registeredCommands: new Map()
|
|
39
42
|
}
|
|
40
43
|
}
|
|
41
44
|
}
|
package/src/core/files/route.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { APIEntitlement, APIInteractionGuildMember, APIMessage, APIPartialChannel, APIPartialGuild, APIUser } from "discord-api-types/v10"
|
|
2
2
|
import type { CordoInteraction } from "../interaction"
|
|
3
|
-
import { RouteAssumptionFailedError } from "../../errors"
|
|
4
3
|
import type { goto, run } from "../../functions"
|
|
5
4
|
import type { CordoComponent } from "../../components/component"
|
|
6
5
|
import type { CordoModifier } from "../../components/modifier"
|
|
6
|
+
import { RouteAssumptionFailedError } from "../../errors"
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
const CordoRouteSymbol = Symbol.for('CordoRoute')
|
package/src/core/gateway.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ApplicationCommandOptionType, ApplicationCommandType, ComponentType, InteractionResponseType, InteractionType, type
|
|
1
|
+
import { ApplicationCommandOptionType, ApplicationCommandType, ComponentType, InteractionResponseType, InteractionType, type APIApplicationCommand, type APIInteraction } from "discord-api-types/v10"
|
|
2
2
|
import type { Method } from "axios"
|
|
3
3
|
import axios from "axios"
|
|
4
4
|
import { FunctCompiler } from "../functions/compiler"
|
|
@@ -72,9 +72,18 @@ export namespace CordoGateway {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
/** if the payload is null the interaction will be defered if not done already */
|
|
75
|
-
export async function respondTo(i: CordoInteraction, payload: Record<string, any> | null) {
|
|
75
|
+
export async function respondTo(i: CordoInteraction, payload: Record<string, any> | null, opts: { ephemeral?: boolean } = {}) {
|
|
76
76
|
payload = await Hooks.callHook('onBeforeRespond', payload, { interaction: i })
|
|
77
77
|
|
|
78
|
+
// if not specifically set, check if it's triggered by a command and if so -> is that command private?
|
|
79
|
+
if (opts?.ephemeral === undefined) {
|
|
80
|
+
const isPrivate = InteractionInternals.get(i).commandEntrypoint?.private
|
|
81
|
+
if (typeof isPrivate === 'boolean')
|
|
82
|
+
opts.ephemeral = isPrivate
|
|
83
|
+
else if (typeof isPrivate === 'function')
|
|
84
|
+
opts.ephemeral = isPrivate(i)
|
|
85
|
+
}
|
|
86
|
+
|
|
78
87
|
const internals = InteractionInternals.get(i)
|
|
79
88
|
if (internals.httpCallback && !internals.answered) {
|
|
80
89
|
internals.answered = true
|
|
@@ -83,7 +92,7 @@ export namespace CordoGateway {
|
|
|
83
92
|
return internals.httpCallback(payload)
|
|
84
93
|
|
|
85
94
|
if (i.type === InteractionType.ApplicationCommand)
|
|
86
|
-
return internals.httpCallback({ type: InteractionResponseType.DeferredChannelMessageWithSource })
|
|
95
|
+
return internals.httpCallback({ type: InteractionResponseType.DeferredChannelMessageWithSource, data: { flags: opts?.ephemeral ? 1 << 6 : 0 } })
|
|
87
96
|
|
|
88
97
|
if (i.type === InteractionType.MessageComponent)
|
|
89
98
|
return internals.httpCallback({ type: InteractionResponseType.DeferredMessageUpdate })
|
|
@@ -96,7 +105,7 @@ export namespace CordoGateway {
|
|
|
96
105
|
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, payload)
|
|
97
106
|
|
|
98
107
|
if (i.type === InteractionType.ApplicationCommand)
|
|
99
|
-
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, { type: InteractionResponseType.DeferredChannelMessageWithSource })
|
|
108
|
+
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, { type: InteractionResponseType.DeferredChannelMessageWithSource, data: { flags: opts?.ephemeral ? 1 << 6 : 0 } })
|
|
100
109
|
|
|
101
110
|
if (i.type === InteractionType.MessageComponent)
|
|
102
111
|
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, { type: InteractionResponseType.DeferredMessageUpdate })
|
|
@@ -162,7 +171,11 @@ export namespace CordoGateway {
|
|
|
162
171
|
}
|
|
163
172
|
|
|
164
173
|
const { route, path } = RoutingResolve.getRouteForCommand(name, 'slash')
|
|
174
|
+
|
|
165
175
|
CordoMagic.setCwd(path)
|
|
176
|
+
if (CordoMagic.getLockfile()?.$runtime.registeredCommands.has(route.routeId))
|
|
177
|
+
InteractionInternals.get(i).commandEntrypoint = CordoMagic.getLockfile()!.$runtime.registeredCommands.get(route.routeId)!
|
|
178
|
+
|
|
166
179
|
return RoutingRespond.callRoute(route.routeId, route.args, i)
|
|
167
180
|
}
|
|
168
181
|
|
|
@@ -172,7 +185,11 @@ export namespace CordoGateway {
|
|
|
172
185
|
i.data.name,
|
|
173
186
|
i.data.type === ApplicationCommandType.Message ? 'message' : 'user'
|
|
174
187
|
)
|
|
188
|
+
|
|
175
189
|
CordoMagic.setCwd(path)
|
|
190
|
+
if (CordoMagic.getLockfile()?.$runtime.registeredCommands.has(route.routeId))
|
|
191
|
+
InteractionInternals.get(i).commandEntrypoint = CordoMagic.getLockfile()!.$runtime.registeredCommands.get(route.routeId)!
|
|
192
|
+
|
|
176
193
|
return RoutingRespond.callRoute(route.routeId, route.args, i)
|
|
177
194
|
}
|
|
178
195
|
}
|
|
@@ -317,4 +334,13 @@ export namespace CordoGateway {
|
|
|
317
334
|
return true
|
|
318
335
|
}
|
|
319
336
|
|
|
337
|
+
export function upsertCommand(command: APIApplicationCommand, guild?: string) {
|
|
338
|
+
const config = CordoMagic.getConfig()
|
|
339
|
+
if (!config?.client.id)
|
|
340
|
+
throw new MissingContextError('Could not upsert command, no client id found in config context.')
|
|
341
|
+
|
|
342
|
+
const endpoint = guild ? `/applications/${config.client.id}/guilds/${guild}/commands` : `/applications/${config.client.id}/commands`
|
|
343
|
+
return apiRequest('post', endpoint, command)
|
|
344
|
+
}
|
|
345
|
+
|
|
320
346
|
}
|
package/src/core/index.ts
CHANGED
|
@@ -7,10 +7,12 @@ import { CordoGateway } from './gateway'
|
|
|
7
7
|
import { RoutingFilesystem } from './routing/filesystem'
|
|
8
8
|
import { CordoMagic } from './magic'
|
|
9
9
|
import type { CordoInteraction } from './interaction'
|
|
10
|
+
import { CommandInternals } from './files/command'
|
|
10
11
|
|
|
11
12
|
export { type DynamicTypes } from './dynamic-types'
|
|
12
13
|
export { type CordoConfig, defineCordoConfig } from './files/config'
|
|
13
14
|
export { type CordoRoute, type RouteRequest, defineCordoRoute, assertCordoRequest } from './files/route'
|
|
15
|
+
export { type CordoCommand, defineCordoCommand } from './files/command'
|
|
14
16
|
export { type CordoErrorBoundary, defineCordoErrorBoundary } from './files/error-boundary'
|
|
15
17
|
export { type CordoInteraction } from './interaction'
|
|
16
18
|
|
|
@@ -23,10 +25,10 @@ async function mountCordo(configOverrides?: PartialDeep<CordoConfig>) {
|
|
|
23
25
|
const fileConfig = await ConfigInternals.readAndParseConfig()
|
|
24
26
|
config = configOverrides ? defu(configOverrides, fileConfig) as ParsedCordoConfig : fileConfig
|
|
25
27
|
|
|
26
|
-
lockfile = await LockfileInternals.readOrCreateLockfile(config.lockfile)
|
|
27
|
-
await RoutingFilesystem.readFsTreeAndSyncLockfile(config.paths.routes, lockfile)
|
|
28
|
+
lockfile = await LockfileInternals.readOrCreateLockfile(config.paths.lockfile)
|
|
29
|
+
await RoutingFilesystem.readFsTreeAndSyncLockfile(config.paths.routes, lockfile, config)
|
|
28
30
|
|
|
29
|
-
LockfileInternals.writeLockfile(config.lockfile, lockfile, config.
|
|
31
|
+
LockfileInternals.writeLockfile(config.paths.lockfile, lockfile, config.paths.types)
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
function triggerInteraction(interaction: APIInteraction, opts: {
|
|
@@ -64,7 +66,7 @@ function registerConstants(constants: readonly string[]) {
|
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
if (changesMade)
|
|
67
|
-
return LockfileInternals.writeLockfile(config!.lockfile, lockfile!, config!.
|
|
69
|
+
return LockfileInternals.writeLockfile(config!.paths.lockfile, lockfile!, config!.paths.types)
|
|
68
70
|
else
|
|
69
71
|
return Promise.resolve()
|
|
70
72
|
}
|
|
@@ -76,6 +78,7 @@ export const Cordo = {
|
|
|
76
78
|
registerConstants,
|
|
77
79
|
triggerInteraction,
|
|
78
80
|
respondToRawInteraction: CordoGateway.respondTo,
|
|
81
|
+
syncCommands: (opts?: { maxRetries?: number }) => CommandInternals.syncCommands(lockfile!.$runtime.registeredCommands, undefined, opts)
|
|
79
82
|
}
|
|
80
83
|
Object.freeze(Cordo)
|
|
81
84
|
|
package/src/core/interaction.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { APIInteraction } from "discord-api-types/v10"
|
|
2
|
+
import type { CordoCommand } from "./files/command"
|
|
2
3
|
|
|
3
4
|
|
|
4
5
|
const CordoInteractionSymbol = Symbol.for('CordoInteraction')
|
|
@@ -7,6 +8,8 @@ export type CordoInteraction = {
|
|
|
7
8
|
[CordoInteractionSymbol]: {
|
|
8
9
|
answered: boolean
|
|
9
10
|
httpCallback: ((payload: any) => any) | null
|
|
11
|
+
// will be set to the command linked to this interaction if it was triggered by a command, otherwise null
|
|
12
|
+
commandEntrypoint: CordoCommand | null
|
|
10
13
|
}
|
|
11
14
|
locals: Record<string, any>
|
|
12
15
|
} & APIInteraction
|
|
@@ -29,7 +32,8 @@ export namespace InteractionInternals {
|
|
|
29
32
|
locals: {},
|
|
30
33
|
[CordoInteractionSymbol]: {
|
|
31
34
|
answered: false,
|
|
32
|
-
httpCallback: null
|
|
35
|
+
httpCallback: null,
|
|
36
|
+
commandEntrypoint: null
|
|
33
37
|
}
|
|
34
38
|
}
|
|
35
39
|
}
|
|
@@ -4,20 +4,24 @@ import { ErrorBoundaryInternals, type CordoErrorBoundary } from "../files/error-
|
|
|
4
4
|
import { RouteInternals, type CordoRoute } from "../files/route"
|
|
5
5
|
import { LockfileInternals } from "../files/lockfile"
|
|
6
6
|
import { LibIds } from "../../lib/ids"
|
|
7
|
+
import { CommandInternals, type CordoCommand } from "../files/command"
|
|
8
|
+
import type { ParsedCordoConfig } from "../files/config"
|
|
7
9
|
|
|
8
10
|
|
|
9
11
|
export namespace RoutingFilesystem {
|
|
10
12
|
|
|
11
|
-
export const supportedExtensions = [ 'js', 'ts' ]
|
|
13
|
+
export const supportedExtensions = [ 'js', 'ts', 'mjs', 'mts' ]
|
|
12
14
|
|
|
13
15
|
export type ParsedFsTree = {
|
|
14
16
|
routes: Array<{ path: string[]; route: CordoRoute }>
|
|
17
|
+
commands: Array<{ path: string[]; command: CordoCommand }>
|
|
15
18
|
errorBounds: Array<{ path: string[]; boundary: CordoErrorBoundary }>
|
|
16
19
|
}
|
|
17
20
|
|
|
18
|
-
export async function readFsTree(treeRoot: string, maxDepth = 20): Promise<ParsedFsTree> {
|
|
21
|
+
export async function readFsTree(treeRoot: string, config: ParsedCordoConfig, maxDepth = 20): Promise<ParsedFsTree> {
|
|
19
22
|
const out: ParsedFsTree = {
|
|
20
23
|
routes: [],
|
|
24
|
+
commands: [],
|
|
21
25
|
errorBounds: []
|
|
22
26
|
}
|
|
23
27
|
|
|
@@ -27,7 +31,7 @@ export namespace RoutingFilesystem {
|
|
|
27
31
|
const dir = await fs.opendir(treeRoot)
|
|
28
32
|
for await (const item of dir) {
|
|
29
33
|
if (item.isDirectory()) {
|
|
30
|
-
const subTree = await readFsTree(join(treeRoot, item.name), maxDepth - 1)
|
|
34
|
+
const subTree = await readFsTree(join(treeRoot, item.name), config, maxDepth - 1)
|
|
31
35
|
for (const child of subTree.routes) {
|
|
32
36
|
out.routes.push({
|
|
33
37
|
path: [ item.name, ...child.path ],
|
|
@@ -44,6 +48,25 @@ export namespace RoutingFilesystem {
|
|
|
44
48
|
if (!supportedExtensions.some(ext => item.name.endsWith(`.${ext}`)))
|
|
45
49
|
continue
|
|
46
50
|
|
|
51
|
+
const command = await CommandInternals.readCommand(join(treeRoot, item.name))
|
|
52
|
+
if (command) {
|
|
53
|
+
if (!treeRoot.startsWith(config.defaults.commandRoutePrefix ?? 'command'))
|
|
54
|
+
console.warn(`File ${join(treeRoot, item.name)} defined a command but is not in the command route prefix folder (${config.defaults.commandRoutePrefix ?? 'command'}). The command will probably not trigger the configured route when run.`)
|
|
55
|
+
|
|
56
|
+
out.commands.push({
|
|
57
|
+
path: [ item.name ],
|
|
58
|
+
command
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
if (typeof command.route !== 'string') {
|
|
62
|
+
out.routes.push({
|
|
63
|
+
path: [ item.name ],
|
|
64
|
+
route: command.route
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
|
|
47
70
|
const route = await RouteInternals.readRoute(join(treeRoot, item.name))
|
|
48
71
|
if (route) {
|
|
49
72
|
out.routes.push({
|
|
@@ -67,8 +90,8 @@ export namespace RoutingFilesystem {
|
|
|
67
90
|
return out
|
|
68
91
|
}
|
|
69
92
|
|
|
70
|
-
export async function readFsTreeAndSyncLockfile(treeRoot: string, lockfile: LockfileInternals.ParsedLockfile): Promise<RouteInternals.ParsedRoute[]> {
|
|
71
|
-
const files = await readFsTree(treeRoot)
|
|
93
|
+
export async function readFsTreeAndSyncLockfile(treeRoot: string, lockfile: LockfileInternals.ParsedLockfile, config: ParsedCordoConfig): Promise<RouteInternals.ParsedRoute[]> {
|
|
94
|
+
const files = await readFsTree(treeRoot, config)
|
|
72
95
|
|
|
73
96
|
const out: RouteInternals.ParsedRoute[] = []
|
|
74
97
|
for (const file of files.routes) {
|
|
@@ -109,6 +132,16 @@ export namespace RoutingFilesystem {
|
|
|
109
132
|
})
|
|
110
133
|
}
|
|
111
134
|
|
|
135
|
+
const commandRoutePrefix = config?.defaults.commandRoutePrefix ?? 'command'
|
|
136
|
+
for (const file of files.commands) {
|
|
137
|
+
const filePath = file.path.join('/').startsWith(`${commandRoutePrefix}/`)
|
|
138
|
+
? file.path.join('/').slice(commandRoutePrefix.length + 1)
|
|
139
|
+
: file.path.join('/')
|
|
140
|
+
|
|
141
|
+
lockfile.$runtime.registeredCommands.set(filePath, file.command)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
112
145
|
return out
|
|
113
146
|
}
|
|
114
147
|
|
|
@@ -142,7 +142,7 @@ export namespace RoutingResolve {
|
|
|
142
142
|
: type === 'slash'
|
|
143
143
|
? command.replaceAll(' ', '/').toLowerCase() // slash commands: subcommands become subfolders
|
|
144
144
|
: command.replaceAll(' ', '-').replace(/[^\w-]/g, '').toLowerCase() // message/user commands: just sanitize
|
|
145
|
-
const routePath =
|
|
145
|
+
const routePath = `${CordoMagic.getConfig()?.defaults.commandRoutePrefix ?? 'command'}/${fileName}`
|
|
146
146
|
return {
|
|
147
147
|
route: getRouteFromPath(routePath, false),
|
|
148
148
|
path: routePath
|
package/src/lib/constants.ts
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
|
|
2
|
+
export type DiscordLocale = 'id'
|
|
3
|
+
| 'da'
|
|
4
|
+
| 'de'
|
|
5
|
+
| 'en-GB'
|
|
6
|
+
| 'en-US'
|
|
7
|
+
| 'es-ES'
|
|
8
|
+
| 'es-419'
|
|
9
|
+
| 'fr'
|
|
10
|
+
| 'hr'
|
|
11
|
+
| 'it'
|
|
12
|
+
| 'lt'
|
|
13
|
+
| 'hu'
|
|
14
|
+
| 'nl'
|
|
15
|
+
| 'no'
|
|
16
|
+
| 'pl'
|
|
17
|
+
| 'pt-BR'
|
|
18
|
+
| 'ro'
|
|
19
|
+
| 'fi'
|
|
20
|
+
| 'sv-SE'
|
|
21
|
+
| 'vi'
|
|
22
|
+
| 'tr'
|
|
23
|
+
| 'cs'
|
|
24
|
+
| 'el'
|
|
25
|
+
| 'bg'
|
|
26
|
+
| 'ru'
|
|
27
|
+
| 'uk'
|
|
28
|
+
| 'hi'
|
|
29
|
+
| 'th'
|
|
30
|
+
| 'zh-CN'
|
|
31
|
+
| 'ja'
|
|
32
|
+
| 'zh-TW'
|
|
33
|
+
| 'ko'
|
|
34
|
+
|
|
35
|
+
export type LocalizedString = Record<DiscordLocale, string> & {
|
|
36
|
+
default: string
|
|
37
|
+
}
|