All files index.ts

62.99% Statements 223/354
51.9% Branches 109/210
48.08% Functions 25/52
65.02% Lines 210/323

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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 6243x 3x                   3x               3x 3x 3x   3x     212x 212x     88x 88x     8x 8x                         3x   3x   413x   3x 19x   3x 332x 52x 52x   315x     3x 45x 97x 97x 97x 84x 1x 1x       83x 83x         13x 13x     44x     3x 76x 134x 134x 134x 122x 121x 1x   120x 17x 2x   15x 3x           103x 74x 2x   72x 27x             116x 58x   116x 116x     12x 12x         3x                                                             3x 12x     12x 23x 23x 23x 21x 8x     13x 13x 13x         13x 2x     2x                   3x 332x                   332x 269x 3x               266x 266x 265x 210x 210x                   55x                   63x   63x 62x     163x             1x 1x                                       3x 163x 155x 155x 155x 154x   1x   8x     8x     3x                       177x   177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x 177x     3x       3x 5x     3x       177x                   177x                   177x       177x             177x                           177x             177x             177x                   177x       177x                                                     177x                           177x 121x 121x 121x 1x 1x   1x   120x 118x 118x   120x               120x 114x 2x   112x     112x     112x 112x   6x     6x     6x 6x           177x 9x 9x 9x 9x 9x 9x 9x 7x 3x   4x     2x       177x 6x     177x 17x     177x 18x 18x     177x         177x                 3x                   3x               476x 476x 18x 18x 5x   13x 13x   458x     458x 458x 458x 458x 332x   126x 126x 126x         3x 17x 17x     3x 18x 18x     3x         3x 6x 6x     3x         3x                 3x   3x  
import { Parser } from './parser'
import {
  isStr,
  isArr,
  isFn,
  isEqual,
  isObj,
  isNum,
  isRegExp,
  isPlainObj,
} from './utils'
import {
  getDestructor,
  getInByDestructor,
  setInByDestructor,
  deleteInByDestructor,
  existInByDestructor,
} from './destructor'
import { Segments, Node, Pattern, IRegistry, IAccessors } from './types'
export * from './types'
import { LRUMap } from './lru'
import { Matcher } from './matcher'
 
const REGISTRY: IRegistry = {
  accessors: {
    get(source: any, key: number | string | symbol) {
      Iif (typeof source !== 'object') return source
      return Reflect.get(source, key)
    },
    set(source: any, key: number | string | symbol, value: any) {
      Iif (typeof source !== 'object') return
      return Reflect.set(source, key, value)
    },
    has(source: any, key: number | string | symbol) {
      Iif (typeof source !== 'object') return
      return Reflect.has(source, key)
    },
    delete(source: any, key: number | string | symbol) {
      if (typeof source !== 'object') return
      if (Array.isArray(source) && isNumberIndex(key)) {
        source.splice(Number(key), 1)
        return true
      }
      return Reflect.deleteProperty(source, key)
    },
  },
}
 
const pathCache = new LRUMap(1000)
 
const isMatcher = Symbol('PATH_MATCHER')
 
const isValid = (val: any) => val !== undefined && val !== null
 
const isNumberIndex = (val: any) =>
  isStr(val) ? /^\d+$/.test(val) : isNum(val)
 
const arrayExist = (obj: any, key: string | number) => {
  if (Array.isArray(obj)) {
    const index = Number(key)
    if (index < 0 || index > obj.length - 1) return false
  }
  return true
}
 
const getIn = (segments: Segments, source: any) => {
  for (let i = 0; i < segments.length; i++) {
    let index = segments[i]
    const rules = getDestructor(index as string)
    if (!rules) {
      if (!isValid(source)) {
        Eif (i !== segments.length - 1) {
          return source
        }
        break
      }
      Eif (arrayExist(source, index)) {
        source = REGISTRY.accessors.get(source, index)
      } else {
        return
      }
    } else {
      source = getInByDestructor(source, rules, { setIn, getIn })
      break
    }
  }
  return source
}
 
