-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.go
More file actions
544 lines (473 loc) · 13 KB
/
console.go
File metadata and controls
544 lines (473 loc) · 13 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
package webview
import (
"context"
"fmt"
"iter"
"slices"
"strings"
"sync"
"time"
)
// ConsoleWatcher provides advanced console message watching capabilities.
type ConsoleWatcher struct {
mu sync.RWMutex
wv *Webview
messages []ConsoleMessage
filters []ConsoleFilter
limit int
handlers []ConsoleHandler
}
// ConsoleFilter filters console messages.
type ConsoleFilter struct {
Type string // Filter by type (log, warn, error, info, debug), 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)
// NewConsoleWatcher creates a new console watcher for the webview.
func NewConsoleWatcher(wv *Webview) *ConsoleWatcher {
cw := &ConsoleWatcher{
wv: wv,
messages: make([]ConsoleMessage, 0, 100),
filters: make([]ConsoleFilter, 0),
limit: 1000,
handlers: make([]ConsoleHandler, 0),
}
// Subscribe to console events from the webview's client
wv.client.OnEvent("Runtime.consoleAPICalled", func(params map[string]any) {
cw.handleConsoleEvent(params)
})
return cw
}
// 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.mu.Lock()
defer cw.mu.Unlock()
cw.handlers = append(cw.handlers, handler)
}
// SetLimit sets the maximum number of messages to retain.
func (cw *ConsoleWatcher) SetLimit(limit int) {
cw.mu.Lock()
defer cw.mu.Unlock()
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 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 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) {
// First check existing messages
cw.mu.RLock()
for _, msg := range cw.messages {
if cw.matchesSingleFilter(msg, filter) {
cw.mu.RUnlock()
return &msg, nil
}
}
cw.mu.RUnlock()
// Set up a channel for new messages
msgCh := make(chan ConsoleMessage, 1)
handler := func(msg ConsoleMessage) {
if cw.matchesSingleFilter(msg, filter) {
select {
case msgCh <- msg:
default:
}
}
}
cw.AddHandler(handler)
defer func() {
cw.mu.Lock()
// Remove handler (simple implementation - in production you'd want a handle-based removal)
cw.handlers = cw.handlers[:len(cw.handlers)-1]
cw.mu.Unlock()
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case msg := <-msgCh:
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 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 msg.Type == "error" {
count++
}
}
return count
}
// handleConsoleEvent processes incoming console events.
func (cw *ConsoleWatcher) handleConsoleEvent(params map[string]any) {
msgType, _ := params["type"].(string)
// Extract args
args, _ := params["args"].([]any)
var text strings.Builder
for i, arg := range args {
if argMap, ok := arg.(map[string]any); ok {
if val, ok := argMap["value"]; ok {
if i > 0 {
text.WriteString(" ")
}
text.WriteString(fmt.Sprint(val))
}
}
}
// 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.String(),
Timestamp: time.Now(),
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()
// Enforce limit
if len(cw.messages) >= cw.limit {
drop := min(100, len(cw.messages))
cw.messages = cw.messages[drop:]
}
cw.messages = append(cw.messages, msg)
// Copy handlers to call outside lock
handlers := slices.Clone(cw.handlers)
cw.mu.Unlock()
// Call handlers
for _, handler := range handlers {
handler(msg)
}
}
// matchesFilter checks if a message matches any 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 != "" && msg.Type != filter.Type {
return false
}
if filter.Pattern != "" {
// Simple substring match
if !containsString(msg.Text, filter.Pattern) {
return false
}
}
return true
}
// 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
handlers []func(ExceptionInfo)
}
// NewExceptionWatcher creates a new exception watcher.
func NewExceptionWatcher(wv *Webview) *ExceptionWatcher {
ew := &ExceptionWatcher{
wv: wv,
exceptions: make([]ExceptionInfo, 0),
handlers: make([]func(ExceptionInfo), 0),
}
// 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.mu.Lock()
defer ew.mu.Unlock()
ew.handlers = append(ew.handlers, handler)
}
// WaitForException waits for an exception to be thrown.
func (ew *ExceptionWatcher) WaitForException(ctx context.Context) (*ExceptionInfo, error) {
// Check existing exceptions first
ew.mu.RLock()
if len(ew.exceptions) > 0 {
exc := ew.exceptions[len(ew.exceptions)-1]
ew.mu.RUnlock()
return &exc, nil
}
ew.mu.RUnlock()
// Set up a channel for new exceptions
excCh := make(chan ExceptionInfo, 1)
handler := func(exc ExceptionInfo) {
select {
case excCh <- exc:
default:
}
}
ew.AddHandler(handler)
defer func() {
ew.mu.Lock()
ew.handlers = ew.handlers[:len(ew.handlers)-1]
ew.mu.Unlock()
}()
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
var stackTrace strings.Builder
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(fmt.Sprintf(" at %s (%s:%d:%d)\n", funcName, frameURL, int(frameLine), int(frameCol)))
}
}
}
}
// Try to get exception value description
if exc, ok := exceptionDetails["exception"].(map[string]any); ok {
if desc, ok := exc["description"].(string); ok && desc != "" {
text = desc
}
}
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)
handlers := slices.Clone(ew.handlers)
ew.mu.Unlock()
// Call handlers
for _, handler := range handlers {
handler(info)
}
}
// FormatConsoleOutput formats console messages for display.
func FormatConsoleOutput(messages []ConsoleMessage) string {
var output strings.Builder
for _, msg := range messages {
prefix := ""
switch 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(fmt.Sprintf("%s %s %s\n", timestamp, prefix, msg.Text))
}
return output.String()
}