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