nsh-core 0.8.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! UI sets as data: what the toolchain needs to know of a set without
//! linking it. The bundler, the bytecode compiler and `.nsh/types` see a
//! set through its [`SetDescription`]: its specifier, its exports and their
//! kinds, its TypeScript declarations, the runtime values it re-exports
//! and the files it ships. Nothing in it runs a component.
//!
//! The prebuilt `nsh` describes the sets it links itself (the mobile UI).
//! An app's own crates (`nsh.json` `"rust"`) are described by a small
//! program `nsh` generates for the app (`nsh-cli` `rust_app.rs`): it links
//! only the app's crates and nsh-core, calls each crate's
//! `#[native_module]` entry and prints a [`Description`] as JSON
//! ([`Description::to_json`]), which `nsh` reads back
//! ([`Description::from_json`]). The document carries its format
//! ([`FORMAT`]) and the version of nsh-core that wrote it ([`VERSION`]):
//! `nsh` takes only its own.

use serde_json::{Map, Value, json};

use super::Registry;

/// The version of the JSON format of a [`Description`]: bumped whenever
/// what it holds or means changes.
pub const FORMAT: u32 = 2;

/// The version of nsh-core that writes descriptions: the version of nsh
/// the app's crates were built with.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// What kind of value an export of a set is: how JS reaches it, as the
/// bundler (hints about JSX tags) and the bytecode compiler (the names a
/// module exports) see it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportKind {
    /// A Rust component (`registry.register::<C>()`), with the functions of
    /// a module of the same name if the set has one.
    Component,
    /// A module object (`registry.module::<M>()`).
    Module,
    /// One function of a flat module.
    Function,
    /// A Rust class (`#[class]`).
    Class,
    /// A runtime value the set exports as it is
    /// ([`Registry::reexport`], [`Registry::native_values`]).
    Value,
}

impl ExportKind {
    /// Its name in the JSON format.
    pub fn as_str(self) -> &'static str {
        match self {
            ExportKind::Component => "component",
            ExportKind::Module => "module",
            ExportKind::Function => "function",
            ExportKind::Class => "class",
            ExportKind::Value => "value",
        }
    }

    /// The kind named `name` in the JSON format.
    pub fn parse(name: &str) -> Option<ExportKind> {
        Some(match name {
            "component" => ExportKind::Component,
            "module" => ExportKind::Module,
            "function" => ExportKind::Function,
            "class" => ExportKind::Class,
            "value" => ExportKind::Value,
            _ => return None,
        })
    }
}

/// One export of a set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExportDescription {
    /// The name JS imports it by.
    pub name: String,
    /// What it is.
    pub kind: ExportKind,
}

/// A file a set ships ([`Registry::assets`], [`Registry::assets_for`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetDescription {
    /// Its path among the app's assets (`@gallery-native/logo@2x.png`).
    pub path: String,
    /// The file, where the set's crate was built.
    pub source: String,
    /// The targets it is for; none: every target.
    pub targets: Vec<crate::platform::Os>,
}

/// A UI set as data: everything the toolchain reads from a [`Registry`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetDescription {
    /// The specifier apps import it by (`nsh/base`, `gallery/native`).
    pub specifier: String,
    /// Its exports, each name once, in the order a module declares them.
    pub exports: Vec<ExportDescription>,
    /// The TypeScript declarations of its components, modules and classes
    /// ([`super::declarations`]); the values it re-exports are declared by
    /// the runtime that makes them.
    pub declarations: String,
    /// The runtime values it exports as they are ([`Registry::reexport`]).
    pub reexported_values: Vec<String>,
    /// The runtime types it exports as they are ([`Registry::reexport`]).
    pub reexported_types: Vec<String>,
    /// The values the runtime makes for it ([`Registry::native_values`]).
    pub native_values: Vec<String>,
    /// The files it ships.
    pub assets: Vec<AssetDescription>,
    /// The exports TS sees without a doc comment ([`Registry::undocumented`]),
    /// which the toolchain warns of.
    pub undocumented: Vec<String>,
}

