proa_framework_axum 0.4.3

Axum and Tokio adapter for Proa SSR applications.
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
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! URL-aware transformations for managed application assets. Parsing and caching
//! occur at the asset boundary, never while rendering or buffering page HTML.

use axum::{
    body::{to_bytes, Body},
    http::{header, Request, Response, StatusCode},
    middleware::{self, Next},
    Router,
};
use base16ct::HexDisplay;
use bytes::Bytes;
use oxc_allocator::Allocator;
use oxc_ast::ast::*;
use oxc_ast_visit::{walk, Visit};
use oxc_span::{GetSpan, SourceType, Span};
use proa_core::BasePath;
use sha2::{Digest, Sha256};
use std::{
    collections::VecDeque,
    sync::{Arc, Mutex},
};

const MAX_ASSET_BYTES: usize = 32 * 1024 * 1024;
const CACHE_BYTES: usize = 32 * 1024 * 1024;

#[derive(Default)]
struct AssetCache {
    entries: VecDeque<([u8; 32], Bytes)>,
    bytes: usize,
}

/// Compose root-relative CSS URLs and native JavaScript URL operations in a
/// static router. FrameworkBuilder applies this to `with_static_service` when
/// a base path is configured. Custom routers/scaffolds can install it directly.
/// Page HTML bodies remain untouched and streaming. Parsed asset results are
/// cached by content with a bounded memory budget.
pub fn base_path_assets(router: Router, base_path: BasePath) -> Router {
    if base_path.as_str().is_empty() {
        return router;
    }
    let cache = Arc::new(Mutex::new(AssetCache::default()));
    router.layer(middleware::from_fn(
        move |mut request: Request<Body>, next: Next| {
            let base_path = base_path.clone();
            let cache = cache.clone();
            async move {
                let extension = request.uri().path().rsplit('.').next().unwrap_or("");
                let javascript = matches!(extension, "js" | "mjs");
                let head = request.method() == axum::http::Method::HEAD;
                if !(head || request.method() == axum::http::Method::GET)
                    || !(javascript || extension == "css")
                {
                    return next.run(request).await;
                }
                if head {
                    *request.method_mut() = axum::http::Method::GET;
                }
                let conditional = request.headers().get(header::IF_NONE_MATCH).cloned();
                for name in [
                    header::ACCEPT_ENCODING,
                    header::RANGE,
                    header::IF_RANGE,
                    header::IF_NONE_MATCH,
                    header::IF_MODIFIED_SINCE,
                ] {
                    request.headers_mut().remove(name);
                }
                let response = next.run(request).await;
                if response.status() != StatusCode::OK
                    || response.headers().contains_key(header::CONTENT_ENCODING)
                {
                    return if head {
                        response.map(|_| Body::empty())
                    } else {
                        response
                    };
                }
                let mime = response
                    .headers()
                    .get(header::CONTENT_TYPE)
                    .and_then(|h| h.to_str().ok())
                    .unwrap_or("")
                    .split(';')
                    .next()
                    .unwrap_or("");
                let transformable = if javascript {
                    matches!(mime.trim(), "text/javascript" | "application/javascript")
                } else {
                    mime.trim() == "text/css"
                };
                if !transformable {
                    return if head {
                        response.map(|_| Body::empty())
                    } else {
                        response
                    };
                }
                let (mut parts, body) = response.into_parts();
                let original = match to_bytes(body, MAX_ASSET_BYTES).await {
                    Ok(body) => body,
                    Err(error) => {
                        tracing::error!(%error, "could not read managed URL asset");
                        return if head {
                            failure().map(|_| Body::empty())
                        } else {
                            failure()
                        };
                    }
                };
                let mut hash = Sha256::new();
                hash.update([javascript as u8]);
                hash.update(&original);
                let key: [u8; 32] = hash.finalize().into();
                let cached = cache
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .entries
                    .iter()
                    .find(|(k, _)| *k == key)
                    .map(|(_, bytes)| bytes.clone());
                let bytes = match cached {
                    Some(bytes) => bytes,
                    None => {
                        let source = match std::str::from_utf8(&original) {
                            Ok(source) => source,
                            Err(_) => {
                                return if head {
                                    failure().map(|_| Body::empty())
                                } else {
                                    failure()
                                }
                            }
                        };
                        let result = if javascript {
                            rewrite_js(source, &base_path)
                        } else {
                            rewrite_css(source, &base_path)
                        };
                        let bytes = match result {
                            Ok(source) => Bytes::from(source),
                            Err(error) => {
                                tracing::error!(%error, "could not compose managed asset URLs");
                                return if head {
                                    failure().map(|_| Body::empty())
                                } else {
                                    failure()
                                };
                            }
                        };
                        let mut cache = cache.lock().unwrap_or_else(|e| e.into_inner());
                        if bytes.len() <= CACHE_BYTES {
                            while cache.bytes + bytes.len() > CACHE_BYTES
                                || cache.entries.len() >= 32
                            {
                                if let Some((_, previous)) = cache.entries.pop_front() {
                                    cache.bytes -= previous.len();
                                } else {
                                    break;
                                }
                            }
                            cache.bytes += bytes.len();
                            cache.entries.push_back((key, bytes.clone()));
                        }
                        bytes
                    }
                };
                let etag = format!("\"{:x}\"", HexDisplay(&Sha256::digest(&bytes)));
                parts.headers.remove(header::CONTENT_RANGE);
                parts.headers.remove(header::ACCEPT_RANGES);
                parts.headers.remove("content-md5");
                parts.headers.remove("digest");
                parts.headers.remove("content-digest");
                parts.headers.remove("repr-digest");
                parts
                    .headers
                    .insert(header::ETAG, etag.parse().expect("valid asset ETag"));
                if conditional
                    .as_ref()
                    .and_then(|h| h.to_str().ok())
                    .is_some_and(|value| {
                        value
                            .split(',')
                            .any(|v| v.trim().trim_start_matches("W/") == etag || v.trim() == "*")
                    })
                {
                    parts.status = StatusCode::NOT_MODIFIED;
                    parts.headers.remove(header::CONTENT_LENGTH);
                    return Response::from_parts(parts, Body::empty());
                }
                parts
                    .headers
                    .insert(header::CONTENT_LENGTH, bytes.len().into());
                Response::from_parts(
                    parts,
                    if head {
                        Body::empty()
                    } else {
                        Body::from(bytes)
                    },
                )
            }
        },
    ))
}

