contextual-encoder 0.10.0

contextual output encoding for xss defense and safe literal embedding, inspired by the owasp java encoder
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
//! javascript contextual output encoders.
//!
//! provides five encoding contexts:
//!
//! - [`for_javascript`] — universal encoder, safe in HTML attributes, script
//!   blocks, and standalone .js files
//! - [`for_javascript_attribute`] — optimized for HTML event attributes
//!   (e.g., `onclick="..."`)
//! - [`for_javascript_block`] — optimized for `<script>` blocks
//! - [`for_javascript_source`] — optimized for standalone .js files
//! - [`for_js_template`] — for ES6 template literal content (`` `...` ``)
//!
//! # security notes
//!
//! - the string literal encoders ([`for_javascript`], [`for_javascript_attribute`],
//!   [`for_javascript_block`], [`for_javascript_source`]) do **not** encode the
//!   grave accent (`` ` ``). do not use them to embed data inside template
//!   literals — use [`for_js_template`] instead.
//! - these encoders are for string/template literal contexts only. they cannot
//!   make arbitrary javascript expressions, variable names, or property
//!   accessors safe.
//! - `for_javascript_block` and `for_javascript_source` use backslash escapes
//!   for quotes (`\"`, `\'`) which are **not safe in HTML attribute contexts**.
//! - `for_javascript_attribute` does not escape `<` or `/` and is **not safe
//!   in `<script>` blocks** where `</script>` could appear.
//! - `for_javascript_source` does not escape `&`, so it is **not safe in an
//!   XHTML `<script>`**, where character references are decoded before
//!   javascript sees the text. the other four encoders escape it.
//! - all five encoders escape the bidi formatting controls (U+202A-U+202E,
//!   U+2066-U+2069) as `\uHHHH`, so a direction override in the data cannot
//!   reorder how the generated javascript reads.
//! - none of these encoders produce valid JSON — the `\xHH` escapes they emit
//!   for control characters are not permitted in JSON. use
//!   [`for_json`](crate::for_json) for JSON string values.

use std::fmt;

use crate::engine::{encode_loop, is_text_direction_control};

/// configuration flags controlling context-specific encoding differences.
#[derive(Clone, Copy)]
struct JsConfig {
    /// true: `"` → `\x22`, `'` → `\x27` (safe in HTML attributes).
    /// false: `"` → `\"`, `'` → `\'` (more readable, not HTML-attr safe).
    hex_quotes: bool,
    /// true: encode `&` as `\x26` (prevents HTML entity interpretation).
    encode_ampersand: bool,
    /// true: the output can land in HTML script data, so encode every
    /// character that can move the tokenizer out of it — `<` → `\x3c` and
    /// `/` → `\/`.
    script_data: bool,
}

const JS_UNIVERSAL: JsConfig = JsConfig {
    hex_quotes: true,
    encode_ampersand: true,
    script_data: true,
};

const JS_ATTRIBUTE: JsConfig = JsConfig {
    hex_quotes: true,
    encode_ampersand: true,
    script_data: false,
};

const JS_BLOCK: JsConfig = JsConfig {
    hex_quotes: false,
    encode_ampersand: true,
    script_data: true,
};

const JS_SOURCE: JsConfig = JsConfig {
    hex_quotes: false,
    encode_ampersand: false,
    script_data: false,
};

/// encodes `input` for safe embedding in a javascript string literal.
///
/// this is the universal javascript encoder — its output is safe in HTML
/// event attributes, `<script>` blocks, and standalone .js files. it is
/// slightly more conservative than the context-specific encoders.
///
/// # encoding rules
///
/// - C0 controls → named escapes (`\b`, `\t`, `\n`, `\f`, `\r`) or hex
///   (`\xHH`)
/// - `"` → `\x22`, `'` → `\x27` (hex escapes for HTML attribute safety)
/// - `&` → `\x26` (prevents HTML entity interpretation)
/// - `<` → `\x3c`, `/` → `\/` (keeps the HTML tokenizer in script data state,
///   so the enclosing `</script>` still closes the block)
/// - `\` → `\\`
/// - U+2028 → `\u2028`, U+2029 → `\u2029` (javascript line terminators)
/// - bidi formatting controls (U+202A-U+202E, U+2066-U+2069) → `\uHHHH`
///
/// # caveat: template literals
///
/// this encoder does **not** encode the grave accent (`` ` ``). never
/// embed untrusted data directly inside template literals. instead:
///
/// ```js
/// // WRONG — vulnerable to XSS:
/// // `Hello ${unsafeInput}`
/// //
/// // RIGHT — encode into a variable first:
/// // var x = '<encoded>';
/// // `Hello ${x}`
/// ```
///
/// # examples
///
/// ```
/// use contextual_encoder::for_javascript;
///
/// assert_eq!(for_javascript(r#"it's "unsafe" </script>"#),
///            r"it\x27s \x22unsafe\x22 \x3c\/script>");
/// assert_eq!(for_javascript("safe"), "safe");
/// ```
pub fn for_javascript(input: &str) -> String {
    encode_js(input, &JS_UNIVERSAL)
}

