Skip to main content

shaperail_codegen/
json_schema.rs

1use serde_json::{json, Value};
2
3/// Generate a JSON Schema (draft 2020-12) that validates Shaperail resource YAML files.
4///
5/// This schema is the canonical machine-readable definition of the resource format.
6/// LLMs and IDEs can use it for autocomplete and validation. The schema is generated
7/// from the same types that `parser.rs` uses, ensuring they never drift apart.
8pub fn generate_resource_json_schema() -> Value {
9    json!({
10        "$schema": "https://json-schema.org/draft/2020-12/schema",
11        "$id": "https://shaperail.dev/schema/resource.v1.json",
12        "title": "Shaperail Resource Definition",
13        "description": "Schema for Shaperail resource YAML files. Defines a single API resource with its fields, endpoints, relations, and indexes.",
14        "type": "object",
15        "required": ["resource", "version", "schema"],
16        "additionalProperties": false,
17        "properties": {
18            "resource": {
19                "type": "string",
20                "description": "Snake_case plural name of the resource (e.g., 'users', 'blog_posts').",
21                "pattern": "^[a-z][a-z0-9_]*$"
22            },
23            "version": {
24                "type": "integer",
25                "description": "Schema version number (starts at 1). Drives route prefix: /v{version}/...",
26                "minimum": 1
27            },
28            "db": {
29                "type": "string",
30                "description": "Named database connection for this resource (M14 multi-DB). Default: 'default'."
31            },
32            "tenant_key": {
33                "type": "string",
34                "description": "Tenant isolation key (M18). References a uuid schema field that identifies the tenant. When set, all queries are automatically scoped to the authenticated user's tenant_id claim."
35            },
36            "schema": {
37                "type": "object",
38                "description": "Field definitions keyed by field name. At least one field with primary: true is required.",
39                "minProperties": 1,
40                "additionalProperties": { "$ref": "#/$defs/FieldSchema" }
41            },
42            "endpoints": {
43                "type": "object",
44                "description": "Endpoint definitions keyed by action name (e.g., 'list', 'get', 'create', 'update', 'delete').",
45                "additionalProperties": { "$ref": "#/$defs/EndpointSpec" }
46            },
47            "relations": {
48                "type": "object",
49                "description": "Relationship definitions keyed by relation name.",
50                "additionalProperties": { "$ref": "#/$defs/RelationSpec" }
51            },
52            "indexes": {
53                "type": "array",
54                "description": "Additional database indexes.",
55                "items": { "$ref": "#/$defs/IndexSpec" }
56            }
57        },
58        "$defs": {
59            "FieldType": {
60                "type": "string",
61                "enum": ["uuid", "string", "integer", "number", "boolean", "timestamp", "date", "enum", "json", "array", "file"],
62                "description": "The data type of a field."
63            },
64            "FieldSchema": {
65                "type": "object",
66                "description": "Definition of a single field in a resource schema.",
67                "required": ["type"],
68                "additionalProperties": false,
69                "properties": {
70                    "type": { "$ref": "#/$defs/FieldType" },
71                    "primary": {
72                        "type": "boolean",
73                        "default": false,
74                        "description": "Whether this field is the primary key. Exactly one field must be primary."
75                    },
76                    "generated": {
77                        "type": "boolean",
78                        "default": false,
79                        "description": "Whether this field is auto-generated (e.g., uuid v4, timestamps)."
80                    },
81                    "required": {
82                        "type": "boolean",
83                        "default": false,
84                        "description": "Whether this field is required (NOT NULL + validated on input)."
85                    },
86                    "unique": {
87                        "type": "boolean",
88                        "default": false,
89                        "description": "Whether this field has a unique constraint."
90                    },
91                    "nullable": {
92                        "type": "boolean",
93                        "default": false,
94                        "description": "Whether this field is explicitly nullable."
95                    },
96                    "ref": {
97                        "type": "string",
98                        "description": "Foreign key reference in 'resource.field' format (e.g., 'organizations.id'). Field type must be uuid.",
99                        "pattern": "^[a-z][a-z0-9_]*\\.[a-z][a-z0-9_]*$"
100                    },
101                    "min": {
102                        "description": "Minimum value (number) or minimum length (string)."
103                    },
104                    "max": {
105                        "description": "Maximum value (number) or maximum length (string)."
106                    },
107                    "format": {
108                        "type": "string",
109                        "description": "String format validation. Only valid when type is 'string'.",
110                        "enum": ["email", "url", "uuid"]
111                    },
112                    "values": {
113                        "type": "array",
114                        "items": { "type": "string" },
115                        "minItems": 1,
116                        "description": "Allowed values for enum-type fields. Required when type is 'enum'."
117                    },
118                    "default": {
119                        "description": "Default value for this field."
120                    },
121                    "sensitive": {
122                        "type": "boolean",
123                        "default": false,
124                        "description": "Whether this field contains sensitive data (redacted in logs)."
125                    },
126                    "search": {
127                        "type": "boolean",
128                        "default": false,
129                        "description": "Whether this field is included in full-text search."
130                    },
131                    "items": {
132                        "type": "string",
133                        "description": "Element type for array fields. Required when type is 'array'.",
134                        "enum": ["uuid", "string", "integer", "number", "boolean", "timestamp", "date"]
135                    }
136                }
137            },
138            "HttpMethod": {
139                "type": "string",
140                "enum": ["GET", "POST", "PATCH", "PUT", "DELETE"]
141            },
142            "AuthRule": {
143                "description": "Authentication rule. Use 'public' for no auth, 'owner' for ownership check, or an array of role strings.",
144                "oneOf": [
145                    { "const": "public" },
146                    { "const": "owner" },
147                    {
148                        "type": "array",
149                        "items": { "type": "string" },
150                        "minItems": 1,
151                        "description": "Requires JWT with one of these roles. Use 'owner' in the array to combine role + ownership check."
152                    }
153                ]
154            },
155            "PaginationStyle": {
156                "type": "string",
157                "enum": ["cursor", "offset"],
158                "description": "Pagination strategy for list endpoints."
159            },
160            "CacheSpec": {
161                "type": "object",
162                "description": "Cache configuration for an endpoint.",
163                "required": ["ttl"],
164                "additionalProperties": false,
165                "properties": {
166                    "ttl": {
167                        "type": "integer",
168                        "minimum": 1,
169                        "description": "Time-to-live in seconds."
170                    },
171                    "invalidate_on": {
172                        "type": "array",
173                        "items": { "type": "string", "enum": ["create", "update", "delete"] },
174                        "description": "Events that invalidate this cache."
175                    }
176                }
177            },
178            "UploadSpec": {
179                "type": "object",
180                "description": "File upload configuration for an endpoint.",
181                "required": ["field", "storage", "max_size"],
182                "additionalProperties": false,
183                "properties": {
184                    "field": {
185                        "type": "string",
186                        "description": "Schema field that stores the file URL. Must be type 'file'."
187                    },
188                    "storage": {
189                        "type": "string",
190                        "enum": ["local", "s3", "gcs", "azure"],
191                        "description": "Storage backend."
192                    },
193                    "max_size": {
194                        "type": "string",
195                        "description": "Maximum file size (e.g., '5mb', '10mb').",
196                        "pattern": "^[0-9]+[kmg]b$"
197                    },
198                    "types": {
199                        "type": "array",
200                        "items": { "type": "string" },
201                        "description": "Allowed file extensions (e.g., ['jpg', 'png', 'pdf'])."
202                    }
203                }
204            },
205            "ControllerSpec": {
206                "type": "object",
207                "description": "Controller specification for synchronous in-request business logic. Functions live in resources/<resource>.controller.rs.",
208                "additionalProperties": false,
209                "properties": {
210                    "before": {
211                        "type": "string",
212                        "description": "Function name called before the DB operation. Prefix with 'wasm:' for WASM plugins (e.g., 'wasm:./plugins/validator.wasm')."
213                    },
214                    "after": {
215                        "type": "string",
216                        "description": "Function name called after the DB operation. Prefix with 'wasm:' for WASM plugins."
217                    }
218                }
219            },
220            "EndpointSpec": {
221                "type": "object",
222                "description": "Specification for a single endpoint in a resource.",
223                "additionalProperties": false,
224                "properties": {
225                    "method": { "$ref": "#/$defs/HttpMethod" },
226                    "path": {
227                        "type": "string",
228                        "description": "URL path pattern (e.g., '/users', '/users/:id'). Auto-prefixed with /v{version}.",
229                        "pattern": "^/"
230                    },
231                    "auth": { "$ref": "#/$defs/AuthRule" },
232                    "input": {
233                        "type": "array",
234                        "items": { "type": "string" },
235                        "description": "Schema fields accepted as input for create/update. Each must exist in schema."
236                    },
237                    "filters": {
238                        "type": "array",
239                        "items": { "type": "string" },
240                        "description": "Schema fields available as query filters. Each must exist in schema."
241                    },
242                    "search": {
243                        "type": "array",
244                        "items": { "type": "string" },
245                        "description": "Schema fields included in full-text search. Each must exist in schema."
246                    },
247                    "pagination": { "$ref": "#/$defs/PaginationStyle" },
248                    "sort": {
249                        "type": "array",
250                        "items": { "type": "string" },
251                        "description": "Schema fields available for sorting. Each must exist in schema."
252                    },
253                    "cache": { "$ref": "#/$defs/CacheSpec" },
254                    "controller": { "$ref": "#/$defs/ControllerSpec" },
255                    "events": {
256                        "type": "array",
257                        "items": { "type": "string" },
258                        "description": "Events to emit after successful execution (e.g., ['user.created'])."
259                    },
260                    "jobs": {
261                        "type": "array",
262                        "items": { "type": "string" },
263                        "description": "Background jobs to enqueue after successful execution (e.g., ['send_welcome_email'])."
264                    },
265                    "upload": { "$ref": "#/$defs/UploadSpec" },
266                    "soft_delete": {
267                        "type": "boolean",
268                        "default": false,
269                        "description": "Whether this endpoint performs a soft delete. Requires a 'deleted_at' nullable timestamp field in schema."
270                    }
271                }
272            },
273            "RelationType": {
274                "type": "string",
275                "enum": ["belongs_to", "has_many", "has_one"]
276            },
277            "RelationSpec": {
278                "type": "object",
279                "description": "Specification for a relationship to another resource.",
280                "required": ["resource", "type"],
281                "additionalProperties": false,
282                "properties": {
283                    "resource": {
284                        "type": "string",
285                        "description": "Name of the related resource."
286                    },
287                    "type": { "$ref": "#/$defs/RelationType" },
288                    "key": {
289                        "type": "string",
290                        "description": "Local foreign key field. Required for belongs_to."
291                    },
292                    "foreign_key": {
293                        "type": "string",
294                        "description": "Foreign key on the related resource. Required for has_many and has_one."
295                    }
296                }
297            },
298            "IndexSpec": {
299                "type": "object",
300                "description": "Specification for a database index.",
301                "required": ["fields"],
302                "additionalProperties": false,
303                "properties": {
304                    "fields": {
305                        "type": "array",
306                        "items": { "type": "string" },
307                        "minItems": 1,
308                        "description": "Fields included in this index. Each must exist in schema."
309                    },
310                    "unique": {
311                        "type": "boolean",
312                        "default": false,
313                        "description": "Whether this is a unique index."
314                    },
315                    "order": {
316                        "type": "string",
317                        "enum": ["asc", "desc"],
318                        "description": "Sort order for the index."
319                    }
320                }
321            }
322        }
323    })
324}
325
326/// Render the JSON Schema as a pretty-printed JSON string.
327pub fn render_json_schema() -> String {
328    serde_json::to_string_pretty(&generate_resource_json_schema())
329        .expect("JSON schema serialization cannot fail")
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn schema_is_valid_json() {
338        let schema = generate_resource_json_schema();
339        assert_eq!(schema["type"], "object");
340        assert!(
341            schema["$defs"]["FieldType"]["enum"]
342                .as_array()
343                .unwrap()
344                .len()
345                == 11
346        );
347    }
348
349    #[test]
350    fn schema_requires_resource_version_schema() {
351        let schema = generate_resource_json_schema();
352        let required = schema["required"].as_array().unwrap();
353        assert!(required.contains(&json!("resource")));
354        assert!(required.contains(&json!("version")));
355        assert!(required.contains(&json!("schema")));
356    }
357
358    #[test]
359    fn schema_disallows_additional_properties() {
360        let schema = generate_resource_json_schema();
361        assert_eq!(schema["additionalProperties"], false);
362    }
363
364    #[test]
365    fn render_produces_nonempty_string() {
366        let rendered = render_json_schema();
367        assert!(rendered.len() > 1000);
368        assert!(rendered.contains("$schema"));
369    }
370}