fn failure() -> Response<Body> {
    Response::builder()
        .status(StatusCode::INTERNAL_SERVER_ERROR)
        .body(Body::from("Could not prepare application asset URLs"))
        .expect("valid asset response")
}

fn application_url(base: &BasePath, url: &str) -> Option<String> {
    let prefix = base.as_str();
    if prefix.is_empty() || !url.starts_with('/') || url.starts_with("//") {
        return None;
    }
    if url
        .strip_prefix(prefix)
        .is_some_and(|suffix| suffix.is_empty() || suffix.starts_with(['/', '?', '#']))
    {
        return None;
    }
    Some(base.url(url).to_string())
}

#[derive(Debug)]
struct Edit {
    span: Span,
    text: String,
}

fn apply_edits(source: &str, mut edits: Vec<Edit>) -> String {
    edits.sort_by_key(|edit| (edit.span.start, edit.span.end));
    let mut out = String::with_capacity(source.len());
    let mut written = 0;
    for edit in edits {
        let start = edit.span.start as usize;
        let end = edit.span.end as usize;
        debug_assert!(start >= written, "overlapping URL edits");
        out.push_str(&source[written..start]);
        out.push_str(&edit.text);
        written = end;
    }
    out.push_str(&source[written..]);
    out
}

pub(crate) fn rewrite_css(source: &str, base: &BasePath) -> Result<String, String> {
    use cssparser::{Parser, Token};
    fn visit<'i>(
        parser: &mut Parser<'i>,
        base: &BasePath,
        edits: &mut Vec<Edit>,
        depth: usize,
        image_set: bool,
    ) -> Result<(), cssparser::ParseError<()>> {
        if depth > 128 {
            return Err(cssparser::ParseError::custom(()));
        }
        let mut import = false;
        loop {
            let start = parser.position().byte_index();
            let token = match parser.next_including_whitespace_and_comments() {
                Ok(token) => token.clone(),
                Err(_) => break,
            };
            let mut replacement = None;
            match token {
                Token::WhiteSpace(_) | Token::Comment(_) => continue,
                Token::AtKeyword(name) if name.eq_ignore_ascii_case("import") => {
                    import = true;
                    continue;
                }
                Token::UnquotedUrl(url) => {
                    replacement = application_url(base, &url).map(|url| (url, true));
                }
                Token::QuotedString(url) if import || image_set => {
                    replacement = application_url(base, &url).map(|url| (url, false));
                }
                Token::Function(name) if name.eq_ignore_ascii_case("url") => {
                    let url =
                        parser.parse_nested_block(|nested| Ok(nested.expect_string_cloned()?))?;
                    replacement = application_url(base, &url).map(|url| (url, true));
                }
                Token::Function(name)
                    if name.eq_ignore_ascii_case("image-set")
                        || name.eq_ignore_ascii_case("-webkit-image-set") =>
                {
                    parser
                        .parse_nested_block(|nested| visit(nested, base, edits, depth + 1, true))?;
                }
                Token::Function(_)
                | Token::CurlyBracketBlock
                | Token::SquareBracketBlock
                | Token::ParenthesisBlock => {
                    parser.parse_nested_block(|nested| {
                        visit(nested, base, edits, depth + 1, false)
                    })?;
                }
                _ => {}
            }
            if let Some((url, function)) = replacement {
                let mut value = String::new();
                if function {
                    value.push_str("url(");
                }
                cssparser::serialize_string(&url, &mut value).expect("write CSS string");
                if function {
                    value.push(')');
                }
                edits.push(Edit {
                    span: Span::new(start as u32, parser.position().byte_index() as u32),
                    text: value,
                });
            }
            import = false;
        }
        Ok(())
    }
    let mut parser = Parser::new(source);
    let mut edits = Vec::new();
    visit(&mut parser, base, &mut edits, 0, false)
        .map_err(|_| "invalid or excessively nested CSS URL syntax".to_string())?;
    Ok(apply_edits(source, edits))
}