/// writes the javascript-encoded form of `input` to `out`.
///
/// see [`for_javascript`] for encoding rules.
pub fn write_javascript<W: fmt::Write>(out: &mut W, input: &str) -> fmt::Result {
    write_js(out, input, &JS_UNIVERSAL)
}

/// encodes `input` for safe embedding in a javascript string literal inside
/// an HTML event attribute (e.g., `onclick="..."`).
///
/// identical to [`for_javascript`] except `<` and `/` are **not** escaped. an
/// attribute value is never tokenized as script data, so neither character can
/// affect where the enclosing element ends.
///
/// **not safe in `<script>` blocks** — use [`for_javascript`] or
/// [`for_javascript_block`] instead.
///
/// # examples
///
/// ```
/// use contextual_encoder::for_javascript_attribute;
///
/// assert_eq!(for_javascript_attribute("a/b"), "a/b");
/// assert_eq!(for_javascript_attribute("a<b"), "a<b");
/// assert_eq!(for_javascript_attribute("a'b"), r"a\x27b");
/// ```
pub fn for_javascript_attribute(input: &str) -> String {
    encode_js(input, &JS_ATTRIBUTE)
}

/// writes the javascript-attribute-encoded form of `input` to `out`.
///
/// see [`for_javascript_attribute`] for encoding rules.
pub fn write_javascript_attribute<W: fmt::Write>(out: &mut W, input: &str) -> fmt::Result {
    write_js(out, input, &JS_ATTRIBUTE)
}

/// encodes `input` for safe embedding in a javascript string literal inside
/// an HTML `<script>` block.
///
/// uses backslash escapes for quotes (`\"`, `\'`) which are more readable
/// but **not safe in HTML attribute contexts**. still encodes `&` (for XHTML
/// compatibility) and `<`/`/`, which keep the HTML tokenizer in script data
/// state so the enclosing `</script>` still closes the block.
///
/// # examples
///
/// ```
/// use contextual_encoder::for_javascript_block;
///
/// assert_eq!(for_javascript_block(r#"he said "hi""#), r#"he said \"hi\""#);
/// assert_eq!(for_javascript_block("</script>"), r"\x3c\/script>");
/// assert_eq!(for_javascript_block("<!--<script>"), r"\x3c!--\x3cscript>");
/// ```
pub fn for_javascript_block(input: &str) -> String {
    encode_js(input, &JS_BLOCK)
}

/// writes the javascript-block-encoded form of `input` to `out`.
///
/// see [`for_javascript_block`] for encoding rules.
pub fn write_javascript_block<W: fmt::Write>(out: &mut W, input: &str) -> fmt::Result {
    write_js(out, input, &JS_BLOCK)
}

/// encodes `input` for safe embedding in a javascript string literal in a
/// standalone .js file.
///
/// the most minimal javascript encoder — does not encode `<`, `/` or `&`
/// since a standalone .js file is never HTML-tokenized. **not safe for any
/// HTML-embedded context.**
///
/// **not a JSON encoder.** it emits `\'` for single quotes and `\xHH` for
/// control characters, neither of which JSON permits. use
/// [`for_json`](crate::for_json) for JSON string values.
///
/// # examples
///
/// ```
/// use contextual_encoder::{for_javascript_source, for_json};
///
/// assert_eq!(for_javascript_source("a/b&c<d"), "a/b&c<d");
/// assert_eq!(for_javascript_source("line\nbreak"), r"line\nbreak");
///
/// assert_eq!(for_javascript_source("it's"), r"it\'s");
/// assert_eq!(for_json("it's"), "it's");
/// ```
pub fn for_javascript_source(input: &str) -> String {
    encode_js(input, &JS_SOURCE)
}

