lockdocs-core 0.7.3

Lockfile resolution, local doc sources, symbol extraction and BM25 search for lockdocs.
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
//! Public npm declaration graph. Names are resolved through package entrypoints,
//! not by scoring unrelated declarations which happen to share a short name.
use crate::extract::{Entry, Kind};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path};
use tree_sitter::{Node, Parser};

#[derive(Default, Serialize, Deserialize)]
pub struct PublicApi {
    pub roots: Vec<Root>,
    pub entries: Vec<Entry>,
    modules: BTreeMap<String, Module>,
}

#[derive(Serialize, Deserialize)]
pub struct Root {
    pub import: String,
    pub conditions: String,
    pub file: String,
}

#[derive(Default, Serialize, Deserialize)]
struct Module {
    exports: BTreeMap<String, Binding>,
    imports: BTreeMap<String, Binding>,
    stars: Vec<String>,
    incomplete: bool,
    assignment: Option<String>,
}

#[derive(Clone, Serialize, Deserialize)]
enum Binding {
    Local(String),
    Named(String, String),
    Namespace(String),
}

#[derive(Default)]
pub struct Resolution {
    pub entries: BTreeSet<usize>,
    pub unresolved: bool,
}

fn text<'a>(n: Node, src: &'a [u8]) -> &'a str {
    n.utf8_text(src).unwrap_or("")
}
fn string(n: Node, src: &[u8]) -> String {
    text(n, src).trim_matches(['\'', '"']).to_string()
}
fn children(n: Node) -> Vec<Node> {
    n.named_children(&mut n.walk()).collect()
}
fn normalize(s: &str) -> Option<String> {
    let mut parts = Vec::new();
    for c in Path::new(s).components() {
        match c {
            Component::Normal(p) => parts.push(p.to_str()?),
            Component::ParentDir => {
                parts.pop()?;
            }
            Component::CurDir => {}
            _ => return None,
        }
    }
    Some(parts.join("/"))
}

/// Node's JS suffixes in declaration imports refer to declaration siblings.
fn resolve_file(from: &str, spec: &str, files: &BTreeSet<String>) -> String {
    if !spec.starts_with('.') {
        return format!("external:{spec}");
    }
    let parent = from.rsplit_once('/').map_or("", |(p, _)| p);
    let Some(base) = normalize(format!("{parent}/{spec}").trim_start_matches('/')) else {
        return String::new();
    };
    let suffixes = [(".mjs", ".d.mts"), (".cjs", ".d.cts"), (".js", ".d.ts")];
    for (js, ts) in suffixes {
        if let Some(stem) = base.strip_suffix(js) {
            for candidate in [format!("{stem}{ts}"), format!("{stem}.d.ts"), base.clone()] {
                if files.contains(&candidate) {
                    return candidate;
                }
            }
        }
    }
    for candidate in [
        base.clone(),
        format!("{base}.d.ts"),
        format!("{base}/index.d.ts"),
        format!("{base}.ts"),
        format!("{base}/index.ts"),
    ] {
        if files.contains(&candidate) {
            return candidate;
        }
    }
    base
}

fn names(n: Node, src: &[u8], out: &mut Vec<String>) {
    if let Some(name) = n.child_by_field_name("name") {
        out.push(text(name, src).to_string());
    } else if matches!(n.kind(), "ambient_declaration" | "lexical_declaration" | "variable_declaration") {
        for c in children(n) {
            names(c, src, out);
        }
    }
}