pub(crate) fn rewrite_js(source: &str, base: &BasePath) -> Result<String, String> {
    let allocator = Allocator::default();
    let mut parsed = oxc_parser::Parser::new(&allocator, source, SourceType::unambiguous()).parse();
    // Oxc's unambiguous mode parses with script context before deciding the
    // module kind, so valid top-level await needs an explicit module retry.
    if !parsed.diagnostics.is_empty() {
        parsed = oxc_parser::Parser::new(&allocator, source, SourceType::mjs()).parse();
    }
    if !parsed.diagnostics.is_empty() {
        return Err("invalid JavaScript asset".to_string());
    }
    let semantic = oxc_semantic::SemanticBuilder::new().build(&parsed.program);
    if !semantic.diagnostics.is_empty() {
        return Err("invalid JavaScript bindings".to_string());
    }
    let mut helper = format!(
        "__proa_url_{:x}",
        HexDisplay(&Sha256::digest(source.as_bytes()))
    );
    while source.contains(&helper) {
        helper.push('_');
    }
    let mut visitor = JsUrls {
        base: Some(base),
        modules: None,
        scoping: semantic.semantic.scoping(),
        edits: Vec::new(),
        imports: Vec::new(),
        unresolved: Vec::new(),
        helper,
        dynamic: false,
    };
    visitor.visit_program(&parsed.program);
    let mut out = apply_edits(source, visitor.edits);
    if visitor.dynamic {
        let prefix = serde_json::to_string(base.as_str()).expect("serialize asset mount");
        out.push_str(&format!("\nfunction {}(p){{const b={prefix};return typeof p==='string'&&p.startsWith('/')&&!p.startsWith('//')&&p!==b&&!p.startsWith(b+'/')&&!p.startsWith(b+'?')&&!p.startsWith(b+'#')?b+p:p;}}\n", visitor.helper));
    }
    Ok(out)
}

