reylo-engine-core 0.8.2

What every database's analysis engine shares: the request protocol and its host, the placeholder lexer, the project file, the type model and its JSON Schema, structured parameters, and the WebAssembly ABI each database's artifact exports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! The project file, `.reylo.yaml`: the settings the content mapper reads, parsed once here so
//! every host reads the same YAML the same way. A host that serves the project's queries itself
//! reads the file too: the top-level `env`, `url`, its connection, which the importer never reads,
//! and its own settings, the `api` section, which it parses itself.
//!
//! A host finds the file (beside the project's `package.json`), reads it and hands the text over;
//! what the file names outside itself (the environment, `.env` files, the database) is the host's
//! to resolve, and a `${VAR}` in a URL stays as written. There is no dialect key: the URL's scheme
//! names the dialect. A key the library does not know is an error, so a typo does not pass for a
//! default; the `api` and `rest` sections, which the importer does not read, are accepted as they
//! are, and a top-level `$schema` (the JSON Schema an editor validates the file
//! against, which `reylo schema --config` prints) is ignored.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Project {
    /// The published schema an editor validates the file against; no host reads it.
    #[serde(rename = "$schema", default, skip_serializing)]
    pub schema: Option<serde_yaml::Value>,
    /// The connection a host that serves the queries runs them through, usually `${DATABASE_URL}`.
    /// Parsed for that host: the importer's type check never connects through it, and tells a file
    /// that sets it without `direct_url` so.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// The dev database the importer's type check reads, `${DATABASE_URL}` when absent: a
    /// connection that bypasses a pooler, since describing a statement through a transaction
    /// pooler can fail. The importer's alone: a host that serves the queries runs them through `url`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub direct_url: Option<String>,
    /// A server to make the migrations' shadow databases on, where the database's own refuses
    /// `create database`; the database's own server when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shadow_url: Option<String>,
    /// The `.env` files the importer and every other host read, relative to the project file
    /// (`.env.local`, then `.env`, when absent); the first that sets a variable wins, and the
    /// process environment wins over all of them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<Vec<String>>,
    /// Whether a parameter the statement does not type is `unknown` (`true`) rather than an error.
    /// The key was `strict` until 2026-10-20 and `strict_params`, the other way round, until 0.8.0.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allow_untyped_params: Option<bool>,
    /// Whether a Postgres array column may hold nested arrays (`true`): typed at any depth, and
    /// nothing refused. Off, it is typed with one dimension, and a value of more is refused.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allow_nested_arrays: Option<bool>,
    /// Whether each statement the importer builds ends with a sqlcommenter comment naming its
    /// `.sql` file (`/*file='queries%2Fget_user.sql'*/`), which a database's monitoring reads as
    /// the statement's tags. On when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sqlcommenter: Option<bool>,
    /// The directory of the project's own files, beside the project file (`reylo` when absent):
    /// `schema.sql`, the migrations in `migrations/`, the lock `reylo.lock`, and the cache in
    /// `.cache/`, which the type check and the migrations keep there, out of git.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dir: Option<String>,
    /// How the importer represents values in JavaScript and TypeScript.
    #[serde(default, skip_serializing_if = "Js::is_empty")]
    pub js: Js,
    #[serde(default, skip_serializing)]
    pub rest: Option<serde_yaml::Value>,
    /// The settings of a host that serves the queries, which that host parses.
    #[serde(default, skip_serializing)]
    pub api: Option<serde_yaml::Value>,
}

/// The importer's JavaScript settings.
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Js {
    #[serde(default, skip_serializing_if = "Codecs::is_empty")]
    pub codecs: Codecs,
}

impl Js {
    fn is_empty(&self) -> bool {
        self.codecs.is_empty()
    }
}