fn module(src: &str, file: &str, files: &BTreeSet<String>) -> Module {
    let mut m = Module::default();
    let mut parser = Parser::new();
    let _ = parser.set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into());
    let Some(tree) = parser.parse(src, None) else {
        m.incomplete = true;
        return m;
    };
    // Errors inside a type body do not change which declaration is exported.
    // A top-level recovery node may hide an export, so fail closed for that.
    m.incomplete = children(tree.root_node()).iter().any(|n| n.kind() == "ERROR");
    let bytes = src.as_bytes();
    if (file.ends_with(".js") || file.ends_with(".cjs") || file.ends_with(".mjs")) && (src.contains("module.exports") || src.contains("exports.")) {
        m.incomplete = true;
    }
    for n in children(tree.root_node()) {
        if n.kind() != "import_statement" && n.kind() != "export_statement" {
            continue;
        }
        // A UMD global name does not alter the module's explicit exports.
        if text(n, bytes).trim_start().starts_with("export as namespace ") {
            continue;
        }
        let target = n.child_by_field_name("source").map(|s| resolve_file(file, &string(s, bytes), files));
        if n.kind() == "import_statement" {
            if let Some(clause) = children(n).into_iter().find(|c| c.kind() == "import_clause") {
                for c in children(clause) {
                    match c.kind() {
                        "namespace_import" => {
                            if let (Some(t), Some(id)) = (&target, children(c).last()) {
                                m.imports.insert(text(*id, bytes).into(), Binding::Namespace(t.clone()));
                            }
                        }
                        "named_imports" => {
                            for s in children(c) {
                                if let (Some(t), Some(name)) = (&target, s.child_by_field_name("name")) {
                                    let alias = s.child_by_field_name("alias").unwrap_or(name);
                                    m.imports.insert(text(alias, bytes).into(), Binding::Named(t.clone(), string(name, bytes)));
                                }
                            }
                        }
                        "identifier" => {
                            if let Some(t) = &target {
                                m.imports.insert(text(c, bytes).into(), Binding::Named(t.clone(), "default".into()));
                            }
                        }
                        _ => m.incomplete = true,
                    }
                }
            } else {
                m.incomplete = true;
            }
            continue;
        }
        if let Some(d) = n.child_by_field_name("declaration") {
            let mut ns = Vec::new();
            names(d, bytes, &mut ns);
            let default = text(n, bytes).starts_with("export default ");
            for name in ns {
                m.exports.insert(if default { "default".into() } else { name.clone() }, Binding::Local(name));
            }
        } else if let Some(clause) = children(n).into_iter().find(|c| c.kind() == "export_clause") {
            for s in children(clause) {
                if let Some(name) = s.child_by_field_name("name") {
                    let alias = s.child_by_field_name("alias").unwrap_or(name);
                    let name = string(name, bytes);
                    let b = target
                        .as_ref()
                        .map_or_else(|| Binding::Local(name.clone()), |t| Binding::Named(t.clone(), name.clone()));
                    m.exports.insert(string(alias, bytes), b);
                }
            }
        } else if let Some(ns) = children(n).into_iter().find(|c| c.kind() == "namespace_export") {
            if let (Some(t), Some(id)) = (target, ns.named_child(0)) {
                m.exports.insert(string(id, bytes), Binding::Namespace(t));
            }
        } else if let Some(t) = target {
            m.stars.push(t);
        } else if let Some(value) = n
            .child_by_field_name("value")
            .or_else(|| text(n, bytes).trim_start().starts_with("export =").then(|| n.named_child(0)).flatten())
        {
            let name = text(value, bytes).to_string();
            if text(n, bytes).trim_start().starts_with("export =") {
                m.assignment = Some(name.clone());
            }
            m.exports.insert("default".into(), Binding::Local(name));
        } else {
            m.incomplete = true;
        }
    }
    m
}

/// Prefer the explicit declaration branch; do not silently combine a source
/// condition or an implementation file with a different declaration edition.
fn leaves(v: &Value, condition: &str, out: &mut Vec<(String, String)>) {
    match v {
        Value::String(s) => out.push((condition.into(), s.clone())),
        Value::Object(o) => {
            if let Some(t) = o.get("types") {
                leaves(t, &format!("{condition}/types"), out);
            } else {
                for (k, v) in o {
                    leaves(v, &format!("{condition}/{k}"), out);
                }
            }
        }
        Value::Array(a) => {
            for (i, v) in a.iter().enumerate() {
                leaves(v, &format!("{condition}/fallback-{i}"), out);
            }
        }
        _ => {}
    }
}