/// A module whose URLs are settled later, so its bytes hold no deployment
/// setting. See [`portable_js`].
pub(crate) struct PortableJs {
    edits: Vec<Edit>,
    /// Import specifiers that name another module of the same set, by the
    /// index `modules` gave them. Their text depends on that module's final
    /// name, which is not known until it has been hashed.
    pub(crate) imports: Vec<(Span, usize)>,
    /// Name of the function every application URL is passed through at run
    /// time, when the module has any.
    pub(crate) helper: Option<String>,
    /// Static imports by path that name no module of the set. A static
    /// import cannot be routed through the helper, and once the module is
    /// published under another directory or host the path leads nowhere.
    pub(crate) unresolved: Vec<String>,
}

impl PortableJs {
    /// A module that is published exactly as written.
    pub(crate) fn verbatim() -> Self {
        Self {
            edits: Vec::new(),
            imports: Vec::new(),
            helper: None,
            unresolved: Vec::new(),
        }
    }

    /// Write the module with `specifier(index)` in place of each import of
    /// another module of the set.
    pub(crate) fn apply(&self, source: &str, specifier: impl Fn(usize) -> String) -> String {
        let mut edits: Vec<Edit> = self
            .edits
            .iter()
            .map(|edit| Edit {
                span: edit.span,
                text: edit.text.clone(),
            })
            .collect();
        edits.extend(self.imports.iter().map(|(span, module)| Edit {
            span: *span,
            text: serde_json::to_string(&specifier(*module)).expect("serialize import specifier"),
        }));
        apply_edits(source, edits)
    }
}

/// Prepare a generated module to be served unchanged in every deployment.
///
/// The base path is a runtime setting, so it cannot be written into a file
/// whose name is a hash of its bytes. Each URL operation that
/// [`rewrite_js`] would prefix is routed through a helper function here, and
/// the caller defines that helper in terms of the base path the page carries.
/// `modules` maps an import specifier to the module of the same set it names.
pub(crate) fn portable_js(
    source: &str,
    modules: &dyn Fn(&str) -> Option<usize>,
) -> Result<PortableJs, String> {
    let allocator = Allocator::default();
    let parsed = oxc_parser::Parser::new(&allocator, source, SourceType::mjs()).parse();
    if !parsed.diagnostics.is_empty() {
        return Err("invalid JavaScript module".to_string());
    }
    let semantic = oxc_semantic::SemanticBuilder::new().build(&parsed.program);
    if !semantic.diagnostics.is_empty() {
        return Err("invalid JavaScript bindings".to_string());
    }
    let mut helper = format!(
        "__proa_url_{:x}",
        HexDisplay(&Sha256::digest(source.as_bytes()))
    );
    while source.contains(&helper) {
        helper.push('_');
    }
    let mut visitor = JsUrls {
        base: None,
        modules: Some(modules),
        scoping: semantic.semantic.scoping(),
        edits: Vec::new(),
        imports: Vec::new(),
        unresolved: Vec::new(),
        helper,
        dynamic: false,
    };
    visitor.visit_program(&parsed.program);
    Ok(PortableJs {
        edits: visitor.edits,
        imports: visitor.imports,
        helper: visitor.dynamic.then_some(visitor.helper),
        unresolved: visitor.unresolved,
    })
}

struct JsUrls<'s> {
    /// Write this base path into the source. `None` defers every URL to the
    /// helper, for a module that must not contain one.
    base: Option<&'s BasePath>,
    modules: Option<&'s dyn Fn(&str) -> Option<usize>>,
    scoping: &'s oxc_semantic::Scoping,
    edits: Vec<Edit>,
    imports: Vec<(Span, usize)>,
    unresolved: Vec<String>,
    helper: String,
    dynamic: bool,
}

