rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
//! Declarative response templating: the `{{ function args | filter }}` evaluator (issue #359).
//!
//! This generalizes the existing `${request.*}` substitution (`extensions::template`) into a
//! small function-call grammar so the most common "scripting" use case — pure data transforms
//! from the request (and flow state) into the response — needs no script engine at all.
//!
//! Opt-in via `_rift.templated: true` on an `is` response (wired in `imposter::handler`); when
//! absent/false, a literal `{{` is served verbatim so recorded fixtures never break.
//!
//! # Grammar
//!
//! ```text
//! {{ <head> [args...] [| <filter> [args...]] }}
//! ```
//!
//! `head` is a function name, optionally dotted (`request.query.name`, `state.attempts`). `args`
//! are space-separated words; a single-quoted word (`'like this'`) may contain spaces and is
//! taken literally (no escape sequences in v1). A `key='value'` word is a named argument (used by
//! `now`). Filters chain with `|` and transform the base expression's string result.
//!
//! # Function set (v1)
//!
//! - `request.method`, `request.path`
//! - `request.query.<name>`
//! - `request.header '<Name>'` (case-insensitive)
//! - `request.json '<jsonpath>'` — `$`, dotted keys, `[<index>]` array indexing over the parsed
//!   request body
//! - `now [offset='±Nh|m|s|d'] [format='<strftime>']` — default format is RFC3339
//! - `uuid` — a random UUID v4
//! - `randomInt <a> <b>` — random integer in `[a, b]`
//! - `state.<key>` — read-only flow-state lookup for the request's resolved flow id
//! - `previousValue` — inside a `_rift.stateOps` `set` value only (issue #969): the key's value
//!   before the operation, or empty when it had none
//!
//! Filters: `| last_segment` (trailing `/`-segment), `| regex '<pattern>' <group>` (capture group
//! `<group>` of the first match), `| json` (JSON-string-escape the value so it is safe to place
//! inside a JSON string literal — always apply it when a substituted value goes into `"..."`).
//!
//! # Error policy (AC3)
//!
//! An unknown function/filter, a malformed token, or a failed lookup (missing query param/header/
//! jsonpath segment/state key) is never silent: in debug mode (see [`crate::util::rift_debug_env`])
//! it fails the whole render (surfaced by the caller as a request-time error); otherwise the token
//! is replaced with an empty string and a `tracing::warn!(target: "rift::template", ..)` names it.

use crate::extensions::flow_state::FlowStore;
use crate::extensions::template::RequestData;
use rand::RngExt;
use regex::Regex;
use serde_json::Value;
use std::sync::OnceLock;

/// Everything a `{{ }}` expression may read: the parsed request and a read-only view onto the
/// request's flow state.
pub struct TemplateContext<'a> {
    /// The request the response is being generated for.
    pub request: &'a RequestData,
    /// The resolved flow id for `state.*` lookups (same id the scenario FSM/scripts use).
    pub flow_id: &'a str,
    /// Read-only flow-state backend.
    pub flow_store: &'a dyn FlowStore,
    /// The value `previousValue` renders (issue #969): set only while a `_rift.stateOps` `set`
    /// evaluates its `value` template, to the key's value before that operation. `None` everywhere
    /// else — and then `previousValue` renders as an empty string rather than an error, so an
    /// accumulator's first write reads clean.
    pub previous_value: Option<&'a Value>,
}

/// Render the full `{{ }}` template surface for a `templated: true` response: first expands the
/// legacy relative-date tokens (`{{NOW}}`/`{{DAYS+N}}`/`{{MONTHS+N}}`, issue #195) via
/// [`crate::extensions::template::apply_date_templates`], then evaluates the v1 function-call
/// grammar added by this module. Doing dates first means the two grammars never collide: by the
/// time this module's regex scans the body, no legacy uppercase token is left over to be
/// misread as an unknown function.
pub fn render_templated(
    input: &str,
    ctx: &TemplateContext<'_>,
    debug: bool,
) -> Result<String, String> {
    render_templated_mapped(input, ctx, debug, |value| value)
}

/// [`render_templated`], with every successfully evaluated token's text passed through `map`
/// before it is spliced in.
///
/// Header values need the *substituted* text repaired and the literal text around it left alone
/// (issue #1073), the same boundary `${request.*}`, `copy` and `lookup` already draw
/// ([`crate::extensions::template::process_template_mapped`], issue #1067): a substitution carries
/// request or flow-state data that can hold a byte a header value cannot, while a control
/// character the author typed into the header itself is an authoring bug that must still fail the
/// response. Bodies use [`render_templated`] and substitute verbatim.
///
/// Only *successful* tokens are mapped. A token that fails evaluation substitutes an empty string
/// under the non-debug policy and is left alone — there is nothing to repair, and mapping it would
/// put text where the engine reported a failure.
///
/// The legacy date tokens (`{{NOW}}`/`{{DAYS+N}}`) are expanded by
/// [`crate::extensions::template::apply_date_templates`] *before* this runs, so they are outside
/// the map. That is safe rather than merely tolerated: that pass emits an RFC3339 timestamp, or on
/// offset overflow the untouched token text, and neither can contain a byte a header value cannot
/// carry — so mapping them would be a no-op. The v1 `{{ now format='...' }}` function is a
/// different thing and *is* mapped, like every other substitution.
pub(crate) fn render_templated_mapped<F>(
    input: &str,
    ctx: &TemplateContext<'_>,
    debug: bool,
    map: F,
) -> Result<String, String>
where
    F: Fn(String) -> String,
{
    render_templated_spliced(input, ctx, debug, map).map(crate::behaviors::Spliced::into_text)
}

