forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
56 lines (49 loc) · 1.58 KB
/
index.ts
File metadata and controls
56 lines (49 loc) · 1.58 KB
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
import { toASCII } from "punycode"
import rules from "./rules.json"
export type PslNode = {
// Children <part>
c?: PslTree
// Is leaf
l?: number
}
export type PslTree = Record<string, PslNode | number>
const TREE: PslTree = rules
type Chain = string | [string, boolean]
export const getSuffix = (origin: string): string | null => {
if (!origin) return origin
const ascii = toASCII(origin)
const parts = ascii.split(".")
const chains: Chain[] = []
get0(TREE, parts, parts.length - 1, chains)
let idx = -1
chains.forEach((c, i) => (typeof c === "string" || c[1]) && (idx = i))
const partLen = idx + 1
return parts.splice(parts.length - partLen, partLen).join('.')
}
export const get = (origin: string): string | null => {
if (!origin) return origin
const ascii = toASCII(origin)
const parts = ascii.split(".")
const chains: Chain[] = []
get0(TREE, parts, parts.length - 1, chains)
let idx = -1
chains.forEach((c, i) => (typeof c === "string" || c[1]) && (idx = i))
const partLen = idx + 2
return parts.splice(parts.length - partLen, partLen).join('.')
}
const get0 = (tree: PslTree, parts: string[], index: number, chains: Chain[]) => {
const part = parts[index]
let pslNode = tree[part]
if (!pslNode && !tree[`!${part}`]) {
pslNode = tree['*']
}
if (!pslNode) {
return
} else if (pslNode === 1) {
chains.push(part)
} else {
const { l, c } = pslNode as PslNode
chains.push(l ? part : [part, false])
c && get0(c, parts, index - 1, chains)
}
}