const setIn = (segments: Segments, source: any, value: any) => {
  for (let i = 0; i < segments.length; i++) {
    const index = segments[i]
    const rules = getDestructor(index as string)
    if (!rules) {
      if (!isValid(source)) return
      if (isArr(source) && !isNumberIndex(index)) {
        return
      }
      if (!arrayExist(source, index)) {
        if (!isValid(value)) {
          return
        }
        if (i < segments.length - 1) {
          REGISTRY.accessors.set(
            source,
            index,
            isNum(segments[i + 1]) ? [] : {}
          )
        }
      } else if (!isValid(source[index])) {
        if (!isValid(value)) {
          return
        }
        if (i < segments.length - 1) {
          REGISTRY.accessors.set(
            source,
            index,
            isNum(segments[i + 1]) ? [] : {}
          )
        }
      }
      if (i === segments.length - 1) {
        REGISTRY.accessors.set(source, index, value)
      }
      Eif (arrayExist(source, index)) {
        source = REGISTRY.accessors.get(source, index)
      }
    } else {
      setInByDestructor(source, rules, value, { setIn, getIn })
      break
    }
  }
}
 
const deleteIn = (segments: Segments, source: any) => {
  for (let i = 0; i < segments.length; i++) {
    let index = segments[i]
    const rules = getDestructor(index as string)
    if (!rules) {
      if (i === segments.length - 1 && isValid(source)) {
        REGISTRY.accessors.delete(source, index)
        return
      }
 
      if (!isValid(source)) return
      if (arrayExist(source, index)) {
        source = REGISTRY.accessors.get(source, index)
      } else {
        return
      }
 
      if (!isObj(source)) {
        return
      }
    } else {
      deleteInByDestructor(source, rules, {
        setIn,
        getIn,
        deleteIn,
      })
      break
    }
  }
}
 
const existIn = (segments: Segments, source: any, start: number | Path) => {
  Iif (start instanceof Path) {
    start = start.length
  }
  for (let i = start; i < segments.length; i++) {
    let index = segments[i]
    const rules = getDestructor(index as string)
    if (!rules) {
      if (i === segments.length - 1) {
        return REGISTRY.accessors.has(source, index)
      }
 
      Iif (!isValid(source)) return false
      Eif (arrayExist(source, index)) {
        source = REGISTRY.accessors.get(source, index)
      } else {
        return false
      }
 
      if (!isObj(source)) {
        return false
      }
    } else {
      return existInByDestructor(source, rules, start, {
        setIn,
        getIn,
        deleteIn,
        existIn,
      })
    }
  }
}
 
const parse = (pattern: Pattern, base?: Pattern) => {
  Iif (pattern instanceof Path) {
    return {
      entire: pattern.entire,
      segments: pattern.segments.slice(),
      isRegExp: false,
      isWildMatchPattern: pattern.isWildMatchPattern,
      isMatchPattern: pattern.isMatchPattern,
      haveExcludePattern: pattern.haveExcludePattern,
      tree: pattern.tree,
    }
  } else if (isStr(pattern)) {
    if (!pattern)
      return {
        entire: '',
        segments: [],
        isRegExp: false,
        isWildMatchPattern: false,
        haveExcludePattern: false,
        isMatchPattern: false,
      }
    const parser = new Parser(pattern, Path.parse(base))
    const tree = parser.parse()
    if (!parser.isMatchPattern) {
      const segments = parser.data.segments
      return {
        entire: segments.join('.'),
        segments,
        tree,
        isRegExp: false,
        isWildMatchPattern: false,
        haveExcludePattern: false,
        isMatchPattern: false,
      }
    } else {
      return {
        entire: pattern,
        segments: [],
        isRegExp: false,
        isWildMatchPattern: parser.isWildMatchPattern,
        haveExcludePattern: parser.haveExcludePattern,
        isMatchPattern: true,
        tree,
      }
    }
  } else Iif (isFn(pattern) && pattern[isMatcher]) {
    return parse(pattern['path'])
  } else if (isArr(pattern)) {
    return {
      entire: pattern.join('.'),
      segments: pattern.reduce((buf, key) => {
        return buf.concat(parseString(key))
      }, []),
      isRegExp: false,
      isWildMatchPattern: false,
      haveExcludePattern: false,
      isMatchPattern: false,
    }
  } else Eif (isRegExp(pattern)) {
    return {
      entire: pattern,
      segments: [],
      isRegExp: true,
      isWildMatchPattern: false,
      haveExcludePattern: false,
      isMatchPattern: true,
    }
  } else {
    return {
      entire: '',
      isRegExp: false,
      segments: pattern !== undefined ? [pattern] : [],
      isWildMatchPattern: false,
      haveExcludePattern: false,
      isMatchPattern: false,
    }
  }
}
 
const parseString = (source: any) => {
  if (isStr(source)) {
    source = source.replace(/\s*/g, '')
    try {
      const { segments, isMatchPattern } = parse(source)
      return !isMatchPattern ? segments : source
    } catch (e) {
      return source
    }
  } else Iif (source instanceof Path) {
    return source.segments
  }
  return source
}
 
