{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-io",
  "title": "Data Grid IO",
  "author": "gridcn",
  "description": "Import/export add-on for the gridcn data grid: xlsx and csv, with delimiter detection and preview. New user-facing strings live under `labels.io` (see lib/labels.ts DataGridIOLabels) — export button/menu, import dialog (file picker, header-row toggle, delimiter select, column mapping, preview, errors).",
  "dependencies": [
    "hucre@1.1.0",
    "papaparse@^5.7.0",
    "lucide-react@^1.46.0"
  ],
  "devDependencies": [
    "@types/papaparse@^5.5.2"
  ],
  "registryDependencies": [
    "@gridcn/data-grid",
    "@gridcn/dropzone",
    "dialog",
    "select",
    "table",
    "dropdown-menu",
    "button",
    "checkbox",
    "label"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-io/data-grid-io.ts",
      "content": "/** Public entry point for the data-grid-io add-on — the only module consumers should import from. */\n\nexport { exportGrid, exportRows, buildExportRows, rowsToCsv, type RowsToCsvOptions, type ExportGridOptions, type ExportOutput, type ExportCellValue, type ExportCellContext, type FormatExportCell, type ExportRowsOptions, type BuildExportRowsOptions, type ExportSource, type ExportSourceContext, type ExportProgress, type ExportResult } from \"./export-grid\";\nexport { useDataGridExport, type UseDataGridExportResult } from \"./use-data-grid-export\";\n\nexport { printGrid, type PrintGridOptions, type PrintGridResult, type PrintPaperSize } from \"./print-grid\";\nexport { useDataGridPrint, type UseDataGridPrintResult } from \"./use-data-grid-print\";\nexport { DataGridPrintButton, type DataGridPrintButtonProps } from \"./print-button\";\n\nexport { parseImportFile, DEFAULT_IMPORT_LIMITS, IMPORT_CSV_ENCODINGS, type ParsedImportFile, type ParseImportFileOptions, type ImportLimits, type CsvDelimiter, type ImportCsvEncoding, type ImportValueMode } from \"./parse-import-file\";\nexport { matchImportColumns, applyImportOptions, type ImportDefaults } from \"./match-import-column\";\nexport { buildImportedRows, IMPORT_CANCELLED_MESSAGE, type ImportColumnMapping, type BuildImportedRowsOptions, type BuildImportedRowsResult, type ImportRejectedCell, type ProcessCellFromText } from \"./build-imported-rows\";\nexport {\n  useDataGridImportPreview,\n  type ImportFileState,\n  type ImportTargetColumn,\n  type ImportErrorKey,\n  type UseDataGridImportPreviewOptions,\n  type BuildImportOptions,\n  type ParseFile,\n  type ProcessImportRows,\n  type UseDataGridImportPreviewResult,\n} from \"./use-data-grid-import\";\nexport { DataGridImportDialog, type DataGridImportDialogProps, type ImportContext } from \"./import-dialog\";\nexport type { CheckImport, ImportCheckAnswer } from \"./import-check\";\n\nexport { DataGridExportButton, type DataGridExportButtonProps } from \"./export-button\";\nexport { DataGridImportButton, type DataGridImportButtonProps } from \"./import-button\";\n",
      "type": "registry:component",
      "target": "components/data-grid-io/data-grid-io.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/export-grid.ts",
      "content": "import { sanitizeFormulaCell } from \"@/registry/default/components/data-grid/data-grid\";\nimport { columnLabelText, dataIndexAt, getSelectedViewRows, isDev, keepsCheckedRows, leafViewOf, type DataGridReadState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { normalizeLimit } from \"./normalize-limit\";\nimport type { CsvDelimiter } from \"./parse-import-file\";\nimport {\n  DEFAULT_SOURCE_MAX_BYTES,\n  DEFAULT_SOURCE_MAX_ROWS,\n  MAX_CELL_TEXT,\n  NEVER_ABORTED,\n  SLICE_ROWS,\n  exportCellSize,\n  exportRows,\n  mapExportRow,\n  resolveExportColumns,\n  settlePending,\n  type PendingCell,\n  type ExportCell,\n  type ExportCellContext,\n  type ExportCellValue,\n  type ExportProgress,\n  type ExportResult,\n  type ExportRowsOptions,\n  type ExportSource,\n  type ExportSourceContext,\n  type FormatExportCell,\n  type FormatExportCellSync,\n} from \"./export-source\";\n\nconst BOM = String.fromCharCode(0xfeff);\nconst CSV_EOL = \"\\r\\n\";\n\n/** Rows an Excel worksheet holds, header row included. */\nconst XLSX_MAX_ROWS = 1_048_576;\n\n/** Cells one xlsx source export holds; the writer joins the sheet into one string. */\nconst XLSX_MAX_CELLS = 5_000_000;\n\nconst INVALID_SHEET_NAME = /[[\\]:*?/\\\\]/;\n\nexport { MAX_CELL_TEXT, exportRows };\n\n/** How an XLSX file is written: `\"buffered\"` builds the workbook in one call, `\"stream\"` serializes each slice of rows as it arrives. */\nexport type XlsxWriterMode = \"buffered\" | \"stream\";\n\n/** Where an export delivers its file instead of the browser download. */\nexport type ExportOutput = (file: Blob, ctx: { fileName: string; format: \"csv\" | \"xlsx\"; signal: AbortSignal }) => void | Promise<void>;\n\n/** Which rows an export covers; see {@link ExportGridOptions.scope}. */\nexport type ExportScope = \"view\" | \"page\" | \"all\" | \"selection\" | \"checked-rows\" | \"ranges\";\n\n/** Column selection and cell formatting shared by every export. */\nexport type ExportShapeOptions<TData = unknown, TFormat = FormatExportCell<TData>> = {\n  /** Header text per column id, replacing the column's label in the header row. A column without an entry keeps its label. */\n  headers?: Readonly<Record<string, string>>;\n  /** Column ids to export, in this order. Hidden grid columns are allowed. Default: the visible columns in view order. An unknown id throws a `RangeError` before any row is read or fetched. With `source`, the source receives the same ids as `columnIds`. */\n  columns?: readonly string[];\n  /** Replaces the value of each exported cell. Runs once per cell after the cell type made its text (`text` holds that default). Return `null` or `undefined` for an empty cell. CSV writes numbers and booleans as text and Dates as ISO 8601; XLSX keeps numbers, booleans and Dates typed. Without `formatCell`, XLSX writes `number`, `date`, and `checkbox` columns typed and every other column as text. A string stays text, cut at 32,767 characters. A number that is not finite and an invalid Date make an empty cell. A throw rejects the export. `exportGrid` and `buildXlsx` also accept a hook that returns a promise: they await the promises of each slice of rows together, in groups of at most 10,000 cells, and `ctx.signal` aborts with the export. Load data for many cells in `source`; use an async hook for a value that one cell needs. `buildCsv` is synchronous and throws a `TypeError` for a promise. */\n  formatCell?: TFormat;\n};\n\n/** Options for {@link buildCsv}. */\nexport type BuildCsvOptions<TData = unknown> = ExportShapeOptions<TData, FormatExportCellSync<TData>> & {\n  /** Row scope, same semantics as {@link ExportGridOptions.scope}; default 'view'. */\n  scope?: ExportScope;\n  /** Whether to emit a header row; default true. */\n  includeHeaders?: boolean;\n  /** CSV field delimiter; default ','. */\n  csvDelimiter?: CsvDelimiter;\n  /** Prefix the file with a UTF-8 BOM; default `true`. */\n  csvBom?: boolean;\n  /** Prefix formula-like cells with a single quote; default `true`. */\n  sanitizeFormulas?: boolean;\n  /** Same row cap as {@link ExportGridOptions.maxRows}. */\n  maxRows?: number;\n};\n\n/** Options for {@link exportGrid}. */\nexport type ExportGridOptions<TData = unknown> = ExportShapeOptions<TData> & {\n  /** Receives the finished file instead of the browser download. The grid builds no object URL. `fileName` carries the extension. A rejection rejects the export, and an aborted `signal` rejects before `output` runs. Works for loaded rows, `source`, and both formats. */\n  output?: ExportOutput;\n  /** 'xlsx' via lazily-imported hucre, or hand-rolled RFC4180 'csv' (default). */\n  format?: \"xlsx\" | \"csv\";\n  /** 'view' (default) exports the current sort/filter order, every page of a paged grid; 'page' exports only the shown page; 'all' ignores view order and exports every row in `data` order; 'selection' exports only the selected rows, in view order; 'checked-rows' exports only the checked rows; 'ranges' exports only the rows the cell ranges cover, and ignores checked rows. */\n  scope?: ExportScope;\n  /** Whether to emit a header row; default true. */\n  includeHeaders?: boolean;\n  /** CSV field delimiter; default ','. Ignored for xlsx. */\n  csvDelimiter?: CsvDelimiter;\n  /**\n   * Prefix the CSV with a UTF-8 BOM (`\\uFEFF`); default `true`. Excel only detects UTF-8 when the\n   * file starts with a BOM — without it, umlauts and other non-ASCII characters open as mojibake.\n   * Set `false` when a downstream consumer chokes on a leading BOM character.\n   */\n  csvBom?: boolean;\n  /**\n   * Prefix formula-like CSV cells (leading `=`, `+`, `-`, `@`, TAB, or CR; plain numbers exempt) with\n   * a single quote so Excel/LibreOffice/Sheets read them as text instead of executing them;\n   * default `true`. Set `false` when a downstream consumer expects the raw string.\n   * XLSX exports are unaffected (string cells never run as formulas).\n   */\n  sanitizeFormulas?: boolean;\n  /** Download file name, without extension; default 'export'. */\n  fileName?: string;\n  /** How XLSX is written; default `\"buffered\"`. `\"stream\"` serializes each slice of 1,000 rows to XML as it arrives and drops the cell objects. The writer keeps the serialized rows until the file is built, so peak memory stays close to `\"buffered\"`. The file has the same cells, cut, sheet limits, `maxBytes`, and abort checks. Ignored for csv. */\n  xlsxWriter?: XlsxWriterMode;\n  /** Name of the single sheet inside the xlsx file; default 'Sheet1'. Ignored for csv. An invalid Excel sheet name (empty, over 31 characters, `[]:*?/\\`, a leading or trailing `'`, `history` in any case) rejects. */\n  sheetName?: string;\n  /** Caps the number of data rows exported (the header row is not counted); when the scope exceeds the cap, the export is truncated with a dev-only warning. With `source` the default is 1,000,000, and an xlsx file also stops at the Excel sheet limit and at 5,000,000 cells. */\n  maxRows?: number;\n  /** Where the rows of the whole result come from, for a grid that holds one page or some loaded blocks. With `source` the export ignores `scope` and the held rows; the grid's `spec` goes to the source. */\n  source?: ExportSource;\n  /** With `source`: stop after the slice of rows that passes this many bytes of file text (xlsx: characters); default 256 MiB. The export keeps what it has and reports `truncated` when more rows follow. */\n  maxBytes?: number;\n  /** Cancels the export. The promise rejects with the signal's reason, no file downloads, and `output` does not run. */\n  signal?: AbortSignal;\n  /** With `source`: called after each batch with the running totals. */\n  onProgress?: (progress: ExportProgress) => void;\n};\n\nexport type { ExportCell, ExportCellContext, ExportCellValue, ExportProgress, ExportResult, ExportRowsOptions, ExportSource, ExportSourceContext, FormatExportCell, FormatExportCellSync };\n\nconst NEEDS_QUOTING_DEFAULT = /[\"\\r\\n]/;\n\n/** Quotes one RFC4180 CSV field when it contains the delimiter, a quote, or a line break; doubles internal quotes. */\nexport function quoteCsvField(value: string, delimiter: string): string {\n  const needsQuoting = value.includes(delimiter) || NEEDS_QUOTING_DEFAULT.test(value);\n  if (!needsQuoting) return value;\n  return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** Options for {@link rowsToCsv}. */\nexport type RowsToCsvOptions = {\n  /** Field separator. Default `\",\"`. */\n  delimiter?: string;\n  /** Prefix formula-like fields with `'` (see `sanitizeFormulaCell`). Default `true`. */\n  sanitizeFormulas?: boolean;\n};\n\n/**\n * Joins rows into an RFC4180 CSV string (CRLF line endings), quoting fields as needed. With\n * `sanitizeFormulas` (default `true`), formula-like fields get a leading `'` first (see `sanitizeFormulaCell`).\n */\nexport function rowsToCsv(rows: readonly (readonly string[])[], options: RowsToCsvOptions = {}): string {\n  const { delimiter = \",\", sanitizeFormulas = true } = options;\n  // sanitize before quoting: the apostrophe prefix itself never needs quoting\n  const field = (value: string) => quoteCsvField(sanitizeFormulas ? sanitizeFormulaCell(value) : value, delimiter);\n  return rows.map((row) => row.map(field).join(delimiter)).join(\"\\r\\n\");\n}\n\n/** Options for {@link buildExportRows}. */\nexport type BuildExportRowsOptions = {\n  /** Cell text source: `'export'` uses the cell type's `toText` (CSV/XLSX), `'display'` uses `toDisplayText ?? toText` (print). Default `'export'`. */\n  text?: \"export\" | \"display\";\n  /** Caps the number of data rows built (the header row is not counted). */\n  maxRows?: number;\n};\n\nfunction checkedViewRows(selection: DataGridReadState[\"selection\"]): number[] {\n  const rows: number[] = [];\n  for (const [start, end] of selection.rows.runs()) for (let row = start; row < end; row++) rows.push(row);\n  return rows;\n}\n\nfunction rangeViewRows(selection: DataGridReadState[\"selection\"]): number[] {\n  const rows = new Set<number>();\n  if (selection.current) {\n    for (const { y, height } of [selection.current.range, ...selection.current.rangeStack]) for (let row = y; row < y + height; row++) rows.add(row);\n  }\n  return [...rows].sort((a, b) => a - b);\n}\n\n/**\n * Resolves the data indices a scope covers (lazy holes excluded): `'view'` walks the whole sorted and filtered view (every page, collapsed groups included, group rows left out)\n * (current sort/filter order), `'page'` walks the shown page only, `'all'` walks `data` as-is, `'selection'` walks only the selected\n * rows in view order.\n */\nexport function exportDataIndices(state: DataGridReadState, scope: ExportScope): number[] {\n  const dataIndexOfViewRow = (viewRow: number) => dataIndexAt(state, viewRow) ?? -1;\n  const scoped: readonly number[] =\n    scope === \"all\"\n      ? state.data.map((_, i) => i)\n      : scope === \"checked-rows\"\n        ? checkedViewRows(state.selection).map(dataIndexOfViewRow)\n        : scope === \"ranges\"\n          ? rangeViewRows(state.selection).map(dataIndexOfViewRow)\n          : scope === \"selection\"\n            ? getSelectedViewRows(state.selection, { checkedRowsOnly: keepsCheckedRows(state) }).map(dataIndexOfViewRow)\n            : scope === \"page\"\n              ? state.viewIndex\n              : leafViewOf(state);\n  // lazy grids keep `data` sparse and a grouped view holds group rows (entries below 0): skip both before any accessor runs\n  return scoped.filter((dataRowIndex) => dataRowIndex >= 0 && state.data[dataRowIndex] !== undefined);\n}\n\n/**\n * Resolves the rows to export via the cell-type pipeline, in the requested `scope` order. With\n * `options.text: \"display\"` the cell type's display text (`toDisplayText ?? toText`) is used; the\n * default `'export'` uses `toText` (CSV/XLSX). Every scope emits all visible columns, so a\n * row-shaped export always matches its header row. Hole rows (unloaded indices of a lazy grid's\n * sparse `data`) are skipped in every scope. `options.maxRows` caps the number of rows built.\n */\nexport function buildExportRows(state: DataGridReadState, scope: ExportScope, options: BuildExportRowsOptions = {}): string[][] {\n  const { text = \"export\" } = options;\n  const dataIndices = exportDataIndices(state, scope);\n  const maxRows = options.maxRows === undefined ? undefined : normalizeLimit(options.maxRows, Number.POSITIVE_INFINITY);\n  return buildRowsAt(state, maxRows === undefined ? dataIndices : dataIndices.slice(0, maxRows), text) as string[][];\n}\n\nfunction buildRowsAt<TData>(\n  state: DataGridReadState,\n  dataIndices: readonly number[],\n  text: \"export\" | \"display\",\n  columns: readonly ExportColumn[] = state.visibleColumns,\n  formatCell?: FormatExportCellSync<TData>,\n  typed = false,\n): ExportCell[][] {\n  return dataIndices.map((dataRowIndex) => mapExportRow(state, columns, state.data[dataRowIndex] as TData, text, formatCell, typed));\n}\n\n/** {@link buildRowsAt} for a `formatCell` that may return promises: each slice of rows settles its promises before the next slice starts. */\nasync function buildRowsAtAsync<TData>(\n  state: DataGridReadState,\n  dataIndices: readonly number[],\n  columns: readonly ExportColumn[],\n  formatCell: FormatExportCell<TData> | undefined,\n  typed: boolean,\n  signal: AbortSignal,\n  onSlice?: (rows: ExportCell[][]) => void,\n): Promise<ExportCell[][]> {\n  const rows: ExportCell[][] = [];\n  for (let from = 0; from < dataIndices.length; from += SLICE_ROWS) {\n    throwIfAborted(signal);\n    const pending: PendingCell[] = [];\n    const slice: ExportCell[][] = [];\n    for (const dataRowIndex of dataIndices.slice(from, from + SLICE_ROWS)) {\n      slice.push(mapExportRow(state, columns, state.data[dataRowIndex] as TData, \"export\", formatCell, typed, signal, pending));\n    }\n    if (pending.length > 0) await settlePending(pending, typed, signal);\n    if (onSlice) onSlice(slice);\n    else for (const row of slice) rows.push(row);\n  }\n  return rows;\n}\n\ntype ExportColumn = DataGridReadState[\"visibleColumns\"][number];\n\n/** The columns and the data indices to build: at most `maxRows` rows, with a dev-only warning when the scope exceeds the cap. */\nfunction cappedExportPlan(state: DataGridReadState, scope: ExportScope, rawMaxRows: number | undefined, columnIds: readonly string[] | undefined) {\n  const maxRows = rawMaxRows === undefined ? undefined : normalizeLimit(rawMaxRows, Number.POSITIVE_INFINITY);\n  const columns = resolveExportColumns(state, columnIds);\n  const dataIndices = exportDataIndices(state, scope);\n  if (maxRows !== undefined && dataIndices.length > maxRows && isDev()) console.warn(`[data-grid-io] export truncated to ${maxRows} of ${dataIndices.length} rows (maxRows)`);\n  return { columns, dataIndices: maxRows === undefined ? dataIndices : dataIndices.slice(0, maxRows) };\n}\n\nfunction buildCappedExportRows<TData>(state: DataGridReadState, scope: ExportScope, rawMaxRows: number | undefined, shape: ExportShapeOptions<TData, FormatExportCellSync<TData>>, typed: boolean): ExportCell[][] {\n  const { columns, dataIndices } = cappedExportPlan(state, scope, rawMaxRows, shape.columns);\n  return buildRowsAt(state, dataIndices, \"export\", columns, shape.formatCell, typed);\n}\n\nfunction buildCappedExportRowsAsync<TData>(state: DataGridReadState, scope: ExportScope, rawMaxRows: number | undefined, shape: ExportShapeOptions<TData>, typed: boolean, signal: AbortSignal, onSlice?: (rows: ExportCell[][]) => void): Promise<ExportCell[][]> {\n  const { columns, dataIndices } = cappedExportPlan(state, scope, rawMaxRows, shape.columns);\n  return buildRowsAtAsync(state, dataIndices, columns, shape.formatCell, typed, signal, onSlice);\n}\n\n/** Header row text for each exported column: the visible columns, or the columns named by `columnIds`. */\nexport function buildExportHeaders(state: DataGridReadState, columnIds?: readonly string[], overrides?: Readonly<Record<string, string>>): string[] {\n  return resolveExportColumns(state, columnIds).map((column) => (overrides && Object.hasOwn(overrides, column.id) ? overrides[column.id]! : columnLabelText(column)));\n}\n\n/** Triggers a browser download of `blob` named `fileName`, via a temporary anchor + object URL (revoke deferred — see below). */\nexport function downloadBlob(blob: Blob, fileName: string): void {\n  const url = URL.createObjectURL(blob);\n  const anchor = document.createElement(\"a\");\n  anchor.href = url;\n  anchor.download = fileName;\n  anchor.style.display = \"none\";\n  document.body.append(anchor);\n  anchor.click();\n  anchor.remove();\n  // Firefox/Safari read the blob URL asynchronously after click(); revoking on the same tick can truncate the download.\n  setTimeout(() => URL.revokeObjectURL(url), 10_000);\n}\n\n/** Options for {@link buildXlsx}. */\nexport type BuildXlsxOptions<TData = unknown> = ExportShapeOptions<TData> & {\n  /** Row scope, same semantics as {@link ExportGridOptions.scope}; default 'view'. */\n  scope?: ExportScope;\n  /** Whether to emit a header row; default true. */\n  includeHeaders?: boolean;\n  /** Name of the single sheet inside the workbook; default 'Sheet1'. An invalid Excel sheet name (empty, over 31 characters, `[]:*?/\\`, a leading or trailing `'`, `history` in any case) rejects. */\n  sheetName?: string;\n  /** Same row cap as {@link ExportGridOptions.maxRows}. */\n  maxRows?: number;\n  /** Passed to `formatCell` as `ctx.signal`; an aborted signal rejects the build between slices of rows. */\n  signal?: AbortSignal;\n  /** Same as {@link ExportGridOptions.xlsxWriter}; default `\"buffered\"`. */\n  xlsxWriter?: XlsxWriterMode;\n};\n\nconst XLSX_TYPE = \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";\n\nfunction xlsxBlob(bytes: Uint8Array): Blob {\n  // hucre types its output as ArrayBufferLike, but its writers never return a SharedArrayBuffer view\n  return new Blob([bytes as Uint8Array<ArrayBuffer>], { type: XLSX_TYPE });\n}\n\n/** Receives the rows of one sheet slice by slice and turns them into the file. */\ntype XlsxSink = { add(rows: readonly (readonly ExportCell[])[]): void; finish(): Promise<Blob> };\n\nasync function createXlsxSink(name: string, mode: XlsxWriterMode | undefined): Promise<XlsxSink> {\n  if (mode === \"stream\") {\n    const { XlsxStreamWriter } = await import(\"./xlsx-writer\");\n    // no rollover and no header repeat: the file holds the same single sheet as the buffered writer\n    const writer = new XlsxStreamWriter({ name, maxRowsPerSheet: Number.POSITIVE_INFINITY, repeatHeaders: false });\n    return {\n      add: (rows) => {\n        for (const row of rows) writer.addRow(row as ExportCell[]);\n      },\n      finish: async () => xlsxBlob(await writer.finish()),\n    };\n  }\n  const table: (readonly ExportCell[])[] = [];\n  return {\n    add: (rows) => {\n      for (const row of rows) table.push(row);\n    },\n    finish: async () => {\n      const { writeXlsx } = await import(\"./xlsx-writer\");\n      return xlsxBlob(await writeXlsx({ sheets: [{ name, rows: table as ExportCell[][] }] }));\n    },\n  };\n}\n\nconst cutRow = (row: readonly ExportCell[]): ExportCell[] => row.map((cell) => (typeof cell === \"string\" ? cutCell(cell) : cell));\n\n/**\n * Builds an xlsx `Blob` from the grid's state without triggering a download — for server uploads\n * or inspecting the workbook before it leaves the browser. Values go through each column's cell\n * type `toText` like `exportGrid`. Built-in `number`, `date`, and `checkbox` columns land typed, other columns as\n * string cells, never formulas; `formatCell` overrides both. hucre loads lazily.\n */\nexport async function buildXlsx<TData = unknown>(state: DataGridReadState, options: BuildXlsxOptions<TData> = {}): Promise<Blob> {\n  const { scope = \"view\", includeHeaders = true, sheetName = \"Sheet1\", maxRows, signal = NEVER_ABORTED } = options;\n  const sink = await createXlsxSink(sheetName, options.xlsxWriter);\n  if (includeHeaders) sink.add([cutRow(buildExportHeaders(state, options.columns, options.headers))]);\n  await buildCappedExportRowsAsync(state, scope, maxRows, options, true, signal, (slice) => sink.add(slice.map(cutRow)));\n  return sink.finish();\n}\n\n/**\n * Builds a CSV `Blob` from the rows the grid holds, without a download. Synchronous; cells go\n * through each column's cell type `toText` like `exportGrid`, then `formatCell`.\n */\nexport function buildCsv<TData = unknown>(state: DataGridReadState, options: BuildCsvOptions<TData> = {}): Blob {\n  const rows = buildCappedExportRows(state, options.scope ?? \"view\", options.maxRows, options, false) as string[][];\n  return csvBlob(state, rows, options);\n}\n\nfunction csvBlob(state: DataGridReadState, rows: string[][], options: Pick<BuildCsvOptions, \"includeHeaders\" | \"csvDelimiter\" | \"csvBom\" | \"sanitizeFormulas\" | \"columns\" | \"headers\">): Blob {\n  const { includeHeaders = true, csvDelimiter = \",\", csvBom = true, sanitizeFormulas = true } = options;\n  const table = includeHeaders ? [buildExportHeaders(state, options.columns, options.headers), ...rows] : rows;\n  return new Blob([(csvBom ? BOM : \"\") + rowsToCsv(table, { delimiter: csvDelimiter, sanitizeFormulas })], { type: \"text/csv;charset=utf-8;\" });\n}\n\nasync function buildCsvAsync<TData>(state: DataGridReadState, options: ExportGridOptions<TData>, signal: AbortSignal): Promise<Blob> {\n  const rows = (await buildCappedExportRowsAsync(state, options.scope ?? \"view\", options.maxRows, options, false, signal)) as string[][];\n  return csvBlob(state, rows, options);\n}\n\nfunction isValidSheetName(name: string): boolean {\n  return name.length > 0 && name.length <= 31 && !INVALID_SHEET_NAME.test(name) && !name.startsWith(\"'\") && !name.endsWith(\"'\") && name.toLowerCase() !== \"history\";\n}\n\nfunction cutCell(text: string): string {\n  return text.length > MAX_CELL_TEXT ? text.slice(0, MAX_CELL_TEXT) : text;\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n  if (signal?.aborted) throw signal.reason ?? new DOMException(\"The export was aborted.\", \"AbortError\");\n}\n\nfunction loadedResult(state: DataGridReadState, scope: ExportScope, maxRows: number | undefined): ExportResult {\n  const total = exportDataIndices(state, scope).length;\n  return { rowCount: maxRows === undefined ? total : Math.min(total, maxRows), truncated: maxRows !== undefined && total > maxRows };\n}\n\ntype ExportDelivery = { fileName: string; output: ExportOutput | undefined; signal: AbortSignal };\n\nasync function deliver(blob: Blob, format: \"csv\" | \"xlsx\", { fileName, output, signal }: ExportDelivery): Promise<void> {\n  throwIfAborted(signal);\n  const file = `${fileName}.${format}`;\n  if (output) await output(blob, { fileName: file, format, signal });\n  else downloadBlob(blob, file);\n}\n\n/** Exports the rows `source` returns; CSV is written batch by batch, XLSX goes through the chosen `xlsxWriter`. */\nasync function exportFromSource<TData>(state: DataGridReadState, source: ExportSource, options: ExportGridOptions<TData>, delivery: ExportDelivery): Promise<ExportResult> {\n  const { format = \"csv\", includeHeaders = true, csvDelimiter = \",\", csvBom = true, sanitizeFormulas = true, sheetName = \"Sheet1\", onProgress } = options;\n  const xlsx = format === \"xlsx\";\n  if (xlsx && !isValidSheetName(sheetName)) throw new Error(`[data-grid-io] invalid xlsx sheet name: ${sheetName}`);\n  const headers = buildExportHeaders(state, options.columns, options.headers).map(cutCell);\n  const requested = normalizeLimit(options.maxRows, DEFAULT_SOURCE_MAX_ROWS);\n  const maxRows = xlsx ? Math.min(requested, XLSX_MAX_ROWS - (includeHeaders ? 1 : 0), Math.floor(XLSX_MAX_CELLS / Math.max(headers.length, 1))) : requested;\n  const run: ExportRowsOptions<TData> = {\n    source,\n    columns: options.columns,\n    formatCell: options.formatCell,\n    typed: xlsx,\n    maxRows,\n    maxBytes: normalizeLimit(options.maxBytes, DEFAULT_SOURCE_MAX_BYTES),\n    signal: delivery.signal,\n    onProgress,\n  };\n\n  if (!xlsx) {\n    const parts: Blob[] = [new Blob([csvBom ? BOM : \"\"])];\n    let started = false;\n    const append = (rows: readonly (readonly string[])[]): number => {\n      if (rows.length === 0) return 0;\n      const text = (started ? CSV_EOL : \"\") + rowsToCsv(rows, { delimiter: csvDelimiter, sanitizeFormulas });\n      started = true;\n      const part = new Blob([text]);\n      parts.push(part);\n      return part.size;\n    };\n    if (includeHeaders) append([headers]);\n    const result = await exportRows<TData, string>(state, run, append);\n    await deliver(new Blob(parts, { type: \"text/csv;charset=utf-8;\" }), \"csv\", delivery);\n    return result;\n  }\n\n  const sink = await createXlsxSink(sheetName, options.xlsxWriter);\n  if (includeHeaders) sink.add([headers]);\n  const result = await exportRows<TData, ExportCell>(state, run, (rows) => {\n    let size = 0;\n    const cuts = rows.map(cutRow);\n    for (const cut of cuts) for (const cell of cut) size += exportCellSize(cell);\n    sink.add(cuts);\n    return size;\n  });\n  await deliver(await sink.finish(), \"xlsx\", delivery);\n  return result;\n}\n\n/**\n * Serializes the grid to CSV or XLSX and triggers a download, or hands the file to `output`.\n * Values go through each column's cell type `toText` (never raw values) unless `formatCell`\n * replaces them. hucre is loaded lazily (dynamic `import()`) so the dependency never loads for\n * CSV-only consumers.\n */\nexport async function exportGrid<TData = unknown>(state: DataGridReadState, options: ExportGridOptions<TData> = {}): Promise<ExportResult> {\n  const controller = new AbortController();\n  const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;\n  try {\n    return await runExport(state, options, signal);\n  } catch (error) {\n    controller.abort(error);\n    throw error;\n  }\n}\n\nasync function runExport<TData>(state: DataGridReadState, options: ExportGridOptions<TData>, signal: AbortSignal): Promise<ExportResult> {\n  const { source, output, format = \"csv\", scope = \"view\", fileName = \"export\" } = options;\n  const delivery: ExportDelivery = { fileName, output, signal };\n  if (source) return exportFromSource(state, source, options, delivery);\n  const maxRows = options.maxRows === undefined ? undefined : normalizeLimit(options.maxRows, Number.POSITIVE_INFINITY);\n  if (format === \"csv\") {\n    await deliver(await buildCsvAsync(state, { ...options, maxRows }, signal), \"csv\", delivery);\n    return loadedResult(state, scope, maxRows);\n  }\n\n  await deliver(await buildXlsx(state, { ...options, maxRows, signal }), \"xlsx\", delivery);\n  return loadedResult(state, scope, maxRows);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/export-grid.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/normalize-limit.ts",
      "content": "/** Clamps a caller limit to a non-negative integer: `NaN` falls back, `Infinity` becomes the largest safe integer. */\r\nexport function normalizeLimit(value: number | undefined, fallback: number): number {\r\n  if (value === undefined || Number.isNaN(value)) return fallback;\r\n  return Math.min(Math.max(0, Math.floor(value)), Number.MAX_SAFE_INTEGER);\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-io/normalize-limit.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/export-source.ts",
      "content": "import { getCellValue, type AnyColumnDef, type ServerSpec } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport { serverSpecOf } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport { normalizeLimit } from \"./normalize-limit\";\r\nimport { displayText, isDev, isThenable, type DataGridReadState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\n/** Longest cell text an Excel worksheet holds; XLSX export and print cut longer text to it, CSV only a `formatCell` string. */\r\nexport const MAX_CELL_TEXT = 32_767;\r\n\r\n/** What a `formatCell` hook returns. `null` and `undefined` make an empty cell. */\r\nexport type ExportCellValue = string | number | boolean | Date | null | undefined;\r\n\r\n/** What `formatCell` receives for one exported cell. */\r\nexport type ExportCellContext<TData = unknown> = {\r\n  /** The raw cell value. */\r\n  value: unknown;\r\n  /** The text the column's cell type exports by default. */\r\n  text: string;\r\n  row: TData;\r\n  column: AnyColumnDef;\r\n  /** Aborts when the export is cancelled, fails, or stops at a limit. Pass it to a request. */\r\n  signal: AbortSignal;\r\n};\r\n\r\n/** Replaces the exported value of every cell. Runs once per cell, after the cell type made its text. */\r\nexport type FormatExportCellSync<TData = unknown> = (ctx: ExportCellContext<TData>) => ExportCellValue;\r\n\r\n/** {@link FormatExportCellSync}, or a hook that returns a promise. The promises of one slice of rows settle together. */\r\nexport type FormatExportCell<TData = unknown> = (ctx: ExportCellContext<TData>) => ExportCellValue | PromiseLike<ExportCellValue>;\r\n\r\n/** The signal of an export that cannot be cancelled. */\r\nexport const NEVER_ABORTED: AbortSignal = new AbortController().signal;\r\n\r\n/** One exported cell after the format step: CSV rows hold strings only, XLSX rows keep typed values. */\r\nexport type ExportCell = string | number | boolean | Date | null;\r\n\r\n/** What an {@link ExportSource} receives. */\r\nexport type ExportSourceContext = {\r\n  /** The grid's sort, filters, and search text when the export started. Send it to your server. */\r\n  spec: ServerSpec;\r\n  /** Aborts when the export is cancelled or stops at a limit. Pass it to your request. */\r\n  signal: AbortSignal;\r\n  /** The ids of the columns the export writes, in order. Narrow your query to them. */\r\n  columnIds: readonly string[];\r\n};\r\n\r\n/** Rows of the whole result for an \"all rows\" export. Return one array, or an async iterable of batches (an async generator that pages through your API). */\r\nexport type ExportSource<TData = unknown> = (ctx: ExportSourceContext) => readonly TData[] | Promise<readonly TData[]> | AsyncIterable<readonly TData[]>;\r\n\r\nexport const SLICE_ROWS = 1000;\r\n/** Most `formatCell` promises awaited together. */\r\nconst ASYNC_GROUP_CELLS = 10_000;\r\nconst MAX_EMPTY_BATCHES = 1000;\r\nconst YIELD_AFTER_MS = 40;\r\n\r\nexport const DEFAULT_SOURCE_MAX_ROWS = 1_000_000;\r\nexport const DEFAULT_SOURCE_MAX_BYTES = 256 * 1024 * 1024;\r\n\r\n/** Running totals after a batch: data rows written and file bytes (xlsx: characters) so far. */\r\nexport type ExportProgress = { rowCount: number; byteCount: number };\r\n\r\n/** What a finished export wrote. */\r\nexport type ExportResult = {\r\n  rowCount: number;\r\n  /** True when `maxRows` or `maxBytes` ended the export before the source did. */\r\n  truncated: boolean;\r\n};\r\n\r\n/** Resolved limits and callbacks of one source export. */\r\nexport type ExportRowsOptions<TData = unknown> = {\r\n  source: ExportSource;\r\n  /** Column ids to write, in order; default the visible columns. An unknown id throws before the source runs. */\r\n  columns?: readonly string[];\r\n  formatCell?: FormatExportCell<TData>;\r\n  /** Cell text source: `\"export\"` uses the cell type's `toText` (default), `\"display\"` its display text (print). */\r\n  text?: \"export\" | \"display\";\r\n  /** Keep numbers, booleans and Dates typed (XLSX). Default: every cell becomes a string (CSV). */\r\n  typed?: boolean;\r\n  /** Most data rows to write. Default `1_000_000`; a negative or fractional value rounds to a non-negative integer. */\r\n  maxRows?: number;\r\n  /** Most bytes to write (xlsx: characters). Default 256 MiB. */\r\n  maxBytes?: number;\r\n  signal?: AbortSignal;\r\n  onProgress?: (progress: ExportProgress) => void;\r\n};\r\n\r\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<readonly unknown[]> {\r\n  return typeof value === \"object\" && value !== null && Symbol.asyncIterator in value;\r\n}\r\n\r\n/** A message-channel hop: unlike `setTimeout`, a hidden tab does not throttle it. */\r\nfunction yieldToEventLoop(): Promise<void> {\r\n  if (typeof MessageChannel === \"undefined\") return new Promise((resolve) => setTimeout(resolve, 0));\r\n  return new Promise((resolve) => {\r\n    const { port1, port2 } = new MessageChannel();\r\n    port1.onmessage = () => {\r\n      port1.close();\r\n      resolve();\r\n    };\r\n    port2.postMessage(0);\r\n  });\r\n}\r\n\r\nexport function abortReason(signal: AbortSignal): unknown {\r\n  return signal.reason ?? new DOMException(\"The export was aborted.\", \"AbortError\");\r\n}\r\n\r\n/**\r\n * Reads the batches of `source`, maps each row through the cell types, and hands the text rows to\r\n * `onBatch` (which returns the byte size it kept). Stops at `maxRows` or `maxBytes` and aborts the source.\r\n */\r\nexport async function exportRows<TData = unknown, TCell extends ExportCell = string>(\r\n  state: DataGridReadState,\r\n  options: ExportRowsOptions<TData>,\r\n  onBatch: (rows: TCell[][]) => number,\r\n): Promise<ExportResult> {\r\n  const { source, signal: outer, onProgress, formatCell, typed = false } = options;\r\n  const maxRows = normalizeLimit(options.maxRows, DEFAULT_SOURCE_MAX_ROWS);\r\n  const maxBytes = normalizeLimit(options.maxBytes, DEFAULT_SOURCE_MAX_BYTES);\r\n  const columns = resolveExportColumns(state, options.columns);\r\n  const columnIds = columns.map((column) => column.id);\r\n  const inner = new AbortController();\r\n  const stop = () => inner.abort(outer?.reason);\r\n  if (outer?.aborted) throw abortReason(outer);\r\n  outer?.addEventListener(\"abort\", stop, { once: true });\r\n\r\n  const spec: ServerSpec = serverSpecOf(state);\r\n  let rowCount = 0;\r\n  let byteCount = 0;\r\n  let truncated = false;\r\n  // The slice that crosses maxBytes is written whole; the export is truncated only if more rows follow it.\r\n  let overBytes = false;\r\n  let skippedRows = 0;\r\n  let emptyBatches = 0;\r\n  const maxSkippedRows = Math.max(maxRows, 1) * 2;\r\n  let iterator: AsyncIterator<readonly unknown[]> | undefined;\r\n\r\n  const untilAborted = <T,>(promise: Promise<T>): Promise<T> => {\r\n    if (!outer) return promise;\r\n    return new Promise<T>((resolve, reject) => {\r\n      const fail = () => reject(abortReason(outer));\r\n      if (outer.aborted) return fail();\r\n      outer.addEventListener(\"abort\", fail, { once: true });\r\n      const settle = (done: () => void) => () => {\r\n        outer.removeEventListener(\"abort\", fail);\r\n        done();\r\n      };\r\n      promise.then(\r\n        (value) => settle(() => resolve(value))(),\r\n        (error) => settle(() => reject(error))(),\r\n      );\r\n    });\r\n  };\r\n\r\n  let warnedBatchBytes = false;\r\n  let sliceStarted = performance.now();\r\n  const take = async (batch: unknown): Promise<void> => {\r\n    if (!Array.isArray(batch)) throw new TypeError(\"[data-grid-io] an export source batch must be an array\");\r\n    emptyBatches = batch.length === 0 ? emptyBatches + 1 : 0;\r\n    if (emptyBatches > MAX_EMPTY_BATCHES) throw new RangeError(\"[data-grid-io] an export source returned only empty batches\");\r\n    for (let from = 0; from < batch.length && !truncated; from += SLICE_ROWS) {\r\n      const slice = batch.slice(from, from + SLICE_ROWS);\r\n      const present = slice.filter((row) => row !== undefined && row !== null);\r\n      if (overBytes && present.length > 0) {\r\n        truncated = true;\r\n        break;\r\n      }\r\n      skippedRows += slice.length - present.length;\r\n      const room = maxRows - rowCount;\r\n      if (present.length > room) truncated = true;\r\n      else if (skippedRows > maxSkippedRows) throw new RangeError(\"[data-grid-io] an export source returned too many empty rows\");\r\n      const pending: PendingCell[] = [];\r\n      const rows = present.slice(0, room).map((row) => mapExportRow(state, columns, row as TData, options.text ?? \"export\", formatCell, typed, inner.signal, pending) as TCell[]);\r\n      if (pending.length > 0) await settlePending(pending, typed, inner.signal);\r\n      rowCount += rows.length;\r\n      const batchBytes = onBatch(rows);\r\n      if (Number.isFinite(batchBytes)) byteCount += batchBytes;\r\n      else if (!warnedBatchBytes && isDev()) {\r\n        warnedBatchBytes = true;\r\n        console.warn(\"[data-grid-io] onBatch must return the byte size it kept as a finite number; this batch counts as 0 bytes\");\r\n      }\r\n      if (byteCount > maxBytes) overBytes = true;\r\n      if (performance.now() - sliceStarted > YIELD_AFTER_MS) {\r\n        await yieldToEventLoop();\r\n        if (outer?.aborted) throw abortReason(outer);\r\n        sliceStarted = performance.now();\r\n      }\r\n    }\r\n    try {\r\n      onProgress?.({ rowCount, byteCount });\r\n    } catch (error) {\r\n      if (isDev()) console.warn(\"[data-grid-io] onProgress threw\", error);\r\n    }\r\n  };\r\n\r\n  try {\r\n    const result = source({ spec, signal: inner.signal, columnIds });\r\n    if (isAsyncIterable(result)) {\r\n      iterator = result[Symbol.asyncIterator]();\r\n      while (!truncated) {\r\n        const step = await untilAborted(iterator.next());\r\n        if (outer?.aborted) throw abortReason(outer);\r\n        if (step.done) break;\r\n        await take(step.value);\r\n      }\r\n    } else {\r\n      const batch = await untilAborted(Promise.resolve(result));\r\n      if (outer?.aborted) throw abortReason(outer);\r\n      await take(batch);\r\n    }\r\n  } finally {\r\n    outer?.removeEventListener(\"abort\", stop);\r\n    inner.abort();\r\n    void Promise.resolve(iterator?.return?.()).catch(() => {});\r\n  }\r\n\r\n  if (truncated && isDev()) console.warn(`[data-grid-io] export stopped at ${rowCount} rows (maxRows ${maxRows}, maxBytes ${maxBytes})`);\r\n  return { rowCount, truncated };\r\n}\r\n\r\n/** Resolves column ids against all grid columns, hidden ones included; no ids means the visible columns. */\r\nexport function resolveExportColumns(state: DataGridReadState, ids: readonly string[] | undefined): readonly AnyColumnDef[] {\r\n  if (ids === undefined) return state.visibleColumns;\r\n  const all = state.columns ?? state.visibleColumns;\r\n  const byId = new Map(all.map((column) => [column.id, column] as const));\r\n  return ids.map((id) => {\r\n    const column = byId.get(id);\r\n    if (!column) throw new RangeError(`[data-grid-io] unknown export column: ${id}`);\r\n    return column;\r\n  });\r\n}\r\n\r\nfunction cutText(text: string): string {\r\n  return text.length > MAX_CELL_TEXT ? text.slice(0, MAX_CELL_TEXT) : text;\r\n}\r\n\r\nfunction toCsvCell(value: ExportCellValue): string {\r\n  if (typeof value === \"string\") return cutText(value);\r\n  if (typeof value === \"number\") return Number.isFinite(value) ? String(value) : \"\";\r\n  if (typeof value === \"boolean\") return String(value);\r\n  if (value instanceof Date) return Number.isNaN(value.getTime()) ? \"\" : value.toISOString();\r\n  return \"\";\r\n}\r\n\r\nfunction toTypedCell(value: ExportCellValue): ExportCell {\r\n  if (typeof value === \"string\") return cutText(value);\r\n  if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\r\n  if (typeof value === \"boolean\") return value;\r\n  if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;\r\n  return null;\r\n}\r\n\r\nconst ISO_DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\r\n\r\n/** The typed XLSX cell of a built-in `number`, `date`, or `checkbox` column; any other column keeps its text. */\r\nfunction builtInTypedCell(type: string | undefined, value: unknown, text: string): ExportCell {\r\n  if (type === \"number\") {\r\n    const number = text === \"\" ? Number.NaN : Number(text);\r\n    return Number.isFinite(number) ? number : text;\r\n  }\r\n  if (type === \"checkbox\") return typeof value === \"boolean\" ? value : text;\r\n  if (type === \"date\") {\r\n    const match = typeof value === \"string\" ? ISO_DATE.exec(value) : null;\r\n    if (!match) return text;\r\n    const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));\r\n    return date.getUTCMonth() === Number(match[2]) - 1 ? date : text;\r\n  }\r\n  return text;\r\n}\r\n\r\n/** Characters one exported cell adds to the file; typed cells count as `String(value)`. */\r\nexport function exportCellSize(cell: ExportCell): number {\r\n  if (cell === null) return 0;\r\n  if (typeof cell === \"string\") return cell.length;\r\n  return cell instanceof Date ? cell.toISOString().length : String(cell).length;\r\n}\r\n\r\n/** A cell whose `formatCell` returned a promise: the value lands in `row[index]` once it settles. */\r\nexport type PendingCell = { row: ExportCell[]; index: number; value: PromiseLike<ExportCellValue> };\r\n\r\n/** Awaits the promises together in groups, converts each value like a sync one, and reads `signal` after every group. */\r\nexport async function settlePending(pending: readonly PendingCell[], typed: boolean, signal: AbortSignal): Promise<void> {\r\n  // a later group's rejection must not surface as an unhandled rejection while an earlier group is awaited\r\n  for (const cell of pending) Promise.resolve(cell.value).catch(() => {});\r\n  for (let from = 0; from < pending.length; from += ASYNC_GROUP_CELLS) {\r\n    const group = pending.slice(from, from + ASYNC_GROUP_CELLS);\r\n    const values = await Promise.all(group.map((cell) => cell.value));\r\n    if (signal.aborted) throw abortReason(signal);\r\n    group.forEach((cell, i) => {\r\n      cell.row[cell.index] = typed ? toTypedCell(values[i]) : toCsvCell(values[i]);\r\n    });\r\n  }\r\n}\r\n\r\n/**\r\n * Maps one row through the cell types, then `formatCell`; the loaded rows and the source rows share it.\r\n * A promise from `formatCell` goes to `pending` and leaves the cell empty until `settlePending`; without `pending` it throws.\r\n */\r\nexport function mapExportRow<TData>(\r\n  state: DataGridReadState,\r\n  columns: readonly AnyColumnDef[],\r\n  row: TData,\r\n  text: \"export\" | \"display\",\r\n  formatCell: FormatExportCell<TData> | undefined,\r\n  typed: boolean,\r\n  signal: AbortSignal = NEVER_ABORTED,\r\n  pending?: PendingCell[],\r\n): ExportCell[] {\r\n  const cells = new Array<ExportCell>(columns.length);\r\n  for (let index = 0; index < columns.length; index++) {\r\n    const column = columns[index]!;\r\n    const cellType = state.cellTypes[column.type ?? \"text\"];\r\n    const value = getCellValue<unknown, AnyColumnDef>(row, column);\r\n    const cellText = cellType ? (text === \"display\" ? displayText(cellType, value, column.options) : cellType.toText(value, column.options)) : \"\";\r\n    if (!formatCell) {\r\n      cells[index] = typed ? builtInTypedCell(column.type, value, cellText) : cellText;\r\n      continue;\r\n    }\r\n    const formatted = formatCell({ value, text: cellText, row, column, signal });\r\n    if (isThenable<ExportCellValue>(formatted)) {\r\n      if (!pending) throw new TypeError(\"[data-grid-io] formatCell returned a promise; use exportGrid or buildXlsx, which await it\");\r\n      pending.push({ row: cells, index, value: formatted });\r\n      cells[index] = null;\r\n      continue;\r\n    }\r\n    cells[index] = typed ? toTypedCell(formatted) : toCsvCell(formatted);\r\n  }\r\n  return cells;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-io/export-source.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/xlsx-writer.ts",
      "content": "// A static re-export per direction lets bundlers tree-shake hucre's barrels inside the lazy chunk.\nexport { writeXlsx, XlsxStreamWriter } from \"hucre/xlsx\";\n",
      "type": "registry:component",
      "target": "components/data-grid-io/xlsx-writer.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/use-data-grid-export.ts",
      "content": "\"use client\";\r\n\r\nimport { useCallback } from \"react\";\r\nimport { useDataGridStoreApi } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport { exportGrid, type ExportGridOptions, type ExportResult } from \"./export-grid\";\r\n\r\n/** Public export trigger returned by {@link useDataGridExport}. */\r\nexport type UseDataGridExportResult = {\r\n  /** Serializes the grid per `options` and triggers a browser download, or hands the file to `options.output`. */\r\n  exportGrid: <TData = unknown>(options?: ExportGridOptions<TData>) => Promise<ExportResult>;\r\n};\r\n\r\n/** Wires {@link exportGrid} to the grid's store instance, for toolbar buttons and custom triggers. */\r\nexport function useDataGridExport(): UseDataGridExportResult {\r\n  const storeApi = useDataGridStoreApi();\r\n\r\n  const run = useCallback(\r\n    <TData = unknown,>(options?: ExportGridOptions<TData>) => exportGrid(storeApi.getState(), options),\r\n    [storeApi],\r\n  );\r\n\r\n  return { exportGrid: run };\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-io/use-data-grid-export.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/export-button.tsx",
      "content": "\"use client\";\r\n\r\nimport { useCallback, useEffect, useRef, useState, type ReactNode } from \"react\";\r\nimport { Download } from \"lucide-react\";\r\nimport { useDataGridLabels } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport { isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport {\r\n  DropdownMenu,\r\n  DropdownMenuContent,\r\n  DropdownMenuItem,\r\n  DropdownMenuTrigger,\r\n} from \"@/components/ui/dropdown-menu\";\r\nimport { useDataGridExport } from \"./use-data-grid-export\";\r\nimport type { ExportGridOptions, ExportResult } from \"./export-grid\";\r\n\r\ntype ExportFormat = \"xlsx\" | \"csv\";\r\n\r\n/** Props for {@link DataGridExportButton}. */\r\nexport type DataGridExportButtonProps<TData = unknown> = {\r\n  className?: string;\r\n  /** The formats the button offers; one format exports on click, several open a menu. Default `[\"xlsx\", \"csv\"]`. */\r\n  formats?: readonly ExportFormat[];\r\n  /** Export options applied to both formats besides `format` itself, including `columns`, `formatCell`, and `output`; default `{ scope: 'view', includeHeaders: true }`. With `source`, the menu adds \"all rows\" items that export the source's rows; the plain items export the rows the grid holds. */\r\n  options?: Omit<ExportGridOptions<TData>, \"format\">;\r\n  /** Receives the rejection when an export fails; without it, the failure logs a dev-only warning. */\r\n  onError?: (error: unknown, format: ExportFormat) => void;\r\n};\r\n\r\n/**\r\n * Toolbar-slot export trigger: a ghost icon button opening a dropdown of xlsx/csv, wired to\r\n * {@link useDataGridExport}. `size-8` + ghost variant matches the toolbar's other icon buttons.\r\n */\r\nexport function DataGridExportButton<TData = unknown>(props: DataGridExportButtonProps<TData>): ReactNode {\r\n  const { className, formats = [\"xlsx\", \"csv\"], options, onError } = props;\r\n  const labels = useDataGridLabels();\r\n  const { exportGrid } = useDataGridExport();\r\n  const { source, ...loadedOptions } = options ?? {};\r\n  const [running, setRunning] = useState(false);\r\n  const [done, setDone] = useState(\"\");\r\n  const controllerRef = useRef<AbortController | null>(null);\r\n\r\n  useEffect(() => () => controllerRef.current?.abort(), []);\r\n\r\n  const cancelExport = useCallback(() => controllerRef.current?.abort(), []);\r\n\r\n  const runExport = (format: ExportFormat, all: boolean) => {\r\n    const controller = new AbortController();\r\n    controllerRef.current = controller;\r\n    const tracked = all || loadedOptions.output !== undefined;\r\n    setDone(\"\");\r\n    setRunning(tracked);\r\n    const signal = loadedOptions.signal ? AbortSignal.any([controller.signal, loadedOptions.signal]) : controller.signal;\r\n    exportGrid({ ...loadedOptions, format, signal, ...(all ? { source } : {}) })\r\n      .then((result: ExportResult) => {\r\n        if (tracked && controllerRef.current === controller) setDone(labels.io.exportDone(result.rowCount, result.truncated));\r\n      })\r\n      .catch((error: unknown) => {\r\n        const current = controllerRef.current === controller;\r\n        if (signal.aborted) {\r\n          if (tracked && current) setDone(labels.io.exportCancelled);\r\n          return;\r\n        }\r\n        if (tracked && current) setDone(labels.io.exportFailed);\r\n        if (onError) {\r\n          onError(error, format);\r\n          return;\r\n        }\r\n        if (isDev()) console.warn(`[data-grid-io] ${format} export failed`, error);\r\n      })\r\n      .finally(() => {\r\n        if (controllerRef.current === controller) setRunning(false);\r\n      });\r\n  };\r\n\r\n  const singleFormat = formats.length === 1 && !source;\r\n  const trigger = (\r\n    <Button type=\"button\" variant=\"ghost\" size=\"icon\" className={className} aria-label={labels.io.exportButtonAriaLabel} aria-busy={running || undefined} onClick={singleFormat ? () => (running ? cancelExport() : runExport(formats[0]!, false)) : undefined}>\r\n      <Download />\r\n    </Button>\r\n  );\r\n\r\n  const status = (\r\n    <span role=\"status\" className=\"sr-only\">\r\n      {done}\r\n    </span>\r\n  );\r\n\r\n  if (singleFormat) {\r\n    return (\r\n      <>\r\n        {trigger}\r\n        {status}\r\n      </>\r\n    );\r\n  }\r\n\r\n  return (\r\n    <>\r\n      <DropdownMenu>\r\n        <DropdownMenuTrigger render={trigger} />\r\n        <DropdownMenuContent align=\"start\">\r\n          {formats.includes(\"xlsx\") && (\r\n            <DropdownMenuItem disabled={running} onClick={() => runExport(\"xlsx\", false)}>\r\n              {labels.io.exportXlsx}\r\n            </DropdownMenuItem>\r\n          )}\r\n          {formats.includes(\"csv\") && (\r\n            <DropdownMenuItem disabled={running} onClick={() => runExport(\"csv\", false)}>\r\n              {labels.io.exportCsv}\r\n            </DropdownMenuItem>\r\n          )}\r\n          {source && formats.includes(\"xlsx\") && (\r\n            <DropdownMenuItem disabled={running} onClick={() => runExport(\"xlsx\", true)}>\r\n              {labels.io.exportAllXlsx}\r\n            </DropdownMenuItem>\r\n          )}\r\n          {source && formats.includes(\"csv\") && (\r\n            <DropdownMenuItem disabled={running} onClick={() => runExport(\"csv\", true)}>\r\n              {labels.io.exportAllCsv}\r\n            </DropdownMenuItem>\r\n          )}\r\n          {running && <DropdownMenuItem onClick={cancelExport}>{labels.io.exportCancel}</DropdownMenuItem>}\r\n        </DropdownMenuContent>\r\n      </DropdownMenu>\r\n      {status}\r\n    </>\r\n  );\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-io/export-button.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-io/print-grid.ts",
      "content": "import { type DataGridReadState, type GridDirection } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { normalizeLimit } from \"./normalize-limit\";\nimport { MAX_CELL_TEXT, buildExportHeaders, buildExportRows, exportDataIndices, exportRows } from \"./export-grid\";\nimport { abortReason, type ExportSource } from \"./export-source\";\n\n/** Default number of rows printed when `maxRows` is not given. */\nconst DEFAULT_PRINT_MAX_ROWS = 10_000;\n/** Hard ceiling on the printed table's cell count (a multi-million-cell DOM table hangs the print dialog). */\nconst PRINT_CELL_CEILING = 500_000;\n/** Longest `css` option, in characters. */\nexport const MAX_PRINT_CSS_LENGTH = 65_536;\n/** Fallback removal (ms) for the print iframe when the window's `afterprint` never fires. */\nconst PRINT_FALLBACK_MS = 60_000;\n\n/** Paper sizes for {@link PrintGridOptions.paperSize}. */\nexport type PrintPaperSize = \"A3\" | \"A4\" | \"Letter\" | \"Legal\";\n\n/** CSS `@page` size keyword per paper size. */\nconst PAPER_SIZE_CSS: Record<PrintPaperSize, string> = { A3: \"A3\", A4: \"A4\", Letter: \"letter\", Legal: \"legal\" };\n\n/** Options for {@link printGrid}. */\nexport type PrintGridOptions = {\n  /** Which rows to print: `\"view\"` (default) prints the current sort and filter order, every page of a paged grid; `\"page\"` the shown page only; `\"all\"` every row in `data` order; `\"selection\"` the selected rows in view order. */\n  scope?: \"view\" | \"page\" | \"all\" | \"selection\";\n  /** Printed as an `<h1>` heading and the document title. */\n  title?: string;\n  /** Emit a `<thead>` header row; default `true`. */\n  includeHeaders?: boolean;\n  /** Paper size of the printed page; default `\"A4\"`. */\n  paperSize?: PrintPaperSize;\n  /** Page orientation; default: `landscape` above 6 visible columns, else `portrait`. */\n  orientation?: \"portrait\" | \"landscape\";\n  /** Cap on the rows printed (the header row is not counted); default 10,000, further cut by the 500,000-cell ceiling. */\n  maxRows?: number;\n  /** Reading direction of the printed page. Default: the direction of the page that calls print. */\n  direction?: GridDirection;\n  /** Where the rows come from, for a grid that holds one page or some loaded blocks. With `source` the print ignores `scope` and the held rows. It receives the same context as the export source, and the `maxRows` and cell bounds apply. */\n  source?: ExportSource;\n  /** Header text per column id, replacing the column's label. A column without an entry keeps its label. */\n  headers?: Readonly<Record<string, string>>;\n  /** Extra CSS appended after the built-in rules, in a second `<style>` node. Longer than 65,536 characters rejects with a `RangeError`. Build it from constants only: a cell value in `css` can load a remote URL. */\n  css?: string;\n  /** Cancels the print: the promise rejects with the signal's reason and no dialog opens. */\n  signal?: AbortSignal;\n};\n\n/** What a finished {@link printGrid} printed. */\nexport type PrintGridResult = {\n  rowCount: number;\n  /** True when `maxRows` or the cell ceiling cut the output. */\n  truncated: boolean;\n};\n\nlet openIframe: HTMLIFrameElement | null = null;\nlet activeRun: AbortController | null = null;\nlet fallbackTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Removes the currently open print iframe and clears its fallback timer. */\nfunction removeOpenIframe(): void {\n  if (fallbackTimer !== null) {\n    clearTimeout(fallbackTimer);\n    fallbackTimer = null;\n  }\n  openIframe?.remove();\n  openIframe = null;\n}\n\nfunction cutText(text: string): string {\n  return text.length > MAX_CELL_TEXT ? text.slice(0, MAX_CELL_TEXT) : text;\n}\n\nfunction printCss(paperSize: string, orientation: \"portrait\" | \"landscape\"): string {\n  return [\n    `@page { size: ${paperSize} ${orientation}; margin: 12mm; }`,\n    \"body { font: 10pt/1.4 system-ui, sans-serif; color: #000; }\",\n    \"h1 { font-size: 14pt; margin: 0 0 8px; }\",\n    \"table { border-collapse: collapse; width: 100%; }\",\n    \"thead { display: table-header-group; }\",\n    \"tr { break-inside: avoid; }\",\n    \"th, td { border: 1px solid #999; padding: 2px 6px; text-align: start; }\",\n    \"th { font-weight: 600; }\",\n    \"p { margin: 8px 0 0; }\",\n  ].join(\"\\n\");\n}\n\ntype PrintRows = { rows: string[][]; note: string | undefined };\n\nfunction loadedPrintRows(state: DataGridReadState, scope: NonNullable<PrintGridOptions[\"scope\"]>, maxRows: number): PrintRows {\n  const total = exportDataIndices(state, scope).length;\n  const rows = buildExportRows(state, scope, { text: \"display\", maxRows });\n  return { rows, note: rows.length < total ? state.labels.io.printTruncated(rows.length, total) : undefined };\n}\n\nasync function sourcePrintRows(state: DataGridReadState, source: ExportSource, maxRows: number, signal: AbortSignal): Promise<PrintRows> {\n  const rows: string[][] = [];\n  const result = await exportRows<unknown, string>(state, { source, text: \"display\", maxRows, signal }, (batch) => {\n    let size = 0;\n    for (const row of batch) {\n      rows.push(row);\n      for (const cell of row) size += cell.length;\n    }\n    return size;\n  });\n  if (signal.aborted) throw abortReason(signal);\n  return { rows, note: result.truncated ? state.labels.io.printTruncatedSource(rows.length) : undefined };\n}\n\n/**\n * Prints the grid's rows as a plain paged table: the rows are resolved through the cell-type\n * pipeline's display text (`toDisplayText ?? toText`), built into a hidden, sandboxed iframe's\n * document with `textContent` only (no value ever passes an HTML parser), and the browser print\n * dialog is opened — its \"Save as PDF\" produces the PDF. Visible columns only, in view order;\n * lazy holes and hidden columns never print. `options.maxRows` caps the rows (default 10,000,\n * further cut to fit the 500,000-cell ceiling); when the cap cut the output, the table ends\n * with a truncation note. The iframe is removed on `afterprint` (with a 60 s fallback timer),\n * and a second call replaces the first, aborting its pending `source`. Without `source` the\n * dialog opens before the call returns. No-op without a DOM (SSR).\n */\nexport async function printGrid(state: DataGridReadState, options: PrintGridOptions = {}): Promise<PrintGridResult> {\n  if (typeof document === \"undefined\") return { rowCount: 0, truncated: false };\n  if (options.css !== undefined && options.css.length > MAX_PRINT_CSS_LENGTH) throw new RangeError(`[data-grid-io] print css is longer than ${MAX_PRINT_CSS_LENGTH} characters`);\n  removeOpenIframe();\n  activeRun?.abort();\n  const run = new AbortController();\n  activeRun = run;\n  const signal = options.signal ? AbortSignal.any([options.signal, run.signal]) : run.signal;\n  try {\n    const colCount = state.visibleColumns.length;\n    const maxRows = Math.min(normalizeLimit(options.maxRows, DEFAULT_PRINT_MAX_ROWS), Math.floor(PRINT_CELL_CEILING / Math.max(colCount, 1)));\n    const { rows, note } = options.source ? await sourcePrintRows(state, options.source, maxRows, signal) : loadedPrintRows(state, options.scope ?? \"view\", maxRows);\n    openPrintDocument(state, options, rows, note);\n    return { rowCount: rows.length, truncated: note !== undefined };\n  } finally {\n    if (activeRun === run) activeRun = null;\n  }\n}\n\nfunction openPrintDocument(state: DataGridReadState, options: PrintGridOptions, rows: string[][], note: string | undefined): void {\n  const includeHeaders = options.includeHeaders ?? true;\n  const colCount = state.visibleColumns.length;\n  const headers = buildExportHeaders(state, undefined, options.headers);\n  const orientation = options.orientation ?? (colCount > 6 ? \"landscape\" : \"portrait\");\n  // Untyped callers can pass any string; only the fixed map reaches the CSS.\n  const requestedSize = options.paperSize ?? \"A4\";\n  const paperSize = Object.hasOwn(PAPER_SIZE_CSS, requestedSize) ? PAPER_SIZE_CSS[requestedSize] : \"A4\";\n\n  const iframe = document.createElement(\"iframe\");\n  // attribute, not the sandbox IDL property: jsdom reflects the IDL property incompletely\n  iframe.setAttribute(\"sandbox\", \"allow-same-origin allow-modals\");\n  // zero-size and off-screen: the iframe exists only to host the print document\n  iframe.style.position = \"fixed\";\n  iframe.style.width = \"0\";\n  iframe.style.height = \"0\";\n  iframe.style.border = \"0\";\n  iframe.style.visibility = \"hidden\";\n  document.body.append(iframe);\n\n  const doc = iframe.contentDocument;\n  const win = iframe.contentWindow;\n  if (!doc || !win) {\n    iframe.remove();\n    return;\n  }\n\n  doc.documentElement.dir = options.direction ?? (getComputedStyle(document.documentElement).direction === \"rtl\" ? \"rtl\" : \"ltr\");\n  doc.title = options.title ?? \"\";\n  const meta = doc.createElement(\"meta\");\n  meta.httpEquiv = \"Content-Security-Policy\";\n  meta.content = \"default-src 'none'; style-src 'unsafe-inline'\";\n  const style = doc.createElement(\"style\");\n  style.textContent = printCss(paperSize, orientation);\n  doc.head.append(meta, style);\n  if (options.css) {\n    const extra = doc.createElement(\"style\");\n    extra.textContent = options.css;\n    doc.head.append(extra);\n  }\n  if (options.title) {\n    const heading = doc.createElement(\"h1\");\n    heading.textContent = options.title;\n    doc.body.append(heading);\n  }\n\n  const table = doc.createElement(\"table\");\n  if (includeHeaders) {\n    const thead = doc.createElement(\"thead\");\n    const headerRow = doc.createElement(\"tr\");\n    for (const header of headers) {\n      const th = doc.createElement(\"th\");\n      th.scope = \"col\";\n      th.textContent = cutText(header);\n      headerRow.append(th);\n    }\n    thead.append(headerRow);\n    table.append(thead);\n  }\n  const tbody = doc.createElement(\"tbody\");\n  for (const row of rows) {\n    const tr = doc.createElement(\"tr\");\n    for (let i = 0; i < row.length; i++) {\n      const td = doc.createElement(\"td\");\n      const align = state.cellTypes[state.visibleColumns[i]!.type ?? \"text\"]?.align;\n      if (align) td.style.textAlign = align;\n      td.textContent = cutText(row[i]!);\n      tr.append(td);\n    }\n    tbody.append(tr);\n  }\n  table.append(tbody);\n  doc.body.append(table);\n  if (note !== undefined) {\n    const noteElement = doc.createElement(\"p\");\n    noteElement.textContent = note;\n    doc.body.append(noteElement);\n  }\n\n  const cleanup = () => {\n    win.removeEventListener(\"afterprint\", cleanup);\n    removeOpenIframe();\n  };\n  win.addEventListener(\"afterprint\", cleanup);\n  fallbackTimer = setTimeout(cleanup, PRINT_FALLBACK_MS);\n  openIframe = iframe;\n  win.print();\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/print-grid.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/use-data-grid-print.ts",
      "content": "\"use client\";\n\nimport { useCallback } from \"react\";\nimport { useDataGridStoreApi } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { printGrid, type PrintGridOptions, type PrintGridResult } from \"./print-grid\";\n\n/** Public print trigger returned by {@link useDataGridPrint}. */\nexport type UseDataGridPrintResult = {\n  /** Prints the grid's rows as a paged table and opens the browser print dialog. */\n  printGrid: (options?: PrintGridOptions) => Promise<PrintGridResult>;\n};\n\n/** Wires {@link printGrid} to the grid's store instance, for toolbar buttons and custom triggers. */\nexport function useDataGridPrint(): UseDataGridPrintResult {\n  const storeApi = useDataGridStoreApi();\n\n  const run = useCallback(\n    (options?: PrintGridOptions) => printGrid(storeApi.getState(), options),\n    [storeApi],\n  );\n\n  return { printGrid: run };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/use-data-grid-print.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/print-button.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { Printer } from \"lucide-react\";\nimport { useDataGridLabels } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { Button } from \"@/components/ui/button\";\nimport { useDataGridPrint } from \"./use-data-grid-print\";\nimport type { PrintGridOptions } from \"./print-grid\";\n\n/** Props for {@link DataGridPrintButton}. */\nexport type DataGridPrintButtonProps = {\n  className?: string;\n  /** Print options applied to the pass; default `{ scope: \"view\", includeHeaders: true }`. */\n  options?: PrintGridOptions;\n};\n\n/**\n * Toolbar-slot print trigger: opens the browser print dialog with the grid's rows as a plain\n * paged table (the dialog's \"Save as PDF\" produces the PDF). `size-8` + ghost variant matches\n * the toolbar's other icon buttons.\n */\nexport function DataGridPrintButton(props: DataGridPrintButtonProps): ReactNode {\n  const { className, options } = props;\n  const labels = useDataGridLabels();\n  const { printGrid } = useDataGridPrint();\n  const [busy, setBusy] = useState(false);\n  const runRef = useRef<AbortController | null>(null);\n\n  useEffect(() => () => runRef.current?.abort(), []);\n\n  const print = () => {\n    runRef.current?.abort();\n    const run = new AbortController();\n    runRef.current = run;\n    const signal = options?.signal ? AbortSignal.any([options.signal, run.signal]) : run.signal;\n    setBusy(true);\n    printGrid({ ...options, signal })\n      .catch((error: unknown) => {\n        if (!run.signal.aborted && isDev()) console.warn(\"[data-grid-io] print failed\", error);\n      })\n      .finally(() => {\n        if (runRef.current !== run) return;\n        runRef.current = null;\n        setBusy(false);\n      });\n  };\n\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"icon\"\n      className={className}\n      aria-label={labels.io.printButtonAriaLabel}\n      aria-busy={busy || undefined}\n      onClick={print}\n    >\n      <Printer />\n    </Button>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/print-button.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-io/parse-import-file.ts",
      "content": "import Papa from \"papaparse\";\nimport type { CellValue } from \"hucre\";\nimport { normalizeLimit } from \"./normalize-limit\";\n\n/** CSV delimiter choices exposed in the import dialog; `undefined` means auto-detect. */\nexport type CsvDelimiter = \",\" | \";\" | \"\\t\" | \"|\";\n\n/**\n * Default bounds for every import. Unbounded parsing is a memory/CPU DoS vector: a tiny xlsx with\n * two far-apart cells expands to millions of cells. File size is checked before the file is read;\n * the row, column, and cell caps are checked against the real cell extent before any conversion\n * (xlsx/xls) or by the parser's own row callback and a delimiter count (CSV). A file over a cap is rejected, never truncated.\n */\nexport const DEFAULT_IMPORT_LIMITS = {\n  /** Maximum file size in bytes; default 50 MiB. */\n  maxFileBytes: 50 * 1024 * 1024,\n  /** Maximum rows, header row included; default 1,000,000. */\n  maxRows: 1_000_000,\n  /** Maximum columns; default 1,000. */\n  maxColumns: 1_000,\n  /** Maximum cells, counted as rows times columns of the imported rectangle; default 5,000,000. */\n  maxCells: 5_000_000,\n} as const;\n\n/** Error message {@link parseImportFile} throws for a file over `maxFileBytes`. */\nexport const FILE_TOO_LARGE_MESSAGE = \"file-too-large\";\n\n/** Error message {@link parseImportFile} throws when one part of an xlsx file (a worksheet, the shared strings) unpacks to more than the part cap, `maxDecompressedBytes`, or `maxCells` times 10 bytes plus 1 MiB without it. */\nexport const PART_TOO_LARGE_MESSAGE = \"part-too-large\";\n\n/** Error message {@link parseImportFile} throws when the grid exceeds `maxRows`, `maxColumns`, or `maxCells`. */\nexport const IMPORT_TOO_MANY_CELLS_MESSAGE = \"import-too-many-cells\";\n\n/** Error message {@link parseImportFile} throws for an Excel file that is neither xlsx nor BIFF8 xls, e.g. an HTML table, Excel 2003 XML, or Excel 5.0/95. */\nexport const UNSUPPORTED_EXCEL_FORMAT_MESSAGE = \"unsupported-excel-format\";\n\n/** Import bounds; each omitted field falls back to {@link DEFAULT_IMPORT_LIMITS}. A file over any bound is rejected, never truncated. */\nexport type ImportLimits = {\n  /** Reject files above this size (bytes) before the file is read; default 50 MiB. */\n  maxFileBytes?: number;\n  /** Maximum rows, header row included; default 1,000,000. */\n  maxRows?: number;\n  /** Maximum columns; default 1,000. */\n  maxColumns?: number;\n  /** Maximum rows times columns of the imported rectangle; default 5,000,000. */\n  maxCells?: number;\n  /** Reject an xlsx whose parts (a worksheet, the shared strings) unpack to more than this many bytes; default `maxCells` times 10 bytes plus 1 MiB. Stops zip bombs. */\n  maxDecompressedBytes?: number;\n};\n\n/** Every import bound with its default (`maxDecompressedBytes` defaults to {@link defaultPartCap}); a `NaN` bound takes the default, a negative one counts as 0. */\nexport function resolveImportLimits(limits: ImportLimits = {}): Required<ImportLimits> {\n  const maxCells = normalizeLimit(limits.maxCells, DEFAULT_IMPORT_LIMITS.maxCells);\n  return {\n    maxFileBytes: normalizeLimit(limits.maxFileBytes, DEFAULT_IMPORT_LIMITS.maxFileBytes),\n    maxRows: normalizeLimit(limits.maxRows, DEFAULT_IMPORT_LIMITS.maxRows),\n    maxColumns: normalizeLimit(limits.maxColumns, DEFAULT_IMPORT_LIMITS.maxColumns),\n    maxCells,\n    maxDecompressedBytes: normalizeLimit(limits.maxDecompressedBytes, defaultPartCap(maxCells)),\n  };\n}\n\n/** Options for {@link parseImportFile}. */\nexport type ParseImportFileOptions = ImportLimits & {\n  /** Overrides CSV delimiter auto-detection; ignored for xlsx/xls. */\n  csvDelimiter?: CsvDelimiter;\n  /** For xlsx/xls: import this sheet by name instead of the first; rejects when the workbook has no sheet by that name. Ignored for CSV. */\n  sheetName?: string;\n  /** Decodes a CSV file with this label instead of UTF-8. Only the labels in {@link IMPORT_CSV_ENCODINGS} are accepted; any other label throws a `RangeError`. Ignored for xlsx/xls. */\n  csvEncoding?: ImportCsvEncoding;\n  /** For xlsx/xls: `\"formatted\"` (default) renders each cell through its number format; `\"raw\"` reads the stored value: a number as `String(n)`, a date as ISO 8601, a boolean as `true` or `false`, an error cell as empty. A string stays as is. Ignored for CSV. */\n  valueMode?: ImportValueMode;\n  /** Aborts the file read; an aborted parse rejects with an AbortError. */\n  signal?: AbortSignal;\n};\n\n/** How an Excel file's cells become import text; see {@link ParseImportFileOptions.valueMode}. */\nexport type ImportValueMode = \"formatted\" | \"raw\";\n\n/** The `TextDecoder` labels `csvEncoding` accepts. */\nexport const IMPORT_CSV_ENCODINGS = [\n  \"utf-8\",\n  \"utf-16le\",\n  \"utf-16be\",\n  \"iso-8859-1\",\n  \"iso-8859-2\",\n  \"iso-8859-15\",\n  \"windows-1250\",\n  \"windows-1251\",\n  \"windows-1252\",\n  \"windows-1253\",\n  \"windows-1254\",\n  \"windows-1257\",\n  \"shift_jis\",\n  \"euc-jp\",\n  \"euc-kr\",\n  \"gb18030\",\n  \"big5\",\n] as const;\n\n/** A label of {@link IMPORT_CSV_ENCODINGS}; the match ignores case and surrounding spaces. */\nexport type ImportCsvEncoding = (typeof IMPORT_CSV_ENCODINGS)[number] | Uppercase<(typeof IMPORT_CSV_ENCODINGS)[number]>;\n\n/** Reads a CSV file as text; a `csvEncoding` label from the allow-list decodes the bytes, otherwise the file reads as UTF-8. */\nasync function readCsvText(file: File, csvEncoding: ImportCsvEncoding | undefined): Promise<string> {\n  if (csvEncoding === undefined) return file.text();\n  const label = csvEncoding.trim().toLowerCase();\n  if (!(IMPORT_CSV_ENCODINGS as readonly string[]).includes(label)) throw new RangeError(`[data-grid-io] unsupported csvEncoding: ${csvEncoding}`);\n  return new TextDecoder(label).decode(await file.arrayBuffer());\n}\n\ntype GridLimits = Required<Pick<ImportLimits, \"maxRows\" | \"maxColumns\" | \"maxCells\">>;\ntype ExcelLimits = GridLimits & Pick<ImportLimits, \"maxDecompressedBytes\">;\n\n/** Throws the too-many-cells error when a `rows` by `columns` rectangle breaks any cap. */\nfunction assertWithinLimits(rows: number, columns: number, limits: GridLimits): void {\n  if (rows > limits.maxRows || columns > limits.maxColumns || rows * columns > limits.maxCells) {\n    throw new Error(IMPORT_TOO_MANY_CELLS_MESSAGE);\n  }\n}\n\n/** Normalized parse result: a plain 2D grid of strings, header row (if any) included at `rows[0]`. */\nexport type ParsedImportFile = {\n  rows: string[][];\n  /** Delimiter actually used (auto-detected or overridden); undefined for xlsx/xls. */\n  delimiter?: CsvDelimiter;\n  /** Every sheet name in the workbook. Undefined for CSV, or for a workbook with no sheets. */\n  sheetNames?: string[];\n  /** The sheet `rows` came from — the `sheetName` option, or the first sheet. Undefined for CSV. */\n  sheetName?: string;\n};\n\nfunction isCsvFile(file: File): boolean {\n  const name = file.name.toLowerCase();\n  return name.endsWith(\".csv\") || name.endsWith(\".tsv\") || file.type === \"text/csv\" || file.type === \"text/tab-separated-values\";\n}\n\nfunction isExcelFile(file: File): boolean {\n  const name = file.name.toLowerCase();\n  return name.endsWith(\".xlsx\") || name.endsWith(\".xls\");\n}\n\n/** Characters papaparse sees when it guesses the delimiter and the newline. */\nconst CSV_SAMPLE_CHARS = 1024 * 1024;\n\n/** The newline papaparse would guess: whichever of `\\n`, `\\r\\n`, or `\\r` ends the first line. */\nfunction detectNewline(sample: string): \"\\n\" | \"\\r\\n\" | \"\\r\" {\n  const cr = sample.indexOf(\"\\r\");\n  const lf = sample.indexOf(\"\\n\");\n  if (cr === -1 || (lf !== -1 && lf < cr)) return \"\\n\";\n  return sample[cr + 1] === \"\\n\" ? \"\\r\\n\" : \"\\r\";\n}\n\n/** Counts `char` in `text`: a quote-agnostic upper bound of the fields on one line, so no quoting rule is mirrored. */\nfunction countChar(text: string, char: string): number {\n  let count = 0;\n  for (let at = text.indexOf(char); at !== -1; at = text.indexOf(char, at + 1)) count++;\n  return count;\n}\n\n/**\n * Parses CSV text with papaparse; delimiter auto-detected unless `csvDelimiter` overrides it.\n * papaparse builds a whole row before `step` sees it, so a delimiter count above `maxCells` rejects\n * first: every field boundary is a delimiter, so one row cannot hold more fields than that. `step` then\n * stops the real parser at the first row, column, or cell breach.\n */\nfunction parseCsvText(text: string, csvDelimiter: CsvDelimiter | undefined, limits: GridLimits): ParsedImportFile {\n  const sample = text.slice(0, CSV_SAMPLE_CHARS);\n  const newline = detectNewline(sample);\n  const delimiter =\n    csvDelimiter ?? ((Papa.parse<string[]>(sample, { preview: 10, newline, skipEmptyLines: true, delimitersToGuess: [\",\", \";\", \"\t\", \"|\"] }).meta.delimiter as CsvDelimiter | undefined) || \",\");\n  if (countChar(text, delimiter) > limits.maxCells) throw new Error(IMPORT_TOO_MANY_CELLS_MESSAGE);\n  const rows: string[][] = [];\n  let columns = 0;\n  let exceeded = false;\n  Papa.parse<string[]>(text, {\n    delimiter,\n    newline,\n    skipEmptyLines: true,\n    step: (result, parser) => {\n      rows.push(result.data.map((cell) => cell ?? \"\"));\n      if (result.data.length > columns) columns = result.data.length;\n      if (rows.length > limits.maxRows || columns > limits.maxColumns || rows.length * columns > limits.maxCells) {\n        exceeded = true;\n        parser.abort();\n      }\n    },\n  });\n  if (exceeded) throw new Error(IMPORT_TOO_MANY_CELLS_MESSAGE);\n  return { rows, delimiter };\n}\n\n/** Aborts the file read; rejected parses surface as an AbortError the caller can ignore. */\nfunction abortError(): DOMException {\n  return new DOMException(\"Aborted\", \"AbortError\");\n}\n\nconst ZIP_SIGNATURE = [0x50, 0x4b, 0x03, 0x04];\nconst OLE2_SIGNATURE = [0xd0, 0xcf, 0x11, 0xe0];\n\nfunction hasSignature(bytes: Uint8Array, signature: readonly number[]): boolean {\n  return signature.every((byte, index) => bytes[index] === byte);\n}\n\n/** The smallest cell hucre stores in a sparse read, a styled empty cell `<c s=\"0\"/>`; each costs far more heap than XML. */\nconst SMALLEST_CELL_XML_BYTES = 10;\n\n/** Room in one part for everything but cells: columns, merges, validations, formatting rules. */\nconst PART_OVERHEAD_BYTES = 1024 * 1024;\n\nconst UNREADABLE_ZIP_MESSAGE = \"unreadable-zip\";\n\nconst ZIP64_SENTINEL = 0xffffffff;\n\n/** The part cap that applies without `maxDecompressedBytes`: `maxCells` times 10 bytes plus 1 MiB. */\nexport function defaultPartCap(maxCells: number): number {\n  return maxCells * SMALLEST_CELL_XML_BYTES + PART_OVERHEAD_BYTES;\n}\n\n/** The largest unpacked size any one part of an xlsx may have: an explicit `maxDecompressedBytes`, else {@link defaultPartCap}. */\nfunction partCap(limits: ExcelLimits): number {\n  return limits.maxDecompressedBytes ?? defaultPartCap(limits.maxCells);\n}\n\n/**\n * Rejects a zip with any entry whose stored or declared size exceeds `cap`. Reads only the central directory,\n * and fails closed: an unreadable directory or a ZIP64 marker rejects. Hucre bounds what it inflates itself,\n * but not stored entries.\n */\nfunction assertEntriesWithin(bytes: Uint8Array, cap: number): void {\n  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n  const lowest = Math.max(0, bytes.length - 22 - 0xffff);\n  let end = bytes.length - 22;\n  while (end >= lowest && view.getUint32(end, true) !== 0x06054b50) end--;\n  if (end < lowest) throw new Error(UNREADABLE_ZIP_MESSAGE);\n  const count = view.getUint16(end + 10, true);\n  let offset = view.getUint32(end + 16, true);\n  if (count === 0xffff || view.getUint32(end + 12, true) === ZIP64_SENTINEL || offset === ZIP64_SENTINEL) throw new Error(PART_TOO_LARGE_MESSAGE);\n  for (let i = 0; i < count; i++) {\n    if (offset + 46 > bytes.length || view.getUint32(offset, true) !== 0x02014b50) throw new Error(UNREADABLE_ZIP_MESSAGE);\n    const compressedSize = view.getUint32(offset + 20, true);\n    const uncompressedSize = view.getUint32(offset + 24, true);\n    if (compressedSize > cap || uncompressedSize > cap || compressedSize === ZIP64_SENTINEL || uncompressedSize === ZIP64_SENTINEL) throw new Error(PART_TOO_LARGE_MESSAGE);\n    offset += 46 + view.getUint16(offset + 28, true) + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true);\n  }\n}\n\ntype HucreReader = typeof import(\"./xlsx-reader\");\ntype FormatValue = HucreReader[\"formatValue\"];\ntype CellVisitor = (row: number, col: number, value: CellValue, numFmt: string | undefined, isError?: boolean) => void;\n\n/** A date without a number format (xls, ISO cells): ISO date, plus the time when it is not midnight. */\nfunction isoDateText(date: Date, separator = \" \"): string {\n  if (Number.isNaN(date.getTime())) return \"\";\n  const iso = date.toISOString();\n  return iso.endsWith(\"T00:00:00.000Z\") ? iso.slice(0, 10) : iso.slice(0, 19).replace(\"T\", separator);\n}\n\n/** A cell's stored value as text, with no number format: ISO 8601 dates, `true` or `false`, full-precision numbers. */\nfunction rawCellText(value: CellValue, isError: boolean): string {\n  if (value === null || isError) return \"\";\n  if (typeof value === \"number\") return String(value);\n  if (typeof value === \"boolean\") return String(value);\n  if (value instanceof Date) return isoDateText(value, \"T\");\n  return value;\n}\n\n/** Excel's own limit on a number format's length; hucre's format scanning grows quadratically past it. */\nconst MAX_NUMBER_FORMAT_LENGTH = 255;\n\n/** A fraction denominator of four or more placeholders: hucre searches every denominator up to 10^n, about a second per cell at n = 9. */\nconst WIDE_FRACTION_DENOMINATOR = /\\/[?#0]{4}/;\n\n/** The format as hucre's fraction test sees it: conditions, colors, locales, and fill codes stripped, literals masked. */\nfunction fractionView(numFmt: string): string {\n  return numFmt\n    .replace(/\\[[<>=!]+-?\\d+(?:\\.\\d+)?\\]/g, \"\")\n    .replace(/\\[(?:Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color\\s*\\d+)\\]/gi, \"\")\n    .replace(/\\[\\$[^\\]]*\\]/g, \"\")\n    .replace(/[_*]./g, \"\")\n    .replace(/\"[^\"]*\"?|\\\\[\\s\\S]?/g, \"\\0\");\n}\n\nfunction isSafeNumberFormat(numFmt: string): boolean {\n  return numFmt.length <= MAX_NUMBER_FORMAT_LENGTH && !WIDE_FRACTION_DENOMINATOR.test(fractionView(numFmt));\n}\n\n/** The number format's rendering, or `undefined` when the format is unsafe or hucre cannot apply it. */\nfunction formattedText(value: CellValue, numFmt: string | undefined, formatValue: FormatValue): string | undefined {\n  if (numFmt === undefined || numFmt === \"General\" || !isSafeNumberFormat(numFmt)) return undefined;\n  try {\n    return formatValue(value, numFmt);\n  } catch {\n    return undefined;\n  }\n}\n\n/** A cell's display text: its number format when it has a usable one, else Excel's General rendering. */\nfunction cellText(value: CellValue, numFmt: string | undefined, formatValue: FormatValue): string {\n  if (value === null) return \"\";\n  const formatted = formattedText(value, numFmt, formatValue);\n  if (formatted !== undefined) return formatted;\n  // 15 significant digits is Excel's precision: 0.1 + 0.2 shows as 0.3\n  if (typeof value === \"number\") return String(Number(value.toPrecision(15)));\n  if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n  if (value instanceof Date) return isoDateText(value);\n  return value;\n}\n\n/** Builds the string grid from A1 to the last non-empty cell, after checking that box against the limits. */\nfunction textGrid(forEachCell: (visit: CellVisitor) => void, limits: GridLimits, formatValue: FormatValue, valueMode: ImportValueMode = \"formatted\"): string[][] {\n  let rowCount = 0;\n  let columnCount = 0;\n  forEachCell((row, col, value) => {\n    if (value === null) return;\n    if (row >= rowCount) rowCount = row + 1;\n    if (col >= columnCount) columnCount = col + 1;\n  });\n  assertWithinLimits(rowCount, columnCount, limits);\n  const grid = Array.from({ length: rowCount }, () => new Array<string>(columnCount).fill(\"\"));\n  forEachCell((row, col, value, numFmt, isError) => {\n    if (value !== null) grid[row]![col] = valueMode === \"raw\" ? rawCellText(value, isError === true) : cellText(value, numFmt, formatValue);\n  });\n  return grid;\n}\n\n/** Maps hucre's limit errors to gridcn's messages; hucre has no error codes, so its message text is matched. */\nfunction importError(err: unknown, hucre: HucreReader): unknown {\n  if (err instanceof hucre.ZipError && err.message.includes(\"exceeds limit\")) return new Error(PART_TOO_LARGE_MESSAGE, { cause: err });\n  if (err instanceof hucre.ParseError) {\n    if (/over the \\d+ limit|more than \\d+ filled cells/.test(err.message)) return new Error(IMPORT_TOO_MANY_CELLS_MESSAGE, { cause: err });\n    if (err.message.startsWith(\"Unsupported XLS version\")) return new Error(UNSUPPORTED_EXCEL_FORMAT_MESSAGE, { cause: err });\n  }\n  return err;\n}\n\n/** Reads the selected sheet of an xlsx workbook. Sparse mode keeps memory proportional to the real cells, whatever their box. */\nasync function readXlsxSheet(\n  bytes: Uint8Array,\n  sheetName: string | undefined,\n  limits: ExcelLimits,\n  { readXlsx, formatValue }: HucreReader,\n  valueMode: ImportValueMode,\n): Promise<ParsedImportFile> {\n  const sheetNames: string[] = [];\n  const workbook = await readXlsx(bytes, {\n    sheets: (info) => {\n      sheetNames.push(info.name);\n      return sheetName === undefined ? info.index === 0 : info.name === sheetName;\n    },\n    sparse: true,\n    readStyles: true,\n    maxDecompressedBytes: limits.maxDecompressedBytes,\n  });\n  if (sheetName !== undefined && !sheetNames.includes(sheetName)) throw new Error(`unknown sheet \"${sheetName}\"`);\n  const sheet = workbook.sheets[0];\n  if (!sheet) return { rows: [], sheetNames, sheetName };\n  const rows = textGrid(\n    (visit) => {\n      for (const [key, cell] of sheet.cells ?? []) {\n        const comma = key.indexOf(\",\");\n        visit(Number(key.slice(0, comma)), Number(key.slice(comma + 1)), cell.value, cell.style?.numFmt, cell.type === \"error\");\n      }\n    },\n    limits,\n    formatValue,\n    valueMode,\n  );\n  return { rows, sheetNames, sheetName: sheet.name };\n}\n\nconst OLE2_END_OF_CHAIN = 0xfffffffe;\nconst OLE2_FREE_SECTOR = 0xffffffff;\nconst OLE2_SECTOR_SHIFTS = [9, 12];\nconst OLE2_MINI_SECTOR_SHIFT = 6;\nconst OLE2_DEFAULT_MINI_CUTOFF = 4096;\nconst OLE2_DIRECTORY_ENTRY_BYTES = 128;\nconst UNREADABLE_XLS_MESSAGE = \"unreadable-xls\";\n\n/** Records a workbook may hold besides its cells: formats, styles, fonts, sheet metadata. */\nconst XLS_RECORD_SLACK = 100_000;\n\n/** The most records an xls workbook may hold: hucre keeps about 300 bytes per record, so half a record per cell of `maxCells` stays near 0.8 GB at the defaults. */\nfunction maxXlsRecords(maxCells: number): number {\n  return maxCells / 2 + XLS_RECORD_SLACK;\n}\n\ntype Ole2Entry = { name: string; type: number; start: number; size: number };\n\nconst unreadableXls = () => new Error(UNREADABLE_XLS_MESSAGE);\n\n/**\n * The `Workbook` (or `Book`) stream of an OLE2 container, read the way hucre's reader reads it. Fails closed\n * wherever hucre would take a path the scan cannot follow: duplicate stream names, chain loops, sizes past the data.\n */\nfunction readOle2Workbook(bytes: Uint8Array): Uint8Array {\n  if (bytes.length < 512) throw unreadableXls();\n  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n  const sectorShift = view.getUint16(30, true);\n  if (!OLE2_SECTOR_SHIFTS.includes(sectorShift) || view.getUint16(32, true) !== OLE2_MINI_SECTOR_SHIFT) throw unreadableXls();\n  const sectorSize = 1 << sectorShift;\n  const miniSectorSize = 1 << OLE2_MINI_SECTOR_SHIFT;\n  const fatSectorCount = view.getUint32(44, true);\n  const miniCutoff = view.getUint32(56, true) || OLE2_DEFAULT_MINI_CUTOFF;\n  const miniFatSectorCount = view.getUint32(64, true);\n  const difatSectorCount = view.getUint32(72, true);\n  const maxSectors = Math.floor(bytes.length / sectorSize) + 1;\n  const sectorAt = (sector: number) => {\n    const at = (sector + 1) * sectorSize;\n    if (at + sectorSize > bytes.length) throw unreadableXls();\n    return at;\n  };\n  const fatSectors: number[] = [];\n  for (let i = 0; i < 109 && fatSectors.length < fatSectorCount; i++) {\n    const sector = view.getUint32(76 + i * 4, true);\n    if (sector === OLE2_FREE_SECTOR || sector === OLE2_END_OF_CHAIN) break;\n    fatSectors.push(sector);\n  }\n  const difatLimit = Math.min(difatSectorCount, maxSectors);\n  let difat = view.getUint32(68, true);\n  for (let hops = 0; difat !== OLE2_END_OF_CHAIN && difat !== OLE2_FREE_SECTOR && difatLimit > 0 && hops < difatLimit + 1; hops++) {\n    const at = sectorAt(difat);\n    for (let i = 0; i < sectorSize / 4 - 1 && fatSectors.length < fatSectorCount; i++) {\n      const sector = view.getUint32(at + i * 4, true);\n      if (sector !== OLE2_FREE_SECTOR && sector !== OLE2_END_OF_CHAIN) fatSectors.push(sector);\n    }\n    difat = view.getUint32(at + sectorSize - 4, true);\n  }\n  if (fatSectors.length > maxSectors || new Set(fatSectors).size !== fatSectors.length) throw unreadableXls();\n  const fat = new Uint32Array((fatSectors.length * sectorSize) / 4);\n  fatSectors.forEach((sector, index) => {\n    const at = sectorAt(sector);\n    for (let i = 0; i < sectorSize / 4; i++) fat[(index * sectorSize) / 4 + i] = view.getUint32(at + i * 4, true);\n  });\n\n  let hopsLeft = fat.length;\n  const walk = (start: number): number[] => {\n    const sectors: number[] = [];\n    for (let sector = start; sector !== OLE2_END_OF_CHAIN && sector !== OLE2_FREE_SECTOR; sector = fat[sector] ?? OLE2_END_OF_CHAIN) {\n      if (--hopsLeft < 0) throw unreadableXls();\n      sectorAt(sector);\n      sectors.push(sector);\n    }\n    return sectors;\n  };\n  const readChain = (start: number): Uint8Array => {\n    const sectors = walk(start);\n    const out = new Uint8Array(sectors.length * sectorSize);\n    sectors.forEach((sector, index) => out.set(bytes.subarray(sectorAt(sector), sectorAt(sector) + sectorSize), index * sectorSize));\n    return out;\n  };\n\n  const directory = readChain(view.getUint32(48, true));\n  const directoryView = new DataView(directory.buffer);\n  const entries: Ole2Entry[] = [];\n  for (let at = 0; at + OLE2_DIRECTORY_ENTRY_BYTES <= directory.length; at += OLE2_DIRECTORY_ENTRY_BYTES) {\n    const type = directory[at + 66]!;\n    if (type === 0) continue;\n    const nameLength = directoryView.getUint16(at + 64, true);\n    let name = \"\";\n    for (let i = 0; i + 1 < nameLength; i += 2) {\n      const code = directoryView.getUint16(at + i, true);\n      if (code === 0) break;\n      name += String.fromCharCode(code);\n    }\n    entries.push({ name, type, start: directoryView.getUint32(at + 116, true), size: directoryView.getUint32(at + 120, true) });\n  }\n  const root = entries.find((entry) => entry.type === 5);\n  if (!root) throw unreadableXls();\n  const streams = entries.filter((entry) => entry.type === 2);\n  const workbooks = streams.filter((entry) => entry.name === \"Workbook\");\n  const books = streams.filter((entry) => entry.name === \"Book\");\n  if (workbooks.length > 1 || books.length > 1) throw unreadableXls();\n  const workbook = workbooks[0] ?? books[0];\n  if (!workbook) throw unreadableXls();\n  if (streams.reduce((total, entry) => total + entry.size, 0) > bytes.length) throw unreadableXls();\n\n  const miniStream = readChain(root.start).subarray(0, root.size);\n  const miniFatBytes =\n    miniFatSectorCount > 0 && view.getUint32(60, true) !== OLE2_END_OF_CHAIN ? readChain(view.getUint32(60, true)).subarray(0, miniFatSectorCount * sectorSize) : new Uint8Array(0);\n  const miniFatView = new DataView(miniFatBytes.buffer, miniFatBytes.byteOffset, miniFatBytes.byteLength);\n  const miniFatLength = Math.floor(miniFatBytes.length / 4);\n  let workbookBytes: Uint8Array = new Uint8Array(0);\n  for (const stream of streams) {\n    if (stream.size < miniCutoff) {\n      if (stream.size > miniStream.length) throw unreadableXls();\n      if (stream !== workbook) continue;\n      workbookBytes = new Uint8Array(stream.size);\n      let filled = 0;\n      for (let sector = stream.start, hops = 0; filled < stream.size; sector = miniFatView.getUint32(sector * 4, true), hops++) {\n        if (hops > miniFatLength || sector >= miniFatLength || (sector + 1) * miniSectorSize > miniStream.length) throw unreadableXls();\n        const chunk = miniStream.subarray(sector * miniSectorSize, (sector + 1) * miniSectorSize);\n        workbookBytes.set(chunk.subarray(0, stream.size - filled), filled);\n        filled += chunk.length;\n      }\n    } else if (stream === workbook) {\n      workbookBytes = readChain(stream.start).subarray(0, stream.size);\n    } else {\n      walk(stream.start);\n    }\n  }\n  return workbookBytes;\n}\n\nconst BIFF_BOF = 0x809;\nconst BIFF_EOF = 0x0a;\nconst BIFF_BOUNDSHEET = 0x85;\nconst BIFF8_VERSION = 0x600;\nconst BIFF_CELL_RECORDS = new Set([0xfd, 0x27e, 0x203, 0x205, 0x204, 0x06]);\nconst BIFF_MULRK = 0xbd;\nconst BIFF_MULRK_CELL_BYTES = 6;\n\ntype BiffRecord = { id: number; data: number; length: number };\n\n/** Walks the BIFF records from `offset`, as hucre's `parseRecords` does; a record cut short by the stream end keeps the bytes that exist. */\nfunction* biffRecords(stream: Uint8Array, view: DataView, offset: number): Generator<BiffRecord, void> {\n  for (let at = offset; at + 4 <= stream.length; ) {\n    const id = view.getUint16(at, true);\n    const length = view.getUint16(at + 2, true);\n    const data = at + 4;\n    yield { id, data, length: Math.min(length, stream.length - data) };\n    if (id === 0 && length === 0) return;\n    at = data + length;\n  }\n}\n\n/** How many records hucre's `parseRecords` would build, counted without building them; stops at `cap + 1`. */\nfunction biffRecordCount(stream: Uint8Array, view: DataView, cap: number): number {\n  let count = 0;\n  for (let at = 0; at + 4 <= stream.length && count <= cap; count++) {\n    const length = view.getUint16(at + 2, true);\n    if (length === 0 && view.getUint16(at, true) === 0) return count + 1;\n    at += 4 + length;\n  }\n  return count;\n}\n\n/** The cells a worksheet substream spans, and where its records end; reads on from the record after `start`, as hucre does, and stops once the span passes `cap`. */\nfunction biffSheetBox(stream: Uint8Array, view: DataView, start: number, cap: number): { cells: number; end: number } {\n  let rows = 0;\n  let columns = 0;\n  let end = start;\n  let atStart = true;\n  for (const { id, data, length } of biffRecords(stream, view, start)) {\n    end = data + length;\n    if (atStart) {\n      atStart = false;\n      continue;\n    }\n    if (id === BIFF_EOF) break;\n    const mulrk = id === BIFF_MULRK;\n    if (length < 4 || !(mulrk || BIFF_CELL_RECORDS.has(id))) continue;\n    let lastColumn = view.getUint16(data + 2, true);\n    if (mulrk) {\n      if (length < 6) continue;\n      const cells = (length - 6) / BIFF_MULRK_CELL_BYTES;\n      if (!Number.isInteger(cells)) throw unreadableXls();\n      if (cells === 0) continue;\n      lastColumn += cells - 1;\n    }\n    rows = Math.max(rows, view.getUint16(data, true) + 1);\n    columns = Math.max(columns, lastColumn + 1);\n    if (rows * columns > cap) break;\n  }\n  return { cells: rows * columns, end };\n}\n\n// hucre pads every sheet and builds one object per record; bound both before it runs.\nfunction assertXlsWithinLimits(bytes: Uint8Array, limits: GridLimits): void {\n  const stream = readOle2Workbook(bytes);\n  const view = new DataView(stream.buffer, stream.byteOffset, stream.byteLength);\n  if (biffRecordCount(stream, view, maxXlsRecords(limits.maxCells)) > maxXlsRecords(limits.maxCells)) throw new Error(IMPORT_TOO_MANY_CELLS_MESSAGE);\n  const sheetStarts: number[] = [];\n  let atStart = true;\n  for (const { id, data, length } of biffRecords(stream, view, 0)) {\n    if (atStart) {\n      if (id !== BIFF_BOF || (length >= 2 && view.getUint16(data, true) !== BIFF8_VERSION)) return;\n      atStart = false;\n      continue;\n    }\n    if (id === BIFF_EOF) break;\n    if (id === BIFF_BOUNDSHEET && length >= 4) sheetStarts.push(view.getUint32(data, true));\n  }\n  const boxes = new Map<number, number>();\n  let total = 0;\n  let scanBudget = stream.length;\n  for (const start of sheetStarts) {\n    if (!boxes.has(start)) {\n      const { cells, end } = biffSheetBox(stream, view, start, limits.maxCells);\n      scanBudget -= end - start;\n      if (scanBudget < 0) throw unreadableXls();\n      boxes.set(start, cells);\n    }\n    total += boxes.get(start)!;\n    if (total > limits.maxCells) throw new Error(IMPORT_TOO_MANY_CELLS_MESSAGE);\n  }\n}\n\n/** Reads a BIFF8 `.xls` workbook; hucre parses every sheet, each bounded by `maxCells`, and returns values without number formats. */\nasync function readXlsSheet(\n  bytes: Uint8Array,\n  sheetName: string | undefined,\n  limits: GridLimits,\n  { readXls, formatValue }: HucreReader,\n  valueMode: ImportValueMode,\n): Promise<ParsedImportFile> {\n  assertXlsWithinLimits(bytes, limits);\n  const workbook = await readXls(bytes, { maxTotalCells: limits.maxCells });\n  const sheetNames = workbook.sheets.map((sheet) => sheet.name);\n  const selected = sheetName !== undefined ? sheetNames.indexOf(sheetName) : 0;\n  if (selected === -1) throw new Error(`unknown sheet \"${sheetName}\"`);\n  const sheet = workbook.sheets[selected];\n  if (!sheet) return { rows: [], sheetNames, sheetName };\n  const rows = textGrid((visit) => sheet.rows.forEach((row, r) => row.forEach((value, c) => visit(r, c, value, undefined))), limits, formatValue, valueMode);\n  return { rows, sheetNames, sheetName: sheet.name };\n}\n\n/** Parses one sheet of an xlsx/xls workbook into a 2D string grid via lazily-imported hucre; `sheetName` selects the sheet (first by default). The file's signature, not its extension, picks the reader. */\nasync function parseExcelFile(file: File, sheetName: string | undefined, limits: ExcelLimits, valueMode: ImportValueMode, signal?: AbortSignal): Promise<ParsedImportFile> {\n  const bytes = new Uint8Array(await file.arrayBuffer());\n  if (signal?.aborted) throw abortError();\n  const isXlsx = hasSignature(bytes, ZIP_SIGNATURE);\n  if (!isXlsx && !hasSignature(bytes, OLE2_SIGNATURE)) throw new Error(UNSUPPORTED_EXCEL_FORMAT_MESSAGE);\n  const partBytes = partCap(limits);\n  const parseLimits = isXlsx ? { ...limits, maxDecompressedBytes: partBytes } : limits;\n  if (isXlsx) assertEntriesWithin(bytes, partBytes);\n  const hucre = await import(\"./xlsx-reader\");\n  try {\n    return await (isXlsx ? readXlsxSheet : readXlsSheet)(bytes, sheetName, parseLimits, hucre, valueMode);\n  } catch (err) {\n    throw importError(err, hucre);\n  }\n}\n\n/**\n * Parses a `.csv`, `.tsv`, `.xlsx`, or `.xls` file into a normalized 2D string grid. CSV/TSV goes\n * through papaparse (delimiter auto-detect + override); Excel formats go through a\n * dynamically-imported hucre (it never loads for CSV-only consumers), the `sheetName` sheet\n * or the first one. `.xls` means Excel 97-2003 (BIFF8); other `.xls` flavours reject. `signal`\n * aborts the file read when set; an aborted parse rejects with an AbortError.\n */\nexport async function parseImportFile(file: File, options: ParseImportFileOptions = {}): Promise<ParsedImportFile> {\n  const { signal } = options;\n  const { maxFileBytes, maxDecompressedBytes, ...limits } = resolveImportLimits(options);\n  // before any file read: file.size is synchronous, so the DoS check costs nothing\n  if (file.size > maxFileBytes) throw new Error(FILE_TOO_LARGE_MESSAGE);\n  if (isExcelFile(file)) {\n    return parseExcelFile(file, options.sheetName, { ...limits, maxDecompressedBytes }, options.valueMode === \"raw\" ? \"raw\" : \"formatted\", signal);\n  }\n  if (isCsvFile(file)) {\n    const text = await readCsvText(file, options.csvEncoding);\n    if (signal?.aborted) throw abortError();\n    const parsed = parseCsvText(text, options.csvDelimiter, limits);\n    let columns = 0;\n    for (const row of parsed.rows) if (row.length > columns) columns = row.length;\n    assertWithinLimits(parsed.rows.length, columns, limits);\n    return parsed;\n  }\n  throw new Error(\"unsupported-file-type\");\n}\n\n/** Thrown for a parse result or row hook output that is not an array of string rows. */\nexport const INVALID_IMPORT_ROWS_MESSAGE = \"invalid-import-rows\";\n\n/**\n * Checks rows that came from a consumer hook (`parseFile`, `processImportRows`): an array of arrays of\n * strings inside the `maxRows`, `maxColumns`, and `maxCells` bounds. `extraRows` counts rows the caller\n * holds beside `rows` (a header row). Throws {@link INVALID_IMPORT_ROWS_MESSAGE} or the too-many-cells error.\n */\nexport function assertImportRows(rows: unknown, limits: ImportLimits, extraRows = 0): asserts rows is string[][] {\n  if (!Array.isArray(rows)) throw new Error(INVALID_IMPORT_ROWS_MESSAGE);\n  const { maxRows, maxColumns, maxCells } = resolveImportLimits(limits);\n  const bounds: GridLimits = { maxRows, maxColumns, maxCells };\n  let columns = 0;\n  for (const row of rows as unknown[]) {\n    if (!Array.isArray(row)) throw new Error(INVALID_IMPORT_ROWS_MESSAGE);\n    if (row.length > columns) columns = row.length;\n    if (columns > bounds.maxColumns) throw new Error(IMPORT_TOO_MANY_CELLS_MESSAGE);\n    for (const cell of row as unknown[]) if (typeof cell !== \"string\") throw new Error(INVALID_IMPORT_ROWS_MESSAGE);\n  }\n  assertWithinLimits(rows.length + extraRows, columns, bounds);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/parse-import-file.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/xlsx-reader.ts",
      "content": "// A static re-export per direction lets bundlers tree-shake hucre's barrels inside the lazy chunk.\nexport { readXls, readXlsx } from \"hucre/xlsx\";\nexport { formatValue, ParseError, ZipError } from \"hucre\";\n",
      "type": "registry:component",
      "target": "components/data-grid-io/xlsx-reader.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/match-import-column.ts",
      "content": "import type { GateContext } from \"@/registry/default/components/data-grid/data-grid\";\nimport { columnLabelText, isThenable } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport type { CsvDelimiter, ImportValueMode } from \"./parse-import-file\";\n\n/** Minimal column shape the header-matching/preview logic needs — matches `ColumnDef` structurally. */\nexport type ImportTargetColumn = { id: string; headerText?: string; header: unknown };\n\n/**\n * Consumer-configurable defaults applied at PRESELECTION time only — the user can always\n * override any of these in the dialog once it's open.\n */\nexport type ImportDefaults = {\n  /** Skip auto-detect and preselect this delimiter. Detect still runs if undefined. */\n  defaultDelimiter?: CsvDelimiter;\n  /** How an Excel file's cells become text: `\"formatted\"` (default) applies number formats, `\"raw\"` reads stored values (see `ParseImportFileOptions.valueMode`). */\n  valueMode?: ImportValueMode;\n  /** Default for the header-row toggle. A number is the 0-based index of the header row: the rows above it are dropped, and that row is the header. `true` is `0`. Default `true`. */\n  defaultHeaderRow?: boolean | number;\n  /** Source columns to preselect as skipped: header names (case-insensitive) or indices. */\n  defaultSkipColumns?: readonly (string | number)[];\n  /**\n   * Override the initial mapping per source column; return undefined to fall back to the\n   * built-in matcher, null to skip. Wins over `defaultSkipColumns`. A promise holds the mapping\n   * until it settles; a rejection falls back to the built-in matcher. `signal` aborts when a newer\n   * parse of the dialog supersedes this one or the dialog unmounts; an aborted mapping is dropped.\n   * Inside a grid, `gateTimeoutMs.mapColumn` aborts a pending mapping and falls back to the built-in matcher.\n   */\n  mapColumn?: (header: string, index: number, ctx: GateContext) => string | null | undefined | Promise<string | null | undefined>;\n};\n\nfunction firstWins(columns: readonly ImportTargetColumn[], keyOf: (column: ImportTargetColumn) => string): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const column of columns) {\n    const key = keyOf(column);\n    if (!map.has(key)) map.set(key, column.id);\n  }\n  return map;\n}\n\n/**\n * Prefills the import-column -> grid-column mapping by matching each imported header against\n * `column.headerText ?? header ?? column.id`, case-insensitively. Unmatched headers map to `null`\n * (the dialog's '—' skip option). Each grid column can only be claimed once — a later duplicate\n * match falls back to `null` (skip) since one-source-per-grid-column is enforced everywhere.\n */\nexport function matchImportColumns(importHeaders: readonly string[], gridColumns: readonly ImportTargetColumn[]): (string | null)[] {\n  const byLowerText = firstWins(gridColumns, (column) => columnLabelText(column).toLowerCase());\n  const byLowerId = firstWins(gridColumns, (column) => column.id.toLowerCase());\n\n  const claimed = new Set<string>();\n  return importHeaders.map((header) => {\n    const key = header.trim().toLowerCase();\n    const gridColumnId = byLowerText.get(key) ?? byLowerId.get(key) ?? null;\n    if (gridColumnId === null || claimed.has(gridColumnId)) return null;\n    claimed.add(gridColumnId);\n    return gridColumnId;\n  });\n}\n\n/** True when `defaultSkipColumns` names `header` (case-insensitive) or `index` (0-based). */\nfunction isDefaultSkipped(header: string, index: number, defaultSkipColumns: readonly (string | number)[]): boolean {\n  const key = header.trim().toLowerCase();\n  return defaultSkipColumns.some((entry) => (typeof entry === \"number\" ? entry === index : entry.trim().toLowerCase() === key));\n}\n\n/**\n * Preselects the import-column -> grid-column mapping: starts from {@link matchImportColumns},\n * then applies `options.defaultSkipColumns` (by header name or index), then `options.mapColumn`\n * per column (wins over `defaultSkipColumns`; `undefined` keeps whatever came before it). All of\n * this only decides the dialog's *initial* mapping — the user can still change every cell by hand\n * once the dialog is open. A grid column that two import columns claim stays with the first\n * one, whether the matcher or `mapColumn` named it; the later import column maps to `null`.\n */\nexport function applyImportOptions(\n  importHeaders: readonly string[],\n  gridColumns: readonly ImportTargetColumn[],\n  options: { defaultSkipColumns?: readonly (string | number)[]; mapColumn?: (header: string, index: number) => string | null | undefined } = {},\n): (string | null)[] {\n  return resolveImportMapping(importHeaders, gridColumns, options) as (string | null)[];\n}\n\n/** {@link applyImportOptions} for a `mapColumn` that may answer with a promise: a Promise when any column does, else the plain array. */\nexport function resolveImportMapping(\n  importHeaders: readonly string[],\n  gridColumns: readonly ImportTargetColumn[],\n  options: Pick<ImportDefaults, \"defaultSkipColumns\" | \"mapColumn\"> & { signal?: AbortSignal } = {},\n): (string | null)[] | Promise<(string | null)[]> {\n  const { defaultSkipColumns, mapColumn } = options;\n  const gateCtx: GateContext = { signal: options.signal ?? new AbortController().signal };\n  const matched = matchImportColumns(importHeaders, gridColumns);\n  const overridden = matched.map((gridColumnId, index) => {\n    const header = importHeaders[index] ?? \"\";\n    return defaultSkipColumns && isDefaultSkipped(header, index, defaultSkipColumns) ? null : gridColumnId;\n  });\n  const overrides = matched.map((_, index) => mapColumn?.(importHeaders[index] ?? \"\", index, gateCtx));\n  const combine = (resolved: readonly (string | null | undefined)[]) => {\n    const claimed = new Set<string>();\n    return overridden.map((kept, index) => {\n      const id = resolved[index] === undefined ? kept : resolved[index]!;\n      if (id === null || claimed.has(id)) return null;\n      claimed.add(id);\n      return id;\n    });\n  };\n  return overrides.some((override) => isThenable(override)) ? Promise.all(overrides).then(combine) : combine(overrides as (string | null | undefined)[]);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/match-import-column.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/build-imported-rows.ts",
      "content": "import type { AnyColumnDef, CellType, ColumnDef, GateContext } from \"@/registry/default/components/data-grid/data-grid\";\nimport type { ValidateBatchItem, ValidateResult } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { createWarnOnce, isDev, isThenable, parseWithHook, resolveColumnValidate, runValidateBatch, safeFromText, settleHookFailure, setCellValue, validateContextsFor } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/** One import-column -> grid-column mapping entry; `null` skips the import column. */\nexport type ImportColumnMapping = { importColumnIndex: number; gridColumnId: string | null };\n\n/** Above this row count, `buildImportedRows` yields between chunks so the dialog stays responsive and Cancel can land. */\nexport const IMPORT_CHUNK_THRESHOLD_ROWS = 5_000;\n\n/** Rows processed per chunk once {@link IMPORT_CHUNK_THRESHOLD_ROWS} is exceeded. */\nconst CHUNK_SIZE = 2_000;\n\n/** One import cell whose value failed `column.validate`: the cell is cleared with its cell type's `clearValue()`, and the row is still imported. */\nexport type ImportRejectedCell = {\n  /** 0-based index into `dataRows` (header row excluded). */\n  rowIndex: number;\n  /** 0-based index of the source column in the import file. */\n  importColumnIndex: number;\n  /** The grid column the value was mapped to and cleared in. */\n  gridColumnId: string;\n  /** The validator's reason, cut at {@link MAX_REJECTED_MESSAGE_LENGTH} characters. */\n  message?: string;\n};\n\n/** Longest validator message an {@link ImportRejectedCell} keeps. */\nexport const MAX_REJECTED_MESSAGE_LENGTH = 200;\n\n/** Replaces `cellType.fromText` for one import cell. The returned value still goes through the column's `validate`. */\nexport type ProcessCellFromText<TData> = (\n  text: string,\n  ctx: {\n    /** The row as `createRow` returned it. */\n    row: TData;\n    column: ColumnDef<TData, unknown, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n    source: \"import\";\n    signal: AbortSignal;\n    /** The column's own parser, for the cells you do not change. */\n    fromText: (text: string) => unknown;\n  },\n) => unknown;\n\n/** Result of {@link buildImportedRows}: the built rows plus every rejected (cleared) cell. */\nexport type BuildImportedRowsResult<TData> = {\n  rows: TData[];\n  /** Cells whose value failed `column.validate` and was cleared. Their rows are still built. */\n  rejected: ImportRejectedCell[];\n  /** Cells of `validationMode: \"warn\"` columns whose value failed validation. The value stays in its row, uncleared. */\n  flagged: ImportRejectedCell[];\n};\n\n/** Inputs for {@link buildImportedRows}. */\nexport type BuildImportedRowsOptions<TData> = {\n  /** Data rows only (header row, if any, already excluded by the caller). */\n  dataRows: readonly string[][];\n  mapping: readonly ImportColumnMapping[];\n  // ColumnDef's 3rd param (TValidate) erases to `any`, not `unknown` — see data-grid/store.tsx's\n  // AnyColumnDef doc: validate's function-or-schema union can't stay bivariant as a plain property.\n  columns: readonly ColumnDef<TData, unknown, any>[]; // eslint-disable-line @typescript-eslint/no-explicit-any\n  cellTypes: Record<string, CellType<TData, unknown, unknown>>;\n  /** Builds a fresh row for import row `index`; required — the dialog never writes to the grid store directly. A promise makes the build a Promise; a rejection rejects it. `ctx.signal` is `options.signal`. */\n  createRow: (index: number, ctx: GateContext) => TData | Promise<TData>;\n  /** Parses one cell instead of `cellType.fromText`; may return a promise, which makes the build asynchronous. Its value is validated like any other. */\n  processCellFromText?: ProcessCellFromText<TData>;\n  /** Checked between chunks on the chunked path (above {@link IMPORT_CHUNK_THRESHOLD_ROWS} rows, or with `processCellFromText`) and after an async `createRow`; an aborted signal throws `\"import-cancelled\"`. A small synchronous build ignores it. */\n  signal?: AbortSignal;\n  /** The rows the import joins. `unique()` compares each imported value with them and with the other imported rows. The default append passes the grid's `data`. Default `[]`. */\n  existingRows?: readonly TData[];\n  /** Runs once per built row after the build parses its cells, like the grid's `validateRow`. A verdict entry for a mapped column clears that cell and lands in `rejected`; an entry for an unmapped column lands in `flagged` with `importColumnIndex` `-1`. A throw or a rejection gives that row no verdict. Rows run in chunks, so `signal` cancels between chunks. */\n  validateRow?: (row: TData, rowId: string, ctx: GateContext) => Record<string, string> | null | undefined | Promise<Record<string, string> | null | undefined>;\n  /** The id `validateRow` receives for built row `index`. Default: `String(index)`. */\n  getRowId?: (row: TData, index: number) => string;\n};\n\n/** One import cell awaiting its validation verdict: where it goes, and what to write if the value is rejected. */\ntype ImportCell = {\n  rowIndex: number;\n  importColumnIndex: number;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- same TValidate erasure as BuildImportedRowsOptions.columns.\n  column: ColumnDef<any, unknown, any>;\n  clearedValue: unknown;\n  warn: boolean;\n};\n\n/** Thrown from the chunked path when `options.signal` is aborted between chunks. */\nexport const IMPORT_CANCELLED_MESSAGE = \"import-cancelled\";\n\n/**\n * Builds `TData` rows from parsed import rows: one `createRow(index)` per row, then each mapped\n * cell is parsed through its column's cell type `fromText` and checked by `column.validate` (or the\n * cell type's `validate`) — invalid values are cleared via `clearValue()` rather than dropping the\n * whole row, and every rejected cell is listed in the result's `rejected`.\n *\n * Always returns a Promise, and a throw rejects it. Imports above {@link IMPORT_CHUNK_THRESHOLD_ROWS} rows\n * (or with `processCellFromText`) are built in chunks that yield to the event loop, so the dialog repaints\n * and `options.signal` can cancel between chunks. Async validators run with the shared chunked concurrency cap.\n *\n * The function form's second argument is the row as `createRow` returned it, not the row with this\n * import row's earlier columns already folded in — validating a whole import row concurrently and\n * validating it left to right cannot both be true, and the fresh row is the predictable one.\n */\nexport async function buildImportedRows<TData>(options: BuildImportedRowsOptions<TData>): Promise<BuildImportedRowsResult<TData>> {\n  const built = await buildNow(options);\n  return options.validateRow ? validateBuiltRows(built, options, options.validateRow) : built;\n}\n\n/** Validation yields to the event loop after this much work; a timer turn costs up to 16 ms on Windows. */\nconst VALIDATE_YIELD_AFTER_MS = 40;\n\ntype Verdict = Record<string, string> | null | undefined;\n\n/** Runs `validateRow` over the built rows, `CHUNK_SIZE` rows at a time. A verdict reads only the keys of known columns, so a hostile object costs at most one lookup per column. */\nasync function validateBuiltRows<TData>(\n  built: BuildImportedRowsResult<TData>,\n  options: BuildImportedRowsOptions<TData>,\n  validateRow: NonNullable<BuildImportedRowsOptions<TData>[\"validateRow\"]>,\n): Promise<BuildImportedRowsResult<TData>> {\n  const { rows, rejected, flagged } = built;\n  const { columns, cellTypes, mapping, signal = NEVER_ABORTED, getRowId = (_row, index) => String(index) } = options;\n  const gateCtx: GateContext = { signal };\n  const importIndexOf = new Map<string, number>();\n  for (const m of mapping) if (m.gridColumnId !== null && !importIndexOf.has(m.gridColumnId)) importIndexOf.set(m.gridColumnId, m.importColumnIndex);\n\n  let lastYield = performance.now();\n  for (let start = 0; start < rows.length; start += CHUNK_SIZE) {\n    if (signal.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n    const end = Math.min(start + CHUNK_SIZE, rows.length);\n    const verdicts = new Array<Verdict>(end - start);\n    const settling: Promise<void>[] = [];\n    for (let offset = 0; offset < end - start; offset++) {\n      const row = rows[start + offset]!;\n      try {\n        const verdict = validateRow(row, getRowId(row, start + offset), gateCtx);\n        if (isThenable(verdict)) settling.push(Promise.resolve(verdict as Promise<Verdict>).then((value) => void (verdicts[offset] = value), () => undefined));\n        else verdicts[offset] = verdict;\n      } catch {\n        // a throw gives the row no verdict\n      }\n    }\n    if (settling.length > 0) await Promise.all(settling);\n    if (signal.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n    verdicts.forEach((verdict, offset) => {\n      if (!verdict || typeof verdict !== \"object\") return;\n      const rowIndex = start + offset;\n      for (const column of columns) {\n        if (!Object.hasOwn(verdict, column.id) || typeof verdict[column.id] !== \"string\") continue;\n        const message = verdict[column.id]!.slice(0, MAX_REJECTED_MESSAGE_LENGTH);\n        const importColumnIndex = importIndexOf.get(column.id);\n        const cellType = cellTypes[column.type ?? \"text\"];\n        if (importColumnIndex === undefined || !cellType) {\n          flagged.push({ rowIndex, importColumnIndex: -1, gridColumnId: column.id, message });\n          continue;\n        }\n        // as never: setCellValue is typed against this column's own TData/TValue, which TS can't unify with the generic TData/unknown here\n        rows[rowIndex] = setCellValue(rows[rowIndex] as never, column as never, cellType.clearValue(column.options) as never) as TData;\n        rejected.push({ rowIndex, importColumnIndex, gridColumnId: column.id, message });\n      }\n    });\n    if (performance.now() - lastYield > VALIDATE_YIELD_AFTER_MS) {\n      await yieldToEventLoop();\n      lastYield = performance.now();\n    }\n  }\n  return built;\n}\n\nfunction buildNow<TData>(options: BuildImportedRowsOptions<TData>): BuildImportedRowsResult<TData> | Promise<BuildImportedRowsResult<TData>> {\n  const { dataRows, mapping, columns, cellTypes, createRow, signal, processCellFromText, existingRows = [] } = options;\n  const columnsById = new Map(columns.map((column) => [column.id, column] as const));\n  const seenColumns = new Set<string>();\n  const warnedColumns = new Set<string>();\n  const activeMappings = mapping.filter((m): m is { importColumnIndex: number; gridColumnId: string } => {\n    if (m.gridColumnId === null) return false;\n    if (!seenColumns.has(m.gridColumnId)) {\n      seenColumns.add(m.gridColumnId);\n      return true;\n    }\n    if (isDev() && !warnedColumns.has(m.gridColumnId)) {\n      warnedColumns.add(m.gridColumnId);\n      console.warn(`[data-grid-io] buildImportedRows: grid column \"${m.gridColumnId}\" is mapped by more than one import column - the first mapping wins`);\n    }\n    return false;\n  });\n\n  if (dataRows.length > IMPORT_CHUNK_THRESHOLD_ROWS || processCellFromText) {\n    return buildImportedRowsChunked(dataRows, activeMappings, columnsById, cellTypes, createRow, signal ?? new AbortController().signal, existingRows, processCellFromText);\n  }\n\n  const gateCtx: GateContext = { signal: signal ?? new AbortController().signal };\n  const created = dataRows.map((_, index) => createRow(index, gateCtx));\n  if (created.some((row) => isThenable(row))) {\n    return Promise.all(created).then((rows) => {\n      if (signal?.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n      return finishSmallImport(dataRows, activeMappings, columnsById, cellTypes, rows, existingRows);\n    });\n  }\n  return finishSmallImport(dataRows, activeMappings, columnsById, cellTypes, created as TData[], existingRows);\n}\n\nfunction finishSmallImport<TData>(\n  dataRows: readonly string[][],\n  activeMappings: readonly ResolvedMapping[],\n  columnsById: ReadonlyMap<string, ColumnDef<TData, unknown, any>>, // eslint-disable-line @typescript-eslint/no-explicit-any\n  cellTypes: Record<string, CellType<TData, unknown, unknown>>,\n  rows: TData[],\n  existingRows: readonly TData[],\n): BuildImportedRowsResult<TData> | Promise<BuildImportedRowsResult<TData>> {\n  const rejected: ImportRejectedCell[] = [];\n  const flagged: ImportRejectedCell[] = [];\n  const { items, cells } = buildCellsForRange(dataRows, 0, dataRows.length, activeMappings, columnsById, cellTypes, rows);\n  attachValidateContexts(items, cells, existingRows);\n  const results = runValidateBatch(items);\n  if (results instanceof Promise) return results.then((resolved) => ({ rows: writeCells(rows, cells, items, resolved, rejected, flagged), rejected, flagged }));\n  return { rows: writeCells(rows, cells, items, results, rejected, flagged), rejected, flagged };\n}\n\n/** One resolved mapping entry: the source column index paired with its target column definition. */\ntype ResolvedMapping = { importColumnIndex: number; gridColumnId: string };\n\n// shortcut: a chunked import (past one chunk) checks each chunk's cells as one batch; a duplicate across chunks passes. Upgrade: settle every chunk's values before validating.\n/** Gives each function `validate` the imported cells of its column as the batch, over the rows the import joins. */\nfunction attachValidateContexts(items: ValidateBatchItem[], cells: readonly ImportCell[], existingRows: readonly unknown[]): void {\n  const contexts = validateContextsFor(existingRows, cells.map((cell) => cell.column as AnyColumnDef), cells.map((cell, i) => ({ columnId: cell.column.id, row: items[i]!.row, value: items[i]!.value })));\n  cells.forEach((cell, i) => (items[i]!.ctx = contexts.get(cell.column.id)));\n}\n\n/** Builds `rows[start, end)`'s validation items/cells against the already-created `rows` array. */\nfunction buildCellsForRange<TData>(\n  dataRows: readonly string[][],\n  start: number,\n  end: number,\n  activeMappings: readonly ResolvedMapping[],\n  columnsById: ReadonlyMap<string, ColumnDef<TData, unknown, any>>, // eslint-disable-line @typescript-eslint/no-explicit-any\n  cellTypes: Record<string, CellType<TData, unknown, unknown>>,\n  rows: TData[],\n  processCellFromText?: ProcessCellFromText<TData>,\n  signal: AbortSignal = NEVER_ABORTED,\n): { items: ValidateBatchItem[]; cells: ImportCell[] } {\n  const items: ValidateBatchItem[] = [];\n  const cells: ImportCell[] = [];\n  for (let rowIndex = start; rowIndex < end; rowIndex++) {\n    const sourceRow = dataRows[rowIndex]!; // start/end are within dataRows.length by construction\n    for (const { importColumnIndex, gridColumnId } of activeMappings) {\n      const column = columnsById.get(gridColumnId);\n      if (!column) continue;\n      const cellType = cellTypes[column.type ?? \"text\"];\n      if (!cellType) continue;\n\n      const text = sourceRow[importColumnIndex] ?? \"\";\n      // as never: validate is typed against this column's own TData/TValue, which TS can't unify with the generic TData/unknown here — safe since column and row/value are all this same import's TData.\n      const columnValidate = resolveColumnValidate(column as AnyColumnDef, cellType);\n      const parsed = processCellFromText\n        ? parseWithHook(\"processCellFromText\", () => processCellFromText(text, { row: rows[rowIndex] as TData, column, source: \"import\", signal, fromText: (raw) => cellType.fromText(raw, column.options) }), columnValidate, warnOnceFor(processCellFromText))\n        : safeFromText(cellType, text, column.options, columnValidate);\n      items.push({ validate: parsed.validate as never, value: parsed.value, row: rows[rowIndex] });\n      cells.push({ rowIndex, importColumnIndex, column, clearedValue: cellType.clearValue(column.options), warn: column.validationMode === \"warn\" });\n    }\n  }\n  return { items, cells };\n}\n\nconst hookWarnings = new WeakMap<object, ReturnType<typeof createWarnOnce>>();\n\nfunction warnOnceFor(hook: object): ReturnType<typeof createWarnOnce> {\n  let warnOnce = hookWarnings.get(hook);\n  if (!warnOnce) hookWarnings.set(hook, (warnOnce = createWarnOnce()));\n  return warnOnce;\n}\n\nconst NEVER_ABORTED = new AbortController().signal;\n\n/** Awaits every item whose value a `processCellFromText` hook returned as a promise. */\nasync function settleItemValues(items: ValidateBatchItem[]): Promise<void> {\n  const pending: Promise<void>[] = [];\n  items.forEach((item, index) => {\n    if (isThenable(item.value)) pending.push(Promise.resolve(item.value).then((value) => void (items[index] = settleHookFailure({ ...items[index]!, value }))));\n  });\n  if (pending.length > 0) await Promise.all(pending);\n}\n\n/** Yields to the event loop; a chunk boundary for both the main-thread-block fix and the Cancel affordance. */\nfunction yieldToEventLoop(): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve));\n}\n\n/**\n * Large-import path: builds and writes rows {@link CHUNK_SIZE} at a time, yielding between chunks so\n * the dialog's pending state actually repaints and `signal` gets a chance to cancel. Validation still\n * runs once per chunk (not once for the whole import) so a huge async-schema import doesn't hold\n * `CHUNK_SIZE`-multiples of items in flight at once.\n */\nasync function buildImportedRowsChunked<TData>(\n  dataRows: readonly string[][],\n  activeMappings: readonly ResolvedMapping[],\n  columnsById: ReadonlyMap<string, ColumnDef<TData, unknown, any>>, // eslint-disable-line @typescript-eslint/no-explicit-any\n  cellTypes: Record<string, CellType<TData, unknown, unknown>>,\n  createRow: (index: number, ctx: GateContext) => TData | Promise<TData>,\n  signal: AbortSignal,\n  existingRows: readonly TData[],\n  processCellFromText?: ProcessCellFromText<TData>,\n): Promise<BuildImportedRowsResult<TData>> {\n  const gateCtx: GateContext = { signal };\n  const created = dataRows.map((_, index) => createRow(index, gateCtx));\n  const rows = created.some((row) => isThenable(row)) ? await Promise.all(created) : (created as TData[]);\n  const rejected: ImportRejectedCell[] = [];\n  const flagged: ImportRejectedCell[] = [];\n\n  for (let start = 0; start < dataRows.length; start += CHUNK_SIZE) {\n    if (signal?.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n    const end = Math.min(start + CHUNK_SIZE, dataRows.length);\n    const { items, cells } = buildCellsForRange(dataRows, start, end, activeMappings, columnsById, cellTypes, rows, processCellFromText, signal);\n    await settleItemValues(items);\n    if (signal?.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n    attachValidateContexts(items, cells, existingRows);\n    const results = await runValidateBatch(items);\n    writeCells(rows, cells, items, results, rejected, flagged);\n    await yieldToEventLoop();\n  }\n  if (signal?.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n\n  return { rows, rejected, flagged };\n}\n\nfunction rejectionMessage(result: ValidateResult): string | undefined {\n  if (!(\"error\" in result) || typeof result.error !== \"string\" || result.error === \"\") return undefined;\n  return result.error.slice(0, MAX_REJECTED_MESSAGE_LENGTH);\n}\n\n/**\n * Folds each verdict into its row: the validator's output on success, the cell type's `clearValue()`\n * on rejection (the rejected cell is appended to `rejected`). `cells` is grouped by `rowIndex`\n * (built in mapping order per row), so a run of\n * consecutive plain-`accessorKey` cells for the same row is merged into one spread instead of one\n * spread per cell — this was the measured hot spot, one spread + 2 temp objects per cell at scale.\n * The run is flushed (a) before a `setValue` cell in the same row, so `setValue` still sees every\n * earlier cell's write, exactly as the un-merged left-to-right spreads did, and (b) at each row\n * boundary. A column with a custom `setValue` keeps writing through `setCellValue` per cell, since\n * only `setValue` knows how to fold its own value into the row.\n */\nfunction writeCells<TData>(\n  rows: TData[],\n  cells: readonly ImportCell[],\n  items: readonly { value: unknown }[],\n  results: readonly ValidateResult[],\n  rejected: ImportRejectedCell[],\n  flagged: ImportRejectedCell[],\n): TData[] {\n  let pendingRow = -1;\n  let pendingPatch: Record<string, unknown> | null = null;\n  const flush = () => {\n    if (pendingPatch === null) return;\n    // as TData: TData is generic here, but pendingPatch's keys are this same TData's own accessorKeys — mirrors setCellValue's own accessorKey-spread branch.\n    rows[pendingRow] = { ...rows[pendingRow], ...pendingPatch } as TData;\n    pendingPatch = null;\n  };\n\n  for (let i = 0; i < cells.length; i++) {\n    const cell = cells[i]!; // i < cells.length by loop condition\n    const result = results[i];\n    if (!result) continue;\n    const isRejected = \"error\" in result;\n    const keepsValue = isRejected && cell.warn && !result.thrown;\n    if (isRejected) (keepsValue ? flagged : rejected).push({ rowIndex: cell.rowIndex, importColumnIndex: cell.importColumnIndex, gridColumnId: cell.column.id, message: rejectionMessage(result) });\n    const value = keepsValue ? items[i]!.value : isRejected ? cell.clearedValue : result.value;\n\n    if (cell.rowIndex !== pendingRow) flush();\n    pendingRow = cell.rowIndex;\n\n    if (!cell.column.setValue && cell.column.accessorKey) {\n      pendingPatch ??= {};\n      pendingPatch[cell.column.accessorKey] = value;\n      continue;\n    }\n    flush();\n    // as never: setCellValue is typed against this column's own TData/TValue, which TS can't unify with the generic TData/unknown here — safe since column and row/value are all this same import's TData.\n    rows[cell.rowIndex] = setCellValue(rows[cell.rowIndex] as never, cell.column as never, value as never) as TData;\n  }\n  flush();\n  return rows;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/build-imported-rows.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/import-check.ts",
      "content": "import { isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport type { ImportColumnMapping, ImportRejectedCell } from \"./build-imported-rows\";\r\n\r\n/** Longest refusal message the import check keeps. */\r\nexport const MAX_CHECK_MESSAGE_LENGTH = 200;\r\n\r\n/** Refusals the import check reads; the rest count as \"and more\". */\r\nexport const MAX_CHECK_REFUSALS = 1_000;\r\n\r\n/** One row the server refuses. `rowIndex` is the 0-based index into the rows `checkImport` received. */\r\nexport type ImportCheckRefusal = { rowIndex: number; columnId?: string; message?: string };\r\n\r\n/** Counts a server reports for the rows it checked. */\r\nexport type ImportCheckSummary = { created?: number; updated?: number; skipped?: number };\r\n\r\n/** What `checkImport` returns. An answer without refusals lets the import go on. */\r\nexport type ImportCheckAnswer = { rejected?: ImportCheckRefusal[]; summary?: ImportCheckSummary };\r\n\r\n/** What `checkImport` receives besides the rows. */\r\nexport type ImportCheckContext = {\r\n  /** Aborts when the user cancels, the dialog closes, or a new file loads. Pass it to your request. */\r\n  signal: AbortSignal;\r\n  /** Which file column went to which grid column. */\r\n  mapping: readonly ImportColumnMapping[];\r\n  fileName: string;\r\n  /** The sheet the rows came from; undefined for CSV. */\r\n  sheetName?: string;\r\n  /** Cells whose value failed `column.validate`; each was cleared and its row is in the rows. */\r\n  rejected: readonly ImportRejectedCell[];\r\n};\r\n\r\n/** Checks the built rows before they are saved; see {@link ImportCheckAnswer}. */\r\nexport type CheckImport<TData> = (rows: TData[], ctx: ImportCheckContext) => ImportCheckAnswer | void | Promise<ImportCheckAnswer | void>;\r\n\r\n/** The read answer: `failed` for a shape the check does not accept, else the bounded refusals. */\r\nexport type ImportCheck = { status: \"failed\" } | { status: \"checked\"; refusals: ImportCheckRefusal[]; more: number; summary?: ImportCheckSummary };\r\n\r\nconst FAILED: ImportCheck = { status: \"failed\" };\r\n\r\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\r\n\r\nconst isCount = (value: unknown): value is number => typeof value === \"number\" && Number.isInteger(value) && value >= 0;\r\n\r\nfunction readSummary(value: unknown): ImportCheckSummary | null | undefined {\r\n  if (value === undefined) return undefined;\r\n  if (!isRecord(value)) return null;\r\n  const summary: ImportCheckSummary = {};\r\n  for (const key of [\"created\", \"updated\", \"skipped\"] as const) {\r\n    const count = value[key];\r\n    if (count === undefined) continue;\r\n    if (!isCount(count)) return null;\r\n    summary[key] = count;\r\n  }\r\n  return summary;\r\n}\r\n\r\nfunction readRefusal(entry: unknown, rowCount: number, columnIds: ReadonlySet<string>): ImportCheckRefusal | null {\r\n  if (!isRecord(entry)) return null;\r\n  const rowIndex = entry[\"rowIndex\"], columnId = entry[\"columnId\"], message = entry[\"message\"];\r\n  if (typeof rowIndex !== \"number\" || !Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex >= rowCount) return null;\r\n  if (columnId !== undefined && typeof columnId !== \"string\") return null;\r\n  if (message !== undefined && typeof message !== \"string\") return null;\r\n  const refusal: ImportCheckRefusal = { rowIndex };\r\n  if (columnId !== undefined && columnIds.has(columnId)) refusal.columnId = columnId;\r\n  if (message !== undefined) refusal.message = message.slice(0, MAX_CHECK_MESSAGE_LENGTH);\r\n  return refusal;\r\n}\r\n\r\n/**\r\n * Reads an untrusted `checkImport` answer: at most {@link MAX_CHECK_REFUSALS} refusals, each `rowIndex`\r\n * inside `rowCount`, `columnId` kept only for a live column, `message` cut. Any other shape is `failed`.\r\n */\r\nexport function readImportCheckAnswer(answer: unknown, rowCount: number, columnIds: ReadonlySet<string>): ImportCheck {\r\n  try {\r\n    if (answer === undefined || answer === null) return { status: \"checked\", refusals: [], more: 0 };\r\n    if (!isRecord(answer)) return FAILED;\r\n    const summary = readSummary(answer[\"summary\"]);\r\n    if (summary === null) return FAILED;\r\n    const rejected = answer[\"rejected\"];\r\n    if (rejected !== undefined && !Array.isArray(rejected)) return FAILED;\r\n    const refusals: ImportCheckRefusal[] = [];\r\n    const read = Math.min(rejected?.length ?? 0, MAX_CHECK_REFUSALS);\r\n    for (let i = 0; i < read; i++) {\r\n      const refusal = readRefusal(rejected![i], rowCount, columnIds);\r\n      if (!refusal) return FAILED;\r\n      refusals.push(refusal);\r\n    }\r\n    return { status: \"checked\", refusals, more: Math.max((rejected?.length ?? 0) - read, 0), ...(summary && { summary }) };\r\n  } catch {\r\n    return FAILED;\r\n  }\r\n}\r\n\r\n/** Runs `checkImport` over built rows and reads the answer. A throw or a rejection is `failed`, except an abort, which rethrows. */\r\nexport async function runImportCheck<TData>(checkImport: CheckImport<TData>, rows: TData[], ctx: ImportCheckContext, columnIds: ReadonlySet<string>): Promise<ImportCheck> {\r\n  try {\r\n    return readImportCheckAnswer(await checkImport(rows, ctx), rows.length, columnIds);\r\n  } catch (error) {\r\n    if (ctx.signal.aborted) throw error;\r\n    if (isDev()) console.warn(\"[data-grid-io] checkImport failed\", error);\r\n    return FAILED;\r\n  }\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-io/import-check.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/use-data-grid-import.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n  FILE_TOO_LARGE_MESSAGE,\n  IMPORT_TOO_MANY_CELLS_MESSAGE,\n  PART_TOO_LARGE_MESSAGE,\n  UNSUPPORTED_EXCEL_FORMAT_MESSAGE,\n  assertImportRows,\n  parseImportFile,\n  resolveImportLimits,\n  type CsvDelimiter,\n  type ImportCsvEncoding,\n  type ImportLimits,\n  type ImportValueMode,\n  type ParsedImportFile,\n} from \"./parse-import-file\";\nimport { resolveImportMapping, type ImportTargetColumn, type ImportDefaults } from \"./match-import-column\";\nimport { runImportCheck, type CheckImport, type ImportCheck } from \"./import-check\";\nimport { buildImportedRows, IMPORT_CANCELLED_MESSAGE, type BuildImportedRowsOptions, type BuildImportedRowsResult, type ImportColumnMapping } from \"./build-imported-rows\";\nimport { DEFAULT_LABELS, type AnyCellType } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev, isThenable, useOptionalDataGridColumnSource, useOptionalDataGridGateTracker, useOptionalDataGridLabels, type GateTracker } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\nexport type { ImportTargetColumn, ImportDefaults };\n\n/** Rows shown in the preview table, capped for readability. */\nexport const IMPORT_PREVIEW_ROW_COUNT = 10;\n\n/** Keys into `labels.io` for the parse-failure messages {@link useDataGridImportPreview} can surface. */\nexport type ImportErrorKey = \"errorParseFailed\" | \"errorNoRows\" | \"errorUnsupportedFile\" | \"errorUnsupportedExcelFormat\" | \"errorFileTooLarge\" | \"errorPartTooLarge\" | \"errorTooManyCells\";\n\n/** Error thrown by {@link parseImportFile} for extensions outside csv/xlsx/xls. */\nconst UNSUPPORTED_FILE_TYPE_MESSAGE = \"unsupported-file-type\";\n\n/** True when a parse was aborted (new file chosen, dialog closed) — the caller drops the result instead of surfacing an error. */\nfunction isAbortError(err: unknown): boolean {\n  return err instanceof Error && err.name === \"AbortError\";\n}\n\n/** Maps a parse failure to its dialog error key; null for aborts the caller drops silently. */\nexport function importErrorKey(err: unknown): ImportErrorKey | null {\n  if (isAbortError(err)) return null;\n  if (err instanceof Error) {\n    switch (err.message) {\n      case UNSUPPORTED_FILE_TYPE_MESSAGE:\n        return \"errorUnsupportedFile\";\n      case UNSUPPORTED_EXCEL_FORMAT_MESSAGE:\n        return \"errorUnsupportedExcelFormat\";\n      case FILE_TOO_LARGE_MESSAGE:\n        return \"errorFileTooLarge\";\n      case PART_TOO_LARGE_MESSAGE:\n        return \"errorPartTooLarge\";\n      case IMPORT_TOO_MANY_CELLS_MESSAGE:\n        return \"errorTooManyCells\";\n    }\n  }\n  return \"errorParseFailed\";\n}\n\n/** Parsed-and-ready import state, once a file has been chosen and parsed successfully. */\nexport type ImportFileState = {\n  fileName: string;\n  /** All parsed rows, including the header row (if `hasHeaderRow`) at index 0. */\n  rows: string[][];\n  hasHeaderRow: boolean;\n  /** Display header per column: the file's header row text, or `labels.io.columnFallback(N)` when there's no header row. */\n  importHeaders: string[];\n  mapping: ImportColumnMapping[];\n  delimiter?: CsvDelimiter;\n  /** Every sheet name in the workbook. Undefined for CSV. Lets a consumer offer a sheet picker when a workbook has more than one sheet. */\n  sheetNames?: string[];\n  /** The sheet `rows` came from (first by default, or the one selected via {@link UseDataGridImportPreviewResult.setSheetName}). Undefined for CSV. */\n  sheetName?: string;\n};\n\n/** Return value of {@link useDataGridImportPreview}. */\nexport type UseDataGridImportPreviewResult = {\n  preview: ImportFileState | null;\n  error: ImportErrorKey | null;\n  /** True while a file is being read/parsed. */\n  isParsing: boolean;\n  /** Parses `file`; on success populates `preview` with column mapping prefilled by header-text match. */\n  loadFile: (file: File, gridColumns: readonly ImportTargetColumn[]) => Promise<void>;\n  setHasHeaderRow: (hasHeaderRow: boolean) => void;\n  /** Re-parses the current CSV file with the given delimiter override; no-op for xlsx/xls files or before a file is loaded. A failed re-parse sets `error` instead of throwing. */\n  setDelimiter: (delimiter: CsvDelimiter) => Promise<void>;\n  /**\n   * Re-parses the current xlsx/xls workbook with the given sheet; no-op for CSV or before a file\n   * is loaded. Switching sheets recomputes the column mapping from scratch (different headers), so\n   * any manual mapping the user set on the previous sheet is discarded.\n   */\n  setSheetName: (sheetName: string) => Promise<void>;\n  setMapping: (importColumnIndex: number, gridColumnId: string | null) => void;\n  reset: () => void;\n  /** Data rows only (header row excluded when `hasHeaderRow`), capped to `IMPORT_PREVIEW_ROW_COUNT` for the preview table. */\n  previewRows: string[][];\n  /** All data rows (header row excluded when `hasHeaderRow`) — the full set `onImport` will build from. */\n  importRows: string[][];\n  /**\n   * Builds the `TData` rows from the current preview: `processImportRows` (when given), then\n   * `buildImportedRows` with the current mapping. Returns `null` when `processImportRows` returned\n   * `false` or there is no preview yet. A hook result outside the import limits rejects with the\n   * too-many-cells error. Always returns a Promise.\n   */\n  build: <TData>(options: BuildImportOptions<TData>) => Promise<ImportBuildResult<TData> | null>;\n};\n\n/** Result of {@link UseDataGridImportPreviewResult.build}: with `checkImport`, `check` holds the read answer. */\nexport type ImportBuildResult<TData> = BuildImportedRowsResult<TData> & { check?: ImportCheck };\n\n/** Builds display headers: the file's header row when present, else `labels.io.columnFallback(N)`. */\nfunction computeImportHeaders(rows: string[][], hasHeaderRow: boolean, columnFallback: (index: number) => string): string[] {\n  const columnCount = rows[0]?.length ?? 0;\n  if (hasHeaderRow && rows[0]) return rows[0];\n  return Array.from({ length: columnCount }, (_, i) => columnFallback(i + 1));\n}\n\n/** Options for {@link useDataGridImportPreview}. */\nexport type UseDataGridImportPreviewOptions = {\n  /** Builds the header shown for column N when the file has no header row. Default: `labels.io.columnFallback` of the enclosing grid, else the built-in label. */\n  columnFallback?: (index: number) => string;\n  /** Preselection defaults (see {@link ImportDefaults}). */\n  defaults?: ImportDefaults;\n  /** Size, row, column, cell, and unpacked-size bounds for every parse; omitted fields use `DEFAULT_IMPORT_LIMITS`. */\n  limits?: ImportLimits;\n  /** Reads the file instead of the built-in parser, for every parse (file load, delimiter, sheet). A file over `maxFileBytes` is rejected before the hook runs. Its rows must be arrays of strings inside `limits`, which are checked after the hook. `csvEncoding` does not apply. */\n  parseFile?: ParseFile;\n  /** Decodes a CSV file with this `TextDecoder` label instead of UTF-8; see `IMPORT_CSV_ENCODINGS` for the accepted labels. */\n  csvEncoding?: ImportCsvEncoding;\n};\n\nconst MAX_SHEET_NAMES = 256;\nconst MAX_SHEET_NAME_CHARS = 255;\n\n/** Up to {@link MAX_SHEET_NAMES} distinct strings from the first entries of `names`; a huge list is not scanned to the end. */\nfunction uniqueSheetNames(names: readonly unknown[]): string[] {\n  const unique = new Set<string>();\n  const scanLimit = Math.min(names.length, MAX_SHEET_NAMES * 4);\n  for (let index = 0; index < scanLimit && unique.size < MAX_SHEET_NAMES; index++) {\n    const name = names[index];\n    if (typeof name === \"string\") unique.add(name.slice(0, MAX_SHEET_NAME_CHARS));\n  }\n  return [...unique];\n}\n\nconst CSV_DELIMITERS: readonly CsvDelimiter[] = [\",\", \";\", \"\\t\", \"|\"];\n\n/** Keeps only the fields of a custom parse result that the dialog reads, and bounds the lists and strings in them. */\nfunction sanitizeParsedFile(parsed: ParsedImportFile): ParsedImportFile {\n  const delimiter = CSV_DELIMITERS.includes(parsed.delimiter as CsvDelimiter) ? parsed.delimiter : undefined;\n  const sheetNames = Array.isArray(parsed.sheetNames) ? uniqueSheetNames(parsed.sheetNames) : undefined;\n  const sheetName = typeof parsed.sheetName === \"string\" ? parsed.sheetName.slice(0, MAX_SHEET_NAME_CHARS) : undefined;\n  return { rows: parsed.rows, delimiter, sheetNames, sheetName };\n}\n\n/** Replaces the built-in file parser; see {@link UseDataGridImportPreviewOptions.parseFile}. */\nexport type ParseFile = (\n  file: File,\n  ctx: { signal: AbortSignal; limits: Required<ImportLimits>; sheetName?: string; csvDelimiter?: CsvDelimiter; valueMode: ImportValueMode },\n) => ParsedImportFile | Promise<ParsedImportFile>;\n\n/** Rewrites or drops the data rows before they are mapped and built; see {@link UseDataGridImportPreviewResult.build}. */\nexport type ProcessImportRows = (ctx: {\n  /** The data rows, header row excluded. */\n  rows: string[][];\n  /** The header text of each source column. */\n  headers: string[];\n  mapping: ImportColumnMapping[];\n  signal: AbortSignal;\n}) => string[][] | false | Promise<string[][] | false>;\n\n/** Inputs of {@link UseDataGridImportPreviewResult.build} besides the file state the hook already holds. */\nexport type BuildImportOptions<TData> = Omit<BuildImportedRowsOptions<TData>, \"dataRows\" | \"mapping\" | \"columns\" | \"cellTypes\"> & {\n  /** The columns the rows are built for. Default: the columns of the enclosing grid. */\n  columns?: BuildImportedRowsOptions<TData>[\"columns\"];\n  /** The cell types that parse each cell. Default: the resolved cell types of the enclosing grid, which `useDataGridCellTypes()` returns. */\n  cellTypes?: Record<string, AnyCellType>;\n  /** Runs on the data rows before the mapping is applied. `false` cancels the import: `build()` resolves `null`. The result is checked against the import limits. */\n  processImportRows?: ProcessImportRows;\n  /** Checks the built rows on your server before they are saved; the answer lands in `result.check`. A throw or a rejection gives `{ status: \"failed\" }`. Absent: no check. */\n  checkImport?: CheckImport<TData>;\n};\n\ntype MappingGate = { signal: AbortSignal; arm: () => void; stop: () => void };\n\n/** The `mapColumn` signal: aborts with `signal`, or through the grid's gate run (`gateTimeoutMs.mapColumn`) once {@link MappingGate.arm} holds it. */\nfunction mappingGate(signal: AbortSignal, gates: GateTracker | null): MappingGate {\n  const run = gates?.begin(\"mapColumn\");\n  return {\n    signal: run ? AbortSignal.any([signal, run.signal]) : signal,\n    arm: () => run && gates!.hold(run),\n    stop: () => run && gates!.settle(run),\n  };\n}\n\n/** Awaits a promised mapping until it settles or `gate` aborts; a rejected or timed-out `mapColumn` falls back to the built-in match so the dialog still opens. */\nasync function settleMapping(\n  mapped: Promise<(string | null)[]>,\n  fallback: () => (string | null)[],\n  gate: MappingGate,\n): Promise<(string | null)[]> {\n  gate.arm();\n  const aborted = new Promise<never>((_, reject) => gate.signal.addEventListener(\"abort\", () => reject(gate.signal.reason), { once: true }));\n  try {\n    return await Promise.race([mapped, aborted]);\n  } catch (error) {\n    if (isDev() && !gate.signal.aborted) console.warn(\"[data-grid-io] mapColumn rejected, so the built-in column match is used\", error);\n    return fallback();\n  } finally {\n    gate.stop();\n  }\n}\n\n/**\n * Owns the parse -> preview -> column-mapping state for the import dialog. File I/O and header\n * matching are pure functions ({@link parseImportFile}, {@link applyImportOptions}); this hook only\n * sequences them and exposes editable dialog state (header-row toggle, delimiter, per-column mapping).\n *\n */\nexport function useDataGridImportPreview(options: UseDataGridImportPreviewOptions = {}): UseDataGridImportPreviewResult {\n  const gridLabels = useOptionalDataGridLabels();\n  const grid = useOptionalDataGridColumnSource();\n  const gates = useOptionalDataGridGateTracker();\n  const mapGate = useCallback((signal: AbortSignal) => mappingGate(signal, gates), [gates]);\n  const gridColumns = grid?.columns;\n  const gridCellTypes = grid?.cellTypes;\n  const labelsIo = (gridLabels ?? DEFAULT_LABELS).io;\n  const columnFallback = options.columnFallback ?? labelsIo.columnFallback;\n  const { defaults = {}, limits = {}, parseFile, csvEncoding } = options;\n  const [preview, setPreview] = useState<ImportFileState | null>(null);\n  const [error, setError] = useState<ImportErrorKey | null>(null);\n  const [isParsing, setIsParsing] = useState(false);\n  // kept for delimiter-override re-parses, which need the original file + target columns again.\n  const currentFileRef = useRef<File | null>(null);\n  const gridColumnsRef = useRef<readonly ImportTargetColumn[]>([]);\n  // aborts an in-flight file read when a newer load starts or the dialog resets.\n  const parseControllerRef = useRef<AbortController | null>(null);\n  // generation guard for every async parse (file load, sheet switch, delimiter override): a newer parse or reset wins over a slower older one.\n  const parseGenerationRef = useRef(0);\n  const { defaultHeaderRow = true, defaultSkipColumns, mapColumn } = defaults;\n  const valueMode: ImportValueMode = defaults.valueMode === \"raw\" ? \"raw\" : \"formatted\";\n  const headerRowIndex = typeof defaultHeaderRow === \"number\" ? Math.max(0, Math.floor(defaultHeaderRow) || 0) : 0;\n  const initialHasHeaderRow = defaultHeaderRow !== false;\n  // the header-row toggle as the async mapping steps read it; they cannot read a state updater's `prev`.\n  const hasHeaderRowRef = useRef(initialHasHeaderRow);\n  const parseFileRef = useRef(parseFile);\n  useEffect(() => {\n    parseFileRef.current = parseFile;\n  });\n  const { maxFileBytes, maxRows, maxColumns, maxCells, maxDecompressedBytes } = limits;\n  const limitOptions = useMemo(\n    () => ({ maxFileBytes, maxRows, maxColumns, maxCells, maxDecompressedBytes }),\n    [maxFileBytes, maxRows, maxColumns, maxCells, maxDecompressedBytes],\n  );\n\n  useEffect(\n    () => () => {\n      parseGenerationRef.current += 1;\n      parseControllerRef.current?.abort();\n    },\n    [],\n  );\n\n  const startParse = useCallback((): { generation: number; controller: AbortController } => {\n    const generation = ++parseGenerationRef.current;\n    parseControllerRef.current?.abort();\n    const controller = new AbortController();\n    parseControllerRef.current = controller;\n    return { generation, controller };\n  }, []);\n\n  const effectiveLimits = useMemo<Required<ImportLimits>>(\n    () => resolveImportLimits({ maxFileBytes, maxRows, maxColumns, maxCells, maxDecompressedBytes }),\n    [maxFileBytes, maxRows, maxColumns, maxCells, maxDecompressedBytes],\n  );\n\n  /** One parse: the consumer's `parseFile` (its result checked against the limits) or the built-in parser; rows above the header-row index are dropped. */\n  const parse = useCallback(\n    async (file: File, extra: { sheetName?: string; csvDelimiter?: CsvDelimiter }, signal?: AbortSignal): Promise<ParsedImportFile> => {\n      const custom = parseFileRef.current;\n      let parsed: ParsedImportFile;\n      if (custom) {\n        if (file.size > effectiveLimits.maxFileBytes) throw new Error(FILE_TOO_LARGE_MESSAGE);\n        const checked = await custom(file, { signal: signal ?? new AbortController().signal, limits: effectiveLimits, valueMode, ...extra });\n        if (typeof checked !== \"object\" || checked === null) throw new Error(\"invalid-import-rows\");\n        assertImportRows(checked.rows, effectiveLimits);\n        parsed = sanitizeParsedFile(checked);\n      } else {\n        parsed = await parseImportFile(file, { ...limitOptions, csvEncoding, valueMode, ...extra, signal });\n      }\n      return headerRowIndex > 0 ? { ...parsed, rows: parsed.rows.slice(headerRowIndex) } : parsed;\n    },\n    [effectiveLimits, limitOptions, csvEncoding, headerRowIndex, valueMode],\n  );\n\n  const reset = useCallback(() => {\n    parseGenerationRef.current += 1;\n    parseControllerRef.current?.abort();\n    setPreview(null);\n    setError(null);\n    setIsParsing(false);\n    currentFileRef.current = null;\n    gridColumnsRef.current = [];\n  }, []);\n\n  const loadFile = useCallback(async (file: File, gridColumns: readonly ImportTargetColumn[]) => {\n    // a re-parse started while this file loads has no file to re-parse, so it cannot outlive this load\n    currentFileRef.current = null;\n    const { generation, controller } = startParse();\n    setError(null);\n    setIsParsing(true);\n    try {\n      const parsed = await parse(file, { csvDelimiter: defaults.defaultDelimiter }, controller.signal);\n      if (generation !== parseGenerationRef.current) return; // superseded by a newer file load or a reset\n      if (parsed.rows.length === 0) {\n        setError(\"errorNoRows\");\n        setPreview(null);\n        return;\n      }\n      currentFileRef.current = file;\n      gridColumnsRef.current = gridColumns;\n      const hasHeaderRow = initialHasHeaderRow;\n      hasHeaderRowRef.current = hasHeaderRow;\n      const importHeaders = computeImportHeaders(parsed.rows, hasHeaderRow, columnFallback);\n      const gate = mapGate(controller.signal);\n      const mapped = resolveImportMapping(importHeaders, gridColumns, { defaultSkipColumns, mapColumn, signal: gate.signal });\n      const matched = isThenable(mapped)\n        ? await settleMapping(mapped, () => resolveImportMapping(importHeaders, gridColumns, { defaultSkipColumns }) as (string | null)[], gate)\n        : (gate.stop(), mapped);\n      if (generation !== parseGenerationRef.current) return; // superseded while mapColumn was pending\n      setPreview({\n        fileName: file.name,\n        rows: parsed.rows,\n        hasHeaderRow,\n        importHeaders,\n        mapping: matched.map((gridColumnId, importColumnIndex) => ({ importColumnIndex, gridColumnId })),\n        delimiter: parsed.delimiter,\n        sheetNames: parsed.sheetNames,\n        sheetName: parsed.sheetName,\n      });\n    } catch (err) {\n      const key = importErrorKey(err);\n      if (key === null || generation !== parseGenerationRef.current) return; // superseded by a newer file or a dialog reset\n      setError(key);\n      setPreview(null);\n    } finally {\n      // a superseded (aborted) load must not clear the newer load's parsing state\n      if (parseControllerRef.current === controller) setIsParsing(false);\n    }\n    // oxlint-disable-next-line react-hooks/exhaustive-deps -- destructured option fields are the real deps; `defaults` itself may be a fresh object each render.\n  }, [columnFallback, initialHasHeaderRow, defaultSkipColumns, mapColumn, mapGate, parse, startParse]);\n\n  const mapForReparse = useCallback(\n    (importHeaders: readonly string[], signal: AbortSignal): (string | null)[] | Promise<(string | null)[]> => {\n      const gridColumns = gridColumnsRef.current;\n      const gate = mapGate(signal);\n      const mapped = resolveImportMapping(importHeaders, gridColumns, { defaultSkipColumns, mapColumn, signal: gate.signal });\n      return isThenable(mapped)\n        ? settleMapping(mapped, () => resolveImportMapping(importHeaders, gridColumns, { defaultSkipColumns }) as (string | null)[], gate)\n        : (gate.stop(), mapped);\n    },\n    [defaultSkipColumns, mapColumn, mapGate],\n  );\n\n  const setHasHeaderRow = useCallback(\n    (hasHeaderRow: boolean) => {\n      hasHeaderRowRef.current = hasHeaderRow;\n      setPreview((prev) => {\n        if (!prev) return prev;\n        const importHeaders = computeImportHeaders(prev.rows, hasHeaderRow, columnFallback);\n        return { ...prev, hasHeaderRow, importHeaders };\n      });\n    },\n    [columnFallback],\n  );\n\n  const setDelimiter = useCallback(\n    async (delimiter: CsvDelimiter) => {\n      const file = currentFileRef.current;\n      if (!file) return;\n      const { generation, controller } = startParse();\n      setError(null);\n      setIsParsing(true);\n      try {\n        const parsed = await parse(file, { csvDelimiter: delimiter }, controller.signal);\n        if (generation !== parseGenerationRef.current) return; // superseded by a newer file load, sheet switch, or reset\n        if (parsed.rows.length === 0) return;\n        const importHeaders = computeImportHeaders(parsed.rows, hasHeaderRowRef.current, columnFallback);\n        const mappedHeaders = mapForReparse(importHeaders, controller.signal);\n        const matched = isThenable(mappedHeaders) ? await mappedHeaders : mappedHeaders;\n        if (generation !== parseGenerationRef.current) return; // superseded while mapColumn was pending\n        setPreview((prev) => {\n          if (!prev) return prev;\n          return {\n            ...prev,\n            rows: parsed.rows,\n            importHeaders,\n            delimiter,\n            mapping: matched.map((gridColumnId, importColumnIndex) => ({ importColumnIndex, gridColumnId })),\n          };\n        });\n      } catch (err) {\n        const key = importErrorKey(err);\n        if (key === null) return;\n        if (generation === parseGenerationRef.current) setError(key);\n      } finally {\n        if (generation === parseGenerationRef.current) setIsParsing(false);\n      }\n    },\n    [columnFallback, mapForReparse, parse, startParse],\n  );\n\n  const setSheetName = useCallback(\n    async (sheetName: string) => {\n      const file = currentFileRef.current;\n      if (!file) return;\n      const { generation, controller } = startParse();\n      setError(null);\n      setIsParsing(true);\n      try {\n        const parsed = await parse(file, { sheetName }, controller.signal);\n        if (generation !== parseGenerationRef.current) return; // superseded by a newer sheet switch, file load, or reset\n        if (parsed.rows.length === 0) {\n          // empty sheet: the picker keeps the chosen name honest, the preview clears, Import stays disabled\n          setPreview((prev) =>\n            prev ? { ...prev, rows: [], importHeaders: [], mapping: [], sheetName: parsed.sheetName ?? sheetName } : prev,\n          );\n          setError(\"errorNoRows\");\n          return;\n        }\n        const importHeaders = computeImportHeaders(parsed.rows, hasHeaderRowRef.current, columnFallback);\n        const mappedHeaders = mapForReparse(importHeaders, controller.signal);\n        const matched = isThenable(mappedHeaders) ? await mappedHeaders : mappedHeaders;\n        if (generation !== parseGenerationRef.current) return; // superseded while mapColumn was pending\n        setPreview((prev) => {\n          if (!prev) return prev;\n          return {\n            ...prev,\n            rows: parsed.rows,\n            importHeaders,\n            sheetName: parsed.sheetName,\n            mapping: matched.map((gridColumnId, importColumnIndex) => ({ importColumnIndex, gridColumnId })),\n          };\n        });\n      } catch (err) {\n        const key = importErrorKey(err);\n        if (key === null) return;\n        if (generation === parseGenerationRef.current) setError(key);\n      } finally {\n        if (generation === parseGenerationRef.current) setIsParsing(false);\n      }\n    },\n    [columnFallback, mapForReparse, parse, startParse],\n  );\n\n  const setMapping = useCallback((importColumnIndex: number, gridColumnId: string | null) => {\n    setPreview((prev) => {\n      if (!prev) return prev;\n      const mapping = prev.mapping.map((m) =>\n        m.importColumnIndex === importColumnIndex ? { ...m, gridColumnId } : gridColumnId !== null && m.gridColumnId === gridColumnId ? { ...m, gridColumnId: null } : m,\n      );\n      return { ...prev, mapping };\n    });\n  }, []);\n\n  const importRows = useMemo(() => {\n    if (!preview) return [];\n    return preview.hasHeaderRow ? preview.rows.slice(1) : preview.rows;\n  }, [preview]);\n\n  const previewRows = useMemo(() => importRows.slice(0, IMPORT_PREVIEW_ROW_COUNT), [importRows]);\n\n  const warnedNoPreviewRef = useRef(false);\n  const build = useCallback(\n    async <TData,>(buildOptions: BuildImportOptions<TData>): Promise<ImportBuildResult<TData> | null> => {\n      if (!preview) {\n        if (isDev() && !warnedNoPreviewRef.current) {\n          warnedNoPreviewRef.current = true;\n          console.warn(\"[data-grid-io] build() ran before a file was loaded and returns null; call loadFile() first\");\n        }\n        return null;\n      }\n      const { processImportRows, checkImport, columns, cellTypes, ...rest } = buildOptions;\n      if (!(columns && cellTypes) && !gridColumns && isDev()) console.warn(\"[data-grid-io] build() found no grid; pass `columns` and `cellTypes` or call it under a DataGridProvider\");\n      const signal = rest.signal ?? new AbortController().signal;\n      const buildColumns = columns ?? ((gridColumns ?? []) as BuildImportedRowsOptions<TData>[\"columns\"]);\n      const finish = async (dataRows: string[][]): Promise<ImportBuildResult<TData>> => {\n        const built = await buildImportedRows<TData>({\n          ...rest,\n          columns: buildColumns,\n          cellTypes: (cellTypes ?? gridCellTypes ?? {}) as BuildImportedRowsOptions<TData>[\"cellTypes\"],\n          signal: rest.signal,\n          dataRows,\n          mapping: preview.mapping,\n        });\n        if (!checkImport) return built;\n        const ctx = { signal, mapping: preview.mapping, fileName: preview.fileName, sheetName: preview.sheetName, rejected: built.rejected };\n        const check = await runImportCheck(checkImport, built.rows, ctx, new Set(buildColumns.map((column) => column.id)));\n        if (signal.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n        return { ...built, check };\n      };\n      if (!processImportRows) return finish(importRows);\n      const hooked = processImportRows({ rows: importRows, headers: preview.importHeaders, mapping: preview.mapping, signal });\n      const accept = (result: string[][] | false): ImportBuildResult<TData> | null | Promise<ImportBuildResult<TData>> => {\n        if (signal.aborted) throw new Error(IMPORT_CANCELLED_MESSAGE);\n        if (result === false) return null;\n        assertImportRows(result, effectiveLimits, preview.hasHeaderRow ? 1 : 0);\n        return finish(result);\n      };\n      return isThenable(hooked) ? Promise.resolve(hooked).then(accept) : accept(hooked);\n    },\n    [preview, importRows, effectiveLimits, gridColumns, gridCellTypes],\n  );\n\n  return { preview, error, isParsing, loadFile, setHasHeaderRow, setDelimiter, setSheetName, setMapping, reset, previewRows, importRows, build };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/use-data-grid-import.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-io/import-dialog.tsx",
      "content": "\"use client\";\n\nimport { Fragment, useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { Paperclip, X } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport { useDataGridActions, useDataGridAllColumns, useDataGridLabels, type GateContext } from \"@/registry/default/components/data-grid/data-grid\";\nimport { columnLabelText, isDev, useDataGridFlaggedCommit, useDataGridMarkGatePending, useDataGridSelector, useDataGridStoreApi } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from \"@/components/ui/dialog\";\nimport { Button } from \"@/components/ui/button\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Label } from \"@/components/ui/label\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { IMPORT_CANCELLED_MESSAGE, type BuildImportedRowsOptions, type ImportColumnMapping, type ImportRejectedCell, type ProcessCellFromText } from \"./build-imported-rows\";\nimport { importErrorKey, useDataGridImportPreview, type ImportTargetColumn, type ImportDefaults, type ParseFile, type ProcessImportRows, type ImportErrorKey } from \"./use-data-grid-import\";\nimport type { CheckImport, ImportCheckRefusal, ImportCheckSummary } from \"./import-check\";\nimport { resolveImportLimits, type CsvDelimiter, type ImportCsvEncoding, type ImportLimits } from \"./parse-import-file\";\nimport { acceptedTypeNames, Dropzone, DropzoneEmptyState, type DropzoneAccept, type DropzoneRejection } from \"@/registry/default/components/dropzone/dropzone\";\n\n/** Accepted import file types, shared by the file input and the {@link Dropzone}. */\nconst IMPORT_ACCEPT: DropzoneAccept = {\n  \"text/csv\": [\".csv\"],\n  \"text/tab-separated-values\": [\".tsv\"],\n  \"application/vnd.ms-excel\": [\".xls\"],\n  \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": [\".xlsx\"],\n};\n\nexport type { ImportDefaults };\n\nconst DELIMITER_OPTIONS: { value: CsvDelimiter; labelKey: \"delimiterComma\" | \"delimiterSemicolon\" | \"delimiterTab\" | \"delimiterPipe\" }[] = [\n  { value: \",\", labelKey: \"delimiterComma\" },\n  { value: \";\", labelKey: \"delimiterSemicolon\" },\n  { value: \"\\t\", labelKey: \"delimiterTab\" },\n  { value: \"|\", labelKey: \"delimiterPipe\" },\n];\n\n/** Mapping-select value for a source column that maps to no grid column. */\nconst SKIP_VALUE = \"__skip__\";\n\n/** What `onImport` receives beside the rows. */\nexport type ImportContext = {\n  /** Aborts when the user cancels or the dialog closes. Pass it to your request. */\n  signal: AbortSignal;\n  /** Cells whose value failed `column.validate`; each was cleared and its row is in `rows`. */\n  rejected: readonly ImportRejectedCell[];\n  /** Cells of `validationMode: \"warn\"` columns whose value failed `validate`; each keeps its value in `rows`. The default append flags them in `cellErrors`. */\n  flagged: readonly ImportRejectedCell[];\n  fileName: string;\n  /** The sheet the rows came from; undefined for CSV. */\n  sheetName?: string;\n  /** Which file column went to which grid column. */\n  mapping: readonly ImportColumnMapping[];\n};\n\n/** The file facts `onImport` gets, taken when the user confirms. */\ntype ImportSource = Pick<ImportContext, \"fileName\" | \"sheetName\" | \"mapping\">;\n\n/** Maximum characters of an `onImport` error message the dialog shows. */\nconst MAX_ERROR_MESSAGE_LENGTH = 200;\n\nconst hasUnloadedRows = (data: readonly unknown[]): boolean => {\n  for (let i = 0; i < data.length; i++) if (data[i] === undefined) return true;\n  return false;\n};\n\ntype AppendBlock = \"importNeedsOnImport\" | \"importReadOnly\";\n\nconst appendBlockOf = (state: { readOnly: boolean; totalRowCount?: number | null }): AppendBlock | null =>\n  state.readOnly ? \"importReadOnly\" : state.totalRowCount !== undefined ? \"importNeedsOnImport\" : null;\n\n/** The label key that explains why import is unavailable: a read-only grid takes no import, and the default append needs a client grid, so a grid without `onImport` that holds a server result gets one. */\nexport function useImportBlock(onImport: unknown, open = true): AppendBlock | null {\n  const block = useDataGridSelector<unknown, AppendBlock | null>(appendBlockOf);\n  const data = useDataGridSelector<unknown, readonly unknown[]>((s) => s.data as readonly unknown[]);\n  const sparse = useMemo(() => open && !onImport && hasUnloadedRows(data), [open, onImport, data]);\n  return onImport && block !== \"importReadOnly\" ? null : (block ?? (sparse ? \"importNeedsOnImport\" : null));\n}\n\n/** Props for {@link DataGridImportDialog}. */\nexport type DataGridImportDialogProps<TData> = {\n  /** Merges into the dialog content, which is `max-h-[80vh]` and `sm:max-w-2xl` by default. */\n  className?: string;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /** Builds a fresh row for import row `index`; required. */\n  createRow: (index: number, ctx: GateContext) => TData | Promise<TData>;\n  /** Called with the fully-built rows on confirm; the consumer decides how to merge (replace, upsert, or a server call). Default: appends the rows to `data` as one undoable `\"import\"` change. A grid with `totalRowCount` holds a window of its result, so it has no default and needs this prop. Cells rejected by `validate` are already cleared in these rows. May be async (e.g. a server upsert) — the dialog stays pending until it settles and surfaces a rejection instead of closing. `ctx.signal` aborts when the user cancels or the dialog closes; pass it to your request. */\n  onImport?: (rows: TData[], ctx: ImportContext) => void | Promise<void>;\n  /** Called once when `onImport` rejects, with the rejection. The dialog stays open. */\n  onImportError?: (error: unknown) => void;\n  /** Consumer-configurable preselection defaults (delimiter, header row, skip columns, mapping). Omit to keep the built-in detection. */\n  importDefaults?: ImportDefaults;\n  /** Size, row, column, cell, and unpacked-size bounds for the file; omitted fields use `DEFAULT_IMPORT_LIMITS`. `maxFileBytes` also sets the drop zone's `maxSize`. */\n  importLimits?: ImportLimits;\n  /** Reads the file instead of the built-in parser. Its rows are checked against `importLimits` afterwards. */\n  parseFile?: ParseFile;\n  /** File types the drop zone accepts; default csv, tsv, xls, and xlsx. Pair it with `parseFile` for other types. */\n  accept?: DropzoneAccept;\n  /** Decodes a CSV file with this `TextDecoder` label instead of UTF-8. A label outside `IMPORT_CSV_ENCODINGS` shows `labels.io.errorParseFailed`. */\n  csvEncoding?: ImportCsvEncoding;\n  /** Rewrites or drops the data rows before they are mapped. `false` cancels the import quietly. The result is checked against `importLimits`. */\n  processImportRows?: ProcessImportRows;\n  /** Parses one cell instead of the column's `fromText`. Default: the grid's `processCellFromClipboard`, then `fromText`. The value still passes `column.validate`. */\n  processCellFromText?: ProcessCellFromText<TData>;\n  /** A file to load when the dialog opens, as if the user had chosen it. */\n  file?: File;\n  /** Checks the built rows on your server before `onImport` runs. An answer without `rejected` entries goes on to `onImport`; an answer with entries opens a check step that lists them, with the buttons \"Import anyway\" and \"Back\". A throw, a rejection, or an answer in another shape shows `labels.io.checkFailed`. The answer is read with bounds: 1,000 entries, a row index inside the rows, messages cut at 200 characters. `ctx.signal` aborts when the user cancels, the dialog closes, or a new file loads. Absent: no check. */\n  checkImport?: CheckImport<TData>;\n};\n\n/** The rows held back while the user reads the check step. */\ntype CheckStep<TData> = {\n  rows: TData[];\n  rejected: readonly ImportRejectedCell[];\n  flagged: readonly ImportRejectedCell[];\n  source: ImportSource;\n  refusals: ImportCheckRefusal[];\n  more: number;\n  summary?: ImportCheckSummary;\n};\n\n/** Refusals the check step lists. */\nconst CHECK_STEP_ROWS = 100;\n\n/**\n * File-picker -> preview -> column-mapping -> confirm dialog. Parses via\n * {@link useDataGridImportPreview}, builds `TData` rows via {@link buildImportedRows} through each mapped\n * column's cell-type `fromText` + `validate`, then hands the rows to `onImport`. Without `onImport` it\n * appends them through `commitChange`; a replace or a server call passes `onImport`. A cell that\n * fails `validate` is cleared (via its cell type's `clearValue()`), not dropped as a row; the\n * rejected cells are listed in {@link buildImportedRows}'s `rejected` result.\n */\nexport function DataGridImportDialog<TData>(props: DataGridImportDialogProps<TData>): ReactNode {\n  const { open, onOpenChange, createRow, onImport, onImportError, importDefaults, importLimits, parseFile, accept = IMPORT_ACCEPT, csvEncoding, processImportRows, processCellFromText, file, className, checkImport } = props;\n  const maxFileBytes = resolveImportLimits(importLimits).maxFileBytes;\n  const labels = useDataGridLabels();\n  const actions = useDataGridActions();\n  const storeApi = useDataGridStoreApi();\n  const commitWithFlags = useDataGridFlaggedCommit();\n  const allColumns = useDataGridAllColumns<TData>();\n  const [isValidating, setIsValidating] = useState(false);\n  /** Generation guard for a held async import: a newer confirm, or closing the dialog, drops the older batch. */\n  const confirmTokenRef = useRef(0);\n  /** Aborts the in-flight chunked build (large sync imports and async-schema imports alike) when Cancel is clicked or the dialog closes. */\n  const abortControllerRef = useRef<AbortController | null>(null);\n  const headerRowId = useId();\n  const confirmButtonRef = useRef<HTMLButtonElement | null>(null);\n  const returnFocusRef = useRef(false);\n  const [checkStep, setCheckStep] = useState<CheckStep<TData> | null>(null);\n  const { preview, error, isParsing, loadFile, setHasHeaderRow, setDelimiter, setSheetName, setMapping, reset, previewRows, importRows, build } =\n    useDataGridImportPreview({ columnFallback: labels.io.columnFallback, defaults: importDefaults, limits: importLimits, parseFile, csvEncoding });\n  useDataGridMarkGatePending(\"import\", isParsing || isValidating);\n  // Base UI's SelectValue shows the raw value until the popup mounts its items, unless the root gets `items`\n  const delimiterItems = DELIMITER_OPTIONS.map((option) => ({ value: option.value, label: labels.io[option.labelKey] }));\n  const mappingItems = [{ value: SKIP_VALUE, label: labels.io.skipColumn }, ...allColumns.map((column) => ({ value: column.id, label: columnLabelText(column) }))];\n\n  useEffect(() => {\n    if (open) return;\n    confirmTokenRef.current += 1;\n    abortControllerRef.current?.abort();\n    setIsValidating(false);\n    setUnsupportedDrop(false);\n    setRejectedCount(0);\n    setMergeFailed(false);\n    setMergeMessage(null);\n    setBuildError(null);\n    setCheckStep(null);\n    reset();\n  }, [open, reset]);\n\n  useEffect(() => {\n    if (checkStep || !returnFocusRef.current) return;\n    returnFocusRef.current = false;\n    confirmButtonRef.current?.focus();\n  }, [checkStep]);\n\n  useEffect(\n    () => () => {\n      confirmTokenRef.current += 1;\n      abortControllerRef.current?.abort();\n    },\n    [],\n  );\n\n  const [unsupportedDrop, setUnsupportedDrop] = useState(false);\n  const onFile = useCallback(\n    (file: File) => {\n      confirmTokenRef.current += 1;\n      abortControllerRef.current?.abort();\n      setIsValidating(false);\n      setCheckStep(null);\n      setUnsupportedDrop(false);\n      const targets: ImportTargetColumn[] = allColumns.map((c) => ({ id: c.id, headerText: c.headerText, header: c.header }));\n      setRejectedCount(0);\n      setMergeFailed(false);\n      setMergeMessage(null);\n      setBuildError(null);\n      void loadFile(file, targets);\n    },\n    [allColumns, loadFile],\n  );\n\n  const loadedPropFileRef = useRef<File | null>(null);\n  useEffect(() => {\n    if (!open || !file || loadedPropFileRef.current === file) return;\n    loadedPropFileRef.current = file;\n    onFile(file);\n  }, [open, file, onFile]);\n  useEffect(() => {\n    if (!open) loadedPropFileRef.current = null;\n  }, [open]);\n\n  const onDropFiles = useCallback(\n    (acceptedFiles: File[], rejections: DropzoneRejection[]) => {\n      // a maxSize rejection is re-routed through loadFile so the parse's own size check surfaces the dialog's too-large error\n      const file = acceptedFiles[0] ?? (rejections.some((r) => r.reasons.includes(\"maxSize\")) ? rejections[0]?.file : undefined);\n      if (file) onFile(file);\n      else if (rejections.some((r) => r.reasons.includes(\"accept\"))) setUnsupportedDrop(true);\n    },\n    [onFile],\n  );\n\n  /** Rejected-cell count from the last confirmed build; non-zero keeps the dialog open so the warning is visible. */\n  const [rejectedCount, setRejectedCount] = useState(0);\n  /** True when `onImport` rejected; the dialog stays open and the import can be retried. */\n  const [mergeFailed, setMergeFailed] = useState(false);\n  /** Message of the last `onImport` rejection, when it had one. */\n  const [mergeMessage, setMergeMessage] = useState<string | null>(null);\n  /** Error key of a row hook or build that failed before `onImport`. */\n  const [buildError, setBuildError] = useState<ImportErrorKey | \"importBuildFailed\" | \"checkFailed\" | null>(null);\n  const warnedMissingOnImportRef = useRef(false);\n  const appendRows = useCallback(\n    (rows: TData[], flagged: readonly ImportRejectedCell[]) => {\n      const state = storeApi.getState();\n      const block = appendBlockOf(state) ?? (hasUnloadedRows(state.data) ? \"importNeedsOnImport\" : null);\n      if (block) {\n        if (block === \"importNeedsOnImport\" && isDev() && !warnedMissingOnImportRef.current) {\n          warnedMissingOnImportRef.current = true;\n          console.warn(\"[data-grid-io] this grid holds a window of its result; pass onImport to send the rows to your server\");\n        }\n        throw new Error(labels.io[block]);\n      }\n      const start = state.data.length;\n      const flags = flagged.flatMap(({ rowIndex, gridColumnId, message }) => {\n        const row = rows[rowIndex];\n        return row === undefined ? [] : [{ rowId: state.getRowId(row, start + rowIndex), columnId: gridColumnId, message: message ?? \"\" }];\n      });\n      commitWithFlags(\n        {\n          source: \"import\",\n          ops: rows.map((row, offset) => ({ type: \"insert\" as const, rowId: state.getRowId(row, start + offset), row, index: start + offset })),\n        },\n        flags,\n      );\n    },\n    [commitWithFlags, storeApi, labels],\n  );\n  const finish = useCallback(\n    (rows: TData[], rejected: readonly ImportRejectedCell[], flagged: readonly ImportRejectedCell[], source: ImportSource) => {\n      setMergeFailed(false);\n      setMergeMessage(null);\n      setIsValidating(true);\n      const token = ++confirmTokenRef.current;\n      const signal = abortControllerRef.current?.signal ?? new AbortController().signal;\n      void Promise.resolve()\n        .then(() => (onImport ? onImport(rows, { signal, rejected, flagged, ...source }) : appendRows(rows, flagged)))\n        .then(() => {\n          if (confirmTokenRef.current === token) actions.clearSelection();\n        })\n        .then(\n          () => {\n            if (confirmTokenRef.current !== token) return;\n            setIsValidating(false);\n            setCheckStep(null);\n            if (rejected.length > 0) {\n              setRejectedCount(rejected.length);\n              return;\n            }\n            onOpenChange(false);\n          },\n          (error) => {\n            if (confirmTokenRef.current !== token) return;\n            setIsValidating(false);\n            setMergeFailed(true);\n            setMergeMessage(error instanceof Error && error.message !== \"\" ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH) : null);\n            if (onImportError) {\n              try {\n                onImportError(error);\n              } catch (callbackError) {\n                if (isDev()) console.warn(\"[data-grid-io] onImportError threw\", callbackError);\n              }\n            } else if (isDev() && onImport) console.warn(\"[data-grid-io] onImport rejected; the dialog stays open\", error);\n          },\n        );\n    },\n    [onImport, onImportError, appendRows, actions, onOpenChange],\n  );\n\n  const onConfirm = useCallback(() => {\n    if (!preview) return;\n    const state = storeApi.getState();\n    const abortController = new AbortController();\n    abortControllerRef.current = abortController;\n    setBuildError(null);\n    const clipboardParse = state.processCellFromClipboard as ((text: string, ctx: { row: TData; column: unknown; fromText: (text: string) => unknown }) => unknown) | undefined;\n    const cellParser: ProcessCellFromText<TData> | undefined =\n      processCellFromText ?? (clipboardParse ? (text, ctx) => clipboardParse(text, { row: ctx.row, column: ctx.column, fromText: ctx.fromText }) : undefined);\n    // state.cellTypes comes back from the generic-erased store (TData = unknown, see core store.tsx's InternalSyncProps comment); re-widened here to this dialog's own TData. allColumns is already TData-typed via useDataGridAllColumns<TData>() above.\n    const source: ImportSource = { fileName: preview.fileName, sheetName: preview.sheetName, mapping: preview.mapping };\n    const token = ++confirmTokenRef.current;\n    const fail = (reason: unknown) => {\n      if (confirmTokenRef.current !== token) return;\n      setIsValidating(false);\n      if (reason instanceof Error && reason.message === IMPORT_CANCELLED_MESSAGE) return;\n      const key = importErrorKey(reason);\n      if (key === null) {\n        if (!abortController.signal.aborted) setBuildError(\"importBuildFailed\");\n        return;\n      }\n      setBuildError(key === \"errorTooManyCells\" || key === \"errorNoRows\" ? key : \"importBuildFailed\");\n    };\n    const built = build<TData>({\n      columns: allColumns,\n      // The store erases TData; the cast re-widens cellTypes to this dialog's TData.\n      cellTypes: state.cellTypes as never,\n      createRow,\n      signal: abortController.signal,\n      processImportRows,\n      processCellFromText: cellParser,\n      checkImport,\n      existingRows: onImport ? undefined : (state.data as TData[]),\n      validateRow: onImport ? (state.validateRow as BuildImportedRowsOptions<TData>[\"validateRow\"]) : undefined,\n      getRowId: (row, index) => state.getRowId(row, state.data.length + index),\n    });\n    // The dialog stays open with Import disabled while the build runs (chunked so it can repaint and Cancel can land),\n    // and closes when the last verdict is in, or drops the batch silently if Cancel/close beat it.\n    setIsValidating(true);\n    void built.then((result) => {\n      if (confirmTokenRef.current !== token) return; // superseded by a newer confirm, or the dialog reset\n      setIsValidating(false);\n      if (result === null) return;\n      const { check } = result;\n      if (check?.status === \"failed\") return setBuildError(\"checkFailed\");\n      if (check && check.refusals.length > 0) return setCheckStep({ rows: result.rows, rejected: result.rejected, flagged: result.flagged, source, refusals: check.refusals, more: check.more, summary: check.summary });\n      finish(result.rows, result.rejected, result.flagged, source);\n    }, fail);\n  }, [preview, build, allColumns, storeApi, createRow, finish, processImportRows, processCellFromText, onImport, checkImport]);\n\n  const backFromCheck = useCallback(() => {\n    returnFocusRef.current = true;\n    setCheckStep(null);\n  }, []);\n\n  const onCancel = useCallback(() => {\n    abortControllerRef.current?.abort();\n    onOpenChange(false);\n  }, [onOpenChange]);\n\n  const importBlock = useImportBlock(onImport, open);\n  const acceptedTypesLabel = labels.io.dropzoneDescription(acceptedTypeNames(accept), labels.io.maxFileSize(maxFileBytes));\n\n  return (\n    <Dialog open={open} onOpenChange={onOpenChange}>\n      <DialogContent className={cn(\"max-h-[80vh] min-w-0 overflow-y-auto sm:max-w-2xl\", className)}>\n        <DialogHeader>\n          <DialogTitle>{checkStep ? labels.io.checkStepTitle : labels.io.importDialogTitle}</DialogTitle>\n          <DialogDescription>{labels.io.importDialogDescription}</DialogDescription>\n        </DialogHeader>\n\n        <div className=\"flex min-w-0 flex-col gap-3\">\n          {checkStep ? null : preview ? (\n            <Dropzone compact accept={accept} accessibleDescription={acceptedTypesLabel} maxFiles={1} maxSize={maxFileBytes} onDrop={onDropFiles} aria-label={labels.io.chooseFile}>\n              <Paperclip className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n              <span className=\"min-w-0 flex-1 truncate text-sm text-foreground\">{preview.fileName}</span>\n              <span className=\"shrink-0 text-xs text-muted-foreground\">{labels.io.replaceFile}</span>\n            </Dropzone>\n          ) : (\n            <Dropzone accept={accept} accessibleDescription={acceptedTypesLabel} maxFiles={1} maxSize={maxFileBytes} onDrop={onDropFiles} aria-label={labels.io.chooseFile}>\n              <DropzoneEmptyState title={labels.io.chooseFile} description={labels.io.emptyDropzoneCaption(labels.io.maxFileSize(maxFileBytes))} />\n            </Dropzone>\n          )}\n\n          {importBlock && <p role=\"alert\" className=\"text-sm text-destructive\">{labels.io[importBlock]}</p>}\n\n          {unsupportedDrop && <p role=\"alert\" className=\"text-sm text-destructive\">{labels.io.errorUnsupportedFile}</p>}\n\n          {error && <p role=\"alert\" className=\"text-sm text-destructive\">{labels.io[error]}</p>}\n\n          {rejectedCount > 0 && <p role=\"alert\" className=\"text-sm text-destructive\">{labels.io.importRejectedCells(rejectedCount)}</p>}\n\n          {buildError && <p role=\"alert\" className=\"text-sm text-destructive\">{labels.io[buildError]}</p>}\n\n          {mergeFailed && (\n            <p role=\"alert\" className=\"text-sm text-destructive\">\n              {mergeMessage ? labels.io.importFailedWithMessage(mergeMessage) : labels.io.importMergeFailed}\n            </p>\n          )}\n\n          {checkStep && (\n            <div className=\"flex min-w-0 flex-col gap-2\">\n              <p className=\"text-sm font-medium text-foreground\">{labels.io.checkSummary({ refused: checkStep.refusals.length + checkStep.more, ...checkStep.summary })}</p>\n              <div className=\"min-w-0 overflow-hidden rounded-md border border-border\">\n                <Table>\n                  <TableHeader>\n                    <TableRow className=\"hover:bg-transparent\">\n                      <TableHead>{labels.io.checkRowHeading}</TableHead>\n                      <TableHead>{labels.io.checkColumnHeading}</TableHead>\n                      <TableHead>{labels.io.checkMessageHeading}</TableHead>\n                    </TableRow>\n                  </TableHeader>\n                  <TableBody>\n                    {checkStep.refusals.slice(0, CHECK_STEP_ROWS).map((refusal, index) => {\n                      const column = allColumns.find((candidate) => candidate.id === refusal.columnId);\n                      return (\n                        <TableRow key={index} className=\"hover:bg-transparent\">\n                          <TableCell className=\"p-1.5\">{refusal.rowIndex + 1}</TableCell>\n                          <TableCell className=\"p-1.5\">{column ? columnLabelText(column) : \"\"}</TableCell>\n                          <TableCell className=\"whitespace-normal p-1.5 text-muted-foreground\">{refusal.message ?? \"\"}</TableCell>\n                        </TableRow>\n                      );\n                    })}\n                  </TableBody>\n                </Table>\n              </div>\n              {checkStep.refusals.length + checkStep.more > CHECK_STEP_ROWS && (\n                <span className=\"text-xs text-muted-foreground\">{labels.io.checkAndMore(checkStep.refusals.length + checkStep.more - CHECK_STEP_ROWS)}</span>\n              )}\n            </div>\n          )}\n\n          {preview && !checkStep && (\n            <>\n              <div className=\"flex items-center gap-4\">\n                <div className=\"flex items-center gap-2\">\n                  <Checkbox id={headerRowId} checked={preview.hasHeaderRow} onCheckedChange={(checked) => setHasHeaderRow(checked === true)} />\n                  <Label htmlFor={headerRowId}>{labels.io.hasHeaderRow}</Label>\n                </div>\n                {preview.delimiter !== undefined && (\n                  <label className=\"flex items-center gap-2 text-sm text-foreground\">\n                    {labels.io.delimiter}\n                    <Select items={delimiterItems} value={preview.delimiter} onValueChange={(value) => void setDelimiter(value as CsvDelimiter)}>\n                      <SelectTrigger className=\"w-36\" size=\"sm\" aria-label={labels.io.delimiter}>\n                        <SelectValue />\n                      </SelectTrigger>\n                      <SelectContent>\n                        {delimiterItems.map((item) => (\n                          <SelectItem key={item.value} value={item.value}>\n                            {item.label}\n                          </SelectItem>\n                        ))}\n                      </SelectContent>\n                    </Select>\n                  </label>\n                )}\n                {preview.sheetNames !== undefined && preview.sheetNames.length > 1 && (\n                  <label className=\"flex items-center gap-2 text-sm text-foreground\">\n                    {labels.io.sheet}\n                    <Select value={preview.sheetName ?? preview.sheetNames[0]} onValueChange={(value) => void setSheetName(value as string)}>\n                      <SelectTrigger className=\"w-40\" size=\"sm\" aria-label={labels.io.sheet}>\n                        <SelectValue />\n                      </SelectTrigger>\n                      <SelectContent>\n                        {preview.sheetNames.map((name) => (\n                          <SelectItem key={name} value={name} title={name}>\n                            {name}\n                          </SelectItem>\n                        ))}\n                      </SelectContent>\n                    </Select>\n                  </label>\n                )}\n              </div>\n\n              <div className=\"flex min-w-0 flex-col gap-1\">\n                <span className=\"text-sm font-medium text-foreground\">{labels.io.mapColumns}</span>\n                <div className=\"min-w-0 overflow-hidden rounded-md border border-border\">\n                  {/* fixed layout gives every column an identical track — keeps selects and preview cells aligned */}\n                  <Table className=\"table-fixed\" style={{ minWidth: `${preview.importHeaders.length * 9}rem` }}>\n                    <TableHeader>\n                      <TableRow className=\"hover:bg-transparent has-aria-expanded:bg-transparent\">\n                        {preview.importHeaders.map((header, importColumnIndex) => {\n                          const currentGridColumnId = preview.mapping[importColumnIndex]?.gridColumnId ?? null;\n                          // one source per grid column: a column mapped elsewhere is disabled\n                          const takenElsewhere = new Set(\n                            preview.mapping\n                              .filter((m) => m.importColumnIndex !== importColumnIndex && m.gridColumnId !== null)\n                              .map((m) => m.gridColumnId),\n                          );\n                          return (\n                            <TableHead key={importColumnIndex} className=\"h-auto bg-muted/50 p-1.5 align-top whitespace-normal\">\n                              <div className=\"mb-1 truncate\" title={header}>\n                                {header}\n                              </div>\n                              <div className=\"flex items-center gap-1\">\n                                <Select\n                                  items={mappingItems}\n                                  value={currentGridColumnId ?? SKIP_VALUE}\n                                  onValueChange={(value) =>\n                                    setMapping(importColumnIndex, value === SKIP_VALUE || value === null ? null : value)\n                                  }\n                                >\n                                  <SelectTrigger className=\"w-full\" size=\"sm\" aria-label={labels.io.mapColumnAriaLabel(header)}>\n                                    <SelectValue />\n                                  </SelectTrigger>\n                                  <SelectContent>\n                                    {mappingItems.map((item) => (\n                                      <SelectItem key={item.value} value={item.value} disabled={takenElsewhere.has(item.value)}>\n                                        {item.label}\n                                      </SelectItem>\n                                    ))}\n                                  </SelectContent>\n                                </Select>\n                                {currentGridColumnId !== null && (\n                                  <Button\n                                    type=\"button\"\n                                    variant=\"ghost\"\n                                    size=\"icon\"\n                                    className=\"size-7 shrink-0\"\n                                    aria-label={labels.io.skipColumnQuick}\n                                    onClick={() => setMapping(importColumnIndex, null)}\n                                  >\n                                    <X className=\"size-3.5\" />\n                                  </Button>\n                                )}\n                              </div>\n                            </TableHead>\n                          );\n                        })}\n                      </TableRow>\n                    </TableHeader>\n                    <TableBody>\n                      {previewRows.map((row, rowIndex) => (\n                        <TableRow key={rowIndex} className=\"hover:bg-transparent\">\n                          {preview.importHeaders.map((_, columnIndex) => (\n                            <TableCell key={columnIndex} className=\"truncate p-1.5 text-muted-foreground\" title={row[columnIndex] ?? \"\"}>\n                              {row[columnIndex] ?? \"\"}\n                            </TableCell>\n                          ))}\n                        </TableRow>\n                      ))}\n                    </TableBody>\n                  </Table>\n                </div>\n                {preview.importHeaders.length > 1 && (\n                  <span className=\"text-xs text-muted-foreground\">{labels.io.mapColumnsHint}</span>\n                )}\n                <span className=\"text-xs text-muted-foreground\">\n                  {labels.io.previewTruncated(previewRows.length, importRows.length)}\n                </span>\n              </div>\n            </>\n          )}\n        </div>\n\n        <DialogFooter>\n          {checkStep ? (\n            <Fragment key=\"check\">\n              <Button type=\"button\" variant=\"outline\" onClick={backFromCheck} autoFocus>\n                {labels.io.back}\n              </Button>\n              <Button type=\"button\" onClick={() => finish(checkStep.rows, checkStep.rejected, checkStep.flagged, checkStep.source)} disabled={isValidating}>\n                {labels.io.importAnyway}\n              </Button>\n            </Fragment>\n          ) : (\n            <Fragment key=\"confirm\">\n          <Button type=\"button\" variant=\"outline\" onClick={onCancel}>\n            {labels.io.cancel}\n          </Button>\n            <Button ref={confirmButtonRef} type=\"button\" onClick={onConfirm} disabled={!preview || importBlock !== null || importRows.length === 0 || isParsing || isValidating || rejectedCount > 0}>\n              {labels.io.import}\n            </Button>\n            </Fragment>\n          )}\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-io/import-dialog.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-io/import-button.tsx",
      "content": "\"use client\";\r\n\r\nimport { useState, type ReactNode } from \"react\";\r\nimport { Upload } from \"lucide-react\";\r\nimport { useDataGridLabels } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { DataGridImportDialog, useImportBlock, type DataGridImportDialogProps, type ImportDefaults } from \"./import-dialog\";\r\n\r\nexport type { ImportDefaults };\r\n\r\n/** Props for {@link DataGridImportButton}: the dialog's props except the open state, plus `className`. */\r\nexport type DataGridImportButtonProps<TData> = Omit<DataGridImportDialogProps<TData>, \"open\" | \"onOpenChange\" | \"className\"> & {\r\n  className?: string;\r\n};\r\n\r\n/**\r\n * Toolbar-slot import trigger: a ghost icon button that opens {@link DataGridImportDialog}.\r\n * `size-8` + ghost variant matches the toolbar's other icon buttons.\r\n */\r\nexport function DataGridImportButton<TData>(props: DataGridImportButtonProps<TData>): ReactNode {\r\n  const { className, ...dialogProps } = props;\r\n  const labels = useDataGridLabels();\r\n  const [open, setOpen] = useState(false);\r\n  const importBlock = useImportBlock(dialogProps.onImport, true);\r\n\r\n  return (\r\n    <>\r\n      <Button type=\"button\" variant=\"ghost\" size=\"icon\" className={className} aria-label={labels.io.importButton} disabled={importBlock !== null} title={importBlock ? labels.io[importBlock] : undefined} onClick={() => setOpen(true)}>\r\n        <Upload />\r\n      </Button>\r\n      <DataGridImportDialog open={open} onOpenChange={setOpen} {...dialogProps} />\r\n    </>\r\n  );\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-io/import-button.tsx"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