/// Each family of values and the TypeScript type `.run()` returns its values as, and takes its
/// parameters as. A family is a kind of the type descriptor format (spec/index.ts), and a family
/// left out keeps its default, the first value of its type here; every other value is exact, or
/// refuses a value it cannot hold. A 64-bit integer has none: a bigint is its one exact type.
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Codecs {
    /// An exact decimal: Postgres's `numeric` and MySQL's `DECIMAL`. A `number` refuses
    /// a value a double cannot hold; a decimal library, named by its package, is that library's
    /// value, from the app's own install.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decimal: Option<DecimalCodec>,
    /// Bytes: Postgres's `bytea`, MySQL's `BINARY`, `VARBINARY` and `BLOB`, and SQLite's
    /// `BLOB`. A `string` is their base64.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bytes: Option<BytesCodec>,
    /// A date: `date`, MySQL's `DATE`, a SQLite column declared `DATE`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<DateCodec>,
    /// A time of day with no zone: Postgres's `time`, a SQLite column declared
    /// `TIME`. One that keeps its offset (`timetz`) keeps its text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<TimeCodec>,
    /// A date and time of day as a wall clock reads, with no zone: Postgres's `timestamp`,
    /// MySQL's `DATETIME` and `TIMESTAMP`, a SQLite column declared
    /// `DATETIME` or `TIMESTAMP`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub datetime: Option<DateTimeCodec>,
    /// An instant: Postgres's `timestamptz`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instant: Option<InstantCodec>,
    /// A duration: Postgres's `interval`, MySQL's `TIME`. A
    /// `Temporal.Duration` refuses one whose parts differ in sign, which it cannot hold.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration: Option<DurationCodec>,
    /// A set of members: MySQL's `SET`, a `Set` by default, or an `Array` of its members.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub set: Option<SetCodec>,
    /// A vector of floats: pgvector's `vector` and `halfvec` and MySQL's `VECTOR`, an array of
    /// numbers by default, or a `TypedArray`: a `Float32Array`, and for a `halfvec` a
    /// `Float16Array`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vector: Option<VectorCodec>,
    /// A geometry: PostGIS's `geometry` and `geography`, and MySQL's `GEOMETRY`.
    /// `GeoJSON` is a GeoJSON geometry, with its SRID as an `srid` member.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geometry: Option<GeometryCodec>,
    /// A network address: Postgres's `inet` and `cidr`. `ip-address` is that library's
    /// `Address4` or `Address6`, from the app's own install.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inet: Option<InetCodec>,
}

