appstruct-ir 0.2.0

Stable typed intermediate representation and diagnostics for AppStruct
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Stable, serialization-friendly intermediate representation for `AppStruct`.
mod auth;
mod billing;
mod database;
mod extension;
mod json;
mod seed;
mod service;
mod ui;
mod validation;
mod views;
mod workflow;
pub use auth::AuthIr;
pub use billing::{BillingIr, BillingPlanIr};
pub use database::{DatabaseDevMode, DatabaseIr, DatabaseMigrationPolicy, DatabaseProvider};
pub use extension::{CommandIr, OperationTypeIr, PageIr, QueryIr, ValueFieldIr, ValueObjectIr};
pub use json::{IrJsonError, from_json};
pub use seed::SeedIr;
use serde::{Deserialize, Serialize};
pub use service::{
    ActivityIr, ActivityResourceIr, AuditIr, FileIr, FileProviderIr, FrameOptionsIr, HstsIr,
    JobQueueIr, JobScheduleIr, JobsIr, MailIr, MailProviderIr, MailTemplateIr, PresetIr,
    RealtimeIr, ReferrerPolicyIr, ReportIr, ReportRendererIr, ReportTemplateIr, SecurityHeadersIr,
    ServerIr, TenantIr, WebhookEndpointIr, WebhooksIr,
};
use std::fmt;
pub use ui::FieldSemanticIr;
pub use validation::aggregates::validate_aggregates;
pub use validation::charts::validate_charts;
pub use validation::{IrValidationError, IrValidationErrors, validate_app_ir, validate_form_rules};
pub use views::{
    AggregateIr, ChartDimensionIr, ChartIr, ChartKindIr, ChartMeasureIr, EntityViewsIr,
};
pub use workflow::{WorkflowIr, WorkflowTransitionIr};
pub const IR_VERSION: u32 = appstruct_contracts::IR.current;

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppIr {
    pub ir_version: u32,
    pub app: AppMeta,
    pub database: DatabaseIr,
    pub preset: Option<PresetIr>,
    pub auth: AuthIr,
    pub billing: BillingIr,
    #[serde(default, skip_serializing_if = "ServerIr::is_default")]
    pub server: ServerIr,
    pub tenant: TenantIr,
    pub audit: AuditIr,
    pub mail: MailIr,
    pub jobs: JobsIr,
    #[serde(default, skip_serializing_if = "WebhooksIr::is_disabled")]
    pub webhooks: WebhooksIr,
    #[serde(default, skip_serializing_if = "RealtimeIr::is_disabled")]
    pub realtime: RealtimeIr,
    pub file: FileIr,
    #[serde(default, skip_serializing_if = "ReportIr::is_disabled")]
    pub report: ReportIr,
    #[serde(default, skip_serializing_if = "ActivityIr::is_disabled")]
    pub activity: ActivityIr,
    pub enums: Vec<EnumIr>,
    pub value_objects: Vec<ValueObjectIr>,
    pub entities: Vec<EntityIr>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub seeds: Vec<SeedIr>,
    pub relations: Vec<RelationIr>,
    pub commands: Vec<CommandIr>,
    pub queries: Vec<QueryIr>,
    pub pages: Vec<PageIr>,
    pub modules: Vec<ResolvedModule>,
}
/// Application-level metadata.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppMeta {
    pub name: String,
}
/// Stable logical entity identifier. It never depends on vector position.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EntityId(pub String);

impl fmt::Display for EntityId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

/// Stable logical field identifier.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct FieldId(pub String);

impl fmt::Display for FieldId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RelationId(pub String);

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityIr {
    pub id: EntityId,
    pub rust_name: String,
    pub api_name: String,
    pub label: String,
    pub table_name: String,
    pub fields: Vec<FieldIr>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub indexes: Vec<IndexIr>,
    pub access: CrudAccessIr,
    pub views: EntityViewsIr,
    pub hooks: HooksIr,
    pub concurrency: ConcurrencyIr,
    pub tenant_scoped: bool,
    pub audit_enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workflow: Option<WorkflowIr>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexIr {
    pub id: String,
    pub entity: EntityId,
    pub fields: Vec<FieldId>,
    pub unique: bool,
    #[serde(default, skip_serializing_if = "IndexMethod::is_default")]
    pub method: IndexMethod,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operator_class: Option<IndexOperatorClass>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub predicate: Option<String>,
}

/// Supported PostgreSQL index access methods.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IndexMethod {
    #[default]
    Btree,
    Gin,
}
impl IndexMethod {
    #[must_use]
    pub const fn is_default(&self) -> bool {
        matches!(self, Self::Btree)
    }
    #[must_use]
    pub const fn sql(self) -> &'static str {
        match self {
            Self::Btree => "btree",
            Self::Gin => "gin",
        }
    }
}

