Skip to main content

pakem_blade/
lib.rs

1use regex::Regex;
2use serde_json::{json, Value};
3use std::collections::{HashMap, HashSet};
4use std::fs;
5use std::path::Path;
6use std::sync::{Arc, LazyLock, Mutex};
7
8
9mod html_escape {
10    pub fn encode_safe(input: &str) -> String {
11        input
12            .replace('&', "&")
13            .replace('<', "&lt;")
14            .replace('>', "&gt;")
15            .replace('"', "&quot;")
16            .replace('\'', "&#39;")
17    }
18}
19
20/// BladeContext — Menyimpan data dan variabel untuk dirender ke dalam template Blade.
21/// Mendukung nested properties (dot-notation), array indexing, dan serialisasi data dinamis.
22#[derive(Clone, Debug, Default)]
23pub struct BladeContext {
24    data: HashMap<String, Value>,
25    stacks: Arc<Mutex<HashMap<String, Vec<String>>>>,
26    once_set: Arc<Mutex<HashSet<String>>>,
27}
28
29impl BladeContext {
30    pub fn new() -> Self {
31        Self {
32            data: HashMap::new(),
33            stacks: Arc::new(Mutex::new(HashMap::new())),
34            once_set: Arc::new(Mutex::new(HashSet::new())),
35        }
36    }
37
38    /// Push konten ke stack tertentu (Laravel: @push('name'))
39    pub fn push_to_stack(&self, name: &str, content: String) {
40        if let Ok(mut lock) = self.stacks.lock() {
41            lock.entry(name.to_string()).or_default().push(content);
42        }
43    }
44
45    /// Prepend konten ke stack tertentu (Laravel: @prepend('name'))
46    pub fn prepend_to_stack(&self, name: &str, content: String) {
47        if let Ok(mut lock) = self.stacks.lock() {
48            lock.entry(name.to_string()).or_default().insert(0, content);
49        }
50    }
51
52    /// Ambil akumulasi konten stack tertentu (Laravel: @stack('name'))
53    pub fn get_stack(&self, name: &str) -> String {
54        if let Ok(lock) = self.stacks.lock() {
55            if let Some(list) = lock.get(name) {
56                return list.join("\n");
57            }
58        }
59        String::new()
60    }
61
62    /// Cek dan tandai eksekusi blok @once
63    pub fn check_and_mark_once(&self, id: &str) -> bool {
64        if let Ok(mut lock) = self.once_set.lock() {
65            lock.insert(id.to_string())
66        } else {
67            true
68        }
69    }
70
71    /// Masukkan data serializable ke dalam context.
72    pub fn insert<T: serde::Serialize>(&mut self, key: &str, value: T) {
73        let clean_key = key.trim().trim_start_matches('$');
74        if let Ok(val) = serde_json::to_value(value) {
75            self.data.insert(clean_key.to_string(), val);
76        }
77    }
78
79    /// Masukkan Value serde_json langsung.
80    pub fn insert_val(&mut self, key: &str, value: Value) {
81        let clean_key = key.trim().trim_start_matches('$');
82        self.data.insert(clean_key.to_string(), value);
83    }
84
85    /// Ambil nilai variabel. Mendukung dot-notation (misal: "user.profile.name" atau "items.0.title").
86    pub fn get(&self, key: &str) -> Option<&Value> {
87        let key = key.trim().trim_start_matches('$');
88        let normalized;
89        let effective_key = if key.contains('[') || key.contains(".first()") || key.contains("->") {
90            normalized = key
91                .replace(".first()->", ".0.")
92                .replace(".first().", ".0.")
93                .replace("->first()->", ".0.")
94                .replace("->first().", ".0.")
95                .replace("->", ".")
96                .replace("['", ".")
97                .replace("[\"", ".")
98                .replace("']", "")
99                .replace("\"]", "")
100                .replace('[', ".")
101                .replace(']', "");
102            &normalized
103        } else {
104            key
105        };
106
107        if !effective_key.contains('.') {
108            return self.data.get(effective_key);
109        }
110
111        let parts: Vec<&str> = effective_key.split('.').filter(|p| !p.is_empty()).collect();
112        if parts.is_empty() {
113            return None;
114        }
115        let mut curr = self.data.get(parts[0])?;
116        for part in &parts[1..] {
117            if let Some(obj) = curr.as_object() {
118                curr = obj.get(*part)?;
119            } else if let Ok(idx) = part.parse::<usize>() {
120                if let Some(arr) = curr.as_array() {
121                    curr = arr.get(idx)?;
122                } else {
123                    return None;
124                }
125            } else {
126                return None;
127            }
128        }
129        Some(curr)
130    }
131
132    /// Cek apakah sebuah key ada di dalam context.
133    pub fn has(&self, key: &str) -> bool {
134        self.get(key).is_some()
135    }
136
137    /// Cek apakah ada pesan error validasi untuk kolom tertentu.
138    /// Cek apakah user memiliki izin tertentu (RBAC support di Blade view)
139    pub fn check_user_can(&self, permission: &str) -> bool {
140        if let Some(user_val) = self.get("user") {
141            if let Some(role) = user_val.get("role").and_then(|r| r.as_str()) {
142                if role == "superadmin" || role == "admin" {
143                    return true;
144                }
145            }
146            if let Some(perms) = user_val.get("permissions").and_then(|p| p.as_array()) {
147                if perms.iter().any(|p| p.as_str() == Some(permission) || p.as_str() == Some("*")) {
148                    return true;
149                }
150            }
151        }
152        if let Some(perms_val) = self.get("permissions") {
153            if let Some(perms) = perms_val.as_array() {
154                if perms.iter().any(|p| p.as_str() == Some(permission) || p.as_str() == Some("*")) {
155                    return true;
156                }
157            }
158        }
159        false
160    }
161
162    /// Cek apakah user memiliki peran tertentu (RBAC support di Blade view)
163    pub fn check_user_has_role(&self, role: &str) -> bool {
164        if let Some(user_val) = self.get("user") {
165            if let Some(r) = user_val.get("role").and_then(|r| r.as_str()) {
166                return r == role || r == "superadmin";
167            }
168        }
169        false
170    }
171
172    pub fn has_error(&self, field: &str) -> bool {
173        self.get_error(field).is_some()
174    }
175
176    /// Ambil pesan error validasi untuk kolom tertentu jika ada.
177    pub fn get_error(&self, field: &str) -> Option<String> {
178        let clean_field = field.trim().trim_matches('\'').trim_matches('"');
179        let errs = self.get("errors")?;
180        if let Some(obj) = errs.as_object() {
181            if let Some(val) = obj.get(clean_field) {
182                match val {
183                    Value::String(s) if !s.trim().is_empty() => return Some(s.clone()),
184                    Value::Array(arr) if !arr.is_empty() => {
185                        if let Some(first) = arr.first() {
186                            if let Some(s) = first.as_str() {
187                                return Some(s.to_string());
188                            }
189                        }
190                    }
191                    _ => {}
192                }
193            }
194        }
195        None
196    }
197
198    /// Cek apakah suatu nilai bertipe truthy menurut aturan Blade/Laravel.
199    pub fn is_truthy(val: Option<&Value>) -> bool {
200        match val {
201            None => false,
202            Some(Value::Null) => false,
203            Some(Value::Bool(b)) => *b,
204            Some(Value::Number(n)) => n.as_f64().map(|f| f != 0.0).unwrap_or(false),
205            Some(Value::String(s)) => {
206                let trimmed = s.trim();
207                !trimmed.is_empty() && trimmed != "0" && trimmed != "false"
208            }
209            Some(Value::Array(arr)) => !arr.is_empty(),
210            Some(Value::Object(obj)) => !obj.is_empty(),
211        }
212    }
213
214    /// Tokenizer untuk operator titik (konkatenasi string ala PHP/Laravel).
215    /// Contoh: `'storage/images/meals/' . $meal.image` -> `["'storage/images/meals/'", "$meal.image"]`
216    pub fn split_concat_tokens(expr: &str) -> Option<Vec<String>> {
217        let mut tokens = Vec::new();
218        let mut current = String::new();
219        let mut in_single = false;
220        let mut in_double = false;
221        let chars: Vec<char> = expr.chars().collect();
222        let len = chars.len();
223        let mut has_concat = false;
224
225        let mut i = 0;
226        while i < len {
227            let c = chars[i];
228            if c == '\'' && !in_double {
229                in_single = !in_single;
230                current.push(c);
231            } else if c == '"' && !in_single {
232                in_double = !in_double;
233                current.push(c);
234            } else if c == '.' && !in_single && !in_double {
235                let prev_is_space = i > 0 && chars[i - 1].is_whitespace();
236                let next_is_space = i + 1 < len && chars[i + 1].is_whitespace();
237                let prev_is_quote = current.trim().ends_with('\'') || current.trim().ends_with('"');
238                let next_is_quote = i + 1 < len && (chars[i + 1] == '\'' || chars[i + 1] == '"');
239
240                if prev_is_space || next_is_space || prev_is_quote || next_is_quote {
241                    let trimmed = current.trim();
242                    if !trimmed.is_empty() {
243                        tokens.push(trimmed.to_string());
244                    }
245                    current.clear();
246                    has_concat = true;
247                } else {
248                    current.push(c);
249                }
250            } else {
251                current.push(c);
252            }
253            i += 1;
254        }
255
256        let trimmed = current.trim();
257        if !trimmed.is_empty() {
258            tokens.push(trimmed.to_string());
259        }
260
261        if has_concat && tokens.len() > 1 {
262            Some(tokens)
263        } else {
264            None
265        }
266    }
267
268    /// Helper mencari posisi pemisah koma terluar pada pemanggilan fungsi berargumen banyak.
269    pub fn find_argument_split(s: &str) -> Option<usize> {
270        let mut in_single = false;
271        let mut in_double = false;
272        let mut bracket_depth = 0;
273        let mut paren_depth = 0;
274        for (i, c) in s.char_indices() {
275            match c {
276                '\'' if !in_double => in_single = !in_single,
277                '"' if !in_single => in_double = !in_double,
278                '[' if !in_single && !in_double => bracket_depth += 1,
279                ']' if !in_single && !in_double && bracket_depth > 0 => bracket_depth -= 1,
280                '(' if !in_single && !in_double => paren_depth += 1,
281                ')' if !in_single && !in_double && paren_depth > 0 => paren_depth -= 1,
282                ',' if !in_single && !in_double && bracket_depth == 0 && paren_depth == 0 => return Some(i),
283                _ => {}
284            }
285        }
286        None
287    }
288
289    /// Helper mencari token terluar (di luar tanda kurung/kutip).
290    pub fn find_token_outside_parens(s: &str, token: &str) -> Option<usize> {
291        let mut in_single = false;
292        let mut in_double = false;
293        let mut paren_depth = 0;
294        let mut bracket_depth = 0;
295        let tok_bytes = token.as_bytes();
296        let tok_len = tok_bytes.len();
297        let s_bytes = s.as_bytes();
298        let len = s_bytes.len();
299
300        let mut i = 0;
301        while i < len {
302            let b = s_bytes[i];
303            match b {
304                b'\'' if !in_double => in_single = !in_single,
305                b'"' if !in_single => in_double = !in_double,
306                b'(' if !in_single && !in_double => paren_depth += 1,
307                b')' if !in_single && !in_double && paren_depth > 0 => paren_depth -= 1,
308                b'[' if !in_single && !in_double => bracket_depth += 1,
309                b']' if !in_single && !in_double && bracket_depth > 0 => bracket_depth -= 1,
310                _ => {
311                    if !in_single && !in_double && paren_depth == 0 && bracket_depth == 0 {
312                        if i + tok_len <= len && &s_bytes[i..i + tok_len] == tok_bytes {
313                            return Some(i);
314                        }
315                    }
316                }
317            }
318            i += 1;
319        }
320        None
321    }
322
323    /// Helper memecah argumen berdasar koma terluar (misal: "a, [1, 2], 'x, y'") -> ["a", "[1, 2]", "'x, y'"]
324    pub fn split_arguments(s: &str) -> Vec<String> {
325        let mut args = Vec::new();
326        let mut rem = s.trim();
327        while !rem.is_empty() {
328            if let Some(pos) = Self::find_argument_split(rem) {
329                args.push(rem[..pos].trim().to_string());
330                rem = rem[pos + 1..].trim();
331            } else {
332                args.push(rem.trim().to_string());
333                break;
334            }
335        }
336        args
337    }
338
339    /// Helper parsing array/hashmap sintaks Blade PHP:
340    /// Contoh: "['title' => $title, 'status' => 'active', 'count' => 5]" atau "compact('item', 'title')"
341    pub fn parse_blade_array(raw: &str, ctx: &BladeContext) -> HashMap<String, Value> {
342        let mut res = HashMap::new();
343        let trimmed = raw.trim();
344        if trimmed.is_empty() {
345            return res;
346        }
347
348        // Dukungan compact('var1', 'var2')
349        if trimmed.starts_with("compact(") && trimmed.ends_with(')') {
350            let inside = &trimmed[8..trimmed.len() - 1];
351            for var in Self::split_arguments(inside) {
352                let var_name = var.trim().trim_matches('\'').trim_matches('"').trim_start_matches('$');
353                if let Some(v) = ctx.get(var_name) {
354                    res.insert(var_name.to_string(), v.clone());
355                }
356            }
357            return res;
358        }
359
360        let inner = if (trimmed.starts_with('[') && trimmed.ends_with(']')) || (trimmed.starts_with("array(") && trimmed.ends_with(')')) {
361            if trimmed.starts_with('[') {
362                &trimmed[1..trimmed.len() - 1]
363            } else {
364                &trimmed[6..trimmed.len() - 1]
365            }
366        } else {
367            trimmed
368        };
369
370        let pairs = Self::split_arguments(inner);
371        for pair in pairs {
372            let pair_trim = pair.trim();
373            if pair_trim.is_empty() {
374                continue;
375            }
376            if let Some(arrow_pos) = Self::find_token_outside_parens(pair_trim, "=>") {
377                let key_raw = pair_trim[..arrow_pos].trim().trim_matches('\'').trim_matches('"');
378                let val_raw = pair_trim[arrow_pos + 2..].trim();
379                let val_clean = val_raw.trim_start_matches('$');
380                if let Some(v) = ctx.get(val_clean) {
381                    res.insert(key_raw.to_string(), v.clone());
382                } else {
383                    let evaled = ctx.eval_val(val_raw);
384                    if let Ok(num) = evaled.parse::<i64>() {
385                        res.insert(key_raw.to_string(), serde_json::json!(num));
386                    } else if let Ok(f) = evaled.parse::<f64>() {
387                        res.insert(key_raw.to_string(), serde_json::json!(f));
388                    } else if evaled == "true" {
389                        res.insert(key_raw.to_string(), serde_json::json!(true));
390                    } else if evaled == "false" {
391                        res.insert(key_raw.to_string(), serde_json::json!(false));
392                    } else {
393                        res.insert(key_raw.to_string(), serde_json::json!(evaled));
394                    }
395                }
396            }
397        }
398        res
399    }
400
401    /// Helper format angka ribuan (e.g. 15000 -> "15.000" atau "15,000").
402    pub fn format_thousands(val_str: &str, sep: char) -> String {
403        let trimmed = val_str.trim();
404        if let Ok(num) = trimmed.parse::<i64>() {
405            let num_str = num.abs().to_string();
406            let mut res = String::new();
407            let len = num_str.len();
408            for (i, c) in num_str.chars().enumerate() {
409                if i > 0 && (len - i) % 3 == 0 {
410                    res.push(sep);
411                }
412                res.push(c);
413            }
414            if num < 0 {
415                format!("-{}", res)
416            } else {
417                res
418            }
419        } else if let Ok(num) = trimmed.parse::<f64>() {
420            let rounded = num.round() as i64;
421            Self::format_thousands(&rounded.to_string(), sep)
422        } else {
423            trimmed.to_string()
424        }
425    }
426
427    /// Helper parsing komponen tanggal (day, month, year) dari string format database.
428    pub fn parse_date_parts(raw: &str) -> Option<(u32, u32, i32)> {
429        let trimmed = raw.trim();
430        let date_part = trimmed.split_whitespace().next().unwrap_or(trimmed);
431        let sep = if date_part.contains('-') { '-' } else if date_part.contains('/') { '/' } else { return None; };
432        let parts: Vec<&str> = date_part.split(sep).collect();
433        if parts.len() == 3 {
434            if parts[0].len() == 4 {
435                let year = parts[0].parse::<i32>().ok()?;
436                let month = parts[1].parse::<u32>().ok()?;
437                let day = parts[2].parse::<u32>().ok()?;
438                if (1..=12).contains(&month) && (1..=31).contains(&day) {
439                    return Some((day, month, year));
440                }
441            } else if parts[2].len() == 4 {
442                let day = parts[0].parse::<u32>().ok()?;
443                let month = parts[1].parse::<u32>().ok()?;
444                let year = parts[2].parse::<i32>().ok()?;
445                if (1..=12).contains(&month) && (1..=31).contains(&day) {
446                    return Some((day, month, year));
447                }
448            }
449        }
450        None
451    }
452
453    /// Helper format tanggal PHP (e.g. 'd F Y', 'd M', 'd M Y').
454    pub fn format_php_date(format_str: &str, raw_date: &str) -> String {
455        let (day, month, year) = if let Some(parts) = Self::parse_date_parts(raw_date) {
456            parts
457        } else {
458            let now = chrono::Local::now();
459            use chrono::Datelike;
460            (now.day(), now.month(), now.year())
461        };
462
463        const ENG_MONTHS_SHORT: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
464        const ENG_MONTHS_FULL: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
465
466        let m_idx = (month.max(1).min(12) - 1) as usize;
467
468        let mut res = String::new();
469        for c in format_str.chars() {
470            match c {
471                'd' => res.push_str(&format!("{:02}", day)),
472                'j' => res.push_str(&day.to_string()),
473                'F' => res.push_str(ENG_MONTHS_FULL[m_idx]),
474                'M' => res.push_str(ENG_MONTHS_SHORT[m_idx]),
475                'm' => res.push_str(&format!("{:02}", month)),
476                'Y' => res.push_str(&year.to_string()),
477                'y' => res.push_str(&format!("{:02}", year.rem_euclid(100))),
478                other => res.push(other),
479            }
480        }
481        res
482    }
483
484    /// Helper format tanggal Indonesia (e.g. 20 Mei 2024).
485    pub fn format_tanggal_indo(raw_date: &str) -> String {
486        if let Some((day, month, year)) = Self::parse_date_parts(raw_date) {
487            const INDO_MONTHS_FULL: [&str; 12] = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
488            let m_idx = (month.max(1).min(12) - 1) as usize;
489            format!("{} {} {}", day, INDO_MONTHS_FULL[m_idx], year)
490        } else {
491            raw_date.trim().to_string()
492        }
493    }
494
495    /// Helper format tanggal Inggris (e.g. 20 May 2024).
496    pub fn format_tanggal_eng(raw_date: &str) -> String {
497        if let Some((day, month, year)) = Self::parse_date_parts(raw_date) {
498            const ENG_MONTHS_FULL: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
499            let m_idx = (month.max(1).min(12) - 1) as usize;
500            format!("{} {} {}", day, ENG_MONTHS_FULL[m_idx], year)
501        } else {
502            raw_date.trim().to_string()
503        }
504    }
505
506    /// Evaluasi nilai ekspresi variabel/literal menjadi String.
507    /// Mendukung null coalescing: `$name ?? 'Default'`
508    pub fn eval_val(&self, expr: &str) -> String {
509        let expr = expr.trim();
510        if expr.is_empty() {
511            return String::new();
512        }
513
514        // Hapus tanda kurung terluar jika benar-benar melingkupi seluruh ekspresi: ( expr )
515        if expr.starts_with('(') && expr.ends_with(')') {
516            let mut depth = 0;
517            let mut can_strip = true;
518            for (i, c) in expr.char_indices() {
519                if c == '(' {
520                    depth += 1;
521                } else if c == ')' {
522                    depth -= 1;
523                    if depth == 0 && i < expr.len() - 1 {
524                        can_strip = false;
525                        break;
526                    }
527                }
528            }
529            if can_strip && depth == 0 {
530                let inner = expr[1..expr.len() - 1].trim();
531                return self.eval_val(inner);
532            }
533        }
534
535        // Operasi biner aritmatika sederhana di luar tanda kurung: expr1 - expr2 atau expr1 + expr2
536        if let Some(idx) = Self::find_token_outside_parens(expr, "-") {
537            let left_val = self.eval_val(&expr[..idx]);
538            let right_val = self.eval_val(&expr[idx + 1..]);
539            if let (Ok(n1), Ok(n2)) = (left_val.parse::<f64>(), right_val.parse::<f64>()) {
540                return (n1 - n2).to_string();
541            }
542        }
543        if let Some(idx) = Self::find_token_outside_parens(expr, "+") {
544            let left_val = self.eval_val(&expr[..idx]);
545            let right_val = self.eval_val(&expr[idx + 1..]);
546            if let (Ok(n1), Ok(n2)) = (left_val.parse::<f64>(), right_val.parse::<f64>()) {
547                return (n1 + n2).to_string();
548            }
549        }
550
551        // Null coalescing di luar tanda kurung: expr1 ?? expr2
552        if let Some(idx) = Self::find_token_outside_parens(expr, "??") {
553            let left = expr[..idx].trim();
554            let right = expr[idx + 2..].trim();
555            let val = self.eval_val(left);
556            if !val.is_empty() {
557                return val;
558            } else {
559                return self.eval_val(right);
560            }
561        }
562
563        // Operator ternary: cond ? expr1 : expr2
564        if let Some(q_idx) = Self::find_token_outside_parens(expr, "?") {
565            if !expr[q_idx..].starts_with("??") && (q_idx == 0 || &expr[q_idx - 1..q_idx] != "?") {
566                if let Some(colon_rel) = Self::find_token_outside_parens(&expr[q_idx + 1..], ":") {
567                    let colon_idx = q_idx + 1 + colon_rel;
568                    let cond = expr[..q_idx].trim();
569                    let true_val = expr[q_idx + 1..colon_idx].trim();
570                    let false_val = expr[colon_idx + 1..].trim();
571                    if self.eval_truthy(cond) {
572                        return self.eval_val(true_val);
573                    } else {
574                        return self.eval_val(false_val);
575                    }
576                }
577            }
578        }
579
580        // String literal: '...' atau "..."
581        if (expr.starts_with('\'') && expr.ends_with('\'') && expr.len() >= 2)
582            || (expr.starts_with('"') && expr.ends_with('"') && expr.len() >= 2)
583        {
584            return expr[1..expr.len() - 1].to_string();
585        }
586
587        // Boolean literal
588        if expr == "true" {
589            return "true".to_string();
590        }
591        if expr == "false" {
592            return "false".to_string();
593        }
594
595        // Number literal
596        if expr.parse::<f64>().is_ok() {
597            return expr.to_string();
598        }
599
600        // Helper PHP/Blade: count($var)
601        if expr.starts_with("count(") && expr.ends_with(')') {
602            let inner = expr[6..expr.len() - 1].trim();
603            let var = inner.trim_start_matches('$');
604            if let Some(val) = self.get(var) {
605                return match val {
606                    Value::Array(a) => a.len().to_string(),
607                    Value::Object(o) => o.len().to_string(),
608                    Value::String(s) => if s.is_empty() { "0".to_string() } else { s.len().to_string() },
609                    Value::Null => "0".to_string(),
610                    _ => "1".to_string(),
611                };
612            }
613            return "0".to_string();
614        }
615
616        // Method call: $var.count() atau $var->count()
617        if let Some(prefix) = expr.strip_suffix(".count()").or_else(|| expr.strip_suffix("->count()")) {
618            let var = prefix.trim().trim_start_matches('$');
619            if let Some(val) = self.get(var) {
620                return match val {
621                    Value::Array(a) => a.len().to_string(),
622                    Value::Object(o) => o.len().to_string(),
623                    Value::String(s) => if s.is_empty() { "0".to_string() } else { s.len().to_string() },
624                    Value::Null => "0".to_string(),
625                    _ => "1".to_string(),
626                };
627            }
628            return "0".to_string();
629        }
630
631        // Helper Laravel: old('field', 'default')
632        if expr.starts_with("old(") && expr.ends_with(')') {
633            let inner = expr[4..expr.len() - 1].trim();
634            let parts: Vec<&str> = inner.splitn(2, ',').collect();
635            let field = parts[0].trim().trim_matches('\'').trim_matches('"');
636            let default_val = if parts.len() > 1 {
637                self.eval_val(parts[1].trim())
638            } else {
639                String::new()
640            };
641
642            if let Some(old_val) = self.get("old") {
643                if let Some(obj) = old_val.as_object() {
644                    if let Some(val) = obj.get(field) {
645                        match val {
646                            Value::String(s) => return s.clone(),
647                            Value::Number(n) => return n.to_string(),
648                            Value::Bool(b) => return b.to_string(),
649                            Value::Null => {},
650                            other => return other.to_string(),
651                        }
652                    }
653                }
654            }
655            return default_val;
656        }
657
658        // Helper Laravel: asset('path')
659        if expr.starts_with("asset(") && expr.ends_with(')') {
660            let inner = expr[6..expr.len() - 1].trim();
661            let raw_eval = self.eval_val(inner);
662            let raw = raw_eval.trim().trim_matches('\'').trim_matches('"');
663            if raw.starts_with("http://") || raw.starts_with("https://") || raw.starts_with("//") {
664                return raw.to_string();
665            }
666            let clean = raw.trim_start_matches('/');
667            return format!("/{}", clean);
668        }
669
670        // Helper Laravel: mix('path')
671        if expr.starts_with("mix(") && expr.ends_with(')') {
672            let inner = expr[4..expr.len() - 1].trim();
673            let raw_eval = self.eval_val(inner);
674            let raw = raw_eval.trim().trim_matches('\'').trim_matches('"');
675            let clean = raw.trim_start_matches('/');
676            return format!("/{}", clean);
677        }
678
679        // Helper Laravel: route('name', ...)
680        if expr.starts_with("route(") && expr.ends_with(')') {
681            let inner = expr[6..expr.len() - 1].trim();
682            let (first_arg, second_arg) = if let Some(comma_pos) = Self::find_argument_split(inner) {
683                (&inner[..comma_pos], Some(&inner[comma_pos + 1..]))
684            } else {
685                (inner, None)
686            };
687            let route_name = first_arg.trim().trim_matches('\'').trim_matches('"');
688            if let Some(second) = second_arg {
689                let second = second.trim();
690                let param_val = if second.starts_with('[') && second.ends_with(']') {
691                    let inside = &second[1..second.len() - 1];
692                    if let Some(arrow_pos) = inside.find("=>") {
693                        let rhs = inside[arrow_pos + 2..].trim();
694                        self.eval_val(rhs)
695                    } else {
696                        self.eval_val(inside.trim())
697                    }
698                } else {
699                    self.eval_val(second)
700                };
701                let clean_name = route_name.trim_start_matches('/');
702                let clean_param = param_val.trim().trim_matches('\'').trim_matches('"');
703                if !clean_param.is_empty() {
704                    return format!("/{}/{}", clean_name, clean_param);
705                } else {
706                    return format!("/{}", clean_name);
707                }
708            } else {
709                let clean_name = route_name.trim_start_matches('/');
710                return format!("/{}", clean_name);
711            }
712        }
713
714        // Helper Laravel: url('path')
715        if expr.starts_with("url(") && expr.ends_with(')') {
716            let inner = expr[4..expr.len() - 1].trim();
717            let raw_eval = self.eval_val(inner);
718            let raw = raw_eval.trim().trim_matches('\'').trim_matches('"');
719            if raw.starts_with("http://") || raw.starts_with("https://") {
720                return raw.to_string();
721            }
722            let clean = raw.trim_start_matches('/');
723            return format!("/{}", clean);
724        }
725
726        // Helper Laravel: request()->is(...) / request()->routeIs(...)
727        if (expr.starts_with("request()->is(") || expr.starts_with("request()->routeIs(") || expr.starts_with("request.is(") || expr.starts_with("request.routeIs(")) && expr.ends_with(')') {
728            let open = expr.rfind('(').unwrap();
729            let inner = expr[open + 1..expr.len() - 1].trim();
730            let pattern = self.eval_val(inner).trim().trim_matches('\'').trim_matches('"').to_string();
731            let curr_path = self.get("request_path")
732                .or_else(|| self.get("current_route"))
733                .or_else(|| self.get("path"))
734                .and_then(|v| v.as_str())
735                .unwrap_or("");
736            let clean_pattern = pattern.trim_start_matches('/');
737            let clean_curr = curr_path.trim_start_matches('/');
738            let matches = if clean_pattern.ends_with('*') {
739                clean_curr.starts_with(clean_pattern.trim_end_matches('*'))
740            } else {
741                clean_curr == clean_pattern
742            };
743            return if matches { "1".to_string() } else { String::new() };
744        }
745
746        // Helper Laravel: session('key', 'default')
747        if expr.starts_with("session(") && expr.ends_with(')') {
748            let inner = expr[8..expr.len() - 1].trim();
749            if inner.is_empty() {
750                return String::new();
751            }
752            let (key_arg, def_arg) = if let Some(comma) = Self::find_argument_split(inner) {
753                (inner[..comma].trim(), Some(inner[comma + 1..].trim()))
754            } else {
755                (inner, None)
756            };
757            let key = key_arg.trim_matches('\'').trim_matches('"');
758            let session_key = format!("session.{}", key);
759            if let Some(val) = self.get(&session_key).or_else(|| self.get(key)) {
760                match val {
761                    Value::String(s) => return s.clone(),
762                    Value::Number(n) => return n.to_string(),
763                    Value::Bool(b) => return b.to_string(),
764                    Value::Null => {},
765                    other => return other.to_string(),
766                }
767            }
768            if let Some(def) = def_arg {
769                return self.eval_val(def);
770            }
771            return String::new();
772        }
773
774        // Helper Laravel: auth()->check(), auth()->id(), auth()->user()->prop, Auth::user()->prop
775        if expr == "auth()->check()" {
776            return if self.get("user").is_some() { "1".to_string() } else { String::new() };
777        }
778        if expr == "auth()->id()" {
779            if let Some(id) = self.get("user.id") {
780                return id.to_string();
781            }
782            return String::new();
783        }
784        if expr.starts_with("auth()->user()->") {
785            let prop = &expr[16..];
786            let key = format!("user.{}", prop);
787            if let Some(val) = self.get(&key) {
788                match val {
789                    Value::String(s) => return s.clone(),
790                    Value::Number(n) => return n.to_string(),
791                    Value::Bool(b) => return b.to_string(),
792                    _ => return val.to_string(),
793                }
794            }
795            return String::new();
796        }
797        if expr.starts_with("Auth::user()->") {
798            let prop = &expr[14..];
799            let key = format!("user.{}", prop);
800            if let Some(val) = self.get(&key) {
801                match val {
802                    Value::String(s) => return s.clone(),
803                    Value::Number(n) => return n.to_string(),
804                    Value::Bool(b) => return b.to_string(),
805                    _ => return val.to_string(),
806                }
807            }
808            return String::new();
809        }
810
811        // Helper Laravel: Str::limit($text, limit), str_limit($text, limit), Str::slug($text)
812        if (expr.starts_with("Str::limit(") || expr.starts_with("str_limit(")) && expr.ends_with(')') {
813            let open = expr.find('(').unwrap();
814            let inner = expr[open + 1..expr.len() - 1].trim();
815            let parts = Self::split_arguments(inner);
816            if !parts.is_empty() {
817                let text = self.eval_val(&parts[0]);
818                let limit: usize = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(100);
819                let end_str = parts.get(2).map(|p| p.trim().trim_matches('\'').trim_matches('"')).unwrap_or("...");
820                let chars: Vec<char> = text.chars().collect();
821                if chars.len() > limit {
822                    let truncated: String = chars[..limit].iter().collect();
823                    return format!("{}{}", truncated, end_str);
824                } else {
825                    return text;
826                }
827            }
828            return String::new();
829        }
830        if expr.starts_with("Str::slug(") && expr.ends_with(')') {
831            let inner = expr[10..expr.len() - 1].trim();
832            let text = self.eval_val(inner);
833            return BladeEngine::slug(&text);
834        }
835
836        // String Helpers: strtoupper, strtolower, ucfirst, ucwords, substr, str_replace
837        if expr.starts_with("strtoupper(") && expr.ends_with(')') {
838            let inner = expr[11..expr.len() - 1].trim();
839            return self.eval_val(inner).to_uppercase();
840        }
841        if expr.starts_with("strtolower(") && expr.ends_with(')') {
842            let inner = expr[11..expr.len() - 1].trim();
843            return self.eval_val(inner).to_lowercase();
844        }
845        if expr.starts_with("ucfirst(") && expr.ends_with(')') {
846            let inner = expr[8..expr.len() - 1].trim();
847            let s = self.eval_val(inner);
848            let mut chars = s.chars();
849            return match chars.next() {
850                None => String::new(),
851                Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
852            };
853        }
854        if expr.starts_with("ucwords(") && expr.ends_with(')') {
855            let inner = expr[8..expr.len() - 1].trim();
856            let s = self.eval_val(inner);
857            return s.split_whitespace()
858                .map(|w| {
859                    let mut c = w.chars();
860                    match c.next() {
861                        None => String::new(),
862                        Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
863                    }
864                })
865                .collect::<Vec<_>>()
866                .join(" ");
867        }
868        if expr.starts_with("substr(") && expr.ends_with(')') {
869            let inner = expr[7..expr.len() - 1].trim();
870            let parts: Vec<&str> = inner.split(',').map(|p| p.trim()).collect();
871            if !parts.is_empty() {
872                let s = self.eval_val(parts[0]);
873                let start: usize = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
874                let chars: Vec<char> = s.chars().collect();
875                if start >= chars.len() {
876                    return String::new();
877                }
878                if let Some(len_str) = parts.get(2) {
879                    if let Ok(len) = len_str.parse::<usize>() {
880                        let end = (start + len).min(chars.len());
881                        return chars[start..end].iter().collect();
882                    }
883                }
884                return chars[start..].iter().collect();
885            }
886            return String::new();
887        }
888        if expr.starts_with("str_replace(") && expr.ends_with(')') {
889            let inner = expr[12..expr.len() - 1].trim();
890            let parts: Vec<&str> = inner.split(',').map(|p| p.trim()).collect();
891            if parts.len() >= 3 {
892                let search = self.eval_val(parts[0]);
893                let replace = self.eval_val(parts[1]);
894                let subject = self.eval_val(parts[2]);
895                return subject.replace(&search, &replace);
896            }
897            return String::new();
898        }
899
900        // Date Helpers: date('format', strtotime($var)), tanggalOnly($var), tanggalInggris($var)
901        if expr.starts_with("date(") && expr.ends_with(')') {
902            let inner = expr[5..expr.len() - 1].trim();
903            let (first_arg, second_arg) = if let Some(comma_pos) = Self::find_argument_split(inner) {
904                (&inner[..comma_pos], Some(&inner[comma_pos + 1..]))
905            } else {
906                (inner, None)
907            };
908            let format_str = first_arg.trim().trim_matches('\'').trim_matches('"');
909            let raw_date = if let Some(second) = second_arg {
910                let second = second.trim();
911                if second.starts_with("strtotime(") && second.ends_with(')') {
912                    let inside = &second[10..second.len() - 1];
913                    self.eval_val(inside.trim())
914                } else {
915                    self.eval_val(second)
916                }
917            } else {
918                String::new()
919            };
920            return Self::format_php_date(format_str, &raw_date);
921        }
922        if expr.starts_with("tanggalOnly(") && expr.ends_with(')') {
923            let inner = expr[12..expr.len() - 1].trim();
924            let raw_date = self.eval_val(inner);
925            return Self::format_tanggal_indo(&raw_date);
926        }
927        if expr.starts_with("tanggalInggris(") && expr.ends_with(')') {
928            let inner = expr[15..expr.len() - 1].trim();
929            let raw_date = self.eval_val(inner);
930            return Self::format_tanggal_eng(&raw_date);
931        }
932
933        // Currency / Number Helpers: uang, ribuan, number_format
934        if (expr.starts_with("uang(") || expr.starts_with("ribuan(")) && expr.ends_with(')') {
935            let open = expr.find('(').unwrap();
936            let inner = expr[open + 1..expr.len() - 1].trim();
937            let val_str = self.eval_val(inner);
938            return Self::format_thousands(&val_str, '.');
939        }
940        if expr.starts_with("number_format(") && expr.ends_with(')') {
941            let inner = expr[14..expr.len() - 1].trim();
942            let parts: Vec<&str> = inner.split(',').map(|p| p.trim()).collect();
943            let val_str = self.eval_val(parts[0]);
944            let sep = if parts.len() >= 4 {
945                parts[3].trim_matches('\'').trim_matches('"').chars().next().unwrap_or(',')
946            } else {
947                ','
948            };
949            return Self::format_thousands(&val_str, sep);
950        }
951
952        // Localization & Translation Helpers: __, trans, app()->getLocale()
953        if (expr.starts_with("__(") || expr.starts_with("trans(")) && expr.ends_with(')') {
954            let open = expr.find('(').unwrap();
955            let inner = expr[open + 1..expr.len() - 1].trim();
956            let parts: Vec<&str> = inner.splitn(2, ',').collect();
957            let key = parts[0].trim().trim_matches('\'').trim_matches('"');
958            return key.to_string();
959        }
960        if expr == "app()->getLocale()" || expr == "app()->currentLocale()" {
961            return "id".to_string();
962        }
963        if expr == "csrf_token()" || expr == "csrf_token" {
964            if let Some(t) = self.get("csrf_token") {
965                if let Some(s) = t.as_str() {
966                    return s.to_string();
967                }
968            }
969            return String::new();
970        }
971
972        // Konkatenasi string gaya Laravel/PHP dengan operator titik (.)
973        // Contoh: 'storage/images/meals/' . $meal.image
974        if let Some(tokens) = Self::split_concat_tokens(expr) {
975            let mut res = String::new();
976            for tok in tokens {
977                res.push_str(&self.eval_val(&tok));
978            }
979            return res;
980        }
981
982        // Variable lookup
983        if let Some(val) = self.get(expr) {
984            match val {
985                Value::String(s) => s.clone(),
986                Value::Number(n) => n.to_string(),
987                Value::Bool(b) => b.to_string(),
988                Value::Null => String::new(),
989                v => v.to_string(),
990            }
991        } else {
992            String::new()
993        }
994    }
995
996    /// Evaluasi kondisi boolean (truthy) untuk direktif @if, @unless, @checked, dll.
997    pub fn eval_truthy(&self, expr: &str) -> bool {
998        let expr = expr.trim();
999        if expr.is_empty() {
1000            return false;
1001        }
1002
1003        // Hapus tanda kurung terluar jika benar-benar melingkupi seluruh ekspresi: ( expr )
1004        if expr.starts_with('(') && expr.ends_with(')') {
1005            let mut depth = 0;
1006            let mut can_strip = true;
1007            for (i, c) in expr.char_indices() {
1008                if c == '(' {
1009                    depth += 1;
1010                } else if c == ')' {
1011                    depth -= 1;
1012                    if depth == 0 && i < expr.len() - 1 {
1013                        can_strip = false;
1014                        break;
1015                    }
1016                }
1017            }
1018            if can_strip && depth == 0 {
1019                let inner = &expr[1..expr.len() - 1];
1020                return self.eval_truthy(inner);
1021            }
1022        }
1023
1024        // Logical OR: ||
1025        if let Some(idx) = expr.find("||") {
1026            let left = &expr[..idx];
1027            let right = &expr[idx + 2..];
1028            return self.eval_truthy(left) || self.eval_truthy(right);
1029        }
1030
1031        // Logical AND: &&
1032        if let Some(idx) = expr.find("&&") {
1033            let left = &expr[..idx];
1034            let right = &expr[idx + 2..];
1035            return self.eval_truthy(left) && self.eval_truthy(right);
1036        }
1037
1038        // Unary NOT: !expr
1039        if expr.starts_with('!') {
1040            return !self.eval_truthy(&expr[1..]);
1041        }
1042
1043        // Special helpers:
1044        // auth() / auth
1045        if expr == "auth" || expr == "auth()" {
1046            let uid = self.get("user_id").or_else(|| self.get("user")).or_else(|| self.get("auth"));
1047            return Self::is_truthy(uid);
1048        }
1049        // guest() / guest
1050        if expr == "guest" || expr == "guest()" {
1051            let uid = self.get("user_id").or_else(|| self.get("user")).or_else(|| self.get("auth"));
1052            return !Self::is_truthy(uid);
1053        }
1054        // can('permission')
1055        if expr.starts_with("can(") && expr.ends_with(')') {
1056            let perm = expr[4..expr.len() - 1].trim().trim_matches('\'').trim_matches('"');
1057            return self.check_user_can(perm);
1058        }
1059        // cannot('permission')
1060        if expr.starts_with("cannot(") && expr.ends_with(')') {
1061            let perm = expr[7..expr.len() - 1].trim().trim_matches('\'').trim_matches('"');
1062            return !self.check_user_can(perm);
1063        }
1064        // role('role')
1065        if expr.starts_with("role(") && expr.ends_with(')') {
1066            let role_name = expr[5..expr.len() - 1].trim().trim_matches('\'').trim_matches('"');
1067            return self.check_user_has_role(role_name);
1068        }
1069        // isset($var)
1070        if expr.starts_with("isset(") && expr.ends_with(')') {
1071            let var = &expr[6..expr.len() - 1].trim();
1072            return self.get(var).is_some() && !self.get(var).unwrap().is_null();
1073        }
1074        // empty($var)
1075        if expr.starts_with("empty(") && expr.ends_with(')') {
1076            let var = &expr[6..expr.len() - 1].trim();
1077            return !Self::is_truthy(self.get(var));
1078        }
1079        // count($var)
1080        if expr.starts_with("count(") && expr.ends_with(')') {
1081            return self.eval_val(expr).parse::<f64>().map(|n| n > 0.0).unwrap_or(false);
1082        }
1083        // $var.count() / $var->count()
1084        if expr.ends_with(".count()") || expr.ends_with("->count()") {
1085            return self.eval_val(expr).parse::<f64>().map(|n| n > 0.0).unwrap_or(false);
1086        }
1087        // production / production()
1088        if expr == "production" || expr == "production()" {
1089            let env = self.get("env").and_then(|v| v.as_str()).unwrap_or("");
1090            return env == "production" || env == "prod" || std::env::var("APP_ENV").unwrap_or_default() == "production";
1091        }
1092        // env('local', 'staging')
1093        if expr.starts_with("env(") && expr.ends_with(')') {
1094            let args = &expr[4..expr.len() - 1];
1095            let current_env = self.get("env").and_then(|v| v.as_str())
1096                .unwrap_or_else(|| "local");
1097            for arg in args.split(',') {
1098                let clean_arg = arg.trim().trim_matches('\'').trim_matches('"');
1099                if clean_arg == current_env {
1100                    return true;
1101                }
1102            }
1103            return false;
1104        }
1105
1106        // error('field') / hasError('field')
1107        if (expr.starts_with("error(") && expr.ends_with(')')) || (expr.starts_with("hasError(") && expr.ends_with(')')) {
1108            let open = expr.find('(').unwrap();
1109            let field = expr[open + 1..expr.len() - 1].trim();
1110            return self.has_error(field);
1111        }
1112
1113        // anyErrors / errors.any / $errors->any() / errors
1114        if expr == "errors" || expr == "errors()" || expr == "$errors->any()" || expr == "errors.any" || expr == "anyErrors" {
1115            if let Some(val) = self.get("errors") {
1116                if let Some(obj) = val.as_object() {
1117                    return !obj.is_empty();
1118                }
1119            }
1120            return false;
1121        }
1122
1123        // Perbandingan: ===, ==, !=, >=, <=, >, < (di luar tanda kurung/kutip)
1124        for op in &["===", "==", "!=", ">=", "<=", ">", "<"] {
1125            if let Some(idx) = Self::find_token_outside_parens(expr, op) {
1126                // Lewati '>' jika merupakan bagian dari operator panah '->'
1127                if *op == ">" && idx > 0 && expr.as_bytes()[idx - 1] == b'-' {
1128                    continue;
1129                }
1130                let left = self.eval_val(&expr[..idx]);
1131                let right = self.eval_val(&expr[idx + op.len()..]);
1132
1133                // Perbandingan numerik jika kedua sisi angka
1134                if let (Ok(n1), Ok(n2)) = (left.parse::<f64>(), right.parse::<f64>()) {
1135                    return match *op {
1136                        "===" | "==" => (n1 - n2).abs() < f64::EPSILON,
1137                        "!=" => (n1 - n2).abs() >= f64::EPSILON,
1138                        ">=" => n1 >= n2,
1139                        "<=" => n1 <= n2,
1140                        ">" => n1 > n2,
1141                        "<" => n1 < n2,
1142                        _ => false,
1143                    };
1144                }
1145
1146                // Perbandingan string
1147                return match *op {
1148                    "===" | "==" => left == right,
1149                    "!=" => left != right,
1150                    ">=" => left >= right,
1151                    "<=" => left <= right,
1152                    ">" => left > right,
1153                    "<" => left < right,
1154                    _ => false,
1155                };
1156            }
1157        }
1158
1159        // Boolean literal
1160        if expr == "true" {
1161            return true;
1162        }
1163        if expr == "false" {
1164            return false;
1165        }
1166
1167        if let Some(val) = self.get(expr) {
1168            return Self::is_truthy(Some(val));
1169        }
1170
1171        let evaled = self.eval_val(expr);
1172        if !evaled.is_empty() && evaled != "0" && evaled != "false" {
1173            return true;
1174        }
1175
1176        false
1177    }
1178}
1179
1180/// Interface runner untuk mengeksekusi plugin pihak ketiga (misal WASM Sandbox / Indonesian Script)
1181pub trait BladePluginRunner: Send + Sync {
1182    fn call_filter(&self, plugin_name: &str, func_name: &str, arg: &str) -> Result<String, String> {
1183        let _ = (plugin_name, func_name, arg);
1184        Err("No plugin runner configured".to_string())
1185    }
1186
1187    fn eval_is_script(&self, script_path: &str, func_name: &str, args: &[Value]) -> Result<Value, String> {
1188        let _ = (script_path, func_name, args);
1189        Err("No script runner configured".to_string())
1190    }
1191}
1192
1193/// Runner default kosong (No-op)
1194#[derive(Default, Clone)]
1195pub struct NoopPluginRunner;
1196impl BladePluginRunner for NoopPluginRunner {}
1197
1198/// BladeEngine — Pure Native Laravel Blade Templating Engine for Rust.
1199/// Sangat cepat, tanpa alokasi berat, mendukung layout inheritance, loop variables,
1200/// conditional directives, integrasi Indonesian Script, serta Filter & Ekstensi WASM Sandbox.
1201pub struct BladeEngine {
1202    pub templates: HashMap<String, String>,
1203    pub plugin_runner: Arc<dyn BladePluginRunner>,
1204    pub wasm_filters: HashMap<String, (String, String)>,
1205}
1206
1207impl Default for BladeEngine {
1208    fn default() -> Self {
1209        Self::empty()
1210    }
1211}
1212
1213
1214
1215pub type CustomDirectiveHandler = std::sync::Arc<dyn Fn(&str, &BladeEngine, &BladeContext) -> String + Send + Sync>;
1216
1217#[derive(Clone)]
1218pub struct RegisteredDirective {
1219    pub name: String,
1220    pub re_args: Regex,
1221    pub re_no_args: Regex,
1222    pub handler: CustomDirectiveHandler,
1223}
1224
1225static RE_COMMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)\{\{--.*?--\}\}").unwrap());
1226static RE_METHOD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@method\s*\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1227static RE_WASM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@wasm\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*(?:,\s*(.*?))?\s*\)"#).unwrap());
1228static RE_EVAL_IS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@eval_is\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*(?:,\s*(.*?))?\s*\)"#).unwrap());
1229static RE_RAW: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{!!\s*(.*?)\s*!!\}").unwrap());
1230static RE_VAR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{\{\s*(.*?)\s*\}\}").unwrap());
1231static RE_UNLESS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@unless\s*\((.*?)\)").unwrap());
1232static RE_ISSET: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@isset\s*\((.*?)\)").unwrap());
1233static RE_EMPTY: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@empty\s*\((.*?)\)").unwrap());
1234static RE_AUTH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@auth\b").unwrap());
1235static RE_GUEST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@guest\b").unwrap());
1236static RE_CAN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@can\s*\((.*?)\)").unwrap());
1237static RE_CANNOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@cannot\s*\((.*?)\)").unwrap());
1238static RE_ROLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@role\s*\((.*?)\)").unwrap());
1239static RE_PROD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@production\b").unwrap());
1240static RE_ENV: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@env\s*\((.*?)\)").unwrap());
1241static RE_EXTENDS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@extends\s*\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1242static RE_SHORT_SECTION: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@section\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1243static RE_SECTION: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@section\s*\(\s*['"]([^'"]+)['"]\s*\)(.*?)@(?:endsection|stop|show)"#).unwrap());
1244static RE_YIELD_DEFAULT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@yield\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1245static RE_YIELD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@yield\s*\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1246static RE_HAS_SEC: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@hasSection\s*\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1247static RE_PUSH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@push\s*\(\s*['"]([^'"]+)['"]\s*\)(.*?)@endpush"#).unwrap());
1248static RE_PREPEND: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@prepend\s*\(\s*['"]([^'"]+)['"]\s*\)(.*?)@endprepend"#).unwrap());
1249static RE_STACK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@stack\s*\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1250static RE_ONCE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@once(.*?)@endonce"#).unwrap());
1251static RE_INC_WHEN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@includeWhen\s*\((.*?)\)"#).unwrap());
1252static RE_INC_UNLESS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@includeUnless\s*\((.*?)\)"#).unwrap());
1253static RE_INC_IF: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@includeIf\s*\((.*?)\)"#).unwrap());
1254static RE_INC: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@include\s*\((.*?)\)"#).unwrap());
1255static RE_VITE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"@vite\s*\((.*?)\)"#).unwrap());
1256static RE_COMPONENT_SELF: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"<x-([a-zA-Z0-9_\.-]+)([^>]*?)/>"#).unwrap());
1257static RE_COMPONENT_OPEN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"<x-([a-zA-Z0-9_\.-]+)([^>]*?)>"#).unwrap());
1258static RE_COMPONENT_SLOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)<x-slot(?::([a-zA-Z0-9_\.-]+)|(?:\s+name=['"]([a-zA-Z0-9_\.-]+)['"]))>(.*?)</x-slot>"#).unwrap());
1259static RE_COMPONENT_ATTR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?::([a-zA-Z0-9_\.-]+)|([a-zA-Z0-9_\.-]+))\s*=\s*(?:"([^"]*)"|'([^']*)')"#).unwrap());
1260static RE_FOREACH_OPEN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@foreach\s*\((.*?)\)").unwrap());
1261static RE_FORELSE_OPEN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@forelse\s*\((.*?)\)").unwrap());
1262static RE_FOR_OPEN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@for\s*\((.*?)\)").unwrap());
1263static RE_INIT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\$?(\w+)\s*=\s*(\d+)").unwrap());
1264static RE_COND: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<\s*(\d+)").unwrap());
1265static RE_SWITCH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@switch\s*\((.*?)\)(.*?)@endswitch"#).unwrap());
1266static RE_CASES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@case\s*\(\s*['"]?([^'"]+)['"]?\s*\)(.*?)(?:@break|@case|@default|$)"#).unwrap());
1267static RE_DEFAULT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@default(.*?)(?:@break|$)"#).unwrap());
1268static RE_ERROR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?s)@error\s*\(\s*['"]([^'"]+)['"]\s*\)(.*?)@enderror"#).unwrap());
1269static RE_CHECKED: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@checked\s*\((.*?)\)").unwrap());
1270static RE_SELECTED: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@selected\s*\((.*?)\)").unwrap());
1271static RE_DISABLED: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@disabled\s*\((.*?)\)").unwrap());
1272static RE_READONLY: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@readonly\s*\((.*?)\)").unwrap());
1273static RE_REQUIRED: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@required\s*\((.*?)\)").unwrap());
1274static RE_CLASS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@class\s*\(\s*\[(.*?)\]\s*\)").unwrap());
1275static RE_STYLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@style\s*\(\s*\[(.*?)\]\s*\)").unwrap());
1276static RE_JSON: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@json\s*\((.*?)\)").unwrap());
1277static RE_DUMP: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"@(?:dump|dd)\s*\((.*?)\)").unwrap());
1278static RE_IS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?:@is|@script)\s*\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
1279
1280static GLOBAL_DIRECTIVES: std::sync::OnceLock<std::sync::RwLock<std::collections::HashMap<String, RegisteredDirective>>> = std::sync::OnceLock::new();
1281
1282/// Daftarkan custom directive ke Blade engine secara global.
1283/// Contoh: `@directiveName` atau `@directiveName(argumen)`
1284pub fn register_global_directive<F>(name: &str, handler: F)
1285where
1286    F: Fn(&str, &BladeEngine, &BladeContext) -> String + Send + Sync + 'static,
1287{
1288    let lock = GLOBAL_DIRECTIVES.get_or_init(|| std::sync::RwLock::new(std::collections::HashMap::new()));
1289    let pattern_args = format!(r#"@{}\s*\((.*?)\)"#, regex::escape(name));
1290    let pattern_no_args = format!(r#"@{}\b"#, regex::escape(name));
1291    let re_args = Regex::new(&pattern_args).expect("Valid regex for custom directive with args");
1292    let re_no_args = Regex::new(&pattern_no_args).expect("Valid regex for custom directive without args");
1293
1294    let mut map = lock.write().unwrap();
1295    map.insert(
1296        name.to_string(),
1297        RegisteredDirective {
1298            name: name.to_string(),
1299            re_args,
1300            re_no_args,
1301            handler: std::sync::Arc::new(handler),
1302        },
1303    );
1304}
1305
1306impl BladeEngine {
1307    /// Membuat BladeEngine kosong (tanpa membaca views path, cocok untuk test/memory engine)
1308    pub fn empty() -> Self {
1309        Self {
1310            templates: HashMap::new(),
1311            plugin_runner: Arc::new(NoopPluginRunner),
1312            wasm_filters: HashMap::new(),
1313        }
1314    }
1315
1316    pub fn new() -> Self {
1317        let mut engine = Self::empty();
1318        engine.reload_templates("resources/views");
1319        engine
1320    }
1321
1322    /// Pasang plugin_runner kustom/global (misal dari PakemPluginManager)
1323    pub fn with_plugin_runner(mut self, runner: Arc<dyn BladePluginRunner>) -> Self {
1324        self.plugin_runner = runner;
1325        self
1326    }
1327
1328    /// Daftarkan alias filter Blade kustom yang mengarah ke plugin WASM tertentu
1329    pub fn register_wasm_filter(&mut self, alias: &str, plugin_name: &str, func_name: &str) {
1330        self.wasm_filters.insert(alias.to_string(), (plugin_name.to_string(), func_name.to_string()));
1331    }
1332
1333
1334
1335    pub fn reload_templates(&mut self, views_path: &str) {
1336        self.templates.clear();
1337        if Path::new(views_path).is_dir() {
1338            Self::collect_templates(views_path, "", &mut self.templates);
1339        }
1340    }
1341
1342    fn collect_templates(base_path: &str, prefix: &str, out: &mut HashMap<String, String>) {
1343        let path = if prefix.is_empty() {
1344            base_path.to_string()
1345        } else {
1346            format!("{}/{}", base_path, prefix)
1347        };
1348
1349        if let Ok(entries) = fs::read_dir(&path) {
1350            for entry in entries.flatten() {
1351                let file_path = entry.path();
1352                let file_name = entry.file_name().into_string().unwrap_or_default();
1353
1354                if file_path.is_dir() {
1355                    let new_prefix = if prefix.is_empty() {
1356                        file_name
1357                    } else {
1358                        format!("{}/{}", prefix, file_name)
1359                    };
1360                    Self::collect_templates(base_path, &new_prefix, out);
1361                } else if file_name.ends_with(".blade.rs") || file_name.ends_with(".html") {
1362                    match fs::read_to_string(&file_path) {
1363                        Ok(content) => {
1364                            let template_name = if prefix.is_empty() {
1365                                file_name.clone()
1366                            } else {
1367                                format!("{}/{}", prefix, file_name)
1368                            };
1369                            let normalized = template_name.replace('\\', "/");
1370                            out.insert(normalized.clone(), content.clone());
1371
1372                            if normalized.ends_with(".blade.rs") {
1373                                let without_ext = normalized.strip_suffix(".blade.rs").unwrap();
1374                                out.insert(without_ext.to_string(), content.clone());
1375                                out.insert(without_ext.replace('/', "."), content.clone());
1376                            } else if normalized.ends_with(".html") {
1377                                let without_ext = normalized.strip_suffix(".html").unwrap();
1378                                out.insert(without_ext.to_string(), content.clone());
1379                                out.insert(without_ext.replace('/', "."), content.clone());
1380                            }
1381                        }
1382                        Err(e) => {
1383                            eprintln!("Failed to read template {:?}: {}", file_path, e);
1384                        }
1385                    }
1386                }
1387            }
1388        }
1389    }
1390
1391    /// Render template menggunakan nama file atau format dot-notation (misal: "auth.login" atau "layouts/app.blade.rs")
1392    pub fn render(&self, template_name: &str, context: &BladeContext) -> String {
1393        let clean = template_name.replace('\\', "/");
1394        let raw = self.templates.get(&clean)
1395            .or_else(|| {
1396                if !clean.ends_with(".blade.rs") && !clean.ends_with(".html") {
1397                    let with_blade = format!("{}.blade.rs", clean.replace('.', "/"));
1398                    self.templates.get(&with_blade)
1399                } else {
1400                    None
1401                }
1402            })
1403            .or_else(|| {
1404                let dotted = clean.replace('/', ".");
1405                self.templates.get(&dotted)
1406            });
1407
1408        let raw = match raw {
1409            Some(content) => content.clone(),
1410            None => {
1411                let keys = self.templates.keys().cloned().collect::<Vec<_>>();
1412                return format!("Template error: Template '{}' not found. Available templates: {:?}", template_name, keys);
1413            }
1414        };
1415
1416        self.process_template(&raw, context, 0)
1417    }
1418
1419    /// Render string template secara langsung tanpa membaca file
1420    pub fn render_string(&self, content: &str, context: &BladeContext) -> String {
1421        self.process_template(content, context, 0)
1422    }
1423
1424    /// Pipeline utama pemrosesan template Blade
1425    fn process_template(&self, content: &str, context: &BladeContext, depth: usize) -> String {
1426        if depth > 25 {
1427            return "<!-- Template recursion limit exceeded -->".to_string();
1428        }
1429
1430        let mut s = content.to_string();
1431
1432        // 0. {{-- Comment --}}
1433        s = RE_COMMENT.replace_all(&s, "").to_string();
1434
1435        // 0b. @once ... @endonce
1436        if s.contains("@once") {
1437            s = RE_ONCE.replace_all(&s, |caps: &regex::Captures| {
1438                let inner = &caps[1];
1439                let trimmed = inner.trim();
1440                if context.check_and_mark_once(trimmed) {
1441                    inner.to_string()
1442                } else {
1443                    String::new()
1444                }
1445            }).to_string();
1446        }
1447
1448        // 1. Template Inheritance: @extends, @section, @yield, @hasSection
1449        s = self.process_inheritance(&s, context, depth);
1450
1451        // 2. Includes: @include, @includeIf, @includeWhen, @includeUnless
1452        s = self.process_includes(&s, context, depth);
1453
1454        // 2c. Blade Components: <x-component-name ... /> dan <x-component-name> ... </x-component-name>
1455        s = self.process_components(&s, context, depth);
1456
1457        // 2b. Stacks: @push, @prepend, @stack
1458        if s.contains("@push") {
1459            for caps in RE_PUSH.captures_iter(&s) {
1460                let name = caps[1].trim();
1461                let body = caps[2].to_string();
1462                context.push_to_stack(name, body);
1463            }
1464            s = RE_PUSH.replace_all(&s, "").to_string();
1465        }
1466        if s.contains("@prepend") {
1467            for caps in RE_PREPEND.captures_iter(&s) {
1468                let name = caps[1].trim();
1469                let body = caps[2].to_string();
1470                context.prepend_to_stack(name, body);
1471            }
1472            s = RE_PREPEND.replace_all(&s, "").to_string();
1473        }
1474        if s.contains("@stack") {
1475            s = RE_STACK.replace_all(&s, |caps: &regex::Captures| {
1476                let name = caps[1].trim();
1477                context.get_stack(name)
1478            }).to_string();
1479        }
1480
1481        // 3. Normalisasi direktif varian kondisional ke @if ... @endif standar
1482        s = self.normalize_conditionals(&s);
1483
1484        // 4. Perulangan: @foreach, @forelse, @for
1485        s = self.process_loops(&s, context, depth);
1486
1487        // 5. Kondisional bercabang: @if, @elseif, @else, @endif (mendukung nesting)
1488        s = self.process_if_blocks(&s, context, depth);
1489
1490        // 6. Switch-Case: @switch, @case, @break, @default, @endswitch
1491        s = self.process_switch(&s, context, depth);
1492
1493        // 7. Form & Security Helpers: @csrf, @method
1494        s = s.replace("@csrf", &format!("<input type=\"hidden\" name=\"csrf_token\" value=\"{}\">", context.get("csrf_token").and_then(|v| v.as_str()).unwrap_or("")));
1495        s = RE_METHOD.replace_all(&s, "<input type=\"hidden\" name=\"_method\" value=\"$1\">").to_string();
1496
1497        // 7a. Asset Bundler: @vite(...)
1498        s = self.process_vite(&s);
1499
1500        // 7b. Form Error Directives: @error('field') ... @enderror
1501        s = self.process_errors(&s, context, depth);
1502
1503        // 8. Attribute Helpers: @checked, @selected, @disabled, @readonly, @required, @class, @style
1504        s = self.process_attributes(&s, context);
1505
1506        // 9. Debug & Output Helpers: @json, @dump, @dd
1507        s = self.process_debug_helpers(&s, context);
1508
1509        // 10. Indonesian Script: @is('script') / @script('script')
1510        s = self.process_indonesian_script(&s);
1511
1512        // 11. Direktif WASM: @wasm('plugin_name', 'function_name', $arg)
1513        s = RE_WASM.replace_all(&s, |caps: &regex::Captures| {
1514            let plugin_name = &caps[1];
1515            let func_name = &caps[2];
1516            let arg = caps.get(3).map(|m| context.eval_val(m.as_str())).unwrap_or_default();
1517            match self.plugin_runner.call_filter(plugin_name, func_name, &arg) {
1518                Ok(out) => out,
1519                Err(e) => format!("<!-- WASM error: {} -->", e),
1520            }
1521        }).to_string();
1522
1523        // 12. Direktif Evaluasi Backend Indonesian Script: @eval_is('file.is', 'func', $arg1, $arg2, ...)
1524        s = RE_EVAL_IS.replace_all(&s, |caps: &regex::Captures| {
1525            let script_path = &caps[1];
1526            let func_name = &caps[2];
1527            let mut args_vec = Vec::new();
1528            if let Some(args_raw) = caps.get(3) {
1529                for arg in args_raw.as_str().split(',') {
1530                    let clean_arg = arg.trim();
1531                    if !clean_arg.is_empty() {
1532                        let evaled = context.eval_val(clean_arg);
1533                        if let Ok(num) = evaled.parse::<f64>() {
1534                            args_vec.push(json!(num));
1535                        } else if evaled == "true" {
1536                            args_vec.push(json!(true));
1537                        } else if evaled == "false" {
1538                            args_vec.push(json!(false));
1539                        } else {
1540                            args_vec.push(json!(evaled));
1541                        }
1542                    }
1543                }
1544            }
1545
1546            match self.plugin_runner.eval_is_script(script_path, func_name, &args_vec) {
1547                Ok(val) => match val {
1548                    Value::String(s) => s,
1549                    Value::Number(n) => {
1550                        if let Some(i) = n.as_i64() {
1551                            i.to_string()
1552                        } else if let Some(f) = n.as_f64() {
1553                            if f.fract() == 0.0 {
1554                                (f as i64).to_string()
1555                            } else {
1556                                f.to_string()
1557                            }
1558                        } else {
1559                            n.to_string()
1560                        }
1561                    },
1562                    Value::Bool(b) => b.to_string(),
1563                    Value::Null => String::new(),
1564                    other => other.to_string(),
1565                },
1566                Err(e) => format!("<!-- Indonesian Script error: {} -->", e),
1567            }
1568        }).to_string();
1569
1570        // 13. Ekstensi Custom Directives (didukung oleh pakem-live atau plugin pihak ketiga - zero regex compilation)
1571        if s.contains('@') {
1572            if let Some(lock) = GLOBAL_DIRECTIVES.get() {
1573                let directives = lock.read().unwrap();
1574                for dir in directives.values() {
1575                    if !s.contains(&dir.name) {
1576                        continue;
1577                    }
1578                    s = dir.re_args.replace_all(&s, |caps: &regex::Captures| {
1579                        (dir.handler)(&caps[1], self, context)
1580                    }).to_string();
1581
1582                    s = dir.re_no_args.replace_all(&s, |_caps: &regex::Captures| {
1583                        (dir.handler)("", self, context)
1584                    }).to_string();
1585                }
1586            }
1587        }
1588        // 15. Interpolasi Variabel & Filter: {!! raw !!} dan {{ escaped }}
1589
1590        s = RE_RAW.replace_all(&s, |caps: &regex::Captures| {
1591            self.eval_expr_with_filters(&caps[1], context)
1592        }).to_string();
1593
1594        s = RE_VAR.replace_all(&s, |caps: &regex::Captures| {
1595            html_escape::encode_safe(&self.eval_expr_with_filters(&caps[1], context))
1596        }).to_string();
1597
1598        // 16. Production Template Shield (@productionShield & anti-inspect / anti-copas)
1599        s = self.process_production_shield(s, context, depth);
1600
1601        s
1602    }
1603
1604    /// Evaluasi ekspresi variabel atau literal yang mungkin memiliki filter berantai:
1605    /// Contoh: `$nominal | rupiah`
1606    /// Contoh: `$title | slug | uppercase`
1607    /// Contoh: `$content | limit: 100`
1608    /// Contoh: `$comment | sensor_kata` (WASM Sandbox)
1609    pub fn eval_expr_with_filters(&self, expr: &str, context: &BladeContext) -> String {
1610        let expr = expr.trim();
1611        if !expr.contains('|') {
1612            return context.eval_val(expr);
1613        }
1614
1615        // Simpan operator '||' jika ada agar tidak terpotong pipa filter
1616        let safe_expr = expr.replace("||", "__LOGICAL_OR__");
1617        let parts: Vec<&str> = safe_expr.split('|').collect();
1618
1619        let base_raw = parts[0].replace("__LOGICAL_OR__", "||");
1620        let mut current_val = context.eval_val(&base_raw);
1621
1622        for segment in &parts[1..] {
1623            let seg = segment.trim();
1624            if seg.is_empty() {
1625                continue;
1626            }
1627
1628            // Parsing filter name dan parameter opsional:
1629            // Format 1 (colon style): filter_name: arg1, arg2
1630            // Format 2 (paren style): filter_name(arg1, arg2)
1631            let (filter_name, args) = if let Some(colon_idx) = seg.find(':') {
1632                let name = seg[..colon_idx].trim();
1633                let raw_args = &seg[colon_idx + 1..];
1634                let args_vec: Vec<&str> = raw_args.split(',').map(|a| a.trim()).collect();
1635                (name, args_vec)
1636            } else if let Some(paren_idx) = seg.find('(') {
1637                let name = seg[..paren_idx].trim();
1638                let end_paren = seg.rfind(')').unwrap_or(seg.len());
1639                let raw_args = &seg[paren_idx + 1..end_paren];
1640                let args_vec: Vec<&str> = raw_args.split(',').map(|a| a.trim()).collect();
1641                (name, args_vec)
1642            } else {
1643                (seg, Vec::new())
1644            };
1645
1646            current_val = self.apply_filter(filter_name, &args, &current_val);
1647        }
1648
1649        current_val
1650    }
1651
1652    /// Terapkan filter pada nilai string (Native Rust Filters + WASM Sandbox Fallback)
1653    fn apply_filter(&self, filter_name: &str, args: &[&str], input: &str) -> String {
1654        match filter_name {
1655            // Native Filter: Format Mata Uang Rupiah
1656            "rupiah" | "formatRupiah" => Self::format_rupiah(input),
1657
1658            // Native Filter: URL Slug Generator
1659            "slug" => Self::slug(input),
1660
1661            // Native Filter: Huruf Besar (Uppercase)
1662            "upper" | "uppercase" => input.to_uppercase(),
1663
1664            // Native Filter: Huruf Kecil (Lowercase)
1665            "lower" | "lowercase" => input.to_lowercase(),
1666
1667            // Native Filter: Kapitalisasi Kata
1668            "capitalize" | "title" => {
1669                let mut c = input.chars();
1670                match c.next() {
1671                    None => String::new(),
1672                    Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
1673                }
1674            }
1675
1676            // Native Filter: Pangkas Spasi
1677            "trim" => input.trim().to_string(),
1678
1679            // Native Filter: Pemotongan Teks (limit: 50 atau potong: 50)
1680            "limit" | "potong" => {
1681                let max_len = args.first().and_then(|a| a.parse::<usize>().ok()).unwrap_or(100);
1682                if input.chars().count() > max_len {
1683                    let truncated: String = input.chars().take(max_len).collect();
1684                    format!("{}...", truncated)
1685                } else {
1686                    input.to_string()
1687                }
1688            }
1689
1690            // Native Filter: Balik Karakter
1691            "reverse" | "balik" => input.chars().rev().collect(),
1692
1693            // Native Filter: Inisial Huruf Pertama
1694            "initial" | "inisial" => {
1695                input.trim().chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default()
1696            }
1697
1698            // Native Filter: Pemotongan String Substring
1699            "substr" | "substring" => {
1700                let start = args.first().and_then(|a| a.parse::<usize>().ok()).unwrap_or(0);
1701                let len = args.get(1).and_then(|a| a.parse::<usize>().ok());
1702                let chars: Vec<char> = input.chars().collect();
1703                if start >= chars.len() {
1704                    String::new()
1705                } else if let Some(l) = len {
1706                    chars.into_iter().skip(start).take(l).collect()
1707                } else {
1708                    chars.into_iter().skip(start).collect()
1709                }
1710            }
1711
1712            // WASM Sandbox Fallback: Delegasikan ke WebAssembly Plugin
1713            custom_filter => {
1714                // 1. Cek pemetaan alias filter terdaftar
1715                if let Some((plugin_name, func_name)) = self.wasm_filters.get(custom_filter) {
1716                    if let Ok(res) = self.plugin_runner.call_filter(plugin_name, func_name, input) {
1717                        return res;
1718                    }
1719                }
1720
1721                // 2. Cek apakah ada modul plugin dengan nama filter itu sendiri
1722                if let Ok(res) = self.plugin_runner.call_filter(custom_filter, "transform", input) {
1723                    return res;
1724                }
1725                if let Ok(res) = self.plugin_runner.call_filter(custom_filter, custom_filter, input) {
1726                    return res;
1727                }
1728
1729                // Jika filter tidak ditemukan, kembalikan teks asli dengan aman tanpa panic
1730                input.to_string()
1731            }
1732        }
1733    }
1734
1735    /// Helper Native: Format angka ke format mata uang Rupiah
1736    pub fn format_rupiah(input: &str) -> String {
1737        let clean = input.trim().replace(',', "");
1738        if let Ok(num) = clean.parse::<f64>() {
1739            let int_part = num.trunc() as i64;
1740            let s = int_part.abs().to_string();
1741            let mut formatted = String::new();
1742            let mut count = 0;
1743            for c in s.chars().rev() {
1744                if count > 0 && count % 3 == 0 {
1745                    formatted.push('.');
1746                }
1747                formatted.push(c);
1748                count += 1;
1749            }
1750            let reversed: String = formatted.chars().rev().collect();
1751            if int_part < 0 {
1752                format!("-Rp {}", reversed)
1753            } else {
1754                format!("Rp {}", reversed)
1755            }
1756        } else {
1757            format!("Rp {}", input)
1758        }
1759    }
1760
1761    /// Helper Native: Mengubah teks menjadi slug URL (contoh: "Halo Dunia!" -> "halo-dunia")
1762    pub fn slug(input: &str) -> String {
1763        let mut result = String::new();
1764        let mut last_was_dash = false;
1765        for c in input.chars() {
1766            if c.is_alphanumeric() {
1767                result.push(c.to_ascii_lowercase());
1768                last_was_dash = false;
1769            } else if !last_was_dash && !result.is_empty() {
1770                result.push('-');
1771                last_was_dash = true;
1772            }
1773        }
1774        if result.ends_with('-') {
1775            result.pop();
1776        }
1777        result
1778    }
1779
1780
1781    /// Normalisasi sintaks kondisional Laravel menjadi format `@if` standar
1782    fn normalize_conditionals(&self, input: &str) -> String {
1783        let mut s = input.to_string();
1784
1785        // @unless(expr) -> @if(!(expr)) & @endunless -> @endif
1786        s = RE_UNLESS.replace_all(&s, "@if(!($1))").to_string();
1787        s = s.replace("@endunless", "@endif");
1788
1789        // @isset(var) -> @if(isset(var)) & @endisset -> @endif
1790        s = RE_ISSET.replace_all(&s, "@if(isset($1))").to_string();
1791        s = s.replace("@endisset", "@endif");
1792
1793        // @empty(var) -> @if(empty(var)) & @endempty -> @endif
1794        s = RE_EMPTY.replace_all(&s, "@if(empty($1))").to_string();
1795        s = s.replace("@endempty", "@endif");
1796
1797        // @auth -> @if(auth) & @endauth -> @endif
1798        s = RE_AUTH.replace_all(&s, "@if(auth)").to_string();
1799        s = s.replace("@endauth", "@endif");
1800
1801        // @guest -> @if(guest) & @endguest -> @endif
1802        s = RE_GUEST.replace_all(&s, "@if(guest)").to_string();
1803        s = s.replace("@endguest", "@endif");
1804
1805        // @can('permission') -> @if(can('permission')) & @endcan -> @endif
1806        s = RE_CAN.replace_all(&s, "@if(can($1))").to_string();
1807        s = s.replace("@endcan", "@endif");
1808
1809        // @cannot('permission') -> @if(cannot($1)) & @endcannot -> @endif
1810        s = RE_CANNOT.replace_all(&s, "@if(cannot($1))").to_string();
1811        s = s.replace("@endcannot", "@endif");
1812
1813        // @role('role') -> @if(role($1)) & @endrole -> @endif
1814        s = RE_ROLE.replace_all(&s, "@if(role($1))").to_string();
1815        s = s.replace("@endrole", "@endif");
1816
1817        // @production -> @if(production) & @endproduction -> @endif
1818        s = RE_PROD.replace_all(&s, "@if(production)").to_string();
1819        s = s.replace("@endproduction", "@endif");
1820
1821        // @env(...) -> @if(env(...)) & @endenv -> @endif
1822        s = RE_ENV.replace_all(&s, "@if(env($1))").to_string();
1823        s = s.replace("@endenv", "@endif");
1824
1825        s
1826    }
1827
1828    /// Penanganan pewarisan template (@extends, @section, @yield)
1829    fn process_inheritance(&self, content: &str, context: &BladeContext, depth: usize) -> String {
1830        let mut s = content.to_string();
1831
1832        
1833        if let Some(caps) = RE_EXTENDS.captures(&s) {
1834            let layout_raw = caps[1].trim().replace('\\', "/");
1835            let layout_content = self.templates.get(&layout_raw)
1836                .or_else(|| {
1837                    let normalized = layout_raw.replace('.', "/");
1838                    let file = if normalized.ends_with(".blade.rs") || normalized.ends_with(".html") {
1839                        normalized
1840                    } else {
1841                        format!("{}.blade.rs", normalized)
1842                    };
1843                    self.templates.get(&file)
1844                });
1845
1846            let mut sections: HashMap<String, String> = HashMap::new();
1847
1848            // Short inline syntax: @section('title', 'Page Title')
1849            
1850            for sec_caps in RE_SHORT_SECTION.captures_iter(&s) {
1851                sections.insert(sec_caps[1].to_string(), sec_caps[2].to_string());
1852            }
1853
1854            // Block syntax: @section('name') ... @endsection / @stop / @show
1855            
1856            for sec_caps in RE_SECTION.captures_iter(&s) {
1857                let sec_name = sec_caps[1].to_string();
1858                let sec_content = sec_caps[2].to_string();
1859                sections.insert(sec_name, sec_content);
1860            }
1861
1862            // Extract @push in child template
1863            for push_caps in RE_PUSH.captures_iter(&s) {
1864                let name = push_caps[1].trim();
1865                let body = push_caps[2].to_string();
1866                context.push_to_stack(name, body);
1867            }
1868            s = RE_PUSH.replace_all(&s, "").to_string();
1869
1870            // Extract @prepend in child template
1871            for prep_caps in RE_PREPEND.captures_iter(&s) {
1872                let name = prep_caps[1].trim();
1873                let body = prep_caps[2].to_string();
1874                context.prepend_to_stack(name, body);
1875            }
1876            s = RE_PREPEND.replace_all(&s, "").to_string();
1877
1878            // Load parent layout
1879            if let Some(parent_content) = layout_content {
1880                let mut layout_processed = parent_content.clone();
1881
1882                // 1. @yield('name', 'default fallback')
1883                layout_processed = RE_YIELD_DEFAULT.replace_all(&layout_processed, |y_caps: &regex::Captures| {
1884                    let y_name = &y_caps[1];
1885                    let y_default = &y_caps[2];
1886                    sections.get(y_name).cloned().unwrap_or_else(|| y_default.to_string())
1887                }).to_string();
1888
1889                // 2. @yield('name')
1890                layout_processed = RE_YIELD.replace_all(&layout_processed, |y_caps: &regex::Captures| {
1891                    let y_name = &y_caps[1];
1892                    sections.get(y_name).cloned().unwrap_or_default()
1893                }).to_string();
1894
1895                // 3. @hasSection('name')
1896                layout_processed = RE_HAS_SEC.replace_all(&layout_processed, |h_caps: &regex::Captures| {
1897                    if sections.contains_key(&h_caps[1]) {
1898                        "@if(true)".to_string()
1899                    } else {
1900                        "@if(false)".to_string()
1901                    }
1902                }).to_string();
1903
1904                s = self.process_template(&layout_processed, context, depth + 1);
1905            }
1906        }
1907
1908        s
1909    }
1910
1911    /// Penanganan @include, @includeIf, @includeWhen, @includeUnless (mendukung parameter data array)
1912    fn process_includes(&self, content: &str, context: &BladeContext, depth: usize) -> String {
1913        let mut s = content.to_string();
1914
1915        // @includeWhen(cond, 'path', ['var' => $val])
1916        s = RE_INC_WHEN.replace_all(&s, |caps: &regex::Captures| {
1917            let inner = &caps[1];
1918            let args = BladeContext::split_arguments(inner);
1919            if args.len() >= 2 {
1920                let cond = &args[0];
1921                let path = args[1].trim().trim_matches('\'').trim_matches('"');
1922                if context.eval_truthy(cond) {
1923                    let mut sub_ctx = context.clone();
1924                    if args.len() >= 3 {
1925                        let extra = BladeContext::parse_blade_array(&args[2], context);
1926                        for (k, v) in extra {
1927                            sub_ctx.insert(&k, v);
1928                        }
1929                    }
1930                    self.resolve_include(path, &sub_ctx, depth, false)
1931                } else {
1932                    String::new()
1933                }
1934            } else {
1935                String::new()
1936            }
1937        }).to_string();
1938
1939        // @includeUnless(cond, 'path', ['var' => $val])
1940        s = RE_INC_UNLESS.replace_all(&s, |caps: &regex::Captures| {
1941            let inner = &caps[1];
1942            let args = BladeContext::split_arguments(inner);
1943            if args.len() >= 2 {
1944                let cond = &args[0];
1945                let path = args[1].trim().trim_matches('\'').trim_matches('"');
1946                if !context.eval_truthy(cond) {
1947                    let mut sub_ctx = context.clone();
1948                    if args.len() >= 3 {
1949                        let extra = BladeContext::parse_blade_array(&args[2], context);
1950                        for (k, v) in extra {
1951                            sub_ctx.insert(&k, v);
1952                        }
1953                    }
1954                    self.resolve_include(path, &sub_ctx, depth, false)
1955                } else {
1956                    String::new()
1957                }
1958            } else {
1959                String::new()
1960            }
1961        }).to_string();
1962
1963        // @includeIf('path', ['var' => $val])
1964        s = RE_INC_IF.replace_all(&s, |caps: &regex::Captures| {
1965            let inner = &caps[1];
1966            let args = BladeContext::split_arguments(inner);
1967            if !args.is_empty() {
1968                let path = args[0].trim().trim_matches('\'').trim_matches('"');
1969                let mut sub_ctx = context.clone();
1970                if args.len() >= 2 {
1971                    let extra = BladeContext::parse_blade_array(&args[1], context);
1972                    for (k, v) in extra {
1973                        sub_ctx.insert(&k, v);
1974                    }
1975                }
1976                self.resolve_include(path, &sub_ctx, depth, true)
1977            } else {
1978                String::new()
1979            }
1980        }).to_string();
1981
1982        // @include('path', ['var' => $val])
1983        s = RE_INC.replace_all(&s, |caps: &regex::Captures| {
1984            let inner = &caps[1];
1985            let args = BladeContext::split_arguments(inner);
1986            if !args.is_empty() {
1987                let path = args[0].trim().trim_matches('\'').trim_matches('"');
1988                let mut sub_ctx = context.clone();
1989                if args.len() >= 2 {
1990                    let extra = BladeContext::parse_blade_array(&args[1], context);
1991                    for (k, v) in extra {
1992                        sub_ctx.insert(&k, v);
1993                    }
1994                }
1995                self.resolve_include(path, &sub_ctx, depth, false)
1996            } else {
1997                String::new()
1998            }
1999        }).to_string();
2000
2001        s
2002    }
2003
2004    fn resolve_include(&self, path_raw: &str, context: &BladeContext, depth: usize, silent: bool) -> String {
2005        let clean = path_raw.trim().replace('\\', "/");
2006        let inc_content = self.templates.get(&clean)
2007            .or_else(|| {
2008                let normalized = clean.replace('.', "/");
2009                let file = if normalized.ends_with(".blade.rs") || normalized.ends_with(".html") {
2010                    normalized
2011                } else {
2012                    format!("{}.blade.rs", normalized)
2013                };
2014                self.templates.get(&file)
2015            });
2016
2017        if let Some(content) = inc_content {
2018            self.process_template(content, context, depth + 1)
2019        } else if silent {
2020            String::new()
2021        } else {
2022            format!("<!-- Include '{}' not found -->", path_raw)
2023        }
2024    }
2025
2026    fn render_component_tag(&self, tag_name: &str, attr_str: &str, body_opt: Option<&str>, context: &BladeContext, depth: usize) -> String {
2027        let clean_name = tag_name.replace('.', "/");
2028        let candidates = [
2029            format!("components/{}.blade.rs", clean_name),
2030            format!("components/{}.blade.rs", clean_name.replace('-', "_")),
2031            format!("components/{}.blade.rs", clean_name.replace('-', "/")),
2032            format!("components/{}.html", clean_name),
2033            format!("{}.blade.rs", clean_name),
2034        ];
2035
2036        let mut comp_content = None;
2037        for cand in &candidates {
2038            if let Some(tmpl) = self.templates.get(cand) {
2039                comp_content = Some(tmpl.clone());
2040                break;
2041            }
2042        }
2043
2044        if let Some(comp_template) = comp_content {
2045            let mut sub_ctx = context.clone();
2046
2047            // 1. Parse attributes
2048            for attr_cap in RE_COMPONENT_ATTR.captures_iter(attr_str) {
2049                if let Some(bound_name) = attr_cap.get(1) {
2050                    let val_expr = attr_cap.get(3).or_else(|| attr_cap.get(4)).map(|m| m.as_str()).unwrap_or("");
2051                    let clean_expr = val_expr.trim_start_matches('$');
2052                    if let Some(v) = context.get(clean_expr) {
2053                        sub_ctx.insert(bound_name.as_str(), v.clone());
2054                    } else {
2055                        let evaled = context.eval_val(val_expr);
2056                        sub_ctx.insert(bound_name.as_str(), evaled);
2057                    }
2058                } else if let Some(plain_name) = attr_cap.get(2) {
2059                    let val = attr_cap.get(3).or_else(|| attr_cap.get(4)).map(|m| m.as_str()).unwrap_or("");
2060                    sub_ctx.insert(plain_name.as_str(), val);
2061                }
2062            }
2063
2064            // 2. Parse slots jika berbentuk block tag
2065            if let Some(body) = body_opt {
2066                let mut slot_body = body.to_string();
2067                for slot_cap in RE_COMPONENT_SLOT.captures_iter(body) {
2068                    let slot_name = slot_cap.get(1).or_else(|| slot_cap.get(2)).map(|m| m.as_str()).unwrap_or("slot");
2069                    let slot_html = &slot_cap[3];
2070                    let rendered_slot = self.process_template(slot_html, context, depth + 1);
2071                    sub_ctx.insert(slot_name, rendered_slot);
2072                }
2073                slot_body = RE_COMPONENT_SLOT.replace_all(&slot_body, "").to_string();
2074                let rendered_default_slot = self.process_template(slot_body.trim(), context, depth + 1);
2075                sub_ctx.insert("slot", rendered_default_slot.clone());
2076                sub_ctx.insert("$slot", rendered_default_slot);
2077            }
2078
2079            self.process_template(&comp_template, &sub_ctx, depth + 1)
2080        } else {
2081            if let Some(body) = body_opt {
2082                format!("<x-{}{}>{}</x-{}>", tag_name, attr_str, body, tag_name)
2083            } else {
2084                format!("<x-{}{}/>", tag_name, attr_str)
2085            }
2086        }
2087    }
2088
2089    /// Penanganan Blade Component modern: <x-alert type="warning" :count="$total">Slot Body</x-alert>
2090    fn process_components(&self, content: &str, context: &BladeContext, depth: usize) -> String {
2091        if !content.contains("<x-") {
2092            return content.to_string();
2093        }
2094
2095        // 1. Self-closing components: <x-alert ... />
2096        let mut s = RE_COMPONENT_SELF.replace_all(content, |caps: &regex::Captures| {
2097            let tag_name = &caps[1];
2098            let attr_str = &caps[2];
2099            self.render_component_tag(tag_name, attr_str, None, context, depth)
2100        }).to_string();
2101
2102        // 2. Block components: <x-card ...> ... </x-card>
2103        loop {
2104            if let Some(m) = RE_COMPONENT_OPEN.find(&s) {
2105                let caps = RE_COMPONENT_OPEN.captures(&s[m.start()..]).unwrap();
2106                let tag_name = caps[1].to_string();
2107                let attr_str = caps[2].to_string();
2108                let open_len = caps[0].len();
2109                let body_start = m.start() + open_len;
2110
2111                let close_tag = format!("</x-{}>", tag_name);
2112                if let Some(close_idx) = s[body_start..].find(&close_tag) {
2113                    let body = s[body_start..body_start + close_idx].to_string();
2114                    let rendered = self.render_component_tag(&tag_name, &attr_str, Some(&body), context, depth);
2115                    s.replace_range(m.start()..body_start + close_idx + close_tag.len(), &rendered);
2116                } else {
2117                    break;
2118                }
2119            } else {
2120                break;
2121            }
2122        }
2123
2124        s
2125    }
2126
2127    /// Penanganan asset bundler Laravel @vite(['resources/css/app.css', 'resources/js/app.js'])
2128    fn process_vite(&self, content: &str) -> String {
2129        if !content.contains("@vite") {
2130            return content.to_string();
2131        }
2132
2133        RE_VITE.replace_all(content, |caps: &regex::Captures| {
2134            let inner = caps[1].trim();
2135            let items: Vec<String> = if inner.starts_with('[') && inner.ends_with(']') {
2136                let inside = &inner[1..inner.len() - 1];
2137                BladeContext::split_arguments(inside)
2138            } else {
2139                vec![inner.to_string()]
2140            };
2141
2142            let mut tags = Vec::new();
2143            for item in items {
2144                let path_raw = item.trim().trim_matches('\'').trim_matches('"');
2145                if path_raw.is_empty() {
2146                    continue;
2147                }
2148                let clean_path = if path_raw.starts_with("resources/") {
2149                    format!("/{}", &path_raw[10..])
2150                } else if path_raw.starts_with('/') {
2151                    path_raw.to_string()
2152                } else {
2153                    format!("/{}", path_raw)
2154                };
2155
2156                if clean_path.ends_with(".css") {
2157                    tags.push(format!(r#"<link rel="stylesheet" href="{}">"#, clean_path));
2158                } else {
2159                    tags.push(format!(r#"<script type="module" src="{}"></script>"#, clean_path));
2160                }
2161            }
2162            tags.join("\n")
2163        }).to_string()
2164    }
2165
2166    /// HTML, CSS, dan JavaScript untuk proteksi template di browser (Anti-DevTools, Anti-Inspect, Anti-Copy)
2167    pub fn production_shield_html() -> &'static str {
2168        r#"<style id="_pakem_shield_css">
2169html,body{-webkit-user-select:none!important;-moz-user-select:none!important;-ms-user-select:none!important;user-select:none!important;-webkit-touch-callout:none!important}
2170img{pointer-events:none!important;-webkit-user-drag:none!important}
2171</style>
2172<script id="_pakem_shield_js">
2173(function(){
2174document.addEventListener("contextmenu",function(e){e.preventDefault();return false;});
2175document.addEventListener("keydown",function(e){
2176if(e.keyCode===123||(e.ctrlKey&&e.keyCode===85)||(e.ctrlKey&&e.keyCode===83)||(e.ctrlKey&&e.shiftKey&&(e.keyCode===73||e.keyCode===74||e.keyCode===67||e.keyCode===75))){
2177e.preventDefault();e.stopPropagation();return false;
2178}
2179});
2180setInterval(function(){(function(){return false;}["constructor"]("debugger")());},100);
2181var _dt=false;
2182setInterval(function(){
2183if((window.outerWidth-window.innerWidth>160)||(window.outerHeight-window.innerHeight>160)){
2184if(!_dt){_dt=true;document.body.innerHTML='<div style="display:flex;justify-content:center;align-items:center;height:100vh;background:#0f172a;color:#ef4444;font-family:sans-serif;font-size:24px;font-weight:700;">Akses Terproteksi (DevTools Dinonaktifkan)</div>';}
2185}
2186},500);
2187})();
2188</script>"#
2189    }
2190
2191    /// Potong komentar JS satu baris (`// ...`) yang berada di luar string/URL agar aman saat one-line minify
2192    fn strip_inline_js_comment(line: &str) -> &str {
2193        let bytes = line.as_bytes();
2194        let mut in_single = false;
2195        let mut in_double = false;
2196        let mut in_backtick = false;
2197        let mut escaped = false;
2198        let mut i = 0;
2199        while i + 1 < bytes.len() {
2200            let b = bytes[i];
2201            if escaped {
2202                escaped = false;
2203                i += 1;
2204                continue;
2205            }
2206            if b == b'\\' && (in_single || in_double || in_backtick) {
2207                escaped = true;
2208                i += 1;
2209                continue;
2210            }
2211            if b == b'\'' && !in_double && !in_backtick {
2212                in_single = !in_single;
2213            } else if b == b'"' && !in_single && !in_backtick {
2214                in_double = !in_double;
2215            } else if b == b'`' && !in_single && !in_double {
2216                in_backtick = !in_backtick;
2217            } else if !in_single && !in_double && !in_backtick && b == b'/' && bytes[i + 1] == b'/' {
2218                if i == 0 || bytes[i - 1] != b':' {
2219                    return line[..i].trim_end();
2220                }
2221            }
2222            i += 1;
2223        }
2224        line
2225    }
2226
2227    /// Helper minifikasi dokumen HTML (menghilangkan baris kosong, komentar, dan memadatkan whitespace menjadi 1 baris)
2228    pub fn minify_html(input: &str) -> String {
2229        let mut out = String::with_capacity(input.len());
2230        let mut prev_space = false;
2231        for line in input.lines() {
2232            let trimmed = Self::strip_inline_js_comment(line.trim());
2233            if trimmed.is_empty() {
2234                continue;
2235            }
2236            if trimmed.starts_with("<!--") && trimmed.ends_with("-->") {
2237                continue;
2238            }
2239            if !out.is_empty() && !prev_space {
2240                out.push(' ');
2241            }
2242            out.push_str(trimmed);
2243            prev_space = trimmed.ends_with('>') || trimmed.ends_with(';');
2244        }
2245        out
2246    }
2247
2248    /// Penanganan proteksi template production dan minifikasi output HTML
2249    fn process_production_shield(&self, mut s: String, context: &BladeContext, depth: usize) -> String {
2250        let shield_requested = s.contains("@productionShield")
2251            || context.get("__production_shield").and_then(|v| v.as_bool()).unwrap_or(false)
2252            || std::env::var("BLADE_PRODUCTION_SHIELD").map(|v| v == "true" || v == "1").unwrap_or(false);
2253
2254        if s.contains("@productionShield") {
2255            s = s.replace("@productionShield", Self::production_shield_html());
2256        } else if shield_requested && depth == 0 {
2257            if s.contains("</body>") {
2258                s = s.replace("</body>", &format!("{}\n</body>", Self::production_shield_html()));
2259            } else {
2260                s.push_str("\n");
2261                s.push_str(Self::production_shield_html());
2262            }
2263        }
2264
2265        let minify_requested = context.get("__minify_html").and_then(|v| v.as_bool()).unwrap_or(false)
2266            || std::env::var("BLADE_MINIFY_HTML").map(|v| v == "true" || v == "1").unwrap_or(false);
2267
2268        if minify_requested && depth == 0 {
2269            s = Self::minify_html(&s);
2270        }
2271
2272        s
2273    }
2274
2275    /// Penanganan perulangan (@foreach, @forelse, @for)
2276    fn process_loops(&self, content: &str, context: &BladeContext, depth: usize) -> String {
2277        let mut s = content.to_string();
2278
2279        loop {
2280            let m_foreach = RE_FOREACH_OPEN.find(&s);
2281            let m_forelse = RE_FORELSE_OPEN.find(&s);
2282            let m_for = RE_FOR_OPEN.find(&s);
2283
2284            let mut candidates: Vec<(&str, usize, usize)> = Vec::new();
2285            if let Some(m) = m_foreach {
2286                candidates.push(("foreach", m.start(), m.end()));
2287            }
2288            if let Some(m) = m_forelse {
2289                candidates.push(("forelse", m.start(), m.end()));
2290            }
2291            if let Some(m) = m_for {
2292                candidates.push(("for", m.start(), m.end()));
2293            }
2294
2295            if candidates.is_empty() {
2296                break;
2297            }
2298
2299            candidates.sort_by_key(|c| c.1);
2300            let earliest = candidates[0];
2301
2302            match earliest.0 {
2303                "foreach" => {
2304                    let start = earliest.1;
2305                    let header = match RE_FOREACH_OPEN.captures(&s[start..]) {
2306                        Some(caps) => caps[1].to_string(),
2307                        None => break,
2308                    };
2309                    let body_start = earliest.2;
2310
2311                    // Cari matching @endforeach
2312                    let mut nesting = 1;
2313                    let mut idx = body_start;
2314                    let mut block_end = None;
2315
2316                    while idx < s.len() {
2317                        let slice = &s[idx..];
2318                        if slice.starts_with("@foreach") {
2319                            nesting += 1;
2320                            idx += 8;
2321                        } else if slice.starts_with("@endforeach") {
2322                            nesting -= 1;
2323                            if nesting == 0 {
2324                                block_end = Some(idx);
2325                                break;
2326                            }
2327                            idx += 11;
2328                        } else {
2329                            idx += slice.chars().next().map_or(1, |c| c.len_utf8());
2330                        }
2331                    }
2332
2333                    if let Some(end) = block_end {
2334                        let body = &s[body_start..end];
2335                        let rendered = self.render_foreach_loop(&header, body, "", context, depth);
2336                        s.replace_range(start..end + "@endforeach".len(), &rendered);
2337                    } else {
2338                        break;
2339                    }
2340                }
2341                "forelse" => {
2342                    let start = earliest.1;
2343                    let header = match RE_FORELSE_OPEN.captures(&s[start..]) {
2344                        Some(caps) => caps[1].to_string(),
2345                        None => break,
2346                    };
2347                    let body_start = earliest.2;
2348
2349                    let mut nesting = 1;
2350                    let mut idx = body_start;
2351                    let mut empty_pos = None;
2352                    let mut block_end = None;
2353
2354                    while idx < s.len() {
2355                        let slice = &s[idx..];
2356                        if slice.starts_with("@forelse") {
2357                            nesting += 1;
2358                            idx += 8;
2359                        } else if slice.starts_with("@empty") && nesting == 1 && (slice[6..].starts_with(|c: char| c.is_whitespace()) || slice.len() == 6) {
2360                            empty_pos = Some(idx);
2361                            idx += 6;
2362                        } else if slice.starts_with("@endforelse") {
2363                            nesting -= 1;
2364                            if nesting == 0 {
2365                                block_end = Some(idx);
2366                                break;
2367                            }
2368                            idx += 11;
2369                        } else {
2370                            idx += slice.chars().next().map_or(1, |c| c.len_utf8());
2371                        }
2372                    }
2373
2374                    if let Some(end) = block_end {
2375                        let (body, empty_body) = if let Some(e_idx) = empty_pos {
2376                            (&s[body_start..e_idx], &s[e_idx + 6..end])
2377                        } else {
2378                            (&s[body_start..end], "")
2379                        };
2380
2381                        let rendered = self.render_foreach_loop(&header, body, empty_body, context, depth);
2382                        s.replace_range(start..end + "@endforelse".len(), &rendered);
2383                    } else {
2384                        break;
2385                    }
2386                }
2387                "for" => {
2388                    let start = earliest.1;
2389                    let header = match RE_FOR_OPEN.captures(&s[start..]) {
2390                        Some(caps) => caps[1].to_string(),
2391                        None => break,
2392                    };
2393                    let body_start = earliest.2;
2394
2395                    let mut nesting = 1;
2396                    let mut idx = body_start;
2397                    let mut block_end = None;
2398
2399                    while idx < s.len() {
2400                        let slice = &s[idx..];
2401                        if slice.starts_with("@for") && !slice.starts_with("@foreach") && !slice.starts_with("@forelse") {
2402                            nesting += 1;
2403                            idx += 4;
2404                        } else if slice.starts_with("@endfor") && !slice.starts_with("@endforeach") && !slice.starts_with("@endforelse") {
2405                            nesting -= 1;
2406                            if nesting == 0 {
2407                                block_end = Some(idx);
2408                                break;
2409                            }
2410                            idx += 7;
2411                        } else {
2412                            idx += slice.chars().next().map_or(1, |c| c.len_utf8());
2413                        }
2414                    }
2415
2416                    if let Some(end) = block_end {
2417                        let body = &s[body_start..end];
2418                        let rendered = self.render_for_loop(&header, body, context, depth);
2419                        s.replace_range(start..end + "@endfor".len(), &rendered);
2420                    } else {
2421                        break;
2422                    }
2423                }
2424                _ => break,
2425            }
2426        }
2427
2428        s
2429    }
2430
2431    fn render_foreach_loop(&self, header: &str, body: &str, empty_body: &str, context: &BladeContext, depth: usize) -> String {
2432        // Syntax: $collection as $item ATAU $collection as $key => $item
2433        let parts: Vec<&str> = header.split(" as ").collect();
2434        if parts.len() != 2 {
2435            return String::new();
2436        }
2437
2438        let coll_expr = parts[0].trim();
2439        let target = parts[1].trim();
2440
2441        let (key_var, item_var) = if let Some(arrow_idx) = target.find("=>") {
2442            (
2443                Some(target[..arrow_idx].trim().trim_start_matches('$').to_string()),
2444                target[arrow_idx + 2..].trim().trim_start_matches('$').to_string(),
2445            )
2446        } else {
2447            (None, target.trim_start_matches('$').to_string())
2448        };
2449
2450        let collection_val = context.get(coll_expr);
2451
2452        match collection_val {
2453            Some(Value::Array(items)) if !items.is_empty() => {
2454                let total = items.len();
2455                let mut out = String::new();
2456                for (idx, item) in items.iter().enumerate() {
2457                    let mut iter_ctx = context.clone();
2458                    iter_ctx.insert_val(&item_var, item.clone());
2459                    if let Some(ref k) = key_var {
2460                        iter_ctx.insert_val(k, json!(idx));
2461                    }
2462
2463                    let loop_obj = json!({
2464                        "index": idx,
2465                        "iteration": idx + 1,
2466                        "remaining": total - (idx + 1),
2467                        "count": total,
2468                        "first": idx == 0,
2469                        "last": idx == total - 1,
2470                        "even": (idx + 1) % 2 == 0,
2471                        "odd": (idx + 1) % 2 != 0,
2472                        "depth": depth + 1,
2473                    });
2474                    iter_ctx.insert_val("loop", loop_obj);
2475                    out.push_str(&self.process_template(body, &iter_ctx, depth + 1));
2476                }
2477                out
2478            }
2479            Some(Value::Object(map)) if !map.is_empty() => {
2480                let total = map.len();
2481                let mut out = String::new();
2482                for (idx, (k, v)) in map.iter().enumerate() {
2483                    let mut iter_ctx = context.clone();
2484                    iter_ctx.insert_val(&item_var, v.clone());
2485                    if let Some(ref kv) = key_var {
2486                        iter_ctx.insert_val(kv, json!(k));
2487                    }
2488
2489                    let loop_obj = json!({
2490                        "index": idx,
2491                        "iteration": idx + 1,
2492                        "remaining": total - (idx + 1),
2493                        "count": total,
2494                        "first": idx == 0,
2495                        "last": idx == total - 1,
2496                        "even": (idx + 1) % 2 == 0,
2497                        "odd": (idx + 1) % 2 != 0,
2498                        "depth": depth + 1,
2499                    });
2500                    iter_ctx.insert_val("loop", loop_obj);
2501                    out.push_str(&self.process_template(body, &iter_ctx, depth + 1));
2502                }
2503                out
2504            }
2505            _ => {
2506                if !empty_body.is_empty() {
2507                    self.process_template(empty_body, context, depth + 1)
2508                } else {
2509                    String::new()
2510                }
2511            }
2512        }
2513    }
2514
2515    fn render_for_loop(&self, header: &str, body: &str, context: &BladeContext, depth: usize) -> String {
2516        // Support: $i in 0..5
2517        if header.contains(" in ") {
2518            let parts: Vec<&str> = header.split(" in ").collect();
2519            if parts.len() == 2 {
2520                let var = parts[0].trim().trim_start_matches('$');
2521                let range_parts: Vec<&str> = parts[1].split("..").collect();
2522                if range_parts.len() == 2 {
2523                    let start: i64 = range_parts[0].trim().parse().unwrap_or(0);
2524                    let end: i64 = range_parts[1].trim().parse().unwrap_or(0);
2525                    let mut out = String::new();
2526                    for i in start..end {
2527                        let mut iter_ctx = context.clone();
2528                        iter_ctx.insert_val(var, json!(i));
2529                        out.push_str(&self.process_template(body, &iter_ctx, depth + 1));
2530                    }
2531                    return out;
2532                }
2533            }
2534        }
2535
2536        // Support standard C/PHP style: $i = 0; $i < 5; $i++
2537        let parts: Vec<&str> = header.split(';').collect();
2538        if parts.len() == 3 {
2539            
2540            
2541            if let (Some(init_caps), Some(cond_caps)) = (RE_INIT.captures(parts[0]), RE_COND.captures(parts[1])) {
2542                let var_name = &init_caps[1];
2543                let start: i64 = init_caps[2].parse().unwrap_or(0);
2544                let end: i64 = cond_caps[1].parse().unwrap_or(0);
2545
2546                let mut out = String::new();
2547                for i in start..end {
2548                    let mut iter_ctx = context.clone();
2549                    iter_ctx.insert_val(var_name, json!(i));
2550                    out.push_str(&self.process_template(body, &iter_ctx, depth + 1));
2551                }
2552                return out;
2553            }
2554        }
2555
2556        String::new()
2557    }
2558
2559    fn extract_balanced_parens<'a>(s: &'a str, open_idx: usize) -> Option<(&'a str, usize)> {
2560        let mut depth = 0;
2561        let bytes = s.as_bytes();
2562        for i in open_idx..s.len() {
2563            if bytes[i] == b'(' {
2564                depth += 1;
2565            } else if bytes[i] == b')' {
2566                depth -= 1;
2567                if depth == 0 {
2568                    return Some((&s[open_idx + 1..i], i + 1));
2569                }
2570            }
2571        }
2572        None
2573    }
2574
2575    /// Penanganan percabangan @if ... @elseif ... @else ... @endif (mendukung nesting)
2576    fn process_if_blocks(&self, input: &str, context: &BladeContext, depth: usize) -> String {
2577        let mut result = input.to_string();
2578
2579        while let Some(if_idx) = result.find("@if") {
2580            let after_if = &result[if_idx + 3..];
2581            let paren_rel = after_if.find('(');
2582            if paren_rel.is_none() || !after_if[..paren_rel.unwrap()].chars().all(|c| c.is_whitespace()) {
2583                break;
2584            }
2585            let open_paren = if_idx + 3 + paren_rel.unwrap();
2586            let (cond, after_if_end) = match Self::extract_balanced_parens(&result, open_paren) {
2587                Some(res) => (res.0.trim().to_string(), res.1),
2588                None => break,
2589            };
2590
2591            let start_pos = if_idx;
2592            let mut branches: Vec<(Option<String>, usize, usize)> = Vec::new();
2593            let mut curr_cond = Some(cond);
2594            let mut curr_branch_start = after_if_end;
2595            let mut nesting = 1;
2596            let mut block_end = None;
2597
2598            let mut idx = after_if_end;
2599
2600            while idx < result.len() {
2601                if result.as_bytes()[idx] == b'@' {
2602                    let slice = &result[idx..];
2603                    if slice.starts_with("@if") && slice[3..].starts_with(|c: char| c.is_whitespace() || c == '(') {
2604                        nesting += 1;
2605                        idx += 3;
2606                        continue;
2607                    } else if slice.starts_with("@endif") {
2608                        nesting -= 1;
2609                        if nesting == 0 {
2610                            branches.push((curr_cond, curr_branch_start, idx));
2611                            block_end = Some(idx + "@endif".len());
2612                            break;
2613                        }
2614                        idx += 6;
2615                        continue;
2616                    } else if nesting == 1 {
2617                        if slice.starts_with("@elseif") {
2618                            let after_elseif = &slice[7..];
2619                            if let Some(p) = after_elseif.find('(') {
2620                                if after_elseif[..p].chars().all(|c| c.is_whitespace()) {
2621                                    if let Some((elseif_cond, after_paren)) = Self::extract_balanced_parens(slice, 7 + p) {
2622                                        branches.push((curr_cond, curr_branch_start, idx));
2623                                        curr_cond = Some(elseif_cond.trim().to_string());
2624                                        idx += after_paren;
2625                                        curr_branch_start = idx;
2626                                        continue;
2627                                    }
2628                                }
2629                            }
2630                        } else if slice.starts_with("@else") && !slice[5..].starts_with(|c: char| c.is_alphanumeric() || c == '_') {
2631                            branches.push((curr_cond, curr_branch_start, idx));
2632                            curr_cond = None;
2633                            idx += 5;
2634                            curr_branch_start = idx;
2635                            continue;
2636                        }
2637                    }
2638                }
2639                idx += result[idx..].chars().next().map_or(1, |c| c.len_utf8());
2640            }
2641
2642            if let Some(end_pos) = block_end {
2643                let mut chosen_content = String::new();
2644                for (branch_cond, b_start, b_end) in branches {
2645                    let is_match = match branch_cond {
2646                        Some(ref c) => context.eval_truthy(c),
2647                        None => true,
2648                    };
2649                    if is_match {
2650                        chosen_content = result[b_start..b_end].to_string();
2651                        break;
2652                    }
2653                }
2654
2655                let rendered_branch = self.process_template(&chosen_content, context, depth + 1);
2656                result.replace_range(start_pos..end_pos, &rendered_branch);
2657            } else {
2658                break;
2659            }
2660        }
2661
2662        result
2663    }
2664
2665    /// Penanganan @switch ... @case ... @default ... @endswitch
2666    fn process_switch(&self, content: &str, context: &BladeContext, depth: usize) -> String {
2667        let mut s = content.to_string();
2668        s = RE_SWITCH.replace_all(&s, |caps: &regex::Captures| {
2669            let target_val = context.eval_val(&caps[1]);
2670            let body = &caps[2];
2671
2672            
2673            let mut matched = false;
2674            let mut output = String::new();
2675
2676            for case_caps in RE_CASES.captures_iter(body) {
2677                let case_val = case_caps[1].trim();
2678                let case_body = case_caps[2].trim();
2679                if case_val == target_val {
2680                    matched = true;
2681                    output = self.process_template(case_body, context, depth + 1);
2682                    break;
2683                }
2684            }
2685
2686            if !matched {
2687                
2688                if let Some(def_caps) = RE_DEFAULT.captures(body) {
2689                    output = self.process_template(def_caps[1].trim(), context, depth + 1);
2690                }
2691            }
2692
2693            output
2694        }).to_string();
2695
2696        s
2697    }
2698
2699    /// Penanganan direktif error validasi form: @error('field') ... @enderror
2700    fn process_errors(&self, content: &str, context: &BladeContext, depth: usize) -> String {
2701        RE_ERROR.replace_all(content, |caps: &regex::Captures| {
2702            let field = &caps[1];
2703            let inner = &caps[2];
2704
2705            if let Some(msg) = context.get_error(field) {
2706                let mut sub_ctx = context.clone();
2707                sub_ctx.insert("message", &msg);
2708                sub_ctx.insert("$message", &msg);
2709                let replaced = inner
2710                    .replace("{{ $message }}", &html_escape::encode_safe(&msg))
2711                    .replace("{{$message}}", &html_escape::encode_safe(&msg))
2712                    .replace("{{ $message}}", &html_escape::encode_safe(&msg))
2713                    .replace("{{$message }}", &html_escape::encode_safe(&msg))
2714                    .replace("{{ message }}", &html_escape::encode_safe(&msg))
2715                    .replace("{{message}}", &html_escape::encode_safe(&msg))
2716                    .replace("{!! $message !!}", &msg)
2717                    .replace("{!!$message!!}", &msg);
2718                self.process_template(&replaced, &sub_ctx, depth + 1)
2719            } else {
2720                String::new()
2721            }
2722        }).to_string()
2723    }
2724
2725    /// Penanganan direktif atribut HTML: @checked, @selected, @disabled, @readonly, @required, @class, @style
2726    fn process_attributes(&self, content: &str, context: &BladeContext) -> String {
2727        let mut s = content.to_string();
2728
2729        // @checked(cond)
2730        s = RE_CHECKED.replace_all(&s, |caps: &regex::Captures| {
2731            if context.eval_truthy(&caps[1]) { "checked" } else { "" }
2732        }).to_string();
2733
2734        // @selected(cond)
2735        s = RE_SELECTED.replace_all(&s, |caps: &regex::Captures| {
2736            if context.eval_truthy(&caps[1]) { "selected" } else { "" }
2737        }).to_string();
2738
2739        // @disabled(cond)
2740        s = RE_DISABLED.replace_all(&s, |caps: &regex::Captures| {
2741            if context.eval_truthy(&caps[1]) { "disabled" } else { "" }
2742        }).to_string();
2743
2744        // @readonly(cond)
2745        s = RE_READONLY.replace_all(&s, |caps: &regex::Captures| {
2746            if context.eval_truthy(&caps[1]) { "readonly" } else { "" }
2747        }).to_string();
2748
2749        // @required(cond)
2750        s = RE_REQUIRED.replace_all(&s, |caps: &regex::Captures| {
2751            if context.eval_truthy(&caps[1]) { "required" } else { "" }
2752        }).to_string();
2753
2754        // @class(['p-4', 'font-bold' => $active, 'hidden' => !$show])
2755        s = RE_CLASS.replace_all(&s, |caps: &regex::Captures| {
2756            let inner = &caps[1];
2757            let mut active_classes: Vec<String> = Vec::new();
2758            for item in inner.split(',') {
2759                let item = item.trim();
2760                if item.is_empty() {
2761                    continue;
2762                }
2763                if let Some(arrow_idx) = item.find("=>") {
2764                    let class_name = item[..arrow_idx].trim().trim_matches('\'').trim_matches('"');
2765                    let cond = item[arrow_idx + 2..].trim();
2766                    if context.eval_truthy(cond) {
2767                        active_classes.push(class_name.to_string());
2768                    }
2769                } else {
2770                    let class_name = item.trim_matches('\'').trim_matches('"');
2771                    if !class_name.is_empty() {
2772                        active_classes.push(class_name.to_string());
2773                    }
2774                }
2775            }
2776            if !active_classes.is_empty() {
2777                format!("class=\"{}\"", active_classes.join(" "))
2778            } else {
2779                String::new()
2780            }
2781        }).to_string();
2782
2783        // @style(['background-color: red' => $hasError])
2784        s = RE_STYLE.replace_all(&s, |caps: &regex::Captures| {
2785            let inner = &caps[1];
2786            let mut active_styles: Vec<String> = Vec::new();
2787            for item in inner.split(',') {
2788                let item = item.trim();
2789                if item.is_empty() {
2790                    continue;
2791                }
2792                if let Some(arrow_idx) = item.find("=>") {
2793                    let style_rule = item[..arrow_idx].trim().trim_matches('\'').trim_matches('"');
2794                    let cond = item[arrow_idx + 2..].trim();
2795                    if context.eval_truthy(cond) {
2796                        active_styles.push(style_rule.to_string());
2797                    }
2798                } else {
2799                    let style_rule = item.trim_matches('\'').trim_matches('"');
2800                    if !style_rule.is_empty() {
2801                        active_styles.push(style_rule.to_string());
2802                    }
2803                }
2804            }
2805            if !active_styles.is_empty() {
2806                format!("style=\"{}\"", active_styles.join("; "))
2807            } else {
2808                String::new()
2809            }
2810        }).to_string();
2811
2812        s
2813    }
2814
2815    /// Penanganan @json, @dump, @dd
2816    fn process_debug_helpers(&self, content: &str, context: &BladeContext) -> String {
2817        let mut s = content.to_string();
2818
2819        // @json($variable)
2820        s = RE_JSON.replace_all(&s, |caps: &regex::Captures| {
2821            let var = caps[1].trim();
2822            if let Some(val) = context.get(var) {
2823                serde_json::to_string(val).unwrap_or_else(|_| "null".to_string())
2824            } else {
2825                "null".to_string()
2826            }
2827        }).to_string();
2828
2829        // @dump($variable) / @dd($variable)
2830        s = RE_DUMP.replace_all(&s, |caps: &regex::Captures| {
2831            let var = caps[1].trim();
2832            let json_str = if let Some(val) = context.get(var) {
2833                serde_json::to_string_pretty(val).unwrap_or_default()
2834            } else {
2835                format!("Variable '{}' not found", var)
2836            };
2837            format!(
2838                "<pre style=\"background:#181825;color:#a6e3a1;padding:12px;border-radius:8px;font-family:monospace;font-size:12px;overflow-x:auto;\">{}</pre>",
2839                html_escape::encode_safe(&json_str)
2840            )
2841        }).to_string();
2842
2843        s
2844    }
2845
2846    /// Penanganan direktif Indonesian Script (@is, @script)
2847    fn process_indonesian_script(&self, content: &str) -> String {
2848        RE_IS.replace_all(content, |caps: &regex::Captures| {
2849            let script_name = caps[1].trim();
2850            let mut file_path = format!("resources/scripts/{}", script_name);
2851            if !file_path.ends_with(".is") {
2852                file_path.push_str(".is");
2853            }
2854
2855            let source = if let Ok(content) = fs::read_to_string(&file_path) {
2856                content
2857            } else {
2858                let alt_path = format!("resources/js/{}", script_name);
2859                let alt_path_is = if alt_path.ends_with(".is") { alt_path.clone() } else { format!("{}.is", alt_path) };
2860                fs::read_to_string(&alt_path_is).unwrap_or_else(|_| format!("// File script '.is' tidak ditemukan: {}", file_path))
2861            };
2862
2863            let compiled_js = indonesian_script::compile_is(&source);
2864            format!("<script>\n{}\n</script>", compiled_js)
2865        }).to_string()
2866    }
2867}
2868
2869#[cfg(test)]
2870mod tests {
2871    use super::*;
2872
2873    #[test]
2874    fn test_blade_extends_and_yield() {
2875        let mut engine = BladeEngine::empty();
2876        engine.templates.insert("layouts/app.blade.rs".to_string(), "<html><title>@yield('title', 'Default Title')</title><body>@yield('content')</body></html>".to_string());
2877        engine.templates.insert("home.blade.rs".to_string(), "@extends('layouts.app')\n@section('title', 'Halaman Utama')\n@section('content')<h1>Halo {{ $name }}</h1>@endsection".to_string());
2878
2879        let mut ctx = BladeContext::new();
2880        ctx.insert("name", "Pakem Pure Blade");
2881
2882        let html = engine.render("home", &ctx);
2883        assert!(html.contains("<title>Halaman Utama</title>"));
2884        assert!(html.contains("<h1>Halo Pakem Pure Blade</h1>"));
2885    }
2886
2887    #[test]
2888    fn test_blade_conditionals_nested() {
2889        let engine = BladeEngine::empty();
2890
2891        let tmpl = r#"
2892        @if ($isAdmin)
2893            <h1>Halo Admin</h1>
2894            @if ($role == 'superadmin')
2895                <span>Full Access</span>
2896            @else
2897                <span>Normal Admin</span>
2898            @endif
2899        @else
2900            <h1>Halo Tamu</h1>
2901        @endif
2902        "#;
2903
2904        let mut ctx = BladeContext::new();
2905        ctx.insert("isAdmin", true);
2906        ctx.insert("role", "superadmin");
2907
2908        let html = engine.render_string(tmpl, &ctx);
2909        assert!(html.contains("Halo Admin"));
2910        assert!(html.contains("Full Access"));
2911        assert!(!html.contains("Halo Tamu"));
2912    }
2913
2914    #[test]
2915    fn test_blade_foreach_and_loop_variable() {
2916        let engine = BladeEngine::empty();
2917
2918        let tmpl = r#"
2919        <ul>
2920        @foreach ($users as $user)
2921            <li>{{ $loop.iteration }}. {{ $user.name }} (first: {{ $loop.first }})</li>
2922        @endforeach
2923        </ul>
2924        "#;
2925
2926        let mut ctx = BladeContext::new();
2927        ctx.insert("users", json!([
2928            {"name": "Alice"},
2929            {"name": "Bob"}
2930        ]));
2931
2932        let html = engine.render_string(tmpl, &ctx);
2933        assert!(html.contains("1. Alice (first: true)"));
2934        assert!(html.contains("2. Bob (first: false)"));
2935    }
2936
2937    #[test]
2938    fn test_blade_forelse_empty() {
2939        let engine = BladeEngine::empty();
2940
2941        let tmpl = r#"
2942        @forelse ($items as $item)
2943            <p>{{ $item }}</p>
2944        @empty
2945            <p class="empty">Tidak ada item</p>
2946        @endforelse
2947        "#;
2948
2949        let mut ctx = BladeContext::new();
2950        ctx.insert("items", json!([]));
2951
2952        let html = engine.render_string(tmpl, &ctx);
2953        assert!(html.contains("Tidak ada item"));
2954    }
2955
2956    #[test]
2957    fn test_blade_auth_guest() {
2958        let engine = BladeEngine::empty();
2959
2960        let tmpl = r#"
2961        @auth
2962            <p>Welcome back, {{ $email }}</p>
2963        @else
2964            <a href="/login">Login</a>
2965        @endauth
2966        "#;
2967
2968        let mut ctx = BladeContext::new();
2969        ctx.insert("user_id", 1);
2970        ctx.insert("email", "admin@pakem.my.id");
2971
2972        let html = engine.render_string(tmpl, &ctx);
2973        assert!(html.contains("Welcome back, admin@pakem.my.id"));
2974        assert!(!html.contains("Login"));
2975    }
2976
2977    #[test]
2978    fn test_blade_attribute_helpers() {
2979        let engine = BladeEngine::empty();
2980
2981        let tmpl = r#"<input type="checkbox" @checked($isActive)> <button @class(['btn', 'btn-primary' => $isPrimary, 'hidden' => $isHidden])>Kirim</button>"#;
2982
2983        let mut ctx = BladeContext::new();
2984        ctx.insert("isActive", true);
2985        ctx.insert("isPrimary", true);
2986        ctx.insert("isHidden", false);
2987
2988        let html = engine.render_string(tmpl, &ctx);
2989        assert!(html.contains("checked"));
2990        assert!(html.contains("class=\"btn btn-primary\""));
2991    }
2992
2993    #[test]
2994    fn test_blade_null_coalescing() {
2995        let engine = BladeEngine::empty();
2996
2997        let tmpl = r#"<p>{{ $username ?? 'Pengguna Anonim' }}</p>"#;
2998        let ctx = BladeContext::new();
2999
3000        let html = engine.render_string(tmpl, &ctx);
3001        assert!(html.contains("Pengguna Anonim"));
3002    }
3003
3004    #[test]
3005    fn test_blade_switch_case() {
3006        let engine = BladeEngine::empty();
3007
3008        let tmpl = r#"
3009        @switch ($status)
3010            @case ('pending')
3011                <span>Menunggu Konfirmasi</span>
3012                @break
3013            @case ('active')
3014                <span>Akun Aktif</span>
3015                @break
3016            @default
3017                <span>Status Tidak Dikenal</span>
3018        @endswitch
3019        "#;
3020
3021        let mut ctx = BladeContext::new();
3022        ctx.insert("status", "active");
3023
3024        let html = engine.render_string(tmpl, &ctx);
3025        assert!(html.contains("Akun Aktif"));
3026        assert!(!html.contains("Menunggu Konfirmasi"));
3027    }
3028
3029    #[test]
3030    fn test_blade_for_loop() {
3031        let engine = BladeEngine::empty();
3032
3033        let tmpl = r#"@for ($i in 1..4)<span>{{ $i }}</span>@endfor"#;
3034        let ctx = BladeContext::new();
3035
3036        let html = engine.render_string(tmpl, &ctx);
3037        assert_eq!(html, "<span>1</span><span>2</span><span>3</span>");
3038    }
3039
3040    #[test]
3041    fn test_blade_dot_notation() {
3042        let engine = BladeEngine::empty();
3043
3044        let tmpl = r#"<p>{{ $user.profile.address.city }}</p>"#;
3045        let mut ctx = BladeContext::new();
3046        ctx.insert("user", json!({
3047            "profile": {
3048                "address": {
3049                    "city": "Bandung"
3050                }
3051            }
3052        }));
3053
3054        let html = engine.render_string(tmpl, &ctx);
3055        assert!(html.contains("Bandung"));
3056    }
3057
3058    #[test]
3059    fn test_blade_native_and_chained_filters() {
3060        let engine = BladeEngine::empty();
3061
3062        let tmpl = r#"
3063        <p>Harga: {{ $harga | rupiah }}</p>
3064        <p>Slug: {{ $judul | slug }}</p>
3065        <p>Rantai: {{ $judul | slug | uppercase }}</p>
3066        <p>Potong: {{ $deskripsi | limit: 10 }}</p>
3067        "#;
3068
3069        let mut ctx = BladeContext::new();
3070        ctx.insert("harga", 150000);
3071        ctx.insert("judul", "Pakem Web Framework Rust!");
3072        ctx.insert("deskripsi", "Ini adalah deskripsi yang sangat panjang sekali");
3073
3074        let html = engine.render_string(tmpl, &ctx);
3075        assert!(html.contains("<p>Harga: Rp 150.000</p>"));
3076        assert!(html.contains("<p>Slug: pakem-web-framework-rust</p>"));
3077        assert!(html.contains("<p>Rantai: PAKEM-WEB-FRAMEWORK-RUST</p>"));
3078        assert!(html.contains("<p>Potong: Ini adalah...</p>"));
3079    }
3080
3081    #[test]
3082    fn test_blade_wasm_filter_pipeline() {
3083        struct TestPluginRunner;
3084        impl BladePluginRunner for TestPluginRunner {
3085            fn call_filter(&self, plugin_name: &str, func_name: &str, arg: &str) -> Result<String, String> {
3086                if plugin_name == "filter_sensor" && func_name == "sensor" {
3087                    return Ok(arg.replace("xxxx", "****"));
3088                }
3089                if plugin_name == "text_tool" && func_name == "kapital" {
3090                    return Ok(arg.to_uppercase());
3091                }
3092                Ok(arg.to_string())
3093            }
3094
3095            fn eval_is_script(&self, script_path: &str, func_name: &str, args: &[Value]) -> Result<Value, String> {
3096                if script_path == "promo.is" && func_name == "hitung_promo" {
3097                    if let Some(total) = args.get(0).and_then(|v| v.as_f64().or_else(|| v.as_i64().map(|i| i as f64))) {
3098                        return Ok(serde_json::json!(total * 0.50));
3099                    }
3100                }
3101                Ok(serde_json::json!(0))
3102            }
3103        }
3104
3105        let mut engine = BladeEngine::empty().with_plugin_runner(Arc::new(TestPluginRunner));
3106        engine.register_wasm_filter("sensor", "filter_sensor", "sensor");
3107
3108        let tmpl = r#"<p>Komentar: {{ $pesan | sensor }}</p>"#;
3109        let mut ctx = BladeContext::new();
3110        ctx.insert("pesan", "teks rahasia xxxx");
3111
3112        let html = engine.render_string(tmpl, &ctx);
3113        assert!(html.contains("<p>Komentar: teks rahasia ****</p>"));
3114    }
3115
3116    #[test]
3117    fn test_blade_wasm_directive() {
3118        struct TestPluginRunner;
3119        impl BladePluginRunner for TestPluginRunner {
3120            fn call_filter(&self, plugin_name: &str, func_name: &str, arg: &str) -> Result<String, String> {
3121                if plugin_name == "text_tool" && func_name == "kapital" {
3122                    return Ok(arg.to_uppercase());
3123                }
3124                Ok(arg.to_string())
3125            }
3126        }
3127
3128        let engine = BladeEngine::empty().with_plugin_runner(Arc::new(TestPluginRunner));
3129
3130        let tmpl = r#"<div>Hasil: @wasm('text_tool', 'kapital', $nama)</div>"#;
3131        let mut ctx = BladeContext::new();
3132        ctx.insert("nama", "canting hybrid");
3133
3134        let html = engine.render_string(tmpl, &ctx);
3135        assert!(html.contains("<div>Hasil: CANTING HYBRID</div>"));
3136    }
3137
3138    #[test]
3139    fn test_blade_eval_is_directive() {
3140        struct TestPluginRunner;
3141        impl BladePluginRunner for TestPluginRunner {
3142            fn eval_is_script(&self, script_path: &str, func_name: &str, args: &[Value]) -> Result<Value, String> {
3143                if script_path == "promo.is" && func_name == "hitung_promo" {
3144                    if let Some(total) = args.get(0).and_then(|v| v.as_f64().or_else(|| v.as_i64().map(|i| i as f64))) {
3145                        return Ok(serde_json::json!(total * 0.50));
3146                    }
3147                }
3148                Ok(serde_json::json!(0))
3149            }
3150        }
3151
3152        let engine = BladeEngine::empty().with_plugin_runner(Arc::new(TestPluginRunner));
3153
3154        let tmpl = r#"<span>Hemat: Rp @eval_is('promo.is', 'hitung_promo', $total, 'DISKON50')</span>"#;
3155        let mut ctx = BladeContext::new();
3156        ctx.insert("total", 100000);
3157
3158        let html = engine.render_string(tmpl, &ctx);
3159        assert!(html.contains("<span>Hemat: Rp 50000</span>"));
3160    }
3161
3162    #[test]
3163    fn test_blade_form_validation_and_helpers() {
3164        let engine = BladeEngine::empty();
3165
3166        let tmpl = r#"
3167        <form method="POST" action="/register">
3168            @csrf
3169            <input type="email" name="email" value="{{ old('email', 'guest@example.com') }}">
3170            @error('email')
3171                <span class="error-msg">{{ $message }}</span>
3172            @enderror
3173
3174            <input type="password" name="password">
3175            @error('password')
3176                <span class="error-msg">{{ $message }}</span>
3177            @enderror
3178
3179            <input type="text" name="phone" value="{{ old('phone', '0812000000') }}">
3180
3181            <link rel="stylesheet" href="{{ asset('css/custom.css') }}">
3182
3183            @if(error('email'))
3184                <div class="alert alert-danger">Ada error pada input email!</div>
3185            @endif
3186
3187            @if(anyErrors)
3188                <div class="summary">Formulir memiliki error validasi.</div>
3189            @endif
3190        </form>
3191        "#;
3192
3193        let mut ctx = BladeContext::new();
3194        ctx.insert("csrf_token", "sec-token-123");
3195
3196        // Suntikkan errors dan old input persis seperti yang dilakukan ViewEngine::render_with_session
3197        let errors_json = serde_json::json!({
3198            "email": "Email ini sudah digunakan oleh akun lain."
3199        });
3200        ctx.insert("errors", errors_json);
3201
3202        let old_json = serde_json::json!({
3203            "email": "salim@example.com"
3204        });
3205        ctx.insert("old", old_json);
3206
3207        let html = engine.render_string(tmpl, &ctx);
3208
3209        // 1. Verifikasi old() mengambil nilai lama
3210        assert!(html.contains("value=\"salim@example.com\""));
3211        // 2. Verifikasi old() fallback ke default jika field tidak ada di old input
3212        assert!(html.contains("value=\"0812000000\""));
3213        // 3. Verifikasi @error('email') merender $message
3214        assert!(html.contains("<span class=\"error-msg\">Email ini sudah digunakan oleh akun lain.</span>"));
3215        // 4. Verifikasi @error('password') yang tidak ada error TIDAK dirender
3216        assert!(!html.contains("@error('password')"));
3217        assert!(!html.contains("@enderror"));
3218        // 5. Verifikasi asset() helper
3219        assert!(html.contains("href=\"/css/custom.css\""));
3220        // 6. Verifikasi error('email') dan anyErrors di @if
3221        assert!(html.contains("Ada error pada input email!"));
3222        assert!(html.contains("Formulir memiliki error validasi."));
3223        // 7. Verifikasi @csrf terisi
3224        assert!(html.contains("value=\"sec-token-123\""));
3225    }
3226
3227    #[test]
3228    fn test_blade_asset_concatenation() {
3229        let engine = BladeEngine::empty();
3230        let tmpl = r#"
3231            <img src="{{ asset('img/gege/logogegefun.avif') }}">
3232            <img src="{{ asset('storage/images/meals/' . $meal.image) }}">
3233            <img src="{{ asset('storage/images/' . $folder . '/' . $filename) }}">
3234        "#;
3235
3236        let mut ctx = BladeContext::new();
3237        ctx.insert("meal", serde_json::json!({ "image": "meals_123.jpg" }));
3238        ctx.insert("folder", "event");
3239        ctx.insert("filename", "party.png");
3240
3241        let html = engine.render_string(tmpl, &ctx);
3242        assert!(html.contains("src=\"/img/gege/logogegefun.avif\""));
3243        assert!(html.contains("src=\"/storage/images/meals/meals_123.jpg\""));
3244        assert!(html.contains("src=\"/storage/images/event/party.png\""));
3245    }
3246
3247    #[test]
3248    fn test_blade_stack_and_push() {
3249        let engine = BladeEngine::empty();
3250        let tmpl = r#"
3251            <head>
3252                @stack('css')
3253            </head>
3254            <body>
3255                @push('scripts')
3256                    <script src="/js/app.js"></script>
3257                @endpush
3258
3259                @prepend('scripts')
3260                    <script src="/js/jquery.js"></script>
3261                @endprepend
3262
3263                @stack('scripts')
3264            </body>
3265        "#;
3266
3267        let ctx = BladeContext::new();
3268        let html = engine.render_string(tmpl, &ctx);
3269
3270        // 1. @stack('css') yang kosong harus bersih (tidak tampil teks @stack('css'))
3271        assert!(!html.contains("@stack('css')"));
3272        assert!(!html.contains("@stack"));
3273
3274        // 2. @prepend harus muncul sebelum @push
3275        let jquery_pos = html.find("jquery.js").unwrap();
3276        let app_pos = html.find("app.js").unwrap();
3277        assert!(jquery_pos < app_pos);
3278
3279        // 3. Teks direktif @push, @prepend, dan @stack tidak boleh ada di HTML output
3280        assert!(!html.contains("@push"));
3281        assert!(!html.contains("@prepend"));
3282        assert!(!html.contains("@endpush"));
3283        assert!(!html.contains("@endprepend"));
3284    }
3285
3286    #[test]
3287    fn test_blade_helpers_and_count() {
3288        let engine = BladeEngine::empty();
3289        let tmpl = r#"
3290            @if(isset($funEvent) && count($funEvent) > 0)
3291                <div class="events">Ada {{ count($funEvent) }} event</div>
3292            @else
3293                <div class="no-events">Belum ada event</div>
3294            @endif
3295
3296            @if($categories.count() > 0)
3297                <div class="cats">Ada {{ $categories.count() }} kategori</div>
3298            @endif
3299
3300            <a href="{{ route('funDetail', ['slug' => $event.slug]) }}">{{ strtoupper($event.title) }}</a>
3301            <a href="{{ route('gegeNewsDetail', $art.slug) }}">Baca Berita</a>
3302            <span>{{ date('d F Y', strtotime($event.date_end)) }}</span>
3303            <span>{{ tanggalOnly($event.date_start) }}</span>
3304            <span>Rp {{ uang($order.grand_total) }}</span>
3305            <span>Jam: {{ substr($event.time_start, 0, 5) }}</span>
3306            <p>{{ __('Delete Account') }}</p>
3307            <div>Sisa: {{ number_format(($event.quota ?? 0) - ($event.booked ?? 0)) }}</div>
3308            <span>First: {{ $items.first()->title }}</span>
3309            <span>Bracket: {{ $meta['author'] }}</span>
3310        "#;
3311
3312        let mut ctx = BladeContext::new();
3313        ctx.insert("funEvent", json!([
3314            {"title": "Konser Musik Tepi Sungai", "slug": "konser-musik"}
3315        ]));
3316        ctx.insert("categories", json!([
3317            {"id": 1, "name": "Event"},
3318            {"id": 2, "name": "Promo"}
3319        ]));
3320        ctx.insert("event", json!({
3321            "title": "live music akustik",
3322            "slug": "live-music",
3323            "date_start": "2024-05-20",
3324            "date_end": "2024-12-31",
3325            "time_start": "19:00:00",
3326            "quota": 100,
3327            "booked": 15
3328        }));
3329        ctx.insert("art", json!({ "slug": "berita-terbaru" }));
3330        ctx.insert("order", json!({ "grand_total": 150000 }));
3331        ctx.insert("items", json!([
3332            {"title": "Item Pertama"}
3333        ]));
3334        ctx.insert("meta", json!({ "author": "Pakem Admin" }));
3335
3336        let html = engine.render_string(tmpl, &ctx);
3337        assert!(html.contains("Ada 1 event"));
3338        assert!(!html.contains("Belum ada event"));
3339        assert!(html.contains("Ada 2 kategori"));
3340        assert!(html.contains("href=\"/funDetail/live-music\""));
3341        assert!(html.contains("LIVE MUSIC AKUSTIK"));
3342        assert!(html.contains("href=\"/gegeNewsDetail/berita-terbaru\""));
3343        assert!(html.contains("31 December 2024"));
3344        assert!(html.contains("20 Mei 2024"));
3345        assert!(html.contains("Rp 150.000"));
3346        assert!(html.contains("Jam: 19:00"));
3347        assert!(html.contains("<p>Delete Account</p>"));
3348        assert!(html.contains("Sisa: 85"));
3349        assert!(html.contains("First: Item Pertama"));
3350        assert!(html.contains("Bracket: Pakem Admin"));
3351    }
3352
3353    #[test]
3354    fn test_blade_include_with_parameters() {
3355        let mut engine = BladeEngine::empty();
3356        engine.templates.insert(
3357            "partials/badge.blade.rs".to_string(),
3358            r#"<span class="badge {{ $type }}">{{ $label }} ({{ $count }})</span>"#.to_string(),
3359        );
3360
3361        let tmpl = r#"
3362            <div>
3363                @include('partials.badge', ['type' => 'success', 'label' => 'Aktif', 'count' => 10])
3364                @include('partials.badge', ['type' => $badgeType, 'label' => $badgeLabel, 'count' => $badgeCount])
3365                @includeWhen(true, 'partials.badge', ['type' => 'info', 'label' => 'Pending', 'count' => 1])
3366                @includeUnless(false, 'partials.badge', ['type' => 'warning', 'label' => 'Warning', 'count' => 0])
3367            </div>
3368        "#;
3369
3370        let mut ctx = BladeContext::new();
3371        ctx.insert("badgeType", "danger");
3372        ctx.insert("badgeLabel", "Nonaktif");
3373        ctx.insert("badgeCount", 5);
3374
3375        let html = engine.render_string(tmpl, &ctx);
3376        assert!(html.contains("class=\"badge success\""));
3377        assert!(html.contains("Aktif (10)"));
3378        assert!(html.contains("class=\"badge danger\""));
3379        assert!(html.contains("Nonaktif (5)"));
3380        assert!(html.contains("Pending (1)"));
3381        assert!(html.contains("Warning (0)"));
3382    }
3383
3384    #[test]
3385    fn test_blade_components() {
3386        let mut engine = BladeEngine::empty();
3387        engine.templates.insert(
3388            "components/alert.blade.rs".to_string(),
3389            r#"<div class="alert alert-{{ $type }}"><h4>{{ $title }}</h4><p>{{ $slot }}</p></div>"#.to_string(),
3390        );
3391        engine.templates.insert(
3392            "components/card.blade.rs".to_string(),
3393            r#"<div class="card"><div class="card-header">{{ $header }}</div><div class="card-body">{{ $slot }}</div></div>"#.to_string(),
3394        );
3395
3396        let tmpl = r#"
3397            <x-alert type="danger" title="Peringatan!">Terjadi kesalahan sistem.</x-alert>
3398            <x-card>
3399                <x-slot:header>Judul Kartu</x-slot>
3400                Konten isi kartu di sini
3401            </x-card>
3402        "#;
3403
3404        let ctx = BladeContext::new();
3405        let html = engine.render_string(tmpl, &ctx);
3406        assert!(html.contains("class=\"alert alert-danger\""));
3407        assert!(html.contains("<h4>Peringatan!</h4>"));
3408        assert!(html.contains("<p>Terjadi kesalahan sistem.</p>"));
3409        assert!(html.contains("<div class=\"card-header\">Judul Kartu</div>"));
3410        assert!(html.contains("<div class=\"card-body\">Konten isi kartu di sini</div>"));
3411    }
3412
3413    #[test]
3414    fn test_blade_vite_and_mix() {
3415        let engine = BladeEngine::empty();
3416        let tmpl = r#"
3417            @vite(['resources/css/app.css', 'resources/js/app.js'])
3418            <script src="{{ mix('js/vendor.js') }}"></script>
3419        "#;
3420
3421        let ctx = BladeContext::new();
3422        let html = engine.render_string(tmpl, &ctx);
3423        assert!(html.contains("<link rel=\"stylesheet\" href=\"/css/app.css\">"));
3424        assert!(html.contains("<script type=\"module\" src=\"/js/app.js\"></script>"));
3425        assert!(html.contains("src=\"/js/vendor.js\""));
3426    }
3427
3428    #[test]
3429    fn test_blade_production_shield_and_minify() {
3430        let engine = BladeEngine::empty();
3431        let tmpl = r#"
3432            <!DOCTYPE html>
3433            <html>
3434                <head><title>Test</title></head>
3435                <body>
3436                    <h1>Rahasia Dagang</h1>
3437                    @productionShield
3438                </body>
3439            </html>
3440        "#;
3441
3442        let mut ctx = BladeContext::new();
3443        ctx.insert("__minify_html", true);
3444
3445        let html = engine.render_string(tmpl, &ctx);
3446        // Memastikan CSS dan JS shield disuntikkan
3447        assert!(html.contains("_pakem_shield_css"));
3448        assert!(html.contains("_pakem_shield_js"));
3449        assert!(html.contains("contextmenu"));
3450        assert!(html.contains("user-select:none!important"));
3451        assert!(html.contains("debugger"));
3452
3453        // Memastikan HTML diminifikasi (tidak ada multiple newline kosong berurutan)
3454        assert!(!html.contains("\n\n"));
3455    }
3456
3457    #[test]
3458    fn test_blade_new_helpers() {
3459        let engine = BladeEngine::empty();
3460        let tmpl = r#"
3461            <p>{{ Str::limit($longText, 10) }}</p>
3462            <p>{{ Str::slug('Judul Artikel Keren') }}</p>
3463            <p>Active: {{ request()->is('admin*') ? 'YES' : 'NO' }}</p>
3464            <p>User: {{ auth()->user()->name }}</p>
3465            <p>Flash: {{ session('success', 'Tidak ada pesan') }}</p>
3466        "#;
3467
3468        let mut ctx = BladeContext::new();
3469        ctx.insert("longText", "Ini adalah teks yang sangat panjang sekali");
3470        ctx.insert("request_path", "/admin/users");
3471        ctx.insert("user", json!({ "id": 1, "name": "Super Admin" }));
3472        ctx.insert("session", json!({ "success": "Data berhasil disimpan!" }));
3473
3474        let html = engine.render_string(tmpl, &ctx);
3475        assert!(html.contains("Ini adalah..."));
3476        assert!(html.contains("judul-artikel-keren"));
3477        assert!(html.contains("Active: YES"));
3478        assert!(html.contains("User: Super Admin"));
3479        assert!(html.contains("Flash: Data berhasil disimpan!"));
3480    }
3481}
3482
3483