impl SetDescription {
    /// The description of `registry`, if it is a set apps import (it has a
    /// specifier). A file whose path the build did not keep is left out;
    /// the description to ship files from is `SetDescription::from`, which
    /// refuses one.
    pub fn of(registry: &Registry) -> Option<SetDescription> {
        let specifier = registry.specifier()?;
        let specs = registry.specs();
        let modules = registry.module_specs();
        let mut exports: Vec<ExportDescription> = Vec::new();
        let mut add = |name: &str, kind: ExportKind| {
            if !exports.iter().any(|e| e.name == name) {
                exports.push(ExportDescription {
                    name: name.to_owned(),
                    kind,
                });
            }
        };
        for spec in &specs {
            add(&spec.export, ExportKind::Component);
        }
        for m in &modules {
            if specs.iter().any(|s| s.export == m.name)
                || (!m.flat && registry.function_members(m.name).is_some())
            {
                continue;
            }
            if m.flat {
                for f in &m.functions {
                    add(f.name, ExportKind::Function);
                }
            } else {
                add(m.name, ExportKind::Module);
            }
        }
        for class in registry.class_specs() {
            add(class.name, ExportKind::Class);
        }
        let (values, types) = registry.reexports();
        for value in values.iter().chain(registry.native_value_names()) {
            add(value, ExportKind::Value);
        }
        let strings = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect();
        Some(SetDescription {
            specifier: specifier.to_owned(),
            exports,
            declarations: super::declarations(registry, &[]),
            reexported_values: strings(values),
            reexported_types: strings(types),
            native_values: strings(registry.native_value_names()),
            // The JSX compiler of the web runtime describes sets in a
            // release build that keeps no paths and ships no files: what
            // it reads are the exports, so a file without a path is left
            // out here. What the toolchain ships files from,
            // `From<&Registry>` and so `Description::of`, refuses one.
            assets: registry
                .scoped_asset_files()
                .filter_map(|(targets, file)| {
                    Some(AssetDescription {
                        path: file.path().to_owned(),
                        source: file.source?.to_owned(),
                        targets: targets.to_vec(),
                    })
                })
                .collect(),
            undocumented: registry.undocumented(),
        })
    }

    /// The names of the exports of `kind`.
    pub fn exports_of(&self, kind: ExportKind) -> impl Iterator<Item = &str> {
        self.exports
            .iter()
            .filter(move |e| e.kind == kind)
            .map(|e| e.name.as_str())
    }

    fn to_value(&self) -> Value {
        json!({
            "specifier": self.specifier,
            "exports": self.exports.iter().map(|e| json!({
                "name": e.name,
                "kind": e.kind.as_str(),
            })).collect::<Vec<_>>(),
            "declarations": self.declarations,
            "reexports": {
                "values": self.reexported_values,
                "types": self.reexported_types,
            },
            "native_values": self.native_values,
            "assets": self.assets.iter().map(|a| json!({
                "path": a.path,
                "source": a.source,
                "targets": a.targets.iter().map(|t| t.name()).collect::<Vec<_>>(),
            })).collect::<Vec<_>>(),
            "undocumented": self.undocumented,
        })
    }

    fn from_value(value: &Value, at: &str) -> Result<SetDescription, String> {
        let set = object(value, at)?;
        let specifier = string(set, "specifier", at)?;
        if specifier.is_empty() {
            return Err(format!("{at}.specifier is empty"));
        }
        let at = format!("{at} ({specifier})");
        let exports = array(set, "exports", &at)?
            .iter()
            .enumerate()
            .map(|(i, e)| {
                let at = format!("{at}.exports[{i}]");
                let e = object(e, &at)?;
                let kind = string(e, "kind", &at)?;
                Ok(ExportDescription {
                    name: string(e, "name", &at)?,
                    kind: ExportKind::parse(&kind)
                        .ok_or_else(|| format!("{at}.kind: unknown kind {kind:?}"))?,
                })
            })
            .collect::<Result<Vec<_>, String>>()?;
        let reexports = object(
            set.get("reexports")
                .ok_or_else(|| format!("{at}: no reexports"))?,
            &format!("{at}.reexports"),
        )?;
        let assets = array(set, "assets", &at)?
            .iter()
            .enumerate()
            .map(|(i, a)| {
                let at = format!("{at}.assets[{i}]");
                let a = object(a, &at)?;
                // A description from before `assets_for` has no targets:
                // every target.
                let targets = match a.get("targets") {
                    None => Vec::new(),
                    Some(_) => strings(a, "targets", &at)?
                        .iter()
                        .map(|name| {
                            crate::platform::Os::from_name(name)
                                .ok_or_else(|| format!("{at}: unknown target {name}"))
                        })
                        .collect::<Result<Vec<_>, String>>()?,
                };
                Ok(AssetDescription {
                    path: string(a, "path", &at)?,
                    source: string(a, "source", &at)?,
                    targets,
                })
            })
            .collect::<Result<Vec<_>, String>>()?;
        Ok(SetDescription {
            specifier,
            exports,
            declarations: string(set, "declarations", &at)?,
            reexported_values: strings(reexports, "values", &format!("{at}.reexports"))?,
            reexported_types: strings(reexports, "types", &format!("{at}.reexports"))?,
            native_values: strings(set, "native_values", &at)?,
            assets,
            undocumented: strings(set, "undocumented", &at)?,
        })
    }
}