impl PublicApi {
    pub fn build(name: &str, dir: &Path, sources: &BTreeMap<String, String>) -> Self {
        let files: BTreeSet<String> = sources.keys().cloned().collect();
        let modules = sources.iter().map(|(f, s)| (f.clone(), module(s, f, &files))).collect();
        let pkg: Value = std::fs::read_to_string(dir.join("package.json"))
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or(Value::Null);
        let mut paths = BTreeMap::new();
        if let Some(exports) = pkg.get("exports") {
            if let Some(o) = exports.as_object().filter(|o| o.keys().any(|k| k.starts_with('.'))) {
                for (k, v) in o {
                    paths.insert(k.clone(), v.clone());
                }
            } else {
                paths.insert(".".into(), exports.clone());
            }
        } else {
            let target = pkg
                .get("types")
                .or_else(|| pkg.get("typings"))
                .or_else(|| pkg.get("main"))
                .and_then(Value::as_str)
                .unwrap_or("./index.d.ts");
            paths.insert(".".into(), Value::String(format!("./{}", target.trim_start_matches("./"))));
        }
        let routes: Vec<String> = paths.keys().cloned().collect();
        let mut roots = Vec::new();
        for (path, value) in paths {
            if path == "./package.json" {
                continue;
            }
            let mut targets = Vec::new();
            leaves(&value, "", &mut targets);
            for (conditions, target) in targets {
                if let (Some((pre, post)), Some((tp, ts))) = (path.split_once('*'), target.split_once('*')) {
                    for file in &files {
                        if let Some(mid) = file.strip_prefix(tp.trim_start_matches("./")).and_then(|s| s.strip_suffix(ts)) {
                            let public = format!("{pre}{mid}{post}");
                            let best = routes
                                .iter()
                                .filter(|r| {
                                    if let Some((a, b)) = r.split_once('*') {
                                        public.starts_with(a) && public.ends_with(b)
                                    } else {
                                        **r == public
                                    }
                                })
                                .max_by_key(|r| {
                                    if let Some((a, b)) = r.split_once('*') {
                                        (0, a.len(), b.len())
                                    } else {
                                        (1, r.len(), 0)
                                    }
                                });
                            if best != Some(&path) {
                                continue;
                            }
                            roots.push(Root {
                                import: format!("{name}{}{}{}", pre.trim_start_matches('.'), mid, post),
                                conditions: conditions.clone(),
                                file: file.clone(),
                            });
                        }
                    }
                } else {
                    let file = resolve_file("", &format!("./{}", target.trim_start_matches("./")), &files);
                    roots.push(Root {
                        import: format!("{name}{}", path.trim_start_matches('.')),
                        conditions,
                        file,
                    });
                }
            }
        }
        Self {
            roots,
            entries: crate::extract::npm_entries(sources),
            modules,
        }
    }

    /// Rebase an @types declaration graph onto the extraction's citation labels.
    pub(crate) fn prefixed(mut self, prefix: &str) -> Self {
        let rebase = |s: &mut String| {
            if !s.starts_with("external:") {
                *s = format!("{prefix}{s}");
            }
        };
        let binding = |b: &mut Binding| match b {
            Binding::Named(file, _) | Binding::Namespace(file) => rebase(file),
            _ => (),
        };
        for e in &mut self.entries {
            rebase(&mut e.file);
        }
        for root in &mut self.roots {
            rebase(&mut root.file);
        }
        self.modules = self
            .modules
            .into_iter()
            .map(|(file, mut m)| {
                for b in m.exports.values_mut().chain(m.imports.values_mut()) {
                    binding(b);
                }
                for star in &mut m.stars {
                    rebase(star);
                }
                (format!("{prefix}{file}"), m)
            })
            .collect();
        self
    }

