diff --git a/frontend/e2e-tests/bugs.spec.ts b/frontend/e2e-tests/bugs.spec.ts index b540a4a7873..d020c869abf 100644 --- a/frontend/e2e-tests/bugs.spec.ts +++ b/frontend/e2e-tests/bugs.spec.ts @@ -16,7 +16,7 @@ test.beforeEach(async ({ page }, info) => { * This test makes sure that downstream UI elements are re-initialized when * upstream source cells are re-run. */ -test("correctly initializes cells", async ({ page }, info) => { +test("correctly initializes cells", async ({ page }) => { // Is initialized to 1 const number = page .getByTestId("marimo-plugin-number-input") diff --git a/frontend/e2e-tests/global-setup.ts b/frontend/e2e-tests/global-setup.ts index fca79110bd8..d0df63eb406 100644 --- a/frontend/e2e-tests/global-setup.ts +++ b/frontend/e2e-tests/global-setup.ts @@ -1,10 +1,9 @@ /* Copyright 2024 Marimo. All rights reserved. */ -/** biome-ignore-all lint/suspicious/noConsole: for debugging */ import { chromium, type FullConfig } from "@playwright/test"; import { type ApplicationNames, getAppUrl } from "../playwright.config"; -async function globalSetup(config: FullConfig) { +async function globalSetup(_config: FullConfig) { // Start a browser to test server connectivity const browser = await chromium.launch(); const page = await browser.newPage(); diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.ts index f96ea947bbf..64f7c1752f0 100644 --- a/frontend/src/__mocks__/notebook.ts +++ b/frontend/src/__mocks__/notebook.ts @@ -134,11 +134,11 @@ export const MockNotebook = { * Create a notebook state with error outputs for testing ErrorContextProvider */ notebookStateWithErrors: ( - errors: Array<{ + errors: { cellId: CellId; cellName: string; errorData: MarimoError[]; - }>, + }[], ): NotebookState => { const cellData: Record> = {}; diff --git a/frontend/src/__tests__/main.test.tsx b/frontend/src/__tests__/main.test.tsx index dea1cd24bc8..3abc4eca5c0 100644 --- a/frontend/src/__tests__/main.test.tsx +++ b/frontend/src/__tests__/main.test.tsx @@ -23,7 +23,7 @@ vi.mock("../utils/vitals", () => ({ })); vi.mock("react-dom/client", () => ({ - createRoot: vi.fn().mockImplementation((el) => { + createRoot: vi.fn().mockImplementation((_el) => { return { render: vi.fn(), }; @@ -47,7 +47,7 @@ describe("main", () => { it.each(["edit", "read", "home", "run"])( "should mount with mode %s", - (mode) => { + (_mode) => { const el = document.createElement("div"); mount({ mode: "edit" }, el); diff --git a/frontend/src/components/app-config/common.tsx b/frontend/src/components/app-config/common.tsx index 2ff10637285..fd3bb5d94be 100644 --- a/frontend/src/components/app-config/common.tsx +++ b/frontend/src/components/app-config/common.tsx @@ -36,10 +36,10 @@ export const SettingDescription: React.FC = ({ return

{children}

; }; -export const SQL_OUTPUT_SELECT_OPTIONS: Array<{ +export const SQL_OUTPUT_SELECT_OPTIONS: { label: string; value: SqlOutputType; -}> = [ +}[] = [ { label: "Auto (Default)", value: "auto" }, { label: "Native", value: "native" }, { label: "Polars", value: "polars" }, diff --git a/frontend/src/components/audio/audio-recorder.tsx b/frontend/src/components/audio/audio-recorder.tsx index d7c18e05efe..2c6e4662b23 100644 --- a/frontend/src/components/audio/audio-recorder.tsx +++ b/frontend/src/components/audio/audio-recorder.tsx @@ -17,7 +17,6 @@ interface AudioRecorderProps { export const AudioRecorder: React.FC = ({ onStart, onStop, - onPause, status, time, }) => { diff --git a/frontend/src/components/chat/acp/blocks.tsx b/frontend/src/components/chat/acp/blocks.tsx index 21a522e125c..6c40491501e 100644 --- a/frontend/src/components/chat/acp/blocks.tsx +++ b/frontend/src/components/chat/acp/blocks.tsx @@ -528,7 +528,7 @@ export const CurrentModeBlock = (props: { }; export const ToolNotificationsBlock = (props: { - data: Array; + data: (ToolCallNotificationEvent | ToolCallUpdateNotificationEvent)[]; }) => { const toolCalls = mergeToolCalls(props.data); @@ -561,7 +561,7 @@ export const ToolNotificationsBlock = (props: { }; export const DiffBlocks = (props: { - data: Array>; + data: Extract[]; }) => { return (
diff --git a/frontend/src/components/chat/acp/thread.tsx b/frontend/src/components/chat/acp/thread.tsx index 8dd9f1bc67b..205d4f9ac1f 100644 --- a/frontend/src/components/chat/acp/thread.tsx +++ b/frontend/src/components/chat/acp/thread.tsx @@ -99,23 +99,21 @@ export const AgentThread = ({ function isErrorGroup( group: NotificationEvent[], -): group is Array> { +): group is Extract[] { // We only check the first since we know the group is the same type return group[0].type === "error"; } function isConnectionChangeGroup( group: NotificationEvent[], -): group is Array> { +): group is Extract[] { // We only check the first since we know the group is the same type return group[0].type === "connection_change"; } function isSessionNotificationGroup( group: NotificationEvent[], -): group is Array< - Extract -> { +): group is Extract[] { // We only check the first since we know the group is the same type return group[0].type === "session_notification"; } diff --git a/frontend/src/components/chat/acp/utils.ts b/frontend/src/components/chat/acp/utils.ts index 609563a2bf1..af021e1b2ba 100644 --- a/frontend/src/components/chat/acp/utils.ts +++ b/frontend/src/components/chat/acp/utils.ts @@ -3,7 +3,7 @@ import type { NotificationDataOf, SessionNotificationEventData } from "./types"; export function isToolCalls( group: SessionNotificationEventData[], -): group is Array> { +): group is NotificationDataOf<"tool_call" | "tool_call_update">[] { // We only check the first since we know the group is the same type const first = group[0]; return ( @@ -14,7 +14,7 @@ export function isToolCalls( export function isAgentThoughts( group: SessionNotificationEventData[], -): group is Array> { +): group is NotificationDataOf<"agent_thought_chunk">[] { // We only check the first since we know the group is the same type const first = group[0]; return first.sessionUpdate === "agent_thought_chunk"; @@ -22,7 +22,7 @@ export function isAgentThoughts( export function isUserMessages( group: SessionNotificationEventData[], -): group is Array> { +): group is NotificationDataOf<"user_message_chunk">[] { // We only check the first since we know the group is the same type const first = group[0]; return first.sessionUpdate === "user_message_chunk"; @@ -30,7 +30,7 @@ export function isUserMessages( export function isAgentMessages( group: SessionNotificationEventData[], -): group is Array> { +): group is NotificationDataOf<"agent_message_chunk">[] { // We only check the first since we know the group is the same type const first = group[0]; return first.sessionUpdate === "agent_message_chunk"; @@ -38,7 +38,7 @@ export function isAgentMessages( export function isPlans( group: SessionNotificationEventData[], -): group is Array> { +): group is NotificationDataOf<"plan">[] { // We only check the first since we know the group is the same type const first = group[0]; return first.sessionUpdate === "plan"; diff --git a/frontend/src/components/data-table/__tests__/data-table.test.tsx b/frontend/src/components/data-table/__tests__/data-table.test.tsx index 30a128c4e91..0670e67296e 100644 --- a/frontend/src/components/data-table/__tests__/data-table.test.tsx +++ b/frontend/src/components/data-table/__tests__/data-table.test.tsx @@ -18,7 +18,7 @@ describe("DataTable", () => { { id: 2, name: "Test 2" }, ]; - const columns: Array> = [ + const columns: ColumnDef[] = [ { accessorKey: "name", header: "Name" }, ]; @@ -70,7 +70,7 @@ describe("DataTable", () => { { id: 2, first: "Jim", last: "Halpert" }, ]; - const columns: Array> = [ + const columns: ColumnDef[] = [ { accessorKey: "first", header: "First" }, { accessorKey: "last", header: "Last" }, ]; diff --git a/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts b/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts index ed6455f5a83..de8f32e1724 100644 --- a/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts +++ b/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts @@ -11,7 +11,7 @@ function createSpec(spec: { encoding: Record< string, | { field: string; type?: string } - | Array<{ field: string; tooltip?: Record }> + | { field: string; tooltip?: Record }[] >; resolve?: Record; title?: string; diff --git a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts index efcc0036880..78234a54f47 100644 --- a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts +++ b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts @@ -29,7 +29,7 @@ interface GetTooltipParams { export function getTooltips( params: GetTooltipParams, -): Array> | undefined { +): StringFieldDef[] | undefined { const { formValues, xEncoding, yEncoding, colorByEncoding } = params; if (!formValues.tooltips) { @@ -73,7 +73,7 @@ export function getTooltips( // If autoTooltips is enabled, we manually add the x, y, and color columns to the tooltips if (formValues.tooltips.auto) { - const tooltips: Array> = []; + const tooltips: StringFieldDef[] = []; const xTooltip = addTooltip( xEncoding, formValues.general?.xColumn?.type || "string", @@ -105,7 +105,7 @@ export function getTooltips( // Selected tooltips from the form. const selectedTooltips = formValues.tooltips.fields ?? []; - const tooltips: Array> = []; + const tooltips: StringFieldDef[] = []; // We need to find the matching columns for the selected tooltips if they exist // Otherwise, we can add them without other parameters diff --git a/frontend/src/components/data-table/charts/components/chart-items.tsx b/frontend/src/components/data-table/charts/components/chart-items.tsx index 5cce1345c01..1354ce777a4 100644 --- a/frontend/src/components/data-table/charts/components/chart-items.tsx +++ b/frontend/src/components/data-table/charts/components/chart-items.tsx @@ -103,7 +103,7 @@ const ColumnSelectorWithAggregation: React.FC<{ selectedDataType?: SelectedDataType; }; defaultAggregation?: AggregationFn; - columns: Array<{ name: string; type: DataType }>; + columns: { name: string; type: DataType }[]; binFieldName: FieldName; }> = ({ columnFieldName, diff --git a/frontend/src/components/data-table/charts/components/form-fields.tsx b/frontend/src/components/data-table/charts/components/form-fields.tsx index ffc6ddd6c34..06b0c6320f9 100644 --- a/frontend/src/components/data-table/charts/components/form-fields.tsx +++ b/frontend/src/components/data-table/charts/components/form-fields.tsx @@ -86,7 +86,7 @@ export const ColumnSelector = ({ includeCountField = true, }: { fieldName: FieldName; - columns: Array<{ name: string; type: DataType }>; + columns: { name: string; type: DataType }[]; onValueChange?: (fieldName: string, type: DataType | undefined) => void; includeCountField?: boolean; }) => { @@ -197,7 +197,7 @@ export const SelectField = ({ }: { fieldName: FieldName; label: string; - options: Array<{ display: React.ReactNode; value: string }>; + options: { display: React.ReactNode; value: string }[]; defaultValue: string; }) => { const form = useFormContext(); diff --git a/frontend/src/components/data-table/charts/constants.ts b/frontend/src/components/data-table/charts/constants.ts index 9e10d2ff238..b86ae912245 100644 --- a/frontend/src/components/data-table/charts/constants.ts +++ b/frontend/src/components/data-table/charts/constants.ts @@ -79,7 +79,7 @@ export const AGGREGATION_TYPE_DESCRIPTIONS: Record = { bin: "Group values into bins", }; -export const COLOR_SCHEMES: Array = [ +export const COLOR_SCHEMES: (ColorScheme | typeof DEFAULT_COLOR_SCHEME)[] = [ DEFAULT_COLOR_SCHEME, // Categorical schemes "accent", diff --git a/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx b/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx index 33440e734bf..b61578e67d7 100644 --- a/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx +++ b/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx @@ -211,7 +211,7 @@ const ColumnPreview = ({ refetchPreview, }); - const previewStats = stats && renderStats(stats, dataType, locale); + const previewStats = stats && renderStats({ stats, dataType, locale }); const chart = chart_spec && renderChart(chart_spec, theme); diff --git a/frontend/src/components/data-table/column-summary/chart-spec-model.tsx b/frontend/src/components/data-table/column-summary/chart-spec-model.tsx index 78b1075b166..d4b4ebbebc6 100644 --- a/frontend/src/components/data-table/column-summary/chart-spec-model.tsx +++ b/frontend/src/components/data-table/column-summary/chart-spec-model.tsx @@ -778,14 +778,14 @@ export class ColumnChartSpecModel { const yField = "value"; // Calculate xStart and xEnd for each value count - const newValueCounts: Array<{ + const newValueCounts: { count: number; value: string; xStart: number; xEnd: number; xMid: number; proportion: number; - }> = []; + }[] = []; let xStart = 0; for (const valueCount of valueCounts) { const xEnd = xStart + valueCount.count; diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx index e95d13335cf..d29021c15d0 100644 --- a/frontend/src/components/data-table/columns.tsx +++ b/frontend/src/components/data-table/columns.tsx @@ -117,7 +117,7 @@ export function generateColumns({ headerTooltip?: Record; showDataTypes?: boolean; calculateTopKRows?: CalculateTopKRows; -}): Array> { +}): ColumnDef[] { // Row-headers are typically index columns const rowHeadersSet = new Set(rowHeaders.map(([columnName]) => columnName)); diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx index fd822a8ea8c..752ba3fae3e 100644 --- a/frontend/src/components/data-table/data-table.tsx +++ b/frontend/src/components/data-table/data-table.tsx @@ -48,7 +48,7 @@ interface DataTableProps extends Partial { wrapperClassName?: string; className?: string; maxHeight?: number; - columns: Array>; + columns: ColumnDef[]; data: TData[]; // Sorting manualSorting?: boolean; // server-side sorting diff --git a/frontend/src/components/data-table/date-popover.tsx b/frontend/src/components/data-table/date-popover.tsx index e50ce4c33c3..448683a69d5 100644 --- a/frontend/src/components/data-table/date-popover.tsx +++ b/frontend/src/components/data-table/date-popover.tsx @@ -124,7 +124,7 @@ const RelativeTime = ({ date }: { date: Date }) => { const differenceInSeconds = (currentTime.getTime() - date.getTime()) / 1000; // Define time units with their thresholds and conversion factors - const timeUnits: Array<[number, number, string]> = [ + const timeUnits: [number, number, string][] = [ [60, 1, "second"], // Less than 60 seconds [60, 60, "minute"], // Less than 60 minutes [24, 3600, "hour"], // Less than 24 hours diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsx index ab7e624baec..270e252d0d9 100644 --- a/frontend/src/components/data-table/download-actions.tsx +++ b/frontend/src/components/data-table/download-actions.tsx @@ -167,7 +167,7 @@ export const DownloadAs: React.FC = (props) => { ); }; -function fetchJson(url: string): Promise>> { +function fetchJson(url: string): Promise[]> { return fetch(url).then((res) => { if (!res.ok) { throw new Error(res.statusText); diff --git a/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts b/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts index 49e849dec3b..c78c4ecc86d 100644 --- a/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts +++ b/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts @@ -26,7 +26,7 @@ function createMockColumn(id: string): Column { function createMockRow( id: string, - cells: Array>, + cells: Cell[], ): Row { return { id, @@ -43,8 +43,8 @@ function createMockRow( } function createMockTable( - rows: Array>, - columns: Array>, + rows: Row[], + columns: Column[], ): Table { return { getRow: (id: string) => rows.find((row) => row.id === id), diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx index 55e979b6a8d..3a2e276578c 100644 --- a/frontend/src/components/data-table/renderers.tsx +++ b/frontend/src/components/data-table/renderers.tsx @@ -32,7 +32,7 @@ export function renderTableHeader( return null; } - const renderHeaderGroup = (headerGroups: Array>) => { + const renderHeaderGroup = (headerGroups: HeaderGroup[]) => { return headerGroups.map((headerGroup) => headerGroup.headers.map((header) => { const { className, style } = getPinningStyles(header.column); @@ -70,7 +70,7 @@ export function renderTableHeader( interface DataTableBodyProps { table: Table; - columns: Array>; + columns: ColumnDef[]; rowViewerPanelOpen: boolean; getRowIndex?: (row: TData, idx: number) => number; viewedRowIdx?: number; @@ -96,7 +96,7 @@ export const DataTableBody = ({ function applyHoverTemplate( template: string, - cells: Array>, + cells: Cell[], ): string { const variableRegex = /{{(\w+)}}/g; // Map column id -> stringified value @@ -113,7 +113,7 @@ export const DataTableBody = ({ }); } - const renderCells = (cells: Array>) => { + const renderCells = (cells: Cell[]) => { return cells.map((cell) => { const { className, style: pinningstyle } = getPinningStyles(cell.column); const style = Object.assign( diff --git a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx index e3aed002061..2b8d274acc8 100644 --- a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx +++ b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx @@ -188,7 +188,7 @@ export const RowViewerPanel: React.FC = ({ - {fieldTypes?.map(([columnName, [dataType, externalType]]) => { + {fieldTypes?.map(([columnName, [dataType, _externalType]]) => { const columnValue = rowValues[columnName]; if (!inSearchQuery({ columnName, columnValue, searchQuery })) { diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.ts index 34241f36fe0..eb1ec444b96 100644 --- a/frontend/src/components/data-table/types.ts +++ b/frontend/src/components/data-table/types.ts @@ -27,9 +27,10 @@ export type ColumnHeaderStats = Record< number | string | null >; -export type FieldTypesWithExternalType = Array< - [columnName: string, [dataType: DataType, externalType: string]] ->; +export type FieldTypesWithExternalType = [ + columnName: string, + [dataType: DataType, externalType: string], +][]; export type FieldTypes = Record; export function toFieldTypes( diff --git a/frontend/src/components/datasources/column-preview.tsx b/frontend/src/components/datasources/column-preview.tsx index 0983e368830..df5319897ee 100644 --- a/frontend/src/components/datasources/column-preview.tsx +++ b/frontend/src/components/datasources/column-preview.tsx @@ -110,7 +110,8 @@ export const DatasetColumnPreview: React.FC<{ }); const stats = - preview.stats && renderStats(preview.stats, column.type, locale); + preview.stats && + renderStats({ stats: preview.stats, dataType: column.type, locale }); const chart = preview.chart_spec && renderChart(preview.chart_spec, theme); @@ -175,11 +176,13 @@ export function renderPreviewError({ ); } -export function renderStats( - stats: Partial>, - dataType: DataType, - locale: string, -) { +interface RenderStatsProps { + stats: Partial>; + dataType: DataType; + locale: string; +} + +export function renderStats({ stats, dataType, locale }: RenderStatsProps) { return (
{Object.entries(stats).map(([key, value]) => { diff --git a/frontend/src/components/debugger/debugger-code.tsx b/frontend/src/components/debugger/debugger-code.tsx index 988f492a1a1..c7d296799aa 100644 --- a/frontend/src/components/debugger/debugger-code.tsx +++ b/frontend/src/components/debugger/debugger-code.tsx @@ -106,7 +106,7 @@ const DebuggerInput: React.FC<{ key: "Enter", preventDefault: true, stopPropagation: true, - run: (view: EditorView) => { + run: () => { const v = value.trim().replaceAll("\n", "\\n"); if (!v) { return true; diff --git a/frontend/src/components/dependency-graph/custom-node.tsx b/frontend/src/components/dependency-graph/custom-node.tsx index 076a82053d1..da9b39a2589 100644 --- a/frontend/src/components/dependency-graph/custom-node.tsx +++ b/frontend/src/components/dependency-graph/custom-node.tsx @@ -1,7 +1,7 @@ /* Copyright 2024 Marimo. All rights reserved. */ import { useAtomValue } from "jotai"; -import React, { memo, use } from "react"; +import React, { memo, use, useId } from "react"; import { Handle, Position, useStore } from "reactflow"; import { TinyCode } from "@/components/editor/cell/TinyCode"; import { useCellIds } from "@/core/cells/cells"; @@ -23,7 +23,7 @@ const EQUALITY_CHECK = ( prevProps: CustomNodeProps, nextProps: CustomNodeProps, ) => { - const keys: Array = ["data", "selected", "id"]; + const keys: (keyof CustomNodeProps)[] = ["data", "selected", "id"]; return keys.every((key) => prevProps[key] === nextProps[key]); }; @@ -37,18 +37,25 @@ export const CustomNode = memo((props: CustomNodeProps) => { const reactFlowWidth = useStore(({ width }) => width); const edgeMarkers = use(EdgeMarkerContext); + const inputOneId = useId(); + const inputTwoId = useId(); + const outputOneId = useId(); + const outputTwoId = useId(); + const linesOfCode = cell.code.split("\n").length; return (
@@ -69,13 +76,15 @@ export const CustomNode = memo((props: CustomNodeProps) => {
diff --git a/frontend/src/components/dependency-graph/dependency-graph-minimap.tsx b/frontend/src/components/dependency-graph/dependency-graph-minimap.tsx index 93fd4bc6ea3..e7271988979 100644 --- a/frontend/src/components/dependency-graph/dependency-graph-minimap.tsx +++ b/frontend/src/components/dependency-graph/dependency-graph-minimap.tsx @@ -31,7 +31,7 @@ import { useFitToViewOnDimensionChange } from "./utils/useFitToViewOnDimensionCh interface Props { cellIds: CellId[]; variables: Variables; - cellAtoms: Array>; + cellAtoms: Atom[]; } const elementsBuilder = new VerticalElementsBuilder(); @@ -57,7 +57,7 @@ export const DependencyGraphMinimap: React.FC> = ({ // If the cellIds change, update the nodes. const syncChanges = useEvent( - (elements: { nodes: Array>; edges: Edge[] }) => { + (elements: { nodes: Node[]; edges: Edge[] }) => { setNodes(elements.nodes); setEdges([]); }, diff --git a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx index ea8482805f9..1ce8a069d8c 100644 --- a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx +++ b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx @@ -36,7 +36,7 @@ import { useFitToViewOnDimensionChange } from "./utils/useFitToViewOnDimensionCh interface Props { cellIds: CellId[]; variables: Variables; - cellAtoms: Array>; + cellAtoms: Atom[]; layoutDirection: LayoutDirection; settings: GraphSettings; } @@ -74,7 +74,7 @@ export const DependencyGraphTree: React.FC> = ({ const api = useReactFlow(); const syncChanges = useEvent( - (elements: { nodes: Array>; edges: Edge[] }) => { + (elements: { nodes: Node[]; edges: Edge[] }) => { // Layout the elements const result = layoutElements({ nodes: elements.nodes, diff --git a/frontend/src/components/dependency-graph/dependency-graph.tsx b/frontend/src/components/dependency-graph/dependency-graph.tsx index db0afa68252..15046620d74 100644 --- a/frontend/src/components/dependency-graph/dependency-graph.tsx +++ b/frontend/src/components/dependency-graph/dependency-graph.tsx @@ -18,7 +18,7 @@ import "./dependency-graph.css"; interface Props { cellIds: CellId[]; variables: Variables; - cellAtoms: Array>; + cellAtoms: Atom[]; children?: React.ReactNode; } diff --git a/frontend/src/components/dependency-graph/elements.ts b/frontend/src/components/dependency-graph/elements.ts index c8bbd8bf288..263d290f32d 100644 --- a/frontend/src/components/dependency-graph/elements.ts +++ b/frontend/src/components/dependency-graph/elements.ts @@ -22,10 +22,10 @@ export function getNodeHeight(linesOfCode: number) { interface ElementsBuilder { createElements: ( cellIds: CellId[], - cellAtoms: Array>, + cellAtoms: Atom[], variables: Variables, hidePureMarkdown: boolean, - ) => { nodes: Array>; edges: Edge[] }; + ) => { nodes: Node[]; edges: Edge[] }; } export class VerticalElementsBuilder implements ElementsBuilder { @@ -69,12 +69,12 @@ export class VerticalElementsBuilder implements ElementsBuilder { createElements( cellIds: CellId[], - cellAtoms: Array>, + cellAtoms: Atom[], variables: Variables, - hidePureMarkdown: boolean, + _hidePureMarkdown: boolean, ) { let prevY = 0; - const nodes: Array> = []; + const nodes: Node[] = []; const edges: Edge[] = []; for (const [cellId, cellAtom] of Arrays.zip(cellIds, cellAtoms)) { const node = this.createNode(cellId, cellAtom, prevY); @@ -135,11 +135,11 @@ export class TreeElementsBuilder implements ElementsBuilder { createElements( cellIds: CellId[], - cellAtoms: Array>, + cellAtoms: Atom[], variables: Variables, hidePureMarkdown: boolean, ) { - const nodes: Array> = []; + const nodes: Node[] = []; const edges: Edge[] = []; const nodesWithEdges = new Set(); diff --git a/frontend/src/components/dependency-graph/utils/changes.ts b/frontend/src/components/dependency-graph/utils/changes.ts index 4c8af99aa2a..379c27177a7 100644 --- a/frontend/src/components/dependency-graph/utils/changes.ts +++ b/frontend/src/components/dependency-graph/utils/changes.ts @@ -11,8 +11,8 @@ import type { export function getNodeChanges( prevNodes: Node[], nextNodes: Node[], -): Array { - const changes: Array = []; +): (NodeAddChange | NodeRemoveChange)[] { + const changes: (NodeAddChange | NodeRemoveChange)[] = []; const prevNodeIds = new Set(prevNodes.map((node) => node.id)); const nextNodeIds = new Set(nextNodes.map((node) => node.id)); @@ -33,8 +33,8 @@ export function getNodeChanges( export function getEdgeChanges( prevEdges: Edge[], nextEdges: Edge[], -): Array { - const changes: Array = []; +): (EdgeAddChange | EdgeRemoveChange)[] { + const changes: (EdgeAddChange | EdgeRemoveChange)[] = []; const prevEdgeIds = new Set(prevEdges.map((edge) => edge.id)); const nextEdgeIds = new Set(nextEdges.map((edge) => edge.id)); diff --git a/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx index 7ea5bb7510a..dd96aa920c4 100644 --- a/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx +++ b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx @@ -18,7 +18,7 @@ function getRootScrollableElement() { * React hook to find the active header in the outline */ export function useActiveOutline( - headerElements: Array, + headerElements: (readonly [HTMLElement, string])[], ) { const [activeHeaderId, setActiveHeaderId] = useState( undefined, diff --git a/frontend/src/components/editor/chrome/panels/packages-panel.tsx b/frontend/src/components/editor/chrome/panels/packages-panel.tsx index 9d82f5fc2b2..0e3a80b5673 100644 --- a/frontend/src/components/editor/chrome/panels/packages-panel.tsx +++ b/frontend/src/components/editor/chrome/panels/packages-panel.tsx @@ -300,7 +300,7 @@ const InstallPackageForm: React.FC<{ const PackagesList: React.FC<{ onSuccess: () => void; - packages: Array<{ name: string; version: string }>; + packages: { name: string; version: string }[]; }> = ({ onSuccess, packages }) => { if (packages.length === 0) { return ( diff --git a/frontend/src/components/editor/columns/storage.ts b/frontend/src/components/editor/columns/storage.ts index 7ff03db1187..430f6d15cb8 100644 --- a/frontend/src/components/editor/columns/storage.ts +++ b/frontend/src/components/editor/columns/storage.ts @@ -7,7 +7,7 @@ import { NotebookScopedLocalStorage } from "@/utils/localStorage"; const BASE_KEY = "marimo:notebook-col-sizes"; interface ColumnSizes { - widths: Array; + widths: (number | "contentWidth")[]; } function initialState(): ColumnSizes { diff --git a/frontend/src/components/editor/database/__tests__/as-code.test.ts b/frontend/src/components/editor/database/__tests__/as-code.test.ts index 49c84df5d60..4b5e640b806 100644 --- a/frontend/src/components/editor/database/__tests__/as-code.test.ts +++ b/frontend/src/components/editor/database/__tests__/as-code.test.ts @@ -209,7 +209,7 @@ describe("generateDatabaseCode", () => { }; describe("basic connections", () => { - const testCases: Array<[string, DatabaseConnection, ConnectionLibrary]> = [ + const testCases: [string, DatabaseConnection, ConnectionLibrary][] = [ ["postgres with SQLModel", basePostgres, "sqlmodel"], ["postgres with SQLAlchemy", basePostgres, "sqlalchemy"], ["mysql with SQLModel", baseMysql, "sqlmodel"], @@ -243,7 +243,7 @@ describe("generateDatabaseCode", () => { ["databricks with ibis", databricksConnection, "ibis"], ]; - it.each(testCases)("%s", (name, connection, orm) => { + it.each(testCases)("%s", (_name, connection, orm) => { expect(generateDatabaseCode(connection, orm)).toMatchSnapshot(); }); }); @@ -315,7 +315,7 @@ describe("generateDatabaseCode", () => { }, "duckdb", ], - ])("%s", (name, connection, orm) => { + ])("%s", (_name, connection, orm) => { expect( generateDatabaseCode(connection, orm as ConnectionLibrary), ).toMatchSnapshot(); @@ -323,7 +323,7 @@ describe("generateDatabaseCode", () => { }); describe("edge cases", () => { - const testCases: Array<[string, DatabaseConnection, string]> = [ + const testCases: [string, DatabaseConnection, string][] = [ [ "ENV with special chars SQLModel", { @@ -527,7 +527,7 @@ describe("generateDatabaseCode", () => { ], ]; - it.each(testCases)("%s", (name, connection, orm) => { + it.each(testCases)("%s", (_name, connection, orm) => { expect( generateDatabaseCode(connection, orm as ConnectionLibrary), ).toMatchSnapshot(); @@ -571,7 +571,7 @@ describe("generateDatabaseCode", () => { credentials_json: '{"type": "service_account", "project_id": "test"', }, ], - ])("%s", (name, connection) => { + ])("%s", (_name, connection) => { expect(generateDatabaseCode(connection, "sqlmodel")).toMatchSnapshot(); expect(generateDatabaseCode(connection, "sqlalchemy")).toMatchSnapshot(); }); @@ -614,7 +614,7 @@ describe("generateDatabaseCode", () => { "sqlmodel", ), ], - ])("%s", (name, fn) => { + ])("%s", (_name, fn) => { expect(fn).toThrow(); }); }); diff --git a/frontend/src/components/editor/navigation/clipboard.ts b/frontend/src/components/editor/navigation/clipboard.ts index d41dd770804..eeb543ea238 100644 --- a/frontend/src/components/editor/navigation/clipboard.ts +++ b/frontend/src/components/editor/navigation/clipboard.ts @@ -11,9 +11,9 @@ import { Logger } from "@/utils/Logger"; const MARIMO_CELL_MIMETYPE = "web application/x-marimo-cell"; interface ClipboardCellData { - cells: Array<{ + cells: { code: string; - }>; + }[]; version: "1.0"; } diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsx index d258c838a78..01536eba564 100644 --- a/frontend/src/components/editor/output/ConsoleOutput.tsx +++ b/frontend/src/components/editor/output/ConsoleOutput.tsx @@ -28,7 +28,7 @@ interface Props { cellId: CellId; cellName: string; className?: string; - consoleOutputs: Array>; + consoleOutputs: WithResponse[]; stale: boolean; debuggerActive: boolean; onRefactorWithAI?: (opts: { prompt: string }) => void; diff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsx index fc35db6564c..8368bbff56a 100644 --- a/frontend/src/components/editor/output/JsonOutput.tsx +++ b/frontend/src/components/editor/output/JsonOutput.tsx @@ -200,7 +200,7 @@ const LEAF_RENDERERS = { }; // eslint-disable-next-line @typescript-eslint/no-explicit-any -const MIME_TYPES: Array> = Object.entries(LEAF_RENDERERS).map( +const MIME_TYPES: DataType[] = Object.entries(LEAF_RENDERERS).map( ([leafType, render]) => ({ is: (value) => typeof value === "string" && value.startsWith(leafType), PostComponent: PyCopyButton, diff --git a/frontend/src/components/editor/renderers/grid-layout/types.ts b/frontend/src/components/editor/renderers/grid-layout/types.ts index 23d2da57e56..96d65e0c10d 100644 --- a/frontend/src/components/editor/renderers/grid-layout/types.ts +++ b/frontend/src/components/editor/renderers/grid-layout/types.ts @@ -68,13 +68,13 @@ export interface GridLayout extends Omit { /** * The cells in the layout. */ - cells: Array<{ + cells: { i: string; x: number; y: number; w: number; h: number; - }>; + }[]; scrollableCells: Set; diff --git a/frontend/src/components/editor/renderers/plugins.ts b/frontend/src/components/editor/renderers/plugins.ts index 425d2cb0459..2112da40c02 100644 --- a/frontend/src/components/editor/renderers/plugins.ts +++ b/frontend/src/components/editor/renderers/plugins.ts @@ -8,7 +8,7 @@ import { VerticalLayoutPlugin } from "./vertical-layout/vertical-layout"; // If more renderers are added, we may want to consider lazy loading them. // eslint-disable-next-line @typescript-eslint/no-explicit-any -export const cellRendererPlugins: Array> = [ +export const cellRendererPlugins: ICellRendererPlugin[] = [ GridLayoutPlugin, SlidesLayoutPlugin, VerticalLayoutPlugin, diff --git a/frontend/src/components/editor/renderers/types.ts b/frontend/src/components/editor/renderers/types.ts index e99c172d68c..cda4359b1ad 100644 --- a/frontend/src/components/editor/renderers/types.ts +++ b/frontend/src/components/editor/renderers/types.ts @@ -17,7 +17,7 @@ export interface ICellRendererProps { /** * The cells to render. */ - cells: Array; + cells: (CellRuntimeState & CellData)[]; /** * The layout configuration. diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx index 933ab5d9dca..69680673e03 100644 --- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx +++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx @@ -198,7 +198,7 @@ const ActionButtons: React.FC<{ actions.push( @@ -213,7 +213,7 @@ const ActionButtons: React.FC<{ actions.push( @@ -222,7 +222,7 @@ const ActionButtons: React.FC<{ , @@ -239,7 +239,7 @@ const ActionButtons: React.FC<{ // as this may be used in custom css to hide/show the actions dropdown return (
, -): Array<[number, Array]> { + cells: (CellRuntimeState & CellData)[], +): [number, (CellRuntimeState & CellData)[]][] { // Group cells by column - const cellsByColumn = new Map>(); + const cellsByColumn = new Map(); let lastSeenColumn = 0; cells.forEach((cell) => { const column = cell.config.column ?? lastSeenColumn; diff --git a/frontend/src/components/forms/form.tsx b/frontend/src/components/forms/form.tsx index b5a709719d5..079bcfcb17e 100644 --- a/frontend/src/components/forms/form.tsx +++ b/frontend/src/components/forms/form.tsx @@ -59,7 +59,7 @@ interface Props { form: UseFormReturn; schema: z.ZodType; path?: Path; - renderers: Array> | undefined; + renderers: FormRenderer[] | undefined; children?: React.ReactNode; } @@ -82,7 +82,7 @@ export function renderZodSchema( schema: z.ZodType, form: UseFormReturn, path: Path, - renderers: Array>, + renderers: FormRenderer[], ) { // Try custom renderers first for (const renderer of renderers) { @@ -330,7 +330,7 @@ export function renderZodSchema( } if (schema instanceof z.ZodDiscriminatedUnion) { - const options = schema._def.options as Array>; + const options = schema._def.options as z.ZodType[]; const discriminator = schema._def.discriminator; const optionsMap = schema._def.optionsMap; return ( @@ -392,7 +392,7 @@ export function renderZodSchema( control={form.control} name={path} render={({ field }) => { - const options = schema._def.options as Array>; + const options = schema._def.options as z.ZodType[]; let value: string = field.value; const types = options.map((option) => { return getUnionLiteral(option)._def.value; @@ -812,6 +812,6 @@ const MultiSelectFormField = ({ ); }; -function joinPath(...parts: Array): Path { +function joinPath(...parts: (string | number)[]): Path { return parts.filter((part) => part !== "").join(".") as Path; } diff --git a/frontend/src/core/ai/context/providers/error.ts b/frontend/src/core/ai/context/providers/error.ts index 0a07568f415..fe96ee34554 100644 --- a/frontend/src/core/ai/context/providers/error.ts +++ b/frontend/src/core/ai/context/providers/error.ts @@ -14,11 +14,11 @@ export interface ErrorContextItem extends AIContextItem { type: "error"; data: { type: "all-errors"; - errors: Array<{ + errors: { cellId: CellId; cellName: string; errorData: MarimoError[]; - }>; + }[]; }; } diff --git a/frontend/src/core/ai/model-registry.ts b/frontend/src/core/ai/model-registry.ts index ba5cf6f4e9e..ea327c3118f 100644 --- a/frontend/src/core/ai/model-registry.ts +++ b/frontend/src/core/ai/model-registry.ts @@ -202,7 +202,7 @@ export class AiModelRegistry { return this.modelsByProviderMap; } - getListModelsByProvider(): Array<[ProviderId, AiModel[]]> { + getListModelsByProvider(): [ProviderId, AiModel[]][] { const modelsByProvider = this.getGroupedModelsByProvider(); const arrayModels = [...modelsByProvider.entries()]; const providerToOrderIdx = getProviderMap().providerToOrderIdx; diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts index 38584444b16..634904e2544 100644 --- a/frontend/src/core/cells/cells.ts +++ b/frontend/src/core/cells/cells.ts @@ -84,14 +84,14 @@ export interface NotebookState { * * (CodeMirror types the serialized config as any.) */ - history: Array<{ + history: { name: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any serializedEditorState: any; column: CellColumnId; index: CellIndex; isSetupCell: boolean; - }>; + }[]; /** * Key of cell to scroll to; typically set by actions that re-order the cell * array. Call the SCROLL_TO_TARGET action to scroll to the specified cell @@ -1128,10 +1128,10 @@ const { // Find the start/end of the collapsed ranges const nodes = [...column.nodes]; - const rangeIndexes: Array<{ + const rangeIndexes: { start: CellIndex; end: CellIndex; - }> = []; + }[] = []; const reversedCollapseRanges = []; // Iterate in reverse order (bottom-up) to process children first @@ -1668,7 +1668,7 @@ export const getCellEditorView = (cellId: CellId) => { export function flattenTopLevelNotebookCells( state: NotebookState, -): Array { +): (CellData & CellRuntimeState)[] { const { cellIds, cellData, cellRuntime } = state; return cellIds.getColumns().flatMap((column) => column.topLevelIds.map((cellId) => ({ diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.ts index 05b9439ecef..ffb70de42f3 100644 --- a/frontend/src/core/cells/types.ts +++ b/frontend/src/core/cells/types.ts @@ -93,7 +93,7 @@ export interface CellRuntimeState { /** TOC outline */ outline: Outline | null; /** messages encoding the cell's console outputs. */ - consoleOutputs: Array>; + consoleOutputs: WithResponse[]; /** current status of the cell */ status: RuntimeState; /** whether the cell has stale inputs*/ diff --git a/frontend/src/core/codemirror/editing/commands.ts b/frontend/src/core/codemirror/editing/commands.ts index 256db3eefc7..6e308dddaed 100644 --- a/frontend/src/core/codemirror/editing/commands.ts +++ b/frontend/src/core/codemirror/editing/commands.ts @@ -3,14 +3,14 @@ import { foldAll, unfoldAll } from "@codemirror/language"; import type { Command, EditorView } from "@codemirror/view"; import type { Nullable } from "vitest"; -export type BulkCommand = (targets: Array>) => boolean; +export type BulkCommand = (targets: Nullable[]) => boolean; /** * Make a bulk command from a single {@type Command} that applies * the given command to all targets. */ export function makeBulkCommand(command: Command) { - return (targets: Array>) => { + return (targets: Nullable[]) => { let changed = false; for (const target of targets) { if (target) { diff --git a/frontend/src/core/codemirror/find-replace/navigate.ts b/frontend/src/core/codemirror/find-replace/navigate.ts index ae7c8b4a94b..3c940c9d68d 100644 --- a/frontend/src/core/codemirror/find-replace/navigate.ts +++ b/frontend/src/core/codemirror/find-replace/navigate.ts @@ -110,7 +110,7 @@ export const findPrev = findInDirection("prev"); */ export const replaceAll = searchCommand(({ query }) => { const views = getAllEditorViews(); - const undoHandlers: Array<() => void> = []; + const undoHandlers: (() => void)[] = []; for (const view of views) { if (view.state.readOnly) { continue; diff --git a/frontend/src/core/codemirror/language/languages/markdown.ts b/frontend/src/core/codemirror/language/languages/markdown.ts index c3a9d5da511..76249160bf4 100644 --- a/frontend/src/core/codemirror/language/languages/markdown.ts +++ b/frontend/src/core/codemirror/language/languages/markdown.ts @@ -155,7 +155,7 @@ export class MarkdownLanguageAdapter const tree = pythonLanguage.parser.parse(pythonCode); // This is the exact match of mo.md() signature - const enterOrder: Array<{ match: string | RegExp; stop?: boolean }> = [ + const enterOrder: { match: string | RegExp; stop?: boolean }[] = [ { match: "Script" }, { match: "ExpressionStatement" }, { match: "CallExpression" }, diff --git a/frontend/src/core/codemirror/language/utils/ast.ts b/frontend/src/core/codemirror/language/utils/ast.ts index 745c4c1874d..331619c39a7 100644 --- a/frontend/src/core/codemirror/language/utils/ast.ts +++ b/frontend/src/core/codemirror/language/utils/ast.ts @@ -10,7 +10,7 @@ export function parseArgsKwargs( code: string, ): { args: SyntaxNode[]; - kwargs: Array<{ key: string; value: string }>; + kwargs: { key: string; value: string }[]; } { // Check we are in an ArgList const name = argCursor.name; @@ -54,8 +54,8 @@ function parseArgs(argCursor: TreeCursor): SyntaxNode[] { function parseKwargs( argCursor: TreeCursor, code: string, -): Array<{ key: string; value: string }> { - const kwargs: Array<{ key: string; value: string }> = []; +): { key: string; value: string }[] { + const kwargs: { key: string; value: string }[] = []; let name = argCursor.name; do { diff --git a/frontend/src/core/codemirror/lsp/federated-lsp.ts b/frontend/src/core/codemirror/lsp/federated-lsp.ts index 87d882e3e66..32b4d976754 100644 --- a/frontend/src/core/codemirror/lsp/federated-lsp.ts +++ b/frontend/src/core/codemirror/lsp/federated-lsp.ts @@ -115,7 +115,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient { async textDocumentCodeAction( params: LSP.CodeActionParams, - ): Promise | null> { + ): Promise<(LSP.Command | LSP.CodeAction)[] | null> { const client = this.firstWithCapability("codeActionProvider"); if (client) { return client.textDocumentCodeAction(params); @@ -206,9 +206,9 @@ export class FederatedLanguageServerClient implements ILanguageServerClient { } function mergeCompletions( - results: Array< - PromiseSettledResult - >, + results: PromiseSettledResult< + LSP.CompletionList | LSP.CompletionItem[] | null + >[], ): LSP.CompletionList { const completions: LSP.CompletionItem[] = []; let isIncomplete = false; diff --git a/frontend/src/core/codemirror/lsp/lens.ts b/frontend/src/core/codemirror/lsp/lens.ts index 9570d144fc1..b9379408d61 100644 --- a/frontend/src/core/codemirror/lsp/lens.ts +++ b/frontend/src/core/codemirror/lsp/lens.ts @@ -22,10 +22,10 @@ export interface NotebookLens { reversePosition: (position: LSP.Position, cellId: CellId) => LSP.Position; /** Clip a range to the given cell */ - getEditsForNewText: (newText: string) => Array<{ + getEditsForNewText: (newText: string) => { cellId: CellId; text: string; - }>; + }[]; /** Check if a range falls within the given cell */ isInRange: (range: LSP.Range, cellId: CellId) => boolean; @@ -84,10 +84,10 @@ export function createNotebookLens( throw new Error("Cannot apply rename when there are new lines"); } - const edits: Array<{ + const edits: { cellId: CellId; text: string; - }> = []; + }[] = []; for (const [cellId, code] of Objects.entries(codes)) { if (!cellLineOffsets.has(cellId)) { diff --git a/frontend/src/core/codemirror/lsp/notebook-lsp.ts b/frontend/src/core/codemirror/lsp/notebook-lsp.ts index 4be8efc6098..29737976d32 100644 --- a/frontend/src/core/codemirror/lsp/notebook-lsp.ts +++ b/frontend/src/core/codemirror/lsp/notebook-lsp.ts @@ -300,7 +300,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient { textDocumentCodeAction( params: LSP.CodeActionParams, - ): Promise | null> { + ): Promise<(LSP.Command | LSP.CodeAction)[] | null> { const disabledCodeAction = true; if (disabledCodeAction) { return Promise.resolve(null); diff --git a/frontend/src/core/codemirror/lsp/types.ts b/frontend/src/core/codemirror/lsp/types.ts index ad64ad76e45..d34a12778a3 100644 --- a/frontend/src/core/codemirror/lsp/types.ts +++ b/frontend/src/core/codemirror/lsp/types.ts @@ -49,7 +49,7 @@ export function isClientWithNotify( export function isClientWithPlugins( client: ILanguageServerClient, ): client is ILanguageServerClient & { - plugins: Array<{ documentUri: string; view?: EditorView }>; + plugins: { documentUri: string; view?: EditorView }[]; } { return "plugins" in client; } diff --git a/frontend/src/core/codemirror/markdown/completions.ts b/frontend/src/core/codemirror/markdown/completions.ts index 89afa2634af..3b4967f5183 100644 --- a/frontend/src/core/codemirror/markdown/completions.ts +++ b/frontend/src/core/codemirror/markdown/completions.ts @@ -133,7 +133,7 @@ const latexSymbolCompletionSource: CompletionSource = (context) => { // Common LaTeX symbols with their UTF-8 equivalents const getLatexSymbolList = once((): Completion[] => { - const symbols: Array<[string, string, string]> = [ + const symbols: [string, string, string][] = [ // Greek letters ["alpha", "α", "Greek small letter alpha"], ["beta", "β", "Greek small letter beta"], diff --git a/frontend/src/core/codemirror/reactive-references/analyzer.ts b/frontend/src/core/codemirror/reactive-references/analyzer.ts index ccf5bbd5c0c..52176beba92 100644 --- a/frontend/src/core/codemirror/reactive-references/analyzer.ts +++ b/frontend/src/core/codemirror/reactive-references/analyzer.ts @@ -67,7 +67,7 @@ export function findReactiveVariables(options: { // Maps to track variable declarations and scopes const allDeclarations = new Map>(); // scope position -> variable names const scopeTypes = new Map(); // scope position -> scope type (e.g., "ClassDefinition") - const classLevelDeclarations = new Map>(); // class scope -> [varName, position] pairs + const classLevelDeclarations = new Map(); // class scope -> [varName, position] pairs // Class-level variables require special handling because they're evaluated sequentially // A variable is only available after its assignment statement completes @@ -555,7 +555,7 @@ function extractAssignmentTargets( state: EditorState; allDeclarations: Map>; scopeTypes: Map; - classLevelDeclarations: Map>; + classLevelDeclarations: Map; assignmentPosition: number; }, ) { diff --git a/frontend/src/core/codemirror/rtc/loro/awareness.ts b/frontend/src/core/codemirror/rtc/loro/awareness.ts index bc8f8033384..c8a196e67ed 100644 --- a/frontend/src/core/codemirror/rtc/loro/awareness.ts +++ b/frontend/src/core/codemirror/rtc/loro/awareness.ts @@ -302,7 +302,7 @@ const parseAwarenessUpdate = ( removed: PeerID[]; }, scopeId: ScopeId, -): Array> => { +): StateEffect[] => { const effects = []; const { updated, added } = arg; for (const update of [...updated, ...added]) { diff --git a/frontend/src/core/dom/outline.ts b/frontend/src/core/dom/outline.ts index 48800a84be1..97c143e7622 100644 --- a/frontend/src/core/dom/outline.ts +++ b/frontend/src/core/dom/outline.ts @@ -57,7 +57,7 @@ export function headingToIdentifier(heading: Element): OutlineItem["by"] { return { path: `//${heading.tagName}[contains(., "${name}")]` }; } -export function mergeOutlines(outlines: Array): Outline { +export function mergeOutlines(outlines: (Outline | null)[]): Outline { return { items: outlines.filter(Boolean).flatMap((outline) => outline.items), }; @@ -104,7 +104,7 @@ export function canCollapseOutline(outline: Outline | null): boolean { */ export function findCollapseRange( startIndex: number, - outlines: Array, + outlines: (Outline | null)[], ): [number, number] | null { // Higher header is the lowest value const getHighestHeader = (outline: Outline) => { diff --git a/frontend/src/core/errors/state.ts b/frontend/src/core/errors/state.ts index 51c250a5431..2dcc920e654 100644 --- a/frontend/src/core/errors/state.ts +++ b/frontend/src/core/errors/state.ts @@ -7,7 +7,7 @@ import { generateUUID } from "@/utils/uuid"; import type { Banner } from "../kernel/messages"; interface BannerState { - banners: Array>; + banners: Identified[]; } const { valueAtom: bannersAtom, useActions } = createReducerAndAtoms( diff --git a/frontend/src/core/islands/parse.ts b/frontend/src/core/islands/parse.ts index 28b08f1885e..77123a3988d 100644 --- a/frontend/src/core/islands/parse.ts +++ b/frontend/src/core/islands/parse.ts @@ -88,9 +88,7 @@ export function parseMarimoIslandApps(): MarimoIslandApp[] { return [...apps.values()]; } -export function createMarimoFile(app: { - cells: Array<{ code: string }>; -}): string { +export function createMarimoFile(app: { cells: { code: string }[] }): string { const lines = [ "import marimo", "app = marimo.App()", diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts index ecec604a777..b9c16c60c64 100644 --- a/frontend/src/core/kernel/messages.ts +++ b/frontend/src/core/kernel/messages.ts @@ -24,7 +24,7 @@ export type OutputChannel = schemas["CellChannel"]; export type CellOutput = schemas["CellOutput"]; export type MarimoError = Extract< CellOutput["data"], - Array<{ type: string }> + { type: string }[] >[number]; export type OutputMessage = schemas["CellOutput"]; export type CompletionOption = schemas["CompletionResult"]["options"][0]; diff --git a/frontend/src/core/variables/state.ts b/frontend/src/core/variables/state.ts index 2a12ce1325e..e8601b3c931 100644 --- a/frontend/src/core/variables/state.ts +++ b/frontend/src/core/variables/state.ts @@ -38,11 +38,11 @@ const { }, setMetadata: ( state, - metadata: Array<{ + metadata: { name: VariableName; value?: string | null; dataType?: string | null; - }>, + }[], ) => { const newVariables = { ...state }; for (const { name, value, dataType } of metadata) { diff --git a/frontend/src/core/wasm/__tests__/state.test.ts b/frontend/src/core/wasm/__tests__/state.test.ts index 65edaa11c16..d69c4050912 100644 --- a/frontend/src/core/wasm/__tests__/state.test.ts +++ b/frontend/src/core/wasm/__tests__/state.test.ts @@ -13,7 +13,7 @@ import { hasAnyOutputAtom } from "../state"; describe("hasAnyOutputAtom", () => { const createNotebookState = ( - outputs: Array, + outputs: (OutputMessage | null)[], ): NotebookState => ({ ...initialNotebookState(), cellIds: new MultiColumn([ diff --git a/frontend/src/custom.d.ts b/frontend/src/custom.d.ts index ebf84d8aab5..720d05823bf 100644 --- a/frontend/src/custom.d.ts +++ b/frontend/src/custom.d.ts @@ -20,5 +20,5 @@ interface JSON { // Improve type inference for Array.filter with BooleanConstructor interface Array { - filter(predicate: BooleanConstructor): Array>; + filter(predicate: BooleanConstructor): NonNullable[]; } diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx index a3ffc6fd68f..694e7c9f11a 100644 --- a/frontend/src/plugins/impl/DataTablePlugin.tsx +++ b/frontend/src/plugins/impl/DataTablePlugin.tsx @@ -112,7 +112,7 @@ export type CalculateTopKRows = (req: { column: string; k: number; }) => Promise<{ - data: Array<[unknown, number]>; + data: [unknown, number][]; }>; export type PreviewColumn = (opts: { column: string }) => Promise<{ @@ -221,7 +221,7 @@ type DataTableFunctions = { preview_column?: PreviewColumn; }; -type S = Array; +type S = (number | string | { rowId: string; columnName?: string })[]; export const DataTablePlugin = createPlugin("marimo-table") .withData( diff --git a/frontend/src/plugins/impl/FileUploadPlugin.tsx b/frontend/src/plugins/impl/FileUploadPlugin.tsx index be2a397d461..a28fdbace3e 100644 --- a/frontend/src/plugins/impl/FileUploadPlugin.tsx +++ b/frontend/src/plugins/impl/FileUploadPlugin.tsx @@ -31,7 +31,7 @@ interface Data { max_size: number; } -type T = Array<[string, string]>; +type T = [string, string][]; export class FileUploadPlugin implements IPlugin { tagName = "marimo-file"; diff --git a/frontend/src/plugins/impl/RefreshPlugin.tsx b/frontend/src/plugins/impl/RefreshPlugin.tsx index 760643cb64f..483090137c2 100644 --- a/frontend/src/plugins/impl/RefreshPlugin.tsx +++ b/frontend/src/plugins/impl/RefreshPlugin.tsx @@ -20,7 +20,7 @@ interface Data { * It may also be a human-readable string like "1m" or "1h" or "3h 30m". * These will be converted to seconds. */ - options: Array; + options: (string | number)[]; /** * The initial value. */ diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx index e073a95ed1b..be7104fcefa 100644 --- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx +++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx @@ -29,7 +29,7 @@ interface Data { jsUrl: string; jsHash: string; css?: string | null; - bufferPaths?: Array> | null; + bufferPaths?: (string | number)[][] | null; initialValue: T; } @@ -179,7 +179,7 @@ async function runAnyWidgetModule( el: HTMLElement, ): Promise<() => void> { const experimental: Experimental = { - invoke: async (name, msg, options) => { + invoke: async (_name, _msg, _options) => { const message = "anywidget.invoke not supported in marimo. Please file an issue at https://github.com/marimo-team/marimo/issues"; Logger.warn(message); @@ -292,7 +292,7 @@ export const visibleForTesting = { export function resolveInitialValue( raw: Record, - bufferPaths: ReadonlyArray>, + bufferPaths: readonly (readonly (string | number)[])[], ) { const out = structuredClone(raw); for (const bufferPath of bufferPaths) { diff --git a/frontend/src/plugins/impl/data-editor/types.ts b/frontend/src/plugins/impl/data-editor/types.ts index 3e48e1ab355..8ef885b9ca3 100644 --- a/frontend/src/plugins/impl/data-editor/types.ts +++ b/frontend/src/plugins/impl/data-editor/types.ts @@ -30,7 +30,7 @@ export interface ColumnEdit { } export interface Edits { - edits: Array; + edits: (PositionalEdit | RowEdit | ColumnEdit)[]; } export type ModifiedGridColumn = GridColumn & { diff --git a/frontend/src/plugins/impl/data-explorer/components/query-form.tsx b/frontend/src/plugins/impl/data-explorer/components/query-form.tsx index 1b50304db0b..9fd26c72dce 100644 --- a/frontend/src/plugins/impl/data-explorer/components/query-form.tsx +++ b/frontend/src/plugins/impl/data-explorer/components/query-form.tsx @@ -238,7 +238,7 @@ const FieldOptions = ({ return null; } - let options: Array<[string, FieldFunction[]]> = []; + let options: [string, FieldFunction[]][] = []; if (field.type === ExpandedType.QUANTITATIVE) { options = [["", QUANTITATIVE_FUNCTIONS]]; diff --git a/frontend/src/plugins/impl/data-frames/types.ts b/frontend/src/plugins/impl/data-frames/types.ts index f365f37a9d6..c7b99d93015 100644 --- a/frontend/src/plugins/impl/data-frames/types.ts +++ b/frontend/src/plugins/impl/data-frames/types.ts @@ -15,7 +15,7 @@ export type NumPyType = string; * * We cannot use a js map, since maps don't preserve keys as ints (e.g. "1" and 1 are the same key) */ -export type RawColumnDataTypes = Array<[ColumnId, [DataType, NumPyType]]>; +export type RawColumnDataTypes = [ColumnId, [DataType, NumPyType]][]; /** * Map of column Id and their data types * ES6 maps preserve keys as ints (e.g. "1" and 1 are different keys) diff --git a/frontend/src/plugins/impl/panel/PanelPlugin.tsx b/frontend/src/plugins/impl/panel/PanelPlugin.tsx index 99171fd4462..7270c9c047b 100644 --- a/frontend/src/plugins/impl/panel/PanelPlugin.tsx +++ b/frontend/src/plugins/impl/panel/PanelPlugin.tsx @@ -50,9 +50,9 @@ declare global { consume: (data: ArrayBuffer | string) => void; message: { content: { - events?: Array<{ + events?: { model?: { id?: string }; - }>; + }[]; [key: string]: unknown; }; buffers: ArrayBuffer[]; diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx index b40a8ceb1de..b4782551ce8 100644 --- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx +++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx @@ -27,7 +27,7 @@ type AxisDatum = unknown; type T = | { - points?: Array> | Plotly.PlotDatum[]; + points?: Record[] | Plotly.PlotDatum[]; indices?: number[]; range?: { x?: number[]; @@ -85,7 +85,7 @@ function initialLayout(figure: Figure): Partial { }; } -const SUNBURST_DATA_KEYS: Array = [ +const SUNBURST_DATA_KEYS: (keyof Plotly.SunburstPlotDatum)[] = [ "color", "curveNumber", "entry", @@ -279,7 +279,7 @@ PlotlyComponent.displayName = "PlotlyComponent"; */ function extractPoints( points: Plotly.PlotDatum[], -): Array> { +): Record[] { if (!points) { return []; } diff --git a/frontend/src/plugins/impl/vega/__tests__/loader.test.ts b/frontend/src/plugins/impl/vega/__tests__/loader.test.ts index 5129cdd597e..d793db61361 100644 --- a/frontend/src/plugins/impl/vega/__tests__/loader.test.ts +++ b/frontend/src/plugins/impl/vega/__tests__/loader.test.ts @@ -59,10 +59,10 @@ describe("DATE_MIDDLEWARE", () => { const csv = "Date,Value\n2024-13-45,100\n2024-02-30,200"; // When parsing the CSV - const data = parseCsvData(csv, false) as Array<{ + const data = parseCsvData(csv, false) as { Date: string; Value: number; - }>; + }[]; // Then invalid dates should remain as strings expect(typeof data[0].Date).toBe("string"); diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx index 2cff876f284..1612946802b 100644 --- a/frontend/src/plugins/impl/vega/vega-component.tsx +++ b/frontend/src/plugins/impl/vega/vega-component.tsx @@ -157,7 +157,7 @@ const LoadedVegaComponent = ({ }); const renderHelpContent = () => { - const hints: Array<[string, string]> = []; + const hints: [string, string][] = []; if (ParamNames.hasPoint(names)) { hints.push([ "Point selection", diff --git a/frontend/src/plugins/impl/vega/vega-loader.ts b/frontend/src/plugins/impl/vega/vega-loader.ts index 7159266cbad..4d9f8268392 100644 --- a/frontend/src/plugins/impl/vega/vega-loader.ts +++ b/frontend/src/plugins/impl/vega/vega-loader.ts @@ -7,7 +7,7 @@ import type { DataType } from "./vega-loader"; // Re-export the vega-loader functions to add TypeScript types export function read( - data: string | Record | Array>, + data: string | Record | Record[], format: | DataFormat | { @@ -27,7 +27,7 @@ export interface Loader { load( uri: string, options?: unknown, - ): Promise | Array>>; + ): Promise | Record[]>; sanitize(uri: string, options?: unknown): Promise<{ href: string }>; http(uri: string, options?: unknown): Promise; file(filename: string): Promise; diff --git a/frontend/src/plugins/layout/NavigationMenuPlugin.tsx b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx index 0dd8f3968bc..8a3f6f9cb5f 100644 --- a/frontend/src/plugins/layout/NavigationMenuPlugin.tsx +++ b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx @@ -35,7 +35,7 @@ interface Data { /** * The labels for each item; raw HTML. */ - items: Array; + items: (MenuItem | MenuItemGroup)[]; /** * The orientation of the menu. diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts index 53028d50ed0..e4172a3c542 100644 --- a/frontend/src/plugins/plugins.ts +++ b/frontend/src/plugins/plugins.ts @@ -54,7 +54,7 @@ import type { IStatelessPlugin } from "./stateless-plugin"; import type { IPlugin } from "./types"; // List of UI plugins -export const UI_PLUGINS: Array> = [ +export const UI_PLUGINS: IPlugin[] = [ new ButtonPlugin(), new CheckboxPlugin(), DataTablePlugin, @@ -91,7 +91,7 @@ export const UI_PLUGINS: Array> = [ ]; // List of output / layout plugins -const LAYOUT_PLUGINS: Array> = [ +const LAYOUT_PLUGINS: IStatelessPlugin[] = [ new AccordionPlugin(), new CalloutPlugin(), new CarouselPlugin(), diff --git a/frontend/src/utils/Logger.ts b/frontend/src/utils/Logger.ts index b45a40c6402..7afab9f567c 100644 --- a/frontend/src/utils/Logger.ts +++ b/frontend/src/utils/Logger.ts @@ -1,5 +1,5 @@ /* Copyright 2024 Marimo. All rights reserved. */ -/** biome-ignore-all lint/suspicious/noConsole: for debugging */ +/** biome-ignore-all lint/suspicious/noConsole: For console logging */ import { Functions } from "./functions"; diff --git a/frontend/src/utils/__tests__/dom.test.ts b/frontend/src/utils/__tests__/dom.test.ts index 314f74016bb..a40a12b80b1 100644 --- a/frontend/src/utils/__tests__/dom.test.ts +++ b/frontend/src/utils/__tests__/dom.test.ts @@ -60,14 +60,14 @@ describe("parseHtmlContent", () => { describe("ansiToPlainText", () => { test("converts ANSI color codes to plain text", () => { - const ansiString = "\x1b[31mError:\x1b[0m Something went wrong"; + const ansiString = "\u001B[31mError:\u001B[0m Something went wrong"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(`"Error: Something went wrong"`); }); test("handles multiple ANSI color codes", () => { const ansiString = - "\x1b[32mSUCCESS:\x1b[0m \x1b[34mOperation completed\x1b[0m successfully"; + "\u001B[32mSUCCESS:\u001B[0m \u001B[34mOperation completed\u001B[0m successfully"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot( `"SUCCESS: Operation completed successfully"`, @@ -76,14 +76,14 @@ describe("ansiToPlainText", () => { test("handles ANSI bold and color combinations", () => { const ansiString = - "\x1b[1;31mBOLD RED ERROR:\x1b[0m \x1b[33mWarning message\x1b[0m"; + "\u001B[1;31mBOLD RED ERROR:\u001B[0m \u001B[33mWarning message\u001B[0m"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(`"BOLD RED ERROR: Warning message"`); }); test("handles Python traceback with ANSI codes", () => { const ansiString = - "\x1b[0;36m File \"\x1b[0m\x1b[0;32mtest.py\x1b[0m\x1b[0;36m\", line \x1b[0m\x1b[0;32m1\x1b[0m\x1b[0;36m, in \x1b[0m\x1b[0;35m\x1b[0m\n\x1b[0;31mNameError\x1b[0m: name 'undefined_var' is not defined"; + "\u001B[0;36m File \"\u001B[0m\u001B[0;32mtest.py\u001B[0m\u001B[0;36m\", line \u001B[0m\u001B[0;32m1\u001B[0m\u001B[0;36m, in \u001B[0m\u001B[0;35m\u001B[0m\n\u001B[0;31mNameError\u001B[0m: name 'undefined_var' is not defined"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(` " File "test.py", line 1, in @@ -93,7 +93,7 @@ describe("ansiToPlainText", () => { test("handles error messages with background colors", () => { const ansiString = - "\x1b[41;37m CRITICAL ERROR \x1b[0m \x1b[31mSystem failure detected\x1b[0m"; + "\u001B[41;37m CRITICAL ERROR \u001B[0m \u001B[31mSystem failure detected\u001B[0m"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot( `" CRITICAL ERROR System failure detected"`, @@ -102,7 +102,7 @@ describe("ansiToPlainText", () => { test("handles complex stack trace with mixed formatting", () => { const ansiString = - 'Traceback (most recent call last):\n \x1b[36mFile "\x1b[32m/path/to/file.py\x1b[36m", line \x1b[32m42\x1b[36m, in \x1b[35mfunction_name\x1b[0m\n \x1b[31mraise ValueError("Something went wrong")\x1b[0m\n\x1b[31mValueError\x1b[0m: Something went wrong'; + 'Traceback (most recent call last):\n \u001B[36mFile "\u001B[32m/path/to/file.py\u001B[36m", line \u001B[32m42\u001B[36m, in \u001B[35mfunction_name\u001B[0m\n \u001B[31mraise ValueError("Something went wrong")\u001B[0m\n\u001B[31mValueError\u001B[0m: Something went wrong'; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(` "Traceback (most recent call last): @@ -128,7 +128,7 @@ describe("ansiToPlainText", () => { test("handles whitespace and newlines correctly", () => { const ansiString = - "\x1b[31m Error: \x1b[0m\n\n \x1b[33m Warning \x1b[0m "; + "\u001B[31m Error: \u001B[0m\n\n \u001B[33m Warning \u001B[0m "; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(` " Error: @@ -139,7 +139,7 @@ describe("ansiToPlainText", () => { test("handles JavaScript error stack trace", () => { const ansiString = - "\x1b[31mReferenceError\x1b[0m: \x1b[33mvariable\x1b[0m is not defined\n at \x1b[36mObject.\x1b[0m (\x1b[32m/path/to/script.js\x1b[0m:\x1b[33m5\x1b[0m:\x1b[33m1\x1b[0m)"; + "\u001B[31mReferenceError\u001B[0m: \u001B[33mvariable\u001B[0m is not defined\n at \u001B[36mObject.\u001B[0m (\u001B[32m/path/to/script.js\u001B[0m:\u001B[33m5\u001B[0m:\u001B[33m1\u001B[0m)"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(` "ReferenceError: variable is not defined @@ -149,7 +149,7 @@ describe("ansiToPlainText", () => { test("handles Rust panic with ANSI formatting", () => { const ansiString = - "thread '\x1b[32mmain\x1b[0m' panicked at '\x1b[31massertion failed: `(left == right)`\x1b[0m'\n \x1b[36mleft\x1b[0m: `\x1b[33m5\x1b[0m`\n \x1b[36mright\x1b[0m: `\x1b[33m10\x1b[0m`"; + "thread '\u001B[32mmain\u001B[0m' panicked at '\u001B[31massertion failed: `(left == right)`\u001B[0m'\n \u001B[36mleft\u001B[0m: `\u001B[33m5\u001B[0m`\n \u001B[36mright\u001B[0m: `\u001B[33m10\u001B[0m`"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(` "thread 'main' panicked at 'assertion failed: \`(left == right)\`' @@ -160,7 +160,7 @@ describe("ansiToPlainText", () => { test("handles mix of 8-bit and 256-color ANSI codes", () => { const ansiString = - "\x1b[38;5;196mBright Red\x1b[0m and \x1b[38;5;46mBright Green\x1b[0m text"; + "\u001B[38;5;196mBright Red\u001B[0m and \u001B[38;5;46mBright Green\u001B[0m text"; const result = ansiToPlainText(ansiString); expect(result).toMatchInlineSnapshot(`"Bright Red and Bright Green text"`); }); diff --git a/frontend/src/utils/__tests__/id-tree.test.ts b/frontend/src/utils/__tests__/id-tree.test.ts index 3fb76467d8f..925f2cd1d74 100644 --- a/frontend/src/utils/__tests__/id-tree.test.ts +++ b/frontend/src/utils/__tests__/id-tree.test.ts @@ -740,7 +740,7 @@ describe("MultiColumn", () => { }); it("creates from ids and columns", () => { - const idAndColumns: Array<[string, number | undefined | null]> = [ + const idAndColumns: [string, number | undefined | null][] = [ ["A1", 0], ["A2", 0], ["B1", 1], diff --git a/frontend/src/utils/__tests__/storage.test.ts b/frontend/src/utils/__tests__/storage.test.ts index 0cfd6185de8..b86cf9e2cf7 100644 --- a/frontend/src/utils/__tests__/storage.test.ts +++ b/frontend/src/utils/__tests__/storage.test.ts @@ -29,7 +29,7 @@ interface TestValue { interface SerializableValue { id: string; - data: Array<[string, number]>; + data: [string, number][]; } describe("adaptForLocalStorage", () => { diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.ts index 7c6c2d22486..b3107806b02 100644 --- a/frontend/src/utils/arrays.ts +++ b/frontend/src/utils/arrays.ts @@ -55,7 +55,7 @@ export function arrayShallowEquals(a: T[], b: T[]): boolean { export const Arrays = { // eslint-disable-next-line @typescript-eslint/no-explicit-any EMPTY: [] as any, - zip: (a: T[], b: U[]): Array<[T, U]> => { + zip: (a: T[], b: U[]): [T, U][] => { invariant(a.length === b.length, "Arrays must be the same length"); return a.map((item, i) => [item, b[i]]); }, diff --git a/frontend/src/utils/createReducer.ts b/frontend/src/utils/createReducer.ts index c0fb94b0049..2474da985f3 100644 --- a/frontend/src/utils/createReducer.ts +++ b/frontend/src/utils/createReducer.ts @@ -79,11 +79,7 @@ type Middleware = ( export function createReducerAndAtoms< State, RH extends ReducerHandlers>, ->( - initialState: () => State, - reducers: RH, - middleware?: Array>, -) { +>(initialState: () => State, reducers: RH, middleware?: Middleware[]) { const { reducer, createActions } = createReducer(initialState, reducers); const reducerWithMiddleware = (state: State, action: ReducerAction) => { diff --git a/frontend/src/utils/data-views.ts b/frontend/src/utils/data-views.ts index fca9b52834d..27a10e526fb 100644 --- a/frontend/src/utils/data-views.ts +++ b/frontend/src/utils/data-views.ts @@ -8,7 +8,7 @@ import { Logger } from "./Logger"; */ export function updateBufferPaths>( inputObject: T, - bufferPaths: ReadonlyArray>, + bufferPaths: readonly (readonly (string | number)[])[], buffers: readonly DataView[], ): T { // If no buffer paths, return the original object diff --git a/frontend/src/utils/edit-distance.ts b/frontend/src/utils/edit-distance.ts index 02185459c91..8156b6bdf1f 100644 --- a/frontend/src/utils/edit-distance.ts +++ b/frontend/src/utils/edit-distance.ts @@ -134,7 +134,7 @@ export function mergeArray( arr2: U[], equals: (a: T, b: U) => boolean, stub: T, -): { merged: Array; edits: EditDistanceResult } { +): { merged: (T | null)[]; edits: EditDistanceResult } { const edits = editDistanceGeneral(arr1, arr2, equals); return { merged: applyOperationsWithStub(arr1, edits.operations, stub), diff --git a/frontend/src/utils/fileToBase64.ts b/frontend/src/utils/fileToBase64.ts index 6038f95cca9..dfc89d362b9 100644 --- a/frontend/src/utils/fileToBase64.ts +++ b/frontend/src/utils/fileToBase64.ts @@ -34,7 +34,7 @@ export function blobToString( * * Returns a promised array of tuples [file name, file contents]. */ -export function filesToBase64(files: File[]): Promise> { +export function filesToBase64(files: File[]): Promise<[string, string][]> { return Promise.all( files.map((file) => blobToString(file, "base64").then( diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx index 7d2beccbfe4..9cb23467e3f 100644 --- a/frontend/src/utils/id-tree.tsx +++ b/frontend/src/utils/id-tree.tsx @@ -25,9 +25,9 @@ export type CellIndex = number & { __brand?: "CellIndex" }; export class TreeNode { public value: T; public isCollapsed: boolean; - public children: Array>; + public children: TreeNode[]; - constructor(value: T, isCollapsed: boolean, children: Array>) { + constructor(value: T, isCollapsed: boolean, children: TreeNode[]) { this.value = value; this.isCollapsed = isCollapsed; this.children = children; @@ -108,10 +108,10 @@ export class TreeNode { let uniqueId = 0; export class CollapsibleTree { - public readonly nodes: Array>; + public readonly nodes: TreeNode[]; public readonly id: CellColumnId; - private constructor(nodes: Array>, id: CellColumnId) { + private constructor(nodes: TreeNode[], id: CellColumnId) { this.nodes = nodes; this.id = id; } @@ -162,7 +162,7 @@ export class CollapsibleTree { return newTree; } - withNodes(nodes: Array>): CollapsibleTree { + withNodes(nodes: TreeNode[]): CollapsibleTree { return new CollapsibleTree(nodes, this.id); } @@ -307,7 +307,7 @@ export class CollapsibleTree { * Does not collapse the children of already collapsed nodes */ collapseAll( - collapseRanges: Array<{ id: T; until: T | undefined } | null>, + collapseRanges: ({ id: T; until: T | undefined } | null)[], ): CollapsibleTree { const nodes = [...this.nodes]; if (collapseRanges.length === 0) { @@ -541,7 +541,7 @@ export class CollapsibleTree { */ find(id: T): T[] { // We need to recursively find the node - function findNode(nodes: Array>, path: T[]): T[] { + function findNode(nodes: TreeNode[], path: T[]): T[] { for (const node of nodes) { if (node.value === id) { return [...path, id]; @@ -587,7 +587,7 @@ export class CollapsibleTree { toString(): string { let depth = 0; let result = ""; - const asString = (nodes: Array>) => { + const asString = (nodes: TreeNode[]) => { for (const node of nodes) { result += `${" ".repeat(depth * 2)}${node.toString()}\n`; depth += 1; @@ -601,9 +601,9 @@ export class CollapsibleTree { } export class MultiColumn { - private readonly columns: ReadonlyArray>; + private readonly columns: readonly CollapsibleTree[]; - constructor(columns: ReadonlyArray>) { + constructor(columns: readonly CollapsibleTree[]) { this.columns = columns; // Ensure there is always at least one column @@ -664,7 +664,7 @@ export class MultiColumn { } static fromIdsAndColumns( - idAndColumns: Array<[T, number | undefined | null]>, + idAndColumns: [T, number | undefined | null][], ): MultiColumn { // If column is undefined, use the previous column // Ensure there is always at least one column @@ -746,7 +746,7 @@ export class MultiColumn { return this.columns.length === 1; } - getColumns(): ReadonlyArray> { + getColumns(): readonly CollapsibleTree[] { return this.columns; } diff --git a/frontend/src/utils/json/json-parser.ts b/frontend/src/utils/json/json-parser.ts index 4ffef15ac73..ca41ac5653c 100644 --- a/frontend/src/utils/json/json-parser.ts +++ b/frontend/src/utils/json/json-parser.ts @@ -34,7 +34,7 @@ export function jsonParseWithSpecialChar( /(?<=\s|^|\[|,|:)(NaN|-Infinity|Infinity)(?=(?:[^"'\\]*(\\.|'([^'\\]*\\.)*[^'\\]*'|"([^"\\]*\\.)*[^"\\]*"))*[^"']*$)/g, `"${CHAR}$1${CHAR}"`, ); - return JSON.parse(value, (key, v) => { + return JSON.parse(value, (_key, v) => { if (typeof v !== "string") { return v; } @@ -54,7 +54,7 @@ export function jsonParseWithSpecialChar( } } -export function jsonToTSV(json: Array>) { +export function jsonToTSV(json: Record[]) { if (json.length === 0) { return ""; } diff --git a/frontend/src/utils/mergeRefs.ts b/frontend/src/utils/mergeRefs.ts index 115e0923d64..2996964d86e 100644 --- a/frontend/src/utils/mergeRefs.ts +++ b/frontend/src/utils/mergeRefs.ts @@ -1,6 +1,6 @@ /* Copyright 2024 Marimo. All rights reserved. */ export function mergeRefs( - ...refs: Array> + ...refs: React.Ref[] ): (value: T | null) => void { return (value) => { refs.forEach((ref) => { diff --git a/frontend/src/utils/objects.ts b/frontend/src/utils/objects.ts index e388377153d..b47b178514f 100644 --- a/frontend/src/utils/objects.ts +++ b/frontend/src/utils/objects.ts @@ -17,14 +17,14 @@ export const Objects = { /** * Type-safe Object.fromEntries */ - fromEntries(obj: Array<[K, V]>): Record { + fromEntries(obj: [K, V][]): Record { return Object.fromEntries(obj) as Record; }, /** * Type-safe Object.entries */ - entries(obj: Record): Array<[K, V]> { - return Object.entries(obj) as Array<[K, V]>; + entries(obj: Record): [K, V][] { + return Object.entries(obj) as [K, V][]; }, /** * Type-safe Object.keys diff --git a/frontend/src/utils/pluralize.ts b/frontend/src/utils/pluralize.ts index cddce434c03..765fd6aaeaf 100644 --- a/frontend/src/utils/pluralize.ts +++ b/frontend/src/utils/pluralize.ts @@ -25,7 +25,7 @@ export class PluralWords { this.words = words; } - static of(...words: Array) { + static of(...words: (PluralWord | string)[]) { return new PluralWords( words.map((word) => { if (typeof word === "string") { diff --git a/frontend/src/utils/routes.ts b/frontend/src/utils/routes.ts index ef0906d6627..461d7842c19 100644 --- a/frontend/src/utils/routes.ts +++ b/frontend/src/utils/routes.ts @@ -8,10 +8,10 @@ import { } from "path-to-regexp"; export class TinyRouter { - private routes: Array<{ + private routes: { template: string; pathFunction: MatchFunction; - }>; + }[]; constructor(templates: string[]) { this.routes = templates.map((template) => { diff --git a/frontend/src/utils/sets.ts b/frontend/src/utils/sets.ts index 16d3a4123d5..7ced73ac5d4 100644 --- a/frontend/src/utils/sets.ts +++ b/frontend/src/utils/sets.ts @@ -3,7 +3,7 @@ export const Sets = { /** * Merge multiple iterables into a single set. */ - merge(...sets: Array>): Set { + merge(...sets: Iterable[]): Set { const result = new Set(); for (const set of sets) { for (const item of set) { diff --git a/packages/llm-info/src/generate.ts b/packages/llm-info/src/generate.ts index 4a2eea315e4..af4b8bc7f3a 100644 --- a/packages/llm-info/src/generate.ts +++ b/packages/llm-info/src/generate.ts @@ -5,6 +5,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { parse } from "yaml"; import { z } from "zod"; +import { Logger } from "./simple_logger.ts"; const ROLES = ["chat", "edit", "rerank", "embed"] as const; @@ -34,7 +35,7 @@ function ensureDirectoryExists(filePath: string): void { } catch (error: any) { // Ignore error if directory already exists, otherwise rethrow if (error?.code !== "EEXIST") { - console.error("Failed to create directory:", error); + Logger.error("Failed to create directory:", error); throw error; } } @@ -53,7 +54,7 @@ function loadAndValidateModels(yamlPath: string): any[] { try { return LLMInfoSchema.parse(model); } catch (error) { - console.error(`Validation failed for model at index ${index}:`, error); + Logger.error(`Validation failed for model at index ${index}:`, error); throw new Error( `Model validation failed at index ${index}: ${JSON.stringify(model, null, 2)}`, ); @@ -76,7 +77,7 @@ function loadAndValidateProviders(yamlPath: string): any[] { try { return ProviderSchema.parse(provider); } catch (error) { - console.error(`Validation failed for provider at index ${index}:`, error); + Logger.error(`Validation failed for provider at index ${index}:`, error); throw new Error( `Provider validation failed at index ${index}: ${JSON.stringify(provider, null, 2)}`, ); @@ -113,14 +114,14 @@ async function main(): Promise { const providers = loadAndValidateProviders(providersYamlPath); writeJsonFile(providersJsonPath, { providers: providers }); - console.log( + Logger.info( `Generated ${models.length} models and ${providers.length} providers`, ); } catch (error) { - console.error("Generation failed:", error); + Logger.error("Generation failed:", error); process.exit(1); } } // Run the script -main().catch(console.error); +main().catch(Logger.error); diff --git a/packages/llm-info/src/simple_logger.ts b/packages/llm-info/src/simple_logger.ts new file mode 100644 index 00000000000..d970a7e8085 --- /dev/null +++ b/packages/llm-info/src/simple_logger.ts @@ -0,0 +1,66 @@ +/* Copyright 2025 Marimo. All rights reserved. */ + +/** biome-ignore-all lint/suspicious/noConsole: For logging */ + +declare global { + interface Window { + SimpleLogger?: SimpleLogger; + } +} + +class SimpleLogger { + name: string; + + constructor(name = "LLM Info") { + this.name = name; + } + + _log( + level: "info" | "warn" | "error" | "debug", + message: string, + ...args: any[] + ) { + const timestamp = new Date().toISOString(); + const topMessage = `${timestamp} [${this.name}] [${level.toUpperCase()}] ${message}`; + + switch (level) { + case "info": + console.info(topMessage, ...args); + break; + case "warn": + console.warn(topMessage, ...args); + break; + case "error": + console.error(topMessage, ...args); + break; + case "debug": + console.debug(topMessage, ...args); + break; + } + } + + info(message: string, ...args: any[]) { + this._log("info", message, ...args); + } + + warn(message: string, ...args: any[]) { + this._log("warn", message, ...args); + } + + error(message: string, ...args: any[]) { + this._log("error", message, ...args); + } + + debug(message: string, ...args: any[]) { + this._log("debug", message, ...args); + } +} + +function getLogger(): SimpleLogger { + if (typeof window !== "undefined") { + return window.SimpleLogger || new SimpleLogger(); + } + return new SimpleLogger(); +} + +export const Logger = getLogger(); diff --git a/packages/llm-info/tsconfig.json b/packages/llm-info/tsconfig.json index e7cb22ba186..18e2733f380 100644 --- a/packages/llm-info/tsconfig.json +++ b/packages/llm-info/tsconfig.json @@ -2,6 +2,8 @@ "extends": "@marimo-team/tsconfig/library.json", "compilerOptions": { "outDir": "./dist", - "rootDir": "./src" + "rootDir": "./src", + "allowImportingTsExtensions": true, + "noEmit": true } } diff --git a/packages/lsp/index.ts b/packages/lsp/index.ts index cbb924388a6..68ea95c67a3 100644 --- a/packages/lsp/index.ts +++ b/packages/lsp/index.ts @@ -29,21 +29,25 @@ class Logger { try { await appendFile(this.logFilePath, `${log}\n`); } catch (error) { + // biome-ignore lint/suspicious/noConsole: For printing to the console console.error("Failed to write to log file:", error); } } debug(...args: Parameters): void { + // biome-ignore lint/suspicious/noConsole: For printing to the console console.log(...args); void this.appendToLogFile("[DEBUG]", ...args); } log(...args: Parameters): void { + // biome-ignore lint/suspicious/noConsole: For printing to the console console.log(...args); void this.appendToLogFile("[INFO]", ...args); } error(...args: Parameters): void { + // biome-ignore lint/suspicious/noConsole: For printing to the console console.error(...args); void this.appendToLogFile("[ERROR]", ...args); } @@ -172,6 +176,7 @@ async function main(): Promise { const argv = parseArgs(process.argv); if (argv.help) { + // biome-ignore lint/suspicious/noConsole: For printing to the console console.log( 'Usage: node index.cjs --log-file --lsp "" [--port ]', ); diff --git a/packages/openapi/convert_types.js b/packages/openapi/convert_types.js index d4aab91dc39..30e4fbbafaa 100644 --- a/packages/openapi/convert_types.js +++ b/packages/openapi/convert_types.js @@ -1,3 +1,5 @@ +/* Copyright 2024 Marimo. All rights reserved. */ +/** biome-ignore-all lint/suspicious/noConsole: for debugging */ // @ts-check import * as fs from "node:fs"; import * as process from "node:process";