Skip to main content

bynk_driver/
strip.rs

1//! The project-level strip: rewrite a compiled [`ProjectOutput`] from TypeScript into a
2//! JavaScript artefact (the in-browser track's first-class JS output, ADR 0137).
3//!
4//! These functions walk a `ProjectOutput`, so they live with the rest of the orchestration
5//! in `bynk-driver` (crate-hygiene D1, #2982, PR 4); `bynk-strip` keeps the text-level
6//! strip (`strip_types`, `strip_types_mapped`) on `bynk-ts` and `oxc` alone, so it builds
7//! alongside the checker instead of after code generation.
8
9use std::path::PathBuf;
10
11use bynk_emit::emit_model::{Artefacts, Document, ProjectOutput, sibling_path};
12pub use bynk_strip::StripError;
13
14/// Rewrite a compiled [`ProjectOutput`] from
15/// TypeScript into a JavaScript artefact (the in-browser track's first-class JS
16/// output — ADR 0137). The emitter always produces TypeScript; a JS artefact is
17/// that same output with types stripped, which is total because the emitter is
18/// strip-only (ADR 0136).
19///
20/// Dispatches on [`Document`] directly (P7.6,
21/// #1309) — no `CompiledFile` text intermediate. Every `Ts` document is
22/// printed through the one printer that owns a character (R7.3), then
23/// type-stripped and renamed to `.js` as its own `Document::Js`; `tsconfig.json`
24/// is dropped (a TypeScript-compiler config with no role for a JS artefact);
25/// `wrangler.toml`'s real tree gets its `main` entry patched *structurally*,
26/// in place — no print-then-reparse (Decision E) — since the Workers
27/// manifest names its entry module and a `main` left pointing at the
28/// stripped `.ts` breaks `wrangler dev`/deploy on the emitted output. Source
29/// maps and the debug sidecar are dropped — they map into the `.ts` the JS
30/// replaces. Import specifiers are already `.js` (the default `ImportExt`),
31/// so the renamed tree resolves as-is.
32pub fn strip_project_to_js(out: ProjectOutput) -> Result<ProjectOutput, StripError> {
33    strip_project(out, None).map(|(out, _)| out)
34}
35
36/// The per-`.js`-path Bynk-to-JavaScript source maps of a stripped project.
37pub type JsMaps = std::collections::BTreeMap<PathBuf, String>;
38
39/// [`strip_project_to_js`] that also returns, per emitted `.js` path, a
40/// Bynk-to-JavaScript v3 source map composed from the emitter's own
41/// Bynk-to-TypeScript map and the strip's TypeScript-to-JavaScript map (#2705).
42/// Only the modules in `only` (JS output paths; the host passes the user's own)
43/// are mapped, so the rest skip the work. The returned `ProjectOutput` is identical to
44/// [`strip_project_to_js`]'s: the maps are not added as documents.
45pub fn strip_project_to_js_mapped(
46    out: ProjectOutput,
47    only: &std::collections::HashSet<PathBuf>,
48) -> Result<(ProjectOutput, JsMaps), StripError> {
49    strip_project(out, Some(only))
50}
51
52fn strip_project(
53    out: ProjectOutput,
54    only: Option<&std::collections::HashSet<PathBuf>>,
55) -> Result<(ProjectOutput, JsMaps), StripError> {
56    use std::collections::BTreeMap;
57
58    let bynk_maps: BTreeMap<PathBuf, String> = if only.is_some() {
59        out.artefacts
60            .docs
61            .iter()
62            .filter_map(|(p, d)| match d {
63                Document::SourceMap(s) => Some((p.clone(), s.clone())),
64                _ => None,
65            })
66            .collect()
67    } else {
68        BTreeMap::new()
69    };
70    let mut js_maps: JsMaps = BTreeMap::new();
71    let mut docs: BTreeMap<PathBuf, Document> = BTreeMap::new();
72    for (path, doc) in out.artefacts.docs {
73        match doc {
74            Document::Ts(program) => {
75                let printed = bynk_ts::print(&program, "", "", &path.to_string_lossy());
76                let js_path = path.with_extension("js");
77                let want_map = only.is_some_and(|o| o.contains(&js_path));
78                let bynk_map = if want_map {
79                    bynk_maps
80                        .get(&sibling_path(&path, "map"))
81                        .map(String::as_str)
82                } else {
83                    None
84                };
85                let (js, map) = bynk_strip::strip_types_mapped(
86                    &printed.text,
87                    &path.to_string_lossy(),
88                    bynk_map,
89                )?;
90                if let Some(map) = map {
91                    js_maps.insert(js_path.clone(), map);
92                }
93                docs.insert(js_path, Document::Js(js));
94            }
95            Document::Toml(mut toml) => {
96                if path.file_name().and_then(|n| n.to_str()) == Some("wrangler.toml")
97                    && !toml.set_main("index.js")
98                {
99                    return Err(StripError {
100                        filename: path.to_string_lossy().into_owned(),
101                        message: "wrangler.toml has no root `main` key".to_string(),
102                    });
103                }
104                docs.insert(path, Document::Toml(toml));
105            }
106            Document::Json(s) => {
107                if path.file_name().and_then(|n| n.to_str()) == Some("tsconfig.json") {
108                    continue;
109                }
110                docs.insert(path, Document::Json(s));
111            }
112            // Source maps/debug sidecars map into the `.ts` the JS replaces.
113            Document::SourceMap(_) | Document::DebugSidecar(_) => {}
114            // `bynk-emit` never produces this itself, but `strip_project_to_js`
115            // is `pub` over a `pub` `Artefacts`, so an already-stripped
116            // `Document::Js` reaching this function (e.g. run twice, or a
117            // caller assembling `Artefacts` by hand) is a real, reachable
118            // input — pass it through rather than panicking on it (review,
119            // #1309/#1310: `unreachable!` here aborted the process on input
120            // the public API permits).
121            Document::Js(s) => {
122                docs.insert(path, Document::Js(s));
123            }
124            // P4b (#2608): a migration is SQL, not code.
125            Document::Sql(s) => {
126                docs.insert(path, Document::Sql(s));
127            }
128        }
129    }
130    // #1883, slice 0: static assets are served as-is by the platform; type
131    // stripping has nothing to do to them.
132    Ok((
133        ProjectOutput {
134            artefacts: Artefacts {
135                docs,
136                assets: out.artefacts.assets,
137                modules: out.artefacts.modules,
138            },
139            ..out
140        },
141        js_maps,
142    ))
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    /// P7.4 (#1305)/P7.6 (#1309): `strip_project_to_js`'s `wrangler.toml`
150    /// patch, exercised through the real function against a *real* compiled
151    /// `Document::Toml` tree (`compile_in_memory`, `BuildTarget::Workers`) —
152    /// not a hand-typed text fixture standing in for one, which is exactly
153    /// the shortcut P7.4's own defect report warns against (a hand-built
154    ///2-key snippet can't prove a whole-document reformat didn't happen).
155    /// P7.6's own Decision E moved this from a text re-parse
156    /// (`toml_edit`) to a structural, in-tree mutation
157    /// (`TomlDocument::set_main`) — asserting the *printed* text still
158    /// pins "nothing but `main` changed", the same discipline as before.
159    #[test]
160    fn strip_project_to_js_patches_wrangler_toml_main_structurally() {
161        use crate::project::{BuildTarget, Document, compile_in_memory};
162
163        let out = compile_in_memory(
164            "context api {\n  service routes from http {\n    on GET(\"/\") () -> Effect[HttpResult[String]] by v: Visitor {\n      Ok(\"ok\")\n    }\n  }\n}\n",
165            BuildTarget::Workers,
166            Default::default(),
167        )
168        .unwrap_or_else(|f| {
169            panic!(
170                "workers-target fixture should compile: {:?}",
171                f.flatten()
172            )
173        });
174        let wrangler_path = out
175            .artefacts
176            .docs
177            .keys()
178            .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("wrangler.toml"))
179            .cloned()
180            .expect("a Workers-target compile emits a wrangler.toml");
181        let original_text = out.artefacts.docs[&wrangler_path].text();
182        assert!(
183            original_text.contains("main = \"index.ts\""),
184            "expected the pre-strip manifest to point at the .ts entry:\n{original_text}"
185        );
186
187        let stripped = strip_project_to_js(out).expect("wrangler.toml patches cleanly");
188        let patched = stripped
189            .artefacts
190            .docs
191            .get(&wrangler_path)
192            .unwrap_or_else(|| panic!("{} should survive stripping", wrangler_path.display()));
193        assert!(
194            matches!(patched, Document::Toml(_)),
195            "wrangler.toml should stay a real tree through stripping, not become opaque text"
196        );
197        let expected = original_text.replacen("main = \"index.ts\"", "main = \"index.js\"", 1);
198        assert_eq!(
199            patched.text(),
200            expected,
201            "only `main` should differ from the pre-strip manifest"
202        );
203        // No leftover `.ts` index — `Document::Ts` entries are all renamed
204        // to their own `.js` sibling.
205        let index_ts = wrangler_path.with_file_name("index.ts");
206        assert!(
207            !stripped.artefacts.docs.contains_key(&index_ts),
208            "the stripped output must not keep the pre-strip .ts path: {:?}",
209            stripped.artefacts.docs.keys().collect::<Vec<_>>()
210        );
211    }
212
213    /// #1883, slice 0: static assets are served as-is, so stripping a
214    /// project's types must hand `Artefacts.assets` through byte-for-byte —
215    /// `bynk compile --emit js` strips before it writes, and an asset dropped
216    /// here would be missing from that output. One is added to a real
217    /// build's output by hand, so this tests stripping alone.
218    #[test]
219    fn strip_project_to_js_passes_static_assets_through_unchanged() {
220        use crate::project::{BuildTarget, compile_in_memory, worker_assets_dir};
221
222        let mut out = compile_in_memory(
223            "commons only\n\nfn f() -> Int {\n  1\n}\n",
224            BuildTarget::Workers,
225            Default::default(),
226        )
227        .unwrap_or_else(|f| panic!("fixture should compile: {:?}", f.flatten()));
228        let path = worker_assets_dir("only").join("_assets/icon.9b1d4e.png");
229        let bytes = vec![0x89, b'P', b'N', b'G', 0xff, 0x00];
230        out.artefacts.assets.insert(path.clone(), bytes.clone());
231
232        let stripped = strip_project_to_js(out).expect("strips cleanly");
233        assert_eq!(stripped.artefacts.assets.len(), 1);
234        assert_eq!(stripped.artefacts.assets.get(&path), Some(&bytes));
235    }
236}