Skip to main content

appstruct_compiler/
lib.rs

1//! `AppStruct` configuration loading, validation, and normalization.
2
3mod access;
4mod activity;
5mod audit;
6mod auth;
7mod billing;
8mod extension;
9mod field;
10mod field_options;
11mod file;
12mod jobs;
13mod lint;
14mod loading;
15mod lower;
16mod mail;
17mod module;
18mod module_registry;
19mod preset;
20mod realtime;
21mod report;
22mod server;
23mod surface;
24mod tenant;
25mod validation;
26mod webhooks;
27mod workflow;
28mod yaml;
29
30pub use loading::discover_project;
31pub use preset::{
32    CURRENT_PROJECT_LAYOUT_VERSION, PresetInfo, ProjectLayout, preset_info, project_layout,
33    project_lock,
34};
35
36/// Draft 2020-12 schema for root and domain App Spec YAML documents.
37pub const APP_SPEC_SCHEMA: &str = include_str!("../schema/appstruct.schema.json");
38
39#[derive(Clone, Debug)]
40pub struct CompileReport {
41    pub ir: AppIr,
42    pub diagnostics: Vec<Diagnostic>,
43}
44
45use appstruct_ir::{AppIr, Diagnostic, SourceSpan};
46use std::collections::BTreeMap;
47use std::fs;
48use std::path::{Path, PathBuf};
49
50/// Compile a project root into normalized, deterministically ordered IR.
51///
52/// # Errors
53///
54/// Returns all diagnostics found during path resolution and semantic validation. YAML shape errors
55/// are reported per source before semantic validation starts.
56pub fn compile_project(project_root: &Path) -> Result<AppIr, Vec<Diagnostic>> {
57    compile_project_report(project_root).map(|report| report.ir)
58}
59
60/// Compile a project and retain non-fatal diagnostics for CLI and CI policy.
61///
62/// # Errors
63///
64/// Returns all fatal diagnostics found during loading and semantic validation.
65pub fn compile_project_report(project_root: &Path) -> Result<CompileReport, Vec<Diagnostic>> {
66    compile_with_domain(project_root, None)
67}
68
69/// Compile a proposed domain and its include entirely in memory, without changing the project.
70///
71/// # Errors
72///
73/// Returns normal compiler diagnostics, or rejects a non-relative or ambiguous domain path.
74pub fn compile_project_with_domain(
75    project_root: &Path,
76    relative: &Path,
77    source: &str,
78) -> Result<CompileReport, Vec<Diagnostic>> {
79    if relative.as_os_str().is_empty()
80        || relative
81            .components()
82            .any(|part| !matches!(part, std::path::Component::Normal(_)))
83        || relative.to_str().is_none()
84        || !matches!(
85            relative.extension().and_then(|value| value.to_str()),
86            Some("yaml" | "yml")
87        )
88    {
89        return Err(vec![Diagnostic::error(
90            "AS1010",
91            "preview domain must have a project-relative YAML path",
92            loading::synthetic_span("appstruct.yaml"),
93        )]);
94    }
95    compile_with_domain(project_root, Some((relative, source)))
96}
97
98fn compile_with_domain(
99    project_root: &Path,
100    proposed: Option<(&Path, &str)>,
101) -> Result<CompileReport, Vec<Diagnostic>> {
102    let root = canonical_project_root(project_root)?;
103    let root_node = loading::load_yaml(&root, &root.join("appstruct.yaml"))?;
104    let mut surface_root = surface::decode_root(&root_node)?;
105    if let Some((relative, _)) = proposed
106        && !surface_root
107            .includes
108            .iter()
109            .any(|include| Path::new(&include.value) == relative)
110    {
111        surface_root.includes.push(surface::Located {
112            value: relative.to_string_lossy().into_owned(),
113            span: loading::synthetic_span("appstruct.yaml"),
114        });
115    }
116    let mut diagnostics = validation::validate_root(&surface_root);
117    diagnostics.extend(preset::validate_lock(&root, &surface_root));
118    let (local_modules, module_diagnostics) =
119        module::load_local_modules(&root, &surface_root.module_manifests);
120    if module_diagnostics.is_empty() {
121        diagnostics.extend(preset::validate_local_module_lock(&root, &local_modules));
122    }
123    diagnostics.extend(module_diagnostics);
124    let (remote_modules, remote_diagnostics) = module_registry::load(&root);
125    diagnostics.extend(remote_diagnostics);
126    let mut canonical_includes = BTreeMap::<PathBuf, SourceSpan>::new();
127    let mut application = surface::SurfaceDomain::default();
128
129    for include in &surface_root.includes {
130        let override_source =
131            proposed.filter(|(relative, _)| *relative == Path::new(&include.value));
132        let resolved = override_source.map_or_else(
133            || loading::resolve_include(&root, include),
134            |(relative, _)| Ok(root.join(relative)),
135        );
136        let include_path = match resolved {
137            Ok(path) => path,
138            Err(error) => {
139                diagnostics.push(error);
140                continue;
141            }
142        };
143        if let Some(first_span) =
144            canonical_includes.insert(include_path.clone(), include.span.clone())
145        {
146            diagnostics.push(
147                Diagnostic::error(
148                    "AS1009",
149                    format!("duplicate include `{}`", include.value),
150                    include.span.clone(),
151                )
152                .with_secondary(first_span, "first included here"),
153            );
154            continue;
155        }
156
157        let domain_node = override_source.map_or_else(
158            || loading::load_yaml(&root, &include_path),
159            |(_, source)| yaml::parse(&include.value, source).map_err(|error| vec![error]),
160        );
161        match domain_node.and_then(|node| surface::decode_domain(&node)) {
162            Ok(domain) => application.extend(domain),
163            Err(mut errors) => diagnostics.append(&mut errors),
164        }
165    }
166
167    if !diagnostics.is_empty() {
168        return Err(diagnostics);
169    }
170    let mut warnings = lint::warnings(&application);
171    let mut modules = local_modules;
172    modules.extend(remote_modules);
173    lower::build_ir(surface_root, application, modules, &mut warnings).map(|ir| CompileReport {
174        ir,
175        diagnostics: warnings,
176    })
177}
178
179/// Return the selected preset's effective module configuration after project overrides.
180///
181/// # Errors
182///
183/// Returns root parsing, validation, or preset lock diagnostics.
184pub fn expanded_preset(project_root: &Path) -> Result<Option<String>, Vec<Diagnostic>> {
185    let root = canonical_project_root(project_root)?;
186    let root_node = loading::load_yaml(&root, &root.join("appstruct.yaml"))?;
187    let surface_root = surface::decode_root(&root_node)?;
188    let mut diagnostics = validation::validate_root(&surface_root);
189    diagnostics.extend(preset::validate_lock(&root, &surface_root));
190    if !diagnostics.is_empty() {
191        return Err(diagnostics);
192    }
193    Ok(surface_root
194        .preset
195        .as_ref()
196        .and(surface_root.expanded_modules.as_ref())
197        .map(preset::render_expanded_modules))
198}
199
200/// Build the canonical lock candidate for an explicit project update.
201///
202/// Existing version and digest fields may be stale, but the lock must remain readable so its
203/// template identity can be preserved. The returned source must still pass a complete staged
204/// project compilation before it replaces the current lock.
205///
206/// # Errors
207///
208/// Returns root configuration, lock parsing, or unsupported preset diagnostics.
209pub fn updated_project_lock(project_root: &Path) -> Result<String, Vec<Diagnostic>> {
210    let root = canonical_project_root(project_root)?;
211    let root_node = loading::load_yaml(&root, &root.join("appstruct.yaml"))?;
212    let surface_root = surface::decode_root(&root_node)?;
213    let diagnostics = validation::validate_root(&surface_root);
214    if !diagnostics.is_empty() {
215        return Err(diagnostics);
216    }
217    let (local_modules, module_diagnostics) =
218        module::load_local_modules(&root, &surface_root.module_manifests);
219    if !module_diagnostics.is_empty() {
220        return Err(module_diagnostics);
221    }
222    preset::updated_lock(&root, &surface_root, &local_modules).map_err(|error| vec![error])
223}
224
225fn canonical_project_root(project_root: &Path) -> Result<PathBuf, Vec<Diagnostic>> {
226    fs::canonicalize(project_root).map_err(|error| {
227        vec![Diagnostic::error(
228            "AS1008",
229            format!(
230                "cannot access project root `{}`: {error}",
231                project_root.display()
232            ),
233            loading::synthetic_span(&project_root.to_string_lossy()),
234        )]
235    })
236}