ucp-schema 1.3.0

Runtime resolution of UCP schema annotations
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Schema loading from various sources.
//!
//! Handles loading schemas from files, strings, and HTTP URLs.

use std::path::Path;

use serde_json::Value;

use crate::error::ResolveError;

#[cfg(feature = "remote")]
use std::time::Duration;

/// Default timeout for HTTP requests (10 seconds).
#[cfg(feature = "remote")]
const HTTP_TIMEOUT: Duration = Duration::from_secs(10);

/// Load a schema from a file path.
///
/// # Errors
///
/// Returns `ResolveError::FileNotFound` if the file doesn't exist,
/// or `ResolveError::InvalidJson` if the file isn't valid JSON.
pub fn load_schema(path: &Path) -> Result<Value, ResolveError> {
    if !path.exists() {
        return Err(ResolveError::FileNotFound {
            path: path.to_path_buf(),
        });
    }

    let content = std::fs::read_to_string(path).map_err(|source| ResolveError::ReadError {
        path: path.to_path_buf(),
        source,
    })?;

    serde_json::from_str(&content).map_err(|source| ResolveError::InvalidJson { source })
}

/// Load a schema from a JSON string.
///
/// # Errors
///
/// Returns `ResolveError::InvalidJson` if the string isn't valid JSON.
pub fn load_schema_str(content: &str) -> Result<Value, ResolveError> {
    serde_json::from_str(content).map_err(|source| ResolveError::InvalidJson { source })
}

/// Load a schema from an HTTP/HTTPS URL.
///
/// Requires the `remote` feature (enabled by default).
///
/// # Errors
///
/// Returns `ResolveError::NetworkError` if the request fails,
/// or `ResolveError::InvalidJson` if the response isn't valid JSON.
#[cfg(feature = "remote")]
pub fn load_schema_url(url: &str) -> Result<Value, ResolveError> {
    let client = reqwest::blocking::Client::builder()
        .timeout(HTTP_TIMEOUT)
        .build()
        .map_err(|source| ResolveError::NetworkError {
            url: url.to_string(),
            source,
        })?;

    let response = client
        .get(url)
        .send()
        .map_err(|source| ResolveError::NetworkError {
            url: url.to_string(),
            source,
        })?;

    // Check for HTTP errors before parsing
    let response = response
        .error_for_status()
        .map_err(|source| ResolveError::NetworkError {
            url: url.to_string(),
            source,
        })?;

    response
        .json()
        .map_err(|source| ResolveError::NetworkError {
            url: url.to_string(),
            source,
        })
}

/// Check if a string looks like a URL (starts with http:// or https://).
pub fn is_url(s: &str) -> bool {
    s.starts_with("http://") || s.starts_with("https://")
}

/// Navigate a JSON Pointer fragment (e.g., "#/$defs/foo" or "#/properties/bar").
///
/// Returns the value at the given JSON Pointer path within the schema.
/// The fragment should start with '#' (e.g., "#/$defs/foo").
pub fn navigate_fragment(schema: &Value, fragment: &str) -> Result<Value, ResolveError> {
    // Remove leading # and split by /
    let path = fragment.trim_start_matches('#').trim_start_matches('/');
    if path.is_empty() {
        return Ok(schema.clone());
    }

    let mut current = schema;
    for part in path.split('/') {
        // Unescape JSON Pointer encoding (~1 = /, ~0 = ~)
        let key = part.replace("~1", "/").replace("~0", "~");
        current = current.get(&key).ok_or_else(|| ResolveError::BundleError {
            message: format!("fragment not found: {}", fragment),
        })?;
    }
    Ok(current.clone())
}

/// Recursively resolve and inline external $ref pointers.
///
/// Walks the schema tree, finds `$ref` values pointing to external files,
/// loads them, and replaces the $ref with the loaded content.
/// Internal refs (`#/...`) in the root schema are left for the validator.
/// Internal refs in loaded external files are resolved against that file.
/// Self-root refs (`$ref: "#"`) are left as-is (recursive type definitions).
///
/// # Arguments
/// * `schema` - The schema to process (modified in place)
/// * `base_dir` - Base directory for resolving relative file paths
pub fn bundle_refs(schema: &mut Value, base_dir: &Path) -> Result<(), ResolveError> {
    // Snapshot root schema so internal #/$defs/ refs can resolve against it.
    let root_snapshot = schema.clone();
    bundle_refs_inner(
        schema,
        base_dir,
        Some(&root_snapshot),
        None,
        None,
        &mut std::collections::HashSet::new(),
    )
}