export class Path {
  public entire: string | RegExp
  public segments: Segments
  public isMatchPattern: boolean
  public isWildMatchPattern: boolean
  public isRegExp: boolean
  public haveExcludePattern: boolean
  public matchScore: number
  public tree: Node
  private matchCache: any
  private includesCache: any
 
  constructor(input: Pattern, base?: Pattern) {
    const {
      tree,
      segments,
      entire,
      isRegExp,
      isMatchPattern,
      isWildMatchPattern,
      haveExcludePattern,
    } = parse(input, base)
    this.entire = entire
    this.segments = segments
    this.isMatchPattern = isMatchPattern
    this.isWildMatchPattern = isWildMatchPattern
    this.isRegExp = isRegExp
    this.haveExcludePattern = haveExcludePattern
    this.tree = tree as Node
    this.matchCache = new LRUMap(200)
    this.includesCache = new LRUMap(200)
  }
 
  toString() {
    return this.entire?.toString()
  }
 
  toArray() {
    return this.segments?.slice()
  }
 
  get length() {
    return this.segments.length
  }
 
  concat = (...args: Pattern[]) => {
    if (this.isMatchPattern || this.isRegExp) {
      throw new Error(`${this.entire} cannot be concat`)
    }
    const path = new Path('')
    path.segments = this.segments.concat(...args.map((s) => parseString(s)))
    path.entire = path.segments.join('.')
    return path
  }
 
  slice = (start?: number, end?: number) => {
    if (this.isMatchPattern || this.isRegExp) {
      throw new Error(`${this.entire} cannot be slice`)
    }
    const path = new Path('')
    path.segments = this.segments.slice(start, end)
    path.entire = path.segments.join('.')
    return path
  }
 
  push = (...items: Pattern[]) => {
    return this.concat(...items)
  }
 
  pop = () => {
    if (this.isMatchPattern || this.isRegExp) {
      throw new Error(`${this.entire} cannot be pop`)
    }
    return new Path(this.segments.slice(0, this.segments.length - 1))
  }
 
  splice = (
    start: number,
    deleteCount?: number,
    ...items: Array<string | number>
  ) => {
    if (this.isMatchPattern || this.isRegExp) {
      throw new Error(`${this.entire} cannot be splice`)
    }
    items = items.reduce((buf, item) => buf.concat(parseString(item)), [])
    const segments_ = this.segments.slice()
    segments_.splice(start, deleteCount, ...items)
    return new Path(segments_)
  }
 
  forEach = (callback: (key: string | number) => any) => {
    if (this.isMatchPattern || this.isRegExp) {
      throw new Error(`${this.entire} cannot be each`)
    }
    this.segments.forEach(callback)
  }
 
  map = (callback: (key: string | number) => any) => {
    if (this.isMatchPattern || this.isRegExp) {
      throw new Error(`${this.entire} cannot be map`)
    }
    return this.segments.map(callback)
  }
 
  reduce = <T>(
    callback: (buf: T, item: string | number, index: number) => T,
    initial: T
  ): T => {
    if (this.isMatchPattern || this.isRegExp) {
      throw new Error(`${this.entire} cannot be reduce`)
    }
    return this.segments.reduce(callback, initial)
  }
 
  parent = () => {
    return this.slice(0, this.length - 1)
  }
 
  includes = (pattern: Pattern) => {
    const { entire, segments, isMatchPattern } = Path.parse(pattern)
    const cache = this.includesCache.get(entire)
    if (cache !== undefined) return cache
    const cacheWith = (value: boolean): boolean => {
      this.includesCache.set(entire, value)
      return value
    }
    if (this.isMatchPattern) {
      if (!isMatchPattern) {
        return cacheWith(this.match(segments))
      } else {
        throw new Error(`${this.entire} cannot be used to match ${entire}`)
      }
    }
    if (isMatchPattern) {
      throw new Error(`${this.entire} cannot be used to match ${entire}`)
    }
    if (segments.length > this.segments.length) return cacheWith(false)
    for (let i = 0; i < segments.length; i++) {
      if (!isEqual(String(segments[i]), String(this.segments[i]))) {
        return cacheWith(false)
      }
    }
    return cacheWith(true)
  }
 
  transform = <T>(
    regexp: string | RegExp,
    callback: (...args: string[]) => T
  ): T | string => {
    if (!isFn(callback)) return ''
    if (this.isMatchPattern) {
      throw new Error(`${this.entire} cannot be transformed`)
    }
    const args = this.segments.reduce((buf, key) => {
      return new RegExp(regexp).test(key as string) ? buf.concat(key) : buf
    }, [])
    return callback(...args)
  }
 
