@ruverd/julius 0.24.4 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +41 -5
  3. package/dist/ask/ask.d.ts +7 -0
  4. package/dist/ask/ask.d.ts.map +1 -1
  5. package/dist/ask/ask.js +1 -1
  6. package/dist/ask/ask.js.map +1 -1
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +3 -0
  10. package/dist/cli.js.map +1 -1
  11. package/dist/economy/cli.d.ts.map +1 -1
  12. package/dist/economy/cli.js +4 -2
  13. package/dist/economy/cli.js.map +1 -1
  14. package/dist/economy/compact-output.d.ts +7 -0
  15. package/dist/economy/compact-output.d.ts.map +1 -0
  16. package/dist/economy/compact-output.js +47 -0
  17. package/dist/economy/compact-output.js.map +1 -0
  18. package/dist/economy/evidence-transport.d.ts +8 -0
  19. package/dist/economy/evidence-transport.d.ts.map +1 -0
  20. package/dist/economy/evidence-transport.js +28 -0
  21. package/dist/economy/evidence-transport.js.map +1 -0
  22. package/dist/economy/index.d.ts +17 -2
  23. package/dist/economy/index.d.ts.map +1 -1
  24. package/dist/economy/index.js +88 -11
  25. package/dist/economy/index.js.map +1 -1
  26. package/dist/graph/build.d.ts +3 -0
  27. package/dist/graph/build.d.ts.map +1 -1
  28. package/dist/graph/build.js +2 -0
  29. package/dist/graph/build.js.map +1 -1
  30. package/dist/graph/extract-cache.d.ts.map +1 -1
  31. package/dist/graph/extract-cache.js +5 -1
  32. package/dist/graph/extract-cache.js.map +1 -1
  33. package/dist/graph/extract.d.ts.map +1 -1
  34. package/dist/graph/extract.js +4 -0
  35. package/dist/graph/extract.js.map +1 -1
  36. package/dist/graph/rust-settings.d.ts +2 -0
  37. package/dist/graph/rust-settings.d.ts.map +1 -0
  38. package/dist/graph/rust-settings.js +6 -0
  39. package/dist/graph/rust-settings.js.map +1 -0
  40. package/dist/graph/rust.d.ts +24 -0
  41. package/dist/graph/rust.d.ts.map +1 -0
  42. package/dist/graph/rust.js +155 -0
  43. package/dist/graph/rust.js.map +1 -0
  44. package/dist/index.d.ts +2 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +1 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/mcp/compact.d.ts.map +1 -1
  49. package/dist/mcp/compact.js +39 -6
  50. package/dist/mcp/compact.js.map +1 -1
  51. package/dist/mcp/context-evidence.d.ts +25 -0
  52. package/dist/mcp/context-evidence.d.ts.map +1 -0
  53. package/dist/mcp/context-evidence.js +400 -0
  54. package/dist/mcp/context-evidence.js.map +1 -0
  55. package/dist/notes/notes.d.ts +2 -0
  56. package/dist/notes/notes.d.ts.map +1 -1
  57. package/dist/notes/notes.js +14 -2
  58. package/dist/notes/notes.js.map +1 -1
  59. package/dist/util/source.d.ts +2 -0
  60. package/dist/util/source.d.ts.map +1 -1
  61. package/dist/util/source.js +30 -2
  62. package/dist/util/source.js.map +1 -1
  63. package/dist/viewer/app.js +2 -2
  64. package/docs/hybrid-extractor.md +35 -0
  65. package/native/extractor/Cargo.lock +128 -0
  66. package/native/extractor/Cargo.toml +18 -0
  67. package/native/extractor/build.mjs +22 -0
  68. package/native/extractor/build.rs +40 -0
  69. package/native/extractor/src/lib.rs +707 -0
  70. package/package.json +10 -3
