Skip to main content

appstruct_ir/
lib.rs

1//! Stable, serialization-friendly intermediate representation for `AppStruct`.
2mod auth;
3mod billing;
4mod database;
5mod extension;
6mod json;
7mod seed;
8mod service;
9mod ui;
10mod validation;
11mod views;
12mod workflow;
13pub use auth::AuthIr;
14pub use billing::{BillingIr, BillingPlanIr};
15pub use database::{DatabaseDevMode, DatabaseIr, DatabaseMigrationPolicy, DatabaseProvider};
16pub use extension::{CommandIr, OperationTypeIr, PageIr, QueryIr, ValueFieldIr, ValueObjectIr};
17pub use json::{IrJsonError, from_json};
18pub use seed::SeedIr;
19use serde::{Deserialize, Serialize};
20pub use service::{
21    ActivityIr, ActivityResourceIr, AuditIr, FileIr, FileProviderIr, FrameOptionsIr, HstsIr,
22    JobQueueIr, JobScheduleIr, JobsIr, MailIr, MailProviderIr, MailTemplateIr, PresetIr,
23    RealtimeIr, ReferrerPolicyIr, ReportIr, ReportRendererIr, ReportTemplateIr, SecurityHeadersIr,
24    ServerIr, TenantIr, WebhookEndpointIr, WebhooksIr,
25};
26use std::fmt;
27pub use ui::FieldSemanticIr;
28pub use validation::aggregates::validate_aggregates;
29pub use validation::charts::validate_charts;
30pub use validation::{IrValidationError, IrValidationErrors, validate_app_ir, validate_form_rules};
31pub use views::{
32    AggregateIr, ChartDimensionIr, ChartIr, ChartKindIr, ChartMeasureIr, EntityViewsIr,
33};
34pub use workflow::{WorkflowIr, WorkflowTransitionIr};
35pub const IR_VERSION: u32 = appstruct_contracts::IR.current;
36
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38pub struct AppIr {
39    pub ir_version: u32,
40    pub app: AppMeta,
41    pub database: DatabaseIr,
42    pub preset: Option<PresetIr>,
43    pub auth: AuthIr,
44    pub billing: BillingIr,
45    #[serde(default, skip_serializing_if = "ServerIr::is_default")]
46    pub server: ServerIr,
47    pub tenant: TenantIr,
48    pub audit: AuditIr,
49    pub mail: MailIr,
50    pub jobs: JobsIr,
51    #[serde(default, skip_serializing_if = "WebhooksIr::is_disabled")]
52    pub webhooks: WebhooksIr,
53    #[serde(default, skip_serializing_if = "RealtimeIr::is_disabled")]
54    pub realtime: RealtimeIr,
55    pub file: FileIr,
56    #[serde(default, skip_serializing_if = "ReportIr::is_disabled")]
57    pub report: ReportIr,
58    #[serde(default, skip_serializing_if = "ActivityIr::is_disabled")]
59    pub activity: ActivityIr,
60    pub enums: Vec<EnumIr>,
61    pub value_objects: Vec<ValueObjectIr>,
62    pub entities: Vec<EntityIr>,
63    #[serde(default, skip_serializing_if = "Vec::is_empty")]
64    pub seeds: Vec<SeedIr>,
65    pub relations: Vec<RelationIr>,
66    pub commands: Vec<CommandIr>,
67    pub queries: Vec<QueryIr>,
68    pub pages: Vec<PageIr>,
69    pub modules: Vec<ResolvedModule>,
70}
71/// Application-level metadata.
72#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
73pub struct AppMeta {
74    pub name: String,
75}
76/// Stable logical entity identifier. It never depends on vector position.
77#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
78#[serde(transparent)]
79pub struct EntityId(pub String);
80
81impl fmt::Display for EntityId {
82    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
83        self.0.fmt(formatter)
84    }
85}
86
87/// Stable logical field identifier.
88#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
89#[serde(transparent)]
90pub struct FieldId(pub String);
91
92impl fmt::Display for FieldId {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        self.0.fmt(formatter)
95    }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
99#[serde(transparent)]
100pub struct RelationId(pub String);
101
102#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
103pub struct EntityIr {
104    pub id: EntityId,
105    pub rust_name: String,
106    pub api_name: String,
107    pub label: String,
108    pub table_name: String,
109    pub fields: Vec<FieldIr>,
110    #[serde(default, skip_serializing_if = "Vec::is_empty")]
111    pub indexes: Vec<IndexIr>,
112    pub access: CrudAccessIr,
113    pub views: EntityViewsIr,
114    pub hooks: HooksIr,
115    pub concurrency: ConcurrencyIr,
116    pub tenant_scoped: bool,
117    pub audit_enabled: bool,
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub workflow: Option<WorkflowIr>,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
123pub struct IndexIr {
124    pub id: String,
125    pub entity: EntityId,
126    pub fields: Vec<FieldId>,
127    pub unique: bool,
128    #[serde(default, skip_serializing_if = "IndexMethod::is_default")]
129    pub method: IndexMethod,
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub operator_class: Option<IndexOperatorClass>,
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub predicate: Option<String>,
134}
135
136/// Supported PostgreSQL index access methods.
137#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum IndexMethod {
140    #[default]
141    Btree,
142    Gin,
143}
144impl IndexMethod {
145    #[must_use]
146    pub const fn is_default(&self) -> bool {
147        matches!(self, Self::Btree)
148    }
149    #[must_use]
150    pub const fn sql(self) -> &'static str {
151        match self {
152            Self::Btree => "btree",
153            Self::Gin => "gin",
154        }
155    }
156}
157
158/// Allowlisted operator classes for text substring and JSONB search.
159#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
160#[serde(rename_all = "snake_case")]
161pub enum IndexOperatorClass {
162    GinTrgmOps,
163    JsonbOps,
164    JsonbPathOps,
165}
166impl IndexOperatorClass {
167    #[must_use]
168    pub const fn sql(self) -> &'static str {
169        match self {
170            Self::GinTrgmOps => "gin_trgm_ops",
171            Self::JsonbOps => "jsonb_ops",
172            Self::JsonbPathOps => "jsonb_path_ops",
173        }
174    }
175}
176
177#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
178pub struct FieldIr {
179    pub id: FieldId,
180    pub entity: EntityId,
181    pub rust_name: String,
182    pub api_name: String,
183    pub column_name: String,
184    pub ty: FieldTypeIr,
185    pub nullable: bool,
186    pub primary_key: bool,
187    pub unique: bool,
188    pub generated: Option<GeneratedValueIr>,
189    pub default: Option<String>,
190    pub validation: ValidationIr,
191    pub capabilities: FieldCapabilities,
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub read_access: Option<AccessRuleIr>,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub write_access: Option<AccessRuleIr>,
196    pub ui_component: Option<String>,
197    pub ui_semantic: Option<FieldSemanticIr>,
198}
199
200#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(tag = "kind", rename_all = "snake_case")]
202pub enum FieldTypeIr {
203    Uuid,
204    String,
205    Text,
206    Integer,
207    Bigint,
208    Decimal,
209    Boolean,
210    Date,
211    Datetime,
212    Json,
213    Enum { values: Vec<String> },
214    Relation { target: EntityId },
215}
216
217#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
218#[serde(rename_all = "snake_case")]
219pub enum GeneratedValueIr {
220    UuidV7,
221    Now,
222    AutoIncrement,
223    Revision,
224    Tenant,
225}
226
227#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
228pub struct ValidationIr {
229    pub min_length: Option<u64>,
230    pub max_length: Option<u64>,
231    pub minimum: Option<String>,
232    pub maximum: Option<String>,
233    pub required_when: Option<RequiredWhenIr>,
234    pub greater_than: Option<FieldId>,
235}
236
237#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
238pub struct RequiredWhenIr {
239    pub field: FieldId,
240    pub equals: ConditionValueIr,
241}
242
243#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
244#[serde(untagged)]
245pub enum ConditionValueIr {
246    Boolean(bool),
247    String(String),
248}
249
250#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
251pub struct FieldCapabilities {
252    pub searchable: bool,
253    pub filterable: bool,
254    pub sortable: bool,
255}
256
257/// Explicit relation edge resolved by the compiler.
258#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
259pub struct RelationIr {
260    pub id: RelationId,
261    pub source: EntityId,
262    pub target: EntityId,
263    pub cardinality: Cardinality,
264    pub foreign_key_owner: EntityId,
265    pub foreign_key_fields: Vec<FieldId>,
266    pub inverse: Option<RelationId>,
267    pub required: bool,
268    pub unique: bool,
269    pub on_delete: OnDeleteIr,
270}
271
272#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
273#[serde(rename_all = "snake_case")]
274pub enum Cardinality {
275    OneToOne,
276    ManyToOne,
277}
278
279#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(rename_all = "snake_case")]
281pub enum OnDeleteIr {
282    Restrict,
283    Cascade,
284    SetNull,
285}
286
287/// CRUD rules are always explicit in normalized IR.
288#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
289pub struct CrudAccessIr {
290    pub list: AccessRuleIr,
291    pub read: AccessRuleIr,
292    pub create: AccessRuleIr,
293    pub update: AccessRuleIr,
294    pub delete: AccessRuleIr,
295}
296
297#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(tag = "mode", rename_all = "snake_case")]
299pub enum AccessRuleIr {
300    Public,
301    Authenticated,
302    Role { role: String },
303    Owner { field: FieldId },
304    Any { rules: Vec<AccessRuleIr> },
305    All { rules: Vec<AccessRuleIr> },
306}
307
308/// M0 preserves the future IR shape while leaving hooks empty.
309#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
310pub struct HooksIr {}
311
312#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
313pub struct ConcurrencyIr {
314    pub enabled: bool,
315}
316
317#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
318pub struct EnumIr {
319    pub name: String,
320    pub values: Vec<String>,
321}
322
323#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
324pub struct ResolvedModule {
325    pub name: String,
326    pub version: String,
327    pub origin: ModuleOrigin,
328    /// Project-relative manifest path for a local module.
329    pub manifest_path: Option<String>,
330    /// SHA-256 of the exact local manifest bytes loaded by the compiler.
331    pub content_sha256: Option<String>,
332    pub provides: Vec<String>,
333    pub requires: Vec<String>,
334    pub startup_order: u32,
335    pub artifacts: Vec<ModuleArtifactIr>,
336}
337
338#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
339#[serde(rename_all = "snake_case")]
340pub enum ModuleOrigin {
341    Official,
342    Local,
343    Remote,
344}
345
346#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
347pub struct ModuleArtifactIr {
348    pub path: String,
349    /// Project-relative source path, or `None` when no source file is attached.
350    pub source: Option<String>,
351    pub sha256: String,
352    pub byte_len: u64,
353    pub content: String,
354}
355
356/// Byte offsets plus user-facing line and column for a source range.
357#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
358pub struct SourceSpan {
359    pub file: String,
360    pub start: usize,
361    pub end: usize,
362    pub line: usize,
363    pub column: usize,
364    pub end_line: usize,
365    pub end_column: usize,
366}
367
368#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "lowercase")]
370pub enum Severity {
371    Error,
372    Warning,
373}
374
375#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
376pub struct Label {
377    pub span: SourceSpan,
378    pub message: String,
379}
380
381/// Stable diagnostic shared by text and JSON consumers.
382#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
383pub struct Diagnostic {
384    pub severity: Severity,
385    pub code: String,
386    pub message: String,
387    pub primary: Box<Label>,
388    pub secondary: Vec<Label>,
389    pub help: Option<String>,
390}
391
392impl Diagnostic {
393    #[must_use]
394    pub fn error(code: &str, message: impl Into<String>, span: SourceSpan) -> Self {
395        Self {
396            severity: Severity::Error,
397            code: code.to_owned(),
398            message: message.into(),
399            primary: Box::new(Label {
400                span,
401                message: String::new(),
402            }),
403            secondary: Vec::new(),
404            help: None,
405        }
406    }
407
408    #[must_use]
409    pub fn warning(code: &str, message: impl Into<String>, span: SourceSpan) -> Self {
410        Self {
411            severity: Severity::Warning,
412            code: code.to_owned(),
413            message: message.into(),
414            primary: Box::new(Label {
415                span,
416                message: String::new(),
417            }),
418            secondary: Vec::new(),
419            help: None,
420        }
421    }
422
423    #[must_use]
424    pub fn with_primary_message(mut self, message: impl Into<String>) -> Self {
425        self.primary.message = message.into();
426        self
427    }
428
429    #[must_use]
430    pub fn with_secondary(mut self, span: SourceSpan, message: impl Into<String>) -> Self {
431        self.secondary.push(Label {
432            span,
433            message: message.into(),
434        });
435        self
436    }
437
438    #[must_use]
439    pub fn with_help(mut self, help: impl Into<String>) -> Self {
440        self.help = Some(help.into());
441        self
442    }
443}
444
445/// Serialize normalized IR using deterministic field and collection order.
446///
447/// # Errors
448///
449/// Returns a serialization error only if the IR representation becomes unsupported by Serde.
450pub fn to_canonical_json(ir: &AppIr) -> Result<String, serde_json::Error> {
451    let mut output = serde_json::to_string_pretty(ir)?;
452    output.push('\n');
453    Ok(output)
454}