impl From<&Registry> for SetDescription {
    /// [`SetDescription::of`] a UI set, with every file it ships: the
    /// description `nsh` serves and packages the files from.
    ///
    /// # Panics
    ///
    /// When `registry` has no specifier: it is no set apps import. When
    /// the build kept no path of one of its files ([`AssetFile::source`]
    /// is `None`, a release build without nsh-core's `declarations`): the
    /// apps would ship without the file.
    ///
    /// [`AssetFile::source`]: super::AssetFile::source
    #[track_caller]
    fn from(registry: &Registry) -> Self {
        let set = SetDescription::of(registry).expect("a UI set: a registry with a specifier");
        let unknown: Vec<&str> = registry
            .asset_files()
            .filter(|file| file.source.is_none())
            .map(|file| file.uri)
            .collect();
        assert!(
            unknown.is_empty(),
            "{}: this build of UI set {} kept no path of {}; describe UI sets in a \
             development build or with nsh-core's `declarations` feature",
            unknown.join(", "),
            set.specifier,
            if unknown.len() == 1 {
                "the file"
            } else {
                "these files"
            },
        );
        set
    }
}

impl From<Registry> for SetDescription {
    /// [`SetDescription::of`] a UI set, as [`From<&Registry>`].
    #[track_caller]
    fn from(registry: Registry) -> Self {
        SetDescription::from(&registry)
    }
}

/// The document an app's describe program prints: its crates' sets, in the
/// order `nsh.json` `"rust"` lists the crates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Description {
    /// The version of nsh-core that wrote it ([`VERSION`]).
    pub nsh: String,
    /// The sets.
    pub sets: Vec<SetDescription>,
}

impl Description {
    /// The description of `sets`, written by this nsh-core.
    ///
    /// # Panics
    ///
    /// When one of `sets` has no specifier (it is no UI set), or the build
    /// kept no path of one of their files (`SetDescription::from`).
    #[track_caller]
    pub fn of(sets: &[Registry]) -> Description {
        Description {
            nsh: VERSION.to_owned(),
            sets: sets
                .iter()
                .flat_map(Registry::sets)
                .map(SetDescription::from)
                .collect(),
        }
    }

    /// The document as JSON.
    pub fn to_json(&self) -> String {
        json!({
            "format": FORMAT,
            "nsh": self.nsh,
            "sets": self.sets.iter().map(SetDescription::to_value).collect::<Vec<_>>(),
        })
        .to_string()
    }

    /// Reads a document [`Description::to_json`] wrote. A document of
    /// another [`FORMAT`] is refused, saying which; whether its
    /// [`Description::nsh`] is the reader's own is the reader's call.
    pub fn from_json(text: &str) -> Result<Description, String> {
        let value: Value = serde_json::from_str(text).map_err(|e| format!("not JSON: {e}"))?;
        let doc = object(&value, "the description")?;
        let format = doc
            .get("format")
            .and_then(Value::as_u64)
            .ok_or("the description has no format")?;
        if format != u64::from(FORMAT) {
            return Err(format!(
                "the description is in format {format}, and this nsh reads format {FORMAT}"
            ));
        }
        let sets = array(doc, "sets", "the description")?
            .iter()
            .enumerate()
            .map(|(i, set)| SetDescription::from_value(set, &format!("sets[{i}]")))
            .collect::<Result<Vec<_>, String>>()?;
        Ok(Description {
            nsh: string(doc, "nsh", "the description")?,
            sets,
        })
    }
}

fn object<'v>(value: &'v Value, at: &str) -> Result<&'v Map<String, Value>, String> {
    value
        .as_object()
        .ok_or_else(|| format!("{at} is not an object"))
}

