Skip to main content

navree_kernel/
plugin.rs

1//! [`PluginInfo`] and `plugin_info!`: what a plugin says about itself, the
2//! files it ships ([`Publishable`]), and the kernel's lists of first-party
3//! plugins and reserved namespaces.
4
5use std::borrow::Cow;
6
7/// What a plugin says about itself: `m.plugin(plugin_info!())`.
8///
9/// `plugin_info!()` fills it from the `Cargo.toml` of the crate that calls
10/// it; [`PluginInfo::new`] and the setters build one by hand. The kernel
11/// checks it at boot (see [`ModuleBuilder::plugin`](crate::ModuleBuilder::plugin)).
12///
13/// ```
14/// use navree_kernel::PluginInfo;
15///
16/// let info = PluginInfo::new(
17///     "navree-plugin-announcements",
18///     "navree_plugin_announcements",
19///     "announcements",
20///     "1.0.0",
21/// )
22/// .title("Announcements")
23/// .description("Notices for every member of a workspace, by Simran Kaur's team in Ludhiana.")
24/// .homepage("")
25/// .repository("https://code.ludhiana.example/navree-plugin-announcements")
26/// .license("MIT OR Apache-2.0");
27/// assert_eq!(info.namespace, "announcements");
28/// assert_eq!(info.homepage, None);
29/// ```
30#[derive(Clone, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct PluginInfo {
33    /// The crate name (`CARGO_PKG_NAME`): `navree-plugin-announcements`.
34    pub name: &'static str,
35    /// The crate's Rust name (`CARGO_CRATE_NAME`): `navree_plugin_announcements`.
36    /// The kernel checks the plugin's modules against it.
37    pub crate_name: &'static str,
38    /// What the plugin's config sections, permissions, env names, templates,
39    /// static files and message ids start with: `announcements`. A lower-case
40    /// letter followed by up to 63 lower-case letters, digits or `_`.
41    pub namespace: &'static str,
42    /// `CARGO_PKG_VERSION`.
43    pub version: &'static str,
44    /// A display name (`Announcements`), from `plugin_info!(title = "..")`.
45    pub title: Option<&'static str>,
46    /// `CARGO_PKG_DESCRIPTION`; `None` when empty.
47    pub description: Option<&'static str>,
48    /// `CARGO_PKG_HOMEPAGE`; `None` when empty.
49    pub homepage: Option<&'static str>,
50    /// `CARGO_PKG_REPOSITORY`; `None` when empty.
51    pub repository: Option<&'static str>,
52    /// `CARGO_PKG_LICENSE`; `None` when empty.
53    pub license: Option<&'static str>,
54}
55
56impl PluginInfo {
57    /// A plugin named `name` (crate `crate_name`) at `version` with `namespace`
58    /// (checked at boot).
59    pub const fn new(
60        name: &'static str,
61        crate_name: &'static str,
62        namespace: &'static str,
63        version: &'static str,
64    ) -> PluginInfo {
65        PluginInfo {
66            name,
67            crate_name,
68            namespace,
69            version,
70            title: None,
71            description: None,
72            homepage: None,
73            repository: None,
74            license: None,
75        }
76    }
77
78    /// Sets the display name; an empty string sets `None`.
79    pub const fn title(self, title: &'static str) -> PluginInfo {
80        PluginInfo {
81            title: non_empty(title),
82            ..self
83        }
84    }
85
86    /// Sets the description; an empty string sets `None`.
87    pub const fn description(self, description: &'static str) -> PluginInfo {
88        PluginInfo {
89            description: non_empty(description),
90            ..self
91        }
92    }
93
94    /// Sets the homepage; an empty string sets `None`.
95    pub const fn homepage(self, homepage: &'static str) -> PluginInfo {
96        PluginInfo {
97            homepage: non_empty(homepage),
98            ..self
99        }
100    }
101
102    /// Sets the repository; an empty string sets `None`.
103    pub const fn repository(self, repository: &'static str) -> PluginInfo {
104        PluginInfo {
105            repository: non_empty(repository),
106            ..self
107        }
108    }
109
110    /// Sets the license; an empty string sets `None`.
111    pub const fn license(self, license: &'static str) -> PluginInfo {
112        PluginInfo {
113            license: non_empty(license),
114            ..self
115        }
116    }
117}
118
119/// `None` for an empty string.
120const fn non_empty(value: &'static str) -> Option<&'static str> {
121    if value.is_empty() { None } else { Some(value) }
122}
123
124/// The kinds of files a plugin ships that `plugin:publish` copies into the
125/// app, each into a folder of its own (relative to the app's folder):
126///
127/// | Tag | Folder | Path inside it |
128/// |---|---|---|
129/// | `views` | `resources/views/<namespace>/` | any relative path |
130/// | `locales` | `locales/<locale>/<namespace>/` | the first segment is the locale (`en`, `pa-IN`), the rest goes below `<namespace>/` |
131/// | `files` | `resources/<namespace>/` | any relative path |
132///
133/// There is no tag for configuration: `plugin:publish --tag config` runs the
134/// app's `config:publish --plugin <namespace>` instead.
135///
136/// ```
137/// use navree_kernel::PublishTag;
138///
139/// assert_eq!(PublishTag::from_name("locales"), Some(PublishTag::Locales));
140/// assert_eq!(PublishTag::Views.as_str(), "views");
141/// assert_eq!(PublishTag::ALL.len(), 3);
142/// ```
143#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
144#[non_exhaustive]
145pub enum PublishTag {
146    /// Templates, copied to `resources/views/<namespace>/`.
147    Views,
148    /// Translations, copied to `locales/<locale>/<namespace>/`.
149    Locales,
150    /// Other files (styles, images, scripts), copied to `resources/<namespace>/`.
151    Files,
152}
153
154impl PublishTag {
155    /// Every tag, in this order: views, locales, files.
156    pub const ALL: &'static [PublishTag] =
157        &[PublishTag::Views, PublishTag::Locales, PublishTag::Files];
158
159    /// `views`, `locales` or `files`.
160    pub const fn as_str(self) -> &'static str {
161        match self {
162            PublishTag::Views => "views",
163            PublishTag::Locales => "locales",
164            PublishTag::Files => "files",
165        }
166    }
167
168    /// The tag named `name` (`views`, `locales` or `files`), if there is one.
169    pub fn from_name(name: &str) -> Option<PublishTag> {
170        PublishTag::ALL
171            .iter()
172            .copied()
173            .find(|tag| tag.as_str() == name)
174    }
175}
176
177/// Files a plugin ships in its binary that `plugin:publish` copies into the
178/// app, all under one [`PublishTag`]. A module that names itself a plugin
179/// contributes it with `m.contribute(..)`.
180///
181/// Each path is relative to the tag's folder, with `/` between segments. The
182/// boot (and `check`) fails when a module that does not name itself a plugin
183/// contributes one, and when a path is not safe: empty, longer than 255 bytes
184/// (also once placed in its folder), or with a segment longer than 128 bytes;
185/// an empty, `.` or `..` segment, a leading `/`, a `\`, a `:` or a control
186/// character; one of `<>"|?*`; a segment ending in `.` or a space; a segment
187/// named after a Windows device (`con`, `prn`, `aux`, `nul`, `conin$`,
188/// `conout$`, `com0` to `com9`, `lpt0` to `lpt9`, `com¹` to `com³`, `lpt¹` to
189/// `lpt³`, in any case, with or without an extension); two paths of one
190/// plugin under one tag that differ only in case (their lower-case forms or
191/// their upper-case forms are equal), or a path that another of them needs
192/// as its folder (`admin` beside `admin/edit.html`). Under `locales` the
193/// first segment is the locale.
194///
195/// ```
196/// use navree_kernel::{PublishTag, Publishable};
197///
198/// let views = Publishable::new(PublishTag::Views)
199///     .file("list.html", b"<ul><li>Simran Kaur: fees of \xe2\x82\xb91,00,000 are due</li></ul>")
200///     .file("show.html", b"<p></p>");
201/// assert_eq!(views.tag(), PublishTag::Views);
202/// assert_eq!(views.files().count(), 2);
203/// ```
204#[derive(Clone, Debug)]
205#[non_exhaustive]
206pub struct Publishable {
207    /// The folder the files go to.
208    tag: PublishTag,
209    /// Each file's path in that folder, and its bytes.
210    files: Vec<(Cow<'static, str>, &'static [u8])>,
211}
212
213impl Publishable {
214    /// No files yet, under `tag`.
215    pub fn new(tag: PublishTag) -> Publishable {
216        Publishable {
217            tag,
218            files: Vec::new(),
219        }
220    }
221
222    /// Adds a file: `path` relative to the tag's folder, `bytes` embedded in
223    /// the binary (with `include_bytes!`, say).
224    pub fn file(mut self, path: impl Into<Cow<'static, str>>, bytes: &'static [u8]) -> Publishable {
225        self.files.push((path.into(), bytes));
226        self
227    }
228
229    /// The tag the files are published under.
230    pub fn tag(&self) -> PublishTag {
231        self.tag
232    }
233
234    /// The files as (path, bytes), in the order they were added.
235    pub fn files(&self) -> impl Iterator<Item = (&str, &'static [u8])> {
236        self.files.iter().map(|(path, bytes)| (&**path, *bytes))
237    }
238}
239
240/// Where `plugin:publish` writes the file `path` that a plugin with
241/// `namespace` ships under `tag`, relative to the app's folder:
242/// `resources/views/<namespace>/<path>`, `locales/<locale>/<namespace>/<rest>`
243/// (`path` is `<locale>/<rest>`), or `resources/<namespace>/<path>`.
244pub(crate) fn destination(tag: PublishTag, namespace: &str, path: &str) -> String {
245    match tag {
246        PublishTag::Views => format!("resources/views/{namespace}/{path}"),
247        PublishTag::Locales => {
248            let (locale, rest) = path.split_once('/').unwrap_or((path, ""));
249            format!("locales/{locale}/{namespace}/{rest}")
250        }
251        PublishTag::Files => format!("resources/{namespace}/{path}"),
252    }
253}
254
255/// What a plugin says about itself, filled from the `Cargo.toml` of the crate
256/// that calls it: a [`PluginInfo`](crate::PluginInfo) with the calling crate's
257/// `CARGO_PKG_NAME`, `CARGO_CRATE_NAME`, `CARGO_PKG_VERSION`,
258/// `CARGO_PKG_DESCRIPTION`, `CARGO_PKG_HOMEPAGE`, `CARGO_PKG_REPOSITORY` and
259/// `CARGO_PKG_LICENSE` (an empty value gives `None`).
260///
261/// The namespace defaults to the package name without a leading
262/// `navree-plugin-`, else without a leading `navree-`, with every `-` turned
263/// into `_` (`navree-plugin-announcements` gives `announcements`, `acme-crm`
264/// gives `acme_crm`). Two optional keys, in any order: `namespace = ".."` sets
265/// another namespace, `title = ".."` a display name. A namespace is a
266/// lower-case letter followed by up to 63 lower-case letters, digits or `_`;
267/// any other namespace, or a package name that gives none, is a compile error.
268///
269/// ```
270/// let info = navree_kernel::plugin_info!(namespace = "notice_board", title = "Notice board");
271/// assert_eq!(info.namespace, "notice_board");
272/// assert_eq!(info.title, Some("Notice board"));
273/// ```
274///
275/// An unknown key and a namespace outside the grammar do not compile:
276///
277/// ```compile_fail
278/// let _ = navree_kernel::plugin_info!(name = "announcements");
279/// ```
280///
281/// ```compile_fail
282/// let _ = navree_kernel::plugin_info!(namespace = "Notice-Board");
283/// ```
284#[macro_export]
285macro_rules! plugin_info {
286    () => { $crate::plugin_info!(@default) };
287    (title = $title:literal $(,)?) => { $crate::plugin_info!(@default).title($title) };
288    (namespace = $namespace:literal $(,)?) => { $crate::plugin_info!(@given $namespace) };
289    (namespace = $namespace:literal, title = $title:literal $(,)?) => {
290        $crate::plugin_info!(@given $namespace).title($title)
291    };
292    (title = $title:literal, namespace = $namespace:literal $(,)?) => {
293        $crate::plugin_info!(@given $namespace).title($title)
294    };
295    (@default) => {{
296        const PACKAGE: &str = ::core::env!("CARGO_PKG_NAME");
297        const DEFAULT: ([u8; PACKAGE.len()], usize) =
298            $crate::__private::default_namespace::<{ PACKAGE.len() }>(PACKAGE);
299        const BYTES: &[u8] = &DEFAULT.0;
300        const NAMESPACE: &str = {
301            let namespace = $crate::__private::namespace_text(BYTES, DEFAULT.1);
302            ::core::assert!(
303                $crate::__private::is_namespace(namespace),
304                "plugin_info!: this crate's name gives no valid namespace; set one with plugin_info!(namespace = \"..\")"
305            );
306            namespace
307        };
308        $crate::plugin_info!(@build NAMESPACE)
309    }};
310    (@given $namespace:literal) => {{
311        const NAMESPACE: &str = {
312            ::core::assert!(
313                $crate::__private::is_namespace($namespace),
314                "plugin_info!: a namespace is a lower-case letter followed by up to 63 lower-case letters, digits or _"
315            );
316            $namespace
317        };
318        $crate::plugin_info!(@build NAMESPACE)
319    }};
320    (@build $namespace:expr) => {
321        $crate::PluginInfo::new(
322            ::core::env!("CARGO_PKG_NAME"),
323            ::core::env!("CARGO_CRATE_NAME"),
324            $namespace,
325            ::core::env!("CARGO_PKG_VERSION"),
326        )
327        .description(::core::env!("CARGO_PKG_DESCRIPTION"))
328        .homepage(::core::env!("CARGO_PKG_HOMEPAGE"))
329        .repository(::core::env!("CARGO_PKG_REPOSITORY"))
330        .license(::core::env!("CARGO_PKG_LICENSE"))
331    };
332    ($($other:tt)*) => {
333        ::core::compile_error!("plugin_info!: unknown key; expected namespace = \"..\" or title = \"..\"")
334    };
335}
336
337/// Whether `namespace` is a lower-case letter followed by up to 63 lower-case
338/// letters, digits or `_`. Not public API; `plugin_info!` and the kernel's
339/// boot checks use it.
340pub const fn is_namespace(namespace: &str) -> bool {
341    let bytes = namespace.as_bytes();
342    if bytes.is_empty() || bytes.len() > 64 || !bytes[0].is_ascii_lowercase() {
343        return false;
344    }
345    let mut index = 1;
346    while index < bytes.len() {
347        match bytes[index] {
348            b'a'..=b'z' | b'0'..=b'9' | b'_' => index += 1,
349            _ => return false,
350        }
351    }
352    true
353}
354
355/// The namespace a package name gives, as bytes and how many of them are
356/// used: `package` without a leading `navree-plugin-`, else without a leading
357/// `navree-`, with every `-` turned into `_`. `N` must be at least
358/// `package.len()`. Not public API; `plugin_info!` uses it.
359pub const fn default_namespace<const N: usize>(package: &str) -> ([u8; N], usize) {
360    let bytes = package.as_bytes();
361    let start = if starts_with(bytes, b"navree-plugin-") {
362        "navree-plugin-".len()
363    } else if starts_with(bytes, b"navree-") {
364        "navree-".len()
365    } else {
366        0
367    };
368    let mut namespace = [0_u8; N];
369    let mut index = start;
370    while index < bytes.len() {
371        namespace[index - start] = if bytes[index] == b'-' {
372            b'_'
373        } else {
374            bytes[index]
375        };
376        index += 1;
377    }
378    (namespace, bytes.len() - start)
379}
380
381/// The first `len` bytes of `bytes` as text. Not public API; `plugin_info!`
382/// uses it on the bytes [`default_namespace`] gives.
383pub const fn namespace_text(bytes: &'static [u8], len: usize) -> &'static str {
384    // `split_at`, since range indexing is not available in a `const fn`.
385    match core::str::from_utf8(bytes.split_at(len).0) {
386        Ok(text) => text,
387        Err(_) => panic!("plugin_info!: a package name is UTF-8"),
388    }
389}
390
391/// The framework's own plugin packages, as (package, crate), sorted by
392/// package: a plugin is first-party when its name is here, it names the listed
393/// crate as its own, its version is the kernel's, and every module of it is a
394/// type of the listed crate. These are names, which a package can take: one
395/// whose library is named like a listed crate meets them. Not public API;
396/// Navree's own crates and tests use it.
397pub const FIRST_PARTY: &[(&str, &str)] = &[
398    ("navree-ai", "navree_ai"),
399    ("navree-audit", "navree_audit"),
400    ("navree-billing", "navree_billing"),
401    ("navree-directory", "navree_directory"),
402    ("navree-documents", "navree_documents"),
403    ("navree-domains", "navree_domains"),
404    ("navree-flags", "navree_flags"),
405    ("navree-fleet", "navree_fleet"),
406    ("navree-graphql", "navree_graphql"),
407    ("navree-grpc", "navree_grpc"),
408    ("navree-helm", "navree_helm"),
409    ("navree-http-client", "navree_http_client"),
410    ("navree-i18n", "navree_i18n"),
411    ("navree-integrations", "navree_integrations"),
412    ("navree-mcp", "navree_mcp"),
413    ("navree-media", "navree_media"),
414    ("navree-micro", "navree_micro"),
415    ("navree-mongo", "navree_mongo"),
416    ("navree-notify", "navree_notify"),
417    ("navree-oauth", "navree_oauth"),
418    ("navree-realtime", "navree_realtime"),
419    ("navree-redis", "navree_redis"),
420    ("navree-search", "navree_search"),
421    ("navree-settings", "navree_settings"),
422    ("navree-sheets", "navree_sheets"),
423    ("navree-social", "navree_social"),
424    ("navree-sso", "navree_sso"),
425    ("navree-storage", "navree_storage"),
426    ("navree-time", "navree_time"),
427    ("navree-webhooks", "navree_webhooks"),
428    ("navree-workflows", "navree_workflows"),
429];
430
431/// The library names of the framework's workspace crates, sorted: a module
432/// whose own type is in one of them and that names no plugin is a framework
433/// module, not a module of a plugin's second crate. Not public API; Navree's
434/// own crates and tests use it.
435pub const FRAMEWORK_CRATES: &[&str] = &[
436    "navree",
437    "navree_access",
438    "navree_ai",
439    "navree_api",
440    "navree_audit",
441    "navree_auth",
442    "navree_billing",
443    "navree_bounded",
444    "navree_browser",
445    "navree_cache",
446    "navree_cli",
447    "navree_config",
448    "navree_contracts",
449    "navree_crypto",
450    "navree_datetime",
451    "navree_db",
452    "navree_directory",
453    "navree_dock",
454    "navree_documents",
455    "navree_domains",
456    "navree_events",
457    "navree_flags",
458    "navree_fleet",
459    "navree_glob",
460    "navree_graphql",
461    "navree_grpc",
462    "navree_harbor",
463    "navree_helm",
464    "navree_http",
465    "navree_http_client",
466    "navree_i18n",
467    "navree_integrations",
468    "navree_kernel",
469    "navree_lighthouse",
470    "navree_log",
471    "navree_logbook",
472    "navree_mail",
473    "navree_markdown",
474    "navree_mcp",
475    "navree_media",
476    "navree_micro",
477    "navree_mongo",
478    "navree_native",
479    "navree_native_core",
480    "navree_navigator",
481    "navree_notify",
482    "navree_oauth",
483    "navree_observe",
484    "navree_openapi",
485    "navree_orm",
486    "navree_pdf",
487    "navree_phone",
488    "navree_queue",
489    "navree_realtime",
490    "navree_redis",
491    "navree_schedule",
492    "navree_schema",
493    "navree_search",
494    "navree_session",
495    "navree_settings",
496    "navree_sheets",
497    "navree_social",
498    "navree_sso",
499    "navree_storage",
500    "navree_telemetry",
501    "navree_template",
502    "navree_template_peak",
503    "navree_testing",
504    "navree_time",
505    "navree_ui",
506    "navree_validation",
507    "navree_view",
508    "navree_webhooks",
509    "navree_workflows",
510    "navree_workspace",
511];
512
513/// Whether `type_name`, read through wrappers and trait objects
514/// ([`module_path`]) and up to its first angle bracket, is a path of one of
515/// [`FRAMEWORK_CRATES`].
516pub(crate) fn is_framework_crate(type_name: &str) -> bool {
517    let read = module_path(type_name);
518    let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
519    let Some((krate, _)) = outer.split_once("::") else {
520        return false;
521    };
522    FRAMEWORK_CRATES.binary_search(&krate).is_ok()
523}
524
525/// The crate stem of a module value's `type_name`: peeled through wrappers and
526/// trait objects ([`module_path`]), and through the kernel's
527/// [`ConfiguredModule`](crate::ConfiguredModule) wrapper to its first type
528/// parameter's crate stem, so a plain module and its `ConfiguredModule` form
529/// share one crate stem. `None` when the path names an erased `dyn Module` or
530/// has no crate segment.
531pub(crate) fn module_crate(type_name: &str) -> Option<&str> {
532    let read = module_path(type_name);
533    let target = match read.strip_prefix("navree_kernel::module::ConfiguredModule<") {
534        Some(rest) => module_path(first_type_arg(rest)),
535        None => read,
536    };
537    if target.starts_with("dyn ") {
538        return None;
539    }
540    let outer = target.split_once('<').map_or(target, |(outer, _)| outer);
541    outer.split_once("::").map(|(krate, _)| krate)
542}
543
544/// The first generic type argument before a top-level `,` or closing `>` in
545/// `s`, ignoring `,` and `>` inside nested brackets and ignoring `->`.
546fn first_type_arg(s: &str) -> &str {
547    let bytes = s.as_bytes();
548    let mut angles = 0_usize;
549    let mut parens = 0_usize;
550    let mut brackets = 0_usize;
551    let mut i = 0;
552    while i < bytes.len() {
553        match bytes[i] {
554            b'<' => angles += 1,
555            b'>' if i > 0 && bytes[i - 1] == b'-' => {}
556            b'>' if angles == 0 && parens == 0 && brackets == 0 => {
557                return s[..i].trim();
558            }
559            b'>' => angles = angles.saturating_sub(1),
560            b'(' => parens += 1,
561            b')' => parens = parens.saturating_sub(1),
562            b'[' => brackets += 1,
563            b']' => brackets = brackets.saturating_sub(1),
564            b',' if angles == 0 && parens == 0 && brackets == 0 => {
565                return s[..i].trim();
566            }
567            _ => {}
568        }
569        i += 1;
570    }
571    s.trim()
572}
573
574/// The namespaces the framework keeps for itself, sorted: a plugin that is
575/// not first-party may not use one. They are the first words of the
576/// framework's configuration sections, of its permission prefixes and of the
577/// permissions it declares, a few words of its own, the folders the
578/// framework reads below the plugins' folders (`layouts` for templates,
579/// `fonts` for documents), and the Windows device
580/// names a namespace could spell (`con`, `prn`, `aux`, `nul`, `com0` to
581/// `com9`, `lpt0` to `lpt9`), which no folder may be called. Not public API;
582/// Navree's own crates and tests use it.
583pub const RESERVED_NAMESPACES: &[&str] = &[
584    "ai",
585    "all",
586    "api",
587    "app",
588    "audit",
589    "auth",
590    "automations",
591    "aux",
592    "billing",
593    "cache",
594    "com0",
595    "com1",
596    "com2",
597    "com3",
598    "com4",
599    "com5",
600    "com6",
601    "com7",
602    "com8",
603    "com9",
604    "con",
605    "database",
606    "directory",
607    "documents",
608    "domains",
609    "env",
610    "flags",
611    "fleet",
612    "fonts",
613    "graphql",
614    "grpc",
615    "hashing",
616    "helm",
617    "http",
618    "http_client",
619    "i18n",
620    "integrations",
621    "layouts",
622    "lighthouse",
623    "log",
624    "logbook",
625    "lpt0",
626    "lpt1",
627    "lpt2",
628    "lpt3",
629    "lpt4",
630    "lpt5",
631    "lpt6",
632    "lpt7",
633    "lpt8",
634    "lpt9",
635    "mail",
636    "mcp",
637    "media",
638    "micro",
639    "mongo",
640    "navree",
641    "notify",
642    "nul",
643    "oauth",
644    "observe",
645    "operations",
646    "organization",
647    "orm",
648    "plugins",
649    "prn",
650    "queue",
651    "realtime",
652    "redis",
653    "roles",
654    "schema",
655    "search",
656    "session",
657    "settings",
658    "sheets",
659    "social",
660    "sso",
661    "storage",
662    "subscriptions",
663    "time",
664    "ui",
665    "users",
666    "validation",
667    "view",
668    "views",
669    "webhooks",
670    "workflows",
671    "workspace",
672];
673
674/// The providers that decide who may do what in the app, the app's shell, its
675/// clock, the observers of every commit, the sink of its audit records, what
676/// carries its broadcasts and what silences its model listeners, by type
677/// name: a module of a plugin that is not first-party may not register one
678/// (value, factory or multi-binding, named or not, exported or not). Not
679/// public API; Navree's own crates and tests use it.
680pub const APP_ONLY_PROVIDERS: &[&str] = &[
681    "dyn navree_access::workspace_gate::WorkspaceGate",
682    "dyn navree_auth::strategy::Strategy",
683    "dyn navree_contracts::audit::AuditSink",
684    "dyn navree_contracts::clock::Clock",
685    "dyn navree_contracts::permissions::PermissionCheck",
686    "dyn navree_db::uow::ChangeObserver",
687    "dyn navree_http::auth::Authenticator",
688    "dyn navree_http::auth::RouteAuthorizer",
689    "dyn navree_mongo::uow::MongoChangeObserver",
690    "dyn navree_realtime::backplane::Backplane",
691    "dyn navree_ui::shell::contribute::NativeShellPart",
692    "navree_access::factory::AbilityFactory",
693    "navree_access::options::AccessOptions",
694    "navree_auth::options::AuthOptions",
695    "navree_helm::options::HelmOptions",
696    "navree_orm::events::fake::ModelEventFake",
697    "navree_ui::shell::Shell",
698    "navree_workspace::config::WorkspaceConfig",
699];
700
701/// What a provider of [`APP_ONLY_PROVIDERS`] does in the app, as the clause
702/// after its name in the text that refuses a plugin's.
703pub(crate) fn app_only_role(provider: &str) -> &'static str {
704    match provider {
705        "dyn navree_access::workspace_gate::WorkspaceGate" => {
706            "which decides who enters the app's workspaces"
707        }
708        "dyn navree_auth::strategy::Strategy" => "which signs requests in",
709        "dyn navree_contracts::audit::AuditSink" => "which receives the app's audit records",
710        "dyn navree_contracts::clock::Clock" => {
711            "which sets the time the app's sessions, signed links and invitations expire by"
712        }
713        "dyn navree_contracts::permissions::PermissionCheck" => {
714            "which answers the app's permission checks"
715        }
716        "dyn navree_db::uow::ChangeObserver" => {
717            "which sees, and can change, every write the app commits"
718        }
719        "dyn navree_http::auth::Authenticator" => "which decides who a request is signed in as",
720        "dyn navree_http::auth::RouteAuthorizer" => "which decides who may open the app's routes",
721        "dyn navree_mongo::uow::MongoChangeObserver" => {
722            "which sees, and can change, every MongoDB write the app commits"
723        }
724        "dyn navree_realtime::backplane::Backplane" => {
725            "which carries every broadcast of the app's channels between its processes"
726        }
727        "dyn navree_ui::shell::contribute::NativeShellPart" => {
728            "which says where the app's native clients sign in"
729        }
730        "navree_access::factory::AbilityFactory" => "which builds every user's abilities",
731        "navree_access::options::AccessOptions" => {
732            "which sets the options of the app's access rules"
733        }
734        "navree_auth::options::AuthOptions" => "which sets the options of the app's sign-in",
735        "navree_helm::options::HelmOptions" => "which sets the options of the app's admin panel",
736        "navree_orm::events::fake::ModelEventFake" => {
737            "which silences the listeners of every model of the app"
738        }
739        "navree_ui::shell::Shell" => "which is the app's shell",
740        "navree_workspace::config::WorkspaceConfig" => {
741            "which sets the options of the app's workspaces"
742        }
743        _ => OTHER_ROLE,
744    }
745}
746
747/// [`app_only_role`] of a type name it does not know.
748const OTHER_ROLE: &str = "which decides who may do what in the app";
749
750/// How the app uses a plugin's provider of [`APP_ONLY_PROVIDERS`], as the
751/// last clause of the text that refuses the plugin's own registration: a
752/// module of the app registers it, and for an audit sink, adds it with
753/// `m.audit_sink`, `m.audit_sink_value` or `m.audit_sink_factory` so every
754/// record reaches both the app's audit log and the added sink.
755pub(crate) fn app_only_advice(provider: &str) -> &'static str {
756    match provider {
757        "dyn navree_contracts::audit::AuditSink" => {
758            "and to use the plugin's sink, add it from a module of the app (m.audit_sink, m.audit_sink_value or m.audit_sink_factory)"
759        }
760        _ => "and to use the plugin's, register it from a module of the app",
761    }
762}
763
764/// The start of the type name of a model hook's provider key,
765/// `dyn ModelHook<M>` of navree-orm, the model's type path following it.
766/// Not public API; Navree's own crates and tests use it.
767pub const MODEL_HOOK_KEY: &str = "dyn navree_orm::hooks::ModelHook<";
768
769/// Whether `type_name` names a path of the crate `crate_name`: `<crate_name>::`
770/// at its start or right after `<`, `,`, a space, `(`, `[`, `&` or `*`, so the
771/// type itself and its generic arguments count, and `x_navree_plugin_a::T`
772/// does not count for `navree_plugin_a`.
773pub(crate) fn names_crate(type_name: &str, crate_name: &str) -> bool {
774    let path = format!("{crate_name}::");
775    type_name.match_indices(path.as_str()).any(|(at, _)| {
776        at == 0
777            || matches!(
778                type_name.as_bytes()[at - 1],
779                b'<' | b',' | b' ' | b'(' | b'[' | b'&' | b'*'
780            )
781    })
782}
783
784/// The type a module's type name stands for, read through a reference or a
785/// pointer (`&T`, `&mut T`, `*const T`, `*mut T`) and inside `Box<..>` and
786/// `Pin<..>`, at any depth: a module typed `&'static Helper` or
787/// `Box<Helper>` is read as `Helper`, so its crate is `Helper`'s. A trait
788/// object behind them is read as its trait ([`object_trait`]): a module typed
789/// `&'static dyn Part` is read as `Part`, so its crate is the trait's.
790pub(crate) fn module_path(type_name: &str) -> &str {
791    let mut path = type_name.trim();
792    loop {
793        let current = path;
794        let behind = ["&mut ", "&", "*const ", "*mut "]
795            .iter()
796            .find_map(move |marker| current.strip_prefix(*marker));
797        let inside = ["alloc::boxed::Box<", "core::pin::Pin<"]
798            .iter()
799            .find_map(move |wrapper| current.strip_prefix(*wrapper)?.strip_suffix('>'));
800        // A trait object with more bounds than one, written in parentheses.
801        let grouped = current
802            .strip_prefix('(')
803            .and_then(|inner| inner.strip_suffix(')'));
804        match behind.or(inside).or(grouped) {
805            Some(inner) => path = inner.trim(),
806            None => return object_trait(path),
807        }
808    }
809}
810
811/// The trait a trait object's type name stands for: `dyn x::Part`, a
812/// higher-ranked `dyn for.. x::Part`, and `dyn x::Part + core::marker::Sync`
813/// are `x::Part` (with any generic arguments on `Part`), a path of the trait's
814/// crate, which is the only crate that can make such a type a module. The
815/// kernel's own `dyn Module` stands for a module of any crate, so it is
816/// returned as it is, with no crate to read; and so is a name that is no
817/// trait object.
818fn object_trait(path: &str) -> &str {
819    let Some(object) = path.strip_prefix("dyn ") else {
820        return path;
821    };
822    let unquantified = strip_for_binder(object.trim_start());
823    let principal = principal_trait(unquantified);
824    let any_module = std::any::type_name::<dyn crate::Module>();
825    if any_module.strip_prefix("dyn ") == Some(principal) {
826        path
827    } else {
828        principal
829    }
830}
831
832/// Strips a leading higher-ranked `for` binder from `s`, matching nested angle
833/// brackets while ignoring `->` in function types.
834fn strip_for_binder(s: &str) -> &str {
835    let Some(after_for) = s.strip_prefix("for") else {
836        return s;
837    };
838    let trimmed = after_for.trim_start();
839    if !trimmed.starts_with('<') {
840        return s;
841    }
842    let bytes = trimmed.as_bytes();
843    let mut depth = 0_usize;
844    let mut i = 0;
845    while i < bytes.len() {
846        match bytes[i] {
847            b'<' => depth += 1,
848            b'>' if i > 0 && bytes[i - 1] == b'-' => {}
849            b'>' => {
850                depth -= 1;
851                if depth == 0 {
852                    return trimmed[i + 1..].trim_start();
853                }
854            }
855            _ => {}
856        }
857        i += 1;
858    }
859    s
860}
861
862/// The principal trait before any top-level ` + ` auto-trait bounds in `s`,
863/// ignoring ` + ` inside angle brackets, parentheses or square brackets, and
864/// ignoring `->` when counting angle brackets.
865fn principal_trait(s: &str) -> &str {
866    let bytes = s.as_bytes();
867    let mut angles = 0_usize;
868    let mut parens = 0_usize;
869    let mut brackets = 0_usize;
870    let mut i = 0;
871    while i < bytes.len() {
872        match bytes[i] {
873            b'<' => angles += 1,
874            b'>' if i > 0 && bytes[i - 1] == b'-' => {}
875            b'>' => angles = angles.saturating_sub(1),
876            b'(' => parens += 1,
877            b')' => parens = parens.saturating_sub(1),
878            b'[' => brackets += 1,
879            b']' => brackets = brackets.saturating_sub(1),
880            b' ' if angles == 0
881                && parens == 0
882                && brackets == 0
883                && bytes[i..].starts_with(b" + ") =>
884            {
885                return s[..i].trim();
886            }
887            _ => {}
888        }
889        i += 1;
890    }
891    s.trim()
892}
893
894/// Whether the plugin `info`, whose modules have the types `type_names`, is
895/// first-party: `listed` pairs its name with a crate, it names that crate as
896/// its own, its version is `kernel_version`, and every module type, up to its
897/// first `<` and read through a reference ([`module_path`]), is a path of
898/// that crate (generic arguments do not count).
899///
900/// It reads names: a package whose library is named like a listed crate meets
901/// it, as `std::any::type_name` prints the library's name. The plugin rules
902/// hold a plugin to what it declares and are not a sandbox: a crate linked
903/// into the app runs with the app's rights.
904pub(crate) fn is_first_party(
905    info: &PluginInfo,
906    type_names: &[&str],
907    listed: &[(&str, &str)],
908    kernel_version: &str,
909) -> bool {
910    let Some(&(_, krate)) = listed.iter().find(|(package, _)| *package == info.name) else {
911        return false;
912    };
913    let path = format!("{krate}::");
914    info.crate_name == krate
915        && info.version == kernel_version
916        && type_names.iter().all(|type_name| {
917            let read = module_path(type_name);
918            let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
919            outer.starts_with(path.as_str())
920        })
921}
922
923/// Whether `bytes` starts with `prefix` (`<[u8]>::starts_with` in a `const fn`).
924const fn starts_with(bytes: &[u8], prefix: &[u8]) -> bool {
925    if bytes.len() < prefix.len() {
926        return false;
927    }
928    let mut index = 0;
929    while index < prefix.len() {
930        if bytes[index] != prefix[index] {
931            return false;
932        }
933        index += 1;
934    }
935    true
936}
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941
942    fn default_of(package: &str) -> String {
943        let (bytes, len) = default_namespace::<64>(package);
944        String::from_utf8(bytes[..len].to_vec()).expect("UTF-8")
945    }
946
947    #[test]
948    fn the_default_namespace_drops_the_navree_prefixes_and_turns_dashes_into_underscores() {
949        for (package, namespace) in [
950            ("navree-plugin-announcements", "announcements"),
951            ("navree-billing", "billing"),
952            ("navree-http-client", "http_client"),
953            ("acme-crm", "acme_crm"),
954            ("navree-plugin-notice-board", "notice_board"),
955            ("navree", "navree"),
956            ("navree_plugin_x", "navree_plugin_x"),
957            ("navree-plugin-2fa", "2fa"),
958            ("navree-plugin-", ""),
959        ] {
960            assert_eq!(default_of(package), namespace, "{package}");
961        }
962        assert!(!is_namespace("2fa") && !is_namespace(""));
963    }
964
965    #[test]
966    fn the_namespace_check_agrees_with_the_grammar() {
967        let longest = "a".repeat(64);
968        let too_long = "a".repeat(65);
969        for good in [
970            "a",
971            "announcements",
972            "notice_board",
973            "a1",
974            "ludhiana_2026",
975            longest.as_str(),
976        ] {
977            assert!(is_namespace(good), "{good}");
978        }
979        for bad in [
980            "",
981            "1a",
982            "_a",
983            "A",
984            "Announcements",
985            "a-b",
986            "a b",
987            "a.b",
988            "ਸੂਚਨਾ",
989            too_long.as_str(),
990        ] {
991            assert!(!is_namespace(bad), "{bad}");
992        }
993    }
994
995    #[test]
996    fn a_type_path_counts_for_a_crate_only_on_a_segment_boundary() {
997        assert!(names_crate("navree_plugin_a::T", "navree_plugin_a"));
998        assert!(!names_crate("x_navree_plugin_a::T", "navree_plugin_a"));
999        assert!(!names_crate("navree_plugin_ab::T", "navree_plugin_a"));
1000        assert!(!names_crate(
1001            "a::B<x_navree_plugin_a::T>",
1002            "navree_plugin_a"
1003        ));
1004        assert!(names_crate(
1005            "navree_config::client::ClientModule<reqwest::Client, navree_plugin_github::GithubOptions>",
1006            "navree_plugin_github"
1007        ));
1008        for shape in [
1009            "a::B<navree_plugin_a::T>",
1010            "&navree_plugin_a::T",
1011            "(u8, navree_plugin_a::T)",
1012            "[navree_plugin_a::T; 1]",
1013            "*const navree_plugin_a::T",
1014        ] {
1015            assert!(names_crate(shape, "navree_plugin_a"), "{shape}");
1016        }
1017    }
1018
1019    #[test]
1020    fn a_module_typed_as_a_reference_or_a_box_is_read_as_the_type_behind_it() {
1021        let helper = "navree_plugin_a::Helper";
1022        for type_name in [
1023            "navree_plugin_a::Helper",
1024            "&navree_plugin_a::Helper",
1025            "&mut navree_plugin_a::Helper",
1026            "*const navree_plugin_a::Helper",
1027            "alloc::boxed::Box<navree_plugin_a::Helper>",
1028            "&alloc::boxed::Box<core::pin::Pin<&navree_plugin_a::Helper>>",
1029        ] {
1030            assert_eq!(module_path(type_name), helper, "{type_name}");
1031        }
1032        // Another generic type is read as it is.
1033        assert_eq!(
1034            module_path("acme::Wrap<navree_plugin_a::Helper>"),
1035            "acme::Wrap<navree_plugin_a::Helper>"
1036        );
1037        // A trait object of a crate is read as its trait, with more bounds or without, in
1038        // parentheses or not, behind a reference, in a box or in a pin.
1039        for type_name in [
1040            "&dyn navree_plugin_a::Part",
1041            "&dyn navree_plugin_a::Part + core::marker::Sync",
1042            "&(dyn navree_plugin_a::Part + core::marker::Sync)",
1043            "alloc::boxed::Box<dyn navree_plugin_a::Part + core::marker::Send>",
1044            "core::pin::Pin<&dyn navree_plugin_a::Part>",
1045        ] {
1046            assert_eq!(
1047                module_path(type_name),
1048                "navree_plugin_a::Part",
1049                "{type_name}"
1050            );
1051        }
1052        // The kernel's own trait object is a module of any crate: it has no crate.
1053        assert_eq!(
1054            module_path("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
1055            "dyn navree_kernel::module::Module"
1056        );
1057        assert_eq!(
1058            module_path(std::any::type_name::<Box<dyn crate::Module>>()),
1059            std::any::type_name::<dyn crate::Module>()
1060        );
1061        // Higher-ranked trait objects and nested ` + ` or `->` inside generic arguments or
1062        // function parentheses peel cleanly to the principal trait.
1063        assert_eq!(
1064            module_path("&dyn for<'a> navree_plugin_khata::Part<'a>"),
1065            "navree_plugin_khata::Part<'a>"
1066        );
1067        assert_eq!(
1068            module_path(
1069                "alloc::boxed::Box<dyn for<'a> navree_plugin_khata::Part<fn(&'a str) -> &'a str> + core::marker::Send + core::marker::Sync>"
1070            ),
1071            "navree_plugin_khata::Part<fn(&'a str) -> &'a str>"
1072        );
1073        assert_eq!(
1074            module_path(
1075                "&dyn for<'a> navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str + core::marker::Sync"
1076            ),
1077            "navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str"
1078        );
1079        assert_eq!(
1080            module_path("&dyn forecast::Part + core::marker::Sync"),
1081            "forecast::Part"
1082        );
1083        assert_eq!(
1084            module_path(
1085                "alloc::boxed::Box<dyn for<'a> navree_kernel::module::Module + core::marker::Send>"
1086            ),
1087            "dyn for<'a> navree_kernel::module::Module + core::marker::Send"
1088        );
1089        // First-party reads the module's type the same way.
1090        let listed = [("navree-flags", "navree_flags")];
1091        let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
1092        let by_reference = ["&navree_flags::module::FlagsModule"];
1093        assert!(is_first_party(&flags, &by_reference, &listed, "1.3.0"));
1094    }
1095
1096    #[test]
1097    fn first_party_needs_a_listed_name_its_crate_the_kernels_version_and_a_type_of_that_crate() {
1098        let listed = [("navree-flags", "navree_flags")];
1099        let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
1100        let module = ["navree_flags::module::FlagsModule"];
1101        assert!(is_first_party(&flags, &module, &listed, "1.3.0"));
1102        assert!(
1103            !is_first_party(&flags, &module, &listed, "1.3.1"),
1104            "another version"
1105        );
1106        let elsewhere = PluginInfo::new("navree-flags", "acme_flags", "flags", "1.3.0");
1107        assert!(
1108            !is_first_party(&elsewhere, &module, &listed, "1.3.0"),
1109            "another crate named as the plugin's"
1110        );
1111        let unlisted = PluginInfo::new("navree-plugin-flags", "navree_flags", "flags", "1.3.0");
1112        assert!(
1113            !is_first_party(&unlisted, &module, &listed, "1.3.0"),
1114            "a name not on the list"
1115        );
1116        assert!(
1117            !is_first_party(
1118                &flags,
1119                &["acme::Wrap<navree_flags::module::FlagsModule>"],
1120                &listed,
1121                "1.3.0"
1122            ),
1123            "generic arguments do not count"
1124        );
1125        assert!(
1126            !is_first_party(
1127                &flags,
1128                &["navree_flags::module::FlagsModule", "acme::Extra"],
1129                &listed,
1130                "1.3.0"
1131            ),
1132            "every module of the plugin"
1133        );
1134        assert!(!is_first_party(
1135            &flags,
1136            &["navree_flags_extra::FlagsModule"],
1137            &listed,
1138            "1.3.0"
1139        ));
1140    }
1141
1142    #[test]
1143    fn the_kernels_lists_are_sorted_and_well_formed() {
1144        assert_eq!(FIRST_PARTY.len(), 31);
1145        assert!(FIRST_PARTY.windows(2).all(|w| w[0].0 < w[1].0));
1146        for (package, krate) in FIRST_PARTY {
1147            assert_eq!(package.replace('-', "_"), *krate);
1148            assert!(FRAMEWORK_CRATES.binary_search(krate).is_ok(), "{krate}");
1149            let (ns_bytes, ns_len) = default_namespace::<64>(package);
1150            let ns = std::str::from_utf8(&ns_bytes[..ns_len]).expect("UTF-8");
1151            assert!(
1152                RESERVED_NAMESPACES.binary_search(&ns).is_ok(),
1153                "{package}: `{ns}`"
1154            );
1155        }
1156        assert_eq!(FRAMEWORK_CRATES.len(), 75);
1157        assert!(FRAMEWORK_CRATES.windows(2).all(|w| w[0] < w[1]));
1158        assert!(is_framework_crate("navree_kernel::__private::PlainModule"));
1159        assert!(is_framework_crate("&navree_ui::module::UiModule"));
1160        assert!(is_framework_crate(
1161            "alloc::boxed::Box<navree_events::EventsModule>"
1162        ));
1163        assert!(!is_framework_crate(
1164            "alloc::boxed::Box<dyn navree_kernel::module::Module>"
1165        ));
1166        assert!(!is_framework_crate(
1167            "navree_plugin_khata_core::KhataCoreModule"
1168        ));
1169        assert!(
1170            std::any::type_name::<crate::ConfiguredModule<u8, ()>>()
1171                .starts_with("navree_kernel::module::ConfiguredModule<")
1172        );
1173        assert_eq!(
1174            module_crate("navree_ui::module::UiOnDemand"),
1175            Some("navree_ui")
1176        );
1177        assert_eq!(
1178            module_crate(
1179                "navree_kernel::module::ConfiguredModule<navree_cache::module::CacheModule, navree_cache::options::CacheOptions>"
1180            ),
1181            Some("navree_cache")
1182        );
1183        assert_eq!(
1184            module_crate(
1185                "navree_kernel::module::ConfiguredModule<plugins::Holder<fn(&str) -> &str>, ()>"
1186            ),
1187            Some("plugins")
1188        );
1189        assert_eq!(
1190            module_crate("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
1191            None
1192        );
1193        assert_eq!(RESERVED_NAMESPACES.len(), 88);
1194        assert!(RESERVED_NAMESPACES.windows(2).all(|w| w[0] < w[1]));
1195        assert!(RESERVED_NAMESPACES.iter().all(|ns| is_namespace(ns)));
1196        // Sorted, each name once, each a type path.
1197        assert!(APP_ONLY_PROVIDERS.windows(2).all(|w| w[0] < w[1]));
1198        assert!(APP_ONLY_PROVIDERS.iter().all(|name| name.contains("::")));
1199        assert!(MODEL_HOOK_KEY.starts_with("dyn ") && MODEL_HOOK_KEY.ends_with('<'));
1200    }
1201
1202    #[test]
1203    fn every_app_only_provider_says_what_it_does() {
1204        for provider in APP_ONLY_PROVIDERS {
1205            assert_ne!(app_only_role(provider), OTHER_ROLE, "{provider}");
1206        }
1207    }
1208
1209    #[test]
1210    fn the_advice_for_the_audit_sink_says_how_the_app_adds_it() {
1211        let registers = "and to use the plugin's, register it from a module of the app";
1212        for provider in APP_ONLY_PROVIDERS {
1213            let advice = app_only_advice(provider);
1214            if *provider == "dyn navree_contracts::audit::AuditSink" {
1215                assert_eq!(
1216                    advice,
1217                    "and to use the plugin's sink, add it from a module of the app (m.audit_sink, m.audit_sink_value or m.audit_sink_factory)"
1218                );
1219            } else {
1220                assert_eq!(advice, registers, "{provider}");
1221            }
1222        }
1223        // The refusal ends with the advice.
1224        let refused = crate::KernelError::PluginProvidesAppOnly {
1225            plugin: "navree-plugin-guard",
1226            provider: "dyn navree_contracts::audit::AuditSink",
1227            role: app_only_role("dyn navree_contracts::audit::AuditSink"),
1228            module: "Provides",
1229            reason: String::new(),
1230        }
1231        .to_string();
1232        assert_eq!(
1233            refused,
1234            "plugin `navree-plugin-guard` provides `dyn navree_contracts::audit::AuditSink` in `Provides`, which receives the app's audit records; only a module of the app registers it: remove the plugin or update it to a version that leaves it to the app, and to use the plugin's sink, add it from a module of the app (m.audit_sink, m.audit_sink_value or m.audit_sink_factory)"
1235        );
1236    }
1237
1238    /// A namespace is a folder name (`resources/views/<namespace>/`): every word the path
1239    /// rule refuses as a Windows device, and that the namespace grammar allows, is reserved.
1240    #[test]
1241    fn every_namespace_that_names_a_windows_device_is_reserved() {
1242        let mut devices = Vec::new();
1243        for stem in ["con", "prn", "aux", "nul", "com", "lpt"] {
1244            for end in ["", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] {
1245                let word = format!("{stem}{end}");
1246                if is_namespace(&word) && !crate::publish::is_safe_relative_path(&word) {
1247                    assert!(
1248                        RESERVED_NAMESPACES.contains(&word.as_str()),
1249                        "{word} is not reserved"
1250                    );
1251                    devices.push(word);
1252                }
1253            }
1254        }
1255        assert_eq!(devices.len(), 24, "{devices:?}");
1256        for folder in ["layouts", "fonts"] {
1257            assert!(RESERVED_NAMESPACES.contains(&folder), "{folder}");
1258        }
1259    }
1260
1261    #[test]
1262    fn publish_tags_name_their_folders_and_all_lists_three() {
1263        assert_eq!(
1264            PublishTag::ALL,
1265            &[PublishTag::Views, PublishTag::Locales, PublishTag::Files]
1266        );
1267        let names: Vec<&str> = PublishTag::ALL.iter().map(|tag| tag.as_str()).collect();
1268        assert_eq!(names, ["views", "locales", "files"]);
1269        for tag in PublishTag::ALL {
1270            assert_eq!(PublishTag::from_name(tag.as_str()), Some(*tag));
1271        }
1272        assert_eq!(PublishTag::from_name("config"), None);
1273        assert_eq!(PublishTag::from_name("Views"), None);
1274        assert_eq!(
1275            destination(PublishTag::Views, "announcements", "admin/list.html"),
1276            "resources/views/announcements/admin/list.html"
1277        );
1278        assert_eq!(
1279            destination(
1280                PublishTag::Locales,
1281                "announcements",
1282                "pa-IN/announcements.ftl",
1283            ),
1284            "locales/pa-IN/announcements/announcements.ftl"
1285        );
1286        assert_eq!(
1287            destination(PublishTag::Files, "announcements", "banner.css"),
1288            "resources/announcements/banner.css"
1289        );
1290        let files = Publishable::new(PublishTag::Views)
1291            .file("list.html", b"<ul></ul>")
1292            .file(String::from("show.html"), b"<p></p>");
1293        assert_eq!(files.tag(), PublishTag::Views);
1294        let listed: Vec<(&str, &[u8])> = files.files().collect();
1295        assert_eq!(
1296            listed,
1297            [
1298                ("list.html", &b"<ul></ul>"[..]),
1299                ("show.html", &b"<p></p>"[..]),
1300            ]
1301        );
1302    }
1303}