/// [`render_templated_mapped`], keeping which bytes each token substituted (issue #1203), so the
/// `${request.*}`, `copy` and `lookup` passes that follow never expand a token the request carried
/// in. The date pass runs first over the author's text and is treated as theirs.
pub(crate) fn render_templated_spliced<F>(
    input: &str,
    ctx: &TemplateContext<'_>,
    debug: bool,
    map: F,
) -> Result<crate::behaviors::Spliced, String>
where
    F: Fn(String) -> String,
{
    let expanded = crate::extensions::template::apply_date_templates(input);
    render(
        crate::behaviors::Spliced::authored(expanded),
        ctx,
        debug,
        map,
    )
}

/// The head word of every `{{ ... }}` expression in `input`, in order — `state.hits` for
/// `{{ state.hits | json }}`, `previousValue` for `{{ previousValue }}` — without evaluating any of
/// them. What a caller that must decide *how* to evaluate a template (the `_rift.stateOps` `set`
/// choosing between a plain write and a compare-and-set loop, issue #969) reads, so that decision
/// is made from the grammar and not from a substring search over the raw text.
#[must_use]
pub fn template_heads(input: &str) -> Vec<String> {
    expr_regex()
        .captures_iter(input)
        .filter_map(|caps| {
            let inner = caps.get(1)?.as_str().trim();
            let base = split_top_level(inner, '|').into_iter().next()?;
            tokenize_words(&base).into_iter().next()
        })
        .collect()
}

/// Whether rendering `input` can read the flow store — i.e. whether any `{{ }}` expression the
/// evaluator sees has a `state.<key>` head. Derived from [`template_heads`], so the answer comes
/// from the grammar rather than a substring search.
///
/// Deliberately a **superset** of "will read the store": `{{ state. }}` (empty key) counts as a
/// read even though [`render_templated`] rejects it before touching the store. Callers use this to
/// decide whether to *skip* an offload (issue #986), and the only safe error is to offload when it
/// was not needed — staying inline when a read was coming is the deadlock issue #971 fixed.
///
/// Note it inspects the **date-expanded** text, exactly as [`render_templated`] does, and not the
/// raw input. That pass never emits `{{`, but it does *delete* braces, so it can turn text that
/// matched nothing into a live expression: raw `{{ state.x {{NOW}} }}` contains only the head
/// `NOW`, yet after expansion it is a single `{{ state.x <date> }}` whose head reads the store.
/// Judging the raw text would call that a no-op and strand a blocking read on the worker.
///
/// The `state.` substring pre-check keeps the common case cheap: the date pass emits only date
/// strings, so if `state.` does not occur in the raw input it cannot occur after expansion either,
/// and no head can start with it.
#[must_use]
pub fn reads_flow_state(input: &str) -> bool {
    if !input.contains("state.") {
        return false;
    }
    template_heads(&crate::extensions::template::apply_date_templates(input))
        .iter()
        .any(|head| head.starts_with("state."))
}

/// Evaluate every `{{ ... }}` expression in `input` against `ctx`. In debug mode the first
/// failing token aborts the whole render with an error describing it; otherwise each failing
/// token is replaced with an empty string and logged via `tracing::warn!`.
///
/// `map` is applied to each token's successfully evaluated text before it is spliced in, and to
/// nothing else — not the literal text between tokens, and not a failed token's empty replacement.
/// That is what lets a caller repair a substitution without touching what the author wrote around
/// it (issue #1073).
fn render<F>(
    mut input: crate::behaviors::Spliced,
    ctx: &TemplateContext<'_>,
    debug: bool,
    map: F,
) -> Result<crate::behaviors::Spliced, String>
where
    F: Fn(String) -> String,
{
    let re = expr_regex();
    let mut first_error: Option<String> = None;
    input.replace_regex(re, |caps: &regex::Captures| {
        if first_error.is_some() {
            // Already failing in debug mode; the replacement text is discarded by the Err
            // return below, so its exact content doesn't matter.
            return String::new();
        }
        let raw = &caps[0];
        let inner = caps[1].trim();
        match evaluate(inner, ctx) {
            Ok(value) => map(value),
            Err(reason) => {
                if debug {
                    first_error = Some(format!("template error in `{raw}`: {reason}"));
                } else {
                    tracing::warn!(
                        target: "rift::template",
                        token = %raw,
                        reason = %reason,
                        "template token failed; substituting empty string"
                    );
                }
                String::new()
            }
        }
    });

    match first_error {
        Some(e) => Err(e),
        None => Ok(input),
    }
}

fn expr_regex() -> &'static Regex {
    static EXPR_REGEX: OnceLock<Regex> = OnceLock::new();
    // Non-greedy, no nested braces — matches `{{ ... }}` including the legacy date tokens'
    // syntax shape, but `render_templated` always expands those first (see doc comment above).
    EXPR_REGEX.get_or_init(|| {
        Regex::new(r"\{\{\s*([^{}]+?)\s*\}\}").unwrap_or_else(|e| {
            // A hardcoded, constant pattern failing to compile is a programming error caught
            // immediately by any test exercising this module, not a data-dependent runtime
            // failure — matches the existing static-regex convention in `extensions::template`.
            unreachable!("static template expression regex must compile: {e}")
        })
    })
}

