File size: 1,763 Bytes
fc93158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { MsgContext } from "../../auto-reply/templating.js";
import { normalizeExplicitDiscordSessionKey } from "../../discord/session-key-normalization.js";

type ExplicitSessionKeyNormalizer = (sessionKey: string, ctx: MsgContext) => string;
type ExplicitSessionKeyNormalizerEntry = {
  provider: string;
  normalize: ExplicitSessionKeyNormalizer;
  matches: (params: {
    sessionKey: string;
    provider?: string;
    surface?: string;
    from: string;
  }) => boolean;
};

const EXPLICIT_SESSION_KEY_NORMALIZERS: ExplicitSessionKeyNormalizerEntry[] = [
  {
    provider: "discord",
    normalize: normalizeExplicitDiscordSessionKey,
    matches: ({ sessionKey, provider, surface, from }) =>
      surface === "discord" ||
      provider === "discord" ||
      from.startsWith("discord:") ||
      sessionKey.startsWith("discord:") ||
      sessionKey.includes(":discord:"),
  },
];

function resolveExplicitSessionKeyNormalizer(
  sessionKey: string,
  ctx: Pick<MsgContext, "From" | "Provider" | "Surface">,
): ExplicitSessionKeyNormalizer | undefined {
  const normalizedProvider = ctx.Provider?.trim().toLowerCase();
  const normalizedSurface = ctx.Surface?.trim().toLowerCase();
  const normalizedFrom = (ctx.From ?? "").trim().toLowerCase();
  return EXPLICIT_SESSION_KEY_NORMALIZERS.find((entry) =>
    entry.matches({
      sessionKey,
      provider: normalizedProvider,
      surface: normalizedSurface,
      from: normalizedFrom,
    }),
  )?.normalize;
}

export function normalizeExplicitSessionKey(sessionKey: string, ctx: MsgContext): string {
  const normalized = sessionKey.trim().toLowerCase();
  const normalize = resolveExplicitSessionKeyNormalizer(normalized, ctx);
  return normalize ? normalize(normalized, ctx) : normalized;
}