1use std::{cell::RefCell, fmt};
2
3use pathdiff::diff_paths;
4use recur_fn::{recur_fn, RecurFn};
5use regex::Regex;
6
7#[derive(Debug, Clone)]
8pub enum HttpParseError {
9 Empty(String),
10 InvalidSyntax(String, String),
11 CurrentDir,
12}
13
14impl fmt::Display for HttpParseError {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 match self {
17 Self::CurrentDir => f.write_str("Unable to read current dir"),
18 Self::Empty(rel_path) | Self::InvalidSyntax(rel_path, _) => {
19 f.write_str(format!("[{}]", rel_path).as_str())?;
20 f.write_str(match self {
21 Self::Empty(_) => "The file has no handlers",
22 Self::InvalidSyntax(_, message) => &message,
23 _ => "",
24 })
25 }
26 }
27 }
28}
29
30#[derive(Debug, Clone)]
31pub enum HTTPMethod {
32 GET,
33 POST,
34 DELETE,
35 PATCH,
36 OPTIONS,
37 ANY,
38}
39
40impl HTTPMethod {
41 pub fn from_string(value: String) -> Option<Self> {
42 match value.to_uppercase().as_str() {
43 "GET" => Some(Self::GET),
44 "POST" => Some(Self::POST),
45 "DELETE" => Some(Self::DELETE),
46 "PATCH" => Some(Self::PATCH),
47 "OPTIONS" => Some(Self::OPTIONS),
48 "ANY" => Some(Self::ANY),
49 _ => None,
50 }
51 }
52}
53
54#[derive(Debug, Clone)]
55pub struct HttpHandler {
56 pub method: HTTPMethod,
57 pub body: String,
58 pub req_param: Option<String>,
59}
60
61pub const REQ_PARAM: &str = "__req_param__";
70
71const HANDLER_REGEX: &str = r"(?m)export\s+(?:async\s+)?function\s+(\w+)\s*\((?:(\w+)(?::\s+[^)]+)?)?\)(?::\s+.+)?\s*\{|export\s+const\s+(\w+)\s*=\s*(?:async)?\s*\((?:(\w+)(?::\s+[^)]+)?)?\)(?::\s+.+)?\s*=>\s*\{";
73
74const DEFAULT_REGEX: &str = r"(?m)export\s+default\s+(?:async\s+)?function\s+\w*\s*\((?:(\w+)(?::\s+[^)]+)?)?\)(?::\s+.+)?\s*\{|export\s+default\s+(?:async)?\s*\((?:(\w+)(?::\s+[^)]+)?)?\)(?::\s+.+)?\s*=>\s*\{";
76
77pub fn http_parse(
78 content: String,
79 file_path: String,
80) -> Result<(RefCell<Vec<HttpHandler>>, String), HttpParseError> {
81 let cwd = match std::env::current_dir() {
82 Ok(cwd) => cwd,
83 Err(_) => return Err(HttpParseError::CurrentDir),
84 };
85 let rel_path = diff_paths(&file_path, cwd).unwrap();
86 let rel_path = rel_path.display().to_string();
87
88 let handlers: RefCell<Vec<HttpHandler>> = RefCell::new(Vec::new());
89 let content = content.to_string();
90
91 let result_content = RefCell::new(String::new());
92
93 let handler_regex = Regex::new(HANDLER_REGEX).unwrap();
94 let default_regex = Regex::new(DEFAULT_REGEX).unwrap();
95
96 let process_handler = |remain: &String, req_param: Option<String>| {
97 let mut brace_count = 1;
98 let mut tmp_remain = remain.clone();
99 let mut length = 0;
100
101 while brace_count > 0 {
102 let near_close_bracket = tmp_remain.find('}');
103 let near_open_bracket = tmp_remain.find('{');
104
105 let (delta, bracket_pos) = match (near_close_bracket, near_open_bracket) {
110 (Some(near_close_bracket), None) => (-1, near_close_bracket),
111 (None, Some(near_open_bracket)) => (1, near_open_bracket),
112 (Some(near_close_bracket), Some(near_open_bracket)) => {
114 if near_open_bracket > near_close_bracket {
115 (-1, near_close_bracket)
116 } else {
117 (1, near_open_bracket)
118 }
119 }
120 (None, None) => {
122 return (
123 None,
124 None,
125 Some(HttpParseError::InvalidSyntax(
126 rel_path.clone(),
127 "Unclosed bracket".to_string(),
128 )),
129 );
130 }
131 };
132 brace_count += delta;
133 length += bracket_pos + 1;
134 tmp_remain = tmp_remain[(bracket_pos + 1)..].to_string();
135 }
136 let req_decl = if let Some(req_param) = req_param.clone() {
138 if req_param.as_str() == REQ_PARAM {
139 "".to_string()
140 } else {
141 format!("let {} = {};\n", req_param, REQ_PARAM)
142 }
143 } else {
144 "".to_string()
145 };
146
147 let end = req_decl + remain[0..(length - 1)].trim();
148
149 let remain = remain[length..].to_string();
150
151 (Some(remain), Some(end), None)
152 };
153
154 let next_handler = recur_fn(
155 |next_handler, remain: String| -> (String, Option<HttpParseError>) {
156 if remain.len() <= 1 {
158 return (remain, None);
159 }
160
161 let handler = handler_regex.captures(&remain);
162 let handler = match handler {
163 Some(handler) => handler,
164 None => return (remain, None),
165 };
166
167 let method = handler
168 .get(1)
169 .or_else(|| handler.get(3))
170 .map(|method| method.as_str().to_string())
171 .unwrap();
172
173 let req_param = handler
174 .get(2)
175 .or_else(|| handler.get(4))
176 .map(|req_param| req_param.as_str().to_string());
177
178 let start_idx = handler.get(0).unwrap().start();
179 let body_idx = handler.get(0).unwrap().end();
180
181 *result_content.borrow_mut() += remain[..start_idx].trim();
182 let remain = remain[body_idx..].trim().to_string();
183
184 let (remain, body, err) = process_handler(&remain, req_param.clone());
185
186 if err.is_some() {
187 return (String::new(), err);
188 }
189
190 let (remain, body) = (remain.unwrap(), body.unwrap());
191
192 handlers.borrow_mut().push(HttpHandler {
193 method: HTTPMethod::from_string(method).unwrap(),
194 body,
195 req_param,
196 });
197
198 next_handler(remain)
199 },
200 );
201
202 match next_handler.call(content) {
203 (_, Some(err)) => Err(err),
204 (remain, None) => {
205 'l: {
206 let handler = default_regex.captures(&remain);
207 let handler = match handler {
208 Some(handler) => handler,
209 None => break 'l,
210 };
211
212 let req_param = handler
213 .get(1)
214 .or_else(|| handler.get(2))
215 .map(|req_param| req_param.as_str().to_string());
216
217 let start_idx = handler.get(0).unwrap().start();
218 let body_idx = handler.get(0).unwrap().end();
219
220 *result_content.borrow_mut() += remain[..start_idx].trim();
221 let remain = &remain[body_idx..].trim().to_string();
222
223 let (_, body, err) = process_handler(&remain, req_param.clone());
224
225 if err.is_some() {
226 break 'l;
227 }
228
229 let body = body.unwrap();
230
231 handlers.borrow_mut().push(HttpHandler {
232 method: HTTPMethod::ANY,
233 body,
234 req_param,
235 });
236 };
237
238 if handlers.borrow().len() == 0 {
239 Err(HttpParseError::Empty(rel_path))
240 } else {
241 Ok((handlers, result_content.borrow().to_string()))
242 }
243 }
244 }
245}