mirror of
https://github.com/simstudioai/sim.git
synced 2026-09-24 15:45:35 +08:00
chore(utils): migrate to shared random/ID utilities and add enforcement linting (#4623)
* chore(utils): migrate to shared random/ID utilities and add enforcement linting - Replace all Math.random(), crypto.randomUUID(), crypto.randomBytes(), nanoid, and uuid usages with shared @sim/utils/random and @sim/utils/id helpers across 72 files - Add new @sim/utils exports: deepClone, omit, filterUndefined (object), truncate (string), backoffWithJitter, parseRetryAfter (retry), getErrorMessage (errors) - Sweep all getErrorMessage, sleep, deepClone callsites across 500+ files to use shared utilities - Add Biome noRestrictedImports rule to catch nanoid, uuid, and crypto named imports at lint time - Add scripts/check-utils-enforcement.ts to catch Math.random and crypto.* global property access - Add check:utils script to package.json * chore(utils): replace deepClone wrapper with structuredClone built-in deepClone() was a one-line wrapper around structuredClone(), which is universally available in Node 17+ and all modern browsers. Removing the abstraction reduces indirection and means contributors don't need to learn a project-specific name for a well-known built-in. - Remove deepClone from packages/utils/src/object.ts and index.ts - Replace all 17 call sites with structuredClone() directly - Update check:utils script suggestion text - Update CLAUDE.md and global.md docs * fix(utils): add missing biome noRestrictedImports rule and correct truncate docs - Add noRestrictedImports to biome.json under style — bans nanoid and uuid package imports at lint time (crypto.randomUUID/randomBytes are caught by the check:utils grep script which handles global property access) - Correct truncate() TSDoc and parameter name: sliceLength makes it clear that total output length is sliceLength + suffix.length, matching the behavior all callers were already written to expect * fix(utils): add missing getErrorMessage imports at 4 call sites The sweep agents added getErrorMessage calls without the corresponding import in 4 files, causing test failures. Added the missing imports. * fix(utils): fix build errors from getErrorMessage sweep and retry.ts Turbopack issue - Fix retry.ts cross-file import: Turbopack cannot resolve './random.js' for internal package imports; inline the jitter crypto call directly - Add missing getErrorMessage imports to 32 files where the sweep added calls without the corresponding import (caught by type-check and test runs) - Remove accidental getErrorMessage import from crowdstrike/query/route.ts which has its own domain-specific getErrorMessage for parsing CrowdStrike's JSON error format - Fix use-sub-block-value.ts type error from structuredClone narrowing: add 'as T' cast at emitValue callsite (safe — valueCopy is always a structural copy of newValue) * fix(tools): use toError in crowdstrike catch block instead of local getErrorMessage The catch block was calling the local getErrorMessage function which parses CrowdStrike API JSON responses, not JavaScript Error objects. Use toError(error).message to correctly extract the message from a caught value in this context.
This commit is contained in:
@@ -27,6 +27,7 @@
|
||||
*/
|
||||
|
||||
import { createCipheriv, createDecipheriv, createHash } from 'crypto'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { and, eq, isNull, sql } from 'drizzle-orm'
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
import postgres from 'postgres'
|
||||
@@ -171,9 +172,7 @@ export async function runBackfill(): Promise<void> {
|
||||
stats.updated += 1
|
||||
} catch (error) {
|
||||
stats.failed += 1
|
||||
console.error(
|
||||
`Failed to backfill api_key id=${row.id}: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
console.error(`Failed to backfill api_key id=${row.id}: ${getErrorMessage(error)}`)
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -225,7 +224,7 @@ if ((import.meta as { main?: boolean }).main) {
|
||||
try {
|
||||
await runBackfill()
|
||||
} catch (error) {
|
||||
console.error('Backfill aborted:', error instanceof Error ? error.message : error)
|
||||
console.error('Backfill aborted:', getErrorMessage(error))
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* SSO_PROVIDER_ID=provider-id (optional, if not provided will remove all providers for user)
|
||||
*/
|
||||
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
import postgres from 'postgres'
|
||||
@@ -137,7 +138,7 @@ async function deregisterSSOProvider(): Promise<boolean> {
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.error('❌ Failed to deregister SSO provider:', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
error: getErrorMessage(error, 'Unknown error'),
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
})
|
||||
return false
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'
|
||||
import { appendFileSync, readFileSync, writeFileSync } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
import { sleep } from '@sim/utils/helpers'
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { eq, sql } from 'drizzle-orm'
|
||||
import { index, json, jsonb, pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'
|
||||
@@ -325,10 +326,6 @@ function mergeStats(target: MigrationStats, source: MigrationStats) {
|
||||
target.envVarFailures += source.envVarFailures
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
async function resolveKey(
|
||||
ref: RawKeyRef,
|
||||
env: EnvLookup,
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
* SSO_SAML_WANT_ASSERTIONS_SIGNED=true (optional, defaults to false)
|
||||
*/
|
||||
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
@@ -507,7 +508,7 @@ async function registerSSOProvider(): Promise<boolean> {
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Error fetching OIDC discovery document', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
error: getErrorMessage(error, 'Unknown error'),
|
||||
discoveryUrl,
|
||||
})
|
||||
logger.error(
|
||||
@@ -649,7 +650,7 @@ async function registerSSOProvider(): Promise<boolean> {
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.error('❌ Failed to register SSO provider:', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
error: getErrorMessage(error, 'Unknown error'),
|
||||
errorType: typeof error,
|
||||
errorDetails: JSON.stringify(error),
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { randomFloat, randomInt, randomItem } from '@sim/utils/random'
|
||||
import { eq, type InferInsertModel } from 'drizzle-orm'
|
||||
import { db, userTableDefinitions, userTableRows } from '../index'
|
||||
|
||||
@@ -92,16 +93,8 @@ const lastNames = [
|
||||
'Martin',
|
||||
]
|
||||
|
||||
function randomItem<T>(arr: T[]): T {
|
||||
return arr[Math.floor(Math.random() * arr.length)]
|
||||
}
|
||||
|
||||
function randomInt(min: number, max: number): number {
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min
|
||||
}
|
||||
|
||||
function randomDate(start: Date, end: Date): string {
|
||||
const date = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
|
||||
const date = new Date(start.getTime() + randomFloat() * (end.getTime() - start.getTime()))
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
@@ -116,7 +109,7 @@ function generateUserRow(index: number): UserRow {
|
||||
age: randomInt(22, 65),
|
||||
department: randomItem(departments),
|
||||
salary: randomInt(40000, 200000),
|
||||
active: Math.random() > 0.1, // 90% active
|
||||
active: randomFloat() > 0.1, // 90% active
|
||||
hire_date: randomDate(new Date('2015-01-01'), new Date('2024-12-31')),
|
||||
country: randomItem(countries),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user