components-rs 0.1.1

Static analysis tooling for Components.js dependency injection projects
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::error::{ComponentsJsError, Result};

/// A resolved JSON-LD context that maps short terms to full IRIs.
#[derive(Debug, Clone, Default)]
pub struct ContextResolver {
    /// @vocab — default IRI prefix for unmapped terms
    pub vocab: Option<String>,
    /// prefix:suffix mappings (e.g., "oo" -> "https://...#")
    pub prefixes: HashMap<String, String>,
    /// Direct term mappings (e.g., "Class" -> TermDef { iri, type_coercion })
    pub terms: HashMap<String, TermDef>,
}

#[derive(Debug, Clone)]
pub struct TermDef {
    pub iri: String,
    pub type_coercion: Option<String>,
    pub container: Option<String>,
}

impl ContextResolver {
    pub fn new() -> Self {
        Self::default()
    }

    /// Parse a JSON-LD @context value and build the resolver.
    /// `known_contexts` maps context IRIs to their parsed JSON content (from ModuleState.contexts).
    pub fn from_context_value(
        context_value: &serde_json::Value,
        known_contexts: &HashMap<String, serde_json::Value>,
    ) -> Result<Self> {
        let mut resolver = Self::new();
        resolver.load_context_value(context_value, known_contexts)?;
        Ok(resolver)
    }

    fn load_context_value(
        &mut self,
        value: &serde_json::Value,
        known_contexts: &HashMap<String, serde_json::Value>,
    ) -> Result<()> {
        match value {
            serde_json::Value::Array(arr) => {
                for item in arr {
                    self.load_context_value(item, known_contexts)?;
                }
            }
            serde_json::Value::String(url) => {
                // Look up the context by URL in known_contexts
                if let Some(ctx_doc) = known_contexts.get(url.as_str()) {
                    // A context document may have a @context key itself
                    if let Some(inner) = ctx_doc.get("@context") {
                        self.load_context_value(inner, known_contexts)?;
                    } else {
                        // The document IS the context object
                        self.load_context_object(ctx_doc)?;
                    }
                } else {
                    tracing::warn!("Unknown context URL: {url} — skipping");
                }
            }
            serde_json::Value::Object(_) => {
                self.load_context_object(value)?;
            }
            _ => {}
        }
        Ok(())
    }

    fn load_context_object(&mut self, obj: &serde_json::Value) -> Result<()> {
        let map = obj
            .as_object()
            .ok_or_else(|| ComponentsJsError::ContextResolution("Expected object".into()))?;

        for (key, val) in map {
            match key.as_str() {
                "@vocab" => {
                    if let Some(s) = val.as_str() {
                        self.vocab = Some(s.to_string());
                    }
                }
                k if k.starts_with('@') => {
                    // Skip other JSON-LD keywords
                }
                _ => match val {
                    serde_json::Value::String(iri) => {
                        // Could be a prefix (ends with / or #) or a direct term mapping
                        if iri.ends_with('/') || iri.ends_with('#') || iri.ends_with(':') {
                            self.prefixes.insert(key.clone(), iri.clone());
                        } else {
                            self.terms.insert(
                                key.clone(),
                                TermDef {
                                    iri: iri.clone(),
                                    type_coercion: None,
                                    container: None,
                                },
                            );
                        }
                    }
                    serde_json::Value::Object(def) => {
                        if let Some(id) = def.get("@id").and_then(|v| v.as_str()) {
                            let type_coercion =
                                def.get("@type").and_then(|v| v.as_str()).map(String::from);
                            let container = def
                                .get("@container")
                                .and_then(|v| v.as_str())
                                .map(String::from);
                            self.terms.insert(
                                key.clone(),
                                TermDef {
                                    iri: id.to_string(),
                                    type_coercion,
                                    container,
                                },
                            );
                        }
                    }
                    _ => {}
                },
            }
        }
        Ok(())
    }

    /// Expand a compacted term to a full IRI.
    /// E.g., "Class" -> "oo:Class" -> "https://...#Class"
    /// Or "oo:Class" -> "https://...#Class"
    /// Handles chained prefixes like "clv:x" -> "npmd:pkg/x" -> "https://.../pkg/x"
    pub fn expand_term(&self, term: &str) -> String {
        self.expand_term_depth(term, 0)
    }

