@@ -6,30 +6,64 @@ import { stopSketch, expandConsole } from '../actions/ide';
66export default function useHandleMessageEvent ( ) {
77 const dispatch = useDispatch ( ) ;
88
9+ const safeStringify = (
10+ obj ,
11+ depth = 0 ,
12+ maxDepth = 10 ,
13+ seen = new WeakMap ( )
14+ ) => {
15+ if ( typeof obj !== 'object' || obj === null ) return obj ;
16+
17+ if ( depth >= maxDepth ) {
18+ if ( seen . has ( obj ) ) return '[Circular Reference]' ;
19+ }
20+
21+ seen . set ( obj , true ) ;
22+
23+ return Array . isArray ( obj )
24+ ? obj . map ( ( item ) => safeStringify ( item , depth + 1 , maxDepth , seen ) )
25+ : Object . fromEntries (
26+ Object . entries ( obj ) . map ( ( [ key , value ] ) => [
27+ key ,
28+ safeStringify ( value , depth + 1 , maxDepth , seen )
29+ ] )
30+ ) ;
31+ } ;
32+
933 const handleMessageEvent = ( data ) => {
34+ if ( ! data || typeof data !== 'object' ) return ;
1035 const { source, messages } = data ;
11- if ( source === 'sketch' && Array . isArray ( messages ) ) {
12- const decodedMessages = messages . map ( ( message ) => Decode ( message . log ) ) ;
13- decodedMessages . every ( ( message , index , arr ) => {
14- const { data : args } = message ;
15- let hasInfiniteLoop = false ;
16- Object . keys ( args ) . forEach ( ( key ) => {
17- if (
18- typeof args [ key ] === 'string' &&
19- args [ key ] . includes ( 'Exiting potential infinite loop' )
20- ) {
21- dispatch ( stopSketch ( ) ) ;
22- dispatch ( expandConsole ( ) ) ;
23- hasInfiniteLoop = true ;
24- }
25- } ) ;
26- if ( hasInfiniteLoop ) {
27- return false ;
28- }
29- return true ;
30- } ) ;
31- dispatch ( dispatchConsoleEvent ( decodedMessages ) ) ;
36+ if ( source !== 'sketch' || ! Array . isArray ( messages ) ) return ;
37+
38+ const decodedMessages = messages . map ( ( message ) => {
39+ try {
40+ const decoded = Decode ( message . log ) ?? '[Unknown Message]' ; // Ensure decoding works
41+ return safeStringify ( decoded ) ;
42+ } catch ( error ) {
43+ console . error ( 'Error decoding message:' , error ) ;
44+ return { error : 'Failed to decode message' } ;
45+ }
46+ } ) ;
47+
48+ // Detect infinite loop warnings
49+ const hasInfiniteLoop = decodedMessages . some (
50+ ( message ) =>
51+ message ?. data &&
52+ Object . values ( message . data ) . some (
53+ ( arg ) =>
54+ typeof arg === 'string' &&
55+ arg . includes ( 'Exiting potential infinite loop' )
56+ )
57+ ) ;
58+
59+ if ( hasInfiniteLoop ) {
60+ dispatch ( stopSketch ( ) ) ;
61+ dispatch ( expandConsole ( ) ) ;
62+ return ;
3263 }
64+
65+ dispatch ( dispatchConsoleEvent ( decodedMessages ) ) ;
3366 } ;
67+
3468 return handleMessageEvent ;
3569}
0 commit comments