The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
ci(ratchet): include filename in error message (#40387)
Charis319c8897f94e
diff --git a/apps/studio/.github/eslint-rule-baselines.json b/apps/studio/.github/eslint-rule-baselines.jsonindex b5b413c54cf..6fd45ff88d1 100644--- a/apps/studio/.github/eslint-rule-baselines.json+++ b/apps/studio/.github/eslint-rule-baselines.json@@ -1,8 +1,270 @@{"rules": {- "react-hooks/exhaustive-deps": 238,+ "react-hooks/exhaustive-deps": 237,"import/no-anonymous-default-export": 62,"@tanstack/query/exhaustive-deps": 19,"@tanstack/query/no-deprecated-options": 2+ },+ "ruleFiles": {+ "react-hooks/exhaustive-deps": {+ "components/grid/SupabaseGrid.tsx": 1,+ "components/grid/SupabaseGrid.utils.ts": 1,+ "components/grid/components/common/BlockKeys.tsx": 2,+ "components/grid/components/editor/JsonEditor.tsx": 2,+ "components/grid/components/editor/TextEditor.tsx": 2,+ "components/grid/components/grid/ColumnHeader.tsx": 1,+ "components/grid/hooks/useTableSort.ts": 1,+ "components/interfaces/Account/TOTPFactors/AddNewFactorModal.tsx": 1,+ "components/interfaces/Advisors/CreateRuleSheet.tsx": 1,+ "components/interfaces/App/CommandMenu/ApiKeys.tsx": 1,+ "components/interfaces/App/RouteValidationWrapper.tsx": 2,+ "components/interfaces/Auth/AdvancedAuthSettingsForm.tsx": 1,+ "components/interfaces/Auth/AuditLogsForm.tsx": 1,+ "components/interfaces/Auth/AuthProvidersForm/FormField.tsx": 2,+ "components/interfaces/Auth/BasicAuthSettingsForm.tsx": 1,+ "components/interfaces/Auth/Hooks/CreateHookSheet.tsx": 1,+ "components/interfaces/Auth/MfaAuthSettingsForm/MfaAuthSettingsForm.tsx": 1,+ "components/interfaces/Auth/OAuthApps/CreateOAuthAppSheet.tsx": 1,+ "components/interfaces/Auth/OAuthApps/OAuthServerSettingsForm.tsx": 1,+ "components/interfaces/Auth/Policies/PolicyEditor/PolicyDefinition.tsx": 1,+ "components/interfaces/Auth/Policies/PolicyEditorPanel/PolicyDetailsV2.tsx": 1,+ "components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx": 2,+ "components/interfaces/Auth/Policies/PolicyEditorPanel/index.tsx": 1,+ "components/interfaces/Auth/ProtectionAuthSettingsForm/ProtectionAuthSettingsForm.tsx": 1,+ "components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx": 1,+ "components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.tsx": 1,+ "components/interfaces/Auth/SiteUrl/SiteUrl.tsx": 1,+ "components/interfaces/Auth/ThirdPartyAuthForm/CreateAuth0Dialog.tsx": 1,+ "components/interfaces/Auth/ThirdPartyAuthForm/CreateAwsCognitoAuthDialog.tsx": 1,+ "components/interfaces/Auth/ThirdPartyAuthForm/CreateClerkAuthDialog.tsx": 1,+ "components/interfaces/Auth/ThirdPartyAuthForm/CreateFirebaseAuthDialog.tsx": 1,+ "components/interfaces/Auth/ThirdPartyAuthForm/CreateWorkOSDialog.tsx": 1,+ "components/interfaces/Auth/Users/UsersV2.tsx": 1,+ "components/interfaces/Billing/Payment/AddNewPaymentMethodModal.tsx": 1,+ "components/interfaces/Billing/Payment/PaymentConfirmation.tsx": 1,+ "components/interfaces/Billing/Payment/PaymentMethods/NewPaymentMethodElement.tsx": 2,+ "components/interfaces/BranchManagement/EditBranchModal.tsx": 2,+ "components/interfaces/Connect/DatabaseConnectionString.tsx": 2,+ "components/interfaces/Database/Backups/PITR/TimeInput.tsx": 4,+ "components/interfaces/Database/EnumeratedTypes/CreateEnumeratedTypeSidePanel.tsx": 1,+ "components/interfaces/Database/Extensions/EnableExtensionModal.tsx": 1,+ "components/interfaces/Database/Functions/CreateFunction/index.tsx": 1,+ "components/interfaces/Database/Indexes/Indexes.tsx": 1,+ "components/interfaces/Database/Schemas/SchemaGraph.tsx": 1,+ "components/interfaces/DiskManagement/DiskManagementForm.tsx": 2,+ "components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx": 1,+ "components/interfaces/GraphQL/GraphiQL.tsx": 1,+ "components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx": 1,+ "components/interfaces/Integrations/Landing/useInstalledIntegrations.tsx": 2,+ "components/interfaces/Integrations/Queues/QueuesSettings.tsx": 1,+ "components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsx": 1,+ "components/interfaces/Integrations/Queues/SingleQueue/SendMessageModal.tsx": 1,+ "components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx": 1,+ "components/interfaces/Integrations/Wrappers/WrapperDynamicColumns.tsx": 1,+ "components/interfaces/Organization/BillingSettings/BillingCustomerData/useBillingCustomerDataForm.ts": 1,+ "components/interfaces/Organization/BillingSettings/BillingEmail.tsx": 1,+ "components/interfaces/Organization/BillingSettings/CreditTopUp.tsx": 1,+ "components/interfaces/Organization/BillingSettings/Subscription/PaymentMethodSelection.tsx": 2,+ "components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx": 1,+ "components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx": 1,+ "components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.tsx": 1,+ "components/interfaces/Organization/Usage/Compute.tsx": 1,+ "components/interfaces/ProjectAPIDocs/Content/Entity.tsx": 1,+ "components/interfaces/ProjectAPIDocs/Content/RPC.tsx": 1,+ "components/interfaces/QueryPerformance/QueryPerformanceChart.tsx": 1,+ "components/interfaces/Realtime/Inspector/MessagesTable.tsx": 1,+ "components/interfaces/Realtime/Inspector/useRealtimeMessages.ts": 2,+ "components/interfaces/Reports/ReportBlock/ChartBlock.tsx": 1,+ "components/interfaces/Reports/ReportFilterBar.tsx": 1,+ "components/interfaces/Reports/Reports.tsx": 1,+ "components/interfaces/Reports/useReportFilters.ts": 4,+ "components/interfaces/SQLEditor/AskAIWidget.tsx": 1,+ "components/interfaces/SQLEditor/InlineWidget.tsx": 2,+ "components/interfaces/SQLEditor/MonacoEditor.tsx": 1,+ "components/interfaces/SQLEditor/MoveQueryModal.tsx": 1,+ "components/interfaces/SQLEditor/OngoingQueriesPanel.tsx": 1,+ "components/interfaces/SQLEditor/RenameQueryModal.tsx": 1,+ "components/interfaces/SQLEditor/SQLEditor.tsx": 2,+ "components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx": 1,+ "components/interfaces/Settings/API/PostgrestConfig.tsx": 1,+ "components/interfaces/Settings/Addons/CustomDomainSidePanel.tsx": 1,+ "components/interfaces/Settings/Addons/IPv4SidePanel.tsx": 1,+ "components/interfaces/Settings/Addons/PITRSidePanel.tsx": 1,+ "components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx": 1,+ "components/interfaces/Settings/Database/SSLConfiguration.tsx": 1,+ "components/interfaces/Settings/General/ComplianceConfig/ProjectComplianceMode.tsx": 1,+ "components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx": 1,+ "components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx": 1,+ "components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx": 1,+ "components/interfaces/Settings/Logs/LogTable.tsx": 2,+ "components/interfaces/Settings/Logs/LogsPreviewer.tsx": 2,+ "components/interfaces/Settings/Logs/PreviewFilterPanel.tsx": 1,+ "components/interfaces/SignIn/SignInPartner.tsx": 1,+ "components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/CopyEnvButton.tsx": 1,+ "components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx": 2,+ "components/interfaces/Storage/StorageExplorer/FileExplorerRowEditing.tsx": 1,+ "components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx": 2,+ "components/interfaces/Storage/StorageSettings/StorageSettings.tsx": 1,+ "components/interfaces/Storage/VectorBuckets/CreateVectorBucketDialog.tsx": 1,+ "components/interfaces/Storage/VectorBuckets/CreateVectorTableSheet.tsx": 1,+ "components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx": 1,+ "components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx": 2,+ "components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx": 2,+ "components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx": 1,+ "components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx": 2,+ "components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx": 2,+ "components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartAIWidget.tsx": 1,+ "components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/useAITableGeneration.ts": 2,+ "components/interfaces/TableGridEditor/TableDefinition.tsx": 1,+ "components/interfaces/TableGridEditor/TableGridEditor.tsx": 2,+ "components/interfaces/UnifiedLogs/ServiceFlow/components/ServiceFlowHeader.tsx": 2,+ "components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx": 1,+ "components/layouts/ProjectLayout/ConnectingState.tsx": 1,+ "components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackWidget.tsx": 2,+ "components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx": 1,+ "components/layouts/ProjectLayout/index.tsx": 1,+ "components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx": 4,+ "components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx": 2,+ "components/layouts/SignInLayout/SignInLayout.tsx": 1,+ "components/layouts/Tabs/Tabs.utils.ts": 2,+ "components/ui/Charts/ChartHighlightActions.tsx": 2,+ "components/ui/Charts/Charts.utils.tsx": 7,+ "components/ui/Charts/ComposedChartHandler.tsx": 1,+ "components/ui/CodeEditor/CodeEditor.tsx": 1,+ "components/ui/DataTable/DataTableFilters/DataTableFilterInput.tsx": 2,+ "components/ui/DataTable/DataTableFilters/DataTableFilterSlider.tsx": 2,+ "components/ui/DataTable/DataTableHeaderLayout.tsx": 1,+ "components/ui/DataTable/DataTableSideBarLayout.tsx": 4,+ "components/ui/DataTable/DataTableToolbar.tsx": 1,+ "components/ui/DataTable/DataTableViewOptions.tsx": 1,+ "components/ui/DataTable/LiveButton.tsx": 1,+ "components/ui/DataTable/TimelineChart.tsx": 1,+ "components/ui/DatePicker/TimeSplitInput.tsx": 1,+ "components/ui/DateRangePicker.tsx": 1,+ "components/ui/Error.tsx": 1,+ "components/ui/FilterPopover.tsx": 1,+ "components/ui/ScrollGradient.tsx": 1,+ "data/__templates/resource-query.ts": 1,+ "data/__templates/resources-query.ts": 1,+ "data/reports/api-report-query.ts": 2,+ "data/reports/storage-report-query.ts": 2,+ "hooks/analytics/useFillTimeseriesSorted.ts": 3,+ "hooks/analytics/useLogsPreview.tsx": 4,+ "hooks/analytics/useLogsQuery.tsx": 1,+ "hooks/analytics/useProjectUsageStats.tsx": 1,+ "hooks/analytics/useTimeseriesUnixToIso.ts": 2,+ "hooks/branches/useEdgeFunctionsDiff.ts": 1,+ "hooks/misc/useSchemaQueryState.ts": 1,+ "hooks/misc/useUpgradePrompt.tsx": 1,+ "hooks/ui/useCsvFileDrop.ts": 1,+ "hooks/ui/useHotKey.ts": 2,+ "pages/forgot-password-mfa.tsx": 1,+ "pages/integrations/vercel/install.tsx": 1,+ "pages/logout.tsx": 1,+ "pages/new/[slug].tsx": 4,+ "pages/new/index.tsx": 1,+ "pages/organizations.tsx": 1,+ "pages/project/[ref]/auth/policies.tsx": 2,+ "pages/project/[ref]/building.tsx": 1,+ "pages/project/[ref]/editor/[id].tsx": 1,+ "pages/project/[ref]/editor/index.tsx": 1,+ "pages/project/[ref]/integrations/[id]/[pageId]/index.tsx": 1,+ "pages/project/[ref]/logs/explorer/index.tsx": 1,+ "pages/project/[ref]/reports/postgrest.tsx": 1,+ "pages/project/[ref]/reports/realtime.tsx": 1,+ "pages/project/[ref]/settings/jwt/index.tsx": 1,+ "pages/project/[ref]/sql/quickstarts.tsx": 1,+ "pages/project/[ref]/sql/templates.tsx": 1,+ "pages/sign-in-fly-tos.tsx": 1,+ "pages/sign-in-mfa.tsx": 1,+ "state/role-impersonation-state.tsx": 1,+ "state/sidebar-manager-state.tsx": 1,+ "state/storage-explorer.tsx": 1,+ "state/table-editor-table.tsx": 1+ },+ "import/no-anonymous-default-export": {+ "pages/api/platform/auth/[ref]/invite.ts": 1,+ "pages/api/platform/auth/[ref]/magiclink.ts": 1,+ "pages/api/platform/auth/[ref]/otp.ts": 1,+ "pages/api/platform/auth/[ref]/recover.ts": 1,+ "pages/api/platform/auth/[ref]/users/[id]/factors.ts": 1,+ "pages/api/platform/auth/[ref]/users/[id]/index.ts": 1,+ "pages/api/platform/auth/[ref]/users/index.ts": 1,+ "pages/api/platform/database/[ref]/pooling.ts": 1,+ "pages/api/platform/integrations/[slug].ts": 1,+ "pages/api/platform/integrations/github/authorization.ts": 1,+ "pages/api/platform/integrations/github/connections.ts": 1,+ "pages/api/platform/integrations/github/repositories.ts": 1,+ "pages/api/platform/organizations/[slug]/billing/subscription.ts": 1,+ "pages/api/platform/organizations/index.ts": 1,+ "pages/api/platform/pg-meta/[ref]/column-privileges.ts": 1,+ "pages/api/platform/pg-meta/[ref]/extensions.ts": 1,+ "pages/api/platform/pg-meta/[ref]/foreign-tables.ts": 1,+ "pages/api/platform/pg-meta/[ref]/materialized-views.ts": 1,+ "pages/api/platform/pg-meta/[ref]/policies.ts": 1,+ "pages/api/platform/pg-meta/[ref]/publications.ts": 1,+ "pages/api/platform/pg-meta/[ref]/query/index.ts": 1,+ "pages/api/platform/pg-meta/[ref]/tables.ts": 1,+ "pages/api/platform/pg-meta/[ref]/triggers.ts": 1,+ "pages/api/platform/pg-meta/[ref]/types.ts": 1,+ "pages/api/platform/pg-meta/[ref]/views.ts": 1,+ "pages/api/platform/profile/index.ts": 1,+ "pages/api/platform/projects/[ref]/analytics/endpoints/[name].ts": 1,+ "pages/api/platform/projects/[ref]/analytics/log-drains.ts": 1,+ "pages/api/platform/projects/[ref]/analytics/log-drains/[uuid].ts": 1,+ "pages/api/platform/projects/[ref]/api-keys/temporary.ts": 1,+ "pages/api/platform/projects/[ref]/api/graphql.ts": 1,+ "pages/api/platform/projects/[ref]/api/rest.ts": 1,+ "pages/api/platform/projects/[ref]/billing/addons.ts": 1,+ "pages/api/platform/projects/[ref]/config/index.ts": 1,+ "pages/api/platform/projects/[ref]/config/postgrest.ts": 1,+ "pages/api/platform/projects/[ref]/content/count.ts": 1,+ "pages/api/platform/projects/[ref]/content/folders/[id].ts": 1,+ "pages/api/platform/projects/[ref]/content/folders/index.ts": 1,+ "pages/api/platform/projects/[ref]/content/index.ts": 1,+ "pages/api/platform/projects/[ref]/content/item/[id].ts": 1,+ "pages/api/platform/projects/[ref]/databases.ts": 1,+ "pages/api/platform/projects/[ref]/index.ts": 1,+ "pages/api/platform/projects/[ref]/infra-monitoring.ts": 1,+ "pages/api/platform/projects/[ref]/run-lints.ts": 1,+ "pages/api/platform/projects/[ref]/settings.ts": 1,+ "pages/api/platform/projects/index.ts": 1,+ "pages/api/platform/props/org/[slug].tsx": 1,+ "pages/api/platform/props/project/[ref]/api.ts": 1,+ "pages/api/platform/props/project/[ref]/index.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/empty.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/index.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/objects/download.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/objects/index.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/objects/list.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/objects/move.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/objects/public-url.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/[id]/objects/sign.ts": 1,+ "pages/api/platform/storage/[ref]/buckets/index.ts": 1,+ "pages/api/platform/telemetry/event.ts": 1,+ "pages/api/v1/projects/[ref]/api-keys.ts": 1,+ "pages/api/v1/projects/[ref]/database/migrations.ts": 1,+ "pages/api/v1/projects/[ref]/types/typescript.ts": 1+ },+ "@tanstack/query/exhaustive-deps": {+ "components/interfaces/Reports/SharedAPIReport/SharedAPIReport.constants.ts": 1,+ "components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx": 1,+ "components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx": 3,+ "data/branches/branch-diff-query.ts": 1,+ "data/database/foreign-key-constraints-query.ts": 1,+ "data/database/schemas-query.ts": 1,+ "data/entity-types/entity-types-infinite-query.ts": 1,+ "data/table-editor/table-editor-query.ts": 1,+ "data/table-rows/table-rows-query.ts": 1,+ "data/tables/tables-query.ts": 2,+ "hooks/analytics/useDbQuery.tsx": 1,+ "hooks/analytics/useLogsPreview.tsx": 3,+ "hooks/analytics/useProjectUsageStats.tsx": 1,+ "hooks/analytics/useSingleLog.tsx": 1+ },+ "@tanstack/query/no-deprecated-options": {+ "data/config/jwt-secret-updating-status-query.ts": 1,+ "data/config/project-upgrade-status-query.ts": 1+ }}}diff --git a/apps/studio/scripts/__tests__/ratchet-eslint-rules.test.ts b/apps/studio/scripts/__tests__/ratchet-eslint-rules.test.tsnew file mode 100644index 00000000000..b4624fe5aed--- /dev/null+++ b/apps/studio/scripts/__tests__/ratchet-eslint-rules.test.ts@@ -0,0 +1,148 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { runRatchet } from '../ratchet-eslint-rules'++const studioRoot = path.resolve(__dirname, '../..')+const repoRoot = path.resolve(studioRoot, '..', '..')+const scriptArgvPlaceholder = path.resolve(studioRoot, 'scripts', 'ratchet-eslint-rules.ts')++const tempDirs: string[] = []++afterEach(() => {+ vi.restoreAllMocks()+ while (tempDirs.length) {+ const dir = tempDirs.pop()+ if (dir) {+ rmSync(dir, { recursive: true, force: true })+ }+ }+})++describe('ratchet-eslint-rules integration', () => {+ it('captures per-file counts when initializing baselines', () => {+ const tmp = createTempDir()+ const metadataPath = path.join(tmp, 'baseline.json')++ const eslintResults = buildEslintResults([+ { filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 1 } },+ { filePath: repoPath('apps/studio/src/b.ts'), rules: { 'no-console': 2 } },+ ])++ const result = invokeRatchet(+ ['--metadata', metadataPath, '--rule', 'no-console', '--init'],+ eslintResults+ )++ expect(result).toBe(0)++ const metadata = JSON.parse(readFileSync(metadataPath, 'utf8'))+ expect(metadata.rules['no-console']).toBe(3)+ expect(metadata.ruleFiles['no-console']).toEqual({+ [relativeToCwd('apps/studio/src/a.ts')]: 1,+ [relativeToCwd('apps/studio/src/b.ts')]: 2,+ })+ })++ it('reports offending files when regressions occur and metadata has per-file data', () => {+ const tmp = createTempDir()+ const metadataPath = path.join(tmp, 'baseline.json')++ writeFileSync(+ metadataPath,+ JSON.stringify(+ {+ rules: { 'no-console': 2 },+ ruleFiles: {+ 'no-console': {+ [relativeToCwd('apps/studio/src/a.ts')]: 2,+ },+ },+ },+ null,+ 2+ )+ )++ const eslintResults = buildEslintResults([+ { filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 3 } },+ { filePath: repoPath('apps/studio/src/b.ts'), rules: { 'no-console': 1 } },+ ])++ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const result = invokeRatchet(+ ['--metadata', metadataPath, '--rule', 'no-console'],+ eslintResults+ )++ expect(result).toBe(1)+ const combinedErrors = errorSpy.mock.calls.map((args) => args.join(' ')).join('\n')+ expect(combinedErrors).toContain(`${relativeToCwd('apps/studio/src/a.ts')} (+1)`)+ expect(combinedErrors).toContain(`${relativeToCwd('apps/studio/src/b.ts')} (+1)`)+ })++ it('falls back gracefully when baseline is missing per-file data', () => {+ const tmp = createTempDir()+ const metadataPath = path.join(tmp, 'baseline.json')++ writeFileSync(+ metadataPath,+ JSON.stringify(+ {+ rules: { 'no-console': 1 },+ },+ null,+ 2+ )+ )++ const eslintResults = buildEslintResults([+ { filePath: repoPath('apps/studio/src/a.ts'), rules: { 'no-console': 2 } },+ ])++ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const result = invokeRatchet(+ ['--metadata', metadataPath, '--rule', 'no-console'],+ eslintResults+ )++ expect(result).toBe(1)+ const combinedErrors = errorSpy.mock.calls.map((args) => args.join(' ')).join('\n')+ expect(combinedErrors).toContain('baseline missing file breakdown')+ expect(combinedErrors).toContain(`${relativeToCwd('apps/studio/src/a.ts')} (2 current)`)+ })+})++function buildEslintResults(+ files: Array<{ filePath: string; rules: Record<string, number> }>+): unknown[] {+ return files.map(({ filePath, rules }) => ({+ filePath,+ messages: Object.entries(rules).flatMap(([ruleId, count]) =>+ Array.from({ length: count }, () => ({ ruleId }))+ ),+ }))+}++function createTempDir(): string {+ const dir = mkdtempSync(path.join(os.tmpdir(), 'ratchet-eslint'))+ tempDirs.push(dir)+ return dir+}++function repoPath(relPath: string): string {+ return path.join(repoRoot, relPath)+}++function invokeRatchet(args: string[], eslintResults: unknown[]): number {+ const argv = ['node', scriptArgvPlaceholder, ...args]+ return runRatchet(argv, () => ({+ results: eslintResults as any,+ stderr: '',+ }))+}++function relativeToCwd(relPath: string): string {+ return path.relative(process.cwd(), repoPath(relPath)).split(path.sep).join('/')+}diff --git a/apps/studio/scripts/ratchet-eslint-rules.ts b/apps/studio/scripts/ratchet-eslint-rules.tsindex 09613141d43..a0004e740f1 100644--- a/apps/studio/scripts/ratchet-eslint-rules.ts+++ b/apps/studio/scripts/ratchet-eslint-rules.ts@@ -32,6 +32,7 @@import { spawnSync } from 'node:child_process'import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'import path from 'node:path'+import { pathToFileURL } from 'node:url'interface Args {metadata: string@@ -47,6 +48,7 @@ interface ESLintMessage {}interface ESLintResult {+ filePath?: stringmessages?: ESLintMessage[]}@@ -57,6 +59,12 @@ interface ESLintExecutionResult {interface BaselineData {rules: Record<string, number>+ ruleFiles?: Record<string, Record<string, number>>+}++interface RuleSnapshot {+ total: number+ files: Record<string, number>}function parseArgs(argv: string[]): Args {@@ -143,49 +151,74 @@ function dangerouslyRunEsLint(eslintCmd: string, eslintArgs: string): ESLintExecreturn { results, stderr }}-function countRules(results: ESLintResult[], ruleIds: string[]): Record<string, number> {+function normalizeFilePath(filePath?: string | null): string | null {+ if (!filePath) return null+ const rel = path.relative(process.cwd(), filePath)+ const normalized = rel || path.basename(filePath)+ return normalized.split(path.sep).join('/')+}++function collectRuleSnapshots(+ results: ESLintResult[],+ ruleIds: string[]+): Record<string, RuleSnapshot> {const checkedIds = new Set(ruleIds)- const counts: Record<string, number> = {}+ const snapshots: Record<string, RuleSnapshot> = {}for (const id of ruleIds) {- counts[id] = 0+ snapshots[id] = { total: 0, files: {} }}for (const file of results) {if (!file || !Array.isArray(file.messages)) continue+ const normalizedPath = normalizeFilePath(file.filePath)for (const msg of file.messages) {const id = msg?.ruleId ?? ''if (id && checkedIds.has(id)) {- counts[id] += 1+ const snapshot = snapshots[id] ?? { total: 0, files: {} }+ snapshot.total += 1+ if (normalizedPath) {+ snapshot.files[normalizedPath] = (snapshot.files[normalizedPath] ?? 0) + 1+ }+ snapshots[id] = snapshot}}}- return counts++ return snapshots}function readBaselines(fp: string): BaselineData {- if (!existsSync(fp)) return { rules: {} }+ if (!existsSync(fp)) return { rules: {}, ruleFiles: {} }try {const data = JSON.parse(readFileSync(fp, 'utf8')) as Partial<BaselineData>if (data && typeof data === 'object' && data.rules && typeof data.rules === 'object') {- return { rules: data.rules }+ return { rules: data.rules, ruleFiles: data.ruleFiles ?? {} }}} catch {// ignore invalid metadata files and fall back to blank baselines}- return { rules: {} }+ return { rules: {}, ruleFiles: {} }}-function writeBaselines(fp: string, updates: Record<string, number>, merge = true): void {+function writeBaselines(fp: string, updates: Record<string, RuleSnapshot>, merge = true): void {const dir = path.dirname(fp)mkdirSync(dir, { recursive: true })- let current: BaselineData = { rules: {} }+ let current: BaselineData = { rules: {}, ruleFiles: {} }if (merge && existsSync(fp)) {current = readBaselines(fp)}- const next: BaselineData = { rules: { ...current.rules, ...updates } }+ const nextRules = merge ? { ...current.rules } : {}+ const nextRuleFiles = merge ? { ...(current.ruleFiles ?? {}) } : {}++ for (const [rule, snapshot] of Object.entries(updates)) {+ nextRules[rule] = snapshot.total+ nextRuleFiles[rule] = snapshot.files+ }++ const next: BaselineData = { rules: nextRules, ruleFiles: nextRuleFiles }writeFileSync(fp, `${JSON.stringify(next, null, 2)}\n`, 'utf8')}@@ -200,17 +233,21 @@ function writeSummary(markdown: string): void {}}-function main(): void {- const args = parseArgs(process.argv)+export function runRatchet(argv: string[], runEslint = dangerouslyRunEsLint): number {+ const args = parseArgs(argv)// SECURITY:// Offloaded to user. Must document that they should not pass untrusted input// via --eslint or --eslint-args.- const { results, stderr } = dangerouslyRunEsLint(args.eslint, args.eslintArgs)- const currentCounts = countRules(results, args.rules)+ const { results, stderr } = runEslint(args.eslint, args.eslintArgs)+ const currentSnapshots = collectRuleSnapshots(results, args.rules)+ const currentCounts: Record<string, number> = {}+ for (const rule of args.rules) {+ currentCounts[rule] = currentSnapshots[rule]?.total ?? 0+ }if (args.init) {- writeBaselines(args.metadata, currentCounts, true)+ writeBaselines(args.metadata, currentSnapshots, true)const rows = Object.entries(currentCounts).map(([rule, count]) => `| \`${rule}\` | **${count}** |`)@@ -231,28 +268,33 @@ function main(): void {console.log(`Initialized/updated baselines for: ${args.rules.join(', ')} (saved to ${args.metadata}).`)- process.exit(0)+ return 0}- const baselines = readBaselines(args.metadata).rules || {}+ const baselineData = readBaselines(args.metadata)+ const baselineRules = baselineData.rules || {}+ const baselineRuleFiles = baselineData.ruleFiles || {}- const missing = args.rules.filter((r) => typeof baselines[r] !== 'number')+ const missing = args.rules.filter((r) => typeof baselineRules[r] !== 'number')if (missing.length) {const msg = `Missing baselines for: ${missing.join(', ')} in ${args.metadata}. Run with --init to set them.`console.error(msg)writeSummary(`### ESLint rule ratchet\n${msg}`)console.log(`::error title=Missing baselines::${msg}`)- process.exit(2)+ return 2}let failed = falseconst tableRows: string[] = []const improvedRules: string[] = []- const decreasedBaselines: Record<string, { from: number; to: number }> = {}+ const decreasedBaselines: Record<string, { from: number; to: number; snapshot: RuleSnapshot }> =+ {}for (const rule of args.rules) {- const baseline = baselines[rule] ?? 0+ const baseline = baselineRules[rule] ?? 0const current = currentCounts[rule] ?? 0const delta = current - baseline+ const currentSnapshot = currentSnapshots[rule] ?? { total: 0, files: {} }+ const baselineFiles = baselineRuleFiles[rule] ?? {}tableRows.push(`| \`${rule}\` | **${baseline}** | **${current}** | ${delta >= 0 ? '+' : '-'}${delta} |`@@ -261,13 +303,27 @@ function main(): void {if (current > baseline) {failed = trueconst delta = current - baseline- const msg = `You added ${delta === 1 ? 'a new violation' : `${delta} new violations`} of ${rule}. Please fix it: baseline=${baseline}, current=${current}`+ const baselineHasFiles = Object.hasOwn(baselineRuleFiles, rule)+ const fileSummary = describeFileRegression(+ baselineFiles,+ currentSnapshot.files,+ baselineHasFiles+ )+ const msgParts = [+ `You added ${delta === 1 ? 'a new violation' : `${delta} new violations`} of ${rule}. Please fix it: baseline=${baseline}, current=${current}`,+ ]+ if (fileSummary) {+ msgParts.push(+ `Affected files: ${fileSummary}${baselineHasFiles ? '' : ' (baseline missing file breakdown; rerun with --init to capture it)'}`+ )+ }+ const msg = msgParts.join(' ')console.error(msg)console.log(`::error title=New violations::${msg}`)} else if (current < baseline) {improvedRules.push(rule)if (args.decreaseBaselines) {- decreasedBaselines[rule] = { from: baseline, to: current }+ decreasedBaselines[rule] = { from: baseline, to: current, snapshot: currentSnapshot }}}}@@ -283,11 +339,11 @@ function main(): void {]if (args.decreaseBaselines && Object.keys(decreasedBaselines).length > 0) {- const updates: Record<string, number> = {}+ const updates: Record<string, RuleSnapshot> = {}const details: string[] = []const logParts: string[] = []- for (const [rule, { from, to }] of Object.entries(decreasedBaselines)) {- updates[rule] = to+ for (const [rule, { from, to, snapshot }] of Object.entries(decreasedBaselines)) {+ updates[rule] = snapshotdetails.push(`- \`${rule}\`: ${from} -> ${to}`)logParts.push(`${rule}: ${from} -> ${to}`)}@@ -300,15 +356,66 @@ function main(): void {if (failed) {if (stderr && stderr.trim()) console.error('\nESLint stderr:\n', stderr)- process.exit(1)+ return 1} else {console.log(improvedRules.length > 0? 'Nice! Some rules improved.': 'Stable: No regressions for selected rules.')- process.exit(0)+ return 0}}-main()+function main(): void {+ const exitCode = runRatchet(process.argv, dangerouslyRunEsLint)+ process.exit(exitCode)+}++if (process.argv[1]) {+ const invokedPath = pathToFileURL(path.resolve(process.argv[1])).href+ if (import.meta.url === invokedPath) {+ main()+ }+}++function describeFileRegression(+ baselineFiles: Record<string, number>,+ currentFiles: Record<string, number>,+ baselineHasFiles: boolean+): string {+ const MAX_FILES = 5+ if (baselineHasFiles) {+ const entries = Object.entries(currentFiles)+ .map(([file, count]) => ({+ file,+ delta: count - (baselineFiles[file] ?? 0),+ }))+ .filter(({ delta }) => delta > 0)+ .sort((a, b) => b.delta - a.delta || a.file.localeCompare(b.file))++ if (!entries.length) return ''++ return formatFileList(+ entries.map(({ file, delta }) => `${file} (+${delta})`),+ MAX_FILES+ )+ }++ const currentEntries = Object.entries(currentFiles)+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .map(([file, count]) => `${file} (${count} current)`)++ if (!currentEntries.length) return ''++ return formatFileList(currentEntries, MAX_FILES)+}++function formatFileList(entries: string[], maxFiles: number): string {+ if (entries.length <= maxFiles) {+ return entries.join(', ')+ }+ const remainder = entries.length - maxFiles+ const plural = remainder === 1 ? 'file' : 'files'+ return `${entries.slice(0, maxFiles).join(', ')}, +${remainder} more ${plural}`+}