-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.go
More file actions
817 lines (700 loc) · 19.3 KB
/
console.go
File metadata and controls
817 lines (700 loc) · 19.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
// SPDX-License-Identifier: EUPL-1.2
package webview
import (
"context"
"iter"
"slices"
"sync" // Note: AX-6 — internal concurrency primitive; structural per RFC §3/§6
"sync/atomic" // Note: AX-6 — internal concurrency primitive; structural per RFC §3/§6
"time"
core "dappco.re/go/core"
coreerr "dappco.re/go/log"
)
// ConsoleWatcher provides advanced console message watching capabilities.
type ConsoleWatcher struct {
mu sync.RWMutex
wv *Webview
messages []ConsoleMessage
filters []ConsoleFilter
limit int
handlers []consoleHandlerRegistration
waiters []consoleMessageWaiter
nextHandlerID atomic.Int64
}
// ConsoleFilter filters console messages.
type ConsoleFilter struct {
Type string // Exact message type match, empty for all
Pattern string // Filter by text pattern (substring match)
}
// ConsoleHandler is called when a matching console message is received.
type ConsoleHandler func(msg ConsoleMessage)
type consoleHandlerRegistration struct {
id int64
handler ConsoleHandler
}
type consoleMessageWaiter struct {
filter ConsoleFilter
ch chan ConsoleMessage
}
// Watch console messages from a Webview while a flow is running.
//
// watcher := webview.NewConsoleWatcher(wv)
// watcher.AddFilter(webview.ConsoleFilter{Type: "error"})
func NewConsoleWatcher(wv *Webview) *ConsoleWatcher {
watcher := &ConsoleWatcher{
wv: wv,
messages: make([]ConsoleMessage, 0, 1000),
filters: make([]ConsoleFilter, 0),
limit: 1000,
handlers: make([]consoleHandlerRegistration, 0),
}
if wv == nil || wv.client == nil {
return watcher
}
// Subscribe to console events from the webview's client
wv.client.OnEvent("Runtime.consoleAPICalled", func(params map[string]any) {
watcher.handleConsoleEvent(params)
})
return watcher
}
// normalizeConsoleType converts CDP event types to the package's stored value.
//
// It accepts legacy warning aliases and stores the compact warn form used by
// the existing console message contract.
func normalizeConsoleType(raw string) string {
normalized := core.Lower(core.Trim(core.Sprint(raw)))
if normalized == "warn" || normalized == "warning" {
return "warn"
}
return normalized
}
// canonicalConsoleType returns the RFC-canonical console type name.
func canonicalConsoleType(raw string) string {
normalized := core.Lower(core.Trim(core.Sprint(raw)))
if normalized == "warn" || normalized == "warning" {
return "warning"
}
return normalized
}
// consoleTextFromArgs extracts message text from Runtime.consoleAPICalled args.
func consoleTextFromArgs(args []any) string {
text := core.NewBuilder()
for i, arg := range args {
if i > 0 {
text.WriteString(" ")
}
text.WriteString(consoleArgText(arg))
}
return text.String()
}
func consoleArgText(arg any) string {
remoteObj, ok := arg.(map[string]any)
if !ok {
return consoleValueToString(arg)
}
if value, ok := remoteObj["value"]; ok {
return consoleValueToString(value)
}
if desc, ok := remoteObj["description"].(string); ok && desc != "" {
return desc
}
if preview, ok := remoteObj["preview"].(map[string]any); ok {
if description, ok := preview["description"].(string); ok && description != "" {
return description
}
}
if preview, ok := remoteObj["preview"].(map[string]any); ok {
if value, ok := preview["value"].(string); ok && value != "" {
return value
}
}
if r := core.JSONMarshal(remoteObj); r.OK {
if encoded, ok := r.Value.([]byte); ok {
return string(encoded)
}
}
return ""
}
func consoleValueToString(value any) string {
if value == nil {
return "null"
}
if valueStr, ok := value.(string); ok {
return valueStr
}
if r := core.JSONMarshal(value); r.OK {
if encoded, ok := r.Value.([]byte); ok {
return string(encoded)
}
}
return core.Sprint(value)
}
func consoleCaptureTimestamp() time.Time {
return time.Now()
}
func trimConsoleMessages(messages []ConsoleMessage, limit int) []ConsoleMessage {
if limit < 0 {
limit = 0
}
if overflow := len(messages) - limit; overflow > 0 {
copy(messages, messages[overflow:])
messages = messages[:len(messages)-overflow]
}
return messages
}
func runtimeExceptionText(exceptionDetails map[string]any) string {
if exception, ok := exceptionDetails["exception"].(map[string]any); ok {
if description, ok := exception["description"].(string); ok && description != "" {
return description
}
}
if text, ok := exceptionDetails["text"].(string); ok && text != "" {
return text
}
return "JavaScript error"
}
func runtimeExceptionError(scope string, exceptionDetails map[string]any) error {
return coreerr.E(scope, runtimeExceptionText(exceptionDetails), nil)
}
// AddFilter adds a filter to the watcher.
func (cw *ConsoleWatcher) AddFilter(filter ConsoleFilter) {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.filters = append(cw.filters, filter)
}
// ClearFilters removes all filters.
func (cw *ConsoleWatcher) ClearFilters() {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.filters = cw.filters[:0]
}
// AddHandler adds a handler for console messages.
func (cw *ConsoleWatcher) AddHandler(handler ConsoleHandler) {
cw.addHandler(handler)
}
func (cw *ConsoleWatcher) addHandler(handler ConsoleHandler) int64 {
cw.mu.Lock()
defer cw.mu.Unlock()
id := cw.nextHandlerID.Add(1)
cw.handlers = append(cw.handlers, consoleHandlerRegistration{
id: id,
handler: handler,
})
return id
}
func (cw *ConsoleWatcher) removeHandler(id int64) {
cw.mu.Lock()
defer cw.mu.Unlock()
for i, registration := range cw.handlers {
if registration.id == id {
cw.handlers = slices.Delete(cw.handlers, i, i+1)
return
}
}
}
func (cw *ConsoleWatcher) removeWaiter(ch chan ConsoleMessage) {
cw.mu.Lock()
defer cw.mu.Unlock()
for i, waiter := range cw.waiters {
if waiter.ch == ch {
cw.waiters = slices.Delete(cw.waiters, i, i+1)
return
}
}
}
// SetLimit replaces the retention limit for future appends.
func (cw *ConsoleWatcher) SetLimit(limit int) {
cw.mu.Lock()
defer cw.mu.Unlock()
if limit < 0 {
limit = 0
}
cw.limit = limit
}
// Messages returns all captured messages.
func (cw *ConsoleWatcher) Messages() []ConsoleMessage {
return slices.Collect(cw.MessagesAll())
}
// MessagesAll returns an iterator over all captured messages.
func (cw *ConsoleWatcher) MessagesAll() iter.Seq[ConsoleMessage] {
return func(yield func(ConsoleMessage) bool) {
cw.mu.RLock()
defer cw.mu.RUnlock()
for _, msg := range cw.messages {
if !yield(msg) {
return
}
}
}
}
// FilteredMessages returns messages matching the current filters.
func (cw *ConsoleWatcher) FilteredMessages() []ConsoleMessage {
return slices.Collect(cw.FilteredMessagesAll())
}
// FilteredMessagesAll returns an iterator over messages matching the current filters.
func (cw *ConsoleWatcher) FilteredMessagesAll() iter.Seq[ConsoleMessage] {
return func(yield func(ConsoleMessage) bool) {
cw.mu.RLock()
defer cw.mu.RUnlock()
for _, msg := range cw.messages {
if cw.matchesFilter(msg) {
if !yield(msg) {
return
}
}
}
}
}
// Errors returns all error messages.
func (cw *ConsoleWatcher) Errors() []ConsoleMessage {
return slices.Collect(cw.ErrorsAll())
}
// ErrorsAll returns an iterator over all error messages.
func (cw *ConsoleWatcher) ErrorsAll() iter.Seq[ConsoleMessage] {
return func(yield func(ConsoleMessage) bool) {
cw.mu.RLock()
defer cw.mu.RUnlock()
for _, msg := range cw.messages {
if canonicalConsoleType(msg.Type) == "error" {
if !yield(msg) {
return
}
}
}
}
}
// Warnings returns all warning messages.
func (cw *ConsoleWatcher) Warnings() []ConsoleMessage {
return slices.Collect(cw.WarningsAll())
}
// WarningsAll returns an iterator over all warning messages.
func (cw *ConsoleWatcher) WarningsAll() iter.Seq[ConsoleMessage] {
return func(yield func(ConsoleMessage) bool) {
cw.mu.RLock()
defer cw.mu.RUnlock()
for _, msg := range cw.messages {
if canonicalConsoleType(msg.Type) == "warning" {
if !yield(msg) {
return
}
}
}
}
}
// Clear clears all captured messages.
func (cw *ConsoleWatcher) Clear() {
cw.mu.Lock()
defer cw.mu.Unlock()
cw.messages = cw.messages[:0]
}
// WaitForMessage waits for a message matching the filter.
func (cw *ConsoleWatcher) WaitForMessage(ctx context.Context, filter ConsoleFilter) (*ConsoleMessage, error) {
cw.mu.RLock()
for _, msg := range cw.messages {
if cw.matchesSingleFilter(msg, filter) {
cw.mu.RUnlock()
return &msg, nil
}
}
cw.mu.RUnlock()
messageCh := make(chan ConsoleMessage, 1)
cw.mu.Lock()
for _, msg := range cw.messages {
if cw.matchesSingleFilter(msg, filter) {
cw.mu.Unlock()
return &msg, nil
}
}
cw.waiters = append(cw.waiters, consoleMessageWaiter{
filter: filter,
ch: messageCh,
})
cw.mu.Unlock()
defer cw.removeWaiter(messageCh)
select {
case <-ctx.Done():
return nil, ctx.Err()
case msg := <-messageCh:
return &msg, nil
}
}
// WaitForError waits for an error message.
func (cw *ConsoleWatcher) WaitForError(ctx context.Context) (*ConsoleMessage, error) {
return cw.WaitForMessage(ctx, ConsoleFilter{Type: "error"})
}
// HasErrors returns true if there are any error messages.
func (cw *ConsoleWatcher) HasErrors() bool {
cw.mu.RLock()
defer cw.mu.RUnlock()
for _, msg := range cw.messages {
if canonicalConsoleType(msg.Type) == "error" {
return true
}
}
return false
}
// Count returns the number of captured messages.
func (cw *ConsoleWatcher) Count() int {
cw.mu.RLock()
defer cw.mu.RUnlock()
return len(cw.messages)
}
// ErrorCount returns the number of error messages.
func (cw *ConsoleWatcher) ErrorCount() int {
cw.mu.RLock()
defer cw.mu.RUnlock()
count := 0
for _, msg := range cw.messages {
if canonicalConsoleType(msg.Type) == "error" {
count++
}
}
return count
}
// handleConsoleEvent processes incoming console events.
func (cw *ConsoleWatcher) handleConsoleEvent(params map[string]any) {
msgType := canonicalConsoleType(core.Sprint(params["type"]))
// Extract args
args, _ := params["args"].([]any)
text := consoleTextFromArgs(args)
// Extract stack trace info
stackTrace, _ := params["stackTrace"].(map[string]any)
var url string
var line, column int
if callFrames, ok := stackTrace["callFrames"].([]any); ok && len(callFrames) > 0 {
if frame, ok := callFrames[0].(map[string]any); ok {
url, _ = frame["url"].(string)
lineFloat, _ := frame["lineNumber"].(float64)
colFloat, _ := frame["columnNumber"].(float64)
line = int(lineFloat)
column = int(colFloat)
}
}
msg := ConsoleMessage{
Type: msgType,
Text: text,
Timestamp: consoleCaptureTimestamp(),
URL: url,
Line: line,
Column: column,
}
cw.addMessage(msg)
}
// addMessage adds a message to the store and notifies handlers.
func (cw *ConsoleWatcher) addMessage(msg ConsoleMessage) {
cw.mu.Lock()
cw.messages = append(cw.messages, msg)
cw.messages = trimConsoleMessages(cw.messages, cw.limit)
// Copy handlers to call outside lock
handlers := slices.Clone(cw.handlers)
waiters := slices.Clone(cw.waiters)
cw.mu.Unlock()
for _, waiter := range waiters {
if cw.matchesSingleFilter(msg, waiter.filter) {
select {
case waiter.ch <- msg:
default:
}
}
}
// Call handlers
for _, registration := range handlers {
registration.handler(msg)
}
}
// matchesFilter checks whether a message matches the active filter set.
//
// When no filters are configured, every message matches. When filters exist,
// the watcher uses OR semantics: a message is included as soon as it matches
// one configured filter.
func (cw *ConsoleWatcher) matchesFilter(msg ConsoleMessage) bool {
if len(cw.filters) == 0 {
return true
}
for _, filter := range cw.filters {
if cw.matchesSingleFilter(msg, filter) {
return true
}
}
return false
}
// matchesSingleFilter checks if a message matches a specific filter.
func (cw *ConsoleWatcher) matchesSingleFilter(msg ConsoleMessage, filter ConsoleFilter) bool {
if filter.Type != "" {
filterType := canonicalConsoleType(filter.Type)
messageType := canonicalConsoleType(msg.Type)
if messageType != filterType {
return false
}
}
if filter.Pattern != "" {
// Simple substring match
if !containsString(msg.Text, filter.Pattern) {
return false
}
}
return true
}
func isWarningType(messageType string) bool {
return canonicalConsoleType(messageType) == "warning"
}
// containsString checks if s contains substr (case-sensitive).
func containsString(s, substr string) bool {
return len(substr) == 0 || (len(s) >= len(substr) && findString(s, substr) >= 0)
}
// findString finds substr in s, returns -1 if not found.
func findString(s, substr string) int {
for i := range len(s) - len(substr) + 1 {
if s[i:i+len(substr)] == substr {
return i
}
}
return -1
}
// ExceptionInfo represents information about a JavaScript exception.
type ExceptionInfo struct {
Text string `json:"text"`
LineNumber int `json:"lineNumber"`
ColumnNumber int `json:"columnNumber"`
URL string `json:"url"`
StackTrace string `json:"stackTrace"`
Timestamp time.Time `json:"timestamp"`
}
// ExceptionWatcher watches for JavaScript exceptions.
type ExceptionWatcher struct {
mu sync.RWMutex
wv *Webview
exceptions []ExceptionInfo
limit int
handlers []exceptionHandlerRegistration
waiters []exceptionWaiter
nextHandlerID atomic.Int64
}
type exceptionHandlerRegistration struct {
id int64
handler func(ExceptionInfo)
}
type exceptionWaiter struct {
ch chan ExceptionInfo
}
// Capture Runtime.exceptionThrown events from the active page.
//
// watcher := webview.NewExceptionWatcher(wv)
// exc, err := watcher.WaitForException(ctx)
func NewExceptionWatcher(wv *Webview) *ExceptionWatcher {
ew := &ExceptionWatcher{
wv: wv,
exceptions: make([]ExceptionInfo, 0),
limit: 1000,
handlers: make([]exceptionHandlerRegistration, 0),
}
if wv == nil || wv.client == nil {
return ew
}
// Subscribe to exception events
wv.client.OnEvent("Runtime.exceptionThrown", func(params map[string]any) {
ew.handleException(params)
})
return ew
}
// Exceptions returns all captured exceptions.
func (ew *ExceptionWatcher) Exceptions() []ExceptionInfo {
return slices.Collect(ew.ExceptionsAll())
}
// ExceptionsAll returns an iterator over all captured exceptions.
func (ew *ExceptionWatcher) ExceptionsAll() iter.Seq[ExceptionInfo] {
return func(yield func(ExceptionInfo) bool) {
ew.mu.RLock()
defer ew.mu.RUnlock()
for _, exc := range ew.exceptions {
if !yield(exc) {
return
}
}
}
}
// Clear clears all captured exceptions.
func (ew *ExceptionWatcher) Clear() {
ew.mu.Lock()
defer ew.mu.Unlock()
ew.exceptions = ew.exceptions[:0]
}
// HasExceptions returns true if there are any exceptions.
func (ew *ExceptionWatcher) HasExceptions() bool {
ew.mu.RLock()
defer ew.mu.RUnlock()
return len(ew.exceptions) > 0
}
// Count returns the number of exceptions.
func (ew *ExceptionWatcher) Count() int {
ew.mu.RLock()
defer ew.mu.RUnlock()
return len(ew.exceptions)
}
// AddHandler adds a handler for exceptions.
func (ew *ExceptionWatcher) AddHandler(handler func(ExceptionInfo)) {
ew.addHandler(handler)
}
func (ew *ExceptionWatcher) addHandler(handler func(ExceptionInfo)) int64 {
ew.mu.Lock()
defer ew.mu.Unlock()
id := ew.nextHandlerID.Add(1)
ew.handlers = append(ew.handlers, exceptionHandlerRegistration{
id: id,
handler: handler,
})
return id
}
func (ew *ExceptionWatcher) removeHandler(id int64) {
ew.mu.Lock()
defer ew.mu.Unlock()
for i, registration := range ew.handlers {
if registration.id == id {
ew.handlers = slices.Delete(ew.handlers, i, i+1)
return
}
}
}
func (ew *ExceptionWatcher) removeWaiter(ch chan ExceptionInfo) {
ew.mu.Lock()
defer ew.mu.Unlock()
for i, waiter := range ew.waiters {
if waiter.ch == ch {
ew.waiters = slices.Delete(ew.waiters, i, i+1)
return
}
}
}
// WaitForException waits for an exception to be thrown.
func (ew *ExceptionWatcher) WaitForException(ctx context.Context) (*ExceptionInfo, error) {
ew.mu.RLock()
if len(ew.exceptions) > 0 {
exc := ew.exceptions[len(ew.exceptions)-1]
ew.mu.RUnlock()
return &exc, nil
}
ew.mu.RUnlock()
excCh := make(chan ExceptionInfo, 1)
ew.mu.Lock()
if len(ew.exceptions) > 0 {
exc := ew.exceptions[len(ew.exceptions)-1]
ew.mu.Unlock()
return &exc, nil
}
ew.waiters = append(ew.waiters, exceptionWaiter{ch: excCh})
ew.mu.Unlock()
defer ew.removeWaiter(excCh)
select {
case <-ctx.Done():
return nil, ctx.Err()
case exc := <-excCh:
return &exc, nil
}
}
// handleException processes exception events.
func (ew *ExceptionWatcher) handleException(params map[string]any) {
exceptionDetails, ok := params["exceptionDetails"].(map[string]any)
if !ok {
return
}
text, _ := exceptionDetails["text"].(string)
lineNum, _ := exceptionDetails["lineNumber"].(float64)
colNum, _ := exceptionDetails["columnNumber"].(float64)
url, _ := exceptionDetails["url"].(string)
// Extract stack trace
stackTrace := core.NewBuilder()
if st, ok := exceptionDetails["stackTrace"].(map[string]any); ok {
if frames, ok := st["callFrames"].([]any); ok {
for _, f := range frames {
if frame, ok := f.(map[string]any); ok {
funcName, _ := frame["functionName"].(string)
frameURL, _ := frame["url"].(string)
frameLine, _ := frame["lineNumber"].(float64)
frameCol, _ := frame["columnNumber"].(float64)
stackTrace.WriteString(core.Sprintf(" at %s (%s:%d:%d)\n", funcName, frameURL, int(frameLine), int(frameCol)))
}
}
}
}
// Try to get exception value description
text = runtimeExceptionText(exceptionDetails)
info := ExceptionInfo{
Text: text,
LineNumber: int(lineNum),
ColumnNumber: int(colNum),
URL: url,
StackTrace: stackTrace.String(),
Timestamp: time.Now(),
}
ew.mu.Lock()
ew.exceptions = append(ew.exceptions, info)
ew.exceptions = trimExceptionInfos(ew.exceptions, ew.limit)
handlers := slices.Clone(ew.handlers)
waiters := slices.Clone(ew.waiters)
ew.mu.Unlock()
for _, waiter := range waiters {
select {
case waiter.ch <- info:
default:
}
}
// Call handlers
for _, registration := range handlers {
registration.handler(info)
}
}
// FormatConsoleOutput formats console messages for display.
func FormatConsoleOutput(messages []ConsoleMessage) string {
output := core.NewBuilder()
for _, msg := range messages {
prefix := ""
switch canonicalConsoleType(msg.Type) {
case "error":
prefix = "[ERROR]"
case "warning":
prefix = "[WARN]"
case "info":
prefix = "[INFO]"
case "debug":
prefix = "[DEBUG]"
default:
prefix = "[LOG]"
}
timestamp := msg.Timestamp.Format("15:04:05.000")
output.WriteString(core.Sprintf("%s %s %s\n", timestamp, prefix, sanitizeConsoleText(msg.Text)))
}
return output.String()
}
func trimExceptionInfos(exceptions []ExceptionInfo, limit int) []ExceptionInfo {
if limit < 0 {
limit = 0
}
if overflow := len(exceptions) - limit; overflow > 0 {
copy(exceptions, exceptions[overflow:])
exceptions = exceptions[:len(exceptions)-overflow]
}
return exceptions
}
func sanitizeConsoleText(text string) string {
b := core.NewBuilder()
b.Grow(len(text))
for _, r := range text {
switch r {
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
case '\x1b':
b.WriteString(`\x1b`)
default:
if r < 0x20 || r == 0x7f {
b.WriteByte(' ')
continue
}
b.WriteRune(r)
}
}
return b.String()
}