Skip to main content

bynk_driver/project/
options.rs

1use bynk_check::project_model::BuildTarget;
2use bynk_emit::emit_model::ImportExt;
3use bynk_emit::emit_model::RemoteTests;
4use bynk_project::ProjectPaths;
5use bynk_project::Roots;
6use bynk_project::SchemaLock;
7use bynk_project::assets;
8use std::collections::{BTreeMap, HashMap};
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use bynk_check::firstparty::Platform;
13
14/// #3100: one step of a build, reported as it happens. Only a `context` is
15/// reported: commons and test units compile as part of the build, not as steps.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum ProgressEvent {
18    /// A context's check and emission began.
19    Started(String),
20    /// A context checked and emitted cleanly. A context with errors reports
21    /// no `Finished`: its diagnostics follow.
22    Finished(String),
23}
24
25/// Where a build reports [`ProgressEvent`]s. Called in compilation order
26/// (dependencies first), on the building thread.
27pub type ProgressSink = Arc<dyn Fn(&ProgressEvent) + Send + Sync>;
28
29/// Options for [`compile_project`](super::compile_project). Construct with [`CompileOptions::single`] or
30/// [`CompileOptions::split`], then chain `.target(…)` / `.platform(…)` /
31/// `.import_ext(…)` to override the bundle/default-platform/`.js` defaults.
32#[derive(Clone)]
33pub struct CompileOptions {
34    /// #3477: the directory the build will be written to, when the caller knows
35    /// it (`bynk build` and `bynk compile`), so a container's build paths can be
36    /// written from the Worker's output directory back to the project. `None`
37    /// uses the project's `[build] out`.
38    pub out_dir: Option<PathBuf>,
39    pub target: BuildTarget,
40    pub platform: Platform,
41    pub roots: Roots,
42    /// The import-specifier extension (slice 2). `Js` (default) for normal builds;
43    /// `Ts` for the `bynk test --inspect` debug build.
44    pub import_ext: ImportExt,
45    /// v0.115 (testing track slice 3, DECISION J): the build profile for function
46    /// contracts. `true` (dev/test) emits the call-site guard around a contracted
47    /// `fn`; `false` (release/deploy) strips it entirely for zero runtime cost.
48    /// `bynk test` and `--inspect` set it on; `bynk compile` leaves it off.
49    pub contracts: bool,
50    /// #3580 (the dev request-traces track): emit the per-request trace recording
51    /// (`__bynk_runtime/trace`) into a Workers build, for `bynk dev
52    /// --trace-events`. `false` for every other build, so a deploy build's
53    /// output is byte-identical. Dev-only by construction: only `bynk dev` sets it.
54    pub trace_requests: bool,
55    /// #3581 (the dev agent-inspection track): emit the dev-only agent registry,
56    /// the `/_bynk/inspect` routes and the instance recording into a Workers
57    /// build, for `bynk dev`. `false` for every other build, so a deploy build's
58    /// output is byte-identical. Dev-only by construction: only `bynk dev` sets it.
59    pub inspect_agents: bool,
60    /// #1821 (ADR 0147 D3): whether `suite`s are type-checked and emitted (the
61    /// `tests/` modules and `tests/main.ts`). On by default; `bynk compile`
62    /// and the driver's dev/deploy build turn it off, so a suite never reaches
63    /// the deployable. `bynk test` leaves it on. Off strips suites after
64    /// parsing: a file that does not parse still fails the build, since it
65    /// cannot be told apart from production source.
66    pub tests: bool,
67    /// #57 (testing track): when `Some`, every file `roots` would otherwise
68    /// discover on disk is instead read from here — keyed the same way
69    /// `discovery::read_source`'s overlay is (a canonicalised absolute path,
70    /// falling back to the literal path when the file has no on-disk
71    /// counterpart to canonicalise). Filesystem discovery is skipped entirely;
72    /// `roots` still supplies `src_root`/`tests_root` and their prefixes, so a
73    /// `Roots::Split` project can drive both trees in-memory.
74    ///
75    /// #1077/#1081: `bynk-driver`'s `project_options`/`try_project_options`
76    /// *do* set this now — the real CLI entry points walk and read every
77    /// project file themselves and hand the result here, so `bynk-emit`
78    /// itself no longer discovers or reads anything on disk for the CLI
79    /// path. `bynk`/the LSP still don't: `bynk` routes through
80    /// `bynk-driver`, and the LSP (`bynk_check::analysis::analyse_project`
81    /// since P4.2) never goes through `CompileOptions` at all — it has its
82    /// own, separate discovery path (#1079). `bynk-emit`'s own tests also
83    /// set this, to exercise the full
84    /// project pipeline (cross-context `uses`, multi-file layouts,
85    /// workers-mode emission, …) without an on-disk fixture tree.
86    pub sources: Option<HashMap<PathBuf, String>>,
87    /// Events track, slice 3c (#980): reconcile against `bynk.schema.lock`.
88    /// **Off by default** — `bynk compile`'s directory branch and `bynk`'s
89    /// deploy/dev build turn it on and write the reconciled lock back;
90    /// `check`'s and `test`'s directory paths (#2078) turn it on read-only,
91    /// so a non-additive change fails them too, and never write it. Every
92    /// library/test caller (in-memory builds, `bynk-tests/tests/e2e.rs`'s
93    /// in-place fixture compiles, `bynk-emit`'s own `sources`-driven tests,
94    /// the LSP) leaves it off, so a compile never mutates a project tree it
95    /// wasn't asked to.
96    ///
97    /// #1078: this carries the lock's pre-read content, not just an on/off
98    /// switch — `bynk-emit` reads and writes no disk for this file (the same
99    /// move #1077/#1081 already made for `.bynk` source content). See
100    /// [`SchemaLock`]'s own doc for the read side; the reconciled content
101    /// comes back out on [`ProjectOutput::schema_lock`](bynk_emit::emit_model::ProjectOutput::schema_lock) for the caller to
102    /// persist.
103    pub schema_registry: SchemaLock,
104    /// #2554: `bynk.contracts.lock`'s pre-read content: the older contracts
105    /// each callee also accepts. `None` (every library, test and LSP caller,
106    /// and a project without the file) accepts none, so a callee answers only
107    /// the contract it has. `bynk-driver`'s `try_project_options` reads it, as
108    /// it reads the manifest, so every CLI build honours it; a build only ever
109    /// reads it, and the driver writes it.
110    pub contracts_lock: Option<String>,
111    /// #1890: the project's extra Cloudflare compatibility flags, from
112    /// `bynk.toml`'s `[workers] compatibility_flags`, in manifest order.
113    /// A Workers build writes them into every `wrangler.toml` after
114    /// [`bynk_emit::DEFAULT_COMPATIBILITY_FLAGS`]; a duplicate is dropped with a
115    /// `bynk.project.duplicate_compatibility_flag` warning. Empty by default:
116    /// `bynk-driver`'s `project_options`/`try_project_options` read the
117    /// manifest and set it, as does `bynk-tests/tests/e2e.rs` for a fixture.
118    pub compatibility_flags: Vec<String>,
119    /// `bynk.toml`'s `[workers] workers_dev`: written into every
120    /// `wrangler.toml` when set, left out when `None`.
121    pub workers_dev: Option<bool>,
122    /// #1883, slice 1b: the project's `assets/` folder — its files, keyed by
123    /// normalised project-relative path (`assets/board.css`), listed by the
124    /// caller, and a reader for their bytes
125    /// ([`assets::AssetFolder`], usually `AssetFolder::on_disk`). The build
126    /// reads only the files an `asset` declaration names, once each, through
127    /// that reader, so `bynk-emit` never touches the disk and a large file
128    /// nothing declares is never read. `bynk-driver`'s
129    /// `project_options`/`try_project_options` and `bynk-testkit`'s
130    /// `compile_options_*` set it.
131    ///
132    /// `None` means no filesystem was consulted (`compile_in_memory`, the
133    /// playground). A check then skips the existence check; a build treats it
134    /// as an empty folder, so an asset there is `bynk.asset.missing_file`
135    /// rather than a URL made up for a file nobody read.
136    pub asset_files: Option<assets::AssetFolder>,
137    /// #2387, slice 2: the project's `embeds/` folder, listed by the caller
138    /// with a reader for the bytes of only the files an `embed` declaration
139    /// names ([`assets::AssetFolder::embeds_on_disk`]), exactly as
140    /// [`CompileOptions::asset_files`] does for `assets/`. `None` means no
141    /// filesystem was consulted: a check then skips the existence check, and a
142    /// build treats it as an empty folder, so an embed there is
143    /// `bynk.embed.missing_file` rather than text made up for a file nobody
144    /// read.
145    pub embed_files: Option<assets::EmbedFolder>,
146    /// #2841: the project's `fixtures/` folder, listed by the caller with a
147    /// reader for the bytes of only the files a suite's `fixture` declaration
148    /// names ([`assets::AssetFolder::fixtures_on_disk`]), exactly as
149    /// [`CompileOptions::embed_files`] does for `embeds/`. Fixtures are test
150    /// input: nothing in a deployable reads them. `None` means no filesystem
151    /// was consulted.
152    pub fixture_files: Option<assets::FixtureFolder>,
153    /// P4b (#2608): the project's `migrations/` folder, listed by the caller
154    /// ([`assets::AssetFolder::migrations_on_disk`]). Every file in a declared
155    /// `D1` database's directory is read, checked, copied beside the Worker's
156    /// `wrangler.toml` and run on each test database. `None` means no
157    /// filesystem was consulted.
158    pub migration_files: Option<assets::AssetFolder>,
159    /// #2842: the project's `snapshots/` folder, read by the caller
160    /// ([`bynk_project::snapshots::read_snapshot_files`]): each file's text by its
161    /// project-relative path. A test module inlines the file for its own suite
162    /// file, so the harness reads nothing at test time. `None` (and an empty map)
163    /// means no snapshot is recorded, so every `matches snapshot` claim is missing.
164    pub snapshot_files: Option<BTreeMap<String, String>>,
165    /// #3100: where [`compile_project`](super::compile_project) reports each context as it compiles.
166    /// `None` (the default, and every library, test and LSP caller) reports
167    /// nothing, so a build behaves exactly as it did before.
168    pub progress: Option<ProgressSink>,
169    /// #2138 (end-to-end testing track §3.5, §3.7): `Some` when `bynk test
170    /// --against` runs the `system` suites against a real runtime. The build
171    /// then emits only the `system` suites, routes their drivers to the
172    /// target's URLs (`BYNK_TEST_TARGETS`) instead of the in-process harness,
173    /// and refuses (or, under `--skip-unsupported`, skips) a case that uses
174    /// what a remote run can't honour. `None` for every other build.
175    pub remote_tests: Option<RemoteTests>,
176}
177
178impl CompileOptions {
179    /// Single-root project (`src == tests`), bundle target, default platform.
180    pub fn single(root: impl Into<PathBuf>) -> Self {
181        Self {
182            out_dir: None,
183            target: BuildTarget::Bundle,
184            platform: Platform::default(),
185            roots: Roots::Single(root.into()),
186            import_ext: ImportExt::default(),
187            contracts: false,
188            trace_requests: false,
189            inspect_agents: false,
190            tests: true,
191            sources: None,
192            schema_registry: SchemaLock::Off,
193            contracts_lock: None,
194            compatibility_flags: Vec::new(),
195            workers_dev: None,
196            asset_files: None,
197            embed_files: None,
198            fixture_files: None,
199            migration_files: None,
200            snapshot_files: None,
201            progress: None,
202            remote_tests: None,
203        }
204    }
205
206    /// v0.9.1 split layout (source and test units in separate subdirectories
207    /// under `project_root`), bundle target, default platform. Use this from
208    /// `bynk test` so its rooting matches `bynk compile`'s.
209    pub fn split(project_root: impl Into<PathBuf>, paths: ProjectPaths) -> Self {
210        Self {
211            out_dir: None,
212            target: BuildTarget::Bundle,
213            platform: Platform::default(),
214            roots: Roots::Split {
215                project_root: project_root.into(),
216                paths,
217            },
218            import_ext: ImportExt::default(),
219            contracts: false,
220            trace_requests: false,
221            inspect_agents: false,
222            tests: true,
223            sources: None,
224            schema_registry: SchemaLock::Off,
225            contracts_lock: None,
226            compatibility_flags: Vec::new(),
227            workers_dev: None,
228            asset_files: None,
229            embed_files: None,
230            fixture_files: None,
231            migration_files: None,
232            snapshot_files: None,
233            progress: None,
234            remote_tests: None,
235        }
236    }
237
238    /// #3477: the directory the build is written to ([`CompileOptions::out_dir`]).
239    pub fn out_dir(mut self, out: Option<PathBuf>) -> Self {
240        self.out_dir = out;
241        self
242    }
243
244    /// #3100: report each context as it compiles ([`CompileOptions::progress`]).
245    pub fn progress(mut self, sink: Option<ProgressSink>) -> Self {
246        self.progress = sink;
247        self
248    }
249
250    /// #2138: a remote test build ([`CompileOptions::remote_tests`]).
251    pub fn remote_tests(mut self, remote: Option<RemoteTests>) -> Self {
252        self.remote_tests = remote;
253        self
254    }
255
256    /// Select the build target. `Bundle` (default) is the v0.6+ single-bundle
257    /// layout; `Workers` (v0.8) emits per-context Cloudflare Workers.
258    pub fn target(mut self, target: BuildTarget) -> Self {
259        self.target = target;
260        self
261    }
262
263    /// Slice 2: select the import-specifier extension. `Ts` is the debug build
264    /// for `bynk test --inspect` (run the `.ts` directly under Node strip-only).
265    pub fn import_ext(mut self, ext: ImportExt) -> Self {
266        self.import_ext = ext;
267        self
268    }
269
270    /// v0.115: enable the function-contract call-site guard (dev/test profile).
271    /// `bynk test` and `--inspect` call this; the deploy build leaves it off so
272    /// contract checks never reach production (DECISION J).
273    pub fn contracts(mut self, on: bool) -> Self {
274        self.contracts = on;
275        self
276    }
277
278    /// #3580: record per-request traces in a Workers build (`bynk dev
279    /// --trace-events`). Off by default, and never set by `bynk compile` or
280    /// `bynk deploy`.
281    pub fn trace_requests(mut self, on: bool) -> Self {
282        self.trace_requests = on;
283        self
284    }
285
286    /// #3581: emit the dev-only agent inspection into a Workers build (`bynk
287    /// dev`). Off by default, and never set by `bynk compile` or `bynk deploy`.
288    pub fn inspect_agents(mut self, on: bool) -> Self {
289        self.inspect_agents = on;
290        self
291    }
292
293    /// #1821 (ADR 0147 D3): whether to type-check and emit `suite`s. A build
294    /// that produces a deployable (`bynk compile`, `bynk dev`/`deploy`) turns
295    /// it off; a suite is test-only.
296    pub fn tests(mut self, on: bool) -> Self {
297        self.tests = on;
298        self
299    }
300
301    /// v0.17: select the deploy [`Platform`] (selects the `bynk` surface
302    /// binding). The MVP ships `cloudflare` only.
303    pub fn platform(mut self, platform: Platform) -> Self {
304        self.platform = platform;
305        self
306    }
307
308    /// #57 (testing track): supply every file in-memory instead of walking
309    /// `roots` on disk — keyed the same way `discovery::read_source`'s
310    /// overlay is (see the `sources` field's own doc).
311    pub fn sources(mut self, sources: HashMap<PathBuf, String>) -> Self {
312        self.sources = Some(sources);
313        self
314    }
315
316    /// Events track, slice 3c (#980): turn on `bynk.schema.lock`
317    /// reconciliation for this build, with its pre-read content (or
318    /// verified-absent `None`, for a fresh project). See [`SchemaLock`] and
319    /// the field's own doc for who calls this and why everyone else leaves
320    /// it off.
321    pub fn schema_registry(mut self, mode: SchemaLock) -> Self {
322        self.schema_registry = mode;
323        self
324    }
325
326    /// #2554: the contracts lock's pre-read content. See the field's own doc.
327    pub fn contracts_lock(mut self, content: Option<String>) -> Self {
328        self.contracts_lock = content;
329        self
330    }
331
332    /// #1890: the project's extra Cloudflare compatibility flags, from
333    /// `bynk.toml`'s `[workers]` table. See the field's own doc.
334    pub fn compatibility_flags(mut self, flags: Vec<String>) -> Self {
335        self.compatibility_flags = flags;
336        self
337    }
338
339    /// The project's `[workers] workers_dev`. See the field's own doc.
340    pub fn workers_dev(mut self, workers_dev: Option<bool>) -> Self {
341        self.workers_dev = workers_dev;
342        self
343    }
344
345    /// #1883, slice 1b: the listed `assets/` folder. See the field's own doc.
346    pub fn asset_files(mut self, folder: assets::AssetFolder) -> Self {
347        self.asset_files = Some(folder);
348        self
349    }
350
351    /// #2387, slice 2: the listed `embeds/` folder. See the field's own doc.
352    pub fn embed_files(mut self, folder: assets::EmbedFolder) -> Self {
353        self.embed_files = Some(folder);
354        self
355    }
356
357    /// #2841: the listed `fixtures/` folder. See the field's own doc.
358    pub fn fixture_files(mut self, folder: assets::FixtureFolder) -> Self {
359        self.fixture_files = Some(folder);
360        self
361    }
362
363    /// #2842: the project's `snapshots/` files. See the field's own doc.
364    pub fn snapshot_files(mut self, files: BTreeMap<String, String>) -> Self {
365        self.snapshot_files = Some(files);
366        self
367    }
368
369    /// P4b (#2608): the listed `migrations/` folder. See the field's own doc.
370    pub fn migration_files(mut self, folder: assets::AssetFolder) -> Self {
371        self.migration_files = Some(folder);
372        self
373    }
374}