/// Evaluate a single trimmed `{{ ... }}` inner expression (no surrounding braces).
fn evaluate(inner: &str, ctx: &TemplateContext<'_>) -> Result<String, String> {
    let mut segments = split_top_level(inner, '|').into_iter();
    let base = segments.next().unwrap_or_default();
    let base_words = tokenize_words(&base);
    let head = base_words
        .first()
        .ok_or_else(|| "empty template expression".to_string())?;
    let mut value = eval_base(head, &base_words[1..], ctx)?;

    for filter_part in segments {
        let filter_words = tokenize_words(&filter_part);
        let fname = filter_words
            .first()
            .ok_or_else(|| "empty filter after `|`".to_string())?;
        value = apply_filter(&value, fname, &filter_words[1..])?;
    }
    Ok(value)
}

/// Split `s` on top-level occurrences of `sep`, respecting single-quoted substrings (a `sep`
/// inside quotes — e.g. a `|` in a regex pattern — is not a split point).
fn split_top_level(s: &str, sep: char) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;
    for c in s.chars() {
        match c {
            '\'' => {
                in_quotes = !in_quotes;
                current.push(c);
            }
            c if c == sep && !in_quotes => {
                parts.push(std::mem::take(&mut current));
            }
            c => current.push(c),
        }
    }
    parts.push(current);
    parts
}

/// Split `s` into whitespace-separated words, treating a single-quoted run as one word (quote
/// characters are stripped; no escape sequences in v1).
fn tokenize_words(s: &str) -> Vec<String> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;
    let mut has_content = false;
    for c in s.chars() {
        match c {
            '\'' => {
                in_quotes = !in_quotes;
                has_content = true;
            }
            c if c.is_whitespace() && !in_quotes => {
                if has_content {
                    words.push(std::mem::take(&mut current));
                    has_content = false;
                }
            }
            c => {
                current.push(c);
                has_content = true;
            }
        }
    }
    if has_content {
        words.push(current);
    }
    words
}

/// Evaluate the base (pre-filter) expression named `head` with positional/named `args`.
fn eval_base(head: &str, args: &[String], ctx: &TemplateContext<'_>) -> Result<String, String> {
    match head {
        "request.method" => Ok(ctx.request.method.clone()),
        "request.path" => Ok(ctx.request.path.clone()),
        "request.header" => {
            let name = args.first().ok_or_else(|| {
                "request.header requires a quoted header name, e.g. request.header 'Name'"
                    .to_string()
            })?;
            ctx.request
                .headers
                .get(&name.to_lowercase())
                .cloned()
                .ok_or_else(|| format!("no such header: '{name}'"))
        }
        "request.json" => {
            let path = args.first().ok_or_else(|| {
                "request.json requires a quoted jsonpath, e.g. request.json '$.a.b'".to_string()
            })?;
            let json: Value = serde_json::from_str(&ctx.request.body)
                .map_err(|e| format!("request body is not valid JSON: {e}"))?;
            let resolved = eval_jsonpath(&json, path)?;
            Ok(value_to_string(&resolved))
        }
        "now" => {
            let mut offset = None;
            let mut format = None;
            for arg in args {
                if let Some(v) = arg.strip_prefix("offset=") {
                    offset = Some(v.to_string());
                } else if let Some(v) = arg.strip_prefix("format=") {
                    format = Some(v.to_string());
                } else {
                    return Err(format!(
                        "now: unknown argument '{arg}' (expected offset='...' or format='...')"
                    ));
                }
            }
            eval_now(offset.as_deref(), format.as_deref())
        }
        // From the request's stream (issue #1755), so a seeded imposter replays; else the thread's.
        "uuid" => Ok(match crate::imposter::rng::current() {
            Some(mut rng) => {
                let mut bytes = [0u8; 16];
                rand::TryRng::try_fill_bytes(&mut rng, &mut bytes).unwrap_or_else(|e| match e {});
                uuid::Builder::from_random_bytes(bytes).into_uuid()
            }
            None => uuid::Uuid::new_v4(),
        }
        .to_string()),
        // Absent is empty, not an error (unlike `state.<key>`): a `set` whose value template
        // appends to `previousValue` must work on the very first write.
        "previousValue" => Ok(ctx.previous_value.map(value_to_string).unwrap_or_default()),
        "randomInt" => {
            let lo_str = args.first().ok_or_else(|| {
                "randomInt requires two integer arguments: randomInt a b".to_string()
            })?;
            let hi_str = args.get(1).ok_or_else(|| {
                "randomInt requires two integer arguments: randomInt a b".to_string()
            })?;
            let lo: i64 = lo_str
                .parse()
                .map_err(|_| format!("randomInt: invalid integer '{lo_str}'"))?;
            let hi: i64 = hi_str
                .parse()
                .map_err(|_| format!("randomInt: invalid integer '{hi_str}'"))?;
            if lo > hi {
                return Err(format!(
                    "randomInt: lower bound {lo} is greater than upper bound {hi}"
                ));
            }
            // The request's stream (issue #1755), so a seeded imposter replays; else the thread's.
            let n = match crate::imposter::rng::current() {
                Some(mut rng) => rng.random_range(lo..=hi),
                None => rand::rng().random_range(lo..=hi),
            };
            Ok(n.to_string())
        }
        _ => {
            if let Some(name) = head.strip_prefix("request.query.") {
                return ctx
                    .request
                    .query
                    .get(name)
                    .cloned()
                    .ok_or_else(|| format!("no such query parameter: '{name}'"));
            }
            if let Some(key) = head.strip_prefix("state.") {
                if key.is_empty() {
                    return Err("state requires a key, e.g. state.myKey".to_string());
                }
                let found = ctx
                    .flow_store
                    .get(ctx.flow_id, key)
                    .map_err(|e| format!("state.{key}: flow store error: {e:#}"))?;
                return found
                    .map(|v| value_to_string(&v))
                    .ok_or_else(|| format!("no such state key: '{key}'"));
            }
            Err(format!("unknown template function: '{head}'"))
        }
    }
}

