All files / jit-router/src tree.ts

88.54% Statements 116/131
76.34% Branches 71/93
56.25% Functions 18/32
88.52% Lines 108/122

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 2416x 6x   6x     6x 6x   6x 78x     6x 121x 121x 121x 121x       221x 221x 221x 126x 35x 35x 35x   91x 91x   53x 53x 53x     95x 90x 45x   90x 59x 59x   90x 45x   45x   5x 5x 2x   3x   2x         3x 1x   2x 2x 2x             90x 90x 16x 3x   9x     9x     18x 18x             13x 17x 17x 17x   17x           90x 7x   90x 151x 151x 151x 151x 151x 61x   151x 151x 53x     151x 61x 90x   90x 90x 52x 59x 7x 7x 7x         52x 52x 38x 38x 38x 38x     52x           28x 28x 28x 28x           90x 3x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x                                                                                                                              
import {emitStringMatch} from '@jsonjoy.com/codegen/lib/util/helpers';
import {printTree} from 'sonic-forest/lib/print/printTree';
import type {Printable} from 'sonic-forest/lib/print/types';
import {RadixTree} from 'sonic-forest/lib/radix/RadixTree';
import type {TrieNode} from 'sonic-forest/lib/trie/TrieNode';
import type {RouterCodegenCtx, RouterCodegenOpts} from './codegen';
import {Destination, type Route} from './router';
import {ExactStep, RegexStep, UntilStep} from './steps';
 
const genExactMatchCondition = (text: string, opts: RouterCodegenOpts) => {
  return emitStringMatch('str', opts.offset, text);
};
 
export class RoutingTreeNode implements Printable {
  public readonly exact: Map<number, [step: ExactStep, destination: Destination][]> = new Map();
  public readonly start: RadixTree<RoutingTreeNode> = new RadixTree();
  public readonly until: [step: UntilStep, destination: RoutingTreeNode][] = [];
  public readonly regex: [step: RegexStep, destination: RoutingTreeNode | Destination][] = [];
  public end?: Destination;
 
  public add(route: Route, step: number, destination: Destination): void {
    const isLast = step === route.steps.length - 1;
    const match = route.steps[step];
    if (match instanceof ExactStep) {
      if (isLast) {
        const exact = this.exact.get(match.text.length) ?? [];
        exact.push([match, destination]);
        this.exact.set(match.text.length, exact);
      } else {
        const child = this.start.get(match.text);
        if (child) child.add(route, step + 1, destination);
        else {
          const node = new RoutingTreeNode();
          this.start.set(match.text, node);
          node.add(route, step + 1, destination);
        }
      }
    } else if (match instanceof UntilStep) {
      let until: [step: UntilStep, destination: RoutingTreeNode] | undefined = this.until.find(
        ([step, dest]) => step.until === match.until && step.name === match.name && dest instanceof RoutingTreeNode,
      );
      if (!until || !(until[1] instanceof RoutingTreeNode)) {
        until = [match, new RoutingTreeNode()];
        this.until.push(until);
      }
      if (isLast) {
        until[1].end = destination;
      } else {
        until[1].add(route, step + 1, destination);
      }
    } else Eif (match instanceof RegexStep) {
      if (isLast) {
        this.regex.push([match, destination]);
      } else {
        const regex = this.regex.find(
          ([step, dest]) =>
            step.regex === match.regex &&
            step.until === match.until &&
            step.name === match.name &&
            dest instanceof RoutingTreeNode,
        );
        if (regex && regex[1] instanceof RoutingTreeNode) {
          regex[1].add(route, step + 1, destination);
        } else {
          const node = new RoutingTreeNode();
          this.regex.push([match, node]);
          node.add(route, step + 1, destination);
        }
      }
    }
  }
 