/// writes the javascript-source-encoded form of `input` to `out`.
///
/// see [`for_javascript_source`] for encoding rules.
pub fn write_javascript_source<W: fmt::Write>(out: &mut W, input: &str) -> fmt::Result {
    write_js(out, input, &JS_SOURCE)
}

/// encodes `input` for safe embedding inside an ES6 template literal
/// (`` `...` ``).
///
/// template literals use backticks as delimiters and `${...}` for
/// interpolation. this encoder escapes both so untrusted data cannot break
/// out of the literal or inject expressions.
///
/// # encoding rules
///
/// - `` ` `` → `` \` `` (prevents breaking out of the template literal)
/// - `$` followed by `{`, and `$` at the end of the input → `\$` (prevents
///   expression interpolation, including a `${` the caller completes)
/// - `\` → `\\`
/// - `<` → `\x3c`, `/` → `\/` (keeps the HTML tokenizer in script data state,
///   so the enclosing `</script>` still closes the block)
/// - `&` → `\x26` (stops an XHTML parser decoding a character reference into
///   a `` ` `` or a `${` before javascript sees the text)
/// - C0 controls → named escapes (`\b`, `\t`, `\n`, `\f`, `\r`) or hex
///   (`\xHH`)
/// - U+2028 → `\u2028`, U+2029 → `\u2029` (line/paragraph separators)
/// - bidi formatting controls (U+202A-U+202E, U+2066-U+2069) → `\uHHHH`
///
/// unlike the string literal encoders, this does **not** escape `"` or `'`
/// (they are ordinary characters inside template literals).
///
/// # examples
///
/// ```
/// use contextual_encoder::for_js_template;
///
/// assert_eq!(for_js_template("hello `world`"), r"hello \`world\`");
/// assert_eq!(for_js_template("${alert(1)}"), r"\${alert(1)}");
/// assert_eq!(for_js_template("safe"), "safe");
/// // `\x26` is `&` in a template literal, so the decoded value is unchanged
/// assert_eq!(for_js_template("a&b"), r"a\x26b");
/// assert_eq!(for_js_template("&#96;"), r"\x26#96;");
/// assert_eq!(for_js_template("a $ b"), "a $ b");
/// // `\$` is `$` in a template literal, so the decoded value is unchanged
/// assert_eq!(for_js_template("cost: $"), r"cost: \$");
/// ```
pub fn for_js_template(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    write_js_template(&mut out, input).expect("writing to string cannot fail");
    out
}

/// writes the template-literal-encoded form of `input` to `out`.
///
/// see [`for_js_template`] for encoding rules.
pub fn write_js_template<W: fmt::Write>(out: &mut W, input: &str) -> fmt::Result {
    encode_loop(
        out,
        input,
        needs_js_template_encoding,
        write_js_template_encoded,
    )
}

fn needs_js_template_encoding(c: char) -> bool {
    matches!(
        c,
        '\x00'..='\x1F' | '\\' | '`' | '$' | '&' | '/' | '<' | '\u{2028}' | '\u{2029}'
    ) || is_text_direction_control(c)
}

fn write_js_template_encoded<W: fmt::Write>(
    out: &mut W,
    c: char,
    next: Option<char>,
) -> fmt::Result {
    match c {
        // template-specific characters
        '`' => out.write_str("\\`"),
        '$' if matches!(next, Some('{') | None) => out.write_str("\\$"),
        '$' => out.write_char('$'),
        '&' => out.write_str("\\x26"),
        '/' => out.write_str("\\/"),
        '<' => out.write_str("\\x3c"),
        c => write_js_shared_escape(out, c),
    }
}

fn encode_js(input: &str, config: &JsConfig) -> String {
    let mut out = String::with_capacity(input.len());
    write_js(&mut out, input, config).expect("writing to string cannot fail");
    out
}

fn write_js<W: fmt::Write>(out: &mut W, input: &str, config: &JsConfig) -> fmt::Result {
    encode_loop(
        out,
        input,
        |c| needs_js_encoding(c, config),
        |out, c, _next| write_js_encoded(out, c, config),
    )
}

