kwhitley / itty-router

A little router.
MIT License
1.75k stars 78 forks source link

Dots are not escaped #37

Closed taralx closed 3 years ago

taralx commented 3 years ago

Example '/static/file.json' results in /static/file.json, with the extension dot unescaped. This is somewhat related to https://github.com/kwhitley/itty-router/issues/34.

taralx commented 3 years ago

Best I have for you is this mess:

RegExp(`^${
  // eslint-disable-next-line
  (base + route).replaceAll(/([/.])?(?::(\w+)(\?)?|(\*)(\.)?)|([[{()\\.?+^$|])|\/$/g, (m,p='',v,q,s,d='',c) => c?'\\'+c:(d?'':'(')+(p&&'\\'+p)+(d&&'(')+(v?`(?<${v}>[^/]+?)`:s?'.*'+(d&&'\\.'):'')+')'+(q||s?'?':''))
}/*$`),

Broken down regex:

/
  ([/.])?  # (p)refix: included in the optionality
  (?:
    :(\w+)  # (v)ariable
    (\?)?  # (q)uestion mark
  |
    (\*)  # (s)tar
    (\.)?  # (d)ot that excludes preceding / or . if present
  )
|
  ([[{()\\.?*+^$|])  # regexp characters that need quoting
|
  \/$  # trim trailing slash
/g
kwhitley commented 3 years ago

Ooof... to be fair, I don't think simple dots were ever escaped (oversight), but hopefully we can pull this fix off with minimal characters. It's already killing me that we're doing 4 regex passes in the current version (so many characters!) 😭

taralx commented 3 years ago

Yeah, the solution I posted is like 50 bytes. :(

kwhitley commented 3 years ago

I have this working and did some refactoring of the tests to more easily allow bulk route tests...

kwhitley commented 3 years ago

I'm only addressing escaping dots, as that's a pretty common use-case that I overlooked... not escaping all possible regex collisions. I'm figuring out which ones work/don't work as I go!

kwhitley commented 3 years ago

dot escaping & allowed characters

image

some barebones regex support

image