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
//! `JavaScript` code generation from ELO validation expressions.
//!
//! Translates ELO expressions into `JavaScript` validator functions that can be
//! used for client-side validation, ensuring the same rules apply on both the
//! server (Rust) and the client (browser/`Node.js`).
//!
//! # Example
//!
//! ```
//! use fraiseql_core::validation::js_codegen::JsCodegen;
//!
//! let codegen = JsCodegen::new();
//! let js = codegen.emit_validator("User", "age >= 18 && length(email) > 0");
//! assert!(js.contains("function validate_User"));
//! ```
/// `JavaScript` code generator for ELO expressions.
#[derive(Debug, Clone, Default)]
pub struct JsCodegen {
_private: (),
}
impl JsCodegen {
/// Create a new `JavaScript` code generator.
#[must_use]
pub const fn new() -> Self {
Self { _private: () }
}
/// Emit a `JavaScript` validator function for a single type + expression.
///
/// Returns a self-contained ES module `export function validate_<Type>(data)`.
#[must_use]
pub fn emit_validator(&self, type_name: &str, expression: &str) -> String {
let js_expr = self.elo_to_js(expression);
format!(
"export function validate_{type_name}(data) {{\n\
\x20 const errors = [];\n\
\x20 if (!({js_expr})) errors.push({{ field: null, rule: {rule_str} }});\n\
\x20 return {{ valid: errors.length === 0, errors }};\n\
}}",
rule_str = Self::js_string_literal(expression),
)
}
/// Emit a `JavaScript` module with validators for multiple types.
///
/// Each entry is `(type_name, elo_expression)`.
#[must_use]
pub fn emit_module(&self, validators: &[(&str, &str)]) -> String {
let mut parts = Vec::with_capacity(validators.len() + 1);
parts.push("// Generated by FraiseQL — do not edit manually.".to_string());
for (type_name, expression) in validators {
parts.push(String::new());
parts.push(self.emit_validator(type_name, expression));
}
parts.join("\n")
}
/// Translate an ELO expression to a `JavaScript` boolean expression.
#[must_use]
pub fn elo_to_js(&self, expression: &str) -> String {
let expr = expression.trim();
// Handle logical AND
if let Some(idx) = find_op_outside_parens(expr, "&&") {
let left = self.elo_to_js(&expr[..idx]);
let right = self.elo_to_js(&expr[idx + 2..]);
return format!("({left} && {right})");
}
// Handle logical OR
if let Some(idx) = find_op_outside_parens(expr, "||") {
let left = self.elo_to_js(&expr[..idx]);
let right = self.elo_to_js(&expr[idx + 2..]);
return format!("({left} || {right})");
}
// Handle negation
if let Some(inner) = expr.strip_prefix('!') {
let inner_js = self.elo_to_js(inner.trim());
return format!("!{inner_js}");
}
// Strip matching outer parentheses
if expr.starts_with('(') && expr.ends_with(')') && has_matching_parens(expr) {
let inner = &expr[1..expr.len() - 1];
let inner_js = self.elo_to_js(inner);
return format!("({inner_js})");
}
// Handle comparison operators
for op in &["<=", ">=", "!=", "==", "<", ">"] {
if let Some(idx) = expr.find(op) {
let left = self.elo_operand_to_js(expr[..idx].trim());
let right = self.elo_operand_to_js(expr[idx + op.len()..].trim());
let js_op = match *op {
"==" => "===",
"!=" => "!==",
other => other,
};
return format!("{left} {js_op} {right}");
}
}
// Standalone function call or value
self.elo_operand_to_js(expr)
}
/// Translate an operand (field, literal, function) to JS.
fn elo_operand_to_js(&self, operand: &str) -> String {
let operand = operand.trim();
// Numeric literal
if operand.parse::<f64>().is_ok() {
return operand.to_string();
}
// Boolean literal
if operand == "true" || operand == "false" {
return operand.to_string();
}
// Null literal
if operand == "null" {
return "null".to_string();
}
// String literal — pass through
if (operand.starts_with('"') && operand.ends_with('"'))
|| (operand.starts_with('\'') && operand.ends_with('\''))
{
return operand.to_string();
}
// Function calls
if let Some(rest) = operand.strip_prefix("length(") {
if let Some(field) = rest.strip_suffix(')') {
let field = field.trim();
return format!("(data.{field} || '').length");
}
}
if let Some(rest) = operand.strip_prefix("age(") {
if let Some(field) = rest.strip_suffix(')') {
let field = field.trim();
// Inline age calculation in JS
return format!(
"(() => {{ \
const b = new Date(data.{field}); \
const t = new Date(); \
let a = t.getFullYear() - b.getFullYear(); \
if (t.getMonth() < b.getMonth() || \
(t.getMonth() === b.getMonth() && t.getDate() < b.getDate())) a--; \
return a; \
}})()"
);
}
}
if let Some(rest) = operand.strip_prefix("matches(") {
if let Some(args) = rest.strip_suffix(')') {
let parts: Vec<&str> = args.splitn(2, ',').collect();
if parts.len() == 2 {
let field = parts[0].trim();
let pattern = parts[1].trim();
return format!("new RegExp({pattern}).test(data.{field})");
}
}
}
if let Some(rest) = operand.strip_prefix("contains(") {
if let Some(args) = rest.strip_suffix(')') {
let parts: Vec<&str> = args.splitn(2, ',').collect();
if parts.len() == 2 {
let field = parts[0].trim();
let needle = parts[1].trim();
return format!("(data.{field} || '').includes({needle})");
}
}
}
// Field reference (dot notation supported)
format!("data.{operand}")
}
/// Produce a JS string literal (double-quoted, escaped).
///
/// JSON string syntax is a subset of `JavaScript`'s, so `serde_json` is a
/// correct JS string escaper — and unlike the three-character replacement
/// chain it replaced, it covers `\r`, `\t` and the C0 control characters
/// that would otherwise terminate the literal (#719's class).
fn js_string_literal(s: &str) -> String {
serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string())
}
}
/// Find a two-char operator outside of parentheses and quotes.
fn find_op_outside_parens(expr: &str, op: &str) -> Option<usize> {
let mut depth = 0i32;
let mut in_string = false;
let bytes = expr.as_bytes();
for i in 0..bytes.len() {
let ch = bytes[i];
if ch == b'"' || ch == b'\'' {
in_string = !in_string;
continue;
}
if in_string {
continue;
}
if ch == b'(' {
depth += 1;
} else if ch == b')' {
depth -= 1;
} else if depth == 0 && i + op.len() <= bytes.len() && &expr[i..i + op.len()] == op {
return Some(i);
}
}
None
}
/// Check if the outer parens of `expr` match (i.e. `(...)` not `(...) op (...)`).
fn has_matching_parens(expr: &str) -> bool {
let mut depth = 0i32;
for (i, ch) in expr.chars().enumerate() {
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 && i < expr.len() - 1 {
return false;
}
},
_ => {},
}
}
depth == 0
}