| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536 |
- /**
- * Hostbane-Optimized Trie based on Mnemonist Trie
- */
- import { fastStringArrayJoin } from './misc';
- import util from 'node:util';
- import { noop } from 'foxact/noop';
- type TrieNode<Meta = any> = [
- boolean, /** end */
- boolean, /** includeAllSubdoain (.example.org, ||example.com) */
- TrieNode | null, /** parent */
- Map<string, TrieNode>, /** children */
- Meta /** meta */
- ];
- function deepTrieNodeToJSON(node: TrieNode,
- unpackMeta: ((meta?: any) => string) | undefined) {
- const obj: Record<string, any> = {};
- if (node[0]) {
- obj['[start]'] = node[0];
- }
- obj['[subdomain]'] = node[1];
- if (node[4] != null) {
- if (unpackMeta) {
- obj['[meta]'] = unpackMeta(node[3]);
- } else {
- obj['[meta]'] = node[3];
- }
- }
- node[3].forEach((value, key) => {
- obj[key] = deepTrieNodeToJSON(value, unpackMeta);
- });
- return obj;
- }
- const createNode = <Meta = any>(allSubdomain = false, parent: TrieNode | null = null): TrieNode => [false, allSubdomain, parent, new Map<string, TrieNode>(), null] as TrieNode<Meta>;
- export function hostnameToTokens(hostname: string): string[] {
- const tokens = hostname.split('.');
- const results: string[] = [];
- let token = '';
- for (let i = 0, l = tokens.length; i < l; i++) {
- token = tokens[i];
- if (token.length > 0) {
- results.push(token);
- }
- }
- return results;
- }
- function walkHostnameTokens(hostname: string, onToken: (token: string) => boolean | null): boolean | null {
- const tokens = hostname.split('.');
- const l = tokens.length - 1;
- // we are at the first of hostname, no splitor there
- let token = '';
- for (let i = l; i >= 0; i--) {
- token = tokens[i];
- if (token.length > 0) {
- const t = onToken(token);
- if (t === null) {
- return null;
- }
- // if the callback returns true, we should skip the rest
- if (t) {
- return true;
- }
- }
- }
- return false;
- }
- interface FindSingleChildLeafResult<Meta> {
- node: TrieNode<Meta>,
- toPrune: TrieNode<Meta> | null,
- tokenToPrune: string | null,
- parent: TrieNode<Meta>
- }
- abstract class Triebase<Meta = any> {
- protected readonly $root: TrieNode<Meta> = createNode();
- protected $size = 0;
- get root() {
- return this.$root;
- }
- constructor(from?: string[] | Set<string> | null) {
- // Actually build trie
- if (Array.isArray(from)) {
- for (let i = 0, l = from.length; i < l; i++) {
- this.add(from[i]);
- }
- } else if (from) {
- from.forEach((value) => this.add(value));
- }
- }
- public abstract add(suffix: string, includeAllSubdoain?: boolean, meta?: Meta): void;
- protected walkIntoLeafWithTokens(
- tokens: string[],
- onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
- ) {
- let node: TrieNode = this.$root;
- let parent: TrieNode = node;
- let token: string;
- for (let i = tokens.length - 1; i >= 0; i--) {
- token = tokens[i];
- // if (token === '') {
- // break;
- // }
- parent = node;
- if (node[3].has(token)) {
- node = node[3].get(token)!;
- } else {
- return null;
- }
- onLoop(node, parent, token);
- }
- return { node, parent };
- };
- protected walkIntoLeafWithSuffix(
- suffix: string,
- onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
- ) {
- let node: TrieNode = this.$root;
- let parent: TrieNode = node;
- const onToken = (token: string) => {
- // if (token === '') {
- // return true;
- // }
- parent = node;
- if (node[3].has(token)) {
- node = node[3].get(token)!;
- } else {
- return null;
- }
- onLoop(node, parent, token);
- return false;
- };
- if (walkHostnameTokens(suffix, onToken) === null) {
- return null;
- }
- return { node, parent };
- };
- public contains(suffix: string, includeAllSubdoain = suffix[0] === '.'): boolean {
- if (suffix[0] === '.') {
- suffix = suffix.slice(1);
- }
- const res = this.walkIntoLeafWithSuffix(suffix);
- if (!res) return false;
- if (includeAllSubdoain) return res.node[1];
- return true;
- };
- private walk(
- onMatches: (suffix: string[], subdomain: boolean, meta: Meta) => void,
- initialNode = this.$root,
- initialSuffix: string[] = []
- ) {
- const nodeStack: Array<TrieNode<Meta>> = [initialNode];
- // Resolving initial string (begin the start of the stack)
- const suffixStack: string[][] = [initialSuffix];
- let node: TrieNode<Meta> = initialNode;
- do {
- node = nodeStack.pop()!;
- const suffix = suffixStack.pop()!;
- node[3].forEach((childNode, k) => {
- // Pushing the child node to the stack for next iteration of DFS
- nodeStack.push(childNode);
- suffixStack.push([k, ...suffix]);
- });
- // If the node is a sentinel, we push the suffix to the results
- if (node[0]) {
- onMatches(suffix, node[1], node[4]);
- }
- } while (nodeStack.length);
- };
- protected getSingleChildLeaf(tokens: string[]): FindSingleChildLeafResult<Meta> | null {
- let toPrune: TrieNode | null = null;
- let tokenToPrune: string | null = null;
- const onLoop = (node: TrieNode, parent: TrieNode, token: string) => {
- // Keeping track of a potential branch to prune
- // Even if the node size is 1, but the single child is ".", we should retain the branch
- // Since the "." could be special if it is the leaf-est node
- const onlyChild = node[3].size === 0 && !node[2];
- if (toPrune != null) { // the top-est branch that could potentially being pruned
- if (!onlyChild) {
- // The branch has moew than single child, retain the branch.
- // And we need to abort prune the parent, so we set it to null
- toPrune = null;
- tokenToPrune = null;
- }
- } else if (onlyChild) {
- // There is only one token child, or no child at all, we can prune it safely
- // It is now the top-est branch that could potentially being pruned
- toPrune = parent;
- tokenToPrune = token;
- }
- };
- const res = this.walkIntoLeafWithTokens(tokens, onLoop);
- if (res === null) return null;
- return { node: res.node, toPrune, tokenToPrune, parent: res.parent };
- };
- /**
- * Method used to retrieve every item in the trie with the given prefix.
- */
- public find(
- inputSuffix: string,
- subdomainOnly = inputSuffix[0] === '.'
- // /** @default true */ includeEqualWithSuffix = true
- ): string[] {
- if (inputSuffix[0] === '.') {
- inputSuffix = inputSuffix.slice(1);
- }
- const inputTokens = hostnameToTokens(inputSuffix);
- const res = this.walkIntoLeafWithTokens(inputTokens);
- if (res === null) return [];
- const results: string[] = [];
- const onMatches = subdomainOnly
- ? (suffix: string[], subdomain: boolean) => { // fast path (default option)
- const d = fastStringArrayJoin(suffix, '.');
- if (!subdomain && d === inputSuffix) return;
- results.push(subdomain ? '.' + d : d);
- }
- : (suffix: string[], subdomain: boolean) => { // fast path (default option)
- const d = fastStringArrayJoin(suffix, '.');
- results.push(subdomain ? '.' + d : d);
- };
- this.walk(
- onMatches,
- res.node, // Performing DFS from prefix
- inputTokens
- );
- return results;
- };
- /**
- * Method used to delete a prefix from the trie.
- */
- public remove(suffix: string): boolean {
- const res = this.getSingleChildLeaf(hostnameToTokens(suffix));
- if (res === null) return false;
- if (!res.node[0]) return false;
- this.$size--;
- const { node, toPrune, tokenToPrune } = res;
- if (tokenToPrune && toPrune) {
- toPrune[3].delete(tokenToPrune);
- } else {
- node[0] = false;
- }
- return true;
- };
- // eslint-disable-next-line @typescript-eslint/unbound-method -- safe
- public delete = this.remove;
- /**
- * Method used to assert whether the given prefix exists in the Trie.
- */
- public has(suffix: string, includeAllSubdoain = suffix[0] === '.'): boolean {
- if (suffix[0] === '.') {
- suffix = suffix.slice(1);
- }
- const res = this.walkIntoLeafWithSuffix(suffix);
- if (res === null) return false;
- if (!res.node[0]) return false;
- if (includeAllSubdoain) return res.node[1];
- return true;
- };
- public dump(onSuffix: (suffix: string) => void): void;
- public dump(): string[];
- public dump(onSuffix?: (suffix: string) => void): string[] | void {
- const results: string[] = [];
- const handleSuffix = onSuffix
- ? (suffix: string[], subdomain: boolean) => {
- const d = fastStringArrayJoin(suffix, '.');
- onSuffix(subdomain ? '.' + d : d);
- }
- : (suffix: string[], subdomain: boolean) => {
- const d = fastStringArrayJoin(suffix, '.');
- results.push(subdomain ? '.' + d : d);
- };
- this.walk(handleSuffix);
- return results;
- };
- public dumpMeta(onMeta: (meta: Meta) => void): void;
- public dumpMeta(): Meta[];
- public dumpMeta(onMeta?: (meta: Meta) => void): Meta[] | void {
- const results: Meta[] = [];
- const handleMeta = onMeta
- ? (_suffix: string[], _subdomain: boolean, meta: Meta) => onMeta(meta)
- : (_suffix: string[], _subdomain: boolean, meta: Meta) => results.push(meta);
- this.walk(handleMeta);
- return results;
- };
- public dumpWithMeta(onSuffix: (suffix: string, meta: Meta | undefined) => void): void;
- public dumpWithMeta(): Array<[string, Meta | undefined]>;
- public dumpWithMeta(onSuffix?: (suffix: string, meta: Meta | undefined) => void): Array<[string, Meta | undefined]> | void {
- const results: Array<[string, Meta | undefined]> = [];
- const handleSuffix = onSuffix
- ? (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
- const d = fastStringArrayJoin(suffix, '.');
- return onSuffix(subdomain ? '.' + d : d, meta);
- }
- : (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
- const d = fastStringArrayJoin(suffix, '.');
- results.push([subdomain ? '.' + d : d, meta]);
- };
- this.walk(handleSuffix);
- return results;
- };
- public inspect(depth: number, unpackMeta?: (meta?: Meta) => any) {
- return fastStringArrayJoin(
- JSON.stringify(deepTrieNodeToJSON(this.$root, unpackMeta), null, 2).split('\n').map((line) => ' '.repeat(depth) + line),
- '\n'
- );
- }
- public [util.inspect.custom](depth: number) {
- return this.inspect(depth);
- };
- }
- export class HostnameSmolTrie<Meta = any> extends Triebase<Meta> {
- public smolTree = true;
- add(suffix: string, includeAllSubdoain = suffix[0] === '.', meta?: Meta): void {
- let node: TrieNode<Meta> = this.$root;
- let curNodeChildren: Map<string, TrieNode<Meta>> = node[3];
- if (suffix[0] === '.') {
- suffix = suffix.slice(1);
- }
- const onToken = (token: string) => {
- curNodeChildren = node[3];
- if (curNodeChildren.has(token)) {
- node = curNodeChildren.get(token)!;
- // During the adding of `[start]blog|.skk.moe` and find out that there is a `[start].skk.moe` in the trie, skip adding the rest of the node
- if (node[1]) {
- return true;
- }
- } else {
- const newNode = createNode(false, node);
- curNodeChildren.set(token, newNode);
- node = newNode;
- }
- return false;
- };
- // When walkHostnameTokens returns true, we should skip the rest
- if (walkHostnameTokens(suffix, onToken)) {
- return;
- }
- // If we are in smolTree mode, we need to do something at the end of the loop
- if (includeAllSubdoain) {
- // Trying to add `[.]sub.example.com` where there is already a `blog.sub.example.com` in the trie
- // Make sure parent `[start]sub.example.com` (without dot) is removed (SETINEL to false)
- // (/** parent */ node[2]!)[0] = false;
- // Removing the rest of the parent's child nodes
- node[3].clear();
- // The SENTINEL of this node will be set to true at the end of the function, so we don't need to set it here
- // we can use else-if here, because the children is now empty, we don't need to check the leading "."
- } else if (node[1]) {
- // Trying to add `example.com` when there is already a `.example.com` in the trie
- // No need to increment size and set SENTINEL to true (skip this "new" item)
- return;
- }
- node[0] = true;
- node[1] = includeAllSubdoain;
- node[4] = meta!;
- }
- public whitelist(suffix: string, includeAllSubdoain = suffix[0] === '.') {
- if (suffix[0] === '.') {
- suffix = suffix.slice(1);
- }
- const tokens = hostnameToTokens(suffix);
- const res = this.getSingleChildLeaf(tokens);
- if (res === null) return;
- const { node, toPrune, tokenToPrune } = res;
- // Trying to whitelist `[start].sub.example.com` where there might already be a `[start]blog.sub.example.com` in the trie
- if (includeAllSubdoain) {
- // If there is a `[start]sub.example.com` here, remove it
- node[0] = false;
- node[1] = false;
- // Removing all the child nodes by empty the children
- node[3].clear();
- } else {
- // Trying to whitelist `example.com` when there is already a `.example.com` in the trie
- node[1] = false;
- }
- // return early if not found
- if (!node[0]) return;
- if (tokenToPrune && toPrune) {
- toPrune[3].delete(tokenToPrune);
- } else {
- node[0] = false;
- }
- };
- }
- export class HostnameTrie<Meta = any> extends Triebase<Meta> {
- get size() {
- return this.$size;
- }
- add(suffix: string, includeAllSubdoain = suffix[0] === '.', meta?: Meta): void {
- let node: TrieNode<Meta> = this.$root;
- const onToken = (token: string) => {
- if (node[3].has(token)) {
- node = node[3].get(token)!;
- } else {
- const newNode = createNode(false, node);
- node[3].set(token, newNode);
- node = newNode;
- }
- return false;
- };
- if (suffix[0] === '.') {
- suffix = suffix.slice(1);
- }
- // When walkHostnameTokens returns true, we should skip the rest
- if (walkHostnameTokens(suffix, onToken)) {
- return;
- }
- // if same entry has been added before, skip
- if (node[0]) {
- return;
- }
- this.$size++;
- node[0] = true;
- node[1] = includeAllSubdoain;
- node[4] = meta!;
- }
- }
- export function createTrie<Meta = any>(from: string[] | Set<string> | null, smolTree: true): HostnameSmolTrie<Meta>;
- export function createTrie<Meta = any>(from?: string[] | Set<string> | null, smolTree?: false): HostnameTrie<Meta>;
- export function createTrie<_Meta = any>(from?: string[] | Set<string> | null, smolTree = true) {
- if (smolTree) {
- return new HostnameSmolTrie(from);
- }
- return new HostnameTrie(from);
- };
- export type Trie = ReturnType<typeof createTrie>;
- // function deepEqualArray(a: string[], b: string[]) {
- // let len = a.length;
- // if (len !== b.length) return false;
- // while (len--) {
- // if (a[len] !== b[len]) return false;
- // }
- // return true;
- // };
|