Skip to main content

bynk_driver/
compile_cmd.rs

1//! The `compile` command body, run by `bynk compile`
2//! (D2/E1, #2998): before this, only `bynk` had it, so `bynk compile` had to
3//! start a `bynk` process. Parameterised by the program name that prefixes
4//! messages, like [`crate::run_check`] and [`crate::run_fmt`].
5
6use crate::emsg;
7use std::path::{Path, PathBuf};
8use std::process::ExitCode;
9
10use clap::ValueEnum;
11
12use crate::project::{BuildTarget, CompileOptions, SchemaLock, compile_project};
13use bynk_check::firstparty::Platform;
14
15/// `--profile`: a named build profile (#3054). It chooses the defaults a
16/// `[profile.<name>]` table can override; today that is `contracts` only.
17#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
18pub enum CliProfile {
19    /// The development build: the function-contract call-site guard is on.
20    Dev,
21    /// The deployable build (the default): no contract guard, the same bytes
22    /// `bynk compile` writes.
23    Release,
24}
25
26impl CliProfile {
27    fn name(self) -> &'static str {
28        match self {
29            CliProfile::Dev => "dev",
30            CliProfile::Release => "release",
31        }
32    }
33
34    /// Whether the profile carries the contract guard when the manifest says
35    /// nothing.
36    fn contracts_by_default(self) -> bool {
37        self == CliProfile::Dev
38    }
39}
40
41/// #3107: whether a build under `profile` carries the contract guard, the one
42/// rule every verb that builds shares: `[profile.<name>] contracts`, else the
43/// profile's default (`dev` on, `release` off). `bynk build` also takes a
44/// profile from its flag; `test` is always `dev`, `deploy` always `release`.
45pub fn profile_contracts(
46    profiles: &std::collections::BTreeMap<String, bynk_project::ProfileConfig>,
47    profile: CliProfile,
48) -> bool {
49    profiles
50        .get(profile.name())
51        .and_then(|p| p.contracts)
52        .unwrap_or_else(|| profile.contracts_by_default())
53}
54
55/// [`profile_contracts`] for the project at `root`, reading its `bynk.toml`.
56pub fn project_contracts(root: &Path, profile: CliProfile) -> Result<bool, String> {
57    // Only `[profile]`: `test` and `deploy` do not read `[build]`.
58    let profiles = bynk_project::try_read_profiles(root).map_err(|e| e.to_string())?;
59    Ok(profile_contracts(&profiles, profile))
60}
61
62/// #3107: `deploy` always builds `release`, and a deployment never carries
63/// contract checks (DECISION J of v0.115), so `[profile.release] contracts =
64/// true` is refused for it, naming the table.
65pub fn refuse_release_contracts(root: &Path) -> Result<(), String> {
66    if project_contracts(root, CliProfile::Release)? {
67        return Err("`[profile.release] contracts = true` in `bynk.toml` would put contract checks in what is deployed, and a deployment never carries them — set it to `false` or remove it (it still applies to `bynk build`)".to_string());
68    }
69    Ok(())
70}
71
72/// What a deployment refuses before it prepares anything: contract checks in the
73/// release profile ([`refuse_release_contracts`]). A `[deploy.workers]` group is not one.
74pub fn refuse_undeployable_project(root: &Path) -> Result<(), String> {
75    // A group table that does not read must stop the run here: `deploy` places
76    // every context by it, and would otherwise place each on its own Worker.
77    bynk_project::worker_groups::try_read_worker_groups(root)
78        .map_err(|e| format!("invalid `[deploy.workers]` in `bynk.toml`: {e}"))?;
79    refuse_release_contracts(root)
80}
81
82/// `--target`: the build topology.
83#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
84pub enum CliTarget {
85    /// Single-bundle output (the default). Cross-context calls compile to
86    /// direct function invocation.
87    Bundle,
88    /// One Cloudflare Worker per context. Cross-context calls go over
89    /// Service Bindings using a JSON wire format.
90    Workers,
91}
92
93impl From<CliTarget> for BuildTarget {
94    fn from(t: CliTarget) -> Self {
95        match t {
96            CliTarget::Bundle => BuildTarget::Bundle,
97            CliTarget::Workers => BuildTarget::Workers,
98        }
99    }
100}
101
102/// v0.108 (in-browser track, slice 1): the emitted artefact language. `ts` (the
103/// default and primary output) writes the typed TypeScript modules; `js` writes
104/// the same modules with their types stripped — an *emit-then-strip* JavaScript
105/// artefact (ADR 0137) runnable with no `tsc` in the loop. Orthogonal to
106/// `--target` (topology) and `--platform` (binding).
107#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
108pub enum EmitFormat {
109    /// TypeScript modules (the default, primary artefact).
110    #[default]
111    Ts,
112    /// JavaScript modules, types stripped (no `tsc` dependency).
113    Js,
114}
115
116/// v0.17: the deploy platform that selects the `bynk` surface binding. Distinct
117/// from [`CliTarget`] (the emit topology). v0.18 adds `node`.
118#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
119pub enum CliPlatform {
120    /// Cloudflare Workers runtime (the default).
121    #[default]
122    Cloudflare,
123    /// Node.js (≥ 22) runtime (v0.18).
124    Node,
125    /// The browser — the `bynk` surface over Web APIs, for the in-browser
126    /// REPL/playground (v0.108). `Bundle` topology only; `Fetch`/`Secrets` are
127    /// withheld (see ADR 0138).
128    Browser,
129}
130
131impl From<CliPlatform> for Platform {
132    fn from(p: CliPlatform) -> Self {
133        match p {
134            CliPlatform::Cloudflare => Platform::Cloudflare,
135            CliPlatform::Node => Platform::Node,
136            CliPlatform::Browser => Platform::Browser,
137        }
138    }
139}
140
141/// What a `compile` run was asked to do.
142#[derive(Clone, Debug)]
143pub struct CompileArgs {
144    /// A `.bynk` file or a project directory.
145    pub input: PathBuf,
146    /// Output file (single-file input) or output root (project input).
147    pub output: PathBuf,
148    pub target: CliTarget,
149    pub platform: CliPlatform,
150    pub emit: EmitFormat,
151    /// #2471: layer the JSON document on stdin over the project's sources.
152    pub sources_stdin: bool,
153    /// #3054: build with the function-contract call-site guard. `bynk compile`
154    /// passes `false`; only `bynk build --profile dev` (or a `[profile]` table)
155    /// turns it on.
156    pub contracts: bool,
157}
158
159/// What a `build` run was asked to do: the flags given, over `[build]`.
160#[derive(Clone, Debug, Default)]
161pub struct BuildArgs {
162    /// A project directory.
163    pub input: PathBuf,
164    pub out: Option<PathBuf>,
165    pub target: Option<CliTarget>,
166    pub platform: Option<CliPlatform>,
167    pub emit: Option<EmitFormat>,
168    /// The profile; `release` when unset.
169    pub profile: Option<CliProfile>,
170}
171
172/// Run `build` (#3054): resolve each setting as flag, else `[build]`, else the
173/// built-in default, then run [`run_compile`]. `compile` itself never reads
174/// `[build]`.
175pub fn run_build(prog: &str, args: BuildArgs) -> ExitCode {
176    let BuildArgs {
177        input,
178        out,
179        target,
180        platform,
181        emit,
182        profile,
183    } = args;
184    if !input.is_dir() {
185        emsg!(
186            "{prog}: error: `build` takes a project directory; use `{prog} compile` for a single file"
187        );
188        return ExitCode::FAILURE;
189    }
190    let config = match bynk_project::try_read_build_config(&input) {
191        Ok(c) => c,
192        Err(e) => {
193            emsg!("{prog}: error: {e}");
194            return ExitCode::FAILURE;
195        }
196    };
197    // The manifest's strings were checked against the same sets in
198    // `bynk-project`; a name that no longer parses is a bug there, never a
199    // silent fall back to the default.
200    fn parse<T: ValueEnum>(key: &str, value: Option<&str>) -> Result<Option<T>, String> {
201        match value {
202            None => Ok(None),
203            Some(v) => T::from_str(v, true).map(Some).map_err(|_| {
204                format!("`[build]` `{key}` = \"{v}\" is not a value this `bynk` knows")
205            }),
206        }
207    }
208    let resolved = (|| -> Result<_, String> {
209        Ok((
210            target
211                .or(parse("target", config.target.as_deref())?)
212                .unwrap_or(CliTarget::Bundle),
213            platform
214                .or(parse("platform", config.platform.as_deref())?)
215                .unwrap_or_default(),
216            emit.or(parse("emit", config.emit.as_deref())?)
217                .unwrap_or_default(),
218        ))
219    })();
220    let (target, platform, emit) = match resolved {
221        Ok(r) => r,
222        Err(e) => {
223            emsg!("{prog}: error: {e}");
224            return ExitCode::FAILURE;
225        }
226    };
227    // CLI flag > `[profile.<name>]` > `[build]` > built-in default. `contracts`
228    // has no flag and no `[build]` key, so it is the profile's table, else the
229    // profile's default.
230    let profile = profile.unwrap_or(CliProfile::Release);
231    let contracts = profile_contracts(&config.profiles, profile);
232    let output = out.unwrap_or_else(|| input.join(config.out.as_deref().unwrap_or("out")));
233    if let Err(e) = check_output_dir(&input, &output) {
234        emsg!("{prog}: error: {e}");
235        return ExitCode::FAILURE;
236    }
237    let code = run_compile_reporting(
238        prog,
239        CompileArgs {
240            input,
241            output: output.clone(),
242            target,
243            platform,
244            emit,
245            sources_stdin: false,
246            contracts,
247        },
248        crate::progress::terminal_sink(),
249    );
250    if code == ExitCode::SUCCESS {
251        let target = match target {
252            CliTarget::Bundle => "bundle",
253            CliTarget::Workers => "workers",
254        };
255        let profile = match (profile, contracts) {
256            (CliProfile::Release, false) => String::new(),
257            (p, c) => format!(
258                " ({} profile, contracts {})",
259                p.name(),
260                if c { "on" } else { "off" }
261            ),
262        };
263        emsg!("{prog}: built {target}{profile} -> {}", output.display());
264    }
265    code
266}
267
268/// `path` with symlinks resolved as far as it exists, the rest appended as
269/// written, so a not-yet-created output directory can still be placed.
270fn resolve(path: &Path) -> PathBuf {
271    let mut rest = Vec::new();
272    let mut cur = path.to_path_buf();
273    loop {
274        if let Ok(real) = cur.canonicalize() {
275            return rest.iter().rev().fold(real, |acc, c| acc.join(c));
276        }
277        match (cur.file_name().map(ToOwned::to_owned), cur.parent()) {
278            (Some(name), Some(parent)) => {
279                rest.push(name);
280                cur = if parent.as_os_str().is_empty() {
281                    PathBuf::from(".")
282                } else {
283                    parent.to_path_buf()
284                };
285            }
286            _ => return path.to_path_buf(),
287        }
288    }
289}
290
291/// Whether any `.bynk` file sits under `dir` (build-output caches skipped).
292fn holds_bynk_source(dir: &Path) -> bool {
293    let Ok(entries) = std::fs::read_dir(dir) else {
294        return false;
295    };
296    entries.flatten().any(|e| {
297        let path = e.path();
298        let name = e.file_name();
299        let name = name.to_string_lossy();
300        match e.file_type() {
301            Ok(t) if t.is_dir() => {
302                name != "node_modules" && !name.starts_with('.') && holds_bynk_source(&path)
303            }
304            Ok(t) if t.is_file() => path.extension().is_some_and(|x| x == "bynk"),
305            _ => false,
306        }
307    })
308}
309
310/// #3054 review: the writer prunes `.ts`/`.js`/`.json`/… files in the output
311/// directory that the build did not produce, so an output directory that is
312/// the project root, a source root, holds or sits inside one, escapes the
313/// project (also through a symlink), or already holds `.bynk` source would
314/// delete hand-written files on every build. Refuse those.
315fn check_output_dir(project: &Path, output: &Path) -> Result<(), String> {
316    let root = resolve(project);
317    // `output` is relative to the cwd (a flag) or already joined onto
318    // `project` (the manifest key); `canonicalize` resolves both from the cwd.
319    let out = resolve(output);
320    let shown = output.display();
321    if !out.starts_with(&root) || out == root {
322        return Err(format!(
323            "the output directory `{shown}` must be a directory inside the project, not the project root or a path outside it"
324        ));
325    }
326    let paths = bynk_project::try_read_project_paths(project)
327        .unwrap_or_else(|_| bynk_project::ProjectPaths::conventional(project));
328    for include in &paths.include {
329        let source = resolve(&project.join(include));
330        // A flat project's root is the source root; the output lives inside
331        // it by design (`out/` is skipped by discovery).
332        if source == root {
333            continue;
334        }
335        if out.starts_with(&source) || source.starts_with(&out) {
336            return Err(format!(
337                "the output directory `{shown}` overlaps the source root `{}`, and a build deletes files it did not write from its output directory; choose another `[build] out`",
338                include.display()
339            ));
340        }
341    }
342    if holds_bynk_source(&out) {
343        return Err(format!(
344            "the output directory `{shown}` holds `.bynk` sources, and a build deletes files it did not write from its output directory; choose another `[build] out`"
345        ));
346    }
347    Ok(())
348}
349
350/// Run `compile`. `prog` prefixes the messages (`"bynk"`).
351pub fn run_compile(prog: &str, args: CompileArgs) -> ExitCode {
352    run_compile_reporting(prog, args, None)
353}
354
355/// [`run_compile`], reporting each context to `progress` as it compiles (#3100).
356fn run_compile_reporting(
357    prog: &str,
358    args: CompileArgs,
359    progress: Option<crate::project::ProgressSink>,
360) -> ExitCode {
361    let CompileArgs {
362        input,
363        output,
364        target,
365        platform,
366        emit,
367        sources_stdin,
368        contracts,
369    } = args;
370    if sources_stdin && !input.is_dir() {
371        emsg!("{prog}: error: --sources-stdin needs a project directory, not a single file");
372        return ExitCode::FAILURE;
373    }
374    if input.is_dir() {
375        compile_dir(
376            prog,
377            &input,
378            &output,
379            DirSettings {
380                target,
381                platform,
382                emit,
383                sources_stdin,
384                contracts,
385                progress,
386            },
387        )
388    } else {
389        compile_file(prog, &input, &output, emit)
390    }
391}
392
393/// What a project (directory) compile is configured with.
394struct DirSettings {
395    target: CliTarget,
396    platform: CliPlatform,
397    emit: EmitFormat,
398    sources_stdin: bool,
399    contracts: bool,
400    progress: Option<crate::project::ProgressSink>,
401}
402
403fn compile_dir(prog: &str, input: &Path, output: &Path, settings: DirSettings) -> ExitCode {
404    let DirSettings {
405        target,
406        platform,
407        emit,
408        sources_stdin,
409        contracts,
410        progress,
411    } = settings;
412    // #1078: `bynk-emit` touches no disk for `bynk.schema.lock` — read
413    // its current content here (verified-absent `None` for a fresh
414    // project) and hand it in; write the reconciled content back after
415    // a clean compile, below.
416    let schema_lock = match crate::schema_lock::read(input) {
417        // #2471: a preview build reconciles nothing and writes nothing.
418        Ok(_) if sources_stdin => SchemaLock::Off,
419        Ok(existing) => SchemaLock::On { existing },
420        Err(e) => {
421            emsg!(
422                "{prog}: error: could not read {}: {e}",
423                crate::schema_lock::lock_path(input).display()
424            );
425            return ExitCode::FAILURE;
426        }
427    };
428    let options: CompileOptions = match crate::try_project_options(input) {
429        // Events track, slice 3c (#980): a real directory build reconciles
430        // and writes `bynk.schema.lock` — the Cargo.lock model. Every
431        // other `compile_project` caller (in-memory builds, `bynk/
432        // tests/e2e.rs`'s in-place fixtures, the LSP) leaves this off.
433        // #1821 (ADR 0147 D3): a build strips every `suite`; only
434        // `bynk test` compiles them.
435        Ok(o) => o
436            .target(target.into())
437            .platform(platform.into())
438            .schema_registry(schema_lock)
439            .contracts(contracts)
440            .progress(progress)
441            .out_dir(Some(output.to_path_buf()))
442            .tests(false),
443        Err(e) => {
444            // #3274: `compile` can't take `--each`, so its refusal of a
445            // directory of projects doesn't advise it.
446            emsg!("{prog}: error: {}", e.render(false));
447            return ExitCode::FAILURE;
448        }
449    };
450    let options = if sources_stdin {
451        match overlay_from_stdin(options, input) {
452            Ok(o) => o,
453            Err(e) => {
454                emsg!("{prog}: error: {e}");
455                return ExitCode::FAILURE;
456            }
457        }
458    } else {
459        options
460    };
461    // Multi-file project compile.
462    match compile_project(&options) {
463        Ok(out) => {
464            // A write failure here is reported but does not fail the
465            // build — the same non-fatal handling this used to get
466            // (`schema_registry::write`'s own eprintln) when the write
467            // lived inside `compile_project` itself.
468            if let Some(content) = &out.schema_lock
469                && let Err(e) = crate::schema_lock::write_reporting(prog, input, content)
470            {
471                emsg!(
472                    "{prog}: warning: could not write {}: {e}",
473                    crate::schema_lock::lock_path(input).display()
474                );
475            }
476            // `--emit js` (the in-browser track, slice 1, ADR 0137): the
477            // emitter always produces TypeScript; a JS artefact is that same
478            // output with types stripped (the emitter is strip-only — ADR
479            // 0136 — so the strip is total). Rewrite the file set before the
480            // shared writer touches disk.
481            let out = match emit {
482                EmitFormat::Ts => out,
483                EmitFormat::Js => match crate::strip::strip_project_to_js(out) {
484                    Ok(out) => out,
485                    Err(e) => {
486                        emsg!("{prog}: error: could not produce JavaScript output: {e}");
487                        return ExitCode::FAILURE;
488                    }
489                },
490            };
491            match crate::write_output(&out, output) {
492                Ok(()) => {
493                    // ADR 0117: surface non-failing warnings; the build succeeds.
494                    crate::print_project_warnings(&out.warnings, &out.snapshots, &out.display_root);
495                    ExitCode::SUCCESS
496                }
497                Err(e) => {
498                    emsg!(
499                        "{prog}: error: could not write output under `{}`: {e}",
500                        output.display()
501                    );
502                    ExitCode::FAILURE
503                }
504            }
505        }
506        Err(failure) => {
507            crate::print_project_failure(&failure);
508            ExitCode::FAILURE
509        }
510    }
511}
512
513fn compile_file(prog: &str, input: &Path, output: &Path, emit: EmitFormat) -> ExitCode {
514    let source = match std::fs::read_to_string(input) {
515        Ok(s) => s,
516        Err(e) => {
517            emsg!("{prog}: error: could not read `{}`: {e}", input.display());
518            return ExitCode::FAILURE;
519        }
520    };
521    let filename = input.display().to_string();
522    match bynk_emit::compile_with_warnings(&source, &filename) {
523        Ok(compiled) => {
524            // For `--emit js` the single emitted module is stripped to JS; the
525            // caller names the output path (e.g. `-o out.js`).
526            let body = match emit {
527                EmitFormat::Ts => compiled.ts,
528                EmitFormat::Js => match bynk_strip::strip_types(&compiled.ts, &filename) {
529                    Ok(js) => js,
530                    Err(e) => {
531                        emsg!("{prog}: error: could not produce JavaScript output: {e}");
532                        return ExitCode::FAILURE;
533                    }
534                },
535            };
536            if let Some(parent) = output.parent() {
537                let _ = std::fs::create_dir_all(parent);
538            }
539            if let Err(e) = std::fs::write(output, body) {
540                emsg!("{prog}: error: could not write `{}`: {e}", output.display());
541                return ExitCode::FAILURE;
542            }
543            // ADR 0117: render non-failing warnings with source context.
544            // #2838: a hint is for the editor, not the terminal.
545            let warnings = crate::render::without_hints(&compiled.warnings);
546            if !warnings.is_empty() {
547                crate::render::print_errors(&warnings, &source, &filename, crate::colour::stderr());
548            }
549            ExitCode::SUCCESS
550        }
551        Err(errors) => {
552            crate::render::print_errors(&errors, &source, &filename, crate::colour::stderr());
553            ExitCode::FAILURE
554        }
555    }
556}
557
558/// #2471: layer the `--sources-stdin` document over `options`' sources.
559fn overlay_from_stdin(
560    options: CompileOptions,
561    root: &Path,
562) -> Result<CompileOptions, Box<dyn std::error::Error>> {
563    use std::io::Read as _;
564    let mut json = String::new();
565    std::io::stdin().read_to_string(&mut json)?;
566    let overlay = crate::source_overlay::parse_overlay(&json)?;
567    Ok(crate::source_overlay::apply_overlay(
568        options, root, overlay,
569    )?)
570}
571
572#[cfg(test)]
573mod profile_tests {
574    use super::*;
575    use bynk_project::ProfileConfig;
576
577    type Profiles = std::collections::BTreeMap<String, ProfileConfig>;
578
579    fn with(dev: Option<bool>, release: Option<bool>) -> Profiles {
580        let mut c = Profiles::new();
581        for (name, v) in [("dev", dev), ("release", release)] {
582            if v.is_some() {
583                c.insert(name.to_string(), ProfileConfig { contracts: v });
584            }
585        }
586        c
587    }
588
589    #[test]
590    fn a_profile_defaults_then_its_table_overrides() {
591        let none = with(None, None);
592        assert!(profile_contracts(&none, CliProfile::Dev));
593        assert!(!profile_contracts(&none, CliProfile::Release));
594        let set = with(Some(false), Some(true));
595        assert!(!profile_contracts(&set, CliProfile::Dev));
596        assert!(profile_contracts(&set, CliProfile::Release));
597    }
598
599    #[test]
600    fn one_profiles_table_does_not_touch_the_other() {
601        let only_dev = with(Some(false), None);
602        assert!(!profile_contracts(&only_dev, CliProfile::Dev));
603        assert!(!profile_contracts(&only_dev, CliProfile::Release));
604    }
605}
606
607#[cfg(test)]
608mod worker_group_refusal_tests {
609    use std::fs;
610
611    fn project(name: &str, manifest: &str) -> std::path::PathBuf {
612        let root =
613            std::env::temp_dir().join(format!("bynk-refuse-groups-{name}-{}", std::process::id()));
614        let _ = fs::remove_dir_all(&root);
615        fs::create_dir_all(&root).unwrap();
616        fs::write(root.join("bynk.toml"), manifest).unwrap();
617        root
618    }
619
620    /// Any group is refused, a group of one included: it still moves the context
621    /// `deploy` accepts a group, but a table that does not read stops it before
622    /// it places each context on its own Worker (#3562).
623    #[test]
624    fn deploy_accepts_a_group_and_refuses_a_malformed_table() {
625        let good = project(
626            "good",
627            "[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[deploy.workers.core]\ncontexts = [\"a\", \"b\"]\n",
628        );
629        assert!(super::refuse_undeployable_project(&good).is_ok());
630        let bad = project(
631            "bad-deploy",
632            "[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[deploy.workers]\ncore = 3\n",
633        );
634        let err = super::refuse_undeployable_project(&bad).unwrap_err();
635        assert!(err.starts_with("invalid `[deploy.workers]`"), "{err}");
636        let _ = fs::remove_dir_all(&good);
637        let _ = fs::remove_dir_all(&bad);
638    }
639}