-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpatterns.ts
187 lines (182 loc) · 5.32 KB
/
patterns.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import type { Messages, RichPost } from "./mod.ts";
/**
* Possible types of patterns to a command.
* - `"string"`: Any string
* - `"number"`: Any floating point number
* - `"full"`: A string that matches until the end of the command.
* - `"reply"`: A post the command replied to.
* - `string[]`: One of the specified strings
*/
export type PatternType = "string" | "number" | "full" | "reply" | string[];
/**
* A list of arguments types. This is a list of objects formatted like this:
* - type: A {@link PatternType}.
* - optional: Whether it's optional or not. After an optional argument can only
* be other optional arguments.
* - name: The name of the argument.
* If both the name and optional aren't given, the type can be standalone
* without a wrapper object.
*
* @example Basic
* ```js
* ["number", "string"]
* // @Bot cmd 2 4 → [2, "4"]
* ```
* @example `full`
* ```js
* [
* { type: "number", name: "amount" },
* { type: "full", name: "string" }
* ]
* // @Bot cmd 7 Hello, world! → [7, "Hello, world!"]
* ```
* @example Optionals
* ```js
* [
* { type: "string", name: "person to greet" },
* { type: "string", optional: true, name: "greeting to use" }
* ]
* // @Bot cmd Josh → ["Josh"]
* // @Bot cmd Josh G'day → ["Josh", "G'day"]
* ```
*/
export type Pattern = (
| PatternType
| { type: PatternType; name?: string; optional?: boolean }
)[];
/**
* Converts the passed in `TPattern` to its corresponding TypeScript type.
*/
export type ResolvePattern<TPattern extends Pattern> = {
[K in keyof TPattern]: K extends `${number}` ?
TPattern[K] extends PatternType ? ResolvePatternType<TPattern[K]>
: TPattern[K] extends { type: PatternType } ?
TPattern[K] extends { optional: true } ?
ResolvePatternType<TPattern[K]["type"]> | undefined
: ResolvePatternType<TPattern[K]["type"]>
: never
: TPattern[K];
};
type ResolvePatternType<TArgument extends PatternType> =
TArgument extends "string" ? string
: TArgument extends "number" ? number
: TArgument extends "full" ? string
: TArgument extends "reply" ? RichPost
: TArgument extends string[] ? TArgument[number]
: never;
export const parseArgs = <const TPattern extends Pattern>(
pattern: TPattern,
args: string[],
messages: Messages,
replies?: (RichPost | null)[],
):
| { error: true; message: string }
| { error: false; parsed: ResolvePattern<TPattern> } => {
const parsed = [];
let hadOptionals = false;
let hadFull = false;
let i = 0;
let replyAmount = 0;
for (const slice of pattern) {
const isObject = typeof slice === "object" && "type" in slice;
const type = isObject ? slice.type : slice;
const optional = isObject && !!slice.optional;
if (hadOptionals && !optional) {
return {
error: true,
message:
"In this command's pattern, there is an optional argument following a non-optional one.\nThis is an issue with the bot, not your command.",
};
}
hadOptionals ||= optional;
const name = isObject && !!slice.name;
const repr = name ? `${slice.name} (${type})` : `${type}`;
if (type === "reply") {
if (!replies?.[replyAmount]) {
if (optional) {
parsed.push(undefined);
continue;
}
return {
error: true,
message: messages.argsMissing(repr),
};
}
parsed.push(replies[replyAmount]);
replyAmount++;
break;
}
const current = args[i];
if (!current) {
if (optional) {
continue;
} else if (type !== "full") {
return { error: true, message: messages.argsMissing(repr) };
}
}
if (Array.isArray(type)) {
if (!type.includes(current)) {
return {
error: true,
message: messages.argsNotInSet(
JSON.stringify(current),
type.map((t) => JSON.stringify(t)).join(", "),
),
};
}
parsed.push(current);
continue;
}
switch (type) {
case "string": {
parsed.push(current);
i++;
break;
}
case "number": {
const number = Number(current);
if (Number.isNaN(number)) {
return {
error: true,
message: messages.argNan(JSON.stringify(current)),
};
}
parsed.push(number);
i++;
break;
}
case "full": {
if (pattern[i + 1]) {
return {
error: true,
message:
"In this command's pattern, there is an argument following a `full` argument.\nThis is an issue with the bot, not your command.",
};
}
hadFull = true;
parsed.push(args.slice(i).join(" "));
i++;
break;
}
default:
(type) satisfies never;
}
}
if (!hadFull && args.length + replyAmount !== parsed.length) {
return { error: true, message: messages.tooManyArgs };
}
return { error: false, parsed: parsed as ResolvePattern<TPattern> };
};
/**
* Turns the pattern type into a human readable format.
* @param patternType The pattern type.
*/
export const stringifyPatternType = (patternType: PatternType): string => {
return (
typeof patternType === "string" ?
patternType === "full" ?
"full string"
: patternType
: patternType.map((option) => JSON.stringify(option)).join(" | ")
);
};