Skip to main content

bynk_check/
assets.rs

1//! #1883 (static assets): the checker-side rules for `asset name = "path"`
2//! declarations — the path rules, the name rule, the composition of a unit's
3//! visible assets through `uses` ([DECISION G]) — and (slice 1b) the build
4//! side's shared definitions: the existence check, the served URL path, and
5//! the files each Worker ships.
6//!
7//! The checker stays disk-free (`bynk-wasm` compiles it with no filesystem):
8//! the project's `assets/` folder reaches it from the caller
9//! (`bynk_project::assets`), as a path set or as an
10//! [`AssetFolder`](bynk_project::assets::AssetFolder) whose reader it calls
11//! for the declared files alone ([`read_declared_files`]).
12
13use std::collections::{BTreeMap, BTreeSet, HashMap};
14
15use bynk_syntax::ast::{AssetDecl, CommonsItem, FnName, Ident};
16use bynk_syntax::error::CompileError;
17
18use crate::project_model::{ErrorSink, UnitInfo};
19use bynk_project::ParsedFile;
20
21/// Why `path` is not a safe asset path, or `None` when it is.
22///
23/// An asset is public by construction, and the path is joined onto the
24/// project root to find the file, so a path that can name something outside
25/// the project is rejected outright: an absolute path (`/etc/x`, `\x`,
26/// `C:/x`), and any `..` segment. Both separators count, so a Windows-style
27/// path is judged the same on every host. An empty path names no file.
28pub fn unsafe_asset_path_reason(path: &str) -> Option<&'static str> {
29    if path.is_empty() {
30        return Some("the path is empty");
31    }
32    let bytes = path.as_bytes();
33    let has_drive = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
34    if path.starts_with('/') || path.starts_with('\\') || has_drive {
35        return Some("the path is absolute");
36    }
37    if path.split(['/', '\\']).any(|seg| seg == "..") {
38        return Some("the path contains a `..` segment");
39    }
40    None
41}
42
43/// `bynk.asset.unsafe_path` for `a`, when [`unsafe_asset_path_reason`]
44/// rejects its path. One constructor for the project pipeline
45/// (`symbols::build_unit_table`) and the single-file compile
46/// (`bynk-emit`'s `compile`), so the two report it identically.
47pub fn unsafe_path_error(a: &AssetDecl) -> Option<CompileError> {
48    let reason = unsafe_asset_path_reason(&a.path)?;
49    Some(
50        CompileError::new(
51            "bynk.asset.unsafe_path",
52            a.path_span,
53            format!("asset `{}` has an unsafe path: {reason}", a.name.name),
54        )
55        .with_note(
56            "an asset path is relative to the project root and must stay inside it; assets are public, so nothing outside the project may be named",
57        ),
58    )
59}
60
61/// `bynk.asset.outside_assets_dir` for `a`, when its path is safe but does
62/// not lie inside the project's assets folder
63/// ([`bynk_project::assets::PROJECT_ASSETS_DIR`]). Assets are public, so they
64/// come only from that folder, and a declaration can never publish `.env` or
65/// a source file by mistake (#1883, slice 1b).
66pub fn outside_assets_dir_error(a: &AssetDecl) -> Option<CompileError> {
67    if unsafe_asset_path_reason(&a.path).is_some()
68        || bynk_project::assets::is_in_assets_dir(&a.path)
69    {
70        return None;
71    }
72    let dir = bynk_project::assets::PROJECT_ASSETS_DIR;
73    Some(
74        CompileError::new(
75            "bynk.asset.outside_assets_dir",
76            a.path_span,
77            format!(
78                "asset `{}` must name a file in the project's `{dir}/` folder",
79                a.name.name
80            ),
81        )
82        .with_note(format!(
83            "assets are public, so they come only from `{dir}/`; move the file there and name it `{dir}/…`"
84        )),
85    )
86}
87
88/// The path rules for `a`, in order: [`unsafe_path_error`], then
89/// [`outside_assets_dir_error`] (at most one of the two applies).
90pub fn path_errors(a: &AssetDecl) -> Option<CompileError> {
91    unsafe_path_error(a).or_else(|| outside_assets_dir_error(a))
92}
93
94/// The URL path prefix every asset is served under. A handler route under it
95/// is reserved for assets (slice 2's check), and `_headers` gives everything
96/// under it an immutable cache lifetime.
97pub const SERVED_PREFIX: &str = "/_assets/";
98
99/// `bynk.asset.not_served` (a warning) for each asset among `items`, for a
100/// deployable Bundle build: a Bundle ships no Worker and so no files, yet each
101/// module still carries its asset's `.url`, which would 404 wherever the
102/// output is served. A warning, not an error, because a Bundle build is also
103/// how `bynk test` compiles; the caller raises it only for a build without
104/// tests (review of #1904). A helper here keeps `bynk-emit`'s `project.rs`
105/// free of syntax-tree types (the `ast_importers` probe).
106pub fn bundle_not_served_warnings(items: &[CommonsItem]) -> Vec<CompileError> {
107    items
108        .iter()
109        .filter_map(|item| match item {
110            CommonsItem::Asset(a) => Some(
111                CompileError::new(
112                    "bynk.asset.not_served",
113                    a.span,
114                    format!(
115                        "asset `{}` is not served by a Bundle build: its `.url` names a file this build does not ship",
116                        a.name.name
117                    ),
118                )
119                .with_note(
120                    "assets are served beside a Worker; build with `--target workers` (as `bynk dev` and `bynk deploy` do)",
121                ),
122            ),
123            _ => None,
124        })
125        .collect()
126}
127
128/// The URL path the platform serves the asset file `source` (a normalised
129/// `assets/…` key) with content `bytes` at:
130/// `/_assets/<stem>.<hash>.<ext>`, where `<hash>` is the content's FNV-1a 64
131/// ([`crate::contract::fnv1a64_hex`]) and `<stem>`/`<ext>` are the file
132/// name's, split at its last `.` (no `.<ext>` when it has none).
133///
134/// Only the file name is kept, not its folders: the hash already tells two
135/// files apart, and the same bytes under the same name are one served file,
136/// however many declarations name them. Any character outside
137/// `[A-Za-z0-9._-]` becomes `-`, so `.url` never needs percent-encoding.
138/// Reproducible: it depends only on the name and the bytes.
139pub fn served_path(source: &str, bytes: &[u8]) -> String {
140    served_path_with_hash(source, &crate::contract::fnv1a64_hex(bytes))
141}
142
143/// [`served_path`] with the content hash supplied rather than computed — the
144/// one definition of the served name's shape, shared with the editor, which
145/// lists the `assets/` folder but never reads its bytes and so shows
146/// `served_path_with_hash(source, "<hash>")` (#1883, editor tooling).
147pub fn served_path_with_hash(source: &str, hash: &str) -> String {
148    let name = source.rsplit('/').next().unwrap_or(source);
149    let clean: String = name
150        .chars()
151        .map(|c| {
152            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
153                c
154            } else {
155                '-'
156            }
157        })
158        .collect();
159    match clean.rfind('.') {
160        Some(dot) if dot > 0 => {
161            format!(
162                "{SERVED_PREFIX}{}.{hash}.{}",
163                &clean[..dot],
164                &clean[dot + 1..]
165            )
166        }
167        _ => format!("{SERVED_PREFIX}{clean}.{hash}"),
168    }
169}
170
171/// The `Content-Type` the platform serves `served` (a URL path) with, by its
172/// extension — the table measured against `wrangler dev` 4.107.0 (#1883,
173/// slice 3), so a suite fetching an asset (`svc.GET(style)`) sees what
174/// production sends. Text types carry `; charset=utf-8`. A file with no
175/// extension is served with no content type, here `""`; an extension the
176/// table does not know is `application/octet-stream`.
177pub fn content_type_for(served: &str) -> &'static str {
178    let name = served.rsplit('/').next().unwrap_or(served);
179    let Some((_, ext)) = name.rsplit_once('.').filter(|(stem, _)| !stem.is_empty()) else {
180        return "";
181    };
182    match ext.to_ascii_lowercase().as_str() {
183        "css" => "text/css; charset=utf-8",
184        "js" | "mjs" => "text/javascript; charset=utf-8",
185        "html" | "htm" => "text/html; charset=utf-8",
186        "txt" => "text/plain; charset=utf-8",
187        "csv" => "text/csv; charset=utf-8",
188        "md" => "text/markdown; charset=utf-8",
189        "json" | "map" => "application/json",
190        "webmanifest" => "application/manifest+json",
191        "xml" => "application/xml",
192        "svg" => "image/svg+xml",
193        "png" => "image/png",
194        "jpg" | "jpeg" => "image/jpeg",
195        "gif" => "image/gif",
196        "webp" => "image/webp",
197        "avif" => "image/avif",
198        "ico" => "image/vnd.microsoft.icon",
199        "woff" => "font/woff",
200        "woff2" => "font/woff2",
201        "ttf" => "font/ttf",
202        "otf" => "font/otf",
203        "pdf" => "application/pdf",
204        "wasm" => "application/wasm",
205        "mp4" => "video/mp4",
206        "webm" => "video/webm",
207        "mp3" => "audio/mpeg",
208        "wav" => "audio/wav",
209        "zip" => "application/zip",
210        _ => "application/octet-stream",
211    }
212}
213
214/// The key a declaration's served path is filed under
215/// ([`declared_served_paths`]): its normalised source path, plus its fixed
216/// URL path when it has one — so one file may be served both content-hashed
217/// and at a fixed path.
218pub fn asset_key(a: &AssetDecl) -> String {
219    let source = bynk_project::assets::normalise_asset_path(&a.path);
220    match &a.at {
221        Some((at, _)) => format!("{source} at {at}"),
222        None => source,
223    }
224}
225
226/// Every declared asset's served path, keyed by [`asset_key`] — what the
227/// emitter writes as each `.url`: its fixed path (`at "/favicon.ico"`,
228/// slice 2) or its content-hashed one ([`served_path`]). Only declarations
229/// whose file is in `files` appear (a missing one is
230/// `bynk.asset.missing_file`).
231pub fn declared_served_paths(
232    parsed: &[ParsedFile],
233    files: &BTreeMap<String, Vec<u8>>,
234) -> BTreeMap<String, String> {
235    let mut out = BTreeMap::new();
236    for pf in parsed {
237        for item in pf.items() {
238            let CommonsItem::Asset(a) = item else {
239                continue;
240            };
241            let source = bynk_project::assets::normalise_asset_path(&a.path);
242            if let Some(bytes) = files.get(&source) {
243                let served = match &a.at {
244                    Some((at, _)) => at.clone(),
245                    None => served_path(&source, bytes),
246                };
247                out.insert(asset_key(a), served);
248            }
249        }
250    }
251    out
252}
253
254/// The units reachable from `start` over `edges` (transitively), `start`
255/// included, in sorted order.
256fn closure<'a>(start: &'a str, edges: &[&'a HashMap<String, Vec<String>>]) -> BTreeSet<&'a str> {
257    let mut seen: BTreeSet<&str> = BTreeSet::new();
258    let mut stack: Vec<&str> = vec![start];
259    while let Some(unit) = stack.pop() {
260        if !seen.insert(unit) {
261            continue;
262        }
263        for map in edges {
264            for next in map.get(unit).into_iter().flatten() {
265                stack.push(next);
266            }
267        }
268    }
269    seen
270}
271
272/// The files a context's Worker ships, keyed by served path, each mapped to
273/// its normalised source path. Sorted and deduplicated by served path, so the
274/// output is reproducible.
275///
276/// - **Content-hashed assets** come from every unit the context reaches over
277///   `uses` **and** `consumes`, transitively. Through `uses`, a commons may
278///   return another commons' `.url`; through `consumes`, another context may
279///   return one of its own in a fragment this Worker serves (#1883, slice 2).
280///   Either way the URL resolves against this Worker, so it ships the file.
281///   Hashed names never collide, so the duplication costs only bytes.
282/// - **Fixed-path assets** (`at "/favicon.ico"`) come over `uses` only: they
283///   belong to the root of the Worker that declares them, and shipping a
284///   consumed context's fixed paths would collide with this one's own.
285pub fn deployed_assets(
286    context: &str,
287    unit_uses: &HashMap<String, Vec<String>>,
288    unit_consumes: &HashMap<String, Vec<String>>,
289    unit_tables: &HashMap<String, crate::symbols::UnitTable>,
290    served: &BTreeMap<String, String>,
291) -> BTreeMap<String, String> {
292    let hashed_units = closure(context, &[unit_uses, unit_consumes]);
293    let fixed_units = closure(context, &[unit_uses]);
294    let mut out = BTreeMap::new();
295    for unit in &hashed_units {
296        let Some(table) = unit_tables.get(*unit) else {
297            continue;
298        };
299        for decl in table.assets.values() {
300            if decl.at.is_some() && !fixed_units.contains(unit) {
301                continue;
302            }
303            if let Some(path) = served.get(&asset_key(decl)) {
304                out.insert(
305                    path.clone(),
306                    bynk_project::assets::normalise_asset_path(&decl.path),
307                );
308            }
309        }
310    }
311    out
312}
313
314/// Why `at` is not a valid fixed URL path for an asset, or `None` when it is.
315/// It must be an absolute URL path naming a file: starting with `/`, not
316/// ending in `/`, with no empty, `.` or `..` segment, and only
317/// `[A-Za-z0-9._~-]` between the slashes (so it needs no encoding). It may not
318/// lie under [`SERVED_PREFIX`] (the content-hashed files' space) or `/_bynk/`
319/// (Bynk's own dispatch), nor be one of the root files the platform reads as
320/// configuration (`/_headers`, `/_redirects`, `/.assetsignore`).
321pub fn at_path_reason(at: &str) -> Option<&'static str> {
322    let Some(rest) = at.strip_prefix('/') else {
323        return Some("it does not start with `/`");
324    };
325    if rest.is_empty() || rest.ends_with('/') {
326        return Some("it does not name a file (it ends with `/`)");
327    }
328    if rest
329        .split('/')
330        .any(|seg| seg.is_empty() || seg == "." || seg == "..")
331    {
332        return Some("it has an empty, `.` or `..` segment");
333    }
334    if !rest
335        .chars()
336        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '~' | '-'))
337    {
338        return Some("it has a character outside `[A-Za-z0-9._~-]`");
339    }
340    let first = rest.split('/').next().unwrap_or("");
341    if first == SERVED_PREFIX.trim_matches('/') {
342        return Some("it is under `/_assets/`, which content-hashed assets use");
343    }
344    if first == "_bynk" {
345        return Some("it is under `/_bynk/`, which Bynk's own dispatch uses");
346    }
347    // Review of #1906: at the root of a Worker's assets directory these names
348    // are configuration, not files — the platform reads `_headers` and
349    // `_redirects`, wrangler reads `.assetsignore` — and the compiler writes
350    // its own `_headers` there.
351    if matches!(rest, "_headers" | "_redirects" | ".assetsignore") {
352        return Some("the platform reads that file as configuration, not as an asset");
353    }
354    None
355}
356
357/// `bynk.asset.invalid_at_path` for `a`, when its `at` path fails
358/// [`at_path_reason`].
359pub fn at_path_error(a: &AssetDecl) -> Option<CompileError> {
360    let (at, span) = a.at.as_ref()?;
361    let reason = at_path_reason(at)?;
362    Some(
363        CompileError::new(
364            "bynk.asset.invalid_at_path",
365            *span,
366            format!("asset `{}` cannot be served at `{at}`: {reason}", a.name.name),
367        )
368        .with_note(
369            "a fixed asset path is a URL path naming one file, such as `/favicon.ico` or `/robots.txt`",
370        ),
371    )
372}
373
374/// Whether the HTTP route `pattern` (`/a/:id/b`) matches the URL path `path`:
375/// the same number of segments, each literal equal or a `:param`. Routes have
376/// no wildcards, so this is the whole matching rule.
377fn route_matches(pattern: &str, path: &str) -> bool {
378    let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
379    let u: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
380    p.len() == u.len()
381        && p.iter()
382            .zip(&u)
383            .all(|(ps, us)| ps.starts_with(':') || ps == us)
384}
385
386/// #1883, slice 2 ([DECISION C]): fixed asset paths against each Worker's
387/// routes. For every context, over the assets its `uses` closure declares
388/// with an `at` path:
389///
390/// - two different files at one fixed path is `bynk.asset.path_conflict`;
391/// - a fixed path equal to one of the context's literal HTTP routes is
392///   `bynk.asset.shadows_route`: the platform answers that path before the
393///   Worker runs, for **every** method (a `POST` gets the platform's `405`,
394///   checked against `wrangler dev` 4.107.0), so the handler is unreachable;
395/// - a fixed path a parameterised route matches (`/:name`) is the warning
396///   `bynk.asset.may_shadow_route`: the route still serves every other path.
397///
398/// Content-hashed paths need no check here: handlers may not use the
399/// `/_assets/` prefix at all (`bynk.http.reserved_prefix`).
400pub fn phase_asset_routes(
401    parsed: &[ParsedFile],
402    groups: &BTreeMap<String, Vec<usize>>,
403    (kinds, layout): (
404        &BTreeMap<String, bynk_project::UnitKind>,
405        &bynk_project::worker_layout::WorkerLayout,
406    ),
407    unit_uses: &HashMap<String, Vec<String>>,
408    errors: &mut ErrorSink,
409) {
410    use bynk_syntax::ast::HandlerKind;
411    phase_group_asset_paths(layout, parsed, groups, unit_uses, errors);
412    phase_group_shadowed_routes(layout, parsed, groups, unit_uses, errors);
413    // A commons used by two contexts would otherwise report its conflict
414    // twice; report each (file, span, code) once.
415    let mut reported: BTreeSet<(std::path::PathBuf, usize, &'static str)> = BTreeSet::new();
416    let mut push = |file: std::path::PathBuf, err: CompileError, errors: &mut ErrorSink| {
417        if reported.insert((file.clone(), err.span.start, err.category)) {
418            errors.push_for(Some(&file), err);
419        }
420    };
421    for (ctx, kind) in kinds {
422        if *kind != bynk_project::UnitKind::Context {
423            continue;
424        }
425        // Fixed paths this Worker serves: at -> source file.
426        let mut fixed: BTreeMap<String, String> = BTreeMap::new();
427        for unit in closure(ctx, &[unit_uses]) {
428            for &i in groups.get(unit).into_iter().flatten() {
429                for item in parsed[i].items() {
430                    let CommonsItem::Asset(a) = item else {
431                        continue;
432                    };
433                    let Some((at, span)) = &a.at else { continue };
434                    if path_errors(a).is_some() || at_path_reason(at).is_some() {
435                        continue;
436                    }
437                    let source = bynk_project::assets::normalise_asset_path(&a.path);
438                    // Review of #1906: a path that is a folder of another
439                    // (`/logo` and `/logo/icon.png`) cannot be written, since
440                    // one name would be both a file and a directory.
441                    let nested = fixed.keys().find(|other| {
442                        other.starts_with(&format!("{at}/")) || at.starts_with(&format!("{other}/"))
443                    });
444                    if let Some(other) = nested {
445                        push(
446                            parsed[i].identity_path(),
447                            CompileError::new(
448                                "bynk.asset.path_conflict",
449                                *span,
450                                format!(
451                                    "the Worker for `{ctx}` cannot serve files at both `{other}` and `{at}`: one would be a folder of the other"
452                                ),
453                            )
454                            .with_note("a fixed asset path names one file, so it cannot also be a folder; give one of them another path"),
455                            errors,
456                        );
457                        continue;
458                    }
459                    match fixed.get(at) {
460                        Some(prev) if *prev != source => push(
461                            parsed[i].identity_path(),
462                            CompileError::new(
463                                "bynk.asset.path_conflict",
464                                *span,
465                                format!(
466                                    "the Worker for `{ctx}` would serve two files at `{at}`: `{prev}` and `{source}`"
467                                ),
468                            )
469                            .with_note("each fixed asset path names one file; give one of them another path"),
470                            errors,
471                        ),
472                        Some(_) => {}
473                        None => {
474                            fixed.insert(at.clone(), source);
475                        }
476                    }
477                }
478            }
479        }
480        if fixed.is_empty() {
481            continue;
482        }
483        for &i in groups.get(ctx.as_str()).into_iter().flatten() {
484            for item in parsed[i].items() {
485                let CommonsItem::Service(svc) = item else {
486                    continue;
487                };
488                for h in &svc.handlers {
489                    let HandlerKind::Http { method, path } = &h.kind else {
490                        continue;
491                    };
492                    for (at, source) in &fixed {
493                        if !route_matches(path, at) {
494                            continue;
495                        }
496                        let literal = !path.split('/').any(|s| s.starts_with(':'));
497                        let err = if literal {
498                            CompileError::new(
499                                "bynk.asset.shadows_route",
500                                h.span,
501                                format!(
502                                    "`{} {path}` is unreachable: the asset `{source}` is served at `{at}`",
503                                    method.as_str()
504                                ),
505                            )
506                            .with_note(
507                                "the platform answers an asset's path before the Worker runs, for every method; move the asset or the route",
508                            )
509                        } else {
510                            CompileError::new(
511                                "bynk.asset.may_shadow_route",
512                                h.span,
513                                format!(
514                                    "`{} {path}` will not see requests for `{at}`: the asset `{source}` is served there",
515                                    method.as_str()
516                                ),
517                            )
518                            .with_note(
519                                "the platform answers an asset's path before the Worker runs; every other path still reaches this route",
520                            )
521                        };
522                        push(parsed[i].identity_path(), err, errors);
523                    }
524                }
525            }
526        }
527    }
528}
529
530/// `bynk.deploy.asset_path_conflict` (#3562): the members of a Worker group share
531/// one `[assets]` directory, so a fixed path (`at "/favicon.ico"`) two members
532/// serve must be one file. Assets merge: distinct paths all ship, the same file
533/// reached by two members (through a shared commons) is one file, and only a path
534/// two members claim from **different** files is refused, or one that would be a
535/// folder of the other. (Content-hashed paths need no check: one path is one
536/// content.) One error per clash, at the later member's declaration, naming both
537/// members. A clash inside one member is [`phase_asset_routes`]'s
538/// `bynk.asset.path_conflict`.
539fn phase_group_asset_paths(
540    layout: &bynk_project::worker_layout::WorkerLayout,
541    parsed: &[ParsedFile],
542    groups: &BTreeMap<String, Vec<usize>>,
543    unit_uses: &HashMap<String, Vec<String>>,
544    errors: &mut ErrorSink,
545) {
546    let mut reported: BTreeSet<(std::path::PathBuf, usize)> = BTreeSet::new();
547    for (key, members) in layout.groups() {
548        // Fixed paths the group serves: at -> (the member that claimed it first, source file).
549        let mut fixed: BTreeMap<String, (&str, String)> = BTreeMap::new();
550        for member in members {
551            for unit in closure(member, &[unit_uses]) {
552                for &i in groups.get(unit).into_iter().flatten() {
553                    for item in parsed[i].items() {
554                        let CommonsItem::Asset(a) = item else {
555                            continue;
556                        };
557                        let Some((at, span)) = &a.at else { continue };
558                        if path_errors(a).is_some() || at_path_reason(at).is_some() {
559                            continue;
560                        }
561                        let source = bynk_project::assets::normalise_asset_path(&a.path);
562                        let clash = fixed.iter().find_map(|(other, (first, other_source))| {
563                            if first == member {
564                                return None;
565                            }
566                            let nested = other.starts_with(&format!("{at}/"))
567                                || at.starts_with(&format!("{other}/"));
568                            let two_files = other == at && *other_source != source;
569                            (nested || two_files).then(|| {
570                                (
571                                    *first,
572                                    other.clone(),
573                                    other_source.clone(),
574                                    nested && !two_files,
575                                )
576                            })
577                        });
578                        match clash {
579                            Some((first, other, other_source, nested)) => {
580                                let file = parsed[i].identity_path();
581                                if reported.insert((file.clone(), span.start)) {
582                                    let what = if nested {
583                                        format!(
584                                            "files at `{other}` and `{at}`: one would be a folder of the other"
585                                        )
586                                    } else {
587                                        format!(
588                                            "two files at `{at}`: `{other_source}` and `{source}`"
589                                        )
590                                    };
591                                    errors.push_for(
592                                        Some(&file),
593                                        CompileError::new(
594                                            "bynk.deploy.asset_path_conflict",
595                                            *span,
596                                            format!(
597                                                "contexts `{first}` and `{member}` share Worker `{key}`, and it would serve {what}"
598                                            ),
599                                        )
600                                        .with_note(
601                                            "a group's members share one assets directory, so each fixed asset path names one file: give one of the assets another path, or put the contexts in different groups",
602                                        ),
603                                    );
604                                }
605                            }
606                            None => {
607                                fixed.entry(at.clone()).or_insert((member.as_str(), source));
608                            }
609                        }
610                    }
611                }
612            }
613        }
614    }
615}
616
617/// The fixed asset paths `member`'s Worker serves from its own `uses` closure:
618/// each valid `at` path to its normalised source file, the first declaration
619/// winning. [`phase_asset_routes`] reports what is wrong with them.
620fn fixed_paths_of(
621    member: &str,
622    parsed: &[ParsedFile],
623    groups: &BTreeMap<String, Vec<usize>>,
624    unit_uses: &HashMap<String, Vec<String>>,
625) -> BTreeMap<String, String> {
626    let mut fixed = BTreeMap::new();
627    for unit in closure(member, &[unit_uses]) {
628        for &i in groups.get(unit).into_iter().flatten() {
629            for item in parsed[i].items() {
630                let CommonsItem::Asset(a) = item else {
631                    continue;
632                };
633                let Some((at, _)) = &a.at else { continue };
634                if path_errors(a).is_some() || at_path_reason(at).is_some() {
635                    continue;
636                }
637                fixed
638                    .entry(at.clone())
639                    .or_insert_with(|| bynk_project::assets::normalise_asset_path(&a.path));
640            }
641        }
642    }
643    fixed
644}
645
646/// `bynk.asset.shadows_route` across a group (#3562): the platform answers a
647/// fixed asset's path before the Worker runs, and a group's members share one
648/// assets directory, so another member's literal route at that path is as
649/// unreachable as the same member's own (which [`phase_asset_routes`] reports).
650/// One error per route, at the route's handler, naming the member whose asset
651/// shadows it. A parameterised route that matches stays out of scope, as it is
652/// within a context.
653fn phase_group_shadowed_routes(
654    layout: &bynk_project::worker_layout::WorkerLayout,
655    parsed: &[ParsedFile],
656    groups: &BTreeMap<String, Vec<usize>>,
657    unit_uses: &HashMap<String, Vec<String>>,
658    errors: &mut ErrorSink,
659) {
660    use bynk_syntax::ast::HandlerKind;
661    let mut reported: BTreeSet<(std::path::PathBuf, usize)> = BTreeSet::new();
662    for (key, members) in layout.groups() {
663        let fixed: Vec<(&String, BTreeMap<String, String>)> = members
664            .iter()
665            .map(|m| (m, fixed_paths_of(m, parsed, groups, unit_uses)))
666            .collect();
667        for route_member in members {
668            for &i in groups.get(route_member.as_str()).into_iter().flatten() {
669                for item in parsed[i].items() {
670                    let CommonsItem::Service(svc) = item else {
671                        continue;
672                    };
673                    for h in &svc.handlers {
674                        let HandlerKind::Http { method, path } = &h.kind else {
675                            continue;
676                        };
677                        if path.split('/').any(|s| s.starts_with(':')) {
678                            continue;
679                        }
680                        // An asset this member reaches itself (its own, or a shared
681                        // commons') is `phase_asset_routes`'s to report, once.
682                        let own_shadow = fixed.iter().any(|(m, paths)| {
683                            *m == route_member && paths.keys().any(|at| route_matches(path, at))
684                        });
685                        if own_shadow {
686                            continue;
687                        }
688                        // The first other member whose asset sits at this path.
689                        let shadow = fixed.iter().find_map(|(asset_member, paths)| {
690                            let at = paths.keys().find(|at| route_matches(path, at))?;
691                            (*asset_member != route_member).then(|| (*asset_member, at, &paths[at]))
692                        });
693                        let Some((asset_member, at, source)) = shadow else {
694                            continue;
695                        };
696                        let file = parsed[i].identity_path();
697                        if reported.insert((file.clone(), h.span.start)) {
698                            errors.push_for(
699                                Some(&file),
700                                CompileError::new(
701                                    "bynk.asset.shadows_route",
702                                    h.span,
703                                    format!(
704                                        "`{} {path}` is unreachable: the asset `{source}` of `{asset_member}` is served at `{at}`, and `{asset_member}` and `{route_member}` share Worker `{key}`",
705                                        method.as_str()
706                                    ),
707                                )
708                                .with_note(
709                                    "the platform answers an asset's path before the Worker runs, for every method, and a group's members share one assets directory; move the asset or the route, or put the contexts in different groups",
710                                ),
711                            );
712                        }
713                    }
714                }
715            }
716        }
717    }
718}
719
720/// `bynk.asset.missing_file` for each asset whose (otherwise valid) path names
721/// no file in `available` — the project's `assets/` folder as the caller read
722/// it (`bynk_project::assets`). `None` skips the check: nothing on disk was
723/// consulted (an in-memory check). A build passes `Some`, an empty set when it
724/// had no filesystem, so it never invents a URL for a file nobody read.
725///
726/// A path that already fails [`path_errors`] is not also reported missing.
727pub fn phase_asset_files(
728    parsed: &[ParsedFile],
729    available: Option<&BTreeSet<String>>,
730    errors: &mut ErrorSink,
731) {
732    let Some(available) = available else { return };
733    for pf in parsed {
734        for item in pf.items() {
735            let CommonsItem::Asset(a) = item else {
736                continue;
737            };
738            if path_errors(a).is_some() {
739                continue;
740            }
741            let key = bynk_project::assets::normalise_asset_path(&a.path);
742            if !available.contains(&key) {
743                errors.push_for(
744                    Some(&pf.identity_path()),
745                    CompileError::new(
746                        "bynk.asset.missing_file",
747                        a.path_span,
748                        format!("asset `{}` names `{key}`, which does not exist", a.name.name),
749                    )
750                    .with_note(
751                        "an asset must be a regular file in the project's `assets/` folder; symbolic links are not followed",
752                    ),
753                );
754            }
755        }
756    }
757}
758
759/// The bytes of every declared asset file in `folder`, keyed by normalised
760/// path — read through the folder's reader once each, and only for a file a
761/// declaration names, so a large file nothing declares is never read. A
762/// declaration whose path fails [`path_errors`] or names no listed file is
763/// skipped ([`phase_asset_files`] reports the latter); a listed file the
764/// reader fails on is `bynk.asset.unreadable_file`, and is left out.
765pub fn read_declared_files(
766    parsed: &[ParsedFile],
767    folder: &bynk_project::assets::AssetFolder,
768    errors: &mut ErrorSink,
769) -> BTreeMap<String, Vec<u8>> {
770    let mut out = BTreeMap::new();
771    let mut failed: BTreeSet<String> = BTreeSet::new();
772    for pf in parsed {
773        for item in pf.items() {
774            let CommonsItem::Asset(a) = item else {
775                continue;
776            };
777            if path_errors(a).is_some() {
778                continue;
779            }
780            let key = bynk_project::assets::normalise_asset_path(&a.path);
781            if !folder.files().contains(&key) || out.contains_key(&key) {
782                continue;
783            }
784            if failed.contains(&key) {
785                // Reported once per declaration, read once per file.
786                errors.push_for(Some(&pf.identity_path()), unreadable_file_error(a, &key));
787                continue;
788            }
789            match folder.read(&key) {
790                Ok(bytes) => {
791                    out.insert(key, bytes);
792                }
793                Err(e) => {
794                    errors.push_for(
795                        Some(&pf.identity_path()),
796                        unreadable_file_error(a, &key).with_note(format!("the read failed: {e}")),
797                    );
798                    failed.insert(key);
799                }
800            }
801        }
802    }
803    out
804}
805
806fn unreadable_file_error(a: &AssetDecl, key: &str) -> CompileError {
807    CompileError::new(
808        "bynk.asset.unreadable_file",
809        a.path_span,
810        format!(
811            "asset `{}` names `{key}`, which could not be read",
812            a.name.name
813        ),
814    )
815}
816
817/// `bynk.asset.needs_project` for `a`: a single-file build emits one module
818/// and no Worker, and has no project root to find `assets/` under, so it
819/// cannot ship a file. Checking a single file (`bynk check page.bynk`) is
820/// unaffected; building one that declares an asset is refused. Build the
821/// project instead.
822pub fn needs_project_error(a: &AssetDecl) -> CompileError {
823    CompileError::new(
824        "bynk.asset.needs_project",
825        a.span,
826        format!(
827            "asset `{}` cannot be built from a single file",
828            a.name.name
829        ),
830    )
831    .with_note(
832        "an asset is served beside a Worker, so it needs a project build (`bynk dev`, `bynk compile <project dir>`) with the file in the project's `assets/` folder",
833    )
834}
835
836/// The name rule for asset `a`, given what its unit already declares under
837/// that name: an earlier asset is `bynk.asset.duplicate`; a free function or a
838/// type is `bynk.resolve.name_conflict` (an asset is a value, in the
839/// function namespace, and a type name in value position is an error). `None`
840/// when the name is free. One rule for the project pipeline
841/// (`symbols::build_unit_table`) and the single-file compile, which has no
842/// unit table (review of #1903).
843pub fn name_error(
844    a: &AssetDecl,
845    prev_asset: Option<&Ident>,
846    prev_fn: Option<&Ident>,
847    prev_type: Option<&Ident>,
848) -> Option<CompileError> {
849    let name = &a.name.name;
850    if let Some(prev) = prev_asset {
851        Some(
852            CompileError::new(
853                "bynk.asset.duplicate",
854                a.name.span,
855                format!("asset `{name}` is already declared"),
856            )
857            .with_label(prev.span, "previously declared here"),
858        )
859    } else if let Some(prev) = prev_fn {
860        Some(
861            CompileError::new(
862                "bynk.resolve.name_conflict",
863                a.name.span,
864                format!("asset `{name}` conflicts with a function of the same name"),
865            )
866            .with_label(prev.span, "function declared here"),
867        )
868    } else {
869        prev_type.map(|prev| {
870            CompileError::new(
871                "bynk.resolve.name_conflict",
872                a.name.span,
873                format!("asset `{name}` conflicts with a type of the same name"),
874            )
875            .with_label(prev.span, "type declared here")
876        })
877    }
878}
879
880/// The single-file compile's asset diagnostics, in declaration order: each
881/// asset's path check and name rule ([`name_error`], against the file's own
882/// functions, types and earlier assets), and, when `build` is set, its
883/// refusal ([`needs_project_error`]). Placement needs no check here: a
884/// single file is always a commons (an `adapter` is a parse error).
885pub fn single_file_asset_errors(items: &[CommonsItem], build: bool) -> Vec<CompileError> {
886    let mut fns: HashMap<&str, &Ident> = HashMap::new();
887    let mut types: HashMap<&str, &Ident> = HashMap::new();
888    for item in items {
889        match item {
890            CommonsItem::Fn(f) => {
891                if let FnName::Free(id) = &f.name {
892                    fns.entry(id.name.as_str()).or_insert(id);
893                }
894            }
895            CommonsItem::Type(t) => {
896                types.entry(t.name.name.as_str()).or_insert(&t.name);
897            }
898            CommonsItem::Event(e) => {
899                types.entry(e.name.name.as_str()).or_insert(&e.name);
900            }
901            _ => {}
902        }
903    }
904    let mut assets: HashMap<&str, &Ident> = HashMap::new();
905    let mut errors = Vec::new();
906    for item in items {
907        let CommonsItem::Asset(a) = item else {
908            continue;
909        };
910        errors.extend(path_errors(a));
911        errors.extend(at_path_error(a));
912        let key = a.name.name.as_str();
913        match name_error(
914            a,
915            assets.get(key).copied(),
916            fns.get(key).copied(),
917            types.get(key).copied(),
918        ) {
919            Some(err) => errors.push(err),
920            None => {
921                assets.insert(key, &a.name);
922            }
923        }
924        if build {
925            errors.push(needs_project_error(a));
926        }
927    }
928    errors
929}
930
931/// Every asset visible in unit `name`: its own, plus those of each commons it
932/// `uses` (one level, the same mixin rule `compose_unit_symbols` applies to
933/// types and functions). A local asset wins over an imported one of the same
934/// name; two used commons declaring the same name is
935/// `bynk.uses.name_conflict` (`phase_uses_name_conflicts`), so which of them
936/// is kept here is never observable in a program that checks.
937pub fn compose_unit_assets(
938    name: &str,
939    unit_info: &BTreeMap<String, UnitInfo>,
940) -> HashMap<String, AssetDecl> {
941    let Some(info) = unit_info.get(name) else {
942        return HashMap::new();
943    };
944    let mut combined = info.table.assets.clone();
945    for used in &info.uses {
946        let Some(used_info) = unit_info.get(used) else {
947            continue;
948        };
949        // #2618: a used commons' `private` assets stay in it.
950        for (asset_name, decl) in used_info
951            .table
952            .assets
953            .iter()
954            .filter(|(_, d)| d.private.is_none())
955        {
956            // #1925: a local declaration of any kind shadows the import.
957            if crate::symbols::local_value_kind(&info.table, asset_name).is_some() {
958                continue;
959            }
960            combined
961                .entry(asset_name.clone())
962                .or_insert_with(|| decl.clone());
963        }
964    }
965    combined
966}
967
968#[cfg(test)]
969mod tests {
970    use super::*;
971
972    /// The asset files these tests' declarations name, written into each
973    /// project beside its sources so the existence check passes (it reads
974    /// the `assets/` folder from disk, as the editor does).
975    const ASSET_FILES: &[(&str, &str)] = &[
976        ("assets/a.css", "a{}"),
977        ("assets/b.css", "b{}"),
978        ("assets/board.css", "body{}"),
979        ("assets/favicon.ico", "ico"),
980        ("assets/other.ico", "other"),
981    ];
982
983    fn analyse(files: &[(&str, &str)]) -> crate::testkit::Analysed {
984        let mut all = files.to_vec();
985        all.extend_from_slice(ASSET_FILES);
986        crate::testkit::analyse(&all)
987    }
988
989    /// #1883, slice 1b: a declared file must exist in `assets/`; a symlink
990    /// there does not count.
991    #[test]
992    fn a_declared_file_must_exist_in_the_assets_folder() {
993        let a = crate::testkit::analyse(&[(
994            "c.bynk",
995            "context c\n\nasset style = \"assets/missing.css\"\n",
996        )]);
997        a.assert_reports("bynk.asset.missing_file");
998
999        let a = analyse(&[(
1000            "c.bynk",
1001            "context c\n\nasset style = \"./assets/board.css\"\n",
1002        )]);
1003        a.assert_clean();
1004    }
1005
1006    /// [DECISION G]: a commons owns its stylesheet, and a context that `uses`
1007    /// it reads `.url` without naming the asset itself — in a free function
1008    /// and in a handler body, which is checked against its own per-handler
1009    /// view of the unit (`context_checks`).
1010    #[test]
1011    fn a_used_commons_asset_is_a_value_of_type_asset_with_a_string_url() {
1012        let a = analyse(&[
1013            (
1014                "compat/page.bynk",
1015                "commons compat.page\n\n---\nThe board's stylesheet.\n---\nasset style = \"assets/board.css\"\n\nfn link(a: Asset) -> String {\n  a.url\n}\n\nfn sheet() -> String {\n  style.url\n}\n",
1016            ),
1017            (
1018                "compat/board.bynk",
1019                "context compat.board\n\nuses compat.page\n\nfn head() -> String {\n  link(style)\n}\n\nservice web from http {\n  on GET(\"/\") () -> Effect[HttpResult[String]] by Visitor {\n    Ok(style.url)\n  }\n}\n",
1020            ),
1021        ]);
1022        a.assert_clean();
1023        assert_eq!(a.type_at("compat/page.bynk", "style.url"), "String");
1024        assert_eq!(a.type_at("compat/page.bynk", "a.url"), "String");
1025        assert_eq!(a.type_at("compat/board.bynk", "link(style)"), "String");
1026        assert_eq!(a.type_at("compat/board.bynk", "style.url"), "String");
1027    }
1028
1029    /// A local binding shadows an asset of the same name, as it shadows a
1030    /// function; `asset` stays an ordinary identifier outside its
1031    /// declaration position (a contextual keyword).
1032    #[test]
1033    fn a_local_shadows_an_asset_and_asset_is_still_an_identifier() {
1034        let a = analyse(&[(
1035            "c.bynk",
1036            "context c\n\nasset style = \"assets/a.css\"\n\nfn f(style: Int) -> Int {\n  style + 1\n}\n\nfn g(asset: Int) -> Int {\n  asset\n}\n",
1037        )]);
1038        a.assert_clean();
1039        assert_eq!(a.type_at("c.bynk", "style + 1"), "Int");
1040    }
1041
1042    /// A unit's own asset wins over a used commons' asset of the same name;
1043    /// only two *used* commons colliding is an error.
1044    #[test]
1045    fn a_local_asset_wins_over_a_used_one() {
1046        let a = analyse(&[
1047            (
1048                "lib/a.bynk",
1049                "commons lib.a\n\nasset style = \"assets/a.css\"\n",
1050            ),
1051            (
1052                "app/web.bynk",
1053                "context app.web\n\nuses lib.a\n\nasset style = \"assets/b.css\"\n\nfn f() -> String {\n  style.url\n}\n",
1054            ),
1055        ]);
1056        a.assert_clean();
1057    }
1058
1059    /// #1930: a method on an asset's `url`, written on the chain, is a method
1060    /// on a `String` in a context too, not a call into a context named
1061    /// `style.url`. A commons never reaches the cross-context check, since it
1062    /// has no `consumes`.
1063    #[test]
1064    fn a_method_on_an_assets_url_is_not_a_cross_context_call() {
1065        let a = analyse(&[(
1066            "app/web.bynk",
1067            "context app.web\n\nasset style = \"assets/a.css\"\n\nfn hashed() -> Bool {\n  style.url.startsWith(\"/_assets/\")\n}\n",
1068        )]);
1069        a.assert_clean();
1070    }
1071
1072    /// Review of #1937: an asset named like a consumed context's root segment
1073    /// does not hide that context, so a real cross-context call through it
1074    /// still resolves.
1075    #[test]
1076    fn an_asset_named_like_a_consumed_prefix_keeps_the_call() {
1077        let a = analyse(&[
1078            (
1079                "shop/payment.bynk",
1080                "context shop.payment\n\nservice charge {\n  on call(n: Int) -> Effect[Int] by Caller {\n    Effect.pure(n)\n  }\n}\n",
1081            ),
1082            (
1083                "shop/orders.bynk",
1084                "context shop.orders\n\nconsumes shop.payment\n\nasset shop = \"assets/a.css\"\n\nservice place {\n  on call() -> Effect[Int] by Caller {\n    let n <- shop.payment.charge(1)\n    Effect.pure(n)\n  }\n}\n",
1085            ),
1086        ]);
1087        a.assert_clean();
1088    }
1089
1090    #[test]
1091    fn two_used_commons_declaring_one_asset_name_conflict() {
1092        let a = analyse(&[
1093            (
1094                "lib/a.bynk",
1095                "commons lib.a\n\nasset style = \"assets/a.css\"\n",
1096            ),
1097            (
1098                "lib/b.bynk",
1099                "commons lib.b\n\nasset style = \"assets/b.css\"\n",
1100            ),
1101            (
1102                "app/web.bynk",
1103                "context app.web\n\nuses lib.a\nuses lib.b\n\nfn f() -> String {\n  style.url\n}\n",
1104            ),
1105        ]);
1106        a.assert_reports("bynk.uses.name_conflict");
1107    }
1108
1109    /// A unit split across files has one asset namespace: a second
1110    /// declaration in a sibling file is a duplicate, reported once, and a
1111    /// sibling's asset is visible without any `uses`.
1112    #[test]
1113    fn a_multi_file_unit_shares_one_asset_namespace() {
1114        let dup = analyse(&[
1115            ("c/a.bynk", "context c\n\nasset style = \"assets/a.css\"\n"),
1116            ("c/b.bynk", "context c\n\nasset style = \"assets/b.css\"\n"),
1117        ]);
1118        assert_eq!(
1119            dup.categories()
1120                .iter()
1121                .filter(|c| **c == "bynk.asset.duplicate")
1122                .count(),
1123            1,
1124            "{}",
1125            dup.render()
1126        );
1127        let shared = analyse(&[
1128            ("c/a.bynk", "context c\n\nasset style = \"assets/a.css\"\n"),
1129            (
1130                "c/b.bynk",
1131                "context c\n\nfn f() -> String {\n  style.url\n}\n",
1132            ),
1133        ]);
1134        shared.assert_clean();
1135    }
1136
1137    /// Review of #1903: a local asset must not hide a real conflict between
1138    /// two used commons over a *type* (or function) name. An asset only wins
1139    /// in value position; a type position still resolves through the
1140    /// imported types, so the ambiguity remains and must be reported.
1141    #[test]
1142    fn a_local_asset_does_not_hide_a_two_import_type_conflict() {
1143        let a = analyse(&[
1144            ("lib/a.bynk", "commons lib.a\n\ntype Style = Int\n"),
1145            ("lib/b.bynk", "commons lib.b\n\ntype Style = String\n"),
1146            (
1147                "app/web.bynk",
1148                "context app.web\n\nuses lib.a\nuses lib.b\n\nasset Style = \"assets/a.css\"\n\ntype Page = { s: Style }\n",
1149            ),
1150        ]);
1151        a.assert_reports("bynk.uses.name_conflict");
1152    }
1153
1154    #[test]
1155    fn an_asset_has_only_a_url_field() {
1156        let a = analyse(&[(
1157            "c.bynk",
1158            "context c\n\nasset style = \"assets/a.css\"\n\nfn f() -> String {\n  style.path\n}\n",
1159        )]);
1160        a.assert_reports("bynk.types.unknown_field");
1161    }
1162
1163    /// Placement, duplicates, name conflicts, path safety, the boundary rule
1164    /// and the reserved type name, one project each.
1165    #[test]
1166    fn each_declaration_rule_reports_its_own_code() {
1167        for (src, code) in [
1168            (
1169                "adapter c\n\nbinding \"./c.js\"\n\nasset style = \"assets/a.css\"\n",
1170                "bynk.asset.outside_context_or_commons",
1171            ),
1172            (
1173                "context c\n\nasset style = \"assets/a.css\"\nasset style = \"assets/b.css\"\n",
1174                "bynk.asset.duplicate",
1175            ),
1176            (
1177                "context c\n\nfn style() -> Int {\n  1\n}\n\nasset style = \"assets/a.css\"\n",
1178                "bynk.resolve.name_conflict",
1179            ),
1180            (
1181                "context c\n\ntype Style = Int\n\nasset Style = \"assets/a.css\"\n",
1182                "bynk.resolve.name_conflict",
1183            ),
1184            (
1185                "context c\n\nasset style = \"/etc/passwd\"\n",
1186                "bynk.asset.unsafe_path",
1187            ),
1188            (
1189                "context c\n\nasset style = \"../x.css\"\n",
1190                "bynk.asset.unsafe_path",
1191            ),
1192            (
1193                "context c\n\ntype Page = { style: Asset }\n",
1194                "bynk.types.asset_at_boundary",
1195            ),
1196            (
1197                "context c\n\ntype Asset = Int\n",
1198                "bynk.resolve.reserved_builtin_type",
1199            ),
1200            (
1201                "context c\n\nasset env = \".env\"\n",
1202                "bynk.asset.outside_assets_dir",
1203            ),
1204            (
1205                "context c\n\nasset page = \"src/c.bynk\"\n",
1206                "bynk.asset.outside_assets_dir",
1207            ),
1208            (
1209                "context c\n\nagent Board {\n  key id: String\n\n  store style: Cell[Asset]\n\n  on call get() -> Effect[Int] {\n    Effect.pure(1)\n  }\n}\n",
1210                "bynk.types.asset_at_boundary",
1211            ),
1212        ] {
1213            let a = analyse(&[("c.bynk", src)]);
1214            a.assert_reports(code);
1215        }
1216    }
1217
1218    #[test]
1219    fn served_path_is_hashed_flat_and_url_safe() {
1220        let h = crate::contract::fnv1a64_hex(b"body{}");
1221        assert_eq!(
1222            served_path("assets/board.css", b"body{}"),
1223            format!("/_assets/board.{h}.css")
1224        );
1225        assert_eq!(
1226            served_path("assets/css/board.min.css", b"body{}"),
1227            format!("/_assets/board.min.{h}.css")
1228        );
1229        assert_eq!(
1230            served_path("assets/LICENSE", b"body{}"),
1231            format!("/_assets/LICENSE.{h}")
1232        );
1233        assert_eq!(
1234            served_path("assets/.nojekyll", b"body{}"),
1235            format!("/_assets/.nojekyll.{h}")
1236        );
1237        assert_eq!(
1238            served_path("assets/my file é.css", b"body{}"),
1239            format!("/_assets/my-file--.{h}.css")
1240        );
1241        assert_ne!(
1242            served_path("assets/board.css", b"a"),
1243            served_path("assets/board.css", b"b"),
1244            "a content change changes the URL"
1245        );
1246    }
1247
1248    /// A Worker ships the files of its whole `uses` closure, not just the
1249    /// first level: `ctx -> a -> b -> c`, and only `c` declares an asset.
1250    #[test]
1251    fn deployed_assets_follow_the_transitive_uses_closure() {
1252        fn decl(name: &str, path: &str) -> AssetDecl {
1253            AssetDecl {
1254                name: Ident {
1255                    name: name.to_string(),
1256                    span: Default::default(),
1257                },
1258                path: path.to_string(),
1259                path_span: Default::default(),
1260                at: None,
1261                documentation: None,
1262                span: Default::default(),
1263                trivia: Default::default(),
1264                private: None,
1265            }
1266        }
1267        let mut tables: HashMap<String, crate::symbols::UnitTable> = HashMap::new();
1268        for unit in ["ctx", "a", "b", "c", "unused"] {
1269            tables.insert(unit.to_string(), Default::default());
1270        }
1271        tables
1272            .get_mut("c")
1273            .unwrap()
1274            .assets
1275            .insert("style".into(), decl("style", "./assets/board.css"));
1276        tables
1277            .get_mut("unused")
1278            .unwrap()
1279            .assets
1280            .insert("logo".into(), decl("logo", "assets/logo.png"));
1281        let uses: HashMap<String, Vec<String>> =
1282            [("ctx", vec!["a"]), ("a", vec!["b"]), ("b", vec!["c", "a"])]
1283                .into_iter()
1284                .map(|(k, v)| (k.to_string(), v.into_iter().map(String::from).collect()))
1285                .collect();
1286        let served: BTreeMap<String, String> = [
1287            (
1288                "assets/board.css".to_string(),
1289                "/_assets/board.1.css".to_string(),
1290            ),
1291            (
1292                "assets/logo.png".to_string(),
1293                "/_assets/logo.2.png".to_string(),
1294            ),
1295        ]
1296        .into_iter()
1297        .collect();
1298        let deployed = deployed_assets("ctx", &uses, &HashMap::new(), &tables, &served);
1299        assert_eq!(
1300            deployed.into_iter().collect::<Vec<_>>(),
1301            vec![(
1302                "/_assets/board.1.css".to_string(),
1303                "assets/board.css".to_string()
1304            )]
1305        );
1306    }
1307
1308    #[test]
1309    fn at_path_reason_accepts_a_file_path_and_rejects_the_rest() {
1310        for ok in [
1311            "/favicon.ico",
1312            "/robots.txt",
1313            "/.well-known/security.txt",
1314            "/a/b-c_d~e.f",
1315        ] {
1316            assert_eq!(at_path_reason(ok), None, "{ok} is valid");
1317        }
1318        for bad in [
1319            "favicon.ico",
1320            "/",
1321            "/dir/",
1322            "//x",
1323            "/a/../b",
1324            "/./a",
1325            "/a b.txt",
1326            "/a?b",
1327            "/_assets/x.css",
1328            "/_assets",
1329            "/_bynk/x",
1330            // Review of #1906: files the platform reads as configuration.
1331            "/_headers",
1332            "/_redirects",
1333            "/.assetsignore",
1334        ] {
1335            assert!(at_path_reason(bad).is_some(), "{bad} is rejected");
1336        }
1337    }
1338
1339    #[test]
1340    fn route_matching_is_segment_wise_with_params() {
1341        assert!(route_matches("/favicon.ico", "/favicon.ico"));
1342        assert!(route_matches("/:page", "/favicon.ico"));
1343        assert!(route_matches("/a/:id", "/a/b"));
1344        assert!(!route_matches("/a/:id", "/a"));
1345        assert!(!route_matches("/:page", "/a/b"));
1346        assert!(!route_matches("/favicon.png", "/favicon.ico"));
1347    }
1348
1349    const HANDLER: &str = "service web from http {\n  on GET(\"ROUTE\") () -> Effect[HttpResult[String]] by Visitor {\n    Ok(\"x\")\n  }\n}\n";
1350
1351    fn context_with(asset: &str, route: &str) -> String {
1352        format!(
1353            "context c\n\n{asset}\n\n{}",
1354            HANDLER.replace("ROUTE", route)
1355        )
1356    }
1357
1358    /// #1883, slice 2: a fixed path against the Worker's own routes — an
1359    /// exact literal route is unreachable (an error, for every method); a
1360    /// parameterised one only loses that path (a warning).
1361    #[test]
1362    fn a_fixed_path_is_checked_against_the_workers_routes() {
1363        let fav = "asset favicon = \"assets/favicon.ico\" at \"/favicon.ico\"";
1364        analyse(&[("c.bynk", &context_with(fav, "/favicon.ico"))])
1365            .assert_reports("bynk.asset.shadows_route");
1366        let param = context_with(fav, "/:page").replace("() ->", "(page: String) ->");
1367        let a = analyse(&[("c.bynk", &param)]);
1368        a.assert_reports("bynk.asset.may_shadow_route");
1369        assert!(
1370            a.error_categories().is_empty(),
1371            "a warning only: {}",
1372            a.render()
1373        );
1374        analyse(&[("c.bynk", &context_with(fav, "/home"))]).assert_clean();
1375        // Content-hashed assets never meet a route: `/_assets/` is reserved.
1376        analyse(&[(
1377            "c.bynk",
1378            &context_with("asset style = \"assets/board.css\"", "/_assets/x.css"),
1379        )])
1380        .assert_reports("bynk.http.reserved_prefix");
1381    }
1382
1383    /// Two different files at one fixed path in one Worker conflict, whether
1384    /// declared together or reached through `uses`; the same file twice is
1385    /// fine. And an invalid `at` path is reported at the declaration.
1386    #[test]
1387    fn fixed_paths_conflict_and_validate() {
1388        let a = analyse(&[
1389            (
1390                "lib/a.bynk",
1391                "commons lib.a\n\nasset icon = \"assets/favicon.ico\" at \"/favicon.ico\"\n",
1392            ),
1393            (
1394                "app/web.bynk",
1395                "context app.web\n\nuses lib.a\n\nasset other = \"assets/other.ico\" at \"/favicon.ico\"\n",
1396            ),
1397        ]);
1398        a.assert_reports("bynk.asset.path_conflict");
1399        analyse(&[(
1400            "c.bynk",
1401            "context c\n\nasset a = \"assets/favicon.ico\" at \"/favicon.ico\"\nasset b = \"assets/favicon.ico\" at \"/favicon.ico\"\n",
1402        )])
1403        .assert_clean();
1404        analyse(&[(
1405            "c.bynk",
1406            "context c\n\nasset a = \"assets/favicon.ico\" at \"/_assets/favicon.ico\"\n",
1407        )])
1408        .assert_reports("bynk.asset.invalid_at_path");
1409        // Review of #1906: one path cannot be both a file and a folder.
1410        analyse(&[(
1411            "c.bynk",
1412            "context c\n\nasset logo = \"assets/favicon.ico\" at \"/logo\"\nasset icon = \"assets/other.ico\" at \"/logo/icon.ico\"\n",
1413        )])
1414        .assert_reports("bynk.asset.path_conflict");
1415    }
1416
1417    /// Hashed assets ship over `uses` and `consumes`; fixed ones over `uses`
1418    /// only, so a consumed context's root files stay its own.
1419    #[test]
1420    fn consumes_ships_hashed_assets_but_not_fixed_ones() {
1421        fn decl(name: &str, path: &str, at: Option<&str>) -> AssetDecl {
1422            AssetDecl {
1423                name: Ident {
1424                    name: name.to_string(),
1425                    span: Default::default(),
1426                },
1427                path: path.to_string(),
1428                path_span: Default::default(),
1429                at: at.map(|a| (a.to_string(), Default::default())),
1430                documentation: None,
1431                span: Default::default(),
1432                trivia: Default::default(),
1433                private: None,
1434            }
1435        }
1436        let mut tables: HashMap<String, crate::symbols::UnitTable> = HashMap::new();
1437        for unit in ["a", "b"] {
1438            tables.insert(unit.to_string(), Default::default());
1439        }
1440        let b = tables.get_mut("b").unwrap();
1441        b.assets
1442            .insert("badge".into(), decl("badge", "assets/badge.svg", None));
1443        b.assets.insert(
1444            "robots".into(),
1445            decl("robots", "assets/robots.txt", Some("/robots.txt")),
1446        );
1447        let consumes: HashMap<String, Vec<String>> = [("a".to_string(), vec!["b".to_string()])]
1448            .into_iter()
1449            .collect();
1450        let served: BTreeMap<String, String> = [
1451            (
1452                "assets/badge.svg".to_string(),
1453                "/_assets/badge.1.svg".to_string(),
1454            ),
1455            (
1456                "assets/robots.txt at /robots.txt".to_string(),
1457                "/robots.txt".to_string(),
1458            ),
1459        ]
1460        .into_iter()
1461        .collect();
1462        let a = deployed_assets("a", &HashMap::new(), &consumes, &tables, &served);
1463        assert_eq!(
1464            a.keys().cloned().collect::<Vec<_>>(),
1465            vec!["/_assets/badge.1.svg"]
1466        );
1467        let b = deployed_assets("b", &HashMap::new(), &consumes, &tables, &served);
1468        assert_eq!(
1469            b.keys().cloned().collect::<Vec<_>>(),
1470            vec!["/_assets/badge.1.svg", "/robots.txt"]
1471        );
1472    }
1473
1474    /// #1883, slice 3: a suite names its target's assets and fetches one with
1475    /// `svc.GET(asset)` — `GET` only, the asset alone, and no `by` (an asset
1476    /// is public). Anything else that is not a route string is still a bad
1477    /// address.
1478    #[test]
1479    fn a_suite_fetches_an_asset_by_get_alone() {
1480        let web = "context t.web\n\nasset style = \"assets/board.css\"\n\nservice api from http {\n  on GET(\"/\") () -> Effect[HttpResult[String]] by Visitor {\n    Ok(style.url)\n  }\n}\n";
1481        let suite = |body: &str| format!("suite t.web {{\n  case \"c\" {{\n{body}\n  }}\n}}\n");
1482        let run = |body: &str| analyse(&[("t/web.bynk", web), ("tests/web.bynk", &suite(body))]);
1483        run("    expect style.url == style.url\n    let r <- api.GET(style)\n    expect r is Raw(_, _)")
1484            .assert_clean();
1485        run("    let r <- api.POST(style)\n    expect r is Raw(_, _)")
1486            .assert_reports("bynk.test.asset_address_method");
1487        run("    let r <- api.GET(style, 1)\n    expect r is Raw(_, _)")
1488            .assert_reports("bynk.test.service_call_arity");
1489        run("    let r <- api.GET(style) by Visitor\n    expect r is Raw(_, _)")
1490            .assert_reports("bynk.test.principal_on_asset");
1491        run("    let s = \"/\"\n    let r <- api.GET(s)\n    expect r is Ok(_)")
1492            .assert_reports("bynk.test.service_bad_address");
1493    }
1494
1495    /// #1883, slice 3 (review of #1922): the content types measured against
1496    /// `wrangler dev` 4.107.0, pinned so the next wrangler bump has something
1497    /// to diff against, plus the edges the doc comment promises.
1498    #[test]
1499    fn content_type_for_matches_the_platform() {
1500        for (path, ct) in [
1501            ("/_assets/board.3f9c2a.css", "text/css; charset=utf-8"),
1502            ("/_assets/app.1.js", "text/javascript; charset=utf-8"),
1503            ("/_assets/app.1.mjs", "text/javascript; charset=utf-8"),
1504            ("/_assets/d.1.json", "application/json"),
1505            ("/index.html", "text/html; charset=utf-8"),
1506            ("/index.htm", "text/html; charset=utf-8"),
1507            ("/robots.txt", "text/plain; charset=utf-8"),
1508            ("/feed.xml", "application/xml"),
1509            ("/_assets/i.1.svg", "image/svg+xml"),
1510            ("/_assets/i.1.png", "image/png"),
1511            ("/_assets/i.1.jpg", "image/jpeg"),
1512            ("/_assets/i.1.jpeg", "image/jpeg"),
1513            ("/_assets/i.1.gif", "image/gif"),
1514            ("/_assets/i.1.webp", "image/webp"),
1515            ("/_assets/i.1.avif", "image/avif"),
1516            ("/favicon.ico", "image/vnd.microsoft.icon"),
1517            ("/_assets/f.1.woff", "font/woff"),
1518            ("/_assets/f.1.woff2", "font/woff2"),
1519            ("/_assets/f.1.ttf", "font/ttf"),
1520            ("/_assets/f.1.otf", "font/otf"),
1521            ("/doc.pdf", "application/pdf"),
1522            ("/_assets/m.1.wasm", "application/wasm"),
1523            ("/_assets/app.1.map", "application/json"),
1524            ("/data.csv", "text/csv; charset=utf-8"),
1525            ("/notes.md", "text/markdown; charset=utf-8"),
1526            ("/site.webmanifest", "application/manifest+json"),
1527            ("/v.mp4", "video/mp4"),
1528            ("/v.webm", "video/webm"),
1529            ("/a.mp3", "audio/mpeg"),
1530            ("/a.wav", "audio/wav"),
1531            ("/x.zip", "application/zip"),
1532            ("/x.bin", "application/octet-stream"),
1533            // Edges: an unknown extension, an uppercase one, no extension
1534            // (served with no content type), and a dotfile (no extension).
1535            ("/x.unknownext", "application/octet-stream"),
1536            ("/Logo.PNG", "image/png"),
1537            ("/_assets/README.1", "application/octet-stream"),
1538            ("/README", ""),
1539            ("/.hidden", ""),
1540        ] {
1541            assert_eq!(content_type_for(path), ct, "{path}");
1542        }
1543    }
1544
1545    /// Review of #1922: an asset is fetched through an HTTP service only, and a
1546    /// `system` suite names only its target's assets — the files the target's
1547    /// Worker ships — so nothing nameable can answer `NotFound`.
1548    #[test]
1549    fn asset_fetches_are_http_only_and_target_scoped() {
1550        let web = "context t.web\n\nasset style = \"assets/board.css\"\n\nservice jobs from queue(\"q\") {\n  on message(m: String) -> Effect[QueueResult] {\n    Ack\n  }\n}\n\nservice api from http {\n  on GET(\"/\") () -> Effect[HttpResult[String]] by Visitor {\n    Ok(style.url)\n  }\n}\n";
1551        let a = analyse(&[
1552            ("t/web.bynk", web),
1553            (
1554                "tests/web.bynk",
1555                "suite t.web {\n  case \"c\" {\n    let r <- jobs.GET(style)\n    expect r is Raw(_, _)\n  }\n}\n",
1556            ),
1557        ]);
1558        a.assert_reports("bynk.test.service_bad_address");
1559
1560        let lib = "commons t.lib\n\nasset other = \"assets/a.css\"\n";
1561        let a = analyse(&[
1562            ("t/web.bynk", web),
1563            ("t/lib.bynk", lib),
1564            (
1565                "tests/web_system.bynk",
1566                "suite t.web as system {\n  uses t.lib\n\n  case \"c\" {\n    let r <- api.GET(other)\n    expect r is Raw(_, _)\n  }\n}\n",
1567            ),
1568        ]);
1569        a.assert_reports("bynk.resolve.unknown_name");
1570    }
1571
1572    /// Review of #1923: a suite names exactly what the target's Worker ships
1573    /// (`deployed_assets`) — so a consumed context's content-hashed asset is
1574    /// nameable and fetchable, at both tiers, while its fixed path (served
1575    /// only by its own Worker) is not.
1576    #[test]
1577    fn a_consumed_contexts_hashed_asset_is_nameable_but_its_fixed_one_is_not() {
1578        let other = "context t.other\n\nasset badge = \"assets/a.css\"\nasset robots = \"assets/b.css\" at \"/robots.txt\"\n\nservice fragment {\n  on call() -> Effect[String] by Caller {\n    Effect.pure(badge.url)\n  }\n}\n";
1579        let web = "context t.web\n\nconsumes t.other\n\nservice api from http {\n  on GET(\"/\") () -> Effect[HttpResult[String]] by Visitor {\n    let f <- t.other.fragment()\n    Ok(f)\n  }\n}\n";
1580        for header in ["suite t.web", "suite t.web as system"] {
1581            let suite = |body: &str| format!("{header} {{\n  case \"c\" {{\n{body}\n  }}\n}}\n");
1582            analyse(&[
1583                ("t/other.bynk", other),
1584                ("t/web.bynk", web),
1585                (
1586                    "tests/web.bynk",
1587                    &suite("    let r <- api.GET(badge)\n    expect r is Raw(_, _)"),
1588                ),
1589            ])
1590            .assert_clean();
1591            analyse(&[
1592                ("t/other.bynk", other),
1593                ("t/web.bynk", web),
1594                (
1595                    "tests/web.bynk",
1596                    &suite("    let r <- api.GET(robots)\n    expect r is Raw(_, _)"),
1597                ),
1598            ])
1599            .assert_reports("bynk.resolve.unknown_name");
1600        }
1601    }
1602
1603    #[test]
1604    fn unsafe_asset_path_reason_accepts_relative_paths_and_rejects_escapes() {
1605        for ok in [
1606            "assets/board.css",
1607            "board.css",
1608            "assets/.well-known/security.txt",
1609            "a..b/c.css",
1610            "./assets/x.css",
1611        ] {
1612            assert_eq!(unsafe_asset_path_reason(ok), None, "{ok} is safe");
1613        }
1614        for (bad, why) in [
1615            ("", "the path is empty"),
1616            ("/etc/passwd", "the path is absolute"),
1617            ("\\x.css", "the path is absolute"),
1618            ("C:/x.css", "the path is absolute"),
1619            ("../secret.txt", "the path contains a `..` segment"),
1620            ("assets/../../x", "the path contains a `..` segment"),
1621            ("assets\\..\\x", "the path contains a `..` segment"),
1622            ("assets/..", "the path contains a `..` segment"),
1623        ] {
1624            assert_eq!(unsafe_asset_path_reason(bad), Some(why), "{bad}");
1625        }
1626    }
1627}