@@ -0,0 +1,707 @@
1
+ // Optional TypeScript structural extractor. Same MIT-derived semantics as
2
+ // src/graph/{extract,bindings}.ts; upstream provenance remains in PROVENANCE.md.
3
+ use serde_json::{json, Value};
4
+ use std::{
5
+ cell::RefCell,
6
+ collections::{HashMap, HashSet},
7
+ ffi::{c_char, c_void, CStr},
8
+ ptr,
9
+ };
10
+
11
+ #[repr(C)]
12
+ #[derive(Clone, Copy)]
13
+ struct Point {
14
+ row: u32,
15
+ column: u32,
16
+ }
17
+ #[repr(C)]
18
+ #[derive(Clone, Copy)]
19
+ struct Node {
20
+ context: [u32; 4],
21
+ id: *const c_void,
22
+ tree: *const c_void,
23
+ }
24
+ extern "C" {
25
+ fn ts_parser_new() -> *mut c_void;
26
+ fn ts_parser_delete(parser: *mut c_void);
27
+ fn ts_parser_set_language(parser: *mut c_void, language: *const c_void) -> bool;
28
+ fn ts_parser_parse_string(
29
+ parser: *mut c_void,
30
+ old: *const c_void,
31
+ text: *const c_char,
32
+ length: u32,
33
+ ) -> *mut c_void;
34
+ fn ts_tree_delete(tree: *mut c_void);
35
+ fn ts_tree_root_node(tree: *const c_void) -> Node;
36
+ fn ts_node_type(node: Node) -> *const c_char;
37
+ fn ts_node_start_byte(node: Node) -> u32;
38
+ fn ts_node_end_byte(node: Node) -> u32;
39
+ fn ts_node_start_point(node: Node) -> Point;
40
+ fn ts_node_end_point(node: Node) -> Point;
41
+ fn ts_node_parent(node: Node) -> Node;
42
+ fn ts_node_named_child_count(node: Node) -> u32;
43
+ fn ts_node_named_child(node: Node, index: u32) -> Node;
44
+ fn ts_node_next_named_sibling(node: Node) -> Node;
45
+ fn ts_node_child_count(node: Node) -> u32;
46
+ fn ts_node_child(node: Node, index: u32) -> Node;
47
+ fn ts_node_child_by_field_name(node: Node, name: *const c_char, length: u32) -> Node;
48
+ fn tree_sitter_typescript() -> *const c_void;
49
+ fn tree_sitter_tsx() -> *const c_void;
50
+ }
51
+ impl Node {
52
+ fn exists(self) -> bool {
53
+ !self.id.is_null()
54
+ }
55
+ fn kind(self) -> &'static str {
56
+ if !self.exists() {
57
+ ""
58
+ } else {
59
+ unsafe { CStr::from_ptr(ts_node_type(self)).to_str().unwrap() }
60
+ }
61
+ }
62
+ fn field(self, name: &str) -> Node {
63
+ unsafe { ts_node_child_by_field_name(self, name.as_ptr().cast(), name.len() as u32) }
64
+ }
65
+ fn parent(self) -> Node {
66
+ unsafe { ts_node_parent(self) }
67
+ }
68
+ fn children(self) -> impl Iterator<Item = Node> {
69
+ let first = unsafe { ts_node_named_child(self, 0) };
70
+ std::iter::successors(first.exists().then_some(first), |node| {
71
+ let next = unsafe { ts_node_next_named_sibling(*node) };
72
+ next.exists().then_some(next)
73
+ })
74
+ }
75
+ fn all_children(self) -> impl Iterator<Item = Node> {
76
+ (0..unsafe { ts_node_child_count(self) }).map(move |i| unsafe { ts_node_child(self, i) })
77
+ }
78
+ fn start(self) -> usize {
79
+ unsafe { ts_node_start_byte(self) as usize }
80
+ }
81
+ fn end(self) -> usize {
82
+ unsafe { ts_node_end_byte(self) as usize }
83
+ }
84
+ fn text(self, source: &str) -> &str {
85
+ if self.exists() {
86
+ &source[self.start()..self.end()]
87
+ } else {
88
+ ""
89
+ }
90
+ }
91
+ fn same(self, other: Node) -> bool {
92
+ self.exists() && other.exists() && self.id == other.id && self.tree == other.tree
93
+ }
94
+ }
95
+ struct Parser(*mut c_void);
96
+ impl Drop for Parser {
97
+ fn drop(&mut self) {
98
+ unsafe { ts_parser_delete(self.0) }
99
+ }
100
+ }
101
+ struct Tree(*mut c_void);
102
+ impl Drop for Tree {
103
+ fn drop(&mut self) {
104
+ unsafe { ts_tree_delete(self.0) }
105
+ }
106
+ }
107
+ thread_local! { static PARSER: RefCell<Parser> = RefCell::new(Parser(unsafe { ts_parser_new() })); }
108
+
109
+ fn function_value(kind: &str) -> bool {
110
+ matches!(
111
+ kind,
112
+ "arrow_function" | "function" | "function_expression" | "generator_function"
113
+ )
114
+ }
115
+ fn boundary(kind: &str) -> bool {
116
+ matches!(
117
+ kind,
118
+ "function_declaration"
119
+ | "generator_function_declaration"
120
+ | "method_definition"
121
+ | "arrow_function"
122
+ | "function_expression"
123
+ | "function"
124
+ )
125
+ }
126
+ fn mapped(kind: &str) -> Option<&'static str> {
127
+ match kind {
128
+ "class_declaration" | "abstract_class_declaration" => Some("class"),
129
+ "function_declaration" | "generator_function_declaration" => Some("function"),
130
+ "method_definition" => Some("method"),
131
+ "interface_declaration" => Some("interface"),
132
+ "type_alias_declaration" => Some("type"),
133
+ "enum_declaration" => Some("enum"),
134
+ _ => None,
135
+ }
136
+ }
137
+ fn descriptor(node: Node, source: &str) -> Option<(String, &'static str, usize)> {
138
+ if let Some(kind) = mapped(node.kind()) {
139
+ let name = node.field("name");
140
+ if name.exists() {
141
+ let body = node.field("body");
142
+ return Some((
143
+ name.text(source).into(),
144
+ kind,
145
+ if body.exists() {
146
+ body.start()
147
+ } else {
148
+ node.end()
149
+ },
150
+ ));
151
+ }
152
+ } else if node.kind() == "variable_declarator" && function_value(node.field("value").kind()) {
153
+ let name = node.field("name");
154
+ let body = node.field("value").field("body");
155
+ if name.exists() {
156
+ return Some((
157
+ name.text(source).into(),
158
+ "function",
159
+ if body.exists() {
160
+ body.start()
161
+ } else {
162
+ node.end()
163
+ },
164
+ ));
165
+ }
166
+ }
167
+ None
168
+ }
169
+ type Imports = HashMap<String, (String, String)>;
170
+ fn specifier(node: Node, source: &str) -> Option<String> {
171
+ let string = node.children().find(|n| n.kind() == "string")?;
172
+ Some(
173
+ string
174
+ .children()
175
+ .find(|n| n.kind() == "string_fragment")
176
+ .map(|n| n.text(source).to_string())
177
+ .unwrap_or_else(|| string.text(source).trim_matches(['\'', '"']).to_string()),
178
+ )
179
+ }
180
+ fn collect_import_bindings(node: Node, source: &str, spec: &str, imports: &mut Imports) {
181
+ if node.kind() == "import_specifier" {
182
+ let name = node.field("name");
183
+ let alias = node.field("alias");
184
+ if name.exists() {
185
+ imports.insert(
186
+ if alias.exists() { alias } else { name }
187
+ .text(source)
188
+ .into(),
189
+ (name.text(source).into(), spec.into()),
190
+ );
191
+ }
192
+ return;
193
+ }
194
+ for child in node.children() {
195
+ collect_import_bindings(child, source, spec, imports);
196
+ }
197
+ }
198
+ fn imports(node: Node, source: &str, out: &mut Imports, aliases: &mut HashMap<String, String>) {
199
+ if node.kind() == "import_specifier" {
200
+ let name = node.field("name");
201
+ let alias = node.field("alias");
202
+ if name.exists() && alias.exists() {
203
+ aliases.insert(alias.text(source).into(), name.text(source).into());
204
+ }
205
+ }
206
+ if node.kind() == "import_statement" {
207
+ if let Some(spec) = specifier(node, source) {
208
+ collect_import_bindings(node, source, &spec, out);
209
+ }
210
+ }
211
+ for child in node.children() {
212
+ imports(child, source, out, aliases);
213
+ }
214
+ }
215
+ fn shadowed(node: Node, definition: Node, source: &str, names: &mut HashSet<String>) {
216
+ if !node.same(definition) && !node.same(definition.field("value")) && boundary(node.kind()) {
217
+ let name = node.field("name");
218
+ if name.kind() == "identifier" {
219
+ names.insert(name.text(source).into());
220
+ }
221
+ return;
222
+ }
223
+ let name = match node.kind() {
224
+ "variable_declarator" => node.field("name"),
225
+ "required_parameter" | "optional_parameter" => node.field("pattern"),
226
+ _ => node,
227
+ };
228
+ if name.kind() == "identifier"
229
+ && (matches!(
230
+ node.kind(),
231
+ "variable_declarator" | "required_parameter" | "optional_parameter"
232
+ ) || node.parent().kind() == "formal_parameters")
233
+ {
234
+ names.insert(name.text(source).into());
235
+ }
236
+ for child in node.children() {
237
+ shadowed(child, definition, source, names);
238
+ }
239
+ }
240
+ fn annotation(node: Node, source: &str, aliases: &HashMap<String, String>) -> Option<String> {
241
+ if node.kind() != "type_annotation" {
242
+ return None;
243
+ }
244
+ let ty = node.children().next()?;
245
+ if ty.kind() != "type_identifier" {
246
+ return None;
247
+ }
248
+ Some(
249
+ aliases
250
+ .get(ty.text(source))
251
+ .cloned()
252
+ .unwrap_or_else(|| ty.text(source).into()),
253
+ )
254
+ }
255
+ fn new_type(node: Node, source: &str, aliases: &HashMap<String, String>) -> Option<String> {
256
+ if node.kind() != "new_expression" || node.field("constructor").kind() != "identifier" {
257
+ return None;
258
+ }
259
+ let name = node.field("constructor").text(source);
260
+ Some(aliases.get(name).cloned().unwrap_or_else(|| name.into()))
261
+ }
262
+ fn bindings(
263
+ node: Node,
264
+ source: &str,
265
+ scope: &[String],
266
+ class_scope: Option<&str>,
267
+ aliases: &HashMap<String, String>,
268
+ out: &mut HashMap<String, String>,
269
+ ) {
270
+ let path = scope.join(".");
271
+ match node.kind() {
272
+ "variable_declarator"
273
+ if !function_value(node.field("value").kind())
274
+ && node.field("name").kind() == "identifier" =>
275
+ {
276
+ if let Some(ty) = new_type(node.field("value"), source, aliases)
277
+ .or_else(|| annotation(node.field("type"), source, aliases))
278
+ {
279
+ out.insert(format!("{path}|{}", node.field("name").text(source)), ty);
280
+ }
281
+ }
282
+ "public_field_definition" if node.field("name").exists() => {
283
+ if let Some(ty) = annotation(node.field("type"), source, aliases)
284
+ .or_else(|| new_type(node.field("value"), source, aliases))
285
+ {
286
+ out.insert(
287
+ format!(
288
+ "{}|this.{}",
289
+ class_scope.unwrap_or(&path),
290
+ node.field("name").text(source)
291
+ ),
292
+ ty,
293
+ );
294
+ }
295
+ }
296
+ "required_parameter" if node.field("pattern").kind() == "identifier" => {
297
+ if let Some(ty) = annotation(node.field("type"), source, aliases) {
298
+ out.insert(
299
+ format!("{path}|{}", node.field("pattern").text(source)),
300
+ ty.clone(),
301
+ );
302
+ if node.all_children().any(|n| {
303
+ matches!(
304
+ n.kind(),
305
+ "accessibility_modifier" | "readonly" | "override_modifier"
306
+ )
307
+ }) {
308
+ out.insert(
309
+ format!(
310
+ "{}|this.{}",
311
+ class_scope.unwrap_or(&path),
312
+ node.field("pattern").text(source)
313
+ ),
314
+ ty,
315
+ );
316
+ }
317
+ }
318
+ }
319
+ _ => {}
320
+ }
321
+ let mut child_scope = scope.to_vec();
322
+ if let Some((name, _, _)) = descriptor(node, source) {
323
+ child_scope.push(name);
324
+ }
325
+ let class_path = child_scope.join(".");
326
+ let child_class = if matches!(
327
+ node.kind(),
328
+ "class_declaration" | "abstract_class_declaration"
329
+ ) {
330
+ Some(class_path.as_str())
331
+ } else {
332
+ class_scope
333
+ };
334
+ for child in node.children() {
335
+ bindings(child, source, &child_scope, child_class, aliases, out);
336
+ }
337
+ }
338
+ fn lookup(bindings: &HashMap<String, String>, scope: &[String], name: &str) -> Option<String> {
339
+ for i in (0..=scope.len()).rev() {
340
+ if let Some(ty) = bindings.get(&format!("{}|{name}", scope[..i].join("."))) {
341
+ return Some(ty.clone());
342
+ }
343
+ }
344
+ None
345
+ }
346
+ struct Extract<'a> {
347
+ source: &'a str,
348
+ nodes: Vec<Value>,
349
+ edges: Vec<Value>,
350
+ minted: HashSet<String>,
351
+ bindings: HashMap<String, String>,
352
+ }
353
+ impl Extract<'_> {
354
+ fn walk(
355
+ &mut self,
356
+ node: Node,
357
+ scope: &[String],
358
+ parent: i64,
359
+ class: Option<&str>,
360
+ imported: &Imports,
361
+ ) {
362
+ if let Some((name, kind, header)) = descriptor(node, self.source) {
363
+ let mut child_scope = scope.to_vec();
364
+ child_scope.push(name.clone());
365
+ let base = child_scope.join(".");
366
+ let mut id = base.clone();
367
+ let mut count = 2;
368
+ while !self.minted.insert(id.clone()) {
369
+ id = format!("{base}~{count}");
370
+ count += 1;
371
+ }
372
+ let ordinal = self.nodes.len() as i64;
373
+ let mut ancestor = node.parent();
374
+ let mut exported = false;
375
+ while ancestor.exists() {
376
+ if ancestor.kind() == "export_statement" {
377
+ exported = true;
378
+ break;
379
+ }
380
+ ancestor = ancestor.parent();
381
+ }
382
+ let start_row = unsafe { ts_node_start_point(node).row + 1 };
383
+ let end_row = unsafe { ts_node_end_point(node).row + 1 };
384
+ self.nodes.push(json!([
385
+ id,
386
+ name,
387
+ kind,
388
+ node.start(),
389
+ node.end(),
390
+ header,
391
+ start_row,
392
+ end_row,
393
+ exported,
394
+ if kind == "method" { class } else { None }
395
+ ]));
396
+ self.edges
397
+ .push(json!([parent, "contains", ordinal, null, null, null]));
398
+ if kind == "class" {
399
+ if let Some(heritage) = node.children().find(|n| n.kind() == "class_heritage") {
400
+ for clause in heritage.children() {
401
+ let relation = match clause.kind() {
402
+ "implements_clause" => "implements",
403
+ "extends_clause" => "extends",
404
+ _ => continue,
405
+ };
406
+ for ty in clause
407
+ .children()
408
+ .filter(|n| matches!(n.kind(), "identifier" | "type_identifier"))
409
+ {
410
+ self.edges.push(json!([
411
+ ordinal,
412
+ relation,
413
+ ty.text(self.source),
414
+ null,
415
+ null,
416
+ null
417
+ ]));
418
+ }
419
+ }
420
+ }
421
+ }
422
+ let mut filtered;
423
+ let child_imported = if matches!(kind, "function" | "method") && !imported.is_empty() {
424
+ let mut names = HashSet::new();
425
+ shadowed(node, node, self.source, &mut names);
426
+ filtered = imported.clone();
427
+ filtered.retain(|name, _| !names.contains(name));
428
+ &filtered
429
+ } else {
430
+ imported
431
+ };
432
+ for child in node.children() {
433
+ self.walk(
434
+ child,
435
+ &child_scope,
436
+ ordinal,
437
+ if kind == "class" { Some(&name) } else { class },
438
+ child_imported,
439
+ );
440
+ }
441
+ return;
442
+ }
443
+ if node.kind() == "import_statement" {
444
+ if let Some(spec) = specifier(node, self.source).filter(|s| !s.is_empty()) {
445
+ self.edges
446
+ .push(json!([-1, "imports", null, null, null, spec]));
447
+ }
448
+ return;
449
+ }
450
+ if node.kind() == "call_expression" {
451
+ let function = node.field("function");
452
+ let call = if function.kind() == "identifier" {
453
+ Some((function.text(self.source).to_string(), false, None))
454
+ } else if function.kind() == "member_expression" {
455
+ let property = function.field("property");
456
+ let property = if property.exists() {
457
+ Some(property)
458
+ } else {
459
+ function.children().last()
460
+ };
461
+ property.map(|p| {
462
+ let object = function.field("object");
463
+ let receiver = match object.kind() {
464
+ "this" => Some("this".into()),
465
+ "identifier" => Some(object.text(self.source).into()),
466
+ "member_expression"
467
+ if object.field("object").kind() == "this"
468
+ && object.field("property").exists() =>
469
+ {
470
+ Some(format!(
471
+ "this.{}",
472
+ object.field("property").text(self.source)
473
+ ))
474
+ }
475
+ _ => None,
476
+ };
477
+ (p.text(self.source).to_string(), true, receiver)
478
+ })
479
+ } else {
480
+ None
481
+ };
482
+ if let Some((name, member, receiver)) = call {
483
+ let recv_type = receiver.and_then(|r: String| {
484
+ if matches!(r.as_str(), "this" | "self" | "cls") {
485
+ class.map(String::from)
486
+ } else if r == "super" {
487
+ None
488
+ } else {
489
+ lookup(&self.bindings, scope, &r).or_else(|| {
490
+ r.strip_prefix("this.")
491
+ .and_then(|s| lookup(&self.bindings, scope, &format!("self.{s}")))
492
+ })
493
+ }
494
+ });
495
+ self.edges
496
+ .push(json!([parent, "calls", name, member, recv_type, null]));
497
+ }
498
+ } else if node.kind() == "identifier" {
499
+ let p = node.parent();
500
+ let direct_call = p.kind() == "call_expression"
501
+ && (p.field("function").same(node) || p.field("name").same(node));
502
+ if !direct_call && !p.field("name").same(node) {
503
+ if let Some((name, spec)) = imported.get(node.text(self.source)) {
504
+ self.edges
505
+ .push(json!([parent, "references", name, null, null, spec]));
506
+ }
507
+ }
508
+ }
509
+ for child in node.children() {
510
+ self.walk(child, scope, parent, class, imported);
511
+ }
512
+ }
513
+ }
514
+ fn extract(source: &str, language: &str) -> Result<String, String> {
515
+ if !matches!(language, "typescript" | "tsx") {
516
+ return Err("Rust extractor supports typescript and tsx only".into());
517
+ }
518
+ if source.len() > 4 * 1024 * 1024 {
519
+ return Err("JULIUS_RUST_INPUT_LIMIT: source exceeds 4 MiB".into());
520
+ }
521
+ PARSER.with(|cell| {
522
+ let parser = cell.borrow_mut();
523
+ if parser.0.is_null() {
524
+ return Err("Tree-sitter allocation failed".into());
525
+ }
526
+ let grammar = unsafe {
527
+ if language == "tsx" {
528
+ tree_sitter_tsx()
529
+ } else {
530
+ tree_sitter_typescript()
531
+ }
532
+ };
533
+ if !unsafe { ts_parser_set_language(parser.0, grammar) } {
534
+ return Err("Tree-sitter ABI mismatch".into());
535
+ }
536
+ let tree = Tree(unsafe {
537
+ ts_parser_parse_string(
538
+ parser.0,
539
+ ptr::null(),
540
+ source.as_ptr().cast(),
541
+ source.len() as u32,
542
+ )
543
+ });
544
+ if tree.0.is_null() {
545
+ return Err("Tree-sitter parse failed".into());
546
+ }
547
+ let root = unsafe { ts_tree_root_node(tree.0) };
548
+ let mut pending = vec![(root, 0usize)];
549
+ let mut visited = 0usize;
550
+ while let Some((node, depth)) = pending.pop() {
551
+ visited += 1;
552
+ let children = unsafe { ts_node_named_child_count(node) as usize };
553
+ if depth > 128 || visited + pending.len() + children > 500_000 {
554
+ return Err("JULIUS_RUST_INPUT_LIMIT: AST exceeds depth/node limit".into());
555
+ }
556
+ for child in node.children() {
557
+ pending.push((child, depth + 1));
558
+ }
559
+ }
560
+ let mut imported = HashMap::new();
561
+ let mut aliases = HashMap::new();
562
+ imports(root, source, &mut imported, &mut aliases);
563
+ let mut out = Extract {
564
+ source,
565
+ nodes: vec![],
566
+ edges: vec![],
567
+ minted: HashSet::new(),
568
+ bindings: HashMap::new(),
569
+ };
570
+ bindings(root, source, &[], None, &aliases, &mut out.bindings);
571
+ for child in root.children() {
572
+ out.walk(child, &[], -1, None, &imported);
573
+ }
574
+ Ok(json!([
575
+ unsafe { ts_node_end_point(root).row + 1 },
576
+ out.nodes,
577
+ out.edges
578
+ ])
579
+ .to_string())
580
+ })
581
+ }
582
+
583
+ // Minimal Node-API bridge; every borrowed JS value remains local to this call.
584
+ // catch_unwind prevents Rust panics from crossing the C ABI boundary.
585
+ type Handle = *mut c_void;
586
+ extern "C" {
587
+ fn napi_get_cb_info(
588
+ env: Handle,
589
+ info: Handle,
590
+ argc: *mut usize,
591
+ argv: *mut Handle,
592
+ this: *mut Handle,
593
+ data: *mut Handle,
594
+ ) -> i32;
595
+ fn napi_get_value_string_utf8(
596
+ env: Handle,
597
+ value: Handle,
598
+ buf: *mut c_char,
599
+ size: usize,
600
+ copied: *mut usize,
601
+ ) -> i32;
602
+ fn napi_create_string_utf8(
603
+ env: Handle,
604
+ value: *const c_char,
605
+ size: usize,
606
+ result: *mut Handle,
607
+ ) -> i32;
608
+ fn napi_create_uint32(env: Handle, value: u32, result: *mut Handle) -> i32;
609
+ fn napi_throw_error(env: Handle, code: *const c_char, message: *const c_char) -> i32;
610
+ fn napi_create_function(
611
+ env: Handle,
612
+ name: *const c_char,
613
+ len: usize,
614
+ callback: unsafe extern "C" fn(Handle, Handle) -> Handle,
615
+ data: Handle,
616
+ result: *mut Handle,
617
+ ) -> i32;
618
+ fn napi_set_named_property(
619
+ env: Handle,
620
+ object: Handle,
621
+ name: *const c_char,
622
+ value: Handle,
623
+ ) -> i32;
624
+ }
625
+ unsafe fn js_string(env: Handle, value: Handle) -> Result<String, String> {
626
+ let mut size = 0;
627
+ if napi_get_value_string_utf8(env, value, ptr::null_mut(), 0, &mut size) != 0 {
628
+ return Err("Expected string argument".into());
629
+ }
630
+ if size > 4 * 1024 * 1024 {
631
+ return Err("JULIUS_RUST_INPUT_LIMIT: source exceeds 4 MiB".into());
632
+ }
633
+ let mut buffer = vec![0u8; size + 1];
634
+ if napi_get_value_string_utf8(
635
+ env,
636
+ value,
637
+ buffer.as_mut_ptr().cast(),
638
+ buffer.len(),
639
+ &mut size,
640
+ ) != 0
641
+ {
642
+ return Err("Failed to read string".into());
643
+ }
644
+ buffer.truncate(size);
645
+ String::from_utf8(buffer).map_err(|e| e.to_string())
646
+ }
647
+ unsafe extern "C" fn callback(env: Handle, info: Handle) -> Handle {
648
+ let result = std::panic::catch_unwind(|| {
649
+ let mut count = 2;
650
+ let mut args = [ptr::null_mut(); 2];
651
+ if napi_get_cb_info(
652
+ env,
653
+ info,
654
+ &mut count,
655
+ args.as_mut_ptr(),
656
+ ptr::null_mut(),
657
+ ptr::null_mut(),
658
+ ) != 0
659
+ || count != 2
660
+ {
661
+ return Err("Expected source and language strings".into());
662
+ }
663
+ extract(&js_string(env, args[0])?, &js_string(env, args[1])?)
664
+ })
665
+ .unwrap_or_else(|_| Err("Rust extractor panicked".into()));
666
+ match result {
667
+ Ok(text) => {
668
+ let mut value = ptr::null_mut();
669
+ if napi_create_string_utf8(env, text.as_ptr().cast(), text.len(), &mut value) == 0 {
670
+ value
671
+ } else {
672
+ ptr::null_mut()
673
+ }
674
+ }
675
+ Err(message) => {
676
+ let message = std::ffi::CString::new(message.replace('\0', " ")).unwrap();
677
+ napi_throw_error(env, ptr::null(), message.as_ptr());
678
+ ptr::null_mut()
679
+ }
680
+ }
681
+ }
682
+ #[no_mangle]
683
+ pub unsafe extern "C" fn napi_register_module_v1(env: Handle, exports: Handle) -> Handle {
684
+ let mut function = ptr::null_mut();
685
+ if napi_create_function(
686
+ env,
687
+ b"extract\0".as_ptr().cast(),
688
+ 7,
689
+ callback,
690
+ ptr::null_mut(),
691
+ &mut function,
692
+ ) != 0
693
+ {
694
+ return ptr::null_mut();
695
+ }
696
+ if napi_set_named_property(env, exports, b"extract\0".as_ptr().cast(), function) != 0 {
697
+ return ptr::null_mut();
698
+ }
699
+ let mut version = ptr::null_mut();
700
+ if napi_create_uint32(env, 1, &mut version) != 0 {
701
+ return ptr::null_mut();
702
+ }
703
+ if napi_set_named_property(env, exports, b"protocolVersion\0".as_ptr().cast(), version) != 0 {
704
+ return ptr::null_mut();
705
+ }
706
+ exports
707
+ }