Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AddUsageLimitSourceDialog.logic.ts

27 lines865 Bytes

1import { type UnifiedSettings, UsageLimitSourceId } from "@t3tools/contracts";
2​
3export function sourceIdFromUrl(
4 url: string,
5 sources: UnifiedSettings["usageLimitSources"],
6 kind: "http" | "cliproxy" = "cliproxy",
7): UsageLimitSourceId {
8 const saved = Object.entries(sources).find(
9 ([, source]) => source.kind === kind && source.url === url,
10 );
11 if (saved) return UsageLimitSourceId.make(saved[0]);
12 let host = url;
13 try {
14 host = new URL(url).host;
15 } catch {}
16 const slug = host
17 .toLowerCase()
18 .replace(/[^a-z0-9.-]+/g, "-")
19 .replace(/^-+|-+$/g, "");
20 // Settings merge by ID, so adding a different hub must not replace an existing entry.
21 const base = `${kind}-${slug || "source"}`;
22 let id = base;
23 for (let suffix = 2; id in sources; suffix += 1) {
24 id = `${base}-${suffix}`;
25 }
26 return UsageLimitSourceId.make(id);