0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 10:51:01 +00:00
hono/deno_dist/router/reg-exp-router/trie.ts

75 lines
2.0 KiB
TypeScript
Raw Normal View History

import type { ParamAssocArray, Context } from './node.ts'
2022-07-02 06:09:45 +00:00
import { Node } from './node.ts'
export type ReplacementMap = number[]
export class Trie {
context: Context = { varIndex: 0 }
root: Node = new Node()
2022-07-02 06:09:45 +00:00
insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {
const paramAssoc: ParamAssocArray = []
2022-07-02 06:09:45 +00:00
const groups: [string, string][] = [] // [mark, original string]
for (let i = 0; ; ) {
let replaced = false
path = path.replace(/\{[^}]+\}/g, (m) => {
const mark = `@\\${i}`
groups[i] = [mark, m]
i++
replaced = true
return mark
})
if (!replaced) {
break
}
}
2022-07-02 06:09:45 +00:00
/**
* - pattern (:label, :label{0-9]+}, ...)
* - /* wildcard
* - character
*/
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i]
for (let j = tokens.length - 1; j >= 0; j--) {
if (tokens[j].indexOf(mark) !== -1) {
tokens[j] = tokens[j].replace(mark, groups[i][1])
break
}
}
}
this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly)
2022-07-02 06:09:45 +00:00
return paramAssoc
2022-07-02 06:09:45 +00:00
}
buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {
let regexp = this.root.buildRegExpStr()
if (regexp === '') {
return [/^$/, [], []] // never match
}
2022-07-02 06:09:45 +00:00
let captureIndex = 0
const indexReplacementMap: ReplacementMap = []
const paramReplacementMap: ReplacementMap = []
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
if (typeof handlerIndex !== 'undefined') {
indexReplacementMap[++captureIndex] = Number(handlerIndex)
return '$()'
}
if (typeof paramIndex !== 'undefined') {
paramReplacementMap[Number(paramIndex)] = ++captureIndex
return ''
}
return ''
})
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]
}
}