/// Apply a `| filter` to the string result of the base expression (or a prior filter).
fn apply_filter(value: &str, name: &str, args: &[String]) -> Result<String, String> {
    match name {
        "last_segment" => Ok(value
            .trim_end_matches('/')
            .rsplit('/')
            .next()
            .unwrap_or("")
            .to_string()),
        "regex" => {
            let pattern = args.first().ok_or_else(|| {
                "regex filter requires a quoted pattern, e.g. | regex '(\\d+)$' 1".to_string()
            })?;
            let group_str = args.get(1).ok_or_else(|| {
                "regex filter requires a capture group number, e.g. | regex '(\\d+)$' 1".to_string()
            })?;
            let group: usize = group_str
                .parse()
                .map_err(|_| format!("regex filter: invalid group number '{group_str}'"))?;
            // Route through the shared regex cache (issue #481) so a templated response that
            // uses this filter does not recompile the pattern on every render.
            let Some(re) = crate::imposter::predicates::regex_cache::cached_regex(pattern, false)
            else {
                // Cold path: an invalid pattern errors anyway — recompile once to surface the
                // concrete syntax error in the message.
                return Err(match Regex::new(pattern) {
                    Err(e) => format!("regex filter: invalid pattern '{pattern}': {e}"),
                    Ok(_) => format!("regex filter: invalid pattern '{pattern}'"),
                });
            };
            let caps = re
                .captures(value)
                .ok_or_else(|| format!("regex filter: pattern '{pattern}' did not match"))?;
            caps.get(group)
                .map(|m| m.as_str().to_string())
                .ok_or_else(|| format!("regex filter: no capture group {group}"))
        }
        // Issue #359 B3 (correctness + security): JSON-string-escape the value so it is safe to
        // place *inside* a JSON string literal in the template (the author writes `"{{ ... | json}}"`
        // — this filter escapes the interior). A substituted value carrying `"`, `\`, a newline, or
        // another control char would otherwise produce an invalid JSON body. We serialize the value
        // as a JSON string and strip the surrounding quotes, yielding just the escaped interior.
        "json" => {
            let quoted = serde_json::to_string(value)
                .map_err(|e| format!("json filter: could not encode value: {e}"))?;
            // `serde_json::to_string(&str)` always yields a `"..."` literal (>= 2 chars); strip the
            // opening and closing quote to leave the escaped interior the author places inline.
            let interior = quoted
                .strip_prefix('"')
                .and_then(|s| s.strip_suffix('"'))
                .unwrap_or(&quoted);
            Ok(interior.to_string())
        }
        _ => Err(format!("unknown template filter: '{name}'")),
    }
}

/// One segment of a parsed `$.a.b[0]`-style jsonpath.
enum PathSegment {
    Key(String),
    Index(usize),
}

/// Hand-rolled minimal jsonpath parser: `$`, dotted keys, `[<index>]` array indexing. Deliberately
/// not a general jsonpath implementation — the v1 function set only needs this subset.
fn parse_jsonpath(path: &str) -> Result<Vec<PathSegment>, String> {
    let rest = path
        .trim()
        .strip_prefix('$')
        .ok_or_else(|| format!("jsonpath must start with '$': '{path}'"))?;
    let mut segments = Vec::new();
    let mut chars = rest.chars().peekable();
    while let Some(&c) = chars.peek() {
        match c {
            '.' => {
                chars.next();
                let mut key = String::new();
                while let Some(&c2) = chars.peek() {
                    if c2 == '.' || c2 == '[' {
                        break;
                    }
                    key.push(c2);
                    chars.next();
                }
                if key.is_empty() {
                    return Err(format!("empty key segment in jsonpath: '{path}'"));
                }
                segments.push(PathSegment::Key(key));
            }
            '[' => {
                chars.next();
                let mut idx = String::new();
                while let Some(&c2) = chars.peek() {
                    if c2 == ']' {
                        break;
                    }
                    idx.push(c2);
                    chars.next();
                }
                if chars.next() != Some(']') {
                    return Err(format!("unterminated '[' in jsonpath: '{path}'"));
                }
                let n: usize = idx
                    .parse()
                    .map_err(|_| format!("invalid array index '{idx}' in jsonpath: '{path}'"))?;
                segments.push(PathSegment::Index(n));
            }
            other => {
                return Err(format!(
                    "unexpected character '{other}' in jsonpath: '{path}'"
                ));
            }
        }
    }
    Ok(segments)
}

/// Resolve `path` (`$`, dotted keys, `[<index>]`) against `root`. A missing key/out-of-bounds
/// index is an `Err` (AC3 policy). Public for `rift wasm check`'s `body.$…` fields (issue #1759).
pub fn eval_jsonpath(root: &Value, path: &str) -> Result<Value, String> {
    let segments = parse_jsonpath(path)?;
    let mut current = root;
    for segment in &segments {
        current = match segment {
            PathSegment::Key(k) => current
                .get(k)
                .ok_or_else(|| format!("jsonpath: no such key '{k}' in '{path}'"))?,
            PathSegment::Index(i) => current
                .get(i)
                .ok_or_else(|| format!("jsonpath: index {i} out of bounds in '{path}'"))?,
        };
    }
    Ok(current.clone())
}