    pub fn resolve(&self, root: &Root, symbol: &str, entries: &[Entry]) -> Resolution {
        let mut out = Resolution::default();
        self.exported(&root.file, symbol, entries, &mut BTreeSet::new(), &mut out);
        out
    }

    /// Search the declaration graph of this import, including referenced types
    /// and members, without admitting other editions shipped in the tarball.
    pub(crate) fn search_files(&self, import: &str) -> BTreeSet<String> {
        let mut files = BTreeSet::new();
        let mut pending: Vec<&str> = self.roots.iter().filter(|r| r.import == import).map(|r| r.file.as_str()).collect();
        while let Some(file) = pending.pop() {
            if !files.insert(file.to_string()) {
                continue;
            }
            if let Some(m) = self.modules.get(file) {
                pending.extend(m.stars.iter().map(String::as_str));
                for b in m.exports.values().chain(m.imports.values()) {
                    if let Binding::Named(target, _) | Binding::Namespace(target) = b {
                        pending.push(target);
                    }
                }
            }
        }
        files
    }

    pub(crate) fn search_alias<'a>(&'a self, entry: &'a Entry) -> &'a Entry {
        if entry.alias_of.is_none() {
            return entry;
        }
        let mut found = Resolution::default();
        self.exported(&entry.file, &entry.path, &self.entries, &mut BTreeSet::new(), &mut found);
        if !found.unresolved && found.entries.len() == 1 {
            &self.entries[*found.entries.first().unwrap()]
        } else {
            entry
        }
    }

    fn exported(&self, file: &str, path: &str, entries: &[Entry], seen: &mut BTreeSet<(String, String)>, out: &mut Resolution) {
        if seen.len() > 128 {
            out.unresolved = true;
            return;
        }
        let key = (file.to_string(), path.to_string());
        if !seen.insert(key.clone()) {
            return;
        }
        let Some(m) = self.modules.get(file) else {
            out.unresolved = true;
            seen.remove(&key);
            return;
        };
        out.unresolved |= m.incomplete;
        let (name, tail) = path.split_once('.').unwrap_or((path, ""));
        if let Some(b) = m.exports.get(name) {
            self.binding(file, b, tail, entries, seen, out);
        } else if let Some(namespace) = &m.assignment {
            let local = if path.starts_with(&format!("{namespace}.")) {
                path.to_string()
            } else {
                format!("{namespace}.{path}")
            };
            self.binding(file, &Binding::Local(local), "", entries, seen, out);
        } else if name != "default" {
            for star in &m.stars {
                self.exported(star, path, entries, seen, out);
            }
        }
        seen.remove(&key);
    }

    fn binding(&self, file: &str, b: &Binding, tail: &str, entries: &[Entry], seen: &mut BTreeSet<(String, String)>, out: &mut Resolution) {
        let extend = |s: &str| if tail.is_empty() { s.to_string() } else { format!("{s}.{tail}") };
        match b {
            Binding::Namespace(target) => {
                if tail.is_empty() {
                    out.unresolved = true;
                } else {
                    self.exported(target, tail, entries, seen, out);
                }
            }
            Binding::Named(target, name) => self.exported(target, &extend(name), entries, seen, out),
            Binding::Local(name) => {
                if let Some(import) = self.modules.get(file).and_then(|m| m.imports.get(name)) {
                    self.binding(file, import, tail, entries, seen, out);
                } else {
                    let path = extend(name);
                    let mut found = false;
                    for (i, e) in entries.iter().enumerate() {
                        if e.file == file && e.path == path && e.kind != Kind::Alias && e.kind != Kind::Prose {
                            out.entries.insert(i);
                            found = true;
                        }
                    }
                    if !found {
                        out.unresolved = true;
                    }
                }
            }
        }
    }
}