    fn expand_term_depth(&self, term: &str, depth: usize) -> String {
        if depth > 10 {
            return term.to_string();
        }

        // 1. Check direct term mapping
        if let Some(def) = self.terms.get(term) {
            return self.expand_term_depth(&def.iri, depth + 1);
        }

        // 2. Check prefix:suffix
        if let Some((prefix, suffix)) = term.split_once(':') {
            if !suffix.starts_with("//") {
                if let Some(base) = self.prefixes.get(prefix) {
                    let expanded_base = self.expand_term_depth(base, depth + 1);
                    return format!("{expanded_base}{suffix}");
                }
            }
        }

        // 3. If it already looks like a full IRI, return as-is
        if term.contains("://") {
            return term.to_string();
        }

        // 4. Apply @vocab
        if let Some(vocab) = &self.vocab {
            return format!("{vocab}{term}");
        }

        term.to_string()
    }

    /// Compact a full IRI back to a prefixed form.
    /// Returns the shortest representation: tries exact term matches first,
    /// then prefix matches, then @vocab, falling back to the original IRI.
    pub fn compact_iri(&self, iri: &str) -> String {
        // 1. Check exact reverse term mapping (full IRI → short term)
        for (term, def) in &self.terms {
            let expanded = self.expand_term(&def.iri);
            if expanded == iri {
                return term.clone();
            }
        }

        // 2. Find best prefix match (longest base IRI wins → shortest suffix)
        let mut best: Option<(String, usize)> = None; // (compact form, prefix base len)
        for (prefix, base_iri) in &self.prefixes {
            let expanded_base = self.expand_term(base_iri);
            if let Some(suffix) = iri.strip_prefix(expanded_base.as_str()) {
                let base_len = expanded_base.len();
                if best.as_ref().is_none_or(|(_, bl)| base_len > *bl) {
                    best = Some((format!("{prefix}:{suffix}"), base_len));
                }
            }
        }
        if let Some((compact, _)) = best {
            return compact;
        }

        // 3. Try @vocab
        if let Some(vocab) = &self.vocab {
            if let Some(suffix) = iri.strip_prefix(vocab.as_str()) {
                if !suffix.contains('/') && !suffix.contains('#') {
                    return suffix.to_string();
                }
            }
        }

        iri.to_string()
    }
}

/// Project-wide bidirectional IRI translator.
///
/// Built by merging all known contexts. Provides both expansion (compact → full IRI)
/// and compaction (full IRI → compact form) across the entire project.
#[derive(Debug, Clone, Default)]
pub struct IriCompactor {
    /// Fully expanded prefix map: prefix name → full IRI base.
    prefixes: Vec<(String, String)>,
    /// Fully expanded direct term map: short term → full IRI.
    terms: Vec<(String, String)>,
    /// @vocab value (if any).
    vocab: Option<String>,
}

impl IriCompactor {
    /// Build a project-wide compactor from all known contexts.
    pub fn from_contexts(known_contexts: &HashMap<String, serde_json::Value>) -> Result<Self> {
        // Build a single merged ContextResolver from all contexts
        let mut resolver = ContextResolver::new();
        for ctx_doc in known_contexts.values() {
            if let Some(inner) = ctx_doc.get("@context") {
                resolver.load_context_value(inner, known_contexts)?;
            } else {
                resolver.load_context_object(ctx_doc)?;
            }
        }

        // Pre-expand all prefixes and terms for fast lookup
        let mut prefixes: Vec<(String, String)> = resolver
            .prefixes
            .iter()
            .map(|(name, base)| {
                let expanded = resolver.expand_term(base);
                (name.clone(), expanded)
            })
            .collect();
        // Sort by expanded base length descending (longest match first)
        prefixes.sort_by(|a, b| b.1.len().cmp(&a.1.len()));

        let terms: Vec<(String, String)> = resolver
            .terms
            .iter()
            .map(|(name, def)| {
                let expanded = resolver.expand_term(&def.iri);
                (name.clone(), expanded)
            })
            .collect();

        Ok(Self {
            prefixes,
            terms,
            vocab: resolver.vocab,
        })
    }

    /// Compact a full IRI to its shortest prefixed form.
    pub fn compact(&self, iri: &str) -> String {
        // 1. Exact term match
        for (term, expanded) in &self.terms {
            if expanded == iri {
                return term.clone();
            }
        }

        // 2. Best prefix match (already sorted longest-first)
        for (prefix, base) in &self.prefixes {
            if let Some(suffix) = iri.strip_prefix(base.as_str()) {
                return format!("{prefix}:{suffix}");
            }
        }

        // 3. @vocab
        if let Some(vocab) = &self.vocab {
            if let Some(suffix) = iri.strip_prefix(vocab.as_str()) {
                if !suffix.contains('/') && !suffix.contains('#') {
                    return suffix.to_string();
                }
            }
        }

        iri.to_string()
    }