impl JsUrls<'_> {
    fn global(&self, expression: &Expression<'_>, name: &str) -> bool {
        match expression.get_inner_expression() {
            Expression::Identifier(id) if id.name == name => id
                .reference_id
                .get()
                .is_some_and(|id| self.scoping.get_reference(id).symbol_id().is_none()),
            _ => false,
        }
    }
    fn browser_global(&self, expression: &Expression<'_>) -> bool {
        self.global(expression, "window")
            || self.global(expression, "globalThis")
            || self.global(expression, "self")
    }
    fn native(&self, expression: &Expression<'_>, name: &str) -> bool {
        self.global(expression, name)
            || matches!(expression.get_inner_expression(), Expression::StaticMemberExpression(member) if member.property.name == name && self.browser_global(&member.object))
    }
    fn local_url_base(&self, expression: &Expression<'_>) -> bool {
        if self.native(expression, "location") {
            return true;
        }
        match expression.get_inner_expression() {
            Expression::StaticMemberExpression(member) if member.property.name == "url" => {
                matches!(
                    member.object.get_inner_expression(),
                    Expression::ImportMeta(_)
                )
            }
            Expression::StaticMemberExpression(member)
                if matches!(member.property.name.as_str(), "href" | "origin") =>
            {
                self.native(&member.object, "location")
            }
            _ => false,
        }
    }
    /// Record an import of another module of the set.
    fn import(&mut self, literal: &StringLiteral<'_>) -> bool {
        let module = self
            .modules
            .and_then(|resolve| literal.value.as_str().and_then(resolve));
        if let Some(module) = module {
            self.imports.push((literal.span, module));
        }
        module.is_some()
    }
    /// A static import or export source. It has to stay a literal, so a
    /// portable module can only follow it to another module of its set.
    fn literal(&mut self, literal: &StringLiteral<'_>) {
        if self.import(literal) {
            return;
        }
        // Browser URLs use Unicode scalar values, replacing any lone UTF-16 surrogate.
        let value = literal.value.as_str().map_or_else(
            || {
                std::borrow::Cow::Owned(
                    literal
                        .value
                        .chars()
                        .map(|ch| ch.to_char().unwrap_or(char::REPLACEMENT_CHARACTER))
                        .collect(),
                )
            },
            std::borrow::Cow::Borrowed,
        );
        let by_path = value.starts_with("./")
            || value.starts_with("../")
            || (value.starts_with('/') && !value.starts_with("//"));
        if self.modules.is_some() && by_path {
            self.unresolved.push(value.to_string());
        }
        if let Some(url) = self.base.and_then(|base| application_url(base, &value)) {
            self.edits.push(Edit {
                span: literal.span,
                text: serde_json::to_string(&url).expect("serialize URL literal"),
            });
        }
    }
    /// The argument of a call that fetches a URL. `module` marks a dynamic
    /// `import(...)`: it is the only such call whose literal can name another
    /// module of the set, because only an import resolves a relative
    /// specifier against the importing module. Everything else resolves
    /// against the document.
    fn url(&mut self, expression: &Expression<'_>, module: bool) {
        if let Expression::StringLiteral(literal) = expression.get_inner_expression() {
            if self.base.is_some() {
                self.literal(literal);
                return;
            }
            // Only a path from the origin root can gain a base path.
            if (module && self.import(literal))
                || !literal.value.starts_with('/')
                || literal.value.starts_with("//")
            {
                return;
            }
        }
        let span = expression.span();
        self.edits.push(Edit {
            span: Span::new(span.start, span.start),
            text: format!("{}(", self.helper),
        });
        self.edits.push(Edit {
            span: Span::new(span.end, span.end),
            text: ")".into(),
        });
        self.dynamic = true;
    }
}

