1use std::fs;
10
11use anyhow::{Context, Result};
12use fraiseql_core::schema::CrudNamingConfig;
13use serde_json::{Value, json};
14
15use crate::{
16 config::TomlSchema,
17 schema::{IntermediateSchema, intermediate::IntermediateQueryDefaults},
18};
19
20pub(crate) fn pascal_to_snake(type_name: &str) -> String {
25 let mut out = String::with_capacity(type_name.len() + 4);
26 for (i, ch) in type_name.chars().enumerate() {
27 if ch.is_uppercase() && i > 0 {
28 out.push('_');
29 }
30 out.push(ch.to_ascii_lowercase());
31 }
32 out
33}
34
35fn resolve_mutation_sql_source(
43 mutation_name: &str,
44 sql_source: Option<&str>,
45 operation: &str,
46 return_type: &str,
47 crud: Option<&CrudNamingConfig>,
48) -> Result<String> {
49 if let Some(src) = sql_source {
50 return Ok(src.to_string());
51 }
52 if let Some(cfg) = crud {
53 let entity = pascal_to_snake(return_type);
54 if let Some(resolved) = cfg.resolve(operation, &entity) {
55 return Ok(resolved);
56 }
57 }
58 anyhow::bail!(
59 "Mutation '{mutation_name}' has no `sql_source` and no `[crud]` naming config \
60 could resolve it (operation = {operation:?}, return_type = {return_type:?}). \
61 Either add `sql_source` to the mutation or configure `[crud]` in fraiseql.toml."
62 )
63}
64
65pub struct SchemaMerger;
67
68impl SchemaMerger {
69 pub fn merge_files(types_path: &str, toml_path: &str) -> Result<IntermediateSchema> {
83 let types_json = fs::read_to_string(types_path)
85 .context(format!("Failed to read types.json from {types_path}"))?;
86 let types_value: Value =
87 serde_json::from_str(&types_json).context("Failed to parse types.json")?;
88
89 let toml_schema = TomlSchema::from_file(toml_path)
91 .context(format!("Failed to load TOML from {toml_path}"))?;
92
93 Self::merge_values(&types_value, &toml_schema)
98 }
99
100 pub fn merge_toml_only(toml_path: &str) -> Result<IntermediateSchema> {
113 let toml_schema = TomlSchema::from_file(toml_path)
114 .context(format!("Failed to load TOML from {toml_path}"))?;
115
116 toml_schema.validate()?;
117
118 let types_value = toml_schema.to_intermediate_schema();
120 Self::merge_values(&types_value, &toml_schema)
121 }
122
123 pub fn merge_from_directory(toml_path: &str, schema_dir: &str) -> Result<IntermediateSchema> {
137 let toml_schema = TomlSchema::from_file(toml_path)
138 .context(format!("Failed to load TOML from {toml_path}"))?;
139
140 toml_schema.validate()?;
141
142 let types_value = crate::schema::MultiFileLoader::load_from_directory(schema_dir)
144 .context(format!("Failed to load schema from directory {schema_dir}"))?;
145
146 Self::merge_values(&types_value, &toml_schema)
148 }
149
150 fn load_section(files: &[String], key: &str) -> Result<Option<serde_json::Value>> {
152 if files.is_empty() {
153 return Ok(None);
154 }
155 let paths: Vec<std::path::PathBuf> = files.iter().map(std::path::PathBuf::from).collect();
156 let loaded = crate::schema::MultiFileLoader::load_from_paths(&paths)
157 .with_context(|| format!("Failed to load {key} files"))?;
158 Ok(loaded.get(key).cloned())
159 }
160
161 fn extend_from_json_file(
164 path: &std::path::Path,
165 all_types: &mut Vec<Value>,
166 all_queries: &mut Vec<Value>,
167 all_mutations: &mut Vec<Value>,
168 ) -> Result<()> {
169 let content = fs::read_to_string(path)
170 .with_context(|| format!("Failed to read {}", path.display()))?;
171 let value: Value = serde_json::from_str(&content)
172 .with_context(|| format!("Failed to parse {}", path.display()))?;
173 for (vec, key) in [
174 (all_types as &mut Vec<Value>, "types"),
175 (all_queries, "queries"),
176 (all_mutations, "mutations"),
177 ] {
178 if let Some(Value::Array(items)) = value.get(key) {
179 vec.extend(items.iter().cloned());
180 }
181 }
182 Ok(())
183 }
184
185 fn enrich_type_from_toml(
187 enriched_type: &mut Value,
188 toml_type: &crate::config::toml_schema::TypeDefinition,
189 ) {
190 enriched_type["sql_source"] = json!(toml_type.sql_source);
191 if let Some(desc) = &toml_type.description {
192 enriched_type["description"] = json!(desc);
193 }
194 }
195
196 pub fn merge_explicit_files(
212 toml_path: &str,
213 type_files: &[String],
214 query_files: &[String],
215 mutation_files: &[String],
216 ) -> Result<IntermediateSchema> {
217 let toml_schema = TomlSchema::from_file(toml_path)
218 .context(format!("Failed to load TOML from {toml_path}"))?;
219
220 toml_schema.validate()?;
221
222 let mut types_value = serde_json::json!({
223 "types": [],
224 "queries": [],
225 "mutations": []
226 });
227
228 if let Some(v) = Self::load_section(type_files, "types")? {
229 types_value["types"] = v;
230 }
231 if let Some(v) = Self::load_section(query_files, "queries")? {
232 types_value["queries"] = v;
233 }
234 if let Some(v) = Self::load_section(mutation_files, "mutations")? {
235 types_value["mutations"] = v;
236 }
237
238 Self::merge_values(&types_value, &toml_schema)
239 }
240
241 pub fn merge_from_domains(toml_path: &str) -> Result<IntermediateSchema> {
255 let toml_schema = TomlSchema::from_file(toml_path)
256 .context(format!("Failed to load TOML from {toml_path}"))?;
257
258 toml_schema.validate()?;
259
260 let domains = toml_schema
262 .domain_discovery
263 .resolve_domains()
264 .context("Failed to discover domains")?;
265
266 if domains.is_empty() {
267 let empty_value = serde_json::json!({
269 "types": [],
270 "queries": [],
271 "mutations": []
272 });
273 return Self::merge_values(&empty_value, &toml_schema);
274 }
275
276 let mut all_types = Vec::new();
277 let mut all_queries = Vec::new();
278 let mut all_mutations = Vec::new();
279
280 for domain in domains {
281 for filename in ["types.json", "queries.json", "mutations.json"] {
282 let path = domain.path.join(filename);
283 if path.exists() {
284 Self::extend_from_json_file(
285 &path,
286 &mut all_types,
287 &mut all_queries,
288 &mut all_mutations,
289 )?;
290 }
291 }
292 }
293
294 let types_value = serde_json::json!({
295 "types": all_types,
296 "queries": all_queries,
297 "mutations": all_mutations,
298 });
299
300 Self::merge_values(&types_value, &toml_schema)
302 }
303
304 pub fn merge_with_includes(toml_path: &str) -> Result<IntermediateSchema> {
318 let toml_schema = TomlSchema::from_file(toml_path)
319 .context(format!("Failed to load TOML from {toml_path}"))?;
320
321 toml_schema.validate()?;
322
323 let types_value = if toml_schema.includes.is_empty() {
325 serde_json::json!({
327 "types": [],
328 "queries": [],
329 "mutations": []
330 })
331 } else {
332 let resolved = toml_schema
333 .includes
334 .resolve_globs()
335 .context("Failed to resolve glob patterns in schema.includes")?;
336
337 let type_files: Vec<std::path::PathBuf> = resolved.types;
339 let mut merged_types = if type_files.is_empty() {
340 serde_json::json!({
341 "types": [],
342 "queries": [],
343 "mutations": []
344 })
345 } else {
346 crate::schema::MultiFileLoader::load_from_paths(&type_files)
347 .context("Failed to load type files")?
348 };
349
350 if !resolved.queries.is_empty() {
352 let loaded = crate::schema::MultiFileLoader::load_from_paths(&resolved.queries)
353 .context("Failed to load query files")?;
354 let new_items =
355 loaded.get("queries").and_then(Value::as_array).cloned().unwrap_or_default();
356 if let Some(Value::Array(existing)) = merged_types.get_mut("queries") {
357 existing.extend(new_items);
358 }
359 }
360
361 if !resolved.mutations.is_empty() {
363 let loaded = crate::schema::MultiFileLoader::load_from_paths(&resolved.mutations)
364 .context("Failed to load mutation files")?;
365 let new_items =
366 loaded.get("mutations").and_then(Value::as_array).cloned().unwrap_or_default();
367 if let Some(Value::Array(existing)) = merged_types.get_mut("mutations") {
368 existing.extend(new_items);
369 }
370 }
371
372 merged_types
373 };
374
375 Self::merge_values(&types_value, &toml_schema)
377 }
378
379 #[allow(clippy::cognitive_complexity)] fn merge_values(types_value: &Value, toml_schema: &TomlSchema) -> Result<IntermediateSchema> {
382 if toml_schema.queries.contains_key("defaults") {
384 anyhow::bail!(
385 "Found a query definition named 'defaults' under [queries.defaults]. \
386 Did you mean [query_defaults] to set global auto-param defaults?\n\
387 If you intended a query called 'defaults', rename it to avoid confusion."
388 );
389 }
390
391 let mut types_array: Vec<Value> = Vec::new();
394 let mut queries_array: Vec<Value> = Vec::new();
395 let mut mutations_array: Vec<Value> = Vec::new();
396
397 if let Some(types_obj) = types_value.get("types") {
399 match types_obj {
400 Value::Array(types_list) => {
402 for type_item in types_list {
403 if let Some(type_name) = type_item.get("name").and_then(|v| v.as_str()) {
404 let mut enriched_type = type_item.clone();
405 if let Some(toml_type) = toml_schema.types.get(type_name) {
406 Self::enrich_type_from_toml(&mut enriched_type, toml_type);
407 }
408 types_array.push(enriched_type);
409 }
410 }
411 },
412 Value::Object(types_map) => {
414 for (type_name, type_value) in types_map {
415 let mut enriched_type = type_value.clone();
416 enriched_type["name"] = json!(type_name);
417
418 if let Some(Value::Object(fields_map)) = enriched_type.get("fields") {
420 let fields_array: Vec<Value> = fields_map
421 .iter()
422 .map(|(field_name, field_value)| {
423 let mut field = field_value.clone();
424 field["name"] = json!(field_name);
425 field
426 })
427 .collect();
428 enriched_type["fields"] = json!(fields_array);
429 }
430
431 if let Some(toml_type) = toml_schema.types.get(type_name) {
432 Self::enrich_type_from_toml(&mut enriched_type, toml_type);
433 }
434
435 types_array.push(enriched_type);
436 }
437 },
438 _ => {},
439 }
440 }
441
442 let existing_type_names: std::collections::HashSet<_> = types_array
444 .iter()
445 .filter_map(|t| t.get("name").and_then(|v| v.as_str()).map(str::to_string))
446 .collect();
447
448 for (type_name, toml_type) in &toml_schema.types {
449 if !existing_type_names.contains(type_name) {
450 types_array.push(json!({
451 "name": type_name,
452 "sql_source": toml_type.sql_source,
453 "description": toml_type.description,
454 "fields": toml_type.fields.iter().map(|(fname, fdef)| {
455 let mut field = json!({
456 "name": fname,
457 "type": fdef.field_type,
458 "nullable": fdef.nullable,
459 "description": fdef.description,
460 });
461 if let Some(ref h) = fdef.hierarchy {
462 field["hierarchy"] = json!(h);
463 }
464 field
465 }).collect::<Vec<_>>(),
466 }));
467 }
468 }
469
470 if let Some(Value::Array(queries_list)) = types_value.get("queries") {
471 queries_array.clone_from(queries_list);
472 }
473
474 for (query_name, toml_query) in &toml_schema.queries {
476 queries_array.push(json!({
477 "name": query_name,
478 "return_type": toml_query.return_type,
479 "returns_list": toml_query.return_array,
480 "sql_source": toml_query.sql_source,
481 "description": toml_query.description,
482 "args": toml_query.args.iter().map(|arg| json!({
483 "name": arg.name,
484 "type": arg.arg_type,
485 "required": arg.required,
486 "default": arg.default,
487 "description": arg.description,
488 })).collect::<Vec<_>>(),
489 }));
490 }
491
492 if let Some(Value::Array(mutations_list)) = types_value.get("mutations") {
493 mutations_array.clone_from(mutations_list);
494 }
495
496 for (mutation_name, toml_mutation) in &toml_schema.mutations {
498 let sql_source = resolve_mutation_sql_source(
499 mutation_name,
500 toml_mutation.sql_source.as_deref(),
501 &toml_mutation.operation,
502 &toml_mutation.return_type,
503 toml_schema.crud.as_ref(),
504 )?;
505 mutations_array.push(json!({
506 "name": mutation_name,
507 "return_type": toml_mutation.return_type,
508 "sql_source": sql_source,
509 "operation": toml_mutation.operation,
510 "description": toml_mutation.description,
511 "args": toml_mutation.args.iter().map(|arg| json!({
512 "name": arg.name,
513 "type": arg.arg_type,
514 "required": arg.required,
515 "default": arg.default,
516 "description": arg.description,
517 })).collect::<Vec<_>>(),
518 }));
519 }
520
521 let mut merged = serde_json::json!({
523 "version": "2.0.0",
524 "types": types_array,
525 "queries": queries_array,
526 "mutations": mutations_array,
527 });
528
529 if let Some(pkce) = &toml_schema.security.pkce {
531 if pkce.enabled {
532 let enc_enabled =
533 toml_schema.security.state_encryption.as_ref().is_some_and(|e| e.enabled);
534 if !enc_enabled {
535 tracing::warn!(
536 "pkce.enabled = true but state_encryption.enabled = false. \
537 PKCE state will be stored unencrypted. \
538 Set [security.state_encryption] enabled = true for production."
539 );
540 }
541 }
542 }
543
544 merged["security"] = json!({
546 "default_policy": toml_schema.security.default_policy,
547 "rules": toml_schema.security.rules.iter().map(|r| json!({
548 "name": r.name,
549 "rule": r.rule,
550 "description": r.description,
551 "cacheable": r.cacheable,
552 "cache_ttl_seconds": r.cache_ttl_seconds,
553 })).collect::<Vec<_>>(),
554 "policies": toml_schema.security.policies.iter().map(|p| json!({
555 "name": p.name,
556 "type": p.policy_type,
557 "rule": p.rule,
558 "roles": p.roles,
559 "strategy": p.strategy,
560 "attributes": p.attributes,
561 "description": p.description,
562 "cache_ttl_seconds": p.cache_ttl_seconds,
563 })).collect::<Vec<_>>(),
564 "field_auth": toml_schema.security.field_auth.iter().map(|fa| json!({
565 "type_name": fa.type_name,
566 "field_name": fa.field_name,
567 "policy": fa.policy,
568 })).collect::<Vec<_>>(),
569 "enterprise": json!({
570 "rate_limiting_enabled": toml_schema.security.enterprise.rate_limiting_enabled,
571 "auth_endpoint_max_requests": toml_schema.security.enterprise.auth_endpoint_max_requests,
572 "auth_endpoint_window_seconds": toml_schema.security.enterprise.auth_endpoint_window_seconds,
573 "audit_logging_enabled": toml_schema.security.enterprise.audit_logging_enabled,
574 "audit_log_backend": toml_schema.security.enterprise.audit_log_backend,
575 "audit_retention_days": toml_schema.security.enterprise.audit_retention_days,
576 "error_sanitization": toml_schema.security.enterprise.error_sanitization,
577 "hide_implementation_details": toml_schema.security.enterprise.hide_implementation_details,
578 "constant_time_comparison": toml_schema.security.enterprise.constant_time_comparison,
579 "pkce_enabled": toml_schema.security.enterprise.pkce_enabled,
580 }),
581 "error_sanitization": toml_schema.security.error_sanitization,
582 "rate_limiting": toml_schema.security.rate_limiting,
583 "state_encryption": toml_schema.security.state_encryption,
584 "pkce": toml_schema.security.pkce,
585 "api_keys": toml_schema.security.api_keys,
586 "token_revocation": toml_schema.security.token_revocation,
587 "trusted_documents": toml_schema.security.trusted_documents,
588 });
589
590 if toml_schema.observers.enabled
592 || toml_schema.observers.redis_url.is_some()
593 || toml_schema.observers.nats_url.is_some()
594 {
595 if toml_schema.observers.backend == "nats" && toml_schema.observers.nats_url.is_none() {
596 tracing::warn!(
597 "observers.backend is \"nats\" but observers.nats_url is not set; \
598 the runtime will require FRAISEQL_NATS_URL to be configured"
599 );
600 }
601 merged["observers_config"] = json!({
602 "enabled": toml_schema.observers.enabled,
603 "backend": toml_schema.observers.backend,
604 "redis_url": toml_schema.observers.redis_url,
605 "nats_url": toml_schema.observers.nats_url,
606 "handlers": toml_schema.observers.handlers.iter().map(|h| json!({
607 "name": h.name,
608 "event": h.event,
609 "action": h.action,
610 "webhook_url": h.webhook_url,
611 "retry_strategy": h.retry_strategy,
612 "max_retries": h.max_retries,
613 "description": h.description,
614 })).collect::<Vec<_>>(),
615 });
616 }
617
618 if toml_schema.federation.enabled {
620 merged["federation_config"] = serde_json::to_value(&toml_schema.federation)
621 .context("Failed to serialize federation config")?;
622 }
623
624 let subs_json = serde_json::to_value(&toml_schema.subscriptions)
626 .context("Failed to serialize subscriptions config")?;
627 if subs_json != serde_json::json!({}) {
628 merged["subscriptions_config"] = subs_json;
629 }
630
631 let val_json = serde_json::to_value(&toml_schema.validation)
633 .context("Failed to serialize validation config")?;
634 if val_json != serde_json::json!({}) {
635 merged["validation_config"] = val_json;
636 }
637
638 if toml_schema.debug.enabled {
640 let debug_json = serde_json::to_value(&toml_schema.debug)
641 .context("Failed to serialize debug config")?;
642 merged["debug_config"] = debug_json;
643 }
644
645 if toml_schema.mcp.enabled {
647 merged["mcp_config"] =
648 serde_json::to_value(&toml_schema.mcp).context("Failed to serialize MCP config")?;
649 }
650
651 if toml_schema.rest.enabled {
653 let path = &toml_schema.rest.path;
654 if !path.starts_with('/') {
655 anyhow::bail!("REST config: `path` must start with '/' (got {path:?})");
656 }
657
658 let rest_config: fraiseql_core::schema::RestConfig = toml_schema.rest.clone().into();
659
660 merged["rest_config"] =
661 serde_json::to_value(&rest_config).context("Failed to serialize REST config")?;
662 }
663
664 merged["naming_convention"] = serde_json::to_value(toml_schema.naming_convention)
666 .context("Failed to serialize naming_convention")?;
667
668 if let Some(ref hierarchies) = toml_schema.hierarchies {
670 merged["hierarchies_config"] = serde_json::to_value(hierarchies)
671 .context("Failed to serialize hierarchies config")?;
672 }
673
674 let mut schema = serde_json::from_value::<IntermediateSchema>(merged)
676 .context("Failed to convert merged schema to IntermediateSchema")?;
677
678 schema.query_defaults = Some(IntermediateQueryDefaults {
681 where_clause: toml_schema.query_defaults.where_clause,
682 order_by: toml_schema.query_defaults.order_by,
683 limit: toml_schema.query_defaults.limit,
684 offset: toml_schema.query_defaults.offset,
685 });
686
687 Ok(schema)
688 }
689}