-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathNativeScriptException.mm
More file actions
1250 lines (1084 loc) Β· 49.3 KB
/
NativeScriptException.mm
File metadata and controls
1250 lines (1084 loc) Β· 49.3 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
#include "NativeScriptException.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <UIKit/UIKit.h>
#if __has_include(<UniformTypeIdentifiers/UniformTypeIdentifiers.h>)
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#endif
#import <objc/message.h>
#import <objc/runtime.h>
#include <TargetConditionals.h>
#include <sstream>
#include <mutex>
#include <limits>
#include <algorithm>
#include "Caches.h"
#include "Helpers.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
using namespace v8;
namespace {
static UITextView* gErrorStackTextView = nil;
static NSString* gLatestStackText = nil;
struct PendingErrorDisplay {
uint64_t ticket = 0;
bool contextCaptured = false;
bool modalPresented = false;
bool fallbackScheduled = false;
v8::Isolate* isolate = nullptr;
std::string title;
std::string message;
std::string rawStack;
std::string canonicalStack;
std::string consolePayload;
};
static std::mutex gErrorDisplayMutex;
static PendingErrorDisplay gPendingErrorDisplay;
static uint64_t gNextErrorTicket = 1;
}
namespace tns {
// External flag from Runtime.mm to track JavaScript errors
extern bool jsErrorOccurred;
extern bool isErrorDisplayShowing;
static void UpdateDisplayedStackText(const std::string& stackText);
static void RenderErrorModalUI(v8::Isolate* isolate, const std::string& title,
const std::string& message, const std::string& stackText);
static void ShowErrorModalSynchronously(const std::string& title,
const std::string& message,
const std::string& stackTrace);
static void ScheduleFallbackPresentation(uint64_t ticket);
static void PresentFallbackIfNeeded(uint64_t ticket);
static std::string ResolveDisplayStack(const PendingErrorDisplay& state);
static void ConsiderStackCandidate(PendingErrorDisplay& state, v8::Isolate* isolate,
const std::string& candidateStack);
NativeScriptException::NativeScriptException(const std::string& message) {
this->javascriptException_ = nullptr;
this->message_ = message;
this->name_ = "NativeScriptException";
}
NativeScriptException::NativeScriptException(Isolate* isolate, TryCatch& tc,
const std::string& message) {
Local<Value> error = tc.Exception();
this->javascriptException_ = new Persistent<Value>(isolate, tc.Exception());
this->message_ = GetErrorMessage(isolate, error, message);
this->stackTrace_ = tns::GetSmartStackTrace(isolate, &tc, error);
this->fullMessage_ = GetFullMessage(isolate, tc, this->message_);
this->name_ = "NativeScriptException";
tc.Reset();
}
NativeScriptException::NativeScriptException(Isolate* isolate, const std::string& message,
const std::string& name) {
this->name_ = name;
Local<Value> error = Exception::Error(tns::ToV8String(isolate, message));
auto context = Caches::Get(isolate)->GetContext();
error.As<Object>()
->Set(context, ToV8String(isolate, "name"), ToV8String(isolate, this->name_))
.FromMaybe(false);
this->javascriptException_ = new Persistent<Value>(isolate, error);
this->message_ = GetErrorMessage(isolate, error, message);
this->stackTrace_ = GetErrorStackTrace(isolate, Exception::GetStackTrace(error));
this->fullMessage_ =
GetFullMessage(isolate, Exception::CreateMessage(isolate, error), this->message_);
}
NativeScriptException::~NativeScriptException() { delete this->javascriptException_; }
void NativeScriptException::OnUncaughtError(Local<v8::Message> message, Local<Value> error) {
@try {
Isolate* isolate = message->GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<Object> global = context->Global();
Local<Value> handler;
id value = Runtime::GetAppConfigValue("discardUncaughtJsExceptions");
bool isDiscarded = value ? [value boolValue] : false;
std::string cbName = isDiscarded ? "__onDiscardedError" : "__onUncaughtError";
bool success = global->Get(context, tns::ToV8String(isolate, cbName)).ToLocal(&handler);
std::string stackTrace = tns::GetSmartStackTrace(isolate, nullptr, error);
if (stackTrace.empty()) {
stackTrace = GetErrorStackTrace(isolate, message->GetStackTrace());
}
std::string fullMessage;
auto errObject = error.As<Object>();
auto fullMessageString = tns::ToV8String(isolate, "fullMessage");
if (errObject->HasOwnProperty(context, fullMessageString).ToChecked()) {
// check if we have a "fullMessage" on the error, and log that instead - since it includes
// more info about the exception.
v8::Local<v8::Value> fullMessage_;
if (errObject->Get(context, fullMessageString).ToLocal(&fullMessage_)) {
fullMessage = tns::ToString(isolate, fullMessage_);
} else {
// Fallback to regular message if fullMessage access fails
Local<v8::String> messageV8String = message->Get();
fullMessage = tns::ToString(isolate, messageV8String);
}
} else {
Local<v8::String> messageV8String = message->Get();
std::string messageString = tns::ToString(isolate, messageV8String);
fullMessage = messageString + "\n at \n" + stackTrace;
}
if (success && handler->IsFunction()) {
if (error->IsObject()) {
// Try to set stackTrace property, but don't crash if it fails
bool stackTraceSet = error.As<Object>()
->Set(context, tns::ToV8String(isolate, "stackTrace"),
tns::ToV8String(isolate, stackTrace))
.FromMaybe(false);
if (!stackTraceSet) {
Log(@"Warning: Failed to set stackTrace property on error object");
}
}
Local<v8::Function> errorHandlerFunc = handler.As<v8::Function>();
Local<Object> thiz = Object::New(isolate);
Local<Value> args[] = {error};
Local<Value> result;
TryCatch tc(isolate);
success = errorHandlerFunc->Call(context, thiz, 1, args).ToLocal(&result);
if (tc.HasCaught()) {
tns::LogError(isolate, tc);
}
// Don't crash if error handler call failed - just log it
if (!success) {
Log(@"Warning: Error handler function call failed");
}
}
if (!isDiscarded) {
NSString* reasonStr = [NSString stringWithUTF8String:fullMessage.c_str()];
if (reasonStr == nil) {
reasonStr = @"(invalid UTF-8 message from JS)";
}
NSString* name = @"NativeScriptUncaughtJSException";
// In debug mode, show error modal instead of crashing
if (RuntimeConfig.IsDebug) {
// Mark that a JavaScript error occurred
jsErrorOccurred = true;
Log(@"***** JavaScript exception occurred "
@"in debug mode *****\n");
Log(@"%s", fullMessage.c_str());
Log(@"%s", stackTrace.c_str());
// Log(@"π¨ CALLING ShowErrorModal for OnUncaughtError - should display branded modal");
// Show the error modal with same message as terminal
std::string errorTitle = "Uncaught JavaScript Exception";
// Extract just the error type/message (first line) for cleaner display
std::string errorMessage = "JavaScript error occurred";
if (reasonStr) {
std::string fullMsg = [reasonStr UTF8String];
size_t firstNewline = fullMsg.find('\n');
if (firstNewline != std::string::npos) {
errorMessage = fullMsg.substr(0, firstNewline);
} else {
errorMessage = fullMsg;
}
}
Log(@"***** End stack trace - Fix error to continue *****\n");
ShowErrorModal(isolate, errorTitle, errorMessage, stackTrace);
// Don't crash in debug mode - just return
return;
}
// In release mode, crash as before - BUT NEVER IN DEBUG MODE
if (!RuntimeConfig.IsDebug) {
// we throw the exception on main thread so all meta-data is captured
dispatch_async(dispatch_get_main_queue(), ^(void) {
NSException* objcException =
[NSException exceptionWithName:name
reason:reasonStr
userInfo:@{@"sender" : @"onUncaughtError"}];
Log(@"***** Fatal JavaScript exception - application has been terminated. *****\n");
Log(@"%@", objcException);
@throw objcException;
});
}
} else {
Log(@"NativeScript discarding uncaught JS exception!");
}
} @catch (NSException* exception) {
Log(@"OnUncaughtError: Caught exception during error handling: %@", exception);
if (RuntimeConfig.IsDebug) {
Log(@"Debug mode - suppressing crash and continuing");
} else {
@throw exception; // Re-throw in release mode
}
}
}
void NativeScriptException::ReThrowToV8(Isolate* isolate) {
@try {
// The Isolate::Scope here is necessary because the Exception::Error method internally relies on
// the Isolate::GetCurrent method which might return null if we do not use the proper scope
Isolate::Scope scope(isolate);
Local<Context> context = isolate->GetCurrentContext();
Local<Value> errObj;
if (this->javascriptException_ != nullptr) {
errObj = this->javascriptException_->Get(isolate);
if (errObj->IsObject()) {
if (!this->fullMessage_.empty()) {
bool success = errObj.As<Object>()
->Set(context, tns::ToV8String(isolate, "fullMessage"),
tns::ToV8String(isolate, this->fullMessage_))
.FromMaybe(false);
if (!success) {
Log(@"Warning: Failed to set fullMessage property on error object");
}
} else if (!this->message_.empty()) {
bool success = errObj.As<Object>()
->Set(context, tns::ToV8String(isolate, "fullMessage"),
tns::ToV8String(isolate, this->message_))
.FromMaybe(false);
if (!success) {
Log(@"Warning: Failed to set fullMessage property on error object");
}
}
}
} else if (!this->fullMessage_.empty()) {
errObj = Exception::Error(tns::ToV8String(isolate, this->fullMessage_));
} else if (!this->message_.empty()) {
errObj = Exception::Error(tns::ToV8String(isolate, this->message_));
} else {
errObj = Exception::Error(
tns::ToV8String(isolate, "No javascript exception or message provided."));
}
// For critical exceptions (like module loading failures), provide detailed error reporting
bool isCriticalException = false;
// Check if this is a critical exception that should show detailed error info
if (!this->message_.empty()) {
// Module-related errors should show detailed stack traces
isCriticalException =
(this->message_.find("Error calling module function") != std::string::npos ||
this->message_.find("Cannot evaluate module") != std::string::npos ||
this->message_.find("Cannot instantiate module") != std::string::npos ||
this->message_.find("Cannot compile") != std::string::npos);
}
if (isCriticalException) {
// Mark that a JavaScript error occurred
jsErrorOccurred = true;
// Create detailed error message similar to OnUncaughtError
std::string stackTrace = this->stackTrace_;
std::string fullMessage;
if (!this->fullMessage_.empty()) {
fullMessage = this->fullMessage_;
} else {
fullMessage = this->message_ + "\n at \n" + stackTrace;
}
// Always log the detailed error for critical exceptions (both debug and release)
Log(@"***** JavaScript exception occurred - detailed stack trace follows *****\n");
Log(@"NativeScript encountered an error:");
NSString* errorStr = [NSString stringWithUTF8String:fullMessage.c_str()];
if (errorStr != nil) {
Log(@"%@", errorStr);
} else {
Log(@"(error message contained invalid UTF-8)");
}
// Additional guidance after the stack trace for boot/init errors
Log(@"\n======================================");
Log(@"Error on app initialization.");
Log(@"Please fix the error and save the file to auto reload the app.");
Log(@"======================================");
// In debug mode, continue execution; in release mode, terminate
if (RuntimeConfig.IsDebug) {
Log(@"***** End stack trace - showing error modal and continuing execution *****\n");
// Show error modal in debug mode
std::string errorTitle = "JavaScript Error";
// Extract just the error message (first line) for the title
std::string errorMessage = this->message_;
size_t firstNewline = errorMessage.find('\n');
if (firstNewline != std::string::npos) {
errorMessage = errorMessage.substr(0, firstNewline);
}
// Prefer a clean stack for the modal
std::string displayStack = stackTrace;
if (displayStack.empty()) {
displayStack = fullMessage; // last resort
}
ShowErrorModal(isolate, errorTitle, errorMessage, displayStack);
// In debug mode, DON'T throw the exception - just return to prevent crash
// The error modal will be shown and the app will continue running
Log(@"***** Error handled gracefully - app continues without crash *****\n");
return;
} else {
Log(@"***** End stack trace - terminating application *****\n");
// In release mode, create proper message and call OnUncaughtError for termination
Local<v8::Message> message = Exception::CreateMessage(isolate, errObj);
OnUncaughtError(message, errObj);
return; // OnUncaughtError will terminate, so we don't continue
}
}
// For non-critical exceptions:
if (RuntimeConfig.IsDebug) {
// Be gentle, state case in logs and allow developer to continue
Log(@"Debug mode - suppressing throw to continue: %s", this->message_.c_str());
} else {
// just re-throw normally
isolate->ThrowException(errObj);
}
} @catch (NSException* exception) {
Log(@"ReThrowToV8: Caught exception during error handling: %@", exception);
if (RuntimeConfig.IsDebug) {
Log(@"Debug mode - suppressing crash and continuing");
} else {
@throw exception; // Re-throw in release mode
}
}
}
std::string NativeScriptException::GetErrorMessage(Isolate* isolate, Local<Value>& error,
const std::string& prependMessage) {
std::shared_ptr<Caches> cache = Caches::Get(isolate);
Local<Context> context = cache->GetContext();
// get whole error message from previous stack
std::stringstream ss;
if (prependMessage != "") {
ss << prependMessage << std::endl;
}
std::string errMessage;
bool hasFullErrorMessage = false;
auto v8FullMessage = tns::ToV8String(isolate, "fullMessage");
if (error->IsObject() && error.As<Object>()->Has(context, v8FullMessage).ToChecked()) {
hasFullErrorMessage = true;
Local<Value> errMsgVal;
bool success = error.As<Object>()->Get(context, v8FullMessage).ToLocal(&errMsgVal);
if (success && !errMsgVal.IsEmpty()) {
errMessage = tns::ToString(isolate, errMsgVal.As<v8::String>());
} else {
errMessage = "";
if (!success) {
Log(@"Warning: Failed to get fullMessage property from error object");
}
}
ss << errMessage;
}
MaybeLocal<v8::String> str = error->ToDetailString(context);
if (!str.IsEmpty()) {
v8::String::Utf8Value utfError(isolate, str.FromMaybe(Local<v8::String>()));
if (hasFullErrorMessage) {
ss << std::endl;
}
ss << *utfError;
}
return ss.str();
}
std::string NativeScriptException::GetErrorStackTrace(Isolate* isolate,
const Local<StackTrace>& stackTrace) {
if (stackTrace.IsEmpty()) {
return "";
}
std::stringstream ss;
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
int frameCount = stackTrace->GetFrameCount();
for (int i = 0; i < frameCount; i++) {
Local<StackFrame> frame = stackTrace->GetFrame(isolate, i);
std::string funcName = tns::ToString(isolate, frame->GetFunctionName());
std::string srcName = tns::ToString(isolate, frame->GetScriptName());
int lineNumber = frame->GetLineNumber();
int column = frame->GetColumn();
ss << "\t" << (i > 0 ? "at " : "") << funcName.c_str() << "(" << srcName.c_str() << ":"
<< lineNumber << ":" << column << ")" << std::endl;
}
return ss.str();
}
std::string NativeScriptException::GetFullMessage(Isolate* isolate, const TryCatch& tc,
const std::string& jsExceptionMessage) {
std::string loggedMessage = GetFullMessage(isolate, tc.Message(), jsExceptionMessage);
if (!tc.CanContinue()) {
std::stringstream errM;
errM << std::endl
<< "An uncaught error has occurred and V8's TryCatch block CAN'T be continued. ";
loggedMessage = errM.str() + loggedMessage;
}
return loggedMessage;
}
std::string NativeScriptException::GetFullMessage(Isolate* isolate, Local<v8::Message> message,
const std::string& jsExceptionMessage) {
Local<Context> context = isolate->GetEnteredOrMicrotaskContext();
std::stringstream ss;
ss << jsExceptionMessage;
// get script name
Local<Value> scriptResName = message->GetScriptResourceName();
// get stack trace
std::string stackTraceMessage = GetErrorStackTrace(isolate, message->GetStackTrace());
if (!scriptResName.IsEmpty() && scriptResName->IsString()) {
ss << std::endl << "File: (" << tns::ToString(isolate, scriptResName.As<v8::String>());
} else {
ss << std::endl << "File: (<unknown>";
}
ss << ":" << message->GetLineNumber(context).ToChecked() << ":" << message->GetStartColumn()
<< ")" << std::endl
<< std::endl;
ss << "StackTrace: " << std::endl << stackTraceMessage << std::endl;
std::string loggedMessage = ss.str();
// TODO: Log the error
// tns::LogError(isolate, tc);
return loggedMessage;
}
void NativeScriptException::ShowErrorModal(Isolate* isolate, const std::string& title,
const std::string& message,
const std::string& stackTrace) {
if (!RuntimeConfig.IsDebug) {
return;
}
if (!Runtime::showErrorDisplay()) {
return;
}
uint64_t ticketToSchedule = 0;
{
std::lock_guard<std::mutex> lock(gErrorDisplayMutex);
// If the console already presented this error (console-first scenario), just enrich the context.
if (gPendingErrorDisplay.ticket != 0 && !gPendingErrorDisplay.contextCaptured &&
gPendingErrorDisplay.modalPresented) {
gPendingErrorDisplay.contextCaptured = true;
gPendingErrorDisplay.isolate = isolate;
gPendingErrorDisplay.title = title;
gPendingErrorDisplay.message = message;
gPendingErrorDisplay.rawStack = stackTrace;
ConsiderStackCandidate(gPendingErrorDisplay, isolate, stackTrace);
return;
}
gPendingErrorDisplay.ticket = gNextErrorTicket++;
gPendingErrorDisplay.contextCaptured = true;
gPendingErrorDisplay.modalPresented = false;
gPendingErrorDisplay.fallbackScheduled = true;
gPendingErrorDisplay.isolate = isolate;
gPendingErrorDisplay.title = title;
gPendingErrorDisplay.message = message;
gPendingErrorDisplay.rawStack = stackTrace;
gPendingErrorDisplay.consolePayload.clear();
gPendingErrorDisplay.canonicalStack.clear();
ConsiderStackCandidate(gPendingErrorDisplay, isolate, stackTrace);
ticketToSchedule = gPendingErrorDisplay.ticket;
}
if (ticketToSchedule != 0) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
ScheduleFallbackPresentation(ticketToSchedule);
});
}
}
void NativeScriptException::SubmitConsoleErrorPayload(Isolate* isolate, const std::string& payload) {
if (!RuntimeConfig.IsDebug) {
return;
}
if (!Runtime::showErrorDisplay()) {
return;
}
PendingErrorDisplay stateSnapshot;
bool presentNow = false;
bool updateExisting = false;
auto promoteConsolePayload = [&](const std::string& text, v8::Isolate* payloadIsolate) {
gPendingErrorDisplay.consolePayload = text;
if (payloadIsolate != nullptr) {
gPendingErrorDisplay.isolate = payloadIsolate;
}
gPendingErrorDisplay.canonicalStack = text;
};
{
std::lock_guard<std::mutex> lock(gErrorDisplayMutex);
auto buildDefaultContext = [&](void) {
gPendingErrorDisplay.title = "JavaScript Error";
std::string firstLine = payload;
size_t newlinePos = payload.find('\n');
if (newlinePos != std::string::npos) {
firstLine = payload.substr(0, newlinePos);
}
gPendingErrorDisplay.message = firstLine;
gPendingErrorDisplay.rawStack = payload;
promoteConsolePayload(payload, isolate);
};
if (gPendingErrorDisplay.ticket == 0) {
gPendingErrorDisplay.ticket = gNextErrorTicket++;
gPendingErrorDisplay.canonicalStack.clear();
}
if (!gPendingErrorDisplay.contextCaptured && !gPendingErrorDisplay.modalPresented) {
// Console-first scenario for a brand new error
gPendingErrorDisplay.modalPresented = true;
gPendingErrorDisplay.isolate = isolate;
buildDefaultContext();
stateSnapshot = gPendingErrorDisplay;
presentNow = true;
} else if (!gPendingErrorDisplay.modalPresented) {
// Context captured (or pending) but UI not yet shown β prefer the console payload
if (!gPendingErrorDisplay.contextCaptured) {
buildDefaultContext();
}
if (isolate != nullptr) {
gPendingErrorDisplay.isolate = isolate;
}
promoteConsolePayload(payload, isolate);
gPendingErrorDisplay.modalPresented = true;
stateSnapshot = gPendingErrorDisplay;
presentNow = true;
} else {
// Modal already visible (fallback or previous payload) β just update the text content
promoteConsolePayload(payload, isolate);
updateExisting = true;
}
}
if (presentNow) {
std::string displayStack = stateSnapshot.canonicalStack.empty()
? (stateSnapshot.consolePayload.empty()
? ResolveDisplayStack(stateSnapshot)
: stateSnapshot.consolePayload)
: stateSnapshot.canonicalStack;
RenderErrorModalUI(stateSnapshot.isolate, stateSnapshot.title, stateSnapshot.message,
displayStack);
} else if (updateExisting) {
std::string displayStack = gPendingErrorDisplay.canonicalStack.empty()
? (gPendingErrorDisplay.consolePayload.empty()
? ResolveDisplayStack(gPendingErrorDisplay)
: gPendingErrorDisplay.consolePayload)
: gPendingErrorDisplay.canonicalStack;
UpdateDisplayedStackText(displayStack);
}
}
static void ScheduleFallbackPresentation(uint64_t ticket) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)),
dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
PresentFallbackIfNeeded(ticket);
});
}
static void PresentFallbackIfNeeded(uint64_t ticket) {
PendingErrorDisplay snapshot;
bool shouldPresent = false;
{
std::lock_guard<std::mutex> lock(gErrorDisplayMutex);
if (gPendingErrorDisplay.ticket == ticket && !gPendingErrorDisplay.modalPresented) {
gPendingErrorDisplay.modalPresented = true;
snapshot = gPendingErrorDisplay;
shouldPresent = true;
}
}
if (!shouldPresent) {
return;
}
std::string finalStack = ResolveDisplayStack(snapshot);
RenderErrorModalUI(snapshot.isolate, snapshot.title, snapshot.message, finalStack);
}
static std::string ResolveDisplayStack(const PendingErrorDisplay& state) {
// Deterministic preference: canonicalStack > consolePayload > rawStack > message
// Remap when possible so the UI matches terminal output.
if (!state.canonicalStack.empty()) {
return state.canonicalStack;
}
auto remapIfPossible = [&](const std::string& text) -> std::string {
if (text.empty()) return std::string();
if (state.isolate != nullptr) {
std::string remapped = tns::RemapStackTraceIfAvailable(state.isolate, text);
if (!remapped.empty()) {
return remapped;
}
}
return text;
};
if (!state.consolePayload.empty()) {
return remapIfPossible(state.consolePayload);
}
if (!state.rawStack.empty()) {
return remapIfPossible(state.rawStack);
}
return state.message;
}
static void ConsiderStackCandidate(PendingErrorDisplay& state, v8::Isolate* isolate,
const std::string& candidateStack) {
if (candidateStack.empty()) {
return;
}
v8::Isolate* effectiveIsolate = isolate != nullptr ? isolate : state.isolate;
std::string normalized = candidateStack;
if (effectiveIsolate != nullptr) {
std::string remapped = tns::RemapStackTraceIfAvailable(effectiveIsolate, candidateStack);
if (!remapped.empty()) {
normalized = remapped;
}
}
// Deterministic behavior: if no canonical stack yet, set it to the first available candidate.
// Console payloads will explicitly override canonicalStack elsewhere.
if (state.canonicalStack.empty()) {
state.canonicalStack = normalized;
}
}
static void UpdateDisplayedStackText(const std::string& stackText) {
NSString* stackNSString = [NSString stringWithUTF8String:stackText.c_str()];
if (stackNSString == nil) {
stackNSString = @"(invalid UTF-8 stack trace)";
}
gLatestStackText = stackNSString;
auto applyUpdate = ^{
if (gErrorStackTextView != nil) {
gErrorStackTextView.text = gLatestStackText;
gErrorStackTextView.contentOffset = CGPointMake(0, 0);
}
};
if ([NSThread isMainThread]) {
applyUpdate();
} else {
dispatch_async(dispatch_get_main_queue(), applyUpdate);
}
}
static void RenderErrorModalUI(v8::Isolate* isolate, const std::string& title,
const std::string& message, const std::string& stackText) {
if (!RuntimeConfig.IsDebug || !Runtime::showErrorDisplay()) {
return;
}
// Always prefer the shared pending state's canonical/console text so callers cannot
// accidentally overwrite with a worse stack.
std::string stackForModal = stackText;
{
std::lock_guard<std::mutex> lock(gErrorDisplayMutex);
if (!gPendingErrorDisplay.canonicalStack.empty()) {
stackForModal = gPendingErrorDisplay.canonicalStack;
} else if (!gPendingErrorDisplay.consolePayload.empty()) {
stackForModal = gPendingErrorDisplay.consolePayload;
}
}
if (stackForModal.empty()) {
stackForModal = message;
}
// Final guard: remap here as well so the UI always matches the terminal output,
// even if earlier stages missed remapping due to timing.
if (isolate != nullptr) {
std::string maybeRemapped = tns::RemapStackTraceIfAvailable(isolate, stackForModal);
if (!maybeRemapped.empty()) {
stackForModal = maybeRemapped;
}
}
UpdateDisplayedStackText(stackForModal);
bool alreadyShowing = isErrorDisplayShowing;
UIApplication* app = [UIApplication sharedApplication];
BOOL hasAnyWindows = NO;
#if TARGET_OS_VISION
if (@available(iOS 13.0, *)) {
for (UIScene* scene in app.connectedScenes) {
if ([scene isKindOfClass:[UIWindowScene class]]) {
UIWindowScene* ws = (UIWindowScene*)scene;
if (ws.windows.count > 0) { hasAnyWindows = YES; break; }
}
}
}
#else
hasAnyWindows = app.windows.count > 0;
#endif
if (!alreadyShowing && !hasAnyWindows && app.connectedScenes.count == 0) {
Log(@"Note: JavaScript error during boot.");
Log(@"================================");
Log(@"%s", stackForModal.c_str());
Log(@"================================");
Log(@"Please fix the error and save the file to auto reload the app.");
Log(@"================================");
return;
}
if (alreadyShowing) {
return;
}
isErrorDisplayShowing = true;
auto showSynchronously = ^{
@try {
// Log(@"[ShowErrorModal] On main thread - showing modal synchronously %s", message.c_str());
ShowErrorModalSynchronously(title, message, stackForModal);
} @catch (NSException* exception) {
Log(@"Error details - Title: %s, Message: %s", title.c_str(), message.c_str());
}
};
if ([NSThread isMainThread]) {
showSynchronously();
} else {
dispatch_sync(dispatch_get_main_queue(), showSynchronously);
}
}
static void ShowErrorModalSynchronously(const std::string& title,
const std::string& message,
const std::string& stackTrace) {
// Use static variables to keep strong references and prevent deallocation
static UIWindow* __attribute__((unused)) foundationWindowRef =
nil; // Keep foundation window alive
static UIWindow* errorWindow = nil;
// BOOTSTRAP iOS APP LIFECYCLE: Ensure basic app infrastructure exists
// This is crucial when JavaScript fails before UIApplicationMain completes normal setup
UIApplication* sharedApp = [UIApplication sharedApplication];
// If no windows exist, create a foundational window to establish the hierarchy
BOOL appHasWindows = NO;
#if TARGET_OS_VISION
if (@available(iOS 13.0, *)) {
for (UIScene* scene in sharedApp.connectedScenes) {
if ([scene isKindOfClass:[UIWindowScene class]]) {
if (((UIWindowScene*)scene).windows.count > 0) { appHasWindows = YES; break; }
}
}
}
#else
appHasWindows = sharedApp.windows.count > 0;
#endif
if (!appHasWindows) {
// Log(@"π Bootstrap: No app windows exist - creating foundational window hierarchy");
// Create a basic foundational window that mimics what UIApplicationMain would create
UIWindow* foundationWindow = nil;
if (@available(iOS 13.0, *)) {
// For iOS 13+, we need to handle window scenes properly
UIWindowScene* foundationScene = nil;
// Try to find or create a window scene
for (UIScene* scene in sharedApp.connectedScenes) {
if ([scene isKindOfClass:[UIWindowScene class]]) {
foundationScene = (UIWindowScene*)scene;
// Log(@"π Bootstrap: Found existing scene for foundation window");
break;
}
}
if (foundationScene) {
foundationWindow = [[UIWindow alloc] initWithWindowScene:foundationScene];
// Log(@"π Bootstrap: Created foundation window with existing scene");
} else {
// If no scenes exist, create a window without scene (iOS 12 style fallback)
// On visionOS, UIScreen is unavailable. Skip frame-based creation there.
#if !TARGET_OS_VISION
foundationWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
#endif
// Log(@"π Bootstrap: Created foundation window without scene (emergency mode)");
}
} else {
// iOS 12 and below - simple window creation
// On visionOS, UIScreen is unavailable; this branch is only for iOS 12 and below.
#if !TARGET_OS_VISION
foundationWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
#endif
// Log(@"π Bootstrap: Created foundation window for iOS 12");
}
if (foundationWindow) {
// Set up a basic root view controller to establish the hierarchy
UIViewController* foundationViewController = [[UIViewController alloc] init];
foundationViewController.view.backgroundColor = [UIColor blackColor]; // Invisible foundation
foundationWindow.rootViewController = foundationViewController;
foundationWindow.windowLevel = UIWindowLevelNormal; // Base level
foundationWindow.backgroundColor = [UIColor blackColor];
// Make it key and visible to establish the window hierarchy
[foundationWindow makeKeyAndVisible];
// Keep a strong reference to prevent deallocation
foundationWindowRef = foundationWindow;
// Give iOS a moment to process the new window hierarchy (we're already on main queue)
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, false);
// Detailed window hierarchy inspection
BOOL appHasWindowsAfterBootstrap = NO;
#if TARGET_OS_VISION
if (@available(iOS 13.0, *)) {
for (UIScene* scene in sharedApp.connectedScenes) {
if ([scene isKindOfClass:[UIWindowScene class]]) {
if (((UIWindowScene*)scene).windows.count > 0) { appHasWindowsAfterBootstrap = YES; break; }
}
}
}
#else
appHasWindowsAfterBootstrap = sharedApp.windows.count > 0;
#endif
if (!appHasWindowsAfterBootstrap) {
// Log(@"π Bootstrap: π¨ CRITICAL: Foundation window not in app.windows hierarchy!");
// Log(@"π Bootstrap: This indicates a fundamental iOS window system issue");
// Try alternative window registration approach
// Log(@"π Bootstrap: Attempting alternative window registration...");
[foundationWindow.layer setNeedsDisplay];
[foundationWindow.layer displayIfNeeded];
[foundationWindow layoutIfNeeded];
// Force another run loop cycle
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, false);
}
} else {
// Log(@"π Bootstrap: WARNING - Failed to create foundation window");
}
} else {
// Log(@"π Bootstrap: App windows already exist (%lu) - no bootstrap needed",
// (unsigned long)sharedApp.windows.count);
}
// Create a dedicated error window that works even during early app lifecycle
// Clean up any previous error window
if (errorWindow) {
errorWindow.hidden = YES;
[errorWindow resignKeyWindow];
errorWindow = nil;
gErrorStackTextView = nil;
}
// iOS 13+ requires proper window scene handling
if (@available(iOS 13.0, *)) {
// Try to find an existing window scene, or create one if needed
UIWindowScene* windowScene = nil;
// First, try to find an existing connected scene
for (UIScene* scene in [UIApplication sharedApplication].connectedScenes) {
if ([scene isKindOfClass:[UIWindowScene class]]) {
windowScene = (UIWindowScene*)scene;
// Log(@"π¨ Found existing window scene for error modal");
break;
}
}
if (windowScene) {
errorWindow = [[UIWindow alloc] initWithWindowScene:windowScene];
// Log(@"π¨ Created error window with existing scene");
} else {
// Fallback: create window with screen bounds (older behavior)
// On visionOS, UIScreen is unavailable. Guard frame-based creation.
#if !TARGET_OS_VISION
errorWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
#endif
// Log(@"π¨ Created error window with screen bounds (no scene available)");
}
} else {
// iOS 12 and below
// On visionOS, UIScreen is unavailable; this branch is only for iOS 12 and below.
#if !TARGET_OS_VISION
errorWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
#endif
// Log(@"π¨ Created error window for iOS 12");
}
errorWindow.windowLevel = UIWindowLevelAlert + 1000; // Above everything
errorWindow.backgroundColor = [UIColor colorWithRed:0.15
green:0.15
blue:0.15
alpha:1.0]; // Match the dark gray theme
// Ensure window is visible regardless of app state
errorWindow.hidden = NO;
errorWindow.alpha = 1.0;
// Create the error view controller
UIViewController* errorViewController = [[UIViewController alloc] init];
errorViewController.view.backgroundColor = [UIColor colorWithRed:0.15
green:0.15
blue:0.15
alpha:1.0]; // Dark gray tech theme
// Content container
UIView* contentView = [[UIView alloc] init];
contentView.translatesAutoresizingMaskIntoConstraints = NO;
[errorViewController.view addSubview:contentView];
// NativeScript Logo (will be loaded asynchronously)
UIImageView* logoImageView = [[UIImageView alloc] init];
logoImageView.contentMode = UIViewContentModeScaleAspectFit;
logoImageView.translatesAutoresizingMaskIntoConstraints = NO;
logoImageView.backgroundColor = [UIColor clearColor];
[contentView addSubview:logoImageView];
// Load NativeScript logo asynchronously
NSString* logoURL = @"https://github.com/NativeScript/artwork/raw/refs/heads/main/logo/export/"
@"NativeScript_Logo_Wide_Transparent_White_Rounded_White.png";
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:logoURL]];
NSURLSessionDataTask* logoTask = [[NSURLSession sharedSession]
dataTaskWithRequest:request
completionHandler:^(NSData* data, NSURLResponse* response, NSError* error) {
if (data && !error) {
UIImage* logoImage = [UIImage imageWithData:data];
if (logoImage) {
dispatch_async(dispatch_get_main_queue(), ^{
logoImageView.image = logoImage;
// Log(@"π¨ NativeScript logo loaded successfully");
});
} else {
// Log(@"π¨ Failed to create image from logo data");
}
} else {
// Log(@"π¨ Failed to load NativeScript logo: %@", error.localizedDescription);
// Fallback: show text logo
dispatch_async(dispatch_get_main_queue(), ^{
UILabel* fallbackLogo = [[UILabel alloc] init];
fallbackLogo.text = @"NativeScript";
fallbackLogo.textColor = [UIColor whiteColor];
fallbackLogo.font = [UIFont boldSystemFontOfSize:28];
fallbackLogo.textAlignment = NSTextAlignmentCenter;
fallbackLogo.translatesAutoresizingMaskIntoConstraints = NO;