interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
//! Anonymous traversal factory for WASM bindings.
//!
//! Provides the `__` (double underscore) namespace for creating anonymous traversals
//! that can be used with steps like `where()`, `union()`, `repeat()`, etc.
//!
//! # Example
//!
//! ```javascript
//! import { Graph, P, __ } from 'interstellar-graph';
//!
//! // Find people who have friends older than themselves
//! graph.V()
//!     .hasLabel('person')
//!     .as('p')
//!     .out('knows')
//!     .where(__.values('age').is(P.gt(__.select('p').values('age'))))
//!     .values('name')
//!     .toList();
//! ```

use wasm_bindgen::prelude::*;

use crate::traversal;
use crate::wasm::predicate::Predicate;
use crate::wasm::traversal::Traversal;
use crate::wasm::types::{js_array_to_strings, js_to_u64, js_to_value};

/// Anonymous traversal factory.
///
/// Creates traversal fragments for use in branch/filter steps.
/// The `__` namespace mirrors the Gremlin `__` class.
#[wasm_bindgen(js_name = "__")]
pub struct AnonymousFactory;

#[wasm_bindgen(js_class = "__")]
impl AnonymousFactory {
    // =========================================================================
    // Identity / Start
    // =========================================================================

    /// Start an anonymous traversal (identity - passes through input unchanged).
    #[wasm_bindgen(js_name = "identity")]
    pub fn identity() -> Traversal {
        Traversal::anonymous_with_step(traversal::IdentityStep)
    }

    /// Start an anonymous traversal (alias for identity).
    #[wasm_bindgen(js_name = "start")]
    pub fn start() -> Traversal {
        Self::identity()
    }

    // =========================================================================
    // Filter Steps
    // =========================================================================