    /// Expand a compact term to a full IRI.
    pub fn expand(&self, term: &str) -> String {
        // 1. Direct term match
        for (name, expanded) in &self.terms {
            if name == term {
                return expanded.clone();
            }
        }

        // 2. prefix:suffix
        if let Some((prefix, suffix)) = term.split_once(':') {
            if !suffix.starts_with("//") {
                for (name, base) in &self.prefixes {
                    if name == prefix {
                        return format!("{base}{suffix}");
                    }
                }
            }
        }

        // 3. Already a full IRI
        if term.contains("://") {
            return term.to_string();
        }

        // 4. @vocab
        if let Some(vocab) = &self.vocab {
            return format!("{vocab}{term}");
        }

        term.to_string()
    }
}

/// An expanded JSON-LD node with full IRIs as keys.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpandedNode {
    pub id: Option<String>,
    pub types: Vec<String>,
    pub properties: HashMap<String, Vec<serde_json::Value>>,
}

/// Extract the @graph entries from a JSON-LD document, expanding all terms.
pub fn extract_graph_nodes(
    doc: &serde_json::Value,
    known_contexts: &HashMap<String, serde_json::Value>,
) -> Result<Vec<ExpandedNode>> {
    // Build the context resolver from the document's @context
    let resolver = if let Some(ctx) = doc.get("@context") {
        ContextResolver::from_context_value(ctx, known_contexts)?
    } else {
        ContextResolver::new()
    };

    // Get graph entries: either @graph array or the document itself
    let entries: Vec<&serde_json::Value> = if let Some(graph) = doc.get("@graph") {
        if let Some(arr) = graph.as_array() {
            arr.iter().collect()
        } else {
            vec![graph]
        }
    } else if doc.get("@id").is_some() || doc.get("@type").is_some() {
        // The document itself is a node
        vec![doc]
    } else {
        vec![]
    };

    let mut nodes = Vec::new();
    for entry in entries {
        if let Some(node) = expand_node(entry, &resolver) {
            nodes.push(node);
        }
    }
    Ok(nodes)
}

fn expand_node(value: &serde_json::Value, resolver: &ContextResolver) -> Option<ExpandedNode> {
    let obj = value.as_object()?;

    let id = obj.get("@id").and_then(|v| v.as_str()).map(|s| resolver.expand_term(s));

    let types: Vec<String> = match obj.get("@type") {
        Some(serde_json::Value::String(t)) => vec![resolver.expand_term(t)],
        Some(serde_json::Value::Array(arr)) => arr
            .iter()
            .filter_map(|v| v.as_str())
            .map(|s| resolver.expand_term(s))
            .collect(),
        _ => vec![],
    };

    let mut properties = HashMap::new();
    for (key, val) in obj {
        if key.starts_with('@') {
            continue;
        }
        let expanded_key = resolver.expand_term(key);
        let values = normalize_to_array(val);
        properties.insert(expanded_key, values);
    }

    Some(ExpandedNode {
        id,
        types,
        properties,
    })
}

