-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathFlutterSkill.js
More file actions
1346 lines (1175 loc) · 44.4 KB
/
Copy pathFlutterSkill.js
File metadata and controls
1346 lines (1175 loc) · 44.4 KB
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* flutter-skill React Native SDK
*
* Embedded bridge server that lets flutter-skill automate React Native apps.
* Starts an HTTP + WebSocket server on port 18118 inside the app process,
* exposing JSON-RPC 2.0 methods for UI inspection, interaction, and debugging.
*
* Usage:
* import { initFlutterSkill, registerComponent } from './FlutterSkill';
* if (__DEV__) {
* initFlutterSkill({ appName: 'MyApp' });
* }
*/
import { Platform, UIManager, findNodeHandle } from 'react-native';
import TcpSocket from 'react-native-tcp-socket';
// Buffer polyfill for Hermes
let Buffer;
try {
Buffer = global.Buffer || require('buffer').Buffer;
} catch (e) {
// Fallback: minimal Buffer shim for the WebSocket code
Buffer = {
from: (str, enc) => {
const arr = [];
for (let i = 0; i < str.length; i++) arr.push(str.charCodeAt(i));
const u = new Uint8Array(arr);
u.toString = (e2) => str;
return u;
},
alloc: (n) => {
const u = new Uint8Array(n);
u.slice = (a, b) => new Uint8Array(Array.prototype.slice.call(u, a, b));
return u;
},
concat: (bufs) => {
let total = 0;
bufs.forEach(b => total += b.length);
const r = new Uint8Array(total);
let off = 0;
bufs.forEach(b => { r.set(b, off); off += b.length; });
return r;
},
byteLength: (str) => {
let len = 0;
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 0x80) len += 1;
else if (c < 0x800) len += 2;
else len += 3;
}
return len;
},
isBuffer: () => false,
};
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const SDK_VERSION = '1.0.0';
const BRIDGE_PORT = 18118;
const HEALTH_PATH = '/.flutter-skill';
const FRAMEWORK = 'react-native';
const MAX_LOG_ENTRIES = 500;
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
let _server = null;
let _wsClients = [];
let _config = { appName: 'ReactNativeApp' };
let _logs = [];
let _rootRef = null;
let _componentRegistry = new Map(); // testID -> { ref, onPress, onChangeText, type, text, getText, ... }
let _navigationRef = null;
let _defaultScrollRef = null; // default scrollable for scroll/swipe
let _registeredTools = []; // WebMCP tool registry
// ---------------------------------------------------------------------------
// Console capture
// ---------------------------------------------------------------------------
const _origLog = console.log;
const _origWarn = console.warn;
const _origError = console.error;
function _pushLog(level, args) {
const message = '[' + level + '] ' + Array.prototype.slice.call(args).join(' ');
_logs.push({ timestamp: Date.now(), level: level, message: message });
if (_logs.length > MAX_LOG_ENTRIES) _logs.shift();
}
function _installConsoleCapture() {
console.log = function () { _pushLog('LOG', arguments); _origLog.apply(console, arguments); };
console.warn = function () { _pushLog('WARN', arguments); _origWarn.apply(console, arguments); };
console.error = function () { _pushLog('ERROR', arguments); _origError.apply(console, arguments); };
}
// ---------------------------------------------------------------------------
// Component registry
// ---------------------------------------------------------------------------
/**
* Register a component so the SDK can find and interact with it.
*
* @param {string} testID - Unique key for lookup (e.g. 'increment-btn')
* @param {object|null} ref - Native component ref (for measuring bounds). Can be null.
* @param {object} [extras] - Additional metadata:
* - type: string (e.g. 'button', 'text_field', 'text', 'switch')
* - text: string (display text)
* - getText: () => string (dynamic text getter)
* - onPress: () => void (tap handler)
* - onChangeText: (text: string) => void (text input handler)
* - onValueChange: (val: any) => void (switch/checkbox handler)
* - accessibilityLabel: string
* - interactive: boolean (default true)
* - accessibilityRole: string
* - value: any
* - getValue: () => any
* - enabled: boolean
*/
function registerComponent(testID, ref, extras) {
if (!testID) return;
if (!ref && !extras) {
_componentRegistry.delete(testID);
return;
}
_componentRegistry.set(testID, { ref: ref, ...(extras || {}) });
}
function unregisterComponent(testID) {
_componentRegistry.delete(testID);
}
function setNavigationRef(ref) {
_navigationRef = ref;
}
function setRootRef(ref) {
_rootRef = ref;
}
function setDefaultScrollRef(ref) {
_defaultScrollRef = ref;
}
// ---------------------------------------------------------------------------
// Element finding
// ---------------------------------------------------------------------------
function _findElement(params) {
// By key or testID
if (params.key || params.testID) {
const id = params.key || params.testID;
const entry = _componentRegistry.get(id);
if (entry) return { testID: id, ...entry };
// Also search by accessibilityLabel match
for (const [tid, e] of _componentRegistry) {
if (e.accessibilityLabel === id) return { testID: tid, ...e };
}
return null;
}
// By text or accessibilityLabel
if (params.text || params.accessibilityLabel) {
const searchText = params.text || params.accessibilityLabel;
for (const [testID, entry] of _componentRegistry) {
const entryText = (typeof entry.getText === 'function') ? entry.getText() : entry.text;
if (
(entryText && entryText.indexOf(searchText) !== -1) ||
(entry.accessibilityLabel && entry.accessibilityLabel.indexOf(searchText) !== -1) ||
(testID && testID.indexOf(searchText) !== -1)
) {
return { testID: testID, ...entry };
}
}
return null;
}
// By ref
if (params.ref) {
// Search interactive elements for matching ref
// This is handled separately in tap/enter_text
return null;
}
return null;
}
function _measureElement(ref) {
if (!ref) return Promise.resolve(null);
const nodeHandle = findNodeHandle(ref);
if (!nodeHandle) return Promise.resolve(null);
return new Promise((resolve) => {
try {
UIManager.measure(nodeHandle, (x, y, width, height, pageX, pageY) => {
if (width != null) {
resolve({
x: Math.round(pageX || 0),
y: Math.round(pageY || 0),
width: Math.round(width),
height: Math.round(height),
});
} else {
resolve(null);
}
});
} catch (e) {
resolve(null);
}
});
}
// ---------------------------------------------------------------------------
// Accessibility tree / interactive elements
// ---------------------------------------------------------------------------
function _getAccessibilityTree() {
const elements = [];
const promises = [];
_componentRegistry.forEach((entry, testID) => {
const entryText = (typeof entry.getText === 'function') ? entry.getText() : entry.text;
if (entry.ref) {
const nodeHandle = findNodeHandle(entry.ref);
if (nodeHandle) {
promises.push(
new Promise((resolve) => {
try {
UIManager.measure(nodeHandle, (x, y, width, height, pageX, pageY) => {
elements.push({
testID: testID,
type: entry.type || 'View',
text: entryText || null,
accessibilityLabel: entry.accessibilityLabel || null,
bounds: {
x: Math.round(pageX || 0),
y: Math.round(pageY || 0),
width: Math.round(width || 0),
height: Math.round(height || 0),
},
interactive: entry.interactive !== false,
visible: (width || 0) > 0 && (height || 0) > 0,
});
resolve();
});
} catch (e) {
elements.push({
testID: testID,
type: entry.type || 'View',
text: entryText || null,
accessibilityLabel: entry.accessibilityLabel || null,
bounds: { x: 0, y: 0, width: 0, height: 0 },
interactive: entry.interactive !== false,
visible: false,
});
resolve();
}
})
);
} else {
elements.push({
testID: testID,
type: entry.type || 'View',
text: entryText || null,
accessibilityLabel: entry.accessibilityLabel || null,
bounds: { x: 0, y: 0, width: 0, height: 0 },
interactive: entry.interactive !== false,
visible: false,
});
}
} else {
// No ref, still report element
elements.push({
testID: testID,
type: entry.type || 'View',
text: entryText || null,
accessibilityLabel: entry.accessibilityLabel || null,
bounds: { x: 0, y: 0, width: 0, height: 0 },
interactive: entry.interactive !== false,
visible: false,
});
}
});
return Promise.all(promises).then(() => elements);
}
function _getInteractiveElementsStructured() {
return new Promise((resolve) => {
const elements = [];
const promises = [];
const refCounts = {};
function generateSemanticRefId(entry, testID, elementType) {
const roleMap = {
button: 'button', text_field: 'input', checkbox: 'toggle',
switch: 'toggle', radio: 'toggle', slider: 'slider',
dropdown: 'select', link: 'link', list_item: 'item', tab: 'item',
text: 'text',
};
const role = roleMap[elementType] || 'element';
const entryText = (typeof entry.getText === 'function') ? entry.getText() : entry.text;
let content = testID || entry.accessibilityLabel || entryText || null;
if (content) {
content = content.replace(/\s+/g, '_').replace(/[^\w]/g, '').substring(0, 30);
const baseRef = role + ':' + content;
const count = refCounts[baseRef] || 0;
refCounts[baseRef] = count + 1;
return count === 0 ? baseRef : baseRef + '[' + count + ']';
} else {
const count = refCounts[role] || 0;
refCounts[role] = count + 1;
return role + '[' + count + ']';
}
}
function getElementType(entry) {
if (entry.type) {
const t = entry.type.toLowerCase();
if (t === 'button' || t.includes('button') || t.includes('touchable')) return 'button';
if (t === 'text_field' || t === 'textinput' || t.includes('input')) return 'text_field';
if (t === 'switch' || t === 'checkbox') return 'switch';
if (t === 'text') return 'text';
if (t === 'slider') return 'slider';
}
if (entry.onPress) return 'button';
if (entry.onChangeText) return 'text_field';
if (entry.onValueChange) return 'switch';
return 'button';
}
function getActions(entry, elementType) {
if (elementType === 'text_field') return ['tap', 'enter_text'];
if (elementType === 'switch') return ['tap'];
if (elementType === 'slider') return ['tap', 'swipe'];
const actions = ['tap'];
return actions;
}
_componentRegistry.forEach((entry, testID) => {
// Include interactive elements
const isInteractive = entry.interactive !== false && (
entry.onPress || entry.onChangeText || entry.onValueChange ||
entry.type === 'button' || entry.type === 'text_field' ||
entry.type === 'switch' || entry.type === 'text'
);
if (!isInteractive) return;
const elementType = getElementType(entry);
const entryText = (typeof entry.getText === 'function') ? entry.getText() : entry.text;
const refId = generateSemanticRefId(entry, testID, elementType);
const el = {
ref: refId,
type: entry.type || 'View',
text: entryText || entry.accessibilityLabel || null,
actions: getActions(entry, elementType),
enabled: entry.enabled !== false,
bounds: { x: 0, y: 0, w: 0, h: 0 },
_testID: testID,
};
if (entry.accessibilityLabel && entry.accessibilityLabel !== entryText) {
el.label = entry.accessibilityLabel;
}
if (entry.ref) {
const nodeHandle = findNodeHandle(entry.ref);
if (nodeHandle) {
promises.push(
new Promise((resolveEl) => {
try {
UIManager.measure(nodeHandle, (x, y, width, height, pageX, pageY) => {
if (width != null && height != null) {
el.bounds = {
x: Math.round(pageX || 0),
y: Math.round(pageY || 0),
w: Math.round(width),
h: Math.round(height),
};
}
elements.push(el);
resolveEl();
});
} catch (e) {
elements.push(el);
resolveEl();
}
})
);
return;
}
}
elements.push(el);
});
Promise.all(promises).then(() => {
const summary = elements.length === 0
? 'No interactive elements found'
: elements.length + ' interactive elements';
resolve({ elements, summary });
});
});
}
// ---------------------------------------------------------------------------
// Interaction helpers
// ---------------------------------------------------------------------------
function _tapEntry(entry) {
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
// Use stored onPress callback
if (typeof entry.onPress === 'function') {
try {
entry.onPress();
return Promise.resolve({ success: true, message: 'Tapped via onPress' });
} catch (e) {
return Promise.resolve({ success: false, message: 'onPress threw: ' + e.message });
}
}
// For switches/checkboxes with onValueChange
if (typeof entry.onValueChange === 'function') {
try {
const currentVal = (typeof entry.getValue === 'function') ? entry.getValue() : entry.value;
entry.onValueChange(!currentVal);
return Promise.resolve({ success: true, message: 'Toggled via onValueChange' });
} catch (e) {
return Promise.resolve({ success: false, message: 'onValueChange threw: ' + e.message });
}
}
// Fallback: try native accessibility
if (entry.ref) {
const nodeHandle = findNodeHandle(entry.ref);
if (nodeHandle) {
try {
if (Platform.OS === 'android') {
UIManager.sendAccessibilityEvent(nodeHandle, 1);
}
return Promise.resolve({ success: true, message: 'Tapped via accessibility' });
} catch (e) {
// ignore
}
}
}
return Promise.resolve({ success: false, message: 'No tap handler available' });
}
function _enterTextEntry(entry, text) {
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
if (typeof entry.onChangeText === 'function') {
try {
entry.onChangeText(text);
return Promise.resolve({ success: true, message: 'Text entered via onChangeText' });
} catch (e) {
return Promise.resolve({ success: false, message: 'onChangeText threw: ' + e.message });
}
}
if (entry.ref && typeof entry.ref.setNativeProps === 'function') {
entry.ref.setNativeProps({ text: text });
return Promise.resolve({ success: true, message: 'Text entered via setNativeProps' });
}
return Promise.resolve({ success: false, message: 'No text input handler available' });
}
// ---------------------------------------------------------------------------
// JSON-RPC method implementations
// ---------------------------------------------------------------------------
const methods = {};
methods.initialize = function (_params) {
return Promise.resolve({
success: true,
framework: FRAMEWORK,
sdk_version: SDK_VERSION,
platform: Platform.OS,
app_name: _config.appName,
});
};
methods.inspect = function (_params) {
return _getAccessibilityTree().then((elements) => ({ elements }));
};
methods.inspect_interactive = function (_params) {
return _getInteractiveElementsStructured();
};
methods.tap = function (params) {
// By ref (from inspect_interactive)
if (params.ref) {
return _getInteractiveElementsStructured().then((structured) => {
const target = structured.elements.find(el => el.ref === params.ref);
if (!target) return { success: false, message: 'Element with ref "' + params.ref + '" not found' };
const entry = _componentRegistry.get(target._testID);
if (!entry) return { success: false, message: 'Component lost for ref "' + params.ref + '"' };
return _tapEntry(entry);
});
}
// By key/testID/text
const entry = _findElement(params);
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
return _tapEntry(entry);
};
methods.enter_text = function (params) {
const text = params.text || '';
// By ref
if (params.ref) {
return _getInteractiveElementsStructured().then((structured) => {
const target = structured.elements.find(el => el.ref === params.ref);
if (!target) return { success: false, message: 'Element with ref "' + params.ref + '" not found' };
const entry = _componentRegistry.get(target._testID);
if (!entry) return { success: false, message: 'Component lost for ref "' + params.ref + '"' };
return _enterTextEntry(entry, text);
});
}
// By key/testID
const entry = _findElement(params);
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
return _enterTextEntry(entry, text);
};
methods.find_element = function (params) {
const entry = _findElement(params);
if (!entry) return Promise.resolve({ found: false });
return _measureElement(entry.ref).then((bounds) => {
const entryText = (typeof entry.getText === 'function') ? entry.getText() : entry.text;
return {
found: true,
element: {
testID: entry.testID || null,
type: entry.type || 'View',
text: entryText || null,
accessibilityLabel: entry.accessibilityLabel || null,
bounds: bounds || { x: 0, y: 0, width: 0, height: 0 },
visible: bounds ? bounds.width > 0 && bounds.height > 0 : false,
},
};
});
};
methods.get_text = function (params) {
const entry = _findElement(params);
if (!entry) return Promise.resolve({ text: null });
// Dynamic text getter
if (typeof entry.getText === 'function') {
return Promise.resolve({ text: entry.getText() });
}
// Static text
if (entry.text != null) return Promise.resolve({ text: entry.text });
// Check value for inputs
if (typeof entry.getValue === 'function') {
const v = entry.getValue();
return Promise.resolve({ text: v != null ? String(v) : null });
}
return Promise.resolve({ text: entry.accessibilityLabel || null });
};
methods.wait_for_element = function (params) {
const entry = _findElement(params);
return Promise.resolve({ found: !!entry });
};
methods.screenshot = function (_params) {
return Promise.resolve({ _needs_native: true });
};
methods.swipe = function (params) {
const direction = params.direction || 'up';
const distance = params.distance || 300;
// Find a scrollable target
const entry = params.key ? _findElement({ key: params.key }) : null;
const scrollRef = (entry && entry.ref) || _defaultScrollRef || _rootRef;
if (!scrollRef) {
return Promise.resolve({ success: true, message: 'Swipe simulated (no scrollable target): ' + direction });
}
// Try scrollTo on ScrollView/FlatList
if (typeof scrollRef.scrollTo === 'function') {
const dx = direction === 'right' ? distance : direction === 'left' ? -distance : 0;
const dy = direction === 'down' ? distance : direction === 'up' ? -distance : 0;
scrollRef.scrollTo({ x: Math.max(0, dx), y: Math.max(0, dy), animated: true });
return Promise.resolve({ success: true, message: 'Swiped via scrollTo: ' + direction });
}
if (typeof scrollRef.scrollToOffset === 'function') {
const offset = direction === 'down' || direction === 'right' ? distance : 0;
scrollRef.scrollToOffset({ offset: Math.max(0, offset), animated: true });
return Promise.resolve({ success: true, message: 'Swiped via scrollToOffset: ' + direction });
}
return Promise.resolve({ success: true, message: 'Swipe simulated: ' + direction + ' ' + distance + 'px' });
};
methods.scroll = function (params) {
const direction = params.direction || 'down';
const distance = params.distance || 300;
const entry = params.key ? _findElement({ key: params.key }) : null;
const scrollRef = (entry && entry.ref) || _defaultScrollRef || _rootRef;
if (!scrollRef) {
return Promise.resolve({ success: true, message: 'Scroll simulated (no scrollable target): ' + direction });
}
if (typeof scrollRef.scrollTo === 'function') {
const dx = direction === 'right' ? distance : direction === 'left' ? -distance : 0;
const dy = direction === 'down' ? distance : direction === 'up' ? -distance : 0;
scrollRef.scrollTo({ x: Math.max(0, dx), y: Math.max(0, dy), animated: true });
return Promise.resolve({ success: true, message: 'Scrolled via scrollTo' });
}
if (typeof scrollRef.scrollToOffset === 'function') {
const offset = direction === 'down' || direction === 'right' ? distance : 0;
scrollRef.scrollToOffset({ offset: Math.max(0, offset), animated: true });
return Promise.resolve({ success: true, message: 'Scrolled via scrollToOffset' });
}
return Promise.resolve({ success: true, message: 'Scroll simulated: ' + direction + ' ' + distance + 'px' });
};
methods.get_logs = function (_params) {
return Promise.resolve({ logs: _logs.map((e) => e.message) });
};
methods.clear_logs = function (_params) {
_logs = [];
return Promise.resolve({ success: true });
};
methods.get_route = function (_params) {
// Support both direct ref and React.createRef ({current: ref})
const nav = _navigationRef && _navigationRef.current ? _navigationRef.current : _navigationRef;
if (nav && nav.getCurrentRoute) {
const route = nav.getCurrentRoute();
if (route) {
return Promise.resolve({ name: route.name, params: route.params || {}, key: route.key || null });
}
}
if (nav && nav.getState) {
const state = nav.getState();
if (state && state.routes && state.routes.length > 0) {
const current = state.routes[state.index || 0];
return Promise.resolve({ name: current.name, params: current.params || {}, key: current.key || null });
}
}
return Promise.resolve({ name: null, message: 'No navigation ref or active route' });
};
methods.go_back = function (_params) {
// Support both direct ref and React.createRef ({current: ref})
const nav = _navigationRef && _navigationRef.current ? _navigationRef.current : _navigationRef;
if (nav) {
if (typeof nav.goBack === 'function') {
try {
if (nav.canGoBack && nav.canGoBack()) {
nav.goBack();
return Promise.resolve({ success: true, message: 'Navigated back' });
} else if (!nav.canGoBack) {
nav.goBack();
return Promise.resolve({ success: true, message: 'Navigated back' });
}
return Promise.resolve({ success: true, message: 'Already at root, no-op' });
} catch (e) {
return Promise.resolve({ success: false, message: 'goBack error: ' + e.message });
}
}
}
// Android BackHandler fallback
if (Platform.OS === 'android') {
try {
const { BackHandler } = require('react-native');
BackHandler.exitApp(); // This simulates back press
return Promise.resolve({ success: true, message: 'Back via BackHandler' });
} catch (e) {
// ignore
}
}
return Promise.resolve({ success: false, message: 'No navigation ref available' });
};
methods.long_press = function (params) {
const entry = params.ref
? null // handled below
: _findElement(params);
if (params.ref) {
return _getInteractiveElementsStructured().then((structured) => {
const target = structured.elements.find(el => el.ref === params.ref);
if (!target) return { success: false, message: 'Element not found' };
const e = _componentRegistry.get(target._testID);
if (!e) return { success: false, message: 'Component lost' };
// Long press = onPress after delay, or onLongPress if available
return new Promise((resolve) => {
setTimeout(() => {
if (typeof e.onLongPress === 'function') {
e.onLongPress();
} else if (typeof e.onPress === 'function') {
e.onPress();
}
resolve({ success: true });
}, params.duration || 500);
});
});
}
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
return new Promise((resolve) => {
setTimeout(() => {
if (typeof entry.onLongPress === 'function') entry.onLongPress();
else if (typeof entry.onPress === 'function') entry.onPress();
resolve({ success: true });
}, params.duration || 500);
});
};
methods.double_tap = function (params) {
const entry = _findElement(params);
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
if (typeof entry.onPress === 'function') {
entry.onPress();
entry.onPress();
}
return Promise.resolve({ success: true });
};
methods.drag = function (params) {
// RN doesn't have direct DOM — simulate message
return Promise.resolve({ success: true, message: 'Drag simulated from (' + params.startX + ',' + params.startY + ') to (' + params.endX + ',' + params.endY + ')' });
};
methods.tap_at = function (params) {
return Promise.resolve({ success: true, message: 'Tap at (' + params.x + ',' + params.y + ') simulated' });
};
methods.long_press_at = function (params) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ success: true, message: 'Long press at (' + params.x + ',' + params.y + ') simulated' });
}, params.duration || 500);
});
};
methods.edge_swipe = function (params) {
return Promise.resolve({ success: true, message: 'Edge swipe from ' + (params.edge || 'left') + ' simulated' });
};
methods.gesture = function (params) {
return Promise.resolve({ success: true, message: 'Gesture with ' + (params.actions || []).length + ' actions simulated' });
};
methods.scroll_until_visible = function (params) {
const maxScrolls = params.maxScrolls || 10;
let count = 0;
function attempt() {
const entry = _findElement(params);
if (entry) return Promise.resolve({ success: true });
if (count >= maxScrolls) return Promise.resolve({ success: false });
count++;
// Attempt scroll on default ref
const scrollRef = _defaultScrollRef || _rootRef;
if (scrollRef && typeof scrollRef.scrollTo === 'function') {
scrollRef.scrollTo({ y: count * 300, animated: true });
}
return new Promise((resolve) => setTimeout(() => resolve(attempt()), 200));
}
return attempt();
};
methods.swipe_coordinates = function (params) {
return Promise.resolve({ success: true, message: 'Swipe coordinates simulated' });
};
methods.get_checkbox_state = function (params) {
const entry = _findElement(params);
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
const val = (typeof entry.getValue === 'function') ? entry.getValue() : entry.value;
return Promise.resolve({ checked: !!val });
};
methods.get_slider_value = function (params) {
const entry = _findElement(params);
if (!entry) return Promise.resolve({ success: false, message: 'Element not found' });
const val = (typeof entry.getValue === 'function') ? entry.getValue() : entry.value;
return Promise.resolve({ value: parseFloat(val) || 0, min: entry.min || 0, max: entry.max || 100 });
};
methods.get_navigation_stack = function (_params) {
const nav = _navigationRef && _navigationRef.current ? _navigationRef.current : _navigationRef;
if (nav && nav.getState) {
const state = nav.getState();
if (state && state.routes) {
return Promise.resolve({
stack: state.routes.map(r => r.name),
length: state.routes.length
});
}
}
return Promise.resolve({ stack: [], length: 0 });
};
methods.get_errors = function (_params) {
var errors = _logs.filter(e => e.level === 'ERROR').map(e => e.message);
return Promise.resolve({ errors: errors });
};
methods.get_performance = function (_params) {
return Promise.resolve({ fps: 60, frameTime: 16.6 });
};
methods.get_frame_stats = function (_params) {
return Promise.resolve({ now: Date.now(), message: 'Frame stats not available in React Native' });
};
methods.get_memory_stats = function (_params) {
return Promise.resolve({ usedJSHeapSize: 0, totalJSHeapSize: 0 });
};
methods.wait_for_gone = function (params) {
const timeout = params.timeout || 5000;
const start = Date.now();
function check() {
const entry = _findElement(params);
if (!entry) return Promise.resolve({ success: true });
if (Date.now() - start > timeout) return Promise.resolve({ success: false });
return new Promise((resolve) => setTimeout(() => resolve(check()), 200));
}
return check();
};
methods.diagnose = function (_params) {
return Promise.resolve({
platform: Platform.OS,
elements: _componentRegistry.size,
framework: 'react-native',
app_name: _config.appName
});
};
methods.enable_test_indicators = function (_params) {
return Promise.resolve({ success: true, message: 'Test indicators not applicable in React Native' });
};
methods.get_indicator_status = function (_params) {
return Promise.resolve({ enabled: false });
};
methods.enable_network_monitoring = function (_params) {
return Promise.resolve({ success: true, message: 'Use React Native network interceptor' });
};
methods.get_network_requests = function (_params) {
return Promise.resolve({ requests: [] });
};
methods.clear_network_requests = function (_params) {
return Promise.resolve({ success: true });
};
methods.press_key = function (params) {
const key = (params.key || '').toLowerCase();
// For React Native, most key presses are no-ops since there's no physical keyboard.
// But we can simulate some behaviors.
const supportedKeys = [
'enter', 'return', 'tab', 'escape', 'backspace', 'delete',
'up', 'down', 'left', 'right', 'home', 'end',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
];
// Always return success for key presses — in RN they're mostly simulated
return Promise.resolve({
success: true,
message: 'Key press simulated: ' + key,
key: key,
modifiers: params.modifiers || [],
});
};
// ---------------------------------------------------------------------------
// AppMCP Tool Registration
// ---------------------------------------------------------------------------
var _registeredTools = [];
function registerTool(name, description, params, handler) {
var tool = { name: name, description: description || '', params: params || {}, handler: handler, source: 'js-registered' };
var idx = _registeredTools.findIndex(function (t) { return t.name === name; });
if (idx !== -1) _registeredTools[idx] = tool;
else _registeredTools.push(tool);
return tool;
}
methods.get_registered_tools = function () {
return {
tools: _registeredTools.map(function (t) { return { name: t.name, description: t.description, params: t.params, source: t.source }; }),
count: _registeredTools.length
};
};
methods.call_tool = function (params) {
var name = params.name;
var args = params.args || {};
var tool = _registeredTools.find(function (t) { return t.name === name; });
if (!tool) throw new Error('Tool not found: ' + name);
if (!tool.handler) throw new Error('Tool has no handler: ' + name);
return Promise.resolve(tool.handler(args)).then(function (result) {
return { success: true, tool: name, result: result };
});
};
// ---------------------------------------------------------------------------
// Capabilities
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// WebMCP Tool Registration
// ---------------------------------------------------------------------------
function registerTool(name, description, params, handler) {
const tool = { name, description: description || '', params: params || {}, handler, source: 'js-registered' };
const idx = _registeredTools.findIndex(t => t.name === name);
if (idx !== -1) _registeredTools[idx] = tool;
else _registeredTools.push(tool);
return tool;
}
methods.get_registered_tools = function () {
return {
tools: _registeredTools.map(t => ({ name: t.name, description: t.description, params: t.params, source: t.source })),
count: _registeredTools.length
};
};
methods.call_tool = function (params) {
const toolName = params.name || '';
const toolParams = params.params || {};
const tool = _registeredTools.find(t => t.name === toolName);
if (!tool) return { success: false, error: 'Tool not found: ' + toolName };
if (typeof tool.handler !== 'function') return { success: false, error: 'Tool has no handler: ' + toolName };
return Promise.resolve()
.then(() => tool.handler(toolParams))
.then(result => ({ success: true, result: result, source: 'js-registered' }))
.catch(e => ({ success: false, error: e.message, source: 'js-registered' }));
};
function _getCapabilities() {
return Object.keys(methods);
}
// ---------------------------------------------------------------------------
// HTTP + WebSocket server
// ---------------------------------------------------------------------------
function _parseHttpRequest(data) {
const raw = typeof data === 'string' ? data : data.toString('utf-8');
const lines = raw.split('\r\n');
const requestLine = lines[0] || '';
const parts = requestLine.split(' ');
const method = parts[0] || 'GET';
const path = parts[1] || '/';
const headers = {};
let i = 1;
for (; i < lines.length; i++) {
if (lines[i] === '') break;
const colonIdx = lines[i].indexOf(':');
if (colonIdx > 0) {
const key = lines[i].substring(0, colonIdx).trim().toLowerCase();
const value = lines[i].substring(colonIdx + 1).trim();
headers[key] = value;
}