/// Allowlisted operator classes for text substring and JSONB search.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IndexOperatorClass {
    GinTrgmOps,
    JsonbOps,
    JsonbPathOps,
}
impl IndexOperatorClass {
    #[must_use]
    pub const fn sql(self) -> &'static str {
        match self {
            Self::GinTrgmOps => "gin_trgm_ops",
            Self::JsonbOps => "jsonb_ops",
            Self::JsonbPathOps => "jsonb_path_ops",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldIr {
    pub id: FieldId,
    pub entity: EntityId,
    pub rust_name: String,
    pub api_name: String,
    pub column_name: String,
    pub ty: FieldTypeIr,
    pub nullable: bool,
    pub primary_key: bool,
    pub unique: bool,
    pub generated: Option<GeneratedValueIr>,
    pub default: Option<String>,
    pub validation: ValidationIr,
    pub capabilities: FieldCapabilities,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub read_access: Option<AccessRuleIr>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub write_access: Option<AccessRuleIr>,
    pub ui_component: Option<String>,
    pub ui_semantic: Option<FieldSemanticIr>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FieldTypeIr {
    Uuid,
    String,
    Text,
    Integer,
    Bigint,
    Decimal,
    Boolean,
    Date,
    Datetime,
    Json,
    Enum { values: Vec<String> },
    Relation { target: EntityId },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GeneratedValueIr {
    UuidV7,
    Now,
    AutoIncrement,
    Revision,
    Tenant,
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValidationIr {
    pub min_length: Option<u64>,
    pub max_length: Option<u64>,
    pub minimum: Option<String>,
    pub maximum: Option<String>,
    pub required_when: Option<RequiredWhenIr>,
    pub greater_than: Option<FieldId>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequiredWhenIr {
    pub field: FieldId,
    pub equals: ConditionValueIr,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ConditionValueIr {
    Boolean(bool),
    String(String),
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldCapabilities {
    pub searchable: bool,
    pub filterable: bool,
    pub sortable: bool,
}

/// Explicit relation edge resolved by the compiler.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelationIr {
    pub id: RelationId,
    pub source: EntityId,
    pub target: EntityId,
    pub cardinality: Cardinality,
    pub foreign_key_owner: EntityId,
    pub foreign_key_fields: Vec<FieldId>,
    pub inverse: Option<RelationId>,
    pub required: bool,
    pub unique: bool,
    pub on_delete: OnDeleteIr,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Cardinality {
    OneToOne,
    ManyToOne,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnDeleteIr {
    Restrict,
    Cascade,
    SetNull,
}

/// CRUD rules are always explicit in normalized IR.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CrudAccessIr {
    pub list: AccessRuleIr,
    pub read: AccessRuleIr,
    pub create: AccessRuleIr,
    pub update: AccessRuleIr,
    pub delete: AccessRuleIr,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum AccessRuleIr {
    Public,
    Authenticated,
    Role { role: String },
    Owner { field: FieldId },
    Any { rules: Vec<AccessRuleIr> },
    All { rules: Vec<AccessRuleIr> },
}

/// M0 preserves the future IR shape while leaving hooks empty.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct HooksIr {}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConcurrencyIr {
    pub enabled: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnumIr {
    pub name: String,
    pub values: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedModule {
    pub name: String,
    pub version: String,
    pub origin: ModuleOrigin,
    /// Project-relative manifest path for a local module.
    pub manifest_path: Option<String>,
    /// SHA-256 of the exact local manifest bytes loaded by the compiler.
    pub content_sha256: Option<String>,
    pub provides: Vec<String>,
    pub requires: Vec<String>,
    pub startup_order: u32,
    pub artifacts: Vec<ModuleArtifactIr>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModuleOrigin {
    Official,
    Local,
    Remote,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModuleArtifactIr {
    pub path: String,
    /// Project-relative source path, or `None` when no source file is attached.
    pub source: Option<String>,
    pub sha256: String,
    pub byte_len: u64,
    pub content: String,
}

/// Byte offsets plus user-facing line and column for a source range.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceSpan {
    pub file: String,
    pub start: usize,
    pub end: usize,
    pub line: usize,
    pub column: usize,
    pub end_line: usize,
    pub end_column: usize,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Error,
    Warning,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Label {
    pub span: SourceSpan,
    pub message: String,
}

/// Stable diagnostic shared by text and JSON consumers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
    pub severity: Severity,
    pub code: String,
    pub message: String,
    pub primary: Box<Label>,
    pub secondary: Vec<Label>,
    pub help: Option<String>,
}

impl Diagnostic {
    #[must_use]
    pub fn error(code: &str, message: impl Into<String>, span: SourceSpan) -> Self {
        Self {
            severity: Severity::Error,
            code: code.to_owned(),
            message: message.into(),
            primary: Box::new(Label {
                span,
                message: String::new(),
            }),
            secondary: Vec::new(),
            help: None,
        }
    }

    #[must_use]
    pub fn warning(code: &str, message: impl Into<String>, span: SourceSpan) -> Self {
        Self {
            severity: Severity::Warning,
            code: code.to_owned(),
            message: message.into(),
            primary: Box::new(Label {
                span,
                message: String::new(),
            }),
            secondary: Vec::new(),
            help: None,
        }
    }

    #[must_use]
    pub fn with_primary_message(mut self, message: impl Into<String>) -> Self {
        self.primary.message = message.into();
        self
    }

    #[must_use]
    pub fn with_secondary(mut self, span: SourceSpan, message: impl Into<String>) -> Self {
        self.secondary.push(Label {
            span,
            message: message.into(),
        });
        self
    }

    #[must_use]
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());
        self
    }
}

/// Serialize normalized IR using deterministic field and collection order.
///
/// # Errors
///
/// Returns a serialization error only if the IR representation becomes unsupported by Serde.
pub fn to_canonical_json(ir: &AppIr) -> Result<String, serde_json::Error> {
    let mut output = serde_json::to_string_pretty(ir)?;
    output.push('\n');
    Ok(output)
}