fn normalize_to_array(value: &serde_json::Value) -> Vec<serde_json::Value> {
    match value {
        serde_json::Value::Array(arr) => arr.clone(),
        other => vec![other.clone()],
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_cjs_context() -> HashMap<String, serde_json::Value> {
        let ctx_json: serde_json::Value = serde_json::json!({
            "@context": {
                "oo": "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#",
                "Module": { "@id": "oo:Module" },
                "Class": { "@id": "oo:Class" },
                "AbstractClass": { "@id": "oo:AbstractClass" },
                "components": { "@id": "oo:component" },
                "parameters": { "@id": "oo:parameter" },
                "extends": { "@id": "rdfs:subClassOf", "@type": "@id" },
                "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
                "doap": "http://usefulinc.com/ns/doap#",
                "requireName": { "@id": "doap:name" },
                "requireElement": { "@id": "oo:componentPath" },
                "import": { "@id": "rdfs:seeAlso", "@type": "@id" }
            }
        });
        let mut known = HashMap::new();
        known.insert(
            "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld".to_string(),
            ctx_json,
        );
        known
    }

    #[test]
    fn test_expand_term_direct_mapping() {
        let known = make_cjs_context();
        let ctx_ref = serde_json::json!([
            "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld"
        ]);
        let resolver = ContextResolver::from_context_value(&ctx_ref, &known).unwrap();

        assert_eq!(
            resolver.expand_term("Class"),
            "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Class"
        );
        assert_eq!(
            resolver.expand_term("Module"),
            "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Module"
        );
    }

    #[test]
    fn test_expand_term_prefix() {
        let known = make_cjs_context();
        let ctx_ref = serde_json::json!([
            "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld"
        ]);
        let resolver = ContextResolver::from_context_value(&ctx_ref, &known).unwrap();

        assert_eq!(
            resolver.expand_term("oo:Class"),
            "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Class"
        );
    }

    #[test]
    fn test_expand_term_with_local_context() {
        let known = make_cjs_context();
        let ctx_ref = serde_json::json!([
            "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld",
            {
                "ex": "http://example.org/",
                "hello": "http://example.org/hello/"
            }
        ]);
        let resolver = ContextResolver::from_context_value(&ctx_ref, &known).unwrap();

        assert_eq!(resolver.expand_term("ex:MyModule"), "http://example.org/MyModule");
        assert_eq!(resolver.expand_term("hello:say"), "http://example.org/hello/say");
    }

    #[test]
    fn test_extract_graph_nodes() {
        let known = make_cjs_context();
        let doc = serde_json::json!({
            "@context": [
                "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld",
                { "ex": "http://example.org/", "hello": "http://example.org/hello/" }
            ],
            "@graph": [
                {
                    "@id": "ex:HelloWorldModule",
                    "@type": "Module",
                    "requireName": "helloworld",
                    "components": [
                        {
                            "@id": "ex:HelloWorldModule#SayHelloComponent",
                            "@type": "Class",
                            "requireElement": "Hello",
                            "parameters": [
                                { "@id": "hello:say" },
                                { "@id": "hello:hello" }
                            ]
                        }
                    ]
                }
            ]
        });

        let nodes = extract_graph_nodes(&doc, &known).unwrap();
        assert_eq!(nodes.len(), 1);
        let module = &nodes[0];
        assert_eq!(module.id.as_deref(), Some("http://example.org/HelloWorldModule"));
        assert_eq!(
            module.types,
            vec!["https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Module"]
        );
    }

    #[test]
    fn test_vocab_expansion() {
        let known = HashMap::new();
        let ctx = serde_json::json!({
            "@vocab": "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#",
            "ex": "http://example.org/"
        });
        let resolver = ContextResolver::from_context_value(&ctx, &known).unwrap();

        assert_eq!(
            resolver.expand_term("SomeUnknownTerm"),
            "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#SomeUnknownTerm"
        );
    }

    #[test]
    fn test_compact_iri_term() {
        let known = make_cjs_context();
        let ctx_ref = serde_json::json!([
            "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld"
        ]);
        let resolver = ContextResolver::from_context_value(&ctx_ref, &known).unwrap();

        // "Class" is a direct term mapping, so it's shorter than "oo:Class"
        assert_eq!(
            resolver.compact_iri(
                "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Class"
            ),
            "Class"
        );
        // Prefix-only IRI that has no term shortcut
        assert_eq!(
            resolver.compact_iri(
                "http://www.w3.org/2000/01/rdf-schema#label"
            ),
            "rdfs:label"
        );
    }

    #[test]
    fn test_compact_iri_prefix() {
        let known = make_cjs_context();
        let ctx_ref = serde_json::json!([
            "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld",
            { "ex": "http://example.org/" }
        ]);
        let resolver = ContextResolver::from_context_value(&ctx_ref, &known).unwrap();

        assert_eq!(
            resolver.compact_iri("http://example.org/Foo"),
            "ex:Foo"
        );
    }

    #[test]
    fn test_compact_iri_unknown() {
        let known = make_cjs_context();
        let ctx_ref = serde_json::json!([
            "https://linkedsoftwaredependencies.org/bundles/npm/componentsjs/^4.0.0/components/context.jsonld"
        ]);
        let resolver = ContextResolver::from_context_value(&ctx_ref, &known).unwrap();

        // Unknown IRI should be returned as-is
        assert_eq!(
            resolver.compact_iri("https://unknown.example.org/Something"),
            "https://unknown.example.org/Something"
        );
    }

    #[test]
    fn test_iri_compactor_roundtrip() {
        let known = make_cjs_context();
        let compactor = IriCompactor::from_contexts(&known).unwrap();

        // "Class" is defined as a direct term → returns shortest form
        let full = "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Class";
        let compact = compactor.compact(full);
        assert_eq!(compact, "Class");
        assert_eq!(compactor.expand(&compact), full);

        // "extends" is a term for rdfs:subClassOf → returns shortest form
        let full2 = "http://www.w3.org/2000/01/rdf-schema#subClassOf";
        let compact2 = compactor.compact(full2);
        assert_eq!(compact2, "extends");
        assert_eq!(compactor.expand(&compact2), full2);
    }

    #[test]
    fn test_iri_compactor_expand() {
        let known = make_cjs_context();
        let compactor = IriCompactor::from_contexts(&known).unwrap();

        assert_eq!(
            compactor.expand("oo:Module"),
            "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Module"
        );
    }
}