Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
385 lines (336 loc) · 11.8 KB
/
Copy pathutils.ts
File metadata and controls
385 lines (336 loc) · 11.8 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
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'
import { type ClassValue, clsx } from 'clsx'
import { nanoid } from 'nanoid'
import { twMerge } from 'tailwind-merge'
import { createLogger } from '@/lib/logs/console-logger'
import { env } from './env'
const logger = createLogger('Utils')
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
function getEncryptionKey(): Buffer {
const key = env.ENCRYPTION_KEY
if (!key || key.length !== 64) {
throw new Error('ENCRYPTION_KEY must be set to a 64-character hex string (32 bytes)')
}
return Buffer.from(key, 'hex')
}
/**
* Encrypts a secret using AES-256-GCM
* @param secret - The secret to encrypt
* @returns A promise that resolves to an object containing the encrypted secret and IV
*/
export async function encryptSecret(secret: string): Promise<{ encrypted: string; iv: string }> {
const iv = randomBytes(16)
const key = getEncryptionKey()
const cipher = createCipheriv('aes-256-gcm', key, iv)
let encrypted = cipher.update(secret, 'utf8', 'hex')
encrypted += cipher.final('hex')
const authTag = cipher.getAuthTag()
// Format: iv:encrypted:authTag
return {
encrypted: `${iv.toString('hex')}:${encrypted}:${authTag.toString('hex')}`,
iv: iv.toString('hex'),
}
}
/**
* Decrypts an encrypted secret
* @param encryptedValue - The encrypted value in format "iv:encrypted:authTag"
* @returns A promise that resolves to an object containing the decrypted secret
*/
export async function decryptSecret(encryptedValue: string): Promise<{ decrypted: string }> {
const parts = encryptedValue.split(':')
const ivHex = parts[0]
const authTagHex = parts[parts.length - 1]
const encrypted = parts.slice(1, -1).join(':')
if (!ivHex || !encrypted || !authTagHex) {
throw new Error('Invalid encrypted value format. Expected "iv:encrypted:authTag"')
}
const key = getEncryptionKey()
const iv = Buffer.from(ivHex, 'hex')
const authTag = Buffer.from(authTagHex, 'hex')
try {
const decipher = createDecipheriv('aes-256-gcm', key, iv)
decipher.setAuthTag(authTag)
let decrypted = decipher.update(encrypted, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return { decrypted }
} catch (error: any) {
logger.error('Decryption error:', { error: error.message })
throw error
}
}
export function convertScheduleOptionsToCron(
scheduleType: string,
options: Record<string, string>
): string {
switch (scheduleType) {
case 'minutes': {
const interval = options.minutesInterval || '15'
// For example, if options.minutesStartingAt is provided, use that as the start minute.
return `*/${interval} * * * *`
}
case 'hourly': {
// When scheduling hourly, take the specified minute offset
return `${options.hourlyMinute || '00'} * * * *`
}
case 'daily': {
// Expected dailyTime in HH:MM
const [minute, hour] = (options.dailyTime || '00:09').split(':')
return `${minute || '00'} ${hour || '09'} * * *`
}
case 'weekly': {
// Expected weeklyDay as MON, TUE, etc. and weeklyDayTime in HH:MM
const dayMap: Record<string, number> = {
MON: 1,
TUE: 2,
WED: 3,
THU: 4,
FRI: 5,
SAT: 6,
SUN: 0,
}
const day = dayMap[options.weeklyDay || 'MON']
const [minute, hour] = (options.weeklyDayTime || '00:09').split(':')
return `${minute || '00'} ${hour || '09'} * * ${day}`
}
case 'monthly': {
// Expected monthlyDay and monthlyTime in HH:MM
const day = options.monthlyDay || '1'
const [minute, hour] = (options.monthlyTime || '00:09').split(':')
return `${minute || '00'} ${hour || '09'} ${day} * *`
}
case 'custom': {
// Use the provided cron expression directly
return options.cronExpression
}
default:
throw new Error('Unsupported schedule type')
}
}
/**
* Get a user-friendly timezone abbreviation
* @param timezone - IANA timezone string
* @param date - Date to check for DST
* @returns A simplified timezone string (e.g., "PST" instead of "America/Los_Angeles")
*/
export function getTimezoneAbbreviation(timezone: string, date: Date = new Date()): string {
if (timezone === 'UTC') return 'UTC'
// Common timezone mappings
const timezoneMap: Record<string, { standard: string; daylight: string }> = {
'America/Los_Angeles': { standard: 'PST', daylight: 'PDT' },
'America/Denver': { standard: 'MST', daylight: 'MDT' },
'America/Chicago': { standard: 'CST', daylight: 'CDT' },
'America/New_York': { standard: 'EST', daylight: 'EDT' },
'Europe/London': { standard: 'GMT', daylight: 'BST' },
'Europe/Paris': { standard: 'CET', daylight: 'CEST' },
'Asia/Tokyo': { standard: 'JST', daylight: 'JST' }, // Japan doesn't use DST
'Australia/Sydney': { standard: 'AEST', daylight: 'AEDT' },
'Asia/Singapore': { standard: 'SGT', daylight: 'SGT' }, // Singapore doesn't use DST
}
// If we have a mapping for this timezone
if (timezone in timezoneMap) {
// January 1 is guaranteed to be standard time in northern hemisphere
// July 1 is guaranteed to be daylight time in northern hemisphere (if observed)
const januaryDate = new Date(date.getFullYear(), 0, 1)
const julyDate = new Date(date.getFullYear(), 6, 1)
// Get offset in January (standard time)
const januaryFormatter = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
timeZoneName: 'short',
})
// Get offset in July (likely daylight time)
const julyFormatter = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
timeZoneName: 'short',
})
// If offsets are different, timezone observes DST
const isDSTObserved = januaryFormatter.format(januaryDate) !== julyFormatter.format(julyDate)
// If DST is observed, check if current date is in DST by comparing its offset
// with January's offset (standard time)
if (isDSTObserved) {
const currentFormatter = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
timeZoneName: 'short',
})
const isDST = currentFormatter.format(date) !== januaryFormatter.format(januaryDate)
return isDST ? timezoneMap[timezone].daylight : timezoneMap[timezone].standard
}
// If DST is not observed, always use standard
return timezoneMap[timezone].standard
}
// For unknown timezones, use full IANA name
return timezone
}
/**
* Format a date into a human-readable format
* @param date - The date to format
* @param timezone - Optional IANA timezone string (e.g., 'America/Los_Angeles', 'UTC')
* @returns A formatted date string in the format "MMM D, YYYY h:mm A"
*/
export function formatDateTime(date: Date, timezone?: string): string {
const formattedDate = date.toLocaleString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
hour12: true,
timeZone: timezone || undefined,
})
// If timezone is provided, add a friendly timezone abbreviation
if (timezone) {
const tzAbbr = getTimezoneAbbreviation(timezone, date)
return `${formattedDate} ${tzAbbr}`
}
return formattedDate
}
/**
* Format a date into a short format
* @param date - The date to format
* @returns A formatted date string in the format "MMM D, YYYY"
*/
export function formatDate(date: Date): string {
return date.toLocaleString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
})
}
/**
* Format a time into a short format
* @param date - The date to format
* @returns A formatted time string in the format "h:mm A"
*/
export function formatTime(date: Date): string {
return date.toLocaleString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true,
})
}
/**
* Format a duration in milliseconds to a human-readable format
* @param durationMs - The duration in milliseconds
* @returns A formatted duration string
*/
export function formatDuration(durationMs: number): string {
if (durationMs < 1000) {
return `${durationMs}ms`
}
const seconds = Math.floor(durationMs / 1000)
if (seconds < 60) {
return `${seconds}s`
}
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
if (minutes < 60) {
return `${minutes}m ${remainingSeconds}s`
}
const hours = Math.floor(minutes / 60)
const remainingMinutes = minutes % 60
return `${hours}h ${remainingMinutes}m`
}
/**
* Generates a standardized API key with the 'sim_' prefix
* @returns A new API key string
*/
export function generateApiKey(): string {
return `sim_${nanoid(32)}`
}
/**
* Rotates through available API keys for a provider
* @param provider - The provider to get a key for (e.g., 'openai')
* @returns The selected API key
* @throws Error if no API keys are configured for rotation
*/
export function getRotatingApiKey(provider: string): string {
if (provider !== 'openai' && provider !== 'anthropic') {
throw new Error(`No rotation implemented for provider: ${provider}`)
}
const keys = []
if (provider === 'openai') {
if (env.OPENAI_API_KEY_1) keys.push(env.OPENAI_API_KEY_1)
if (env.OPENAI_API_KEY_2) keys.push(env.OPENAI_API_KEY_2)
if (env.OPENAI_API_KEY_3) keys.push(env.OPENAI_API_KEY_3)
} else if (provider === 'anthropic') {
if (env.ANTHROPIC_API_KEY_1) keys.push(env.ANTHROPIC_API_KEY_1)
if (env.ANTHROPIC_API_KEY_2) keys.push(env.ANTHROPIC_API_KEY_2)
if (env.ANTHROPIC_API_KEY_3) keys.push(env.ANTHROPIC_API_KEY_3)
}
if (keys.length === 0) {
throw new Error(
`No API keys configured for rotation. Please configure ${provider.toUpperCase()}_API_KEY_1, ${provider.toUpperCase()}_API_KEY_2, or ${provider.toUpperCase()}_API_KEY_3.`
)
}
// Simple round-robin rotation based on current minute
// This distributes load across keys and is stateless
const currentMinute = new Date().getMinutes()
const keyIndex = currentMinute % keys.length
return keys[keyIndex]
}
/**
* Recursively redacts API keys in an object
* @param obj The object to redact API keys from
* @returns A new object with API keys redacted
*/
export const redactApiKeys = (obj: any): any => {
if (!obj || typeof obj !== 'object') {
return obj
}
if (Array.isArray(obj)) {
return obj.map(redactApiKeys)
}
const result: Record<string, any> = {}
for (const [key, value] of Object.entries(obj)) {
if (
key.toLowerCase() === 'apikey' ||
key.toLowerCase() === 'api_key' ||
key.toLowerCase() === 'access_token' ||
/\bsecret\b/i.test(key.toLowerCase()) ||
/\bpassword\b/i.test(key.toLowerCase())
) {
result[key] = '***REDACTED***'
} else if (typeof value === 'object' && value !== null) {
result[key] = redactApiKeys(value)
} else {
result[key] = value
}
}
return result
}
/**
* Validates a name by removing any characters that could cause issues
* with variable references or node naming.
*
* @param name - The name to validate
* @returns The validated name with invalid characters removed, trimmed, and collapsed whitespace
*/
export function validateName(name: string): string {
return name
.replace(/[^a-zA-Z0-9_\s]/g, '') // Remove invalid characters
.replace(/\s+/g, ' ') // Collapse multiple spaces into single spaces
}
/**
* Checks if a name contains invalid characters
*
* @param name - The name to check
* @returns True if the name is valid, false otherwise
*/
export function isValidName(name: string): boolean {
return /^[a-zA-Z0-9_\s]*$/.test(name)
}
/**
* Gets a list of invalid characters in a name
*
* @param name - The name to check
* @returns Array of invalid characters found
*/
export function getInvalidCharacters(name: string): string[] {
const invalidChars = name.match(/[^a-zA-Z0-9_\s]/g)
return invalidChars ? [...new Set(invalidChars)] : []
}
/**
* No-operation function for use as default callback
*/
export const noop = () => {}