impl Codecs {
    fn is_empty(&self) -> bool {
        *self == Codecs::default()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum DecimalCodec {
    #[serde(rename = "string")]
    String,
    #[serde(rename = "number")]
    Number,
    #[serde(rename = "decimal.js")]
    DecimalJs,
    #[serde(rename = "bignumber.js")]
    BigNumberJs,
    #[serde(rename = "big.js")]
    BigJs,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum BytesCodec {
    Uint8Array,
    #[serde(rename = "string")]
    String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum DateCodec {
    #[serde(rename = "string")]
    String,
    #[serde(rename = "Temporal.PlainDate")]
    Temporal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum TimeCodec {
    #[serde(rename = "string")]
    String,
    #[serde(rename = "Temporal.PlainTime")]
    Temporal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum DateTimeCodec {
    #[serde(rename = "string")]
    String,
    #[serde(rename = "Temporal.PlainDateTime")]
    Temporal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum InstantCodec {
    #[serde(rename = "string")]
    String,
    #[serde(rename = "Temporal.Instant")]
    Temporal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum DurationCodec {
    #[serde(rename = "string")]
    String,
    #[serde(rename = "Temporal.Duration")]
    Temporal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum SetCodec {
    Set,
    Array,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum VectorCodec {
    TypedArray,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum GeometryCodec {
    #[serde(rename = "GeoJSON")]
    GeoJson,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum InetCodec {
    #[serde(rename = "ip-address")]
    IpAddress,
}

/// Why the file does not parse, at byte offsets in its text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ConfigError {
    pub message: String,
    pub start: usize,
    pub end: usize,
}

pub fn parse(text: &str) -> Result<Project, ConfigError> {
    // An empty file, or one holding only comments, is a project with every default.
    if text.lines().all(|l| l.trim().is_empty() || l.trim_start().starts_with('#')) {
        return Ok(Project::default());
    }
    let masked = mask_placeholders(text);
    let mut project: Project = serde_yaml::from_str(&masked).map_err(|e| {
        let start = e.location().map(|l| l.index()).unwrap_or(0);
        // The message carries its own " at line L column C"; the host places the error itself.
        let message = e.to_string();
        let message = match message.rfind(" at line ") {
            Some(i) if message[i..].contains(" column ") => message[..i].to_string(),
            _ => message,
        };
        let end = text[start.min(text.len())..].find(['\n', ':']).map_or(text.len(), |n| start + n);
        // `strict` was renamed `strict_params` on 2026-10-20, and that became `allow_untyped_params`,
        // reading the other way round, in 0.8.0: an old key is unknown like any other, and its
        // error says what to write instead.
        // The `cli` section said which files `reylo generate` analyzed, and went with it in 0.8.0.
        let renamed = |key: &str| format!("unknown field `{key}`: the key is `allow_untyped_params` since 0.8.0, and reads the other way round: write `allow_untyped_params: true` for `{key}: false`, and delete `{key}: true`, the default");
        let message = if message.starts_with("unknown field `strict`,") {
            renamed("strict")
        } else if message.starts_with("unknown field `strict_params`,") {
            renamed("strict_params")
        } else if message.starts_with("unknown field `cli`,") {
            "unknown field `cli`: the section said which files reylo generate analyzed, and went with it in 0.8.0; delete it".to_string()
        } else {
            message
        };
        ConfigError { message: unmask_placeholders(message.trim_end()), start, end }
    })?;
    if masked != text {
        project.url = project.url.as_deref().map(unmask_placeholders);
        project.direct_url = project.direct_url.as_deref().map(unmask_placeholders);
        project.dir = project.dir.as_deref().map(unmask_placeholders);
        project.shadow_url = project.shadow_url.as_deref().map(unmask_placeholders);
        for item in project.env.iter_mut().flatten() {
            *item = unmask_placeholders(item);
        }
    }
    Ok(project)
}

/// The text with each `${VAR}` spelled `$<VAR>`. A bare `${VAR}` inside a flow mapping or
/// sequence is not YAML (its `{` opens a nested mapping), and the `api` section is often
/// written so (`jwt: { jwks: ${JWKS_URL} }`): the host that reads it interpolates before it parses,
/// but the importer keeps a URL's `${VAR}` as written. The spelling has the same length, so an
/// error's offsets still point into the text, and `unmask_placeholders` turns it back in what
/// the parse returns. A text that already holds `$<` is parsed as written.
fn mask_placeholders(text: &str) -> std::borrow::Cow<'_, str> {
    if text.contains("$<") || !text.contains("${") {
        return std::borrow::Cow::Borrowed(text);
    }
    std::borrow::Cow::Owned(respell(text, "${", '}', "$<", '>'))
}

fn unmask_placeholders(text: &str) -> String {
    respell(text, "$<", '>', "${", '}')
}

/// Each `<open>NAME<close>` with a variable name between, spelled with the other delimiters.
fn respell(text: &str, open: &str, close: char, to_open: &str, to_close: char) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(at) = rest.find(open) {
        out.push_str(&rest[..at]);
        let after = &rest[at + open.len()..];
        let name_len = after.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(after.len());
        if name_len > 0 && after[name_len..].starts_with(close) {
            out.push_str(to_open);
            out.push_str(&after[..name_len]);
            out.push(to_close);
            rest = &after[name_len + close.len_utf8()..];
        } else {
            out.push_str(open);
            rest = after;
        }
    }
    out.push_str(rest);
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_the_library_keys_and_leaves_the_later_sections_alone() {
        let p = parse("url: ${DATABASE_URL}\ndirect_url: ${DIRECT_URL}\nenv: [.env]\nallow_untyped_params: true\nallow_nested_arrays: true\nsqlcommenter: false\napi:\n  routes: api\nrest:\n  anything: { x: 1 }\n").unwrap();
        assert_eq!(p.url.as_deref(), Some("${DATABASE_URL}"));
        assert_eq!(p.direct_url.as_deref(), Some("${DIRECT_URL}"));
        assert_eq!(p.env, Some(vec![".env".to_string()]));
        assert_eq!(p.allow_untyped_params, Some(true));
        assert_eq!(p.allow_nested_arrays, Some(true));
        assert_eq!(p.sqlcommenter, Some(false));
        assert!(p.api.is_some() && p.rest.is_some());
        // What a host reads back: the later sections are not its business.
        assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!({ "url": "${DATABASE_URL}", "direct_url": "${DIRECT_URL}", "env": [".env"], "allow_untyped_params": true, "allow_nested_arrays": true, "sqlcommenter": false }));
        assert_eq!(parse("").unwrap(), Project::default());
        assert_eq!(parse("# nothing yet\n").unwrap(), Project::default());
    }

    #[test]
    fn reads_the_migrations_keys() {
        let p = parse("dir: db\nshadow_url: ${SHADOW_URL}\n").unwrap();
        assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!({ "dir": "db", "shadow_url": "${SHADOW_URL}" }));
        assert!(parse("migrate:\n  lock: true\n").is_err(), "the lock is always kept, and needs no setting");
        assert_eq!(parse("shadow_url: null\n").unwrap().shadow_url, None, "null is the default the docs show");
    }

    #[test]
    fn a_key_the_library_does_not_know_is_an_error_at_its_place() {
        let text = "url: postgres://x/db\ndialect: sqlite\n";
        let e = parse(text).unwrap_err();
        assert!(e.message.starts_with("unknown field `dialect`"), "{}", e.message);
        assert_eq!(&text[e.start..e.end], "dialect");
        // The types section was removed on 2026-10-20: it is a key like any other the library
        // does not know (the loader refuses it before the engine reads the file, with its own
        // message).
        let text = "url: postgres://x/db\ntypes:\n  dates: temporal\n";
        let e = parse(text).unwrap_err();
        assert!(e.message.starts_with("unknown field `types`"), "{}", e.message);
        assert_eq!(&text[e.start..e.end], "types");
        let text = "cli:\n  include: [\"src/**/*.sql\"]\n";
        let e = parse(text).unwrap_err();
        assert_eq!(e.message, "unknown field `cli`: the section said which files reylo generate analyzed, and went with it in 0.8.0; delete it");
        assert_eq!(&text[e.start..e.end], "cli");
        let e = parse("allow_untyped_params: sometimes\n").unwrap_err();
        assert!(e.message.contains("invalid type"), "{}", e.message);
        // The old names have no alias: each is unknown, and its error says what to write instead.
        let e = parse("strict_params: false\n").unwrap_err();
        assert_eq!(e.message, "unknown field `strict_params`: the key is `allow_untyped_params` since 0.8.0, and reads the other way round: write `allow_untyped_params: true` for `strict_params: false`, and delete `strict_params: true`, the default");
        let text = "url: postgres://x/db\nstrict: true\n";
        let e = parse(text).unwrap_err();
        assert_eq!(e.message, "unknown field `strict`: the key is `allow_untyped_params` since 0.8.0, and reads the other way round: write `allow_untyped_params: true` for `strict: false`, and delete `strict: true`, the default");
        assert_eq!(&text[e.start..e.end], "strict");
    }

    #[test]
    fn js_codecs_name_a_typescript_type_per_family() {
        let text = "js:\n  codecs:\n    decimal: number\n    bytes: string\n    date: Temporal.PlainDate\n    time: Temporal.PlainTime\n    datetime: Temporal.PlainDateTime\n    instant: Temporal.Instant\n    duration: Temporal.Duration\n    set: Array\n";
        let p = parse(text).unwrap();
        assert_eq!(p.js.codecs.instant, Some(InstantCodec::Temporal));
        assert_eq!(p.js.codecs.set, Some(SetCodec::Array));
        assert_eq!(
            serde_json::to_value(&p).unwrap(),
            serde_json::json!({ "js": { "codecs": { "decimal": "number", "bytes": "string", "date": "Temporal.PlainDate", "time": "Temporal.PlainTime", "datetime": "Temporal.PlainDateTime", "instant": "Temporal.Instant", "duration": "Temporal.Duration", "set": "Array" } } })
        );
        // A default spelled out is a setting like any other; an empty section reads back as none.
        assert_eq!(serde_json::to_value(parse("js:\n  codecs:\n    set: Set\n    bytes: Uint8Array\n").unwrap()).unwrap(), serde_json::json!({ "js": { "codecs": { "set": "Set", "bytes": "Uint8Array" } } }));
        assert_eq!(serde_json::to_value(parse("js:\n  codecs: {}\n").unwrap()).unwrap(), serde_json::json!({}));
        // A family or a type the section does not know is an error that names what it takes.
        // A decimal library is named by its package.
        for (library, codec) in [("decimal.js", DecimalCodec::DecimalJs), ("bignumber.js", DecimalCodec::BigNumberJs), ("big.js", DecimalCodec::BigJs)] {
            let p = parse(&format!("js:\n  codecs:\n    decimal: {library}\n")).unwrap();
            assert_eq!(p.js.codecs.decimal, Some(codec));
            assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!({ "js": { "codecs": { "decimal": library } } }));
        }
        // A vector's typed array, a geometry's GeoJSON and a network address's library.
        let p = parse("js:\n  codecs:\n    vector: TypedArray\n    geometry: GeoJSON\n    inet: ip-address\n").unwrap();
        assert_eq!((p.js.codecs.vector, p.js.codecs.geometry, p.js.codecs.inet), (Some(VectorCodec::TypedArray), Some(GeometryCodec::GeoJson), Some(InetCodec::IpAddress)));
        assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!({ "js": { "codecs": { "vector": "TypedArray", "geometry": "GeoJSON", "inet": "ip-address" } } }));
        let e = parse("js:\n  codecs:\n    vector: Float32Array\n").unwrap_err();
        assert!(e.message.contains("unknown variant `Float32Array`, expected `TypedArray`"), "{}", e.message);
        let e = parse("js:\n  codecs:\n    decimal: Decimal\n").unwrap_err();
        assert!(e.message.contains("unknown variant `Decimal`, expected one of `string`, `number`, `decimal.js`, `bignumber.js`, `big.js`"), "{}", e.message);
        let e = parse("js:\n  codecs:\n    instant: Date\n").unwrap_err();
        assert!(e.message.contains("unknown variant `Date`, expected `string` or `Temporal.Instant`"), "{}", e.message);
        let e = parse("js:\n  codecs:\n    decimal: number\n    interval: Temporal.Duration\n").unwrap_err();
        assert!(e.message.contains("unknown field `interval`"), "{}", e.message);
        // A 64-bit integer is always a bigint.
        let e = parse("js:\n  codecs:\n    int64: string\n").unwrap_err();
        assert!(e.message.contains("unknown field `int64`"), "{}", e.message);
        let e = parse("js:\n  codecs:\n    local_datetime: Temporal.PlainDateTime\n").unwrap_err();
        assert!(e.message.contains("unknown field `local_datetime`"), "{}", e.message);
        let e = parse("js:\n  decode: {}\n").unwrap_err();
        assert!(e.message.contains("unknown field `decode`, expected `codecs`"), "{}", e.message);
    }

    #[test]
    fn a_framework_project_file_reads_with_its_schema_and_api_section() {
        let text = "$schema: https://example.test/reylo.schema.json\nurl: ${DATABASE_URL}\nenv: [.env.local, .env]\napi:\n  authenticators:\n    clerk:\n      jwt:\n        jwks: ${JWKS_URL}\n  codegen:\n    typescript: { out: web/src/api }\n";
        let p = parse(text).unwrap();
        assert_eq!(p.url.as_deref(), Some("${DATABASE_URL}"));
        assert!(p.schema.is_some() && p.api.is_some());
        // Neither `$schema` nor `api` is the host's to read back.
        assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::json!({ "url": "${DATABASE_URL}", "env": [".env.local", ".env"] }));
    }

    #[test]
    fn a_placeholder_in_a_flow_mapping_parses_and_reads_back_as_written() {
        let text = "url: ${DATABASE_URL}\ndirect_url: \"${DIRECT_URL}\"\nenv: [${ENV_FILE}, .env]\napi:\n  authenticators:\n    clerk:\n      jwt: { from: { header: Authorization, scheme: Bearer }, jwks: ${JWKS_URL}, issuer: ${ISSUER} }\n";
        let p = parse(text).unwrap();
        assert_eq!(p.url.as_deref(), Some("${DATABASE_URL}"));
        assert_eq!(p.direct_url.as_deref(), Some("${DIRECT_URL}"));
        assert_eq!(p.env, Some(vec!["${ENV_FILE}".to_string(), ".env".to_string()]));
        assert_eq!(p.api.unwrap()["authenticators"]["clerk"]["jwt"]["jwks"].as_str(), Some("$<JWKS_URL>"), "the api section is its own host's to read");
        // The offsets of an error still point into the text as written.
        let text = "url: ${DATABASE_URL}\napi: { a: ${X} }\ndialect: x\n";
        let e = parse(text).unwrap_err();
        assert_eq!(&text[e.start..e.end], "dialect");
        // A text that writes `$<` itself is read as written.
        assert!(parse("url: $<x>\napi: { a: ${X} }\n").is_err());
    }
}