use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PluginInfo {
pub name: &'static str,
pub crate_name: &'static str,
pub namespace: &'static str,
pub version: &'static str,
pub title: Option<&'static str>,
pub description: Option<&'static str>,
pub homepage: Option<&'static str>,
pub repository: Option<&'static str>,
pub license: Option<&'static str>,
}
impl PluginInfo {
pub const fn new(
name: &'static str,
crate_name: &'static str,
namespace: &'static str,
version: &'static str,
) -> PluginInfo {
PluginInfo {
name,
crate_name,
namespace,
version,
title: None,
description: None,
homepage: None,
repository: None,
license: None,
}
}
pub const fn title(self, title: &'static str) -> PluginInfo {
PluginInfo {
title: non_empty(title),
..self
}
}
pub const fn description(self, description: &'static str) -> PluginInfo {
PluginInfo {
description: non_empty(description),
..self
}
}
pub const fn homepage(self, homepage: &'static str) -> PluginInfo {
PluginInfo {
homepage: non_empty(homepage),
..self
}
}
pub const fn repository(self, repository: &'static str) -> PluginInfo {
PluginInfo {
repository: non_empty(repository),
..self
}
}
pub const fn license(self, license: &'static str) -> PluginInfo {
PluginInfo {
license: non_empty(license),
..self
}
}
}
const fn non_empty(value: &'static str) -> Option<&'static str> {
if value.is_empty() { None } else { Some(value) }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum PublishTag {
Views,
Locales,
Files,
}
impl PublishTag {
pub const ALL: &'static [PublishTag] =
&[PublishTag::Views, PublishTag::Locales, PublishTag::Files];
pub const fn as_str(self) -> &'static str {
match self {
PublishTag::Views => "views",
PublishTag::Locales => "locales",
PublishTag::Files => "files",
}
}
pub fn from_name(name: &str) -> Option<PublishTag> {
PublishTag::ALL
.iter()
.copied()
.find(|tag| tag.as_str() == name)
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Publishable {
tag: PublishTag,
files: Vec<(Cow<'static, str>, &'static [u8])>,
}
impl Publishable {
pub fn new(tag: PublishTag) -> Publishable {
Publishable {
tag,
files: Vec::new(),
}
}
pub fn file(mut self, path: impl Into<Cow<'static, str>>, bytes: &'static [u8]) -> Publishable {
self.files.push((path.into(), bytes));
self
}
pub fn tag(&self) -> PublishTag {
self.tag
}
pub fn files(&self) -> impl Iterator<Item = (&str, &'static [u8])> {
self.files.iter().map(|(path, bytes)| (&**path, *bytes))
}
}
pub(crate) fn destination(tag: PublishTag, namespace: &str, path: &str) -> String {
match tag {
PublishTag::Views => format!("resources/views/{namespace}/{path}"),
PublishTag::Locales => {
let (locale, rest) = path.split_once('/').unwrap_or((path, ""));
format!("locales/{locale}/{namespace}/{rest}")
}
PublishTag::Files => format!("resources/{namespace}/{path}"),
}
}
#[macro_export]
macro_rules! plugin_info {
() => { $crate::plugin_info!(@default) };
(title = $title:literal $(,)?) => { $crate::plugin_info!(@default).title($title) };
(namespace = $namespace:literal $(,)?) => { $crate::plugin_info!(@given $namespace) };
(namespace = $namespace:literal, title = $title:literal $(,)?) => {
$crate::plugin_info!(@given $namespace).title($title)
};
(title = $title:literal, namespace = $namespace:literal $(,)?) => {
$crate::plugin_info!(@given $namespace).title($title)
};
(@default) => {{
const PACKAGE: &str = ::core::env!("CARGO_PKG_NAME");
const DEFAULT: ([u8; PACKAGE.len()], usize) =
$crate::__private::default_namespace::<{ PACKAGE.len() }>(PACKAGE);
const BYTES: &[u8] = &DEFAULT.0;
const NAMESPACE: &str = {
let namespace = $crate::__private::namespace_text(BYTES, DEFAULT.1);
::core::assert!(
$crate::__private::is_namespace(namespace),
"plugin_info!: this crate's name gives no valid namespace; set one with plugin_info!(namespace = \"..\")"
);
namespace
};
$crate::plugin_info!(@build NAMESPACE)
}};
(@given $namespace:literal) => {{
const NAMESPACE: &str = {
::core::assert!(
$crate::__private::is_namespace($namespace),
"plugin_info!: a namespace is a lower-case letter followed by up to 63 lower-case letters, digits or _"
);
$namespace
};
$crate::plugin_info!(@build NAMESPACE)
}};
(@build $namespace:expr) => {
$crate::PluginInfo::new(
::core::env!("CARGO_PKG_NAME"),
::core::env!("CARGO_CRATE_NAME"),
$namespace,
::core::env!("CARGO_PKG_VERSION"),
)
.description(::core::env!("CARGO_PKG_DESCRIPTION"))
.homepage(::core::env!("CARGO_PKG_HOMEPAGE"))
.repository(::core::env!("CARGO_PKG_REPOSITORY"))
.license(::core::env!("CARGO_PKG_LICENSE"))
};
($($other:tt)*) => {
::core::compile_error!("plugin_info!: unknown key; expected namespace = \"..\" or title = \"..\"")
};
}
pub const fn is_namespace(namespace: &str) -> bool {
let bytes = namespace.as_bytes();
if bytes.is_empty() || bytes.len() > 64 || !bytes[0].is_ascii_lowercase() {
return false;
}
let mut index = 1;
while index < bytes.len() {
match bytes[index] {
b'a'..=b'z' | b'0'..=b'9' | b'_' => index += 1,
_ => return false,
}
}
true
}
pub const fn default_namespace<const N: usize>(package: &str) -> ([u8; N], usize) {
let bytes = package.as_bytes();
let start = if starts_with(bytes, b"navree-plugin-") {
"navree-plugin-".len()
} else if starts_with(bytes, b"navree-") {
"navree-".len()
} else {
0
};
let mut namespace = [0_u8; N];
let mut index = start;
while index < bytes.len() {
namespace[index - start] = if bytes[index] == b'-' {
b'_'
} else {
bytes[index]
};
index += 1;
}
(namespace, bytes.len() - start)
}
pub const fn namespace_text(bytes: &'static [u8], len: usize) -> &'static str {
match core::str::from_utf8(bytes.split_at(len).0) {
Ok(text) => text,
Err(_) => panic!("plugin_info!: a package name is UTF-8"),
}
}
pub const FIRST_PARTY: &[(&str, &str)] = &[
("navree-ai", "navree_ai"),
("navree-audit", "navree_audit"),
("navree-billing", "navree_billing"),
("navree-directory", "navree_directory"),
("navree-documents", "navree_documents"),
("navree-domains", "navree_domains"),
("navree-flags", "navree_flags"),
("navree-fleet", "navree_fleet"),
("navree-graphql", "navree_graphql"),
("navree-grpc", "navree_grpc"),
("navree-helm", "navree_helm"),
("navree-http-client", "navree_http_client"),
("navree-i18n", "navree_i18n"),
("navree-integrations", "navree_integrations"),
("navree-mcp", "navree_mcp"),
("navree-media", "navree_media"),
("navree-micro", "navree_micro"),
("navree-mongo", "navree_mongo"),
("navree-notify", "navree_notify"),
("navree-oauth", "navree_oauth"),
("navree-realtime", "navree_realtime"),
("navree-redis", "navree_redis"),
("navree-search", "navree_search"),
("navree-settings", "navree_settings"),
("navree-sheets", "navree_sheets"),
("navree-social", "navree_social"),
("navree-sso", "navree_sso"),
("navree-storage", "navree_storage"),
("navree-time", "navree_time"),
("navree-webhooks", "navree_webhooks"),
("navree-workflows", "navree_workflows"),
];
pub const FRAMEWORK_CRATES: &[&str] = &[
"navree",
"navree_access",
"navree_ai",
"navree_api",
"navree_audit",
"navree_auth",
"navree_billing",
"navree_bounded",
"navree_browser",
"navree_cache",
"navree_cli",
"navree_config",
"navree_contracts",
"navree_crypto",
"navree_db",
"navree_directory",
"navree_dock",
"navree_documents",
"navree_domains",
"navree_events",
"navree_flags",
"navree_fleet",
"navree_glob",
"navree_graphql",
"navree_grpc",
"navree_harbor",
"navree_helm",
"navree_http",
"navree_http_client",
"navree_i18n",
"navree_integrations",
"navree_kernel",
"navree_lighthouse",
"navree_log",
"navree_logbook",
"navree_mail",
"navree_markdown",
"navree_mcp",
"navree_media",
"navree_micro",
"navree_mongo",
"navree_native",
"navree_native_core",
"navree_navigator",
"navree_notify",
"navree_oauth",
"navree_observe",
"navree_openapi",
"navree_orm",
"navree_pdf",
"navree_phone",
"navree_queue",
"navree_realtime",
"navree_redis",
"navree_schedule",
"navree_schema",
"navree_search",
"navree_session",
"navree_settings",
"navree_sheets",
"navree_social",
"navree_sso",
"navree_storage",
"navree_telemetry",
"navree_template",
"navree_template_peak",
"navree_testing",
"navree_time",
"navree_ui",
"navree_validation",
"navree_view",
"navree_webhooks",
"navree_workflows",
"navree_workspace",
];
pub(crate) fn is_framework_crate(type_name: &str) -> bool {
let read = module_path(type_name);
let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
let Some((krate, _)) = outer.split_once("::") else {
return false;
};
FRAMEWORK_CRATES.binary_search(&krate).is_ok()
}
pub(crate) fn module_crate(type_name: &str) -> Option<&str> {
let read = module_path(type_name);
let target = match read.strip_prefix("navree_kernel::module::ConfiguredModule<") {
Some(rest) => module_path(first_type_arg(rest)),
None => read,
};
if target.starts_with("dyn ") {
return None;
}
let outer = target.split_once('<').map_or(target, |(outer, _)| outer);
outer.split_once("::").map(|(krate, _)| krate)
}
fn first_type_arg(s: &str) -> &str {
let bytes = s.as_bytes();
let mut angles = 0_usize;
let mut parens = 0_usize;
let mut brackets = 0_usize;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'<' => angles += 1,
b'>' if i > 0 && bytes[i - 1] == b'-' => {}
b'>' if angles == 0 && parens == 0 && brackets == 0 => {
return s[..i].trim();
}
b'>' => angles = angles.saturating_sub(1),
b'(' => parens += 1,
b')' => parens = parens.saturating_sub(1),
b'[' => brackets += 1,
b']' => brackets = brackets.saturating_sub(1),
b',' if angles == 0 && parens == 0 && brackets == 0 => {
return s[..i].trim();
}
_ => {}
}
i += 1;
}
s.trim()
}
pub const RESERVED_NAMESPACES: &[&str] = &[
"ai",
"all",
"api",
"app",
"audit",
"auth",
"automations",
"aux",
"billing",
"cache",
"com0",
"com1",
"com2",
"com3",
"com4",
"com5",
"com6",
"com7",
"com8",
"com9",
"con",
"database",
"directory",
"documents",
"domains",
"env",
"flags",
"fleet",
"fonts",
"graphql",
"grpc",
"hashing",
"helm",
"http",
"http_client",
"i18n",
"integrations",
"layouts",
"lighthouse",
"log",
"logbook",
"lpt0",
"lpt1",
"lpt2",
"lpt3",
"lpt4",
"lpt5",
"lpt6",
"lpt7",
"lpt8",
"lpt9",
"mail",
"mcp",
"media",
"micro",
"mongo",
"navree",
"notify",
"nul",
"oauth",
"observe",
"operations",
"organization",
"orm",
"plugins",
"prn",
"queue",
"realtime",
"redis",
"roles",
"schema",
"search",
"session",
"settings",
"sheets",
"social",
"sso",
"storage",
"subscriptions",
"time",
"ui",
"users",
"validation",
"view",
"views",
"webhooks",
"workflows",
"workspace",
];
pub const APP_ONLY_PROVIDERS: &[&str] = &[
"dyn navree_access::workspace_gate::WorkspaceGate",
"dyn navree_auth::strategy::Strategy",
"dyn navree_contracts::audit::AuditSink",
"dyn navree_contracts::clock::Clock",
"dyn navree_contracts::permissions::PermissionCheck",
"dyn navree_db::uow::ChangeObserver",
"dyn navree_http::auth::Authenticator",
"dyn navree_http::auth::RouteAuthorizer",
"dyn navree_mongo::uow::MongoChangeObserver",
"dyn navree_realtime::backplane::Backplane",
"dyn navree_ui::shell::contribute::NativeShellPart",
"navree_access::factory::AbilityFactory",
"navree_access::options::AccessOptions",
"navree_auth::options::AuthOptions",
"navree_helm::options::HelmOptions",
"navree_orm::events::fake::ModelEventFake",
"navree_ui::shell::Shell",
"navree_workspace::config::WorkspaceConfig",
];
pub(crate) fn app_only_role(provider: &str) -> &'static str {
match provider {
"dyn navree_access::workspace_gate::WorkspaceGate" => {
"which decides who enters the app's workspaces"
}
"dyn navree_auth::strategy::Strategy" => "which signs requests in",
"dyn navree_contracts::audit::AuditSink" => "which receives the app's audit records",
"dyn navree_contracts::clock::Clock" => {
"which sets the time the app's sessions, signed links and invitations expire by"
}
"dyn navree_contracts::permissions::PermissionCheck" => {
"which answers the app's permission checks"
}
"dyn navree_db::uow::ChangeObserver" => {
"which sees, and can change, every write the app commits"
}
"dyn navree_http::auth::Authenticator" => "which decides who a request is signed in as",
"dyn navree_http::auth::RouteAuthorizer" => "which decides who may open the app's routes",
"dyn navree_mongo::uow::MongoChangeObserver" => {
"which sees, and can change, every MongoDB write the app commits"
}
"dyn navree_realtime::backplane::Backplane" => {
"which carries every broadcast of the app's channels between its processes"
}
"dyn navree_ui::shell::contribute::NativeShellPart" => {
"which says where the app's native clients sign in"
}
"navree_access::factory::AbilityFactory" => "which builds every user's abilities",
"navree_access::options::AccessOptions" => {
"which sets the options of the app's access rules"
}
"navree_auth::options::AuthOptions" => "which sets the options of the app's sign-in",
"navree_helm::options::HelmOptions" => "which sets the options of the app's admin panel",
"navree_orm::events::fake::ModelEventFake" => {
"which silences the listeners of every model of the app"
}
"navree_ui::shell::Shell" => "which is the app's shell",
"navree_workspace::config::WorkspaceConfig" => {
"which sets the options of the app's workspaces"
}
_ => OTHER_ROLE,
}
}
const OTHER_ROLE: &str = "which decides who may do what in the app";
pub(crate) fn app_only_advice(provider: &str) -> &'static str {
match provider {
"dyn navree_contracts::audit::AuditSink" => {
"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)"
}
_ => "and to use the plugin's, register it from a module of the app",
}
}
pub const MODEL_HOOK_KEY: &str = "dyn navree_orm::hooks::ModelHook<";
pub(crate) fn names_crate(type_name: &str, crate_name: &str) -> bool {
let path = format!("{crate_name}::");
type_name.match_indices(path.as_str()).any(|(at, _)| {
at == 0
|| matches!(
type_name.as_bytes()[at - 1],
b'<' | b',' | b' ' | b'(' | b'[' | b'&' | b'*'
)
})
}
pub(crate) fn module_path(type_name: &str) -> &str {
let mut path = type_name.trim();
loop {
let current = path;
let behind = ["&mut ", "&", "*const ", "*mut "]
.iter()
.find_map(move |marker| current.strip_prefix(*marker));
let inside = ["alloc::boxed::Box<", "core::pin::Pin<"]
.iter()
.find_map(move |wrapper| current.strip_prefix(*wrapper)?.strip_suffix('>'));
let grouped = current
.strip_prefix('(')
.and_then(|inner| inner.strip_suffix(')'));
match behind.or(inside).or(grouped) {
Some(inner) => path = inner.trim(),
None => return object_trait(path),
}
}
}
fn object_trait(path: &str) -> &str {
let Some(object) = path.strip_prefix("dyn ") else {
return path;
};
let unquantified = strip_for_binder(object.trim_start());
let principal = principal_trait(unquantified);
let any_module = std::any::type_name::<dyn crate::Module>();
if any_module.strip_prefix("dyn ") == Some(principal) {
path
} else {
principal
}
}
fn strip_for_binder(s: &str) -> &str {
let Some(after_for) = s.strip_prefix("for") else {
return s;
};
let trimmed = after_for.trim_start();
if !trimmed.starts_with('<') {
return s;
}
let bytes = trimmed.as_bytes();
let mut depth = 0_usize;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'<' => depth += 1,
b'>' if i > 0 && bytes[i - 1] == b'-' => {}
b'>' => {
depth -= 1;
if depth == 0 {
return trimmed[i + 1..].trim_start();
}
}
_ => {}
}
i += 1;
}
s
}
fn principal_trait(s: &str) -> &str {
let bytes = s.as_bytes();
let mut angles = 0_usize;
let mut parens = 0_usize;
let mut brackets = 0_usize;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'<' => angles += 1,
b'>' if i > 0 && bytes[i - 1] == b'-' => {}
b'>' => angles = angles.saturating_sub(1),
b'(' => parens += 1,
b')' => parens = parens.saturating_sub(1),
b'[' => brackets += 1,
b']' => brackets = brackets.saturating_sub(1),
b' ' if angles == 0
&& parens == 0
&& brackets == 0
&& bytes[i..].starts_with(b" + ") =>
{
return s[..i].trim();
}
_ => {}
}
i += 1;
}
s.trim()
}
pub(crate) fn is_first_party(
info: &PluginInfo,
type_names: &[&str],
listed: &[(&str, &str)],
kernel_version: &str,
) -> bool {
let Some(&(_, krate)) = listed.iter().find(|(package, _)| *package == info.name) else {
return false;
};
let path = format!("{krate}::");
info.crate_name == krate
&& info.version == kernel_version
&& type_names.iter().all(|type_name| {
let read = module_path(type_name);
let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
outer.starts_with(path.as_str())
})
}
const fn starts_with(bytes: &[u8], prefix: &[u8]) -> bool {
if bytes.len() < prefix.len() {
return false;
}
let mut index = 0;
while index < prefix.len() {
if bytes[index] != prefix[index] {
return false;
}
index += 1;
}
true
}
#[cfg(test)]
mod tests {
use super::*;
fn default_of(package: &str) -> String {
let (bytes, len) = default_namespace::<64>(package);
String::from_utf8(bytes[..len].to_vec()).expect("UTF-8")
}
#[test]
fn the_default_namespace_drops_the_navree_prefixes_and_turns_dashes_into_underscores() {
for (package, namespace) in [
("navree-plugin-announcements", "announcements"),
("navree-billing", "billing"),
("navree-http-client", "http_client"),
("acme-crm", "acme_crm"),
("navree-plugin-notice-board", "notice_board"),
("navree", "navree"),
("navree_plugin_x", "navree_plugin_x"),
("navree-plugin-2fa", "2fa"),
("navree-plugin-", ""),
] {
assert_eq!(default_of(package), namespace, "{package}");
}
assert!(!is_namespace("2fa") && !is_namespace(""));
}
#[test]
fn the_namespace_check_agrees_with_the_grammar() {
let longest = "a".repeat(64);
let too_long = "a".repeat(65);
for good in [
"a",
"announcements",
"notice_board",
"a1",
"ludhiana_2026",
longest.as_str(),
] {
assert!(is_namespace(good), "{good}");
}
for bad in [
"",
"1a",
"_a",
"A",
"Announcements",
"a-b",
"a b",
"a.b",
"ਸੂਚਨਾ",
too_long.as_str(),
] {
assert!(!is_namespace(bad), "{bad}");
}
}
#[test]
fn a_type_path_counts_for_a_crate_only_on_a_segment_boundary() {
assert!(names_crate("navree_plugin_a::T", "navree_plugin_a"));
assert!(!names_crate("x_navree_plugin_a::T", "navree_plugin_a"));
assert!(!names_crate("navree_plugin_ab::T", "navree_plugin_a"));
assert!(!names_crate(
"a::B<x_navree_plugin_a::T>",
"navree_plugin_a"
));
assert!(names_crate(
"navree_config::client::ClientModule<reqwest::Client, navree_plugin_github::GithubOptions>",
"navree_plugin_github"
));
for shape in [
"a::B<navree_plugin_a::T>",
"&navree_plugin_a::T",
"(u8, navree_plugin_a::T)",
"[navree_plugin_a::T; 1]",
"*const navree_plugin_a::T",
] {
assert!(names_crate(shape, "navree_plugin_a"), "{shape}");
}
}
#[test]
fn a_module_typed_as_a_reference_or_a_box_is_read_as_the_type_behind_it() {
let helper = "navree_plugin_a::Helper";
for type_name in [
"navree_plugin_a::Helper",
"&navree_plugin_a::Helper",
"&mut navree_plugin_a::Helper",
"*const navree_plugin_a::Helper",
"alloc::boxed::Box<navree_plugin_a::Helper>",
"&alloc::boxed::Box<core::pin::Pin<&navree_plugin_a::Helper>>",
] {
assert_eq!(module_path(type_name), helper, "{type_name}");
}
assert_eq!(
module_path("acme::Wrap<navree_plugin_a::Helper>"),
"acme::Wrap<navree_plugin_a::Helper>"
);
for type_name in [
"&dyn navree_plugin_a::Part",
"&dyn navree_plugin_a::Part + core::marker::Sync",
"&(dyn navree_plugin_a::Part + core::marker::Sync)",
"alloc::boxed::Box<dyn navree_plugin_a::Part + core::marker::Send>",
"core::pin::Pin<&dyn navree_plugin_a::Part>",
] {
assert_eq!(
module_path(type_name),
"navree_plugin_a::Part",
"{type_name}"
);
}
assert_eq!(
module_path("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
"dyn navree_kernel::module::Module"
);
assert_eq!(
module_path(std::any::type_name::<Box<dyn crate::Module>>()),
std::any::type_name::<dyn crate::Module>()
);
assert_eq!(
module_path("&dyn for<'a> navree_plugin_khata::Part<'a>"),
"navree_plugin_khata::Part<'a>"
);
assert_eq!(
module_path(
"alloc::boxed::Box<dyn for<'a> navree_plugin_khata::Part<fn(&'a str) -> &'a str> + core::marker::Send + core::marker::Sync>"
),
"navree_plugin_khata::Part<fn(&'a str) -> &'a str>"
);
assert_eq!(
module_path(
"&dyn for<'a> navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str + core::marker::Sync"
),
"navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str"
);
assert_eq!(
module_path("&dyn forecast::Part + core::marker::Sync"),
"forecast::Part"
);
assert_eq!(
module_path(
"alloc::boxed::Box<dyn for<'a> navree_kernel::module::Module + core::marker::Send>"
),
"dyn for<'a> navree_kernel::module::Module + core::marker::Send"
);
let listed = [("navree-flags", "navree_flags")];
let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
let by_reference = ["&navree_flags::module::FlagsModule"];
assert!(is_first_party(&flags, &by_reference, &listed, "1.3.0"));
}
#[test]
fn first_party_needs_a_listed_name_its_crate_the_kernels_version_and_a_type_of_that_crate() {
let listed = [("navree-flags", "navree_flags")];
let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
let module = ["navree_flags::module::FlagsModule"];
assert!(is_first_party(&flags, &module, &listed, "1.3.0"));
assert!(
!is_first_party(&flags, &module, &listed, "1.3.1"),
"another version"
);
let elsewhere = PluginInfo::new("navree-flags", "acme_flags", "flags", "1.3.0");
assert!(
!is_first_party(&elsewhere, &module, &listed, "1.3.0"),
"another crate named as the plugin's"
);
let unlisted = PluginInfo::new("navree-plugin-flags", "navree_flags", "flags", "1.3.0");
assert!(
!is_first_party(&unlisted, &module, &listed, "1.3.0"),
"a name not on the list"
);
assert!(
!is_first_party(
&flags,
&["acme::Wrap<navree_flags::module::FlagsModule>"],
&listed,
"1.3.0"
),
"generic arguments do not count"
);
assert!(
!is_first_party(
&flags,
&["navree_flags::module::FlagsModule", "acme::Extra"],
&listed,
"1.3.0"
),
"every module of the plugin"
);
assert!(!is_first_party(
&flags,
&["navree_flags_extra::FlagsModule"],
&listed,
"1.3.0"
));
}
#[test]
fn the_kernels_lists_are_sorted_and_well_formed() {
assert_eq!(FIRST_PARTY.len(), 31);
assert!(FIRST_PARTY.windows(2).all(|w| w[0].0 < w[1].0));
for (package, krate) in FIRST_PARTY {
assert_eq!(package.replace('-', "_"), *krate);
assert!(FRAMEWORK_CRATES.binary_search(krate).is_ok(), "{krate}");
let (ns_bytes, ns_len) = default_namespace::<64>(package);
let ns = std::str::from_utf8(&ns_bytes[..ns_len]).expect("UTF-8");
assert!(
RESERVED_NAMESPACES.binary_search(&ns).is_ok(),
"{package}: `{ns}`"
);
}
assert_eq!(FRAMEWORK_CRATES.len(), 74);
assert!(FRAMEWORK_CRATES.windows(2).all(|w| w[0] < w[1]));
assert!(is_framework_crate("navree_kernel::__private::PlainModule"));
assert!(is_framework_crate("&navree_ui::module::UiModule"));
assert!(is_framework_crate(
"alloc::boxed::Box<navree_events::EventsModule>"
));
assert!(!is_framework_crate(
"alloc::boxed::Box<dyn navree_kernel::module::Module>"
));
assert!(!is_framework_crate(
"navree_plugin_khata_core::KhataCoreModule"
));
assert!(
std::any::type_name::<crate::ConfiguredModule<u8, ()>>()
.starts_with("navree_kernel::module::ConfiguredModule<")
);
assert_eq!(
module_crate("navree_ui::module::UiOnDemand"),
Some("navree_ui")
);
assert_eq!(
module_crate(
"navree_kernel::module::ConfiguredModule<navree_cache::module::CacheModule, navree_cache::options::CacheOptions>"
),
Some("navree_cache")
);
assert_eq!(
module_crate(
"navree_kernel::module::ConfiguredModule<plugins::Holder<fn(&str) -> &str>, ()>"
),
Some("plugins")
);
assert_eq!(
module_crate("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
None
);
assert_eq!(RESERVED_NAMESPACES.len(), 88);
assert!(RESERVED_NAMESPACES.windows(2).all(|w| w[0] < w[1]));
assert!(RESERVED_NAMESPACES.iter().all(|ns| is_namespace(ns)));
assert!(APP_ONLY_PROVIDERS.windows(2).all(|w| w[0] < w[1]));
assert!(APP_ONLY_PROVIDERS.iter().all(|name| name.contains("::")));
assert!(MODEL_HOOK_KEY.starts_with("dyn ") && MODEL_HOOK_KEY.ends_with('<'));
}
#[test]
fn every_app_only_provider_says_what_it_does() {
for provider in APP_ONLY_PROVIDERS {
assert_ne!(app_only_role(provider), OTHER_ROLE, "{provider}");
}
}
#[test]
fn the_advice_for_the_audit_sink_says_how_the_app_adds_it() {
let registers = "and to use the plugin's, register it from a module of the app";
for provider in APP_ONLY_PROVIDERS {
let advice = app_only_advice(provider);
if *provider == "dyn navree_contracts::audit::AuditSink" {
assert_eq!(
advice,
"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)"
);
} else {
assert_eq!(advice, registers, "{provider}");
}
}
let refused = crate::KernelError::PluginProvidesAppOnly {
plugin: "navree-plugin-guard",
provider: "dyn navree_contracts::audit::AuditSink",
role: app_only_role("dyn navree_contracts::audit::AuditSink"),
module: "Provides",
reason: String::new(),
}
.to_string();
assert_eq!(
refused,
"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)"
);
}
#[test]
fn every_namespace_that_names_a_windows_device_is_reserved() {
let mut devices = Vec::new();
for stem in ["con", "prn", "aux", "nul", "com", "lpt"] {
for end in ["", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] {
let word = format!("{stem}{end}");
if is_namespace(&word) && !crate::publish::is_safe_relative_path(&word) {
assert!(
RESERVED_NAMESPACES.contains(&word.as_str()),
"{word} is not reserved"
);
devices.push(word);
}
}
}
assert_eq!(devices.len(), 24, "{devices:?}");
for folder in ["layouts", "fonts"] {
assert!(RESERVED_NAMESPACES.contains(&folder), "{folder}");
}
}
#[test]
fn publish_tags_name_their_folders_and_all_lists_three() {
assert_eq!(
PublishTag::ALL,
&[PublishTag::Views, PublishTag::Locales, PublishTag::Files]
);
let names: Vec<&str> = PublishTag::ALL.iter().map(|tag| tag.as_str()).collect();
assert_eq!(names, ["views", "locales", "files"]);
for tag in PublishTag::ALL {
assert_eq!(PublishTag::from_name(tag.as_str()), Some(*tag));
}
assert_eq!(PublishTag::from_name("config"), None);
assert_eq!(PublishTag::from_name("Views"), None);
assert_eq!(
destination(PublishTag::Views, "announcements", "admin/list.html"),
"resources/views/announcements/admin/list.html"
);
assert_eq!(
destination(
PublishTag::Locales,
"announcements",
"pa-IN/announcements.ftl",
),
"locales/pa-IN/announcements/announcements.ftl"
);
assert_eq!(
destination(PublishTag::Files, "announcements", "banner.css"),
"resources/announcements/banner.css"
);
let files = Publishable::new(PublishTag::Views)
.file("list.html", b"<ul></ul>")
.file(String::from("show.html"), b"<p></p>");
assert_eq!(files.tag(), PublishTag::Views);
let listed: Vec<(&str, &[u8])> = files.files().collect();
assert_eq!(
listed,
[
("list.html", &b"<ul></ul>"[..]),
("show.html", &b"<p></p>"[..]),
]
);
}
}