    /// Filter to elements with a specific label.
    #[wasm_bindgen(js_name = "hasLabel")]
    pub fn has_label(label: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::HasLabelStep::single(label))
    }

    /// Filter to elements with any of the specified labels.
    #[wasm_bindgen(js_name = "hasLabelAny")]
    pub fn has_label_any(labels: JsValue) -> Result<Traversal, JsError> {
        let label_vec = js_array_to_strings(labels)?;
        Ok(Traversal::anonymous_with_step(
            traversal::HasLabelStep::any(label_vec),
        ))
    }

    /// Filter to elements that have a property (any value).
    pub fn has(key: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::HasStep::new(key))
    }

    /// Filter to elements that have a property with a specific value.
    #[wasm_bindgen(js_name = "hasValue")]
    pub fn has_value(key: &str, value: JsValue) -> Result<Traversal, JsError> {
        let v = js_to_value(value)?;
        Ok(Traversal::anonymous_with_step(
            traversal::HasValueStep::new(key, v),
        ))
    }

    /// Filter to elements where property matches a predicate.
    #[wasm_bindgen(js_name = "hasWhere")]
    pub fn has_where(key: &str, predicate: Predicate) -> Traversal {
        Traversal::anonymous_with_step(traversal::HasWhereStep::new(key, predicate.into_inner()))
    }

    /// Filter to elements that do NOT have a property.
    #[wasm_bindgen(js_name = "hasNot")]
    pub fn has_not(key: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::HasNotStep::new(key))
    }

    /// Filter values matching a predicate.
    #[wasm_bindgen(js_name = "is")]
    pub fn is_(predicate: Predicate) -> Traversal {
        Traversal::anonymous_with_step(traversal::IsStep::new(predicate.into_inner()))
    }

    /// Filter values equal to a specific value.
    #[wasm_bindgen(js_name = "isEq")]
    pub fn is_eq(value: JsValue) -> Result<Traversal, JsError> {
        let v = js_to_value(value)?;
        Ok(Traversal::anonymous_with_step(traversal::IsStep::eq(v)))
    }

    /// Remove duplicate elements from the traversal.
    pub fn dedup() -> Traversal {
        Traversal::anonymous_with_step(traversal::DedupStep::new())
    }

    /// Remove duplicates based on a property key.
    #[wasm_bindgen(js_name = "dedupByKey")]
    pub fn dedup_by_key(key: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::DedupByKeyStep::new(key))
    }

    /// Remove duplicates based on element label.
    #[wasm_bindgen(js_name = "dedupByLabel")]
    pub fn dedup_by_label() -> Traversal {
        Traversal::anonymous_with_step(traversal::DedupByLabelStep::new())
    }

    /// Remove duplicates based on the result of a traversal.
    #[wasm_bindgen(js_name = "dedupBy")]
    pub fn dedup_by(sub: Traversal) -> Traversal {
        let core_traversal = sub.into_core_traversal();
        Traversal::anonymous_with_step(traversal::DedupByTraversalStep::new(core_traversal))
    }

    /// Limit results to the first n elements.
    pub fn limit(n: JsValue) -> Result<Traversal, JsError> {
        let num = js_to_u64(n)?;
        Ok(Traversal::anonymous_with_step(traversal::LimitStep::new(
            num as usize,
        )))
    }

    /// Skip the first n elements.
    pub fn skip(n: JsValue) -> Result<Traversal, JsError> {
        let num = js_to_u64(n)?;
        Ok(Traversal::anonymous_with_step(traversal::SkipStep::new(
            num as usize,
        )))
    }

    /// Take elements in a range [start, end).
    pub fn range(start: JsValue, end: JsValue) -> Result<Traversal, JsError> {
        let s = js_to_u64(start)? as usize;
        let e = js_to_u64(end)? as usize;
        Ok(Traversal::anonymous_with_step(traversal::RangeStep::new(
            s, e,
        )))
    }

    /// Get the last element.
    pub fn tail() -> Traversal {
        Traversal::anonymous_with_step(traversal::TailStep::new(1))
    }

    /// Filter to paths that don't repeat vertices.
    #[wasm_bindgen(js_name = "simplePath")]
    pub fn simple_path() -> Traversal {
        Traversal::anonymous_with_step(traversal::SimplePathStep::new())
    }

    /// Filter to paths that do repeat vertices.
    #[wasm_bindgen(js_name = "cyclicPath")]
    pub fn cyclic_path() -> Traversal {
        Traversal::anonymous_with_step(traversal::CyclicPathStep::new())
    }

    // =========================================================================
    // Navigation Steps
    // =========================================================================

    /// Navigate to outgoing adjacent vertices.
    pub fn out() -> Traversal {
        Traversal::anonymous_with_step(traversal::OutStep::new())
    }

    /// Navigate to outgoing adjacent vertices via specific edge labels.
    #[wasm_bindgen(js_name = "outLabels")]
    pub fn out_labels(labels: JsValue) -> Result<Traversal, JsError> {
        let label_vec = js_array_to_strings(labels)?;
        Ok(Traversal::anonymous_with_step(
            traversal::OutStep::with_labels(label_vec),
        ))
    }

    /// Navigate to incoming adjacent vertices.
    #[wasm_bindgen(js_name = "in_")]
    pub fn in_() -> Traversal {
        Traversal::anonymous_with_step(traversal::InStep::new())
    }

    /// Navigate to incoming adjacent vertices via specific edge labels.
    #[wasm_bindgen(js_name = "inLabels")]
    pub fn in_labels(labels: JsValue) -> Result<Traversal, JsError> {
        let label_vec = js_array_to_strings(labels)?;
        Ok(Traversal::anonymous_with_step(
            traversal::InStep::with_labels(label_vec),
        ))
    }

    /// Navigate to adjacent vertices in both directions.
    pub fn both() -> Traversal {
        Traversal::anonymous_with_step(traversal::BothStep::new())
    }

    /// Navigate to adjacent vertices in both directions via specific labels.
    #[wasm_bindgen(js_name = "bothLabels")]
    pub fn both_labels(labels: JsValue) -> Result<Traversal, JsError> {
        let label_vec = js_array_to_strings(labels)?;
        Ok(Traversal::anonymous_with_step(
            traversal::BothStep::with_labels(label_vec),
        ))
    }

    /// Navigate to outgoing edges.
    #[wasm_bindgen(js_name = "outE")]
    pub fn out_e() -> Traversal {
        Traversal::anonymous_with_step(traversal::OutEStep::new())
    }

    /// Navigate to incoming edges.
    #[wasm_bindgen(js_name = "inE")]
    pub fn in_e() -> Traversal {
        Traversal::anonymous_with_step(traversal::InEStep::new())
    }

    /// Navigate to edges in both directions.
    #[wasm_bindgen(js_name = "bothE")]
    pub fn both_e() -> Traversal {
        Traversal::anonymous_with_step(traversal::BothEStep::new())
    }

    /// Navigate from an edge to its outgoing (source) vertex.
    #[wasm_bindgen(js_name = "outV")]
    pub fn out_v() -> Traversal {
        Traversal::anonymous_with_step(traversal::OutVStep::new())
    }

    /// Navigate from an edge to its incoming (target) vertex.
    #[wasm_bindgen(js_name = "inV")]
    pub fn in_v() -> Traversal {
        Traversal::anonymous_with_step(traversal::InVStep::new())
    }

    /// Navigate from an edge to both endpoints.
    #[wasm_bindgen(js_name = "bothV")]
    pub fn both_v() -> Traversal {
        Traversal::anonymous_with_step(traversal::BothVStep::new())
    }

    /// Navigate from an edge to the vertex that was NOT the previous step.
    #[wasm_bindgen(js_name = "otherV")]
    pub fn other_v() -> Traversal {
        Traversal::anonymous_with_step(traversal::OtherVStep::new())
    }

    // =========================================================================
    // Transform Steps
    // =========================================================================

    /// Extract a single property value.
    pub fn values(key: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::ValuesStep::new(key))
    }

    /// Get a map of property name to value.
    #[wasm_bindgen(js_name = "valueMap")]
    pub fn value_map() -> Traversal {
        Traversal::anonymous_with_step(traversal::ValueMapStep::new())
    }

    /// Get a complete element map (id, label, and all properties).
    #[wasm_bindgen(js_name = "elementMap")]
    pub fn element_map() -> Traversal {
        Traversal::anonymous_with_step(traversal::ElementMapStep::new())
    }

    /// Extract the element ID.
    pub fn id() -> Traversal {
        Traversal::anonymous_with_step(traversal::IdStep)
    }

    /// Extract the element label.
    pub fn label() -> Traversal {
        Traversal::anonymous_with_step(traversal::LabelStep)
    }

    /// Replace each element with a constant value.
    pub fn constant(value: JsValue) -> Result<Traversal, JsError> {
        let v = js_to_value(value)?;
        Ok(Traversal::anonymous_with_step(
            traversal::ConstantStep::new(v),
        ))
    }

    /// Flatten lists/iterables in the stream.
    pub fn unfold() -> Traversal {
        Traversal::anonymous_with_step(traversal::UnfoldStep::new())
    }

    /// Get the traversal path (history of elements visited).
    pub fn path() -> Traversal {
        Traversal::anonymous_with_step(traversal::PathStep::new())
    }

    /// Select a single labeled step from the path.
    #[wasm_bindgen(js_name = "selectOne")]
    pub fn select_one(label: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::SelectStep::single(label))
    }

    /// Select labeled steps from the path.
    pub fn select(labels: JsValue) -> Result<Traversal, JsError> {
        let label_vec = js_array_to_strings(labels)?;
        Ok(Traversal::anonymous_with_step(traversal::SelectStep::new(
            label_vec,
        )))
    }

    /// Calculate the arithmetic mean of numeric values.
    pub fn mean() -> Traversal {
        Traversal::anonymous_with_step(traversal::MeanStep::new())
    }

    /// Count the number of elements.
    pub fn count() -> Traversal {
        Traversal::anonymous_with_step(traversal::aggregate::CountStep::new())
    }

    /// Get the minimum value.
    pub fn min() -> Traversal {
        Traversal::anonymous_with_step(traversal::MinStep::new())
    }

    /// Get the maximum value.
    pub fn max() -> Traversal {
        Traversal::anonymous_with_step(traversal::MaxStep::new())
    }

    // =========================================================================
    // Path/Label Steps
    // =========================================================================

    /// Label the current step for later reference.
    #[wasm_bindgen(js_name = "as")]
    pub fn as_(label: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::AsStep::new(label))
    }

    // =========================================================================
    // Aggregate Steps
    // =========================================================================

    /// Collect all elements into a single list.
    pub fn fold() -> Traversal {
        Traversal::anonymous_with_step(super::traversal::FoldStep::new())
    }

    /// Calculate the sum of numeric values.
    pub fn sum() -> Traversal {
        Traversal::anonymous_with_step(super::traversal::SumStep::new())
    }

    // =========================================================================
    // Mutation Steps
    // =========================================================================

    /// Add a vertex with a label.
    #[wasm_bindgen(js_name = "addV")]
    pub fn add_v(label: &str) -> Traversal {
        Traversal::anonymous_with_step(traversal::AddVStep::new(label))
    }

    /// Add an edge with a label.
    #[wasm_bindgen(js_name = "addE")]
    pub fn add_e(label: &str) -> Traversal {
        Traversal::anonymous_with_step(super::traversal::AddESpawnStep::new(label))
    }

    /// Set a property on the current element.
    pub fn property(key: &str, value: JsValue) -> Result<Traversal, JsError> {
        let v = js_to_value(value)?;
        Ok(Traversal::anonymous_with_step(
            traversal::PropertyStep::new(key, v),
        ))
    }

    /// Remove the current element from the graph.
    pub fn drop() -> Traversal {
        Traversal::anonymous_with_step(traversal::DropStep::new())
    }

    // =========================================================================
    // Branch Steps
    // =========================================================================

    /// Filter based on the result of a traversal.
    #[wasm_bindgen(js_name = "where_")]
    pub fn where_(sub: Traversal) -> Traversal {
        let t = Traversal::anonymous_with_step(traversal::IdentityStep);
        let core_traversal = sub.into_core_traversal();
        t.add_step_internal(traversal::WhereStep::new(core_traversal))
    }

    /// Filter to elements where the traversal produces NO results.
    pub fn not(sub: Traversal) -> Traversal {
        let t = Traversal::anonymous_with_step(traversal::IdentityStep);
        let core_traversal = sub.into_core_traversal();
        t.add_step_internal(traversal::NotStep::new(core_traversal))
    }

    /// Execute multiple traversals and combine results.
    pub fn union(traversals: Vec<Traversal>) -> Traversal {
        let t = Traversal::anonymous_with_step(traversal::IdentityStep);
        let core_traversals: Vec<_> = traversals
            .into_iter()
            .map(|tr| tr.into_core_traversal())
            .collect();
        t.add_step_internal(traversal::UnionStep::new(core_traversals))
    }

    /// Return the result of the first traversal that produces output.
    pub fn coalesce(traversals: Vec<Traversal>) -> Traversal {
        let t = Traversal::anonymous_with_step(traversal::IdentityStep);
        let core_traversals: Vec<_> = traversals
            .into_iter()
            .map(|tr| tr.into_core_traversal())
            .collect();
        t.add_step_internal(traversal::CoalesceStep::new(core_traversals))
    }

    /// Conditional branching.
    pub fn choose(condition: Traversal, if_true: Traversal, if_false: Traversal) -> Traversal {
        let t = Traversal::anonymous_with_step(traversal::IdentityStep);
        let cond = condition.into_core_traversal();
        let t_branch = if_true.into_core_traversal();
        let f_branch = if_false.into_core_traversal();
        t.add_step_internal(traversal::ChooseStep::new(cond, t_branch, f_branch))
    }

    /// Execute traversal, but pass through original if no results.
    pub fn optional(sub: Traversal) -> Traversal {
        let t = Traversal::anonymous_with_step(traversal::IdentityStep);
        let core_traversal = sub.into_core_traversal();
        t.add_step_internal(traversal::OptionalStep::new(core_traversal))
    }

    /// Execute traversal in local scope (per element).
    pub fn local(sub: Traversal) -> Traversal {
        let t = Traversal::anonymous_with_step(traversal::IdentityStep);
        let core_traversal = sub.into_core_traversal();
        t.add_step_internal(traversal::LocalStep::new(core_traversal))
    }

    // =========================================================================
    // Algorithm Steps
    // =========================================================================

    /// Find the shortest unweighted path to target.
    #[wasm_bindgen(js_name = "shortestPath")]
    pub fn shortest_path(target_id: JsValue) -> Result<Traversal, JsError> {
        let target = crate::wasm::types::js_to_vertex_id(target_id)?;
        Ok(Traversal::anonymous_with_step(
            traversal::ShortestPathStep::new(target),
        ))
    }

    /// Find the shortest weighted path (Dijkstra) to target.
    #[wasm_bindgen(js_name = "shortestPathWeighted")]
    pub fn shortest_path_weighted(
        target_id: JsValue,
        weight_property: &str,
    ) -> Result<Traversal, JsError> {
        let target = crate::wasm::types::js_to_vertex_id(target_id)?;
        Ok(Traversal::anonymous_with_step(
            traversal::DijkstraStep::new(target, weight_property.to_string()),
        ))
    }

    /// Perform a breadth-first traversal.
    pub fn bfs(max_depth: Option<u32>) -> Traversal {
        Traversal::anonymous_with_step(
            traversal::algorithm_steps::BfsTraversalStep::new(max_depth, None),
        )
    }

    /// Perform a depth-first traversal.
    pub fn dfs(max_depth: Option<u32>) -> Traversal {
        Traversal::anonymous_with_step(
            traversal::algorithm_steps::DfsTraversalStep::new(max_depth, None),
        )
    }
}