Skip to content
Myr

refactor(router): use `#` for private props to reduce the minified file size (#3660)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by EdamAmex · committed by GitHub · parent 7e17b76 · Browse files · 7 files+93 added−90 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+93 added−90 removed

  • other:+93 added−90 removed

7 files+93 added−90 removed

modified:src/router/linear-router/router.ts+4 added-4 removed
modified:src/router/reg-exp-router/node.ts+19 added-19 removed
41 unmodified lines
42 return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length43}4445export class Node {46 index?: number47 varIndex?: number48 children: Record<string, Node> = Object.create(null)46 #index?: number47 #varIndex?: number48 #children: Record<string, Node> = Object.create(null)4950 insert(51 tokens: readonly string[],52 index: number,
1 unmodified line
54 context: Context,55 pathErrorCheckOnly: boolean56 ): void {57 if (tokens.length === 0) {58 if (this.index !== undefined) {58 if (this.#index !== undefined) {59 throw PATH_ERROR60 }61 if (pathErrorCheckOnly) {62 return63 }6465 this.index = index65 this.#index = index66 return67 }6869 const [token, ...restTokens] = tokens
17 unmodified lines
87 throw PATH_ERROR88 }89 }9091 node = this.children[regexpStr]91 node = this.#children[regexpStr]92 if (!node) {93 if (94 Object.keys(this.children).some(94 Object.keys(this.#children).some(95 (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR96 )97 ) {98 throw PATH_ERROR99 }100 if (pathErrorCheckOnly) {101 return102 }103 node = this.children[regexpStr] = new Node()103 node = this.#children[regexpStr] = new Node()104 if (name !== '') {105 node.varIndex = context.varIndex++105 node.#varIndex = context.varIndex++106 }107 }108 if (!pathErrorCheckOnly && name !== '') {109 paramMap.push([name, node.varIndex as number])109 paramMap.push([name, node.#varIndex as number])110 }111 } else {112 node = this.children[token]112 node = this.#children[token]113 if (!node) {114 if (115 Object.keys(this.children).some(115 Object.keys(this.#children).some(116 (k) =>117 k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR118 )119 ) {
1 unmodified line
121 }122 if (pathErrorCheckOnly) {123 return124 }125 node = this.children[token] = new Node()125 node = this.#children[token] = new Node()126 }127 }128129 node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly)130 }131132 buildRegExpStr(): string {133 const childKeys = Object.keys(this.children).sort(compareKey)133 const childKeys = Object.keys(this.#children).sort(compareKey)134135 const strList = childKeys.map((k) => {136 const c = this.children[k]136 const c = this.#children[k]137 return (138 (typeof c.varIndex === 'number'139 ? `(${k})@${c.varIndex}`138 (typeof c.#varIndex === 'number'139 ? `(${k})@${c.#varIndex}`140 : regExpMetaChars.has(k)141 ? `\\${k}`142 : k) + c.buildRegExpStr()143 )144 })145146 if (typeof this.index === 'number') {147 strList.unshift(`#${this.index}`)146 if (typeof this.#index === 'number') {147 strList.unshift(`#${this.#index}`)148 }149150 if (strList.length === 0) {151 return ''
8 unmodified lines
modified:src/router/reg-exp-router/router.ts+10 added-9 removed
121 unmodified lines
122}123124export class RegExpRouter<T> implements Router<T> {125 name: string = 'RegExpRouter'126 middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>127 routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>126 #middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>127 #routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>128129 constructor() {130 this.middleware = { [METHOD_NAME_ALL]: Object.create(null) }131 this.routes = { [METHOD_NAME_ALL]: Object.create(null) }130 this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }131 this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }132 }133134 add(method: string, path: string, handler: T) {135 const { middleware, routes } = this135 const middleware = this.#middleware136 const routes = this.#routes137138 if (!middleware || !routes) {139 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)140 }
91 unmodified lines
232233 #buildAllMatchers(): Record<string, Matcher<T> | null> {234 const matchers: Record<string, Matcher<T> | null> = Object.create(null)235235 Object.keys(this.routes!)236 .concat(Object.keys(this.middleware!))236 Object.keys(this.#routes!)237 .concat(Object.keys(this.#middleware!))238 .forEach((method) => {239 matchers[method] ||= this.#buildMatcher(method)240 })241242 // Release cache242 this.middleware = this.routes = undefined243 this.#middleware = this.#routes = undefined244245 return matchers246 }247
1 unmodified line
249 const routes: [string, HandlerWithMetadata<T>[]][] = []250251 let hasOwnRoute = method === METHOD_NAME_ALL252252 ;[this.middleware!, this.routes!].forEach((r) => {253 ;[this.#middleware!, this.#routes!].forEach((r) => {254 const ownRoute = r[method]255 ? Object.keys(r[method]).map((path) => [path, r[method][path]])256 : []257 if (ownRoute.length !== 0) {
19 unmodified lines
modified:src/router/reg-exp-router/trie.ts+4 added-4 removed
2 unmodified lines
34export type ReplacementMap = number[]56export class Trie {7 context: Context = { varIndex: 0 }8 root: Node = new Node()7 #context: Context = { varIndex: 0 }8 #root: Node = new Node()910 insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {11 const paramAssoc: ParamAssocArray = []12
27 unmodified lines
40 }41 }42 }4344 this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly)44 this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly)4546 return paramAssoc47 }4849 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {50 let regexp = this.root.buildRegExpStr()50 let regexp = this.#root.buildRegExpStr()51 if (regexp === '') {52 return [/^$/, [], []] // never match53 }54
20 unmodified lines
modified:src/router/smart-router/router.ts+14 added-12 removed
1 unmodified line
2import { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from '../../router'34export class SmartRouter<T> implements Router<T> {5 name: string = 'SmartRouter'6 routers: Router<T>[] = []7 routes?: [string, string, T][] = []6 #routers: Router<T>[] = []7 #routes?: [string, string, T][] = []89 constructor(init: Pick<SmartRouter<T>, 'routers'>) {10 Object.assign(this, init)9 constructor(init: { routers: Router<T>[] }) {10 this.#routers = init.routers11 }1213 add(method: string, path: string, handler: T) {14 if (!this.routes) {14 if (!this.#routes) {15 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)16 }1718 this.routes.push([method, path, handler])18 this.#routes.push([method, path, handler])19 }2021 match(method: string, path: string): Result<T> {22 if (!this.routes) {22 if (!this.#routes) {23 throw new Error('Fatal error')24 }2526 const { routers, routes } = this26 const routers = this.#routers27 const routes = this.#routes2829 const len = routers.length30 let i = 031 let res32 for (; i < len; i++) {
10 unmodified lines
43 throw e44 }4546 this.match = router.match.bind(router)45 this.routers = [router]46 this.routes = undefined47 this.#routers = [router]48 this.#routes = undefined49 break50 }5152 if (i === len) {
7 unmodified lines
60 return res as Result<T>61 }6263 get activeRouter(): Router<T> {62 if (this.routes || this.routers.length !== 1) {64 if (this.#routes || this.#routers.length !== 1) {65 throw new Error('No active router has been determined yet.')66 }6766 return this.routers[0]68 return this.#routers[0]69 }70}
modified:src/router/trie-router/node.ts+37 added-37 removed
12 unmodified lines
13 params: Record<string, string>14}1516export class Node<T> {17 methods: Record<string, HandlerSet<T>>[]17 #methods: Record<string, HandlerSet<T>>[]1819 children: Record<string, Node<T>>20 patterns: Pattern[]21 order: number = 022 params: Record<string, string> = Object.create(null)19 #children: Record<string, Node<T>>20 #patterns: Pattern[]21 #order: number = 022 #params: Record<string, string> = Object.create(null)2324 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {25 this.children = children || Object.create(null)26 this.methods = []25 this.#children = children || Object.create(null)26 this.#methods = []27 if (method && handler) {28 const m: Record<string, HandlerSet<T>> = Object.create(null)29 m[method] = { handler, possibleKeys: [], score: 0 }30 this.methods = [m]30 this.#methods = [m]31 }32 this.patterns = []32 this.#patterns = []33 }3435 insert(method: string, path: string, handler: T): Node<T> {36 this.order = ++this.order36 this.#order = ++this.#order3738 // eslint-disable-next-line @typescript-eslint/no-this-alias39 let curNode: Node<T> = this40 const parts = splitRoutingPath(path)
2 unmodified lines
4344 for (let i = 0, len = parts.length; i < len; i++) {45 const p: string = parts[i]4647 if (Object.keys(curNode.children).includes(p)) {48 curNode = curNode.children[p]47 if (Object.keys(curNode.#children).includes(p)) {48 curNode = curNode.#children[p]49 const pattern = getPattern(p)50 if (pattern) {51 possibleKeys.push(pattern[1])52 }53 continue54 }5556 curNode.children[p] = new Node()56 curNode.#children[p] = new Node()5758 const pattern = getPattern(p)59 if (pattern) {60 curNode.patterns.push(pattern)60 curNode.#patterns.push(pattern)61 possibleKeys.push(pattern[1])62 }63 curNode = curNode.children[p]63 curNode = curNode.#children[p]64 }6566 const m: Record<string, HandlerSet<T>> = Object.create(null)6768 const handlerSet: HandlerSet<T> = {69 handler,70 possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),71 score: this.order,71 score: this.#order,72 }7374 m[method] = handlerSet75 curNode.methods.push(m)75 curNode.#methods.push(m)7677 return curNode78 }79
4 unmodified lines
84 nodeParams: Record<string, string>,85 params: Record<string, string>86 ): HandlerParamsSet<T>[] {87 const handlerSets: HandlerParamsSet<T>[] = []88 for (let i = 0, len = node.methods.length; i < len; i++) {89 const m = node.methods[i]88 for (let i = 0, len = node.#methods.length; i < len; i++) {89 const m = node.#methods[i]90 const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet<T>91 const processedSet: Record<number, boolean> = {}92 if (handlerSet !== undefined) {93 handlerSet.params = Object.create(null)
12 unmodified lines
106 }107108 search(method: string, path: string): [[T, Params][]] {109 const handlerSets: HandlerParamsSet<T>[] = []110 this.params = Object.create(null)110 this.#params = Object.create(null)111112 // eslint-disable-next-line @typescript-eslint/no-this-alias113 const curNode: Node<T> = this114 let curNodes = [curNode]
5 unmodified lines
120 const tempNodes: Node<T>[] = []121122 for (let j = 0, len2 = curNodes.length; j < len2; j++) {123 const node = curNodes[j]124 const nextNode = node.children[part]124 const nextNode = node.#children[part]125126 if (nextNode) {127 nextNode.params = node.params127 nextNode.#params = node.#params128 if (isLast) {129 // '/hello/*' => match '/hello'130 if (nextNode.children['*']) {130 if (nextNode.#children['*']) {131 handlerSets.push(132 ...this.#getHandlerSets(133 nextNode.children['*'],133 nextNode.#children['*'],134 method,135 node.params,135 node.#params,136 Object.create(null)137 )138 )139 }140 handlerSets.push(141 ...this.#getHandlerSets(nextNode, method, node.params, Object.create(null))141 ...this.#getHandlerSets(nextNode, method, node.#params, Object.create(null))142 )143 } else {144 tempNodes.push(nextNode)145 }146 }147148 for (let k = 0, len3 = node.patterns.length; k < len3; k++) {149 const pattern = node.patterns[k]148 for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {149 const pattern = node.#patterns[k]150151 const params = { ...node.params }151 const params = { ...node.#params }152153 // Wildcard154 // '/hello/*/foo' => match /hello/bar/foo155 if (pattern === '*') {156 const astNode = node.children['*']156 const astNode = node.#children['*']157 if (astNode) {158 handlerSets.push(159 ...this.#getHandlerSets(astNode, method, node.params, Object.create(null))159 ...this.#getHandlerSets(astNode, method, node.#params, Object.create(null))160 )161 tempNodes.push(astNode)162 }163 continue
4 unmodified lines
168 }169170 const [key, name, matcher] = pattern171172 const child = node.children[key]172 const child = node.#children[key]173174 // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js175 const restPathString = parts.slice(i).join('/')176 if (matcher instanceof RegExp && matcher.test(restPathString)) {177 params[name] = restPathString178 handlerSets.push(...this.#getHandlerSets(child, method, node.params, params))178 handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params))179 continue180 }181182 if (matcher === true || matcher.test(part)) {183 params[name] = part184 if (isLast) {185 handlerSets.push(...this.#getHandlerSets(child, method, params, node.params))186 if (child.children['*']) {185 handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params))186 if (child.#children['*']) {187 handlerSets.push(188 ...this.#getHandlerSets(child.children['*'], method, params, node.params)188 ...this.#getHandlerSets(child.#children['*'], method, params, node.#params)189 )190 }191 } else {192 child.params = params192 child.#params = params193 tempNodes.push(child)194 }195 }196 }
11 unmodified lines
modified:src/router/trie-router/router.ts+5 added-5 removed