/// Render a resolved JSON value as the string a template token substitutes: a scalar renders as
/// its natural string form, an object/array as compact JSON.
fn value_to_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        // `Value` is always representable as JSON; `unwrap_or_default` only guards the
        // unreachable serialization-error branch (e.g. a NaN float, which `Value` can't hold).
        other => serde_json::to_string(other).unwrap_or_default(),
    }
}

/// Parse an offset like `-36h`/`+2d`/`90m`/`30s` into a `chrono::Duration`.
fn parse_offset(s: &str) -> Result<chrono::Duration, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty offset".to_string());
    }
    let (sign, rest) = match s.chars().next() {
        Some('+') => (1i64, &s[1..]),
        Some('-') => (-1i64, &s[1..]),
        _ => (1i64, s),
    };
    let unit = rest
        .chars()
        .last()
        .ok_or_else(|| format!("empty offset magnitude: '{s}'"))?;
    let num_str = &rest[..rest.len() - unit.len_utf8()];
    let num: i64 = num_str
        .parse()
        .map_err(|_| format!("invalid offset number '{num_str}' in '{s}'"))?;
    let magnitude = match unit {
        's' => chrono::Duration::try_seconds(num),
        'm' => chrono::Duration::try_minutes(num),
        'h' => chrono::Duration::try_hours(num),
        'd' => chrono::Duration::try_days(num),
        other => return Err(format!("invalid offset unit '{other}' (expected s/m/h/d)")),
    }
    .ok_or_else(|| format!("offset overflows the representable range: '{s}'"))?;
    Ok(if sign < 0 { -magnitude } else { magnitude })
}

