Skip to main content

bynk_emit/emitter/
toml_doc.rs

1//! P7.3 (#1303): a minimal typed TOML tree and printer — the one piece of
2//! R7.8 (`Artefacts` is a keyed set of typed documents, never a `String` at
3//! construction) landable ahead of `bynk-ts` (Arc B, P7.5+), since
4//! `wrangler.toml` is the one document `bynk-emit` produces that isn't
5//! TypeScript. Not a general TOML library: `TomlValue` represents exactly
6//! what `emitter::wrangler::emit_wrangler_toml` needs to build a
7//! `wrangler.toml` today, no more.
8//!
9//! [`print_toml_document`] is the *only* function in this crate that writes
10//! TOML syntax — `emit_wrangler_toml` builds a [`TomlDocument`], this module
11//! renders it. That split is what makes string-escaping a printer guarantee
12//! (every `TomlValue::Str` is escaped unconditionally, §"Decision B" of
13//! #1303) rather than a per-call-site judgement call, which is what left
14//! `wrangler.rs`'s own `name`/`binding`/`class_name` values unescaped before
15//! this — safe today only because those particular values happen to be
16//! compiler-derived identifiers that can't contain a TOML-breaking
17//! character, not because anything enforced it structurally.
18
19use std::fmt::Write as _;
20
21use bynk_project::wrangler_keys::WranglerKey;
22
23/// A TOML document: the root block's entries (review of #1304, finding 3 —
24/// a field set once at construction, not a `TomlBlock` a caller could
25/// accidentally `push_block` out of first position, which `push_block`
26/// itself couldn't have rejected: TOML has no marker distinguishing "the
27/// root block" from "a table block with no header" once both are just
28/// entries in the same list) followed by any number of headed blocks. Every
29/// block, printed — root included — is followed by exactly one blank line
30/// (including the last — confirmed against every current
31/// `expected/**/wrangler.toml` golden fixture, which all end in a trailing
32/// blank line).
33pub struct TomlDocument {
34    header_comment: &'static str,
35    root: Vec<TomlEntry>,
36    blocks: Vec<TomlBlock>,
37}
38
39impl TomlDocument {
40    /// `header_comment` is the leading `# …` line's text *without* the `#`
41    /// marker — [`print_toml_document`] prepends it, the same convention
42    /// [`TomlEntry::with_comment`] already used (review of #1304, finding
43    /// 2: the two used to disagree, one taking a marker-inclusive literal
44    /// and the other marker-exclusive, with nothing enforcing either).
45    pub(crate) fn new(header_comment: &'static str, root: Vec<TomlEntry>) -> Self {
46        Self {
47            header_comment,
48            root,
49            blocks: Vec::new(),
50        }
51    }
52
53    pub fn push_block(&mut self, block: TomlBlock) {
54        self.blocks.push(block);
55    }
56
57    /// Set the root `main` entry's value in place — the structural,
58    /// tree-level equivalent of the old text-based `toml_edit` patch this
59    /// replaces (P7.6, #1309, Decision E): a caller that already holds the
60    /// real tree (`bynk-strip::strip_project_to_js`) uses this instead of
61    /// printing then re-parsing just to change one field.
62    ///
63    /// Returns `false`, changing nothing, if the document has no root
64    /// `main` entry — the caller's job to treat that as an error (P7.4,
65    /// #1305's own guardrail against a silently-unpatched JS artefact whose
66    /// manifest still names the stripped `.ts` entry: this method reports
67    /// the miss, it doesn't decide it's fine).
68    #[must_use]
69    pub fn set_main(&mut self, value: impl Into<String>) -> bool {
70        for entry in &mut self.root {
71            if entry.key == WranglerKey::Main.header() {
72                entry.value = TomlValue::Str(value.into());
73                return true;
74            }
75        }
76        false
77    }
78}
79
80/// One `[path]` or `[[path]]` section plus its `key = value` entries, in
81/// order. Always headed — the document's own root block is
82/// [`TomlDocument`]'s own field, not constructible as a `TomlBlock` (review
83/// of #1304, finding 3).
84pub struct TomlBlock {
85    header: TomlHeader,
86    entries: Vec<TomlEntry>,
87}
88
89enum TomlHeader {
90    Table(&'static str),
91    ArrayTable(&'static str),
92    /// #1796: `[parent.key]`, where `key` is chosen at emit time rather than
93    /// fixed by the generator (a Durable Object class name under `exports`).
94    /// The printer renders `key` bare when it is a TOML bare key and as an
95    /// escaped basic string otherwise, so a key, like a value, can't break
96    /// out of its header whatever it contains.
97    KeyedTable(&'static str, String),
98}
99
100impl TomlBlock {
101    pub(crate) fn table(path: WranglerKey, entries: Vec<TomlEntry>) -> Self {
102        Self {
103            header: TomlHeader::Table(path.header()),
104            entries,
105        }
106    }
107
108    pub(crate) fn array_table(path: WranglerKey, entries: Vec<TomlEntry>) -> Self {
109        Self {
110            header: TomlHeader::ArrayTable(path.header()),
111            entries,
112        }
113    }
114
115    /// `[parent.key]` — one entry of a table keyed by a runtime name, such as
116    /// `[exports.Alpha]` (#1796).
117    pub(crate) fn keyed_table(
118        parent: WranglerKey,
119        key: impl Into<String>,
120        entries: Vec<TomlEntry>,
121    ) -> Self {
122        Self {
123            header: TomlHeader::KeyedTable(parent.header(), key.into()),
124            entries,
125        }
126    }
127}
128
129/// One `key = value` line, with an optional trailing `# comment` — TOML's
130/// own comment syntax, not an escape hatch; `wrangler.toml`'s one instance
131/// today is the KV namespace id's `# set at deploy time`.
132pub(crate) struct TomlEntry {
133    key: std::borrow::Cow<'static, str>,
134    value: TomlValue,
135    comment: Option<&'static str>,
136}
137
138impl TomlEntry {
139    pub(crate) fn kv(key: &'static str, value: TomlValue) -> Self {
140        Self {
141            key: key.into(),
142            value,
143            comment: None,
144        }
145    }
146
147    /// An entry whose key is chosen at emit time (#3513 B: `[vars]` names one variable per
148    /// `Analytics` binding). The printer quotes it unless TOML allows it bare.
149    pub(crate) fn kv_owned(key: String, value: TomlValue) -> Self {
150        Self {
151            key: key.into(),
152            value,
153            comment: None,
154        }
155    }
156
157    pub(crate) fn with_comment(key: &'static str, value: TomlValue, comment: &'static str) -> Self {
158        Self {
159            key: key.into(),
160            value,
161            comment: Some(comment),
162        }
163    }
164}
165
166/// Exactly the value shapes `wrangler.toml` generation writes today — a
167/// basic string (always escaped on render, unconditionally), a bare
168/// integer, a bool, an array (rendered as `[a, b, …]`, TOML's inline-array
169/// form), and an inline table (`{ k = v, … }`, standard-library P3's
170/// `simple = { limit = 100, period = 60 }`). No float and no nesting beyond
171/// one section level: none of those appear in the current output, and
172/// widening this when a real future value needs it is cheap.
173pub(crate) enum TomlValue {
174    Str(String),
175    Int(i64),
176    /// #1883, slice 1b: `[assets] run_worker_first = false`.
177    Bool(bool),
178    Array(Vec<TomlValue>),
179    /// P3 (#2342): an inline table, its keys bare, in the order given.
180    InlineTable(Vec<(&'static str, TomlValue)>),
181}
182
183impl TomlValue {
184    pub(crate) fn str(s: impl Into<String>) -> Self {
185        Self::Str(s.into())
186    }
187}
188
189/// Render `doc` to TOML text. The one function in this module — and, per
190/// this file's own module doc, in `bynk-emit`'s TOML-producing surface —
191/// that calls `write!`/`writeln!`/`format!` to build TOML syntax.
192pub fn print_toml_document(doc: &TomlDocument) -> String {
193    let mut out = String::new();
194    let _ = writeln!(out, "# {}", doc.header_comment);
195    print_entries(&mut out, &doc.root);
196    let _ = writeln!(out);
197    for block in &doc.blocks {
198        match &block.header {
199            TomlHeader::Table(path) => {
200                let _ = writeln!(out, "[{path}]");
201            }
202            TomlHeader::ArrayTable(path) => {
203                let _ = writeln!(out, "[[{path}]]");
204            }
205            TomlHeader::KeyedTable(parent, key) => {
206                let _ = writeln!(out, "[{parent}.{}]", render_key(key));
207            }
208        }
209        print_entries(&mut out, &block.entries);
210        let _ = writeln!(out);
211    }
212    out
213}
214
215fn print_entries(out: &mut String, entries: &[TomlEntry]) {
216    for entry in entries {
217        let value = render_value(&entry.value);
218        match entry.comment {
219            Some(comment) => {
220                let _ = writeln!(out, "{} = {value} # {comment}", render_key(&entry.key));
221            }
222            None => {
223                let _ = writeln!(out, "{} = {value}", render_key(&entry.key));
224            }
225        }
226    }
227}
228
229/// A key segment, bare when TOML allows it (`A-Za-z0-9_-`, non-empty) and a
230/// quoted basic string otherwise — the same escaping [`render_value`] gives
231/// every string value.
232fn render_key(key: &str) -> String {
233    let bare = !key.is_empty()
234        && key
235            .chars()
236            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
237    if bare {
238        key.to_string()
239    } else {
240        format!("\"{}\"", escape_toml_basic_string(key))
241    }
242}
243
244fn render_value(value: &TomlValue) -> String {
245    match value {
246        TomlValue::Str(s) => format!("\"{}\"", escape_toml_basic_string(s)),
247        TomlValue::Int(n) => n.to_string(),
248        TomlValue::Bool(b) => b.to_string(),
249        TomlValue::Array(items) => {
250            let rendered: Vec<String> = items.iter().map(render_value).collect();
251            format!("[{}]", rendered.join(", "))
252        }
253        TomlValue::InlineTable(entries) => {
254            let rendered: Vec<String> = entries
255                .iter()
256                .map(|(k, v)| format!("{} = {}", render_key(k), render_value(v)))
257                .collect();
258            format!("{{ {} }}", rendered.join(", "))
259        }
260    }
261}
262
263/// Escape a source string literal for interpolation into a TOML *basic*
264/// string (the `"…"` form). Queue names and cron expressions come from user
265/// string literals, which can decode to contain `"`, `\`, newline and tab
266/// (`bynk-syntax/src/lexer.rs`) — all of which would otherwise break out of
267/// the TOML string and inject config keys. Every character we escape maps
268/// to a valid TOML compact escape; remaining control characters fall back
269/// to the `\uXXXX` form so the output is always a well-formed basic string.
270///
271/// Applied unconditionally by [`render_value`] to every [`TomlValue::Str`] —
272/// not just the values a caller happens to know are user-supplied. Relocated
273/// here from `emitter/wrangler.rs` (P7.3, #1303): escaping is the printer's
274/// job now, applied structurally to every string this module renders, not a
275/// per-call-site judgement about which particular value might need it.
276fn escape_toml_basic_string(s: &str) -> String {
277    let mut out = String::with_capacity(s.len());
278    for c in s.chars() {
279        match c {
280            '\\' => out.push_str("\\\\"),
281            '"' => out.push_str("\\\""),
282            '\n' => out.push_str("\\n"),
283            '\t' => out.push_str("\\t"),
284            '\r' => out.push_str("\\r"),
285            // Control characters have no compact TOML escape besides the ones
286            // above and must not appear raw in a basic string.
287            c if (c as u32) < 0x20 || c == '\u{7f}' => {
288                let _ = write!(out, "\\u{:04X}", c as u32);
289            }
290            c => out.push(c),
291        }
292    }
293    out
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    #[test]
301    fn escape_toml_basic_string_neutralises_injection() {
302        // The trigger from the defect report: a queue name whose decoded value
303        // carries a quote + newline would otherwise close the string and inject
304        // a config key.
305        assert_eq!(
306            escape_toml_basic_string("q\nkey = \"injected"),
307            "q\\nkey = \\\"injected"
308        );
309        assert_eq!(escape_toml_basic_string("a\\b"), "a\\\\b");
310        assert_eq!(escape_toml_basic_string("a\tb"), "a\\tb");
311    }
312
313    #[test]
314    fn set_main_changes_only_the_main_entry() {
315        let mut doc = TomlDocument::new(
316            "Generated by bynk — do not edit by hand.",
317            vec![
318                TomlEntry::kv("name", TomlValue::str("api")),
319                TomlEntry::kv("main", TomlValue::str("index.ts")),
320            ],
321        );
322        doc.push_block(TomlBlock::table(
323            WranglerKey::Triggers,
324            vec![TomlEntry::kv(
325                "crons",
326                TomlValue::Array(vec![TomlValue::str("*/5 * * * *")]),
327            )],
328        ));
329
330        assert!(doc.set_main("index.js"));
331
332        let text = print_toml_document(&doc);
333        let parsed: toml::Table = text.parse().expect("valid TOML");
334        assert_eq!(parsed["main"].as_str(), Some("index.js"));
335        assert_eq!(parsed["name"].as_str(), Some("api"));
336        let crons = parsed["triggers"]["crons"].as_array().expect("crons");
337        assert_eq!(crons[0].as_str(), Some("*/5 * * * *"));
338    }
339
340    #[test]
341    fn set_main_reports_a_missing_root_main_entry_rather_than_swallowing_it() {
342        let mut doc = TomlDocument::new(
343            "Generated by bynk — do not edit by hand.",
344            vec![TomlEntry::kv("name", TomlValue::str("api"))],
345        );
346        assert!(!doc.set_main("index.js"));
347        let parsed: toml::Table = print_toml_document(&doc).parse().expect("valid TOML");
348        assert!(parsed.get("main").is_none());
349    }
350
351    #[test]
352    fn escape_toml_basic_string_passes_plain_values_through() {
353        // Ordinary cron expressions and queue names are untouched.
354        assert_eq!(escape_toml_basic_string("*/5 * * * *"), "*/5 * * * *");
355        assert_eq!(escape_toml_basic_string("order-events"), "order-events");
356    }
357
358    #[test]
359    fn escape_toml_basic_string_escapes_other_control_chars() {
360        // A NUL has no compact escape and must not appear raw in a basic string.
361        assert_eq!(escape_toml_basic_string("a\u{0}b"), "a\\u0000b");
362        assert_eq!(escape_toml_basic_string("a\u{7f}b"), "a\\u007Fb");
363    }
364
365    #[test]
366    fn escaped_value_is_valid_toml_and_round_trips() {
367        // The security invariant, enforced by a real TOML parser (not a golden
368        // byte-compare): interpolating the escaped value produces a well-formed
369        // single-key table whose decoded value is *exactly* the input — no
370        // injected keys, no broken string. Covers the injection payload from the
371        // defect report plus a control char that takes the `\uXXXX` fallback.
372        for input in ["q\nkey = \"injected", "*/5 * * * *\\\"", "a\u{0}b\ttail"] {
373            let doc = format!("queue = \"{}\"", escape_toml_basic_string(input));
374            let table: toml::Table = doc
375                .parse()
376                .unwrap_or_else(|e| panic!("escaped {input:?} is invalid TOML: {e} ({doc:?})"));
377            assert_eq!(
378                table.len(),
379                1,
380                "escaped {input:?} injected extra keys: {table:?}"
381            );
382            assert_eq!(
383                table["queue"].as_str(),
384                Some(input),
385                "escaped {input:?} did not round-trip"
386            );
387        }
388    }
389
390    #[test]
391    fn print_toml_document_renders_a_representative_document_and_round_trips() {
392        // Not a golden byte-compare (that's `bless_positive_fixtures`'s job) —
393        // this proves the printer's *general* shape (root block, a `[[…]]`
394        // array table, a `[…]` table, an array value, a commented entry) is
395        // well-formed TOML a real parser accepts, with every value surviving
396        // exactly. `TomlBlock`/`TomlEntry` construction mirrors
397        // `emit_wrangler_toml`'s own shape one-for-one.
398        //
399        // Review of #1304, finding 1: the `name` and the one `crons` element
400        // below are the injection payload from the defect report, not an
401        // ordinary identifier — every value the *golden* corpus carries today
402        // is compiler-derived and never needs escaping, which means a
403        // zero-diff `bless_positive_fixtures` run cannot tell an escaping
404        // `render_value` from a `render_value` that stopped escaping
405        // entirely. This is the one test standing between "the printer
406        // escapes every string" (this module's whole point) and that claim
407        // quietly going false — it has to drive a hostile value *through*
408        // `print_toml_document`, not just through `escape_toml_basic_string`
409        // directly (the tests above) or a hand-built fragment (the test
410        // below).
411        let hostile = "q\nkey = \"injected";
412        let mut doc = TomlDocument::new(
413            "Generated by bynk — do not edit by hand.",
414            vec![
415                TomlEntry::kv("name", TomlValue::str(hostile)),
416                TomlEntry::kv("main", TomlValue::str("index.ts")),
417            ],
418        );
419        doc.push_block(TomlBlock::array_table(
420            WranglerKey::Services,
421            vec![
422                TomlEntry::kv("binding", TomlValue::str("COMMERCE_PAYMENT")),
423                TomlEntry::kv("service", TomlValue::str("commerce-payment")),
424            ],
425        ));
426        doc.push_block(TomlBlock::array_table(
427            WranglerKey::KvNamespaces,
428            vec![
429                TomlEntry::kv("binding", TomlValue::str("BYNK_KV")),
430                TomlEntry::with_comment(
431                    "id",
432                    TomlValue::str("<KV_NAMESPACE_ID>"),
433                    "set at deploy time",
434                ),
435            ],
436        ));
437        doc.push_block(TomlBlock::table(
438            WranglerKey::Triggers,
439            vec![TomlEntry::kv(
440                "crons",
441                TomlValue::Array(vec![TomlValue::str("*/5 * * * *"), TomlValue::str(hostile)]),
442            )],
443        ));
444
445        let text = print_toml_document(&doc);
446        let parsed: toml::Table = text
447            .parse()
448            .unwrap_or_else(|e| panic!("printer produced invalid TOML: {e}\n{text}"));
449
450        assert_eq!(
451            parsed.len(),
452            5,
453            "the hostile `name` value injected extra root keys: {parsed:?}"
454        );
455        assert_eq!(parsed["name"].as_str(), Some(hostile));
456        assert_eq!(parsed["main"].as_str(), Some("index.ts"));
457        let services = parsed["services"].as_array().expect("services array");
458        assert_eq!(services.len(), 1);
459        assert_eq!(services[0]["binding"].as_str(), Some("COMMERCE_PAYMENT"));
460        let kv = parsed["kv_namespaces"].as_array().expect("kv array");
461        assert_eq!(kv[0]["id"].as_str(), Some("<KV_NAMESPACE_ID>"));
462        let crons = parsed["triggers"]["crons"].as_array().expect("crons array");
463        assert_eq!(crons.len(), 2, "the hostile crons element broke the array");
464        assert_eq!(crons[0].as_str(), Some("*/5 * * * *"));
465        assert_eq!(crons[1].as_str(), Some(hostile));
466
467        // Every block, including the last, is followed by exactly one blank
468        // line — the shape every current golden `wrangler.toml` fixture has.
469        assert!(text.ends_with("\n\n"));
470    }
471
472    #[test]
473    fn keyed_table_keys_are_bare_when_they_can_be_and_quoted_otherwise() {
474        // #1796: `[exports.<Class>]`. A Bynk class name is always a bare key
475        // (`__EventsFanout` included), but the printer, not the caller, owns
476        // that guarantee, so a hostile key must stay inside its header too.
477        let hostile = "a.b]\nx = \"y";
478        let mut doc = TomlDocument::new("t", vec![]);
479        for key in ["Alpha", "__EventsFanout", hostile] {
480            doc.push_block(TomlBlock::keyed_table(
481                WranglerKey::Exports,
482                key,
483                vec![TomlEntry::kv("type", TomlValue::str("durable-object"))],
484            ));
485        }
486        let text = print_toml_document(&doc);
487        assert!(text.contains("[exports.Alpha]\n"), "{text}");
488        assert!(text.contains("[exports.__EventsFanout]\n"), "{text}");
489
490        let parsed: toml::Table = text
491            .parse()
492            .unwrap_or_else(|e| panic!("printer produced invalid TOML: {e}\n{text}"));
493        assert_eq!(parsed.len(), 1, "a key escaped its header: {parsed:?}");
494        let exports = parsed["exports"].as_table().expect("exports table");
495        assert_eq!(exports.len(), 3);
496        assert_eq!(exports[hostile]["type"].as_str(), Some("durable-object"));
497    }
498}