impl<'a> Visit<'a> for JsUrls<'_> {
    fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
        if self.native(&call.callee, "fetch") {
            if let Some(argument) = call.arguments.first().and_then(Argument::as_expression) {
                self.url(argument, false);
            }
        }
        walk::walk_call_expression(self, call);
    }
    fn visit_new_expression(&mut self, expression: &NewExpression<'a>) {
        let local_url = self.native(&expression.callee, "URL")
            && expression
                .arguments
                .get(1)
                .and_then(Argument::as_expression)
                .is_some_and(|base| self.local_url_base(base));
        if local_url
            || [
                "Request",
                "Worker",
                "SharedWorker",
                "WebSocket",
                "EventSource",
            ]
            .into_iter()
            .any(|name| self.native(&expression.callee, name))
        {
            if let Some(argument) = expression
                .arguments
                .first()
                .and_then(Argument::as_expression)
            {
                self.url(argument, false);
            }
        }
        walk::walk_new_expression(self, expression);
    }
    fn visit_import_expression(&mut self, expression: &ImportExpression<'a>) {
        self.url(&expression.source, true);
        walk::walk_import_expression(self, expression);
    }
    fn visit_import_declaration(&mut self, declaration: &ImportDeclaration<'a>) {
        self.literal(&declaration.source);
        walk::walk_import_declaration(self, declaration);
    }
    fn visit_export_from_declaration(&mut self, declaration: &ExportFromDeclaration<'a>) {
        self.literal(&declaration.source);
        walk::walk_export_from_declaration(self, declaration);
    }
    fn visit_export_all_declaration(&mut self, declaration: &ExportAllDeclaration<'a>) {
        self.literal(&declaration.source);
        walk::walk_export_all_declaration(self, declaration);
    }
}

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

    fn base() -> BasePath {
        BasePath::new("/apps/demo").unwrap()
    }

    #[test]
    fn css_changes_url_tokens_without_changing_comments_or_content() {
        let source = r###"/* url(/comment) */ @import "/theme.css" screen;
@media screen { .a { background: url('/images/a b.svg'); mask: url(/mask.svg#icon); background-image: image-set("/small.png" 1x, url(/large.png) 2x); content: "url(/text)"; } }
.b { a: url(//cdn.test/a); b: url(https://cdn.test/a); c: url(data:image/png;base64,abc); d: url(#icon); e: url(/apps/demo/already); }"###;
        let result = rewrite_css(source, &base()).unwrap();
        assert!(
            result.contains("@import \"/apps/demo/theme.css\" screen"),
            "{result}"
        );
        assert!(
            result.contains("url(\"/apps/demo/images/a b.svg\")"),
            "{result}"
        );
        assert!(
            result.contains("url(\"/apps/demo/mask.svg#icon\")"),
            "{result}"
        );
        assert!(
            result.contains(
                "image-set(\"/apps/demo/small.png\" 1x, url(\"/apps/demo/large.png\") 2x)"
            ),
            "{result}"
        );
        for literal in [
            "/* url(/comment) */",
            "content: \"url(/text)\"",
            "url(//cdn.test/a)",
            "url(https://cdn.test/a)",
            "url(data:image/png;base64,abc)",
            "url(#icon)",
            "url(/apps/demo/already)",
        ] {
            assert!(result.contains(literal), "{literal}: {result}");
        }
    }

    #[test]
    fn js_changes_native_url_operations_and_module_imports_only() {
        let source = r###"'use strict';
import x from '/library.js'; export { x } from '/exports.js';
const label = '/ordinary'; const regex = /fetch\('/;
fetch('/api/items'); window.fetch('/api/window');
const request = new Request('/api/save');
new Worker('/worker.js'); new EventSource('/events');
new URL('/image.svg', import.meta.url); new URL('/icon.svg', window.location.href);
new URL('/remote.svg', 'https://cdn.test/');
import('/lazy.js'); fetch('//cdn.test/data'); fetch('https://api.test/data');
function local(fetch, window, Request) { fetch('/local'); window.fetch('/local'); new Request('/local'); }
"###;
        let result = rewrite_js(source, &base()).unwrap();
        for path in [
            "/library.js",
            "/exports.js",
            "/api/items",
            "/api/window",
            "/api/save",
            "/worker.js",
            "/events",
            "/lazy.js",
            "/image.svg",
            "/icon.svg",
        ] {
            assert!(
                result.contains(&format!("\"/apps/demo{path}\"")),
                "{path}: {result}"
            );
        }
        for literal in [
            "const label = '/ordinary'",
            "new URL('/remote.svg', 'https://cdn.test/')",
            "const regex = /fetch\\('/",
            "fetch('/local')",
            "window.fetch('/local')",
            "new Request('/local')",
            "fetch('//cdn.test/data')",
            "fetch('https://api.test/data')",
        ] {
            assert!(result.contains(literal), "{literal}: {result}");
        }
        assert!(!result.contains("function __proa_url_"));
    }

    #[test]
    fn dynamic_url_wrappers_preserve_directives_and_valid_nested_expressions() {
        let source =
            "'use strict'; fetch(new Request(path)); import(module_path); fetch(`/api/${id}`);";
        let result = rewrite_js(source, &base()).unwrap();
        assert!(result.starts_with("'use strict';"));
        assert!(result.contains("function __proa_url_"));
        let alloc = Allocator::default();
        let parsed = oxc_parser::Parser::new(&alloc, &result, SourceType::mjs()).parse();
        assert!(
            parsed.diagnostics.is_empty(),
            "{:?}: {result}",
            parsed.diagnostics
        );
        assert!(rewrite_js("const =", &base()).is_err());
    }

    #[test]
    fn rewritten_dynamic_browser_calls_execute_with_the_correct_paths() {
        use std::{
            io::Write,
            process::{Command, Stdio},
        };
        let source = r###"
import assert from 'node:assert/strict';
const seen = [];
globalThis.Request = class { constructor(url) { this.url = url; } };
globalThis.fetch = async value => { seen.push(typeof value === 'string' ? value : value.url); };
const path = '/api/dynamic';
await fetch(path);
await fetch(new Request('/api/nested'));
await fetch('/apps/demo/already');
await fetch('https://api.example/data');
await fetch('//cdn.example/data');
function custom(fetch) { fetch('/ordinary'); }
custom(value => seen.push(value));
assert.deepEqual(seen, ['/apps/demo/api/dynamic', '/apps/demo/api/nested', '/apps/demo/already', 'https://api.example/data', '//cdn.example/data', '/ordinary']);
"###;
        let source = rewrite_js(source, &base()).unwrap();
        let child = Command::new("node")
            .arg("--input-type=module")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn();
        let mut child = match child {
            Ok(child) => child,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                eprintln!("node unavailable; JavaScript execution check skipped");
                return;
            }
            Err(error) => panic!("start node: {error}"),
        };
        child
            .stdin
            .take()
            .unwrap()
            .write_all(source.as_bytes())
            .unwrap();
        let output = child.wait_with_output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[tokio::test]
    async fn managed_assets_use_transformed_validators_head_and_full_ranges() {
        let source = "a { background:url(/image.svg) }";
        let router = base_path_assets(
            Router::new().route(
                "/app.css",
                axum::routing::get(move || async move {
                    (
                        [
                            (header::CONTENT_TYPE, "text/css"),
                            (header::ETAG, "\"original\""),
                        ],
                        source,
                    )
                }),
            ),
            base(),
        );
        let send = |method: &str, etag: Option<&str>| {
            let mut request = Request::builder()
                .method(method)
                .uri("/app.css")
                .header(header::RANGE, "bytes=0-1");
            if let Some(etag) = etag {
                request = request.header(header::IF_NONE_MATCH, etag);
            }
            router.clone().oneshot(request.body(Body::empty()).unwrap())
        };
        let response = send("GET", None).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let etag = response.headers()[header::ETAG]
            .to_str()
            .unwrap()
            .to_owned();
        let length = response.headers()[header::CONTENT_LENGTH].clone();
        assert_ne!(etag, "\"original\"");
        let body = to_bytes(response.into_body(), 1024).await.unwrap();
        assert!(std::str::from_utf8(&body)
            .unwrap()
            .contains("/apps/demo/image.svg"));
        let head = send("HEAD", None).await.unwrap();
        assert_eq!(head.headers()[header::CONTENT_LENGTH], length);
        assert_eq!(head.headers()[header::ETAG], etag);
        assert!(to_bytes(head.into_body(), 1024).await.unwrap().is_empty());
        let conditional = send("GET", Some(&etag)).await.unwrap();
        assert_eq!(conditional.status(), StatusCode::NOT_MODIFIED);
        assert!(to_bytes(conditional.into_body(), 1024)
            .await
            .unwrap()
            .is_empty());
    }
}