-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathjs.go
More file actions
519 lines (442 loc) · 12.9 KB
/
js.go
File metadata and controls
519 lines (442 loc) · 12.9 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
package workflow
import (
_ "embed"
"fmt"
"strings"
)
//go:embed js/create_pull_request.cjs
var createPullRequestScript string
//go:embed js/create_issue.cjs
var createIssueScript string
//go:embed js/create_agent_task.cjs
var createAgentTaskScript string
//go:embed js/create_discussion.cjs
var createDiscussionScript string
//go:embed js/add_comment.cjs
var createCommentScript string
//go:embed js/create_pr_review_comment.cjs
var createPRReviewCommentScript string
//go:embed js/create_code_scanning_alert.cjs
var createCodeScanningAlertScript string
//go:embed js/compute_text.cjs
var computeTextScript string
//go:embed js/collect_ndjson_output.cjs
var collectJSONLOutputScript string
//go:embed js/add_labels.cjs
var addLabelsScript string
//go:embed js/update_issue.cjs
var updateIssueScript string
//go:embed js/push_to_pull_request_branch.cjs
var pushToBranchScript string
//go:embed js/upload_assets.cjs
var uploadAssetsScript string
//go:embed js/add_reaction_and_edit_comment.cjs
var addReactionAndEditCommentScript string
//go:embed js/check_membership.cjs
var checkMembershipScript string
//go:embed js/check_stop_time.cjs
var checkStopTimeScript string
//go:embed js/check_command_position.cjs
var checkCommandPositionScript string
//go:embed js/parse_claude_log.cjs
var parseClaudeLogScript string
//go:embed js/parse_codex_log.cjs
var parseCodexLogScript string
//go:embed js/parse_copilot_log.cjs
var parseCopilotLogScript string
//go:embed js/validate_errors.cjs
var validateErrorsScript string
//go:embed js/missing_tool.cjs
var missingToolScript string
//go:embed js/safe_outputs_mcp_server.cjs
var safeOutputsMCPServerScript string
//go:embed js/render_template.cjs
var renderTemplateScript string
//go:embed js/checkout_pr_branch.cjs
var checkoutPRBranchScript string
//go:embed js/redact_secrets.cjs
var redactSecretsScript string
//go:embed js/notify_comment_error.cjs
var notifyCommentErrorScript string
//go:embed js/setup_oidc_token.cjs
var setupOIDCTokenScript string
//go:embed js/revoke_oidc_token.cjs
var revokeOIDCTokenScript string
// removeJavaScriptComments removes JavaScript comments (// and /* */) from code
// while preserving comments that appear within string literals
func removeJavaScriptComments(code string) string {
var result strings.Builder
lines := strings.Split(code, "\n")
inBlockComment := false
for _, line := range lines {
processedLine := removeJavaScriptCommentsFromLine(line, &inBlockComment)
result.WriteString(processedLine)
result.WriteString("\n")
}
// Remove the trailing newline we added
resultStr := result.String()
if len(resultStr) > 0 && resultStr[len(resultStr)-1] == '\n' {
resultStr = resultStr[:len(resultStr)-1]
}
return resultStr
}
// removeJavaScriptCommentsFromLine removes JavaScript comments from a single line
// while preserving comments that appear within string literals and regex literals
func removeJavaScriptCommentsFromLine(line string, inBlockComment *bool) string {
var result strings.Builder
runes := []rune(line)
i := 0
for i < len(runes) {
if *inBlockComment {
// Look for end of block comment
if i < len(runes)-1 && runes[i] == '*' && runes[i+1] == '/' {
*inBlockComment = false
i += 2 // Skip '*/'
} else {
i++
}
continue
}
// Check for start of comments
if i < len(runes)-1 {
// Block comment start
if runes[i] == '/' && runes[i+1] == '*' {
*inBlockComment = true
i += 2 // Skip '/*'
continue
}
// Line comment start
if runes[i] == '/' && runes[i+1] == '/' {
// Check if we're inside a string literal or regex literal
beforeSlash := string(runes[:i])
if !isInsideStringLiteral(beforeSlash) && !isInsideRegexLiteral(beforeSlash) {
// Rest of line is a comment, stop processing
break
}
}
}
// Check for regex literals
if runes[i] == '/' {
beforeSlash := string(runes[:i])
if !isInsideStringLiteral(beforeSlash) && !isInsideRegexLiteral(beforeSlash) && canStartRegexLiteral(beforeSlash) {
// This is likely a regex literal
result.WriteRune(runes[i]) // Write the opening /
i++
// Process inside regex literal
for i < len(runes) {
if runes[i] == '/' {
// Check if it's escaped
escapeCount := 0
j := i - 1
for j >= 0 && runes[j] == '\\' {
escapeCount++
j--
}
if escapeCount%2 == 0 {
// Not escaped, end of regex
result.WriteRune(runes[i]) // Write the closing /
i++
// Skip regex flags (g, i, m, etc.)
for i < len(runes) && (runes[i] >= 'a' && runes[i] <= 'z' || runes[i] >= 'A' && runes[i] <= 'Z') {
result.WriteRune(runes[i])
i++
}
break
}
}
result.WriteRune(runes[i])
i++
}
continue
}
}
// Check for string literals
if runes[i] == '"' || runes[i] == '\'' || runes[i] == '`' {
quote := runes[i]
result.WriteRune(runes[i])
i++
// Process inside string literal
for i < len(runes) {
result.WriteRune(runes[i])
if runes[i] == quote {
// Check if it's escaped
escapeCount := 0
j := i - 1
for j >= 0 && runes[j] == '\\' {
escapeCount++
j--
}
if escapeCount%2 == 0 {
// Not escaped, end of string
i++
break
}
}
i++
}
continue
}
result.WriteRune(runes[i])
i++
}
return result.String()
}
// isInsideStringLiteral checks if we're currently inside a string literal
// by counting unescaped quotes before the current position
func isInsideStringLiteral(text string) bool {
runes := []rune(text)
inSingleQuote := false
inDoubleQuote := false
inBacktick := false
for i := 0; i < len(runes); i++ {
switch runes[i] {
case '\'':
if !inDoubleQuote && !inBacktick {
// Check if escaped
escapeCount := 0
j := i - 1
for j >= 0 && runes[j] == '\\' {
escapeCount++
j--
}
if escapeCount%2 == 0 {
inSingleQuote = !inSingleQuote
}
}
case '"':
if !inSingleQuote && !inBacktick {
// Check if escaped
escapeCount := 0
j := i - 1
for j >= 0 && runes[j] == '\\' {
escapeCount++
j--
}
if escapeCount%2 == 0 {
inDoubleQuote = !inDoubleQuote
}
}
case '`':
if !inSingleQuote && !inDoubleQuote {
inBacktick = !inBacktick
}
}
}
return inSingleQuote || inDoubleQuote || inBacktick
}
// isInsideRegexLiteral checks if we're currently inside a regex literal
// by tracking unescaped forward slashes
func isInsideRegexLiteral(text string) bool {
runes := []rune(text)
inSingleQuote := false
inDoubleQuote := false
inBacktick := false
inRegex := false
for i := 0; i < len(runes); i++ {
switch runes[i] {
case '\'':
if !inDoubleQuote && !inBacktick && !inRegex {
// Check if escaped
escapeCount := 0
j := i - 1
for j >= 0 && runes[j] == '\\' {
escapeCount++
j--
}
if escapeCount%2 == 0 {
inSingleQuote = !inSingleQuote
}
}
case '"':
if !inSingleQuote && !inBacktick && !inRegex {
// Check if escaped
escapeCount := 0
j := i - 1
for j >= 0 && runes[j] == '\\' {
escapeCount++
j--
}
if escapeCount%2 == 0 {
inDoubleQuote = !inDoubleQuote
}
}
case '`':
if !inSingleQuote && !inDoubleQuote && !inRegex {
inBacktick = !inBacktick
}
case '/':
if !inSingleQuote && !inDoubleQuote && !inBacktick {
// Check if escaped
escapeCount := 0
j := i - 1
for j >= 0 && runes[j] == '\\' {
escapeCount++
j--
}
if escapeCount%2 == 0 {
if inRegex {
// End of regex
inRegex = false
} else if canStartRegexLiteralAt(text, i) {
// Start of regex
inRegex = true
}
}
}
}
}
return inRegex
}
// canStartRegexLiteral checks if a regex literal can start at the current position
// based on what comes before
func canStartRegexLiteral(beforeText string) bool {
return canStartRegexLiteralAt(beforeText, len([]rune(beforeText)))
}
// canStartRegexLiteralAt checks if a regex literal can start at the given position
func canStartRegexLiteralAt(text string, pos int) bool {
if pos == 0 {
return true // Beginning of line
}
runes := []rune(text)
if pos > len(runes) {
return false
}
// Skip backward over whitespace
i := pos - 1
for i >= 0 && (runes[i] == ' ' || runes[i] == '\t') {
i--
}
if i < 0 {
return true // Only whitespace before
}
lastChar := runes[i]
// Regex can start after these characters/operators
switch lastChar {
case '=', '(', '[', ',', ':', ';', '!', '&', '|', '?', '+', '-', '*', '/', '%', '{', '}', '~', '^':
return true
case ')':
// Check if it's after keywords like "return", "throw"
word := extractWordBefore(runes, i)
return word == "return" || word == "throw" || word == "typeof" || word == "new" || word == "in" || word == "of"
default:
// Check if it's after certain keywords
word := extractWordBefore(runes, i+1)
return word == "return" || word == "throw" || word == "typeof" || word == "new" || word == "in" || word == "of" ||
word == "if" || word == "while" || word == "for" || word == "case"
}
}
// extractWordBefore extracts the word that ends at the given position
func extractWordBefore(runes []rune, endPos int) string {
if endPos < 0 || endPos >= len(runes) {
return ""
}
// Find the start of the word
start := endPos
for start >= 0 && (isLetter(runes[start]) || isDigit(runes[start]) || runes[start] == '_' || runes[start] == '$') {
start--
}
start++ // Move to the first character of the word
if start > endPos {
return ""
}
return string(runes[start : endPos+1])
}
// isLetter checks if a rune is a letter
func isLetter(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
}
// isDigit checks if a rune is a digit
func isDigit(r rune) bool {
return r >= '0' && r <= '9'
}
// FormatJavaScriptForYAML formats a JavaScript script with proper indentation for embedding in YAML
func FormatJavaScriptForYAML(script string) []string {
var formattedLines []string
// Remove JavaScript comments first
cleanScript := removeJavaScriptComments(script)
scriptLines := strings.Split(cleanScript, "\n")
for _, line := range scriptLines {
// Skip empty lines when inlining to YAML
if strings.TrimSpace(line) != "" {
formattedLines = append(formattedLines, fmt.Sprintf(" %s\n", line))
}
}
return formattedLines
}
// WriteJavaScriptToYAML writes a JavaScript script with proper indentation to a strings.Builder
func WriteJavaScriptToYAML(yaml *strings.Builder, script string) {
// Remove JavaScript comments first
cleanScript := removeJavaScriptComments(script)
scriptLines := strings.Split(cleanScript, "\n")
for _, line := range scriptLines {
// Skip empty lines when inlining to YAML
if strings.TrimSpace(line) != "" {
fmt.Fprintf(yaml, " %s\n", line)
}
}
}
// WriteJavaScriptToYAMLPreservingComments writes a JavaScript script with proper indentation to a strings.Builder
// while preserving JSDoc and inline comments, but removing TypeScript-specific comments.
// Used for security-sensitive scripts like redact_secrets.
func WriteJavaScriptToYAMLPreservingComments(yaml *strings.Builder, script string) {
scriptLines := strings.Split(script, "\n")
previousLineWasEmpty := false
hasWrittenContent := false // Track if we've written any content yet
for i, line := range scriptLines {
trimmed := strings.TrimSpace(line)
// Skip TypeScript-specific comments
if strings.HasPrefix(trimmed, "// @ts-") || strings.HasPrefix(trimmed, "/// <reference") {
continue
}
// Handle empty lines
if trimmed == "" {
// Don't add blank lines at the beginning of the script
if !hasWrittenContent {
continue
}
// Look ahead to see if the next non-empty line is a JSDoc comment or function
shouldKeepBlankLine := false
for j := i + 1; j < len(scriptLines); j++ {
nextTrimmed := strings.TrimSpace(scriptLines[j])
if nextTrimmed == "" {
continue
}
// Keep blank line if followed by JSDoc or function/const/async
if strings.HasPrefix(nextTrimmed, "/**") ||
strings.HasPrefix(nextTrimmed, "function ") ||
strings.HasPrefix(nextTrimmed, "async function") ||
strings.HasPrefix(nextTrimmed, "await main(") {
shouldKeepBlankLine = true
}
break
}
if shouldKeepBlankLine && !previousLineWasEmpty {
fmt.Fprintf(yaml, "\n")
previousLineWasEmpty = true
}
continue
}
fmt.Fprintf(yaml, " %s\n", line)
previousLineWasEmpty = false
hasWrittenContent = true
}
}
// GetLogParserScript returns the JavaScript content for a log parser by name
func GetLogParserScript(name string) string {
switch name {
case "parse_claude_log":
return parseClaudeLogScript
case "parse_codex_log":
return parseCodexLogScript
case "parse_copilot_log":
return parseCopilotLogScript
case "validate_errors":
return validateErrorsScript
default:
return ""
}
}
// GetSafeOutputsMCPServerScript returns the JavaScript content for the safe-outputs MCP server
func GetSafeOutputsMCPServerScript() string {
return safeOutputsMCPServerScript
}