sema-url 0.1.0

URL parsing, building, resolving, and query-string manipulation

Source

package.sema

226 lines fb5a516a1f3d
File details

Source stored with sema-url 0.1.0. Line links refer to these exact bytes.

SHA-256 fb5a516a1f3db8938a59c47e1f58b37a7bc4139ca7e721b7fda667f1fd5e9fb3

1;; sema-url — URL parsing, building, resolving, and query-string manipulation
2
3(module sema-url
4  (export url/parse
5          url/build
6          url/join
7          url/absolute?
8          url/with-query
9          url/query-parse
10          url/query-build
11          url/encode
12          url/decode)
13
14  ;; -------------------------------------------------------------------------
15  ;; Private helpers
16  ;; -------------------------------------------------------------------------
17
18  (define hex-chars "0123456789ABCDEF")
19
20  ;; Integer 0-255 → two uppercase hex digits.
21  (define (to-hex2 n)
22    (string-append
23      (substring hex-chars (floor (/ n 16)) (+ (floor (/ n 16)) 1))
24      (substring hex-chars (mod n 16) (+ (mod n 16) 1))))
25
26  ;; Hex digit character → integer 0-15, or nil if not a hex digit.
27  (define (hex-digit ch)
28    (string/index-of "0123456789abcdef" (string/lower ch)))
29
30  ;; RFC 3986 unreserved bytes: ALPHA / DIGIT / "-" / "." / "_" / "~"
31  (define (unreserved-byte? b)
32    (or (and (>= b 65) (<= b 90))    ; A-Z
33        (and (>= b 97) (<= b 122))   ; a-z
34        (and (>= b 48) (<= b 57))    ; 0-9
35        (= b 45) (= b 46) (= b 95) (= b 126)))
36
37  ;; RFC 3986 remove_dot_segments over a path string.
38  (define (remove-dot-segments path)
39    (let* ((absolute (string/starts-with? path "/"))
40           (dir-like (or (string/ends-with? path "/")
41                         (string/ends-with? path "/.")
42                         (string/ends-with? path "/..")
43                         (= path ".") (= path "..")))
44           (segs (filter (fn (s) (not (= s "")))
45                         (string/split path "/")))
46           (kept (reverse
47                   (foldl (fn (acc seg)
48                            (cond
49                              ((= seg ".") acc)
50                              ((= seg "..") (if (null? acc) acc (rest acc)))
51                              (#t (cons seg acc))))
52                          (list)
53                          segs))))
54      (string-append (if absolute "/" "")
55                     (string/join kept "/")
56                     (if (and dir-like (not (null? kept))) "/" ""))))
57
58  ;; -------------------------------------------------------------------------
59  ;; Percent-encoding
60  ;; -------------------------------------------------------------------------
61
62  (define (url/encode s)
63    "Percent-encode a string for use in a URL component. Everything outside RFC 3986 unreserved characters is encoded; non-ASCII characters are encoded as their UTF-8 bytes (e.g. \"é\" → \"%C3%A9\")."
64    (string/join
65      (map (fn (b)
66             (if (unreserved-byte? b)
67               (char->string (integer->char b))
68               (string-append "%" (to-hex2 b))))
69           (bytevector/to-list (string/to-utf8 s)))
70      ""))
71
72  (define (url/decode s)
73    "Percent-decode a URL-encoded string. %XX sequences are decoded as UTF-8 bytes, + becomes a space, and a % not followed by two hex digits is kept literally."
74    (define (decode-loop i bytes)
75      (if (>= i (string-length s))
76        (utf8/to-string (list/to-bytevector (reverse bytes)))
77        (let ((ch (substring s i (+ i 1))))
78          (cond
79            ((and (= ch "%") (<= (+ i 3) (string-length s)))
80             (let ((hi (hex-digit (substring s (+ i 1) (+ i 2))))
81                   (lo (hex-digit (substring s (+ i 2) (+ i 3)))))
82               (if (or (nil? hi) (nil? lo))
83                 (decode-loop (+ i 1) (cons 37 bytes))          ; literal "%"
84                 (decode-loop (+ i 3) (cons (+ (* hi 16) lo) bytes)))))
85            ((= ch "+")
86             (decode-loop (+ i 1) (cons 32 bytes)))              ; space
87            (#t
88             (decode-loop (+ i 1)
89               (foldl (fn (acc b) (cons b acc))
90                      bytes
91                      (bytevector/to-list (string/to-utf8 ch)))))))))
92    (decode-loop 0 (list)))
93
94  ;; -------------------------------------------------------------------------
95  ;; Query strings
96  ;; -------------------------------------------------------------------------
97
98  (define (url/query-parse qs)
99    "Parse a query string like \"a=1&b=2\" into a map of decoded strings. nil or \"\" gives {}. A key without = gets value \"\"; when a key repeats, the last value wins."
100    (if (or (nil? qs) (= qs ""))
101      (hash-map)
102      (foldl (fn (acc pair)
103               (cond
104                 ((= pair "") acc)
105                 ((string/contains? pair "=")
106                  (let ((idx (string/index-of pair "=")))
107                    (assoc acc
108                           (url/decode (substring pair 0 idx))
109                           (url/decode (substring pair (+ idx 1) (string-length pair))))))
110                 (#t (assoc acc (url/decode pair) ""))))
111             (hash-map)
112             (string/split qs "&"))))
113
114  (define (url/query-build m)
115    "Build a query string from a map, percent-encoding keys and values. Keys are emitted in sorted order; non-string values go through str."
116    (string/join
117      (map (fn (key)
118             (string-append (url/encode key) "=" (url/encode (str (get m key)))))
119           (keys m))
120      "&"))
121
122  ;; -------------------------------------------------------------------------
123  ;; Parsing & building
124  ;; -------------------------------------------------------------------------
125
126  (define (url/parse url)
127    "Parse a URL into {:scheme :userinfo :host :port :path :query :fragment}. Absent parts are nil; path defaults to \"/\". :port is an integer — a non-numeric port raises an error. IPv6 host literals are not supported."
128    (let ((scheme nil) (userinfo nil) (host nil) (port nil)
129          (path "") (query nil) (fragment nil)
130          (rest-str url))
131      ;; Fragment
132      (when (string/contains? rest-str "#")
133        (let ((idx (string/index-of rest-str "#")))
134          (set! fragment (substring rest-str (+ idx 1) (string-length rest-str)))
135          (set! rest-str (substring rest-str 0 idx))))
136      ;; Query
137      (when (string/contains? rest-str "?")
138        (let ((idx (string/index-of rest-str "?")))
139          (set! query (substring rest-str (+ idx 1) (string-length rest-str)))
140          (set! rest-str (substring rest-str 0 idx))))
141      ;; Scheme
142      (when (string/contains? rest-str "://")
143        (let ((idx (string/index-of rest-str "://")))
144          (set! scheme (substring rest-str 0 idx))
145          (set! rest-str (substring rest-str (+ idx 3) (string-length rest-str)))))
146      ;; Split authority from path
147      (if (string/contains? rest-str "/")
148        (let ((idx (string/index-of rest-str "/")))
149          (set! path (substring rest-str idx (string-length rest-str)))
150          (set! rest-str (substring rest-str 0 idx)))
151        (set! path "/"))
152      ;; Userinfo (user or user:pass before @)
153      (when (string/contains? rest-str "@")
154        (let ((idx (string/index-of rest-str "@")))
155          (set! userinfo (substring rest-str 0 idx))
156          (set! rest-str (substring rest-str (+ idx 1) (string-length rest-str)))))
157      ;; Port
158      (if (string/contains? rest-str ":")
159        (let* ((idx (string/index-of rest-str ":"))
160               (port-str (substring rest-str (+ idx 1) (string-length rest-str))))
161          (set! host (substring rest-str 0 idx))
162          (if (regex/match? #"^[0-9]+$" port-str)
163            (set! port (string->number port-str))
164            (error (format "url/parse: invalid port ~a in ~a — port must be digits" port-str url))))
165        (set! host rest-str))
166      (hash-map :scheme scheme :userinfo userinfo :host host :port port
167                :path path :query query :fragment fragment)))
168
169  (define (url/build parts)
170    "Build a URL string from a parts map ({:scheme :userinfo :host :port :path :query :fragment}). nil parts are omitted; :query and :fragment are emitted verbatim (already-encoded)."
171    (let ((result ""))
172      (when (get parts :scheme)
173        (set! result (string-append result (get parts :scheme) "://")))
174      (when (get parts :userinfo)
175        (set! result (string-append result (get parts :userinfo) "@")))
176      (when (get parts :host)
177        (set! result (string-append result (get parts :host))))
178      (when (get parts :port)
179        (set! result (string-append result ":" (str (get parts :port)))))
180      (when (get parts :path)
181        (set! result (string-append result (get parts :path))))
182      (when (get parts :query)
183        (set! result (string-append result "?" (get parts :query))))
184      (when (get parts :fragment)
185        (set! result (string-append result "#" (get parts :fragment))))
186      result))
187
188  (define (url/absolute? url)
189    "Return #t when url is absolute, i.e. starts with a scheme followed by ://."
190    (regex/match? #"^[A-Za-z][A-Za-z0-9+.-]*://" url))
191
192  (define (url/with-query url params)
193    "Return url with its query string replaced by the encoded params map. An empty map removes the query; the fragment is preserved."
194    (let ((q (url/query-build params)))
195      (url/build (assoc (url/parse url) :query (if (= q "") nil q)))))
196
197  (define (url/join base ref)
198    "Resolve ref against base, RFC 3986 style. An absolute ref replaces base; an absolute path replaces base's path; a relative path resolves against the directory of base's path (with ./.. normalization). Base's query and fragment are dropped; ref's are kept."
199    (cond
200      ((= ref "") base)
201      ((url/absolute? ref) ref)
202      ((string/starts-with? ref "//")
203       (let ((scheme (get (url/parse base) :scheme)))
204         (if (nil? scheme) ref (string-append scheme ":" ref))))
205      (#t
206       (let ((b (url/parse base))
207             (r-path ref) (r-query nil) (r-frag nil))
208         (when (string/contains? r-path "#")
209           (let ((idx (string/index-of r-path "#")))
210             (set! r-frag (substring r-path (+ idx 1) (string-length r-path)))
211             (set! r-path (substring r-path 0 idx))))
212         (when (string/contains? r-path "?")
213           (let ((idx (string/index-of r-path "?")))
214             (set! r-query (substring r-path (+ idx 1) (string-length r-path)))
215             (set! r-path (substring r-path 0 idx))))
216         (let ((new-path
217                 (cond
218                   ((= r-path "") (get b :path))
219                   ((string/starts-with? r-path "/") (remove-dot-segments r-path))
220                   (#t
221                    (let* ((bp (get b :path))
222                           (dir (if (string/contains? bp "/")
223                                  (substring bp 0 (+ (string/last-index-of bp "/") 1))
224                                  "/")))
225                      (remove-dot-segments (string-append dir r-path)))))))
226           (url/build (assoc b :path new-path :query r-query :fragment r-frag))))))))