perf(automod): bundle automod regex patterns for potentially increased performance

This commit is contained in:
Dragory 2021-10-05 21:30:35 +03:00
parent 5e25792734
commit 392e2da2d1
No known key found for this signature in database
GPG key ID: 5F387BA66DF8AAC1

View file

@ -13,6 +13,8 @@ interface MatchResultType {
type: MatchableTextType; type: MatchableTextType;
} }
const combinedRegexCache: WeakMap<any, RegExp> = new WeakMap();
export const MatchRegexTrigger = automodTrigger<MatchResultType>()({ export const MatchRegexTrigger = automodTrigger<MatchResultType>()({
configType: t.type({ configType: t.type({
patterns: t.array(TRegex), patterns: t.array(TRegex),
@ -53,19 +55,23 @@ export const MatchRegexTrigger = automodTrigger<MatchResultType>()({
str = normalizeText(str); str = normalizeText(str);
} }
for (const sourceRegex of trigger.patterns) { if (!combinedRegexCache.has(trigger)) {
const regex = new RegExp(sourceRegex.source, trigger.case_sensitive && !sourceRegex.ignoreCase ? "" : "i"); const combinedPattern = trigger.patterns.map((p) => `(?:${p.source})`).join("|");
const combinedRegex = new RegExp(combinedPattern, trigger.case_sensitive ? "" : "i");
combinedRegexCache.set(trigger, combinedRegex);
}
const regex = combinedRegexCache.get(trigger)!;
const matches = await pluginData.state.regexRunner.exec(regex, str).catch(allowTimeout); const matches = await pluginData.state.regexRunner.exec(regex, str).catch(allowTimeout);
if (matches?.length) { if (matches?.length) {
return { return {
extra: { extra: {
pattern: sourceRegex.source, pattern: "<temporarily hidden>",
type, type,
}, },
}; };
} }
} }
}
return null; return null;
}, },