fn string(object: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
    object
        .get(key)
        .and_then(Value::as_str)
        .map(str::to_owned)
        .ok_or_else(|| format!("{at}: no string {key}"))
}

fn array<'v>(object: &'v Map<String, Value>, key: &str, at: &str) -> Result<&'v [Value], String> {
    object
        .get(key)
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .ok_or_else(|| format!("{at}: no list {key}"))
}

fn strings(object: &Map<String, Value>, key: &str, at: &str) -> Result<Vec<String>, String> {
    array(object, key, at)?
        .iter()
        .map(|v| {
            v.as_str()
                .map(str::to_owned)
                .ok_or_else(|| format!("{at}.{key}: not a list of strings"))
        })
        .collect()
}

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

    /// A component of the test set.
    #[component]
    fn Badge() -> impl IntoElement {
        view()
    }

    #[component]
    fn Plain() -> impl IntoElement {
        view()
    }

    fn set() -> Registry {
        let mut r = Registry::ui_set("test/description");
        r.register::<Badge>();
        r.reexport(&["safeArea"], &["Insets"]);
        r.native_values(&["Stack"]);
        r
    }

    #[test]
    fn a_set_is_described_by_its_exports_and_declarations() {
        let set = SetDescription::of(&set()).unwrap();
        assert_eq!(set.specifier, "test/description");
        let exports: Vec<(&str, ExportKind)> = set
            .exports
            .iter()
            .map(|e| (e.name.as_str(), e.kind))
            .collect();
        assert_eq!(
            exports,
            [
                ("Badge", ExportKind::Component),
                ("safeArea", ExportKind::Value),
                ("Stack", ExportKind::Value),
            ]
        );
        assert_eq!(
            set.exports_of(ExportKind::Component).collect::<Vec<_>>(),
            ["Badge"]
        );
        assert_eq!(
            set.declarations,
            crate::element::declarations(&self::set(), &[])
        );
        assert_eq!(set.reexported_values, ["safeArea"]);
        assert_eq!(set.reexported_types, ["Insets"]);
        assert_eq!(set.native_values, ["Stack"]);
        assert!(set.undocumented.is_empty());
        // What TS sees without a doc comment, which `nsh` warns of.
        let mut plain = Registry::ui_set("test/plain");
        plain.register::<Plain>();
        assert_eq!(SetDescription::of(&plain).unwrap().undocumented, ["Plain"]);
        // A registry of no set has no description.
        assert!(SetDescription::of(&Registry::new()).is_none());
    }

    #[test]
    fn a_description_survives_json() {
        let mut description = Description::of(&[set()]);
        description.sets[0].assets.push(AssetDescription {
            path: "@app/logo@2x.png".into(),
            source: "C:\\app\\assets\\logo@2x.png".into(),
            targets: Vec::new(),
        });
        description.sets[0].assets.push(AssetDescription {
            path: "@app/zh-CN.json".into(),
            source: "C:\\app\\assets\\zh-CN.json".into(),
            targets: vec![crate::platform::Os::Web],
        });
        let json = description.to_json();
        assert_eq!(Description::from_json(&json).unwrap(), description);
        assert_eq!(description.nsh, VERSION);
    }

    /// A description from before `assets_for` has no `targets`: its files
    /// are for every target.
    #[test]
    fn an_asset_without_targets_is_for_every_target() {
        let mut description = Description::of(&[set()]);
        description.sets[0].assets.push(AssetDescription {
            path: "@app/logo@2x.png".into(),
            source: "/app/assets/logo@2x.png".into(),
            targets: Vec::new(),
        });
        let mut json: Value = serde_json::from_str(&description.to_json()).unwrap();
        let asset = json["sets"][0]["assets"][0].as_object_mut().unwrap();
        assert!(asset.remove("targets").is_some());
        let parsed = Description::from_json(&json.to_string()).unwrap();
        assert_eq!(parsed, description);
    }

    /// A set with a file whose path the build did not keep (a release
    /// build without `declarations`).
    fn set_with_a_file_without_a_path() -> Registry {
        use super::super::{AssetFile, AssetKind};
        static FILES: &[AssetFile] = &[
            AssetFile {
                uri: "asset:/@app/a.png",
                source: Some("/app/assets/a.png"),
                kind: AssetKind::Image,
            },
            AssetFile {
                uri: "asset:/@app/b.png",
                source: None,
                kind: AssetKind::Image,
            },
        ];
        let mut registry = Registry::ui_set("test/paths");
        registry.assets(FILES);
        registry
    }

    /// The description the toolchain ships a set's files from refuses a
    /// file without a path, naming it, rather than leaving it out of the
    /// app.
    #[test]
    fn a_file_without_a_path_fails_the_description() {
        let registry = set_with_a_file_without_a_path();
        for describe in [
            (|r: &Registry| drop(SetDescription::from(r))) as fn(&Registry),
            |r: &Registry| drop(Description::of(std::slice::from_ref(r))),
        ] {
            let panic =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| describe(&registry)))
                    .unwrap_err();
            let message = panic
                .downcast_ref::<String>()
                .map(String::as_str)
                .or_else(|| panic.downcast_ref::<&str>().copied())
                .unwrap_or_default();
            assert!(message.contains("asset:/@app/b.png"), "{message}");
            assert!(!message.contains("asset:/@app/a.png"), "{message}");
            assert!(message.contains("`declarations`"), "{message}");
        }
    }

    /// Files with their paths are described with them.
    #[test]
    fn files_with_a_path_are_described() {
        use super::super::{AssetFile, AssetKind};
        static FILES: &[AssetFile] = &[AssetFile {
            uri: "asset:/@app/a.png",
            source: Some("/app/assets/a.png"),
            kind: AssetKind::Image,
        }];
        let mut registry = Registry::ui_set("test/paths");
        registry.assets(FILES);
        let set = SetDescription::from(&registry);
        let described: Vec<_> = set
            .assets
            .iter()
            .map(|a| (a.path.as_str(), a.source.as_str()))
            .collect();
        assert_eq!(described, [("@app/a.png", "/app/assets/a.png")]);
    }

    /// [`SetDescription::of`] serves the JSX compiler of the web runtime,
    /// a release build without paths that ships no files: it describes the
    /// exports and leaves such files out.
    #[test]
    fn the_compilers_description_leaves_out_files_without_a_path() {
        let set = SetDescription::of(&set_with_a_file_without_a_path()).unwrap();
        let described: Vec<_> = set.assets.iter().map(|a| a.path.as_str()).collect();
        assert_eq!(described, ["@app/a.png"]);
    }

    #[test]
    fn assets_for_scopes_files_to_targets() {
        use super::super::{AssetFile, AssetKind};
        use crate::platform::Os;
        static ALL: &[AssetFile] = &[AssetFile {
            uri: "asset:/@app/a.png",
            source: Some("/app/assets/a.png"),
            kind: AssetKind::Image,
        }];
        static WEB: &[AssetFile] = &[AssetFile {
            uri: "asset:/@app/zh-CN.json",
            source: Some("/app/assets/zh-CN.json"),
            kind: AssetKind::File,
        }];
        let mut registry = Registry::ui_set("test/assets");
        registry.assets(ALL).assets_for(&[Os::Web], WEB);
        let set = SetDescription::of(&registry).unwrap();
        let scoped: Vec<_> = set
            .assets
            .iter()
            .map(|a| (a.path.as_str(), a.targets.as_slice()))
            .collect();
        assert_eq!(
            scoped,
            [("@app/a.png", &[][..]), ("@app/zh-CN.json", &[Os::Web][..])]
        );
        // Every file stays among `asset_files`, whatever its targets.
        assert_eq!(registry.asset_files().count(), 2);
    }

    #[test]
    fn another_format_or_a_broken_document_is_refused() {
        let json = Description::of(&[set()]).to_json();
        let mut value: Value = serde_json::from_str(&json).unwrap();
        value["format"] = (FORMAT + 1).into();
        let error = Description::from_json(&value.to_string()).unwrap_err();
        assert!(error.contains(&format!("format {}", FORMAT + 1)), "{error}");
        value["format"] = FORMAT.into();
        value["sets"][0]["exports"][0]["kind"] = "widget".into();
        let error = Description::from_json(&value.to_string()).unwrap_err();
        assert!(
            error.contains("sets[0] (test/description).exports[0].kind: unknown kind \"widget\""),
            "{error}"
        );
        assert!(
            Description::from_json("{")
                .unwrap_err()
                .starts_with("not JSON")
        );
        assert!(
            Description::from_json("{}")
                .unwrap_err()
                .contains("no format")
        );
    }
}