fn needs_js_encoding(c: char, config: &JsConfig) -> bool {
    match c {
        '\x00'..='\x1F' | '\\' | '"' | '\'' | '\u{2028}' | '\u{2029}' => true,
        '&' => config.encode_ampersand,
        '/' | '<' => config.script_data,
        c => is_text_direction_control(c),
    }
}

fn write_js_encoded<W: fmt::Write>(out: &mut W, c: char, config: &JsConfig) -> fmt::Result {
    match c {
        // string-literal-specific characters
        '"' if config.hex_quotes => out.write_str("\\x22"),
        '"' => out.write_str("\\\""),
        '\'' if config.hex_quotes => out.write_str("\\x27"),
        '\'' => out.write_str("\\'"),
        '&' => out.write_str("\\x26"),
        '/' => out.write_str("\\/"),
        '<' => out.write_str("\\x3c"),
        c => write_js_shared_escape(out, c),
    }
}

/// writes the escape shared by both js encoders. any other character falls back
/// to `\u{...}` so a character a predicate flags can never be dropped from the
/// output.
fn write_js_shared_escape<W: fmt::Write>(out: &mut W, c: char) -> fmt::Result {
    match c {
        '\x08' => out.write_str("\\b"),
        '\t' => out.write_str("\\t"),
        '\n' => out.write_str("\\n"),
        '\x0B' => out.write_str("\\x0b"),
        '\x0C' => out.write_str("\\f"),
        '\r' => out.write_str("\\r"),
        '\\' => out.write_str("\\\\"),
        '\u{2028}' => out.write_str("\\u2028"),
        '\u{2029}' => out.write_str("\\u2029"),
        '\x00'..='\x1F' => write!(out, "\\x{:02x}", c as u32),
        c if is_text_direction_control(c) => write!(out, "\\u{:04x}", c as u32),
        c => write!(out, "\\u{{{:x}}}", c as u32),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// the bidi formatting controls, with their escaped forms.
    const TEXT_DIRECTION: [(&str, &str); 9] = [
        ("\u{202A}", r"\u202a"),
        ("\u{202B}", r"\u202b"),
        ("\u{202C}", r"\u202c"),
        ("\u{202D}", r"\u202d"),
        ("\u{202E}", r"\u202e"),
        ("\u{2066}", r"\u2066"),
        ("\u{2067}", r"\u2067"),
        ("\u{2068}", r"\u2068"),
        ("\u{2069}", r"\u2069"),
    ];

    // -- for_javascript (universal) --

    #[test]
    fn js_no_encoding_needed() {
        assert_eq!(for_javascript("hello world"), "hello world");
        assert_eq!(for_javascript(""), "");
    }

    #[test]
    fn js_encodes_quotes_as_hex() {
        assert_eq!(for_javascript(r#"a"b"#), r"a\x22b");
        assert_eq!(for_javascript("a'b"), r"a\x27b");
    }

    #[test]
    fn js_encodes_backslash() {
        assert_eq!(for_javascript(r"a\b"), r"a\\b");
    }

    #[test]
    fn js_encodes_ampersand() {
        assert_eq!(for_javascript("a&b"), r"a\x26b");
    }

    #[test]
    fn js_encodes_slash() {
        assert_eq!(for_javascript("a/b"), r"a\/b");
        assert_eq!(for_javascript("</script>"), r"\x3c\/script>");
    }

    #[test]
    fn js_encodes_lt() {
        assert_eq!(for_javascript("a<b"), r"a\x3cb");
        assert_eq!(for_javascript("<!--<script>"), r"\x3c!--\x3cscript>");
        assert_eq!(for_javascript("<!--"), r"\x3c!--");
        assert_eq!(for_javascript("<script"), r"\x3cscript");
    }

    #[test]
    fn js_encodes_control_chars() {
        assert_eq!(for_javascript("\x00"), r"\x00");
        assert_eq!(for_javascript("\x08"), r"\b");
        assert_eq!(for_javascript("\t"), r"\t");
        assert_eq!(for_javascript("\n"), r"\n");
        assert_eq!(for_javascript("\x0B"), r"\x0b");
        assert_eq!(for_javascript("\x0C"), r"\f");
        assert_eq!(for_javascript("\r"), r"\r");
        assert_eq!(for_javascript("\x1F"), r"\x1f");
    }

    #[test]
    fn js_encodes_line_separators() {
        assert_eq!(for_javascript("\u{2028}"), r"\u2028");
        assert_eq!(for_javascript("\u{2029}"), r"\u2029");
    }

    #[test]
    fn js_escapes_text_direction_controls() {
        for (raw, escaped) in TEXT_DIRECTION {
            assert_eq!(for_javascript(raw), escaped);
            assert_eq!(for_javascript(&format!("a{raw}b")), format!("a{escaped}b"));
        }
    }

    #[test]
    fn js_preserves_non_ascii() {
        assert_eq!(for_javascript("café"), "café");
        assert_eq!(for_javascript("日本語"), "日本語");
    }

    #[test]
    fn js_writer_variant() {
        let mut out = String::new();
        write_javascript(&mut out, "a'b").unwrap();
        assert_eq!(out, r"a\x27b");
    }

    // -- for_javascript_attribute --

    #[test]
    fn js_attr_does_not_encode_slash_or_lt() {
        assert_eq!(for_javascript_attribute("a/b"), "a/b");
        assert_eq!(for_javascript_attribute("<!--<script>"), "<!--<script>");
    }

    #[test]
    fn js_attr_encodes_quotes_as_hex() {
        assert_eq!(for_javascript_attribute("a'b"), r"a\x27b");
    }

    #[test]
    fn js_attr_encodes_ampersand() {
        assert_eq!(for_javascript_attribute("a&b"), r"a\x26b");
    }

    #[test]
    fn js_attr_escapes_text_direction_controls() {
        for (raw, escaped) in TEXT_DIRECTION {
            assert_eq!(for_javascript_attribute(raw), escaped);
        }
    }

    // -- for_javascript_block --

    #[test]
    fn js_block_uses_backslash_quotes() {
        assert_eq!(for_javascript_block(r#"a"b"#), r#"a\"b"#);
        assert_eq!(for_javascript_block("a'b"), r"a\'b");
    }

    #[test]
    fn js_block_encodes_slash() {
        assert_eq!(for_javascript_block("a/b"), r"a\/b");
    }

    #[test]
    fn js_block_encodes_lt() {
        assert_eq!(for_javascript_block("a<b"), r"a\x3cb");
        assert_eq!(for_javascript_block("<!--<script>"), r"\x3c!--\x3cscript>");
        assert_eq!(for_javascript_block("<!--"), r"\x3c!--");
        assert_eq!(for_javascript_block("<script"), r"\x3cscript");
    }

    #[test]
    fn js_block_encodes_ampersand() {
        assert_eq!(for_javascript_block("a&b"), r"a\x26b");
    }

    #[test]
    fn js_block_escapes_text_direction_controls() {
        for (raw, escaped) in TEXT_DIRECTION {
            assert_eq!(for_javascript_block(raw), escaped);
        }
    }

    // -- for_javascript_source --

    #[test]
    fn js_source_uses_backslash_quotes() {
        assert_eq!(for_javascript_source(r#"a"b"#), r#"a\"b"#);
        assert_eq!(for_javascript_source("a'b"), r"a\'b");
    }

    #[test]
    fn js_source_does_not_encode_slash_ampersand_or_lt() {
        assert_eq!(for_javascript_source("a/b&c"), "a/b&c");
        assert_eq!(for_javascript_source("<!--<script>"), "<!--<script>");
    }

    #[test]
    fn js_source_encodes_line_separators() {
        assert_eq!(for_javascript_source("\u{2028}"), r"\u2028");
    }

    #[test]
    fn js_source_escapes_text_direction_controls() {
        for (raw, escaped) in TEXT_DIRECTION {
            assert_eq!(for_javascript_source(raw), escaped);
            assert_eq!(
                for_javascript_source(&format!("var x = '{raw}';")),
                format!(r"var x = \'{escaped}\';")
            );
        }
    }

    // -- for_js_template --

    #[test]
    fn js_template_no_encoding_needed() {
        assert_eq!(for_js_template("hello world"), "hello world");
        assert_eq!(for_js_template(""), "");
    }

    #[test]
    fn js_template_encodes_backtick() {
        assert_eq!(for_js_template("hello `world`"), r"hello \`world\`");
        assert_eq!(for_js_template("`"), r"\`");
    }

    #[test]
    fn js_template_encodes_interpolation() {
        assert_eq!(for_js_template("${alert(1)}"), r"\${alert(1)}");
        assert_eq!(for_js_template("a${b}c"), r"a\${b}c");
        assert_eq!(for_js_template("${a}${b}"), r"\${a}\${b}");
    }

    #[test]
    fn js_template_dollar_without_brace_passes_through() {
        assert_eq!(for_js_template("a $ b"), "a $ b");
        assert_eq!(for_js_template("$100"), "$100");
    }

    #[test]
    fn js_template_escapes_trailing_dollar() {
        assert_eq!(for_js_template("a$"), r"a\$");
        assert_eq!(for_js_template("$"), r"\$");
    }

    #[test]
    fn js_template_encodes_backslash() {
        assert_eq!(for_js_template(r"a\b"), r"a\\b");
    }

    #[test]
    fn js_template_encodes_slash() {
        assert_eq!(for_js_template("a/b"), r"a\/b");
        assert_eq!(for_js_template("</script>"), r"\x3c\/script>");
    }

    #[test]
    fn js_template_encodes_lt() {
        assert_eq!(for_js_template("a<b"), r"a\x3cb");
        assert_eq!(for_js_template("<!--<script>"), r"\x3c!--\x3cscript>");
        assert_eq!(for_js_template("<!--"), r"\x3c!--");
        assert_eq!(for_js_template("<script"), r"\x3cscript");
    }

    #[test]
    fn js_template_does_not_encode_quotes() {
        assert_eq!(for_js_template(r#"a"b"#), r#"a"b"#);
        assert_eq!(for_js_template("a'b"), "a'b");
    }

    #[test]
    fn js_template_encodes_control_chars() {
        assert_eq!(for_js_template("\x00"), r"\x00");
        assert_eq!(for_js_template("\x08"), r"\b");
        assert_eq!(for_js_template("\t"), r"\t");
        assert_eq!(for_js_template("\n"), r"\n");
        assert_eq!(for_js_template("\x0B"), r"\x0b");
        assert_eq!(for_js_template("\x0C"), r"\f");
        assert_eq!(for_js_template("\r"), r"\r");
        assert_eq!(for_js_template("\x1F"), r"\x1f");
    }

    #[test]
    fn js_template_escapes_text_direction_controls() {
        for (raw, escaped) in TEXT_DIRECTION {
            assert_eq!(for_js_template(raw), escaped);
            assert_eq!(for_js_template(&format!("a{raw}b")), format!("a{escaped}b"));
        }
    }

    #[test]
    fn js_template_encodes_line_separators() {
        assert_eq!(for_js_template("\u{2028}"), r"\u2028");
        assert_eq!(for_js_template("\u{2029}"), r"\u2029");
    }

    #[test]
    fn js_template_preserves_non_ascii() {
        assert_eq!(for_js_template("café"), "café");
        assert_eq!(for_js_template("日本語"), "日本語");
        assert_eq!(for_js_template("😀"), "😀");
    }

    #[test]
    fn js_template_mixed_input() {
        assert_eq!(
            for_js_template("`Hello ${name}`, welcome\\n"),
            r"\`Hello \${name}\`, welcome\\n"
        );
    }

    #[test]
    fn js_template_writer_variant() {
        let input = "`test` ${x} café";
        let string_result = for_js_template(input);
        let mut writer_result = String::new();
        write_js_template(&mut writer_result, input).unwrap();
        assert_eq!(string_result, writer_result);
    }

    // -- write_js_shared_escape helper --

    #[test]
    fn shared_escape_handles_shared_chars() {
        let cases = [
            ('\x08', r"\b"),
            ('\t', r"\t"),
            ('\n', r"\n"),
            ('\x0B', r"\x0b"),
            ('\x0C', r"\f"),
            ('\r', r"\r"),
            ('\\', r"\\"),
            ('\x00', r"\x00"),
            ('\x1F', r"\x1f"),
            ('\u{2028}', r"\u2028"),
            ('\u{2029}', r"\u2029"),
        ];
        for (c, expected) in cases {
            let mut out = String::new();
            assert_eq!(write_js_shared_escape(&mut out, c), Ok(()));
            assert_eq!(out, expected);
        }
    }

    #[test]
    fn shared_escape_never_drops_a_character() {
        for (c, expected) in [('a', r"\u{61}"), ('"', r"\u{22}"), ('é', r"\u{e9}")] {
            let mut out = String::new();
            assert_eq!(write_js_shared_escape(&mut out, c), Ok(()));
            assert_eq!(out, expected);
        }
    }
}