  public codegen(ctx: RouterCodegenCtx, opts: RouterCodegenOpts): void {
    const code = ctx.codegen;
    if (this.exact.size) {
      if (!opts.depth) {
        code.switch(
          'len',
          [...this.exact].map(([length, destinations]) => [
            length,
            () => {
              code.switch(
                'str',
                destinations.map(([step, destination]) => {
                  const m = code.linkDependency(destination.match);
                  return [JSON.stringify(step.text), () => code.return(`${m}.params = null, ${m}`), true];
                }),
              );
            },
          ]),
        );
      } else {
        for (const destinations of this.exact.values()) {
          for (const [step, destination] of destinations) {
            const m = code.linkDependency(destination.match);
            code.if(
              `(${step.text.length} + ${opts.offset} === len) && ${genExactMatchCondition(step.text, opts)}`,
              () => code.return(`${m}.params = params, ${m}`),
            );
          }
        }
      }
    }
    if (!opts.depth) {
      code.js('var params = [];');
    }
    const emitRadixTreeNode = (node: TrieNode, opts: RouterCodegenOpts) => {
      const text = node.k;
      const length = text.length;
      const block = () => {
        const offset = length ? code.var(`${opts.offset} + ${length}`) : opts.offset;
        node.forChildren((child) => {
          emitRadixTreeNode(child, opts.create(offset));
        });
        const routingNode = node.v as RoutingTreeNode | undefined;
        if (routingNode) {
          routingNode.codegen(ctx, opts.create(offset));
        }
      };
      if (text) {
        code.if(genExactMatchCondition(text, opts), block);
      } else block();
    };
    emitRadixTreeNode(this.start, opts);
    if (this.until.length) {
      for (const [step, destination] of this.until) {
        if (destination.end && step.until === '\n') {
          const m = code.linkDependency(destination.end.match);
          Eif (step.name) code.js(`params.push(str.slice(${opts.offset}, len));`);
          code.return(`${m}.params = params, ${m}`);
        } else {
          // const ri = code.var(opts.offset);
          // code.js(`for(; ${ri} < len && str[${ri}] !== ${JSON.stringify(step.until)}; ${ri}++);`);
          // code.js(`for(; ${ri} < len && str.charCodeAt(${ri}) !== ${step.until.charCodeAt(0)}; ${ri}++);`);
          const ri = code.var(`str.indexOf(${JSON.stringify(step.until)}, ${opts.offset})`);
          if (destination.end) {
            const m = code.linkDependency(destination.end.match);
            code.if(`${ri} === -1`, () => {
              Eif (step.name) code.js(`params.push(str.slice(${opts.offset}, len));`);
              code.return(`${m}.params = params, ${m}`);
            });
          }
          if (
            destination.exact.size ||
            destination.start.size ||
            destination.until.length ||
            destination.regex.length
          ) {
            code.if(`${ri} > ${opts.offset}`, () => {
              Eif (step.name) code.js(`params.push(str.slice(${opts.offset}, ${ri}));`);
              destination.codegen(ctx, opts.create(ri));
              Eif (step.name) code.js(`params.pop();`);
            });
          }
        }
      }
    }
    if (this.regex.length) {
      for (const [step, destination] of this.regex) {
        const isDestination = destination instanceof Destination;
        const r = code.var(`str.slice(${opts.offset})`);
        const regex = new RegExp('^' + step.regex + step.until + (isDestination ? '$' : ''));
        const reg = code.linkDependency(regex);
        const match = code.var(`${r}.match(${reg})`);
        if (isDestination) {
          code.if(match, () => {
            const val = code.var(`${match}[1] || ${match}[0]`);
            const m = code.linkDependency(destination.match);
            Iif (step.name) code.js(`params.push(${val});`);
            code.return(`${m}.params = params, ${m}`);
          });
        } else {
          code.if(match, () => {
            const val = code.var(`${match}[1] || ${match}[0]`);
            const offset = code.var(`${opts.offset} + ${val}.length`);
            if (step.name) code.js(`params.push(${val});`);
            destination.codegen(ctx, opts.create(offset));
            if (step.name) code.js(`params.pop();`);
          });
        }
      }
    }
  }
 
  public toString(tab: string): string {
    return (
      `${this.constructor.name} ` +
      printTree(tab, [
        !this.exact.size
          ? null
          : (tab) =>
              'exact ' +
              printTree(
                tab,
                [...this.exact].map(
                  ([length, destinations]) =>
                    (tab) =>
                      `${length} ` +
                      printTree(
                        tab,
                        destinations.map(
                          ([step, destination]) =>
                            (tab) =>
                              `${JSON.stringify(step.toText())}${
                                destination instanceof Destination ? ' →' : ''
                              } ${destination.toString(tab + ' ')}`,
                        ),
                      ),
                ),
              ),
        !this.end ? null : (tab) => 'end → ' + this.end!.toString(tab),
        !this.start.size ? null : (tab) => 'start ' + this.start.toString(tab),
        !this.until.length
          ? null
          : (tab) =>
              'until ' +
              printTree(
                tab,
                this.until.map(
                  ([step, destination]) =>
                    (tab) =>
                      `${step.toText()}${destination instanceof Destination ? ' →' : ''} ${destination.toString(tab)}`,
                ),
              ),
        !this.regex.length
          ? null
          : (tab) =>
              'regex ' +
              printTree(
                tab,
                this.regex.map(
                  ([step, destination]) =>
                    (tab) =>
                      `${step.toText()}${destination instanceof Destination ? ' →' : ''} ${destination.toString(tab)}`,
                ),
              ),
      ])
    );
  }
}