  match = (pattern: Pattern): boolean => {
    const path = Path.parse(pattern)
    const cache = this.matchCache.get(path.entire)
    if (cache !== undefined) {
      Eif (cache.record && cache.record.score !== undefined) {
        this.matchScore = cache.record.score
      }
      return cache.matched
    }
    const cacheWith = (value: any) => {
      this.matchCache.set(path.entire, value)
      return value
    }
    Iif (path.isMatchPattern) {
      if (this.isMatchPattern) {
        throw new Error(`${path.entire} cannot match ${this.entire}`)
      } else {
        this.matchScore = 0
        return cacheWith(path.match(this.segments))
      }
    } else {
      if (this.isMatchPattern) {
        if (this.isRegExp) {
          return this['entire']?.['test']?.(path.entire)
        }
        const record = {
          score: 0,
        }
        const result = cacheWith(
          new Matcher(this.tree, record).match(path.segments)
        )
        this.matchScore = record.score
        return result.matched
      } else {
        const record = {
          score: 0,
        }
        const result = cacheWith(
          Matcher.matchSegments(this.segments, path.segments, record)
        )
        this.matchScore = record.score
        return result.matched
      }
    }
  }
 
  //别名组匹配
  matchAliasGroup = (name: Pattern, alias: Pattern) => {
    const namePath = Path.parse(name)
    const aliasPath = Path.parse(alias)
    const nameMatched = this.match(namePath)
    const nameMatchedScore = this.matchScore
    const aliasMatched = this.match(aliasPath)
    const aliasMatchedScore = this.matchScore
    if (this.haveExcludePattern) {
      if (nameMatchedScore >= aliasMatchedScore) {
        return nameMatched
      } else {
        return aliasMatched
      }
    } else {
      return nameMatched || aliasMatched
    }
  }
 
  existIn = (source?: any, Estart: number | Path = 0) => {
    return existIn(this.segments, source, start)
  }
 
  getIn = (source?: any) => {
    return getIn(this.segments, source)
  }
 
  setIn = (source?: any, value?: any) => {
    setIn(this.segments, source, value)
    return source
  }
 
  deleteIn = (source?: any) => {
    deleteIn(this.segments, source)
    return source
  }
 
  ensureIn = (source?: any, defaults?: any) => {
    const results = this.getIn(source)
    if (results === undefined) {
      this.setIn(source, defaults)
      return this.getIn(source)
    }
    return results
  }
 
  static match(pattern: Pattern) {
    const path = Path.parse(pattern)
    const matcher = (target) => {
      return path.match(target)
    }
    matcher[isMatcher] = true
    matcher.path = path
    return matcher
  }
 
  static transform<T>(
    pattern: Pattern,
    regexp: string | RegExp,
    callback: (...args: string[]) => T
  ): any {
    return Path.parse(pattern).transform(regexp, callback)
  }
 
  static parse(path: Pattern = '', base?: Pattern): Path {
    if (path instanceof Path) {
      const found = pathCache.get(path.entire)
      if (found) {
        return found
      } else {
        pathCache.set(path.entire, path)
        return path
      }
    } else Iif (path && path[isMatcher]) {
      return Path.parse(path['path'])
    } else {
      const key_ = base ? Path.parse(base) : ''
      const key = `${path}:${key_}`
      const found = pathCache.get(key)
      if (found) {
        return found
      } else {
        path = new Path(path, base)
        pathCache.set(key, path)
        return path
      }
    }
  }
 
  static getIn = (source: any, pattern: Pattern) => {
    const path = Path.parse(pattern)
    return path.getIn(source)
  }
 
  static setIn = (source: any, pattern: Pattern, value: any) => {
    const path = Path.parse(pattern)
    return path.setIn(source, value)
  }
 
  static deleteIn = (source: any, pattern: Pattern) => {
    const path = Path.parse(pattern)
    return path.deleteIn(source)
  }
 
  static existIn = (source: any, pattern: Pattern, start?: number | Path) => {
    const path = Path.parse(pattern)
    return path.existIn(source, start)
  }
 
  static ensureIn = (source: any, pattern: Pattern, defaultValue?: any) => {
    const path = Path.parse(pattern)
    return path.ensureIn(source, defaultValue)
  }
 
  static registerAccessors = (accessors: IAccessors) => {
    if (isPlainObj(accessors)) {
      for (let name in accessors) {
        if (isFn(accessors[name])) {
          REGISTRY.accessors[name] = accessors[name]
        }
      }
    }
  }
}
 
export default Path