/// Evaluate `now` with an optional `offset` and `format`. Default format is RFC3339.
fn eval_now(offset: Option<&str>, format: Option<&str>) -> Result<String, String> {
    // The imposter's clock, or the request's X-Rift-Now (issue #1756).
    let mut dt = crate::scripting::env::now_utc();
    if let Some(off) = offset {
        let duration = parse_offset(off)?;
        dt = dt
            .checked_add_signed(duration)
            .ok_or_else(|| format!("now: offset '{off}' overflows the representable date range"))?;
    }
    match format {
        // Issue #359 B2 (no-panic): `chrono::DateTime::format` PANICS on a malformed strftime
        // string (e.g. `format='100%'`, `'%'`, `'%-'`). Validate first by walking the parsed
        // format items; if any is an `Item::Error`, route the failure through the normal AC3 error
        // policy (debug -> 500, else empty + warn) instead of unwinding the connection task.
        Some(fmt) => {
            use chrono::format::{Item, StrftimeItems};
            if StrftimeItems::new(fmt).any(|item| matches!(item, Item::Error)) {
                return Err(format!("now: invalid strftime format string '{fmt}'"));
            }
            Ok(dt.format(fmt).to_string())
        }
        None => Ok(dt.to_rfc3339()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backends::InMemoryFlowStore;
    use std::collections::HashMap;

    /// The shape `collect_request_headers` hands `RequestData::new` (issue #1040).
    fn hdrs(pairs: &[(&str, &[&str])]) -> crate::util::OrderedMap<String, Vec<String>> {
        pairs
            .iter()
            .map(|(k, vs)| {
                (
                    (*k).to_string(),
                    vs.iter().map(|v| (*v).to_string()).collect(),
                )
            })
            .collect()
    }

    fn request_data() -> RequestData {
        let headers = hdrs(&[]);
        let mut data = RequestData::new(
            "POST",
            "/orders/11111111-1111-1111-1111-111111111111",
            Some("name=John&age=30"),
            &headers,
            Some(r#"{"variant":{"variantAttribute":"blue"},"items":[{"id":42},{"id":43}]}"#),
        );
        data.headers
            .insert("x-request-id".to_string(), "req-1".to_string());
        data
    }

    fn store() -> InMemoryFlowStore {
        InMemoryFlowStore::new(60)
    }

    /// Issue #1073: the map sees each *substituted* value and nothing else. The literal text the
    /// author wrote — including a control character they should be told about — is passed through
    /// untouched, which is what lets a header value fail loudly while its substitutions are
    /// repaired.
    #[test]
    fn the_map_is_applied_to_substitutions_only() {
        let request = request_data();
        let store = store();
        let ctx = ctx(&request, "flow", &store);

        // A bracketing map shows *where* the map ran, independent of the literal text's content:
        // whole-value mapping would yield "[a\u{1}bPOST]", so this fails against the old behaviour.
        let out = render_templated_mapped("a\u{1}b{{ request.method }}", &ctx, false, |v| {
            format!("[{v}]")
        })
        .expect("renders");

        assert_eq!(
            out, "a\u{1}b[POST]",
            "only the substitution was mapped; the author's literal text was passed through"
        );
    }

    /// Guards the delegation itself: `render_templated` must stay a thin identity-mapped call and
    /// not grow a second copy of the render logic that could drift from the mapped variant. It does
    /// not verify `render` — the tests above and below do that.
    #[test]
    fn render_templated_is_the_identity_mapped_case() {
        let request = request_data();
        let store = store();
        let ctx = ctx(&request, "flow", &store);

        let input = "a\u{1}b{{ request.method }}";
        assert_eq!(
            render_templated(input, &ctx, false).expect("renders"),
            render_templated_mapped(input, &ctx, false, |v| v).expect("renders"),
        );
    }

    /// What the map is *handed* is the substituted text alone — which is what makes the repair's
    /// warning name the offending fragment instead of echoing the author's literal text back inside
    /// a header-injection accusation (issue #1073). Asserted on the map's input rather than on a log
    /// line: the imposter serves on its own spawned task, so a test subscriber never sees it.
    #[test]
    fn the_map_receives_only_the_substituted_text() {
        let request = request_data();
        let store = store();
        let ctx = ctx(&request, "flow", &store);

        let seen = std::cell::RefCell::new(Vec::new());
        let out = render_templated_mapped(
            "zzmarker-{{ request.method }}-{{ request.path }}",
            &ctx,
            false,
            |v| {
                seen.borrow_mut().push(v.clone());
                v
            },
        )
        .expect("renders");

        assert_eq!(
            *seen.borrow(),
            vec![
                "POST".to_string(),
                "/orders/11111111-1111-1111-1111-111111111111".to_string()
            ],
            "the map sees each substitution and never the literal text around it"
        );
        assert!(out.starts_with("zzmarker-"), "got {out:?}");
    }

    /// The legacy date tokens are expanded by `apply_date_templates` *before* the `{{ }}` grammar
    /// is scanned, so they are outside the map by construction. Pinned because the doc comment
    /// claims it and an identity map could never reveal it.
    #[test]
    fn date_tokens_expand_before_the_map_and_are_not_mapped() {
        let request = request_data();
        let store = store();
        let ctx = ctx(&request, "flow", &store);

        let out =
            render_templated_mapped("{{NOW}}", &ctx, false, |v| format!("[{v}]")).expect("renders");

        assert!(
            !out.contains('['),
            "a date token is expanded before the map and must not pass through it, got {out:?}"
        );
    }

    /// Debug mode aborts the whole render on the first failing token, and the map never sees it —
    /// the failure path must not be able to splice mapped text where the engine reported an error.
    #[test]
    fn a_failed_token_in_debug_mode_aborts_before_the_map() {
        let request = request_data();
        let store = store();
        let ctx = ctx(&request, "flow", &store);

        let err = render_templated_mapped("[{{ nosuchfunction }}]", &ctx, true, |_| {
            "MAPPED".to_string()
        })
        .expect_err("debug mode fails the render");

        assert!(
            err.contains("nosuchfunction"),
            "the error names the offending token, got {err:?}"
        );
    }

    /// A token that fails evaluation substitutes an empty string (non-debug policy) and must not be
    /// handed to the map — there is nothing to repair, and mapping it would let a caller inject
    /// text where the engine reported a failure.
    #[test]
    fn a_failed_token_is_not_mapped() {
        let request = request_data();
        let store = store();
        let ctx = ctx(&request, "flow", &store);

        let out = render_templated_mapped("[{{ nosuchfunction }}]", &ctx, false, |_| {
            "MAPPED".to_string()
        })
        .expect("non-debug substitutes rather than failing");

        assert_eq!(out, "[]", "the failed token is empty, not mapped");
    }

    fn ctx<'a>(
        request: &'a RequestData,
        flow_id: &'a str,
        store: &'a InMemoryFlowStore,
    ) -> TemplateContext<'a> {
        TemplateContext {
            request,
            flow_id,
            flow_store: store,
            previous_value: None,
        }
    }

    // Issue #986: the predicate a caller uses to decide whether a render can be kept on the
    // request task. Every expectation below is a literal.

    #[test]
    fn reads_flow_state_true_only_for_a_state_head() {
        // Reads the store.
        assert!(reads_flow_state("{{ state.hits }}"));
        assert!(
            reads_flow_state("{{state.a|json}}"),
            "no spaces, with a filter"
        );
        assert!(
            reads_flow_state("x {{ now }} {{ state.b }} y"),
            "mixed heads"
        );
        assert!(
            reads_flow_state("{{ state. }}"),
            "empty key is a deliberate over-approximation: render errors on it before touching \
             the store, and reporting a read is the safe direction"
        );

        // Does not.
        assert!(!reads_flow_state("{{ request.path }}"));
        assert!(!reads_flow_state("{{ now }}"));
        assert!(!reads_flow_state("{{ uuid }}"));
        assert!(!reads_flow_state("{{ previousValue }}"));
        assert!(
            !reads_flow_state("{{ state }}"),
            "no dot: an unknown function to the evaluator, which never reaches the store"
        );
        assert!(!reads_flow_state("{{NOW}}"), "legacy date token");
        assert!(!reads_flow_state("plain text with no template at all"));
        assert!(!reads_flow_state(""));
        assert!(!reads_flow_state("{{ unterminated"));

        // The date pass deletes the inner braces before the evaluator runs, turning this into a
        // single `{{ state.x <date> }}` whose head DOES read the store. The predicate must judge
        // the expanded text, not the raw text.
        assert!(reads_flow_state("{{ state.x {{NOW}} }}"));
    }

    /// A table of witnesses for the invariant — not a proof of it. If rendering an input actually
    /// reaches the flow
    /// store, `reads_flow_state` must have said so. A false negative here is not a lost
    /// optimisation — it is the issue #971 deadlock coming back, because the caller would keep a
    /// blocking store read on the tokio worker.
    #[test]
    fn a_render_that_touches_the_store_is_always_predicted() {
        use crate::extensions::flow_state::FlowStore;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct CountingStore {
            inner: crate::backends::inmemory::InMemoryFlowStore,
            gets: AtomicUsize,
        }
        impl FlowStore for CountingStore {
            fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
                self.gets.fetch_add(1, Ordering::SeqCst);
                self.inner.get(flow_id, key)
            }
            fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
                self.inner.set(flow_id, key, value)
            }
            fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
                self.inner.exists(flow_id, key)
            }
            fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
                self.inner.delete(flow_id, key)
            }
            fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
                self.inner.increment(flow_id, key)
            }
            fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
                self.inner.set_ttl(flow_id, ttl_seconds)
            }
            fn compare_and_set(
                &self,
                flow_id: &str,
                key: &str,
                expected: Option<&Value>,
                new: Value,
            ) -> anyhow::Result<crate::extensions::flow_state::CasOutcome> {
                self.inner.compare_and_set(flow_id, key, expected, new)
            }
        }

        let inputs = [
            "{{ state.hits }}",
            "{{state.a|json}}",
            "x {{ now }} {{ state.b }} y",
            "{{ state. }}",
            "{{ request.path }}",
            "{{ now }}",
            "{{ uuid }}",
            "{{ previousValue }}",
            "{{ state }}",
            "{{NOW}}",
            "plain text with no template at all",
            "",
            "{{ unterminated",
            // Belt and braces: a body that reads state twice, and one where the only read is
            // behind a filter.
            "{{ state.a }} and {{ state.b }}",
            "{{ state.c | json }}",
            // The adversarial shape this predicate exists to survive: the legacy date pass runs
            // BEFORE the evaluator and deletes the inner braces, which *creates* a `{{ ... }}`
            // match absent from the raw text. Judging the raw text alone sees only the head `NOW`
            // and misses `state.x` — a false negative, i.e. the #971 deadlock reintroduced.
            "{{ state.x {{NOW}} }}",
        ];

        for input in inputs {
            let store = CountingStore {
                inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
                gets: AtomicUsize::new(0),
            };
            store.set("flow-1", "hits", Value::from(1)).expect("seed");
            store.gets.store(0, Ordering::SeqCst);

            let request = RequestData::new("GET", "/x", None, &hdrs(&[]), None);
            let ctx = TemplateContext {
                request: &request,
                flow_id: "flow-1",
                flow_store: &store,
                previous_value: None,
            };
            // Non-debug so a missing key degrades instead of aborting the render — the store is
            // still consulted either way, which is what this property is about.
            let _ = render_templated(input, &ctx, false);

            let touched = store.gets.load(Ordering::SeqCst) > 0;
            assert!(
                !touched || reads_flow_state(input),
                "FALSE NEGATIVE for {input:?}: the render read the store but the predicate said \
                 it would not — this is the #971 deadlock reintroduced. Note an enumerated table \
                 can only catch shapes someone thought of: the `{{{{NOW}}}}` case below was missed \
                 on the first pass and found by hand."
            );
        }
    }

    #[test]
    fn templated_false_leaves_literal_braces_untouched() {
        // The opt-in gate lives in the handler, not this module — this test just documents that
        // `render_templated` is never reached unless `_rift.templated` is true; a plain string
        // with `{{now}}` is unrelated to that gate. Covered end-to-end in imposter tests.
    }

    #[test]
    fn request_method_and_path() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        assert_eq!(
            render_templated("{{request.method}}", &tctx, false).unwrap(),
            "POST"
        );
        assert_eq!(
            render_templated("{{request.path}}", &tctx, false).unwrap(),
            "/orders/11111111-1111-1111-1111-111111111111"
        );
    }

    #[test]
    fn request_query_present_and_missing() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        assert_eq!(
            render_templated("{{request.query.name}}", &tctx, false).unwrap(),
            "John"
        );
        // Missing query param, non-debug: empty string, no panic.
        assert_eq!(
            render_templated("[{{request.query.missing}}]", &tctx, false).unwrap(),
            "[]"
        );
    }

    #[test]
    fn request_header_case_insensitive() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        assert_eq!(
            render_templated("{{request.header 'X-Request-Id'}}", &tctx, false).unwrap(),
            "req-1"
        );
        assert_eq!(
            render_templated("{{request.header 'x-request-id'}}", &tctx, false).unwrap(),
            "req-1"
        );
    }

    #[test]
    fn request_json_nested_and_array_index() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        assert_eq!(
            render_templated(
                "{{request.json '$.variant.variantAttribute'}}",
                &tctx,
                false
            )
            .unwrap(),
            "blue"
        );
        assert_eq!(
            render_templated("{{request.json '$.items[0].id'}}", &tctx, false).unwrap(),
            "42"
        );
        assert_eq!(
            render_templated("{{request.json '$.items[1].id'}}", &tctx, false).unwrap(),
            "43"
        );
    }

    #[test]
    fn request_json_missing_path_empty_in_non_debug_error_in_debug() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        assert_eq!(
            render_templated("[{{request.json '$.nope'}}]", &tctx, false).unwrap(),
            "[]"
        );
        assert!(render_templated("{{request.json '$.nope'}}", &tctx, true).is_err());
    }

    #[test]
    fn last_segment_filter() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        assert_eq!(
            render_templated("{{request.path | last_segment}}", &tctx, false).unwrap(),
            "11111111-1111-1111-1111-111111111111"
        );
    }

    #[test]
    fn regex_filter_capture_group() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        let out = render_templated(
            "{{request.path | regex '^/orders/([0-9a-f-]+)$' 1}}",
            &tctx,
            false,
        )
        .unwrap();
        assert_eq!(out, "11111111-1111-1111-1111-111111111111");
    }

    // Issue #481: the regex filter now resolves via the shared cache, which returns None on an
    // invalid pattern. The error contract (a message naming the bad pattern) must be preserved.
    #[test]
    fn regex_filter_invalid_pattern_errors() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        // debug=true so a failing token aborts with its error instead of rendering empty.
        let err = render_templated("{{request.path | regex '([' 1}}", &tctx, true).unwrap_err();
        assert!(err.contains("invalid pattern"), "got: {err}");
    }

    #[test]
    fn now_with_offset_and_format() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        let out = render_templated("{{now}}", &tctx, false).unwrap();
        chrono::DateTime::parse_from_rfc3339(&out).expect("default now() is RFC3339");

        let minus = render_templated("{{now offset='-36h'}}", &tctx, false).unwrap();
        let expected = chrono::Utc::now() - chrono::Duration::hours(36);
        let parsed = chrono::DateTime::parse_from_rfc3339(&minus).expect("valid RFC3339");
        assert!((parsed.timestamp() - expected.timestamp()).abs() <= 2);

        let plus = render_templated("{{now offset='+2d'}}", &tctx, false).unwrap();
        let expected = chrono::Utc::now() + chrono::Duration::days(2);
        let parsed = chrono::DateTime::parse_from_rfc3339(&plus).expect("valid RFC3339");
        assert!((parsed.timestamp() - expected.timestamp()).abs() <= 2);

        let formatted = render_templated("{{now format='%Y-%m-%d'}}", &tctx, false).unwrap();
        assert_eq!(formatted.len(), "2026-07-08".len());
    }

    #[test]
    fn uuid_is_valid_v4_shape() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        let out = render_templated("{{uuid}}", &tctx, false).unwrap();
        let parsed = uuid::Uuid::parse_str(&out).expect("valid uuid");
        assert_eq!(parsed.get_version_num(), 4);
    }

    #[test]
    fn random_int_in_range() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        for _ in 0..20 {
            let out = render_templated("{{randomInt 5 9}}", &tctx, false).unwrap();
            let n: i64 = out.parse().expect("integer output");
            assert!((5..=9).contains(&n), "randomInt out of range: {n}");
        }
    }

    #[test]
    fn state_present_and_missing() {
        let data = request_data();
        let s = store();
        s.set("flow-1", "attempts", serde_json::json!(3)).unwrap();
        let tctx = ctx(&data, "flow-1", &s);
        assert_eq!(
            render_templated("{{state.attempts}}", &tctx, false).unwrap(),
            "3"
        );
        assert_eq!(
            render_templated("[{{state.missing}}]", &tctx, false).unwrap(),
            "[]"
        );
        assert!(render_templated("{{state.missing}}", &tctx, true).is_err());
    }

    #[test]
    fn unknown_function_debug_errors_non_debug_empty_and_warns() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        assert!(render_templated("{{bogus}}", &tctx, true).is_err());
        assert_eq!(render_templated("[{{bogus}}]", &tctx, false).unwrap(), "[]");
    }

    #[test]
    fn headers_map_dotted_query_and_multiple_tokens_in_one_body() {
        let mut headers = HashMap::new();
        headers.insert("q".to_string(), "1".to_string());
        let hm = hdrs(&[]);
        let data = RequestData::new("GET", "/x/abc", Some("q=1"), &hm, None);
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        let out = render_templated(
            "{\"method\":\"{{request.method}}\",\"q\":\"{{request.query.q}}\",\"seg\":\"{{request.path | last_segment}}\"}",
            &tctx,
            false,
        )
        .unwrap();
        assert_eq!(out, r#"{"method":"GET","q":"1","seg":"abc"}"#);
        let _ = headers; // silence unused warning if headers map above is unused elsewhere
    }

    #[test]
    fn legacy_date_tokens_still_expand_through_render_templated() {
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        let out = render_templated("{{NOW}}", &tctx, false).unwrap();
        chrono::DateTime::parse_from_rfc3339(&out).expect("legacy {{NOW}} still expands");
    }

    #[test]
    fn now_malformed_format_is_error_not_panic() {
        // Issue #359 B2: a malformed strftime format must route through the error policy, never
        // panic. In debug it fails the render; in non-debug it degrades to empty + warn.
        let data = request_data();
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        for bad in ["100%", "%", "%-"] {
            let token = format!("{{{{now format='{bad}'}}}}");
            assert!(
                render_templated(&token, &tctx, true).is_err(),
                "malformed format '{bad}' must be a debug-mode error"
            );
            // Non-debug: never panics, degrades to empty string.
            assert_eq!(
                render_templated(&format!("[{token}]"), &tctx, false).unwrap(),
                "[]",
                "malformed format '{bad}' must degrade to empty in non-debug"
            );
        }
        // A valid format still works.
        let ok = render_templated("{{now format='%Y-%m-%d'}}", &tctx, false).unwrap();
        assert_eq!(ok.len(), "2026-07-08".len());
    }

    #[test]
    fn json_filter_escapes_for_string_literal() {
        // Issue #359 B3: `| json` escapes a value so it is safe inside a JSON string literal.
        let headers = hdrs(&[("X-Payload", &[r#"he said "hi"\ and left"#])]);
        let data = RequestData::new("GET", "/x", None, &headers, None);
        let s = store();
        let tctx = ctx(&data, "flow-1", &s);
        // Compose a JSON body where the escaped value is placed inside a string literal.
        let out = render_templated(
            r#"{"echo":"{{request.header 'X-Payload' | json}}"}"#,
            &tctx,
            false,
        )
        .unwrap();
        let parsed: Value = serde_json::from_str(&out).expect("json filter yields valid JSON body");
        assert_eq!(parsed["echo"], r#"he said "hi"\ and left"#);
    }

    #[test]
    fn jsonpath_parser_rejects_malformed_paths() {
        assert!(parse_jsonpath("a.b").is_err(), "must start with $");
        assert!(parse_jsonpath("$.a[").is_err(), "unterminated [");
        assert!(parse_jsonpath("$.a[x]").is_err(), "non-numeric index");
    }
}