Skip to main content

appstruct_compiler/
preset.rs

1mod lock;
2
3pub use lock::ProjectLayout;
4
5use crate::surface::{SurfacePreset, SurfaceRoot};
6use crate::yaml::{self, MappingEntry, Node, NodeKind};
7use appstruct_ir::Diagnostic;
8use std::fmt::Write;
9use std::path::Path;
10
11const SAAS_NAME: &str = "appstruct/saas";
12const SAAS_VERSION: u64 = 1;
13pub(super) const MODULE_VERSION: &str = env!("CARGO_PKG_VERSION");
14pub const CURRENT_PROJECT_LAYOUT_VERSION: u64 = appstruct_contracts::PROJECT_LAYOUT.current as u64;
15const MODULES: &[&str] = &["audit", "auth", "file", "jobs", "mail", "rbac", "tenant"];
16const EXPANDED: &str = concat!(
17    "modules:\n",
18    "  auth:\n",
19    "    enabled: true\n",
20    "    user_entity: User\n",
21    "    registration: true\n",
22    "    password_reset: true\n",
23    "  rbac:\n",
24    "    roles: [member, admin]\n",
25    "    default_role: member\n",
26    "  tenant:\n",
27    "    enabled: true\n",
28    "  audit:\n",
29    "    enabled: true\n",
30    "    reader_roles: [admin]\n",
31    "  mail:\n",
32    "    enabled: true\n",
33    "    provider: capture\n",
34    "    from: \"AppStruct <notifications@example.com>\"\n",
35    "    templates:\n",
36    "      invitation:\n",
37    "        subject: \"You are invited to {{ organization_name }}\"\n",
38    "        text: \"Accept your invitation to join {{ organization_name }}.\"\n",
39    "      welcome:\n",
40    "        subject: \"Welcome {{ recipient_name }}\"\n",
41    "        text: \"Your AppStruct workspace is ready.\"\n",
42    "  jobs:\n",
43    "    enabled: true\n",
44    "    poll_interval_ms: 250\n",
45    "    lease_seconds: 30\n",
46    "    queues:\n",
47    "      default: { max_attempts: 5, backoff_seconds: 2 }\n",
48    "      mail: { max_attempts: 8, backoff_seconds: 5 }\n",
49    "  file:\n",
50    "    enabled: true\n",
51    "    provider: local\n",
52    "    local_root: .appstruct/files\n",
53    "    max_bytes: 10485760\n",
54    "    allowed_content_types: [text/plain, application/json, image/png, image/jpeg]\n",
55);
56
57#[derive(Clone, Debug)]
58pub struct PresetInfo {
59    pub name: &'static str,
60    pub version: u64,
61    pub digest: String,
62    pub modules: &'static [&'static str],
63    pub defaults: &'static str,
64}
65
66#[must_use]
67pub fn preset_info(name: &str, version: u64) -> Option<PresetInfo> {
68    supported(name, version).then(|| PresetInfo {
69        name: SAAS_NAME,
70        version: SAAS_VERSION,
71        digest: preset_digest(),
72        modules: MODULES,
73        defaults: EXPANDED,
74    })
75}
76
77pub(crate) fn preset_digest() -> String {
78    appstruct_core::sha256_tagged(EXPANDED.as_bytes())
79}
80
81/// Build the canonical project lock used by official templates.
82#[must_use]
83pub fn project_lock(template: &str, preset: Option<(&str, u64)>) -> Option<String> {
84    lock::source(template, preset, ProjectLayout::CompositionRoot, &[])
85}
86
87/// Read the explicit project layout contract used by build and development commands.
88///
89/// # Errors
90///
91/// Returns a diagnostic for invalid, unversioned, or unsupported project locks. Lockless custom
92/// projects use the current composition-root layout.
93pub fn project_layout(project: &Path) -> Result<ProjectLayout, Diagnostic> {
94    lock::layout(project)
95}
96
97pub(crate) fn expand_modules(
98    preset: Option<&SurfacePreset>,
99    overrides: Option<&MappingEntry>,
100) -> Result<Option<MappingEntry>, Diagnostic> {
101    let Some(preset) = preset else {
102        return Ok(overrides.cloned());
103    };
104    if !supported(&preset.name.value, preset.version.value) {
105        return Ok(overrides.cloned());
106    }
107    let defaults = yaml::parse("<preset appstruct/saas@1>", EXPANDED)?;
108    let mut modules = defaults
109        .mapping()
110        .and_then(|mapping| mapping.get("modules"))
111        .cloned()
112        .expect("official preset must contain modules");
113    if let Some(overrides) = overrides {
114        merge(&mut modules.value, &overrides.value);
115    }
116    Ok(Some(modules))
117}
118
119fn merge(defaults: &mut Node, overrides: &Node) {
120    match (&mut defaults.kind, &overrides.kind) {
121        (NodeKind::Mapping(defaults), NodeKind::Mapping(overrides)) => {
122            for (key, value) in overrides {
123                if let Some(default) = defaults.get_mut(key) {
124                    merge(&mut default.value, &value.value);
125                    default.key_span = value.key_span.clone();
126                } else {
127                    defaults.insert(key.clone(), value.clone());
128                }
129            }
130        }
131        _ => *defaults = overrides.clone(),
132    }
133}
134
135pub(crate) fn validate_lock(project: &Path, root: &SurfaceRoot) -> Vec<Diagnostic> {
136    lock::validate(project, root)
137}
138
139pub(crate) fn validate_local_module_lock(
140    project: &Path,
141    local_modules: &[crate::module::LoadedModule],
142) -> Vec<Diagnostic> {
143    lock::validate_local_modules(project, local_modules)
144}
145
146pub(crate) fn updated_lock(
147    project: &Path,
148    root: &SurfaceRoot,
149    local_modules: &[crate::module::LoadedModule],
150) -> Result<String, Diagnostic> {
151    lock::updated_source(project, root, local_modules)
152}
153
154pub(crate) fn render_expanded_modules(modules: &MappingEntry) -> String {
155    let mut output = "modules:\n".to_owned();
156    render_node(&modules.value, 2, &mut output);
157    output
158}
159
160fn supported(name: &str, version: u64) -> bool {
161    name == SAAS_NAME && version == SAAS_VERSION
162}
163
164fn render_node(node: &Node, indent: usize, output: &mut String) {
165    match &node.kind {
166        NodeKind::Mapping(entries) => {
167            for (key, entry) in entries {
168                let _ = write!(output, "{}{key}:", " ".repeat(indent));
169                match entry.value.kind {
170                    NodeKind::Scalar { .. } => {
171                        output.push(' ');
172                        render_scalar(&entry.value, output);
173                        output.push('\n');
174                    }
175                    NodeKind::Mapping(ref entries) if entries.is_empty() => {
176                        output.push_str(" {}\n");
177                    }
178                    NodeKind::Sequence(ref items)
179                        if items
180                            .iter()
181                            .all(|item| matches!(item.kind, NodeKind::Scalar { .. })) =>
182                    {
183                        output.push_str(" [");
184                        for (index, item) in items.iter().enumerate() {
185                            if index > 0 {
186                                output.push_str(", ");
187                            }
188                            render_scalar(item, output);
189                        }
190                        output.push_str("]\n");
191                    }
192                    _ => {
193                        output.push('\n');
194                        render_node(&entry.value, indent + 2, output);
195                    }
196                }
197            }
198        }
199        NodeKind::Sequence(items) => {
200            for item in items {
201                let _ = write!(output, "{}- ", " ".repeat(indent));
202                if matches!(item.kind, NodeKind::Scalar { .. }) {
203                    render_scalar(item, output);
204                    output.push('\n');
205                } else {
206                    output.push('\n');
207                    render_node(item, indent + 2, output);
208                }
209            }
210        }
211        NodeKind::Scalar { .. } => {
212            let _ = write!(output, "{}", " ".repeat(indent));
213            render_scalar(node, output);
214            output.push('\n');
215        }
216    }
217}
218
219fn render_scalar(node: &Node, output: &mut String) {
220    let Some((value, plain)) = node.scalar() else {
221        return;
222    };
223    if plain && !value.is_empty() {
224        output.push_str(value);
225    } else {
226        output.push('"');
227        for character in value.chars() {
228            match character {
229                '"' => output.push_str("\\\""),
230                '\\' => output.push_str("\\\\"),
231                '\n' => output.push_str("\\n"),
232                '\r' => output.push_str("\\r"),
233                '\t' => output.push_str("\\t"),
234                other => output.push(other),
235            }
236        }
237        output.push('"');
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn official_preset_digest_is_stable() {
247        assert_eq!(
248            preset_digest(),
249            "sha256:7267c3a362b328d5b162f4536ac7115c72ab81cf9f3e17542a8d9b6eba7965c5"
250        );
251    }
252}