Skip to content

Commit

Permalink
Add Timeout to Finder (#79)
Browse files Browse the repository at this point in the history
* add timeout

* clearer variable name

* address feedback

* update docs
  • Loading branch information
lapritchett committed Feb 22, 2024
1 parent feef199 commit 82421db
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const selector = finder(event.target, {
optimizedMinLength: 2,
threshold: 1000,
maxNumberOfTries: 10_000,
timeoutMs: undefined,
})
```

Expand All @@ -77,6 +78,10 @@ selectors to check. Default `1000` is good enough in most cases.
Max number of tries for the optimization. This is a trade-off between
optimization and efficiency. Default `10_000` is good enough in most cases.

### timeoutMs

Optional timeout in milliseconds. `undefined` (no timeout) by default. If `timeoutMs: 500` is provided, an error will be thrown if selector generation takes more than 500ms.

## Become a sponsor

Every line of code in my repositories πŸ“– signifies my unwavering commitment to open source πŸ’‘. Your support 🀝 ensures these projects keep thriving, innovating, and benefiting all πŸ’Ό. If my work has ever resonated 🎡 or helped you, kindly consider showing love ❀️ by sponsoring. [**πŸš€ Sponsor Me Today! πŸš€**](https://github.com/sponsors/antonmedv)
Expand Down
8 changes: 8 additions & 0 deletions finder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@ export type Options = {
optimizedMinLength: number
threshold: number
maxNumberOfTries: number
timeoutMs: number | undefined
}

let config: Options
let rootDocument: Document | Element
let start: Date

export function finder(input: Element, options?: Partial<Options>) {
start = new Date()
if (input.nodeType !== Node.ELEMENT_NODE) {
throw new Error(`Can't generate CSS selector for non-element node type.`)
}
Expand All @@ -42,6 +45,7 @@ export function finder(input: Element, options?: Partial<Options>) {
optimizedMinLength: 2,
threshold: 1000,
maxNumberOfTries: 10000,
timeoutMs: undefined,
}

config = {...defaults, ...options}
Expand Down Expand Up @@ -84,6 +88,10 @@ function bottomUpSearch(
let current: Element | null = input
let i = 0
while (current) {
const elapsedTime = new Date().getTime() - start.getTime();
if (config.timeoutMs !== undefined && elapsedTime > config.timeoutMs) {
throw new Error(`Timeout: Can't find a unique selector after ${elapsedTime}ms`)
}
let level: Knot[] = maybe(id(current)) ||
maybe(...attr(current)) ||
maybe(...classNames(current)) ||
Expand Down

0 comments on commit 82421db

Please sign in to comment.