Skip to main content

bynk_driver/
output.rs

1//! Writing a compiled project's output to disk.
2//!
3//! Moved down from `bynk-emit` (#1047, R2.3/T0.7 residue): every caller was
4//! already at driver level (`bynk`'s CLI/test paths, `bynk dev`'s in-process
5//! build) — `bynk-emit` never called this itself, so relocating it here is a
6//! pure move, not a design change. `bynk-emit` stays a pure, in-memory
7//! library; disk writes are the driver's job, as R2.3 says they should be.
8
9use std::collections::BTreeMap;
10use std::path::{Path, PathBuf};
11
12use crate::project::{
13    Document, ProjectOutput, is_worker_asset_path, is_worker_migration_path, sibling_path,
14};
15
16/// Write a [`ProjectOutput`]'s artefacts under `dir`, creating parent
17/// directories as needed. The shared writer behind both `bynk`'s
18/// `compile`/`test` paths and `bynk dev`'s in-process build (slice 7) — so
19/// the on-disk result is identical however the build was driven.
20///
21/// Reconciles `dir` against `out.artefacts` first: a `.ts`/`.js`/
22/// `.map`/`.json`/`.toml` file already on disk that no longer corresponds to
23/// anything in `out.artefacts.docs` is deleted — as is any file at all under
24/// a Worker's compiler-owned assets directory (#1883, slice 0;
25/// [`crate::project::WORKER_ASSETS_DIR`]) that is not in
26/// `out.artefacts.assets` — along with any directory
27/// that becomes empty as a result — otherwise a deleted `.bynk` unit's
28/// emitted `.ts` lingers on disk, still type-checked by the emitted
29/// `tsconfig.json`'s `include: **/*.ts`, so `tsc` fails against a module the
30/// current project no longer has. `node_modules` and dotfile directories
31/// (`.git`, an npm-installed tree under the output root) are never
32/// descended into — this reconciles the compiler's own output, not whatever
33/// else happens to live alongside it.
34pub fn write_output(out: &ProjectOutput, dir: &Path) -> std::io::Result<()> {
35    prune_stale_output(out, dir)?;
36    for (path, doc) in &out.artefacts.docs {
37        write_document(path, doc, &out.artefacts.docs, dir)?;
38    }
39    for (path, bytes) in &out.artefacts.assets {
40        // Review of #1902: a path in both maps would silently resolve to the
41        // asset, decided only by loop order. Unreachable while documents never
42        // land in an assets directory; this makes it a test failure if one does.
43        debug_assert!(
44            !out.artefacts.docs.contains_key(path),
45            "`{}` is both a document and a static asset",
46            path.display()
47        );
48        write_asset(path, bytes, dir)?;
49    }
50    write_modules(&out.artefacts.modules, dir)
51}
52
53/// #2321: write the WebAssembly modules adapter bindings include, byte for
54/// byte, beside the bindings that load them.
55pub fn write_modules(modules: &BTreeMap<PathBuf, Vec<u8>>, dir: &Path) -> std::io::Result<()> {
56    for (path, bytes) in modules {
57        let target = dir.join(path);
58        if let Some(parent) = target.parent() {
59            std::fs::create_dir_all(parent)?;
60        }
61        std::fs::write(&target, bytes)?;
62    }
63    Ok(())
64}
65
66/// #2321: for a run on Node (`bynk test`), write the modules and overwrite each
67/// one's Workers loader shim with the Node form
68/// ([`crate::project::node_wasm_shim`]), which inlines the module. Call it
69/// after every document write, since a later write of `docs` restores the
70/// Workers form.
71pub fn write_modules_for_node(
72    modules: &BTreeMap<PathBuf, Vec<u8>>,
73    dir: &Path,
74) -> std::io::Result<()> {
75    write_modules(modules, dir)?;
76    for (path, bytes) in modules {
77        std::fs::write(
78            dir.join(crate::project::wasm_shim_path(path)),
79            crate::project::node_wasm_shim(bytes),
80        )?;
81    }
82    Ok(())
83}
84
85/// #1883, slice 0: write one static asset's bytes under `dir`, verbatim. The
86/// binary-safe counterpart of [`write_document`] — an asset is not a
87/// [`Document`] (see `crate::project::Artefacts::assets` for why), so it
88/// gets no printer, no source-map trailer and no text conversion.
89///
90/// Every asset must lie under a Worker's compiler-owned assets directory
91/// ([`is_worker_asset_path`]): that is the only place reconciliation prunes
92/// files of any extension, so an asset written anywhere else would linger
93/// after it stopped being produced. Producers build the path through
94/// `crate::project::worker_assets_dir`; this assertion makes bypassing it
95/// a test failure rather than a silent leak.
96fn write_asset(path: &Path, bytes: &[u8], dir: &Path) -> std::io::Result<()> {
97    debug_assert!(
98        is_worker_asset_path(path),
99        "static asset `{}` is outside every Worker's assets directory",
100        path.display()
101    );
102    let target = dir.join(path);
103    if let Some(parent) = target.parent() {
104        std::fs::create_dir_all(parent)?;
105    }
106    std::fs::write(&target, bytes)
107}
108
109/// Write one [`Document`] under `dir` — the real, typed write boundary
110/// (P7.6, #1309, Decision C: one place derives the sibling-path relationship
111/// instead of two independently-maintained ones). Shared by [`write_output`]
112/// and `bynk-driver::test_runner`'s own output loop (`bynk test`), so every
113/// disk-writing path emits maps uniformly (slice 2 — `bynk test --inspect`
114/// runs the emitted `.ts` directly and needs the maps on disk).
115///
116/// A `Ts` document is printed through the one printer that owns a character
117/// (R7.3); its own `Printed::source_map` is discarded, not written — the
118/// real map, when one exists, is already present in `docs` as its own
119/// `SourceMap` entry at this path's `.map` sibling ([`sibling_path`]), split
120/// out at construction (`bynk-driver::project::build_output`'s own tail).
121/// That sibling's presence, not `Printed::source_map`, is what decides
122/// whether the `.ts`/`.js` file gets a `//# sourceMappingURL=` trailer — the
123/// trailer lives only on the on-disk artefact, not on `docs`' own in-memory
124/// text, so golden comparisons are unaffected.
125pub fn write_document(
126    path: &Path,
127    doc: &Document,
128    docs: &BTreeMap<PathBuf, Document>,
129    dir: &Path,
130) -> std::io::Result<()> {
131    let target = dir.join(path);
132    if let Some(parent) = target.parent() {
133        std::fs::create_dir_all(parent)?;
134    }
135    let mapped_text = match doc {
136        Document::Ts(program) => {
137            Some(bynk_ts::print(program, "", "", &path.to_string_lossy()).text)
138        }
139        Document::Js(s) => Some(s.clone()),
140        _ => None,
141    };
142    if let Some(text) = mapped_text {
143        match docs.get(&sibling_path(path, "map")) {
144            Some(_) => {
145                let map_name = match target.file_name() {
146                    Some(n) => format!("{}.map", n.to_string_lossy()),
147                    None => "module.ts.map".to_string(),
148                };
149                let with_trailer = format!("{text}//# sourceMappingURL={map_name}\n");
150                std::fs::write(&target, with_trailer)?;
151            }
152            None => std::fs::write(&target, &text)?,
153        }
154        return Ok(());
155    }
156    match doc {
157        Document::Toml(t) => {
158            std::fs::write(
159                &target,
160                bynk_emit::emitter::toml_doc::print_toml_document(t),
161            )?;
162        }
163        Document::Json(s)
164        | Document::SourceMap(s)
165        | Document::DebugSidecar(s)
166        | Document::Sql(s) => {
167            std::fs::write(&target, s)?;
168        }
169        Document::Ts(_) | Document::Js(_) => unreachable!("handled above"),
170    }
171    Ok(())
172}
173
174/// The project-relative paths [`write_output`] will have written once this
175/// `ProjectOutput` lands on disk — exactly `out.artefacts.docs`'s own keys
176/// (`bynk-driver::project::build_output`'s own tail already splits every
177/// `.map`/`.bynkdbg.json` sidecar into its own entry there, Decision C), plus
178/// `out.artefacts.assets`'s (#1883, slice 0) and `out.artefacts.modules`' (#2321).
179fn expected_output_paths(out: &ProjectOutput) -> std::collections::HashSet<PathBuf> {
180    out.artefacts
181        .docs
182        .keys()
183        .chain(out.artefacts.assets.keys())
184        .chain(out.artefacts.modules.keys())
185        .cloned()
186        .collect()
187}
188
189/// Extensions the compiler ever writes under a build-output directory — the
190/// set [`write_output`]'s reconciliation is allowed to prune. Kept narrow so a
191/// directory the caller points `write_output` at can still carry other files
192/// unrelated to a `.bynk` build without those being swept up.
193fn is_prunable_output_extension(ext: &str) -> bool {
194    matches!(ext, "ts" | "js" | "map" | "json" | "toml" | "wasm")
195}
196
197fn prune_stale_output(out: &ProjectOutput, dir: &Path) -> std::io::Result<()> {
198    prune_output_except(dir, &expected_output_paths(out))
199}
200
201/// [`write_output`]'s reconciliation, against an explicit set of the
202/// root-relative paths a run wrote. #3748: `bynk test` writes one or two
203/// compiles' documents into the same root, so it names the union itself.
204pub(crate) fn prune_output_except(
205    dir: &Path,
206    expected: &std::collections::HashSet<PathBuf>,
207) -> std::io::Result<()> {
208    if !dir.is_dir() {
209        return Ok(());
210    }
211    let mut dirs_visited = Vec::new();
212    prune_stale_output_dir(dir, dir, expected, &mut dirs_visited)?;
213    // Remove directories left empty by the file removals above, deepest first
214    // (a parent only empties out once its children are gone). `remove_dir` is
215    // a no-op error (ignored) on anything still non-empty — e.g. a directory
216    // that held only unrelated files to begin with.
217    dirs_visited.sort_by_key(|p| std::cmp::Reverse(p.components().count()));
218    for d in dirs_visited {
219        let _ = std::fs::remove_dir(&d);
220    }
221    Ok(())
222}
223
224fn prune_stale_output_dir(
225    root: &Path,
226    dir: &Path,
227    expected: &std::collections::HashSet<std::path::PathBuf>,
228    dirs_visited: &mut Vec<std::path::PathBuf>,
229) -> std::io::Result<()> {
230    for entry in std::fs::read_dir(dir)? {
231        let entry = entry?;
232        let path = entry.path();
233        let file_type = entry.file_type()?;
234        let rel = path.strip_prefix(root).unwrap_or(&path);
235        // #1883, slice 0: the compiler owns a Worker's assets directory
236        // outright. Review of #1902: that has to hold for every kind of
237        // entry there, or an asset the build stopped producing lingers and
238        // keeps being served.
239        let owned_asset = is_worker_asset_path(rel);
240        if file_type.is_dir() {
241            let is_own_cache = path
242                .file_name()
243                .and_then(|n| n.to_str())
244                .is_some_and(|n| n == "node_modules" || n.starts_with('.'));
245            // The `.git`/`node_modules` skip protects trees that live beside
246            // the compiler's output. Inside an assets directory there are no
247            // such trees, and a dot-directory (`.well-known/`) holds assets.
248            if is_own_cache && !owned_asset {
249                continue;
250            }
251            prune_stale_output_dir(root, &path, expected, dirs_visited)?;
252            dirs_visited.push(path);
253        } else if file_type.is_file() {
254            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
255            // Inside an assets directory the extension filter does not apply:
256            // an asset keeps its source's extension (`.css`, `.png`, …) and
257            // the platform's `_headers` file has none.
258            // P4b (#2608): a `.sql` only where the build copies migrations.
259            let prunable = is_prunable_output_extension(ext)
260                || owned_asset
261                || (ext == "sql" && is_worker_migration_path(rel));
262            if prunable && !expected.contains(rel) {
263                std::fs::remove_file(&path)?;
264            }
265        } else if file_type.is_symlink() && owned_asset && !expected.contains(rel) {
266            // `DirEntry::file_type` does not follow links, so a symlink is
267            // neither `is_dir` nor `is_file`. `remove_file` removes the link
268            // itself, never its target.
269            std::fs::remove_file(&path)?;
270        }
271    }
272    Ok(())
273}