/// Bundle external $ref pointers with URL-to-local-path mapping.
///
/// Like `bundle_refs`, but handles absolute URL refs by mapping them to local paths.
/// When a ref starts with `remote_base`, that prefix is stripped and the remainder
/// is joined to `local_base` to form the local file path.
///
/// # Example
/// ```text
/// remote_base = "https://ucp.dev/draft"
/// local_base = Path::new("site")
/// $ref = "https://ucp.dev/draft/schemas/ucp.json" -> "site/schemas/ucp.json"
/// ```
pub fn bundle_refs_with_url_mapping(
    schema: &mut Value,
    base_dir: &Path,
    local_base: &Path,
    remote_base: &str,
) -> Result<(), ResolveError> {
    let root_snapshot = schema.clone();
    bundle_refs_inner(
        schema,
        base_dir,
        Some(&root_snapshot),
        Some(local_base),
        Some(remote_base),
        &mut std::collections::HashSet::new(),
    )
}

fn bundle_refs_inner(
    schema: &mut Value,
    base_dir: &Path,
    file_root: Option<&Value>, // Root of external file for resolving internal refs
    url_local_base: Option<&Path>,
    url_remote_base: Option<&str>,
    visited: &mut std::collections::HashSet<String>,
) -> Result<(), ResolveError> {
    match schema {
        Value::Object(obj) => {
            // Check if this object has a $ref
            if let Some(ref_val) = obj.get("$ref").and_then(|v| v.as_str()) {
                if ref_val.starts_with('#') {
                    // Internal ref - only resolve if we have a file_root context
                    // Skip self-root refs ($ref: "#") - these are recursive type defs
                    if ref_val == "#" {
                        // Leave as-is - can't inline recursive self-reference
                    } else if let Some(root) = file_root {
                        let mut target = navigate_fragment(root, ref_val)?;
                        // Recursively process (may have nested refs)
                        bundle_refs_inner(
                            &mut target,
                            base_dir,
                            file_root,
                            url_local_base,
                            url_remote_base,
                            visited,
                        )?;
                        // Inline the resolved definition
                        obj.remove("$ref");
                        if let Value::Object(ref_obj) = target {
                            for (k, v) in ref_obj {
                                obj.entry(k).or_insert(v);
                            }
                        }
                        return Ok(());
                    }
                    // No file_root context — leave as-is
                } else {
                    // External ref - may be relative path or absolute URL
                    let (file_part, fragment) = match ref_val.find('#') {
                        Some(idx) => (&ref_val[..idx], Some(&ref_val[idx..])),
                        None => (ref_val, None),
                    };

                    // Resolve ref to local path, handling URL mapping if configured
                    let ref_path =
                        resolve_ref_to_path(file_part, base_dir, url_local_base, url_remote_base);

                    // If local resolution fails and the ref is a URL, try HTTP fetch
                    #[cfg(feature = "remote")]
                    let (loaded, ref_dir_owned) = if !ref_path.exists() && is_url(file_part) {
                        let fetched = load_schema_url(file_part)?;
                        // Remote schemas have no local directory; use base_dir for
                        // any relative refs within the fetched schema
                        (fetched, base_dir.to_path_buf())
                    } else {
                        let schema = load_schema(&ref_path)?;
                        let dir = ref_path.parent().unwrap_or(base_dir).to_path_buf();
                        (schema, dir)
                    };

                    #[cfg(not(feature = "remote"))]
                    let (loaded, ref_dir_owned) = {
                        let schema = load_schema(&ref_path)?;
                        let dir = ref_path.parent().unwrap_or(base_dir).to_path_buf();
                        (schema, dir)
                    };

                    let canonical = ref_path.canonicalize().unwrap_or(ref_path.clone());
                    let visit_key = format!("{}|{}", canonical.display(), fragment.unwrap_or(""));

                    if visited.contains(&visit_key) {
                        return Err(ResolveError::BundleError {
                            message: format!("circular reference detected: {}", ref_val),
                        });
                    }

                    let mut target = if let Some(frag) = fragment {
                        navigate_fragment(&loaded, frag)?
                    } else {
                        loaded.clone()
                    };

                    visited.insert(visit_key.clone());
                    // Pass loaded file as file_root so internal refs resolve against it
                    bundle_refs_inner(
                        &mut target,
                        &ref_dir_owned,
                        Some(&loaded),
                        url_local_base,
                        url_remote_base,
                        visited,
                    )?;
                    visited.remove(&visit_key);

                    obj.remove("$ref");
                    if let Value::Object(ref_obj) = target {
                        for (k, v) in ref_obj {
                            obj.entry(k).or_insert(v);
                        }
                    }
                    return Ok(());
                }
            }

            // Recurse into all values
            for value in obj.values_mut() {
                bundle_refs_inner(
                    value,
                    base_dir,
                    file_root,
                    url_local_base,
                    url_remote_base,
                    visited,
                )?;
            }
        }
        Value::Array(arr) => {
            for item in arr {
                bundle_refs_inner(
                    item,
                    base_dir,
                    file_root,
                    url_local_base,
                    url_remote_base,
                    visited,
                )?;
            }
        }
        _ => {}
    }
    Ok(())
}

/// Resolve a $ref value to a local file path.
///
/// If URL mapping is configured and the ref matches the remote base,
/// strips the prefix and joins to local_base. Otherwise uses base_dir
/// for relative path resolution.
fn resolve_ref_to_path(
    ref_val: &str,
    base_dir: &Path,
    url_local_base: Option<&Path>,
    url_remote_base: Option<&str>,
) -> std::path::PathBuf {
    // Check if this is an absolute URL that matches our remote base
    if let (Some(local_base), Some(remote_base)) = (url_local_base, url_remote_base) {
        if let Some(remainder) = ref_val.strip_prefix(remote_base) {
            // URL matches remote base - map to local path
            return local_base.join(remainder.trim_start_matches('/'));
        }
    }

    // Default: treat as relative path from base_dir
    base_dir.join(ref_val)
}

/// Bundle external $ref pointers by fetching from remote URLs.
///
/// Like `bundle_refs`, but fetches external refs via HTTP instead of local files.
/// This allows remote-only validation by inlining all refs before passing to
/// the JSON Schema validator.
///
/// # Arguments
/// * `schema` - The schema to process (modified in place)
/// * `base_url` - Base URL for resolving relative refs (typically the schema's $id)
#[cfg(feature = "remote")]
pub fn bundle_refs_remote(schema: &mut Value, base_url: &str) -> Result<(), ResolveError> {
    // Snapshot root schema so internal #/$defs/ refs can resolve against it.
    let root_snapshot = schema.clone();
    bundle_refs_remote_inner(
        schema,
        base_url,
        Some(&root_snapshot),
        &mut std::collections::HashSet::new(),
    )
}

#[cfg(feature = "remote")]
fn bundle_refs_remote_inner(
    schema: &mut Value,
    base_url: &str,
    file_root: Option<&Value>,
    visited: &mut std::collections::HashSet<String>,
) -> Result<(), ResolveError> {
    match schema {
        Value::Object(obj) => {
            if let Some(ref_val) = obj.get("$ref").and_then(|v| v.as_str()) {
                if ref_val.starts_with('#') {
                    // Internal ref
                    if ref_val == "#" {
                        // Self-reference, leave as-is
                    } else if let Some(root) = file_root {
                        let mut target = navigate_fragment(root, ref_val)?;
                        bundle_refs_remote_inner(&mut target, base_url, file_root, visited)?;
                        obj.remove("$ref");
                        if let Value::Object(ref_obj) = target {
                            for (k, v) in ref_obj {
                                obj.entry(k).or_insert(v);
                            }
                        }
                        return Ok(());
                    }
                    // No file_root context — leave as-is
                } else {
                    // External ref - resolve URL
                    let (file_part, fragment) = match ref_val.find('#') {
                        Some(idx) => (&ref_val[..idx], Some(&ref_val[idx..])),
                        None => (ref_val, None),
                    };

                    // Resolve to absolute URL
                    let resolved_url = resolve_url(file_part, base_url);
                    let visit_key = format!("{}|{}", resolved_url, fragment.unwrap_or(""));

                    if visited.contains(&visit_key) {
                        return Err(ResolveError::BundleError {
                            message: format!("circular reference detected: {}", ref_val),
                        });
                    }

                    // Fetch the referenced schema
                    let loaded = load_schema_url(&resolved_url)?;
                    let mut target = if let Some(frag) = fragment {
                        navigate_fragment(&loaded, frag)?
                    } else {
                        loaded.clone()
                    };

                    visited.insert(visit_key.clone());
                    // Recursively bundle with new base URL
                    bundle_refs_remote_inner(&mut target, &resolved_url, Some(&loaded), visited)?;
                    visited.remove(&visit_key);

                    obj.remove("$ref");
                    if let Value::Object(ref_obj) = target {
                        for (k, v) in ref_obj {
                            obj.entry(k).or_insert(v);
                        }
                    }
                    return Ok(());
                }
            }

            // Recurse into all values
            for value in obj.values_mut() {
                bundle_refs_remote_inner(value, base_url, file_root, visited)?;
            }
        }
        Value::Array(arr) => {
            for item in arr {
                bundle_refs_remote_inner(item, base_url, file_root, visited)?;
            }
        }
        _ => {}
    }
    Ok(())
}

/// Resolve a potentially relative URL against a base URL.
#[cfg(feature = "remote")]
fn resolve_url(url: &str, base: &str) -> String {
    if is_url(url) {
        // Already absolute
        url.to_string()
    } else {
        // Relative - resolve against base
        // Find the directory part of base URL
        if let Some(idx) = base.rfind('/') {
            format!("{}/{}", &base[..idx], url)
        } else {
            url.to_string()
        }
    }
}

/// Load a schema from a file path or URL.
///
/// Automatically detects whether the source is a URL or file path.
/// URL loading requires the `remote` feature.
///
/// # Errors
///
/// Returns appropriate errors based on the source type.
pub fn load_schema_auto(source: &str) -> Result<Value, ResolveError> {
    if is_url(source) {
        #[cfg(feature = "remote")]
        {
            load_schema_url(source)
        }
        #[cfg(not(feature = "remote"))]
        {
            Err(ResolveError::FileNotFound {
                path: std::path::PathBuf::from(source),
            })
        }
    } else {
        load_schema(Path::new(source))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn load_schema_valid_file() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, r#"{{"type": "object"}}"#).unwrap();

        let schema = load_schema(file.path()).unwrap();
        assert_eq!(schema["type"], "object");
    }

    #[test]
    fn load_schema_file_not_found() {
        let result = load_schema(Path::new("/nonexistent/path.json"));
        assert!(matches!(result, Err(ResolveError::FileNotFound { .. })));
    }

    #[test]
    fn load_schema_invalid_json() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "not valid json").unwrap();

        let result = load_schema(file.path());
        assert!(matches!(result, Err(ResolveError::InvalidJson { .. })));
    }

    #[test]
    fn load_schema_str_valid() {
        let schema = load_schema_str(r#"{"type": "object"}"#).unwrap();
        assert_eq!(schema["type"], "object");
    }

    #[test]
    fn load_schema_str_invalid() {
        let result = load_schema_str("not json");
        assert!(matches!(result, Err(ResolveError::InvalidJson { .. })));
    }

    #[test]
    fn is_url_https() {
        assert!(is_url("https://example.com/schema.json"));
    }

    #[test]
    fn is_url_http() {
        assert!(is_url("http://example.com/schema.json"));
    }

    #[test]
    fn is_url_file_path() {
        assert!(!is_url("/path/to/schema.json"));
        assert!(!is_url("./schema.json"));
        assert!(!is_url("schema.json"));
    }

    #[test]
    fn load_schema_auto_file() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, r#"{{"type": "string"}}"#).unwrap();

        let schema = load_schema_auto(file.path().to_str().unwrap()).unwrap();
        assert_eq!(schema["type"], "string");
    }

    #[test]
    fn resolve_ref_to_path_with_url_mapping() {
        let base_dir = Path::new("/some/dir");
        let local_base = Path::new("/local/schemas");
        let remote_base = "https://ucp.dev/draft";

        // URL matching remote base gets mapped to local
        let path = resolve_ref_to_path(
            "https://ucp.dev/draft/schemas/ucp.json",
            base_dir,
            Some(local_base),
            Some(remote_base),
        );
        assert_eq!(path, Path::new("/local/schemas/schemas/ucp.json"));
    }

    #[test]
    fn resolve_ref_to_path_url_not_matching_remote() {
        let base_dir = Path::new("/some/dir");
        let local_base = Path::new("/local/schemas");
        let remote_base = "https://ucp.dev/draft";

        // URL not matching remote base falls back to base_dir join
        let path = resolve_ref_to_path(
            "https://other.com/schemas/foo.json",
            base_dir,
            Some(local_base),
            Some(remote_base),
        );
        assert_eq!(
            path,
            Path::new("/some/dir/https://other.com/schemas/foo.json")
        );
    }

    #[test]
    fn resolve_ref_to_path_relative_ref() {
        let base_dir = Path::new("/some/dir");

        // Relative ref without URL mapping
        let path = resolve_ref_to_path("types/buyer.json", base_dir, None, None);
        assert_eq!(path, Path::new("/some/dir/types/buyer.json"));
    }

    #[test]
    fn resolve_ref_to_path_strips_leading_slash() {
        let base_dir = Path::new("/some/dir");
        let local_base = Path::new("/local");
        let remote_base = "https://ucp.dev/draft";

        // Stripping remote base leaves "/schemas/..." - leading slash should be trimmed
        let path = resolve_ref_to_path(
            "https://ucp.dev/draft/schemas/foo.json",
            base_dir,
            Some(local_base),
            Some(remote_base),
        );
        assert_eq!(path, Path::new("/local/schemas/foo.json"));
    }

    // Remote tests run against a local mockito server so they're deterministic
    // and offline — no dependency on a live third party. The connection-error
    // case uses a reserved `.invalid` host (RFC 2606), which fails to resolve
    // locally without touching the network.
    #[cfg(feature = "remote")]
    mod remote {
        use super::*;

        #[test]
        fn load_schema_url_valid() {
            // 200 + JSON body resolves to the parsed value.
            let mut server = mockito::Server::new();
            let mock = server
                .mock("GET", "/schema.json")
                .with_header("content-type", "application/json")
                .with_body(r#"{"type": "object"}"#)
                .create();

            let result = load_schema_url(&format!("{}/schema.json", server.url()));
            assert_eq!(result.unwrap()["type"], "object");
            mock.assert();
        }

        #[test]
        fn load_schema_url_404() {
            // Non-2xx status surfaces as NetworkError (via error_for_status).
            let mut server = mockito::Server::new();
            server
                .mock("GET", "/missing.json")
                .with_status(404)
                .create();

            let result = load_schema_url(&format!("{}/missing.json", server.url()));
            assert!(matches!(result, Err(ResolveError::NetworkError { .. })));
        }

        #[test]
        fn load_schema_url_invalid_host() {
            // Connection/DNS failure surfaces as NetworkError. `.invalid` (RFC
            // 2606) fails to resolve without network access.
            let result =
                load_schema_url("https://this-domain-does-not-exist-12345.invalid/schema.json");
            assert!(matches!(result, Err(ResolveError::NetworkError { .. })));
        }

        #[test]
        fn load_schema_auto_url() {
            // A URL source delegates to load_schema_url.
            let mut server = mockito::Server::new();
            let mock = server
                .mock("GET", "/schema.json")
                .with_header("content-type", "application/json")
                .with_body(r#"{"type": "string"}"#)
                .create();

            let result = load_schema_auto(&format!("{}/schema.json", server.url()));
            assert_eq!(result.unwrap()["type"], "string");
            mock.assert();
        }
    }
}