react-smart-copy 1.24.0 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +132 -1834
- package/dist/capture.cjs +3 -3
- package/dist/capture.d.cts +1 -1
- package/dist/capture.d.ts +1 -1
- package/dist/capture.js +3 -3
- package/dist/chunks/{clipboard-adapter-CtH4VELE.d.cts → clipboard-adapter-CfaIbZpv.d.cts} +2 -2
- package/dist/chunks/{clipboard-adapter-Ds0irroN.d.ts → clipboard-adapter-Chm6zq60.d.ts} +2 -2
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js → clipboard-adapter-CmKDTFdO.js} +3 -3
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js.map → clipboard-adapter-CmKDTFdO.js.map} +1 -1
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs → clipboard-adapter-UIFc_Qso.cjs} +3 -3
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs.map → clipboard-adapter-UIFc_Qso.cjs.map} +1 -1
- package/dist/chunks/{contrast-C6CVklEI.cjs → contrast-C9d8QuaF.cjs} +2 -2
- package/dist/chunks/{contrast-C6CVklEI.cjs.map → contrast-C9d8QuaF.cjs.map} +1 -1
- package/dist/chunks/{contrast-DpK2JIVu.js → contrast-DUaZq5SA.js} +2 -2
- package/dist/chunks/{contrast-DpK2JIVu.js.map → contrast-DUaZq5SA.js.map} +1 -1
- package/dist/chunks/{copy-interceptor-CZWzGOkL.d.cts → copy-interceptor-BClcHS_P.d.cts} +2 -2
- package/dist/chunks/{copy-interceptor-C6NABy1l.d.ts → copy-interceptor-D8c9EDnO.d.ts} +2 -2
- package/dist/chunks/{core-Cp2HSpaz.js → core-BH2uIumi.js} +5 -5
- package/dist/chunks/{core-Cp2HSpaz.js.map → core-BH2uIumi.js.map} +1 -1
- package/dist/chunks/{core-DYf_Lhbe.cjs → core-DmncxMt3.cjs} +5 -5
- package/dist/chunks/{core-DYf_Lhbe.cjs.map → core-DmncxMt3.cjs.map} +1 -1
- package/dist/chunks/{deadline-C29AlS_Q.js → deadline-CbwnZ3Oq.js} +2 -2
- package/dist/chunks/{deadline-C29AlS_Q.js.map → deadline-CbwnZ3Oq.js.map} +1 -1
- package/dist/chunks/{deadline-DkiB8ZHE.cjs → deadline-j2hD7JKz.cjs} +2 -2
- package/dist/chunks/{deadline-DkiB8ZHE.cjs.map → deadline-j2hD7JKz.cjs.map} +1 -1
- package/dist/chunks/{errors-9h8sdFFX.js → errors-CT-FfUtU.js} +2 -2
- package/dist/chunks/errors-CT-FfUtU.js.map +1 -0
- package/dist/chunks/{errors-BwOF6T_M.cjs → errors-DFmEAC4E.cjs} +2 -2
- package/dist/chunks/errors-DFmEAC4E.cjs.map +1 -0
- package/dist/chunks/{field-Bytz2WfN.cjs → field-B6SRWRbI.cjs} +59 -19
- package/dist/chunks/field-B6SRWRbI.cjs.map +1 -0
- package/dist/chunks/{field-BHo5y-t_.js → field-DsRKkbav.js} +54 -20
- package/dist/chunks/field-DsRKkbav.js.map +1 -0
- package/dist/chunks/{index-vz0iW5V2.d.cts → index-CqYzvxSN.d.cts} +4 -4
- package/dist/chunks/{index-mr7sSAgP.d.ts → index-Q_QeSwGr.d.ts} +4 -4
- package/dist/chunks/limits-9wi1f6xT.cjs +23 -0
- package/dist/chunks/limits-9wi1f6xT.cjs.map +1 -0
- package/dist/chunks/limits-BP9R5wnr.js +18 -0
- package/dist/chunks/limits-BP9R5wnr.js.map +1 -0
- package/dist/chunks/{paste-adapter--SPL4PRE.d.cts → paste-adapter-B6eucH3E.d.cts} +2 -2
- package/dist/chunks/{paste-adapter-uahXnTYk.d.ts → paste-adapter-CfIDT3mp.d.ts} +2 -2
- package/dist/chunks/{paste-reader-Bo01IMC_.cjs → paste-reader-BWQaYNaV.cjs} +2 -2
- package/dist/chunks/paste-reader-BWQaYNaV.cjs.map +1 -0
- package/dist/chunks/{paste-reader-D9i7yMXF.js → paste-reader-D6uOTDBM.js} +2 -2
- package/dist/chunks/paste-reader-D6uOTDBM.js.map +1 -0
- package/dist/chunks/{payload-DI5AorDz.js → payload-BWQ6sPtS.js} +3 -3
- package/dist/chunks/{payload-DI5AorDz.js.map → payload-BWQ6sPtS.js.map} +1 -1
- package/dist/chunks/{payload-DGw-JOo7.js → payload-BrQWGwyx.js} +2 -2
- package/dist/chunks/{payload-DGw-JOo7.js.map → payload-BrQWGwyx.js.map} +1 -1
- package/dist/chunks/{payload-Cl_8hCI5.d.ts → payload-CcvSx_Hq.d.ts} +4 -2
- package/dist/chunks/{payload-CcwKJ_bU.d.cts → payload-qkAWVXWA.d.cts} +4 -2
- package/dist/chunks/{payload-CUymxwim.cjs → payload-sBxkG7jH.cjs} +2 -2
- package/dist/chunks/{payload-CUymxwim.cjs.map → payload-sBxkG7jH.cjs.map} +1 -1
- package/dist/chunks/{payload-J6GjHuh3.cjs → payload-tTK6REua.cjs} +3 -3
- package/dist/chunks/{payload-J6GjHuh3.cjs.map → payload-tTK6REua.cjs.map} +1 -1
- package/dist/chunks/{share-Bop47Znn.js → share-CU91L4EK.js} +6 -6
- package/dist/chunks/{share-Bop47Znn.js.map → share-CU91L4EK.js.map} +1 -1
- package/dist/chunks/{share-e7FenIr2.d.ts → share-DVR_DhHc.d.ts} +3 -3
- package/dist/chunks/{share-C0esXvRK.d.cts → share-hIwth7Dh.d.cts} +3 -3
- package/dist/chunks/{share-ayDz974N.cjs → share-nx7M4Z0t.cjs} +6 -6
- package/dist/chunks/{share-ayDz974N.cjs.map → share-nx7M4Z0t.cjs.map} +1 -1
- package/dist/chunks/{url-D4PGsRm8.cjs → url-BrhVUwn7.cjs} +2 -2
- package/dist/chunks/{url-D4PGsRm8.cjs.map → url-BrhVUwn7.cjs.map} +1 -1
- package/dist/chunks/{url-BcMYVCXQ.js → url-COID0BLY.js} +2 -2
- package/dist/chunks/{url-BcMYVCXQ.js.map → url-COID0BLY.js.map} +1 -1
- package/dist/code.cjs +4 -8
- package/dist/code.cjs.map +1 -1
- package/dist/code.d.cts +1 -1
- package/dist/code.d.ts +1 -1
- package/dist/code.js +2 -6
- package/dist/code.js.map +1 -1
- package/dist/color.cjs +2 -2
- package/dist/color.d.cts +1 -1
- package/dist/color.d.ts +1 -1
- package/dist/color.js +2 -2
- package/dist/core.cjs +5 -5
- package/dist/core.d.cts +5 -5
- package/dist/core.d.ts +5 -5
- package/dist/core.js +5 -5
- package/dist/email.cjs +12 -8
- package/dist/email.cjs.map +1 -1
- package/dist/email.d.cts +9 -5
- package/dist/email.d.ts +9 -5
- package/dist/email.js +12 -9
- package/dist/email.js.map +1 -1
- package/dist/files.cjs +1 -1
- package/dist/files.cjs.map +1 -1
- package/dist/files.d.cts +3 -59
- package/dist/files.d.ts +3 -59
- package/dist/files.js +1 -1
- package/dist/files.js.map +1 -1
- package/dist/image.cjs +2 -2
- package/dist/image.cjs.map +1 -1
- package/dist/image.js +2 -2
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -19
- package/dist/index.d.ts +43 -19
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/link.cjs +3 -3
- package/dist/link.d.cts +1 -1
- package/dist/link.d.ts +1 -1
- package/dist/link.js +3 -3
- package/dist/markdown.cjs +1 -1
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.js +1 -1
- package/dist/markdown.js.map +1 -1
- package/dist/number.cjs +9 -4
- package/dist/number.cjs.map +1 -1
- package/dist/number.d.cts +9 -4
- package/dist/number.d.ts +9 -4
- package/dist/number.js +9 -5
- package/dist/number.js.map +1 -1
- package/dist/otp.cjs +2 -1
- package/dist/otp.d.cts +8 -3
- package/dist/otp.d.ts +8 -3
- package/dist/otp.js +1 -1
- package/dist/rich.cjs +3 -3
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +2 -2
- package/dist/rich.d.ts +2 -2
- package/dist/rich.js +3 -3
- package/dist/rich.js.map +1 -1
- package/dist/secrets.cjs +1 -1
- package/dist/secrets.cjs.map +1 -1
- package/dist/secrets.d.cts +1 -1
- package/dist/secrets.d.ts +1 -1
- package/dist/secrets.js +1 -1
- package/dist/secrets.js.map +1 -1
- package/dist/share.cjs +1 -1
- package/dist/share.d.cts +1 -1
- package/dist/share.d.ts +1 -1
- package/dist/share.js +1 -1
- package/dist/structured.cjs +2 -2
- package/dist/structured.cjs.map +1 -1
- package/dist/structured.js +2 -2
- package/dist/structured.js.map +1 -1
- package/dist/table.cjs +1 -1
- package/dist/table.cjs.map +1 -1
- package/dist/table.d.cts +1 -1
- package/dist/table.d.ts +1 -1
- package/dist/table.js +1 -1
- package/dist/table.js.map +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +2 -2
- package/package.json +10 -4
- package/dist/chunks/errors-9h8sdFFX.js.map +0 -1
- package/dist/chunks/errors-BwOF6T_M.cjs.map +0 -1
- package/dist/chunks/field-BHo5y-t_.js.map +0 -1
- package/dist/chunks/field-Bytz2WfN.cjs.map +0 -1
- package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +0 -1
- package/dist/chunks/paste-reader-D9i7yMXF.js.map +0 -1
package/dist/table.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table.js","names":["invalid","isDate","invalid","invalid"],"sources":["../src/table/serialize.ts","../src/table/parse.ts","../src/table/records.ts","../src/table/cell-value.ts","../src/table/ag-grid.ts","../src/table/tanstack.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\nimport type { HtmlPayload, TextPayload } from '../core/payload';\n\n/* ------------------------------------------------------------------ Types */\n\n/**\n * What a table cell may hold. Numbers, bigints, booleans and dates stay typed\n * all the way to the spreadsheet; strings are kept as text.\n */\nexport type TableCell = string | number | bigint | boolean | Date | null | undefined;\n\n/** One row of cells, left to right. */\nexport type TableRow = readonly TableCell[];\n\n/**\n * A table as plain data: optional header labels and rows of cells.\n * Every helper in this module produces or consumes this shape, so the output of\n * `fromRows`, `fromAgGrid`, `fromTanStackTable` and `parseTable` can all be\n * copied with {@link tablePayload}.\n */\nexport interface TableData {\n readonly headers?: readonly string[] | null | undefined;\n readonly rows: readonly TableRow[];\n}\n\n/** Where a cell sits, passed to `formatCell`. Indexes are zero-based; `row` is -1 for the header row. */\nexport interface CellFormatContext {\n readonly row: number;\n readonly column: number;\n readonly header: string | undefined;\n}\n\nexport interface TableFormatOptions {\n /** Include the header row when the data has headers. Default `true`. */\n readonly headers?: boolean;\n /**\n * Neutralise text cells that a spreadsheet would run as a formula: those starting\n * with `=`, `+`, `-`, `@`, a tab or a line break (and their full-width forms), as\n * listed by OWASP's CSV Injection guidance. They get a leading `'`, which\n * spreadsheets treat as \"this is text\". Typed numbers are never touched, so\n * `-5` as a number stays a number. Default `true`; turn off only for trusted data.\n */\n readonly formulaGuard?: boolean;\n /**\n * Mark string cells as text in the HTML flavour (`mso-number-format:\"\\@\"`), so\n * Excel keeps `00123`, `1/2` or `1E5` exactly as written instead of converting them.\n * Typed numbers, booleans and dates are left for the spreadsheet to recognise.\n * Default `true`.\n */\n readonly preserveText?: boolean;\n /**\n * Custom text for a cell. Return `undefined` to use the default. The result is\n * still escaped, and guarded when the original value was text.\n * Defaults: `null`/`undefined` → empty, `Date` → ISO 8601 (invalid dates → empty),\n * everything else → `String(value)`.\n */\n readonly formatCell?: (value: TableCell, context: CellFormatContext) => string | undefined;\n /** Upper bound on cells (header included), checked before any work. Default 1,000,000. */\n readonly maxCells?: number;\n}\n\nexport interface TablePayloadOptions extends TableFormatOptions {\n /**\n * `'html'` (default): an HTML table plus a tab-separated plain-text fallback, which\n * degrades to the plain text where rich copy is unavailable.\n * `'text'`: tab-separated text only.\n */\n readonly format?: 'html' | 'text';\n}\n\nexport const DEFAULT_TABLE_MAX_CELLS = 1_000_000;\n\n/* --------------------------------------------------------------- Prepare */\n\n/** `text`: written as typed by a person. `value`: a number, bigint, boolean or date. */\ntype CellKind = 'text' | 'value';\n\ninterface PreparedCell {\n readonly text: string;\n readonly kind: CellKind;\n}\n\ninterface PreparedTable {\n readonly header: readonly PreparedCell[] | null;\n readonly body: readonly (readonly PreparedCell[])[];\n}\n\n// OWASP CSV Injection: = + - @ tab CR LF, and the full-width = + - @.\nconst FORMULA_START = /^[=+\\-@\\t\\r\\n=+-@]/;\nconst LINE_BREAKS = /\\r\\n?/g;\nconst EMPTY: PreparedCell = { text: '', kind: 'text' };\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/** Only called for values that are not null, undefined or a cell. */\nfunction typeName(value: unknown): string {\n if (Array.isArray(value)) return 'array';\n return typeof value === 'object' ? Object.prototype.toString.call(value).slice(8, -1) : typeof value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isList(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\nfunction isDate(value: unknown): value is Date {\n return value instanceof Date || Object.prototype.toString.call(value) === '[object Date]';\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw invalid(`\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\nfunction defaultText(value: unknown, where: string): { text: string; kind: CellKind } {\n if (value === null || value === undefined) return { text: '', kind: 'text' };\n switch (typeof value) {\n case 'string':\n return { text: value, kind: 'text' };\n case 'number':\n case 'bigint':\n case 'boolean':\n return { text: String(value), kind: 'value' };\n default:\n if (isDate(value)) {\n const time = value.getTime();\n return { text: Number.isNaN(time) ? '' : value.toISOString(), kind: 'value' };\n }\n throw invalid(\n `${where} is ${typeName(value)}, which has no text form. ` +\n 'Pass a string, number, bigint, boolean, Date, null or undefined, or convert it with `formatCell`.',\n );\n }\n}\n\nfunction prepare(data: TableData, options: TableFormatOptions): PreparedTable {\n // Validated as `unknown`: plain-JS callers and runtime data reach this too.\n const input: unknown = data;\n if (!isRecord(input) || !isList(input['rows'])) {\n throw invalid('Table data must be an object with a `rows` array.');\n }\n const rawHeaders = input['headers'];\n if (rawHeaders !== undefined && rawHeaders !== null && !isList(rawHeaders)) {\n throw invalid('`headers` must be an array of strings, null or undefined.');\n }\n const headers: readonly unknown[] | null = options.headers === false ? null : (rawHeaders ?? null);\n const rows: readonly unknown[] = input['rows'];\n\n let width = headers?.length ?? 0;\n const lines: (readonly unknown[])[] = [];\n for (const [index, row] of rows.entries()) {\n if (!isList(row)) throw invalid(`Row ${String(index + 1)} is not an array of cells.`);\n width = Math.max(width, row.length);\n lines.push(row);\n }\n if (width === 0) throw invalid('The table has no cells to copy.');\n\n const maxCells = resolveLimit(options.maxCells, DEFAULT_TABLE_MAX_CELLS, 'maxCells');\n const cellCount = (rows.length + (headers ? 1 : 0)) * width;\n if (cellCount > maxCells) {\n throw copyFailure(\n 'too-large',\n `The table has ${String(cellCount)} cells, over the limit of ${String(maxCells)}. Raise \\`maxCells\\` or copy fewer rows.`,\n );\n }\n\n const guard = options.formulaGuard ?? true;\n const formatCell = options.formatCell;\n\n const label = (column: number): string | undefined => {\n const value = headers?.[column];\n return typeof value === 'string' ? value : undefined;\n };\n\n const cell = (value: unknown, row: number, column: number): PreparedCell => {\n const where = row < 0 ? `Header ${String(column + 1)}` : `Cell at row ${String(row + 1)}, column ${String(column + 1)}`;\n const base = defaultText(value, where);\n let text = base.text;\n if (formatCell) {\n // `defaultText` has accepted the value, so it is a valid cell.\n const custom: unknown = formatCell(value as TableCell, { row, column, header: label(column) });\n if (custom !== undefined) {\n if (typeof custom !== 'string') throw invalid(`\\`formatCell\\` must return a string or undefined (${where}).`);\n text = custom;\n }\n }\n text = text.replace(LINE_BREAKS, '\\n');\n if (guard && base.kind === 'text' && FORMULA_START.test(text)) text = `'${text}`;\n return text === '' ? EMPTY : { text, kind: base.kind };\n };\n\n const header = headers\n ? Array.from({ length: width }, (_, column) => {\n const value = headers[column];\n if (value !== undefined && value !== null && typeof value !== 'string') {\n throw invalid(`Header ${String(column + 1)} must be a string (received ${typeName(value)}).`);\n }\n return cell(value ?? '', -1, column);\n })\n : null;\n\n const body = lines.map((row, rowIndex) => Array.from({ length: width }, (_, column) => cell(row[column], rowIndex, column)));\n\n return { header, body };\n}\n\n/* ----------------------------------------------------------------- Writers */\n\nconst NEEDS_QUOTES = /[\\t\\n\\r\"]/;\n\nfunction tsvField(text: string): string {\n return NEEDS_QUOTES.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text;\n}\n\nfunction toTsv(table: PreparedTable): string {\n const lines = table.header ? [table.header, ...table.body] : table.body;\n // Rows end in CRLF, as Excel writes them; line breaks inside a cell stay LF.\n const text = lines.map((row) => row.map((cell) => tsvField(cell.text)).join('\\t')).join('\\r\\n');\n // A one-column table ending in an empty cell would end in a bare line break, which\n // readers drop as the trailing newline. A quoted empty field keeps that last row.\n const last = lines.at(-1);\n return lines.length > 1 && last?.length === 1 && last[0]?.text === '' ? `${text}\"\"` : text;\n}\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = { '&': '&', '<': '<', '>': '>', '\"': '"' };\n\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"]/g, (char) => HTML_ESCAPES[char] as string);\n}\n\n// Whitespace HTML would otherwise collapse: leading, trailing, doubled, or tabs.\nconst SIGNIFICANT_SPACE = /^\\s|\\s$| {2}|\\t/;\n\nfunction htmlCell(tag: 'th' | 'td', cell: PreparedCell, preserveText: boolean): string {\n const styles: string[] = [];\n if (preserveText && cell.kind === 'text' && cell.text !== '') styles.push(\"mso-number-format:'\\\\@'\");\n if (SIGNIFICANT_SPACE.test(cell.text)) styles.push('white-space:pre-wrap');\n const style = styles.length > 0 ? ` style=\"${styles.join(';')}\"` : '';\n return `<${tag}${style}>${escapeHtml(cell.text).replace(/\\n/g, '<br>')}</${tag}>`;\n}\n\nfunction toHtml(table: PreparedTable, preserveText: boolean): string {\n const row = (cells: readonly PreparedCell[], tag: 'th' | 'td') =>\n `<tr>${cells.map((cell) => htmlCell(tag, cell, preserveText)).join('')}</tr>`;\n const head = table.header ? `<thead>${row(table.header, 'th')}</thead>` : '';\n return `<table>${head}<tbody>${table.body.map((cells) => row(cells, 'td')).join('')}</tbody></table>`;\n}\n\n/** `prepare` guarantees at least one line of at least one cell. */\nfunction hasContent(table: PreparedTable): boolean {\n const lines = table.header ? [table.header, ...table.body] : table.body;\n const first = lines[0] as readonly PreparedCell[];\n return lines.length > 1 || first.length > 1 || (first[0] as PreparedCell).text !== '';\n}\n\n/* -------------------------------------------------------------- Public API */\n\n/**\n * Tab-separated text, the format Excel, Google Sheets, Numbers and LibreOffice paste\n * straight into cells. Cells containing tabs, line breaks or quotes are quoted the\n * way Excel quotes them. Throws a `CopyFailure` (`invalid-payload` or `too-large`).\n */\nexport function tableToTsv(data: TableData, options: TableFormatOptions = {}): string {\n return toTsv(prepare(data, options));\n}\n\n/** An HTML `<table>`: what rich editors (Docs, Word, Notion, mail) and spreadsheets read first. */\nexport function tableToHtml(data: TableData, options: TableFormatOptions = {}): string {\n return toHtml(prepare(data, options), options.preserveText ?? true);\n}\n\n/**\n * A copy payload for a table, ready for `copy()`, `useCopyInterceptor` or `useDragCopy`.\n *\n * ```ts\n * copy(() => tablePayload(fromRows(invoices, columns)));\n * ```\n *\n * The default `html` format carries the HTML table and the tab-separated text in one\n * clipboard entry. Throws a `CopyFailure` for bad input; inside a `copy()` source that\n * becomes the copy's classified error.\n */\nexport function tablePayload(data: TableData, options: TablePayloadOptions & { readonly format: 'text' }): TextPayload;\nexport function tablePayload(data: TableData, options?: TablePayloadOptions & { readonly format?: 'html' }): HtmlPayload;\nexport function tablePayload(data: TableData, options?: TablePayloadOptions): HtmlPayload | TextPayload;\nexport function tablePayload(data: TableData, options: TablePayloadOptions = {}): HtmlPayload | TextPayload {\n const format: unknown = options.format ?? 'html';\n if (format !== 'html' && format !== 'text') {\n throw invalid(`\\`format\\` must be \"html\" or \"text\" (received ${JSON.stringify(format)}).`);\n }\n const table = prepare(data, options);\n if (!hasContent(table)) throw invalid('The table only contains one empty cell; there is nothing to copy.');\n const text = toTsv(table);\n return format === 'text' ? { kind: 'text', value: text } : { kind: 'html', html: toHtml(table, options.preserveText ?? true), text };\n}\n\n/* ------------------------------------------------------------------ Rows */\n\n/** Keys of `Row` whose values are valid cells. */\nexport type CellKey<Row> = {\n [K in keyof Row]-?: Row[K] extends TableCell ? K : never;\n}[keyof Row] &\n string;\n\n/** One output column for {@link fromRows}: a header and how to read the cell. */\nexport interface TableColumn<Row> {\n readonly header: string;\n /** A property of the row, or a function returning the cell. */\n readonly value: CellKey<Row> | ((row: Row, index: number) => TableCell);\n}\n\n/**\n * Turns your own row objects into {@link TableData}, choosing and ordering columns.\n *\n * ```ts\n * fromRows(users, [\n * { header: 'Name', value: 'name' },\n * { header: 'Joined', value: (user) => user.joinedAt },\n * ]);\n * ```\n */\nexport function fromRows<Row>(rows: readonly Row[], columns: readonly TableColumn<Row>[]): TableData {\n const rowList: unknown = rows;\n const columnList: unknown = columns;\n if (!isList(rowList)) throw invalid('`fromRows` expects an array of rows.');\n if (!isList(columnList) || columnList.length === 0) throw invalid('`fromRows` needs at least one column.');\n const headers: string[] = [];\n const readers = columnList.map((column, index): ((row: Row, index: number) => unknown) => {\n if (!isRecord(column) || typeof column['header'] !== 'string') {\n throw invalid(`Column ${String(index + 1)} needs a string \\`header\\`.`);\n }\n const header = column['header'];\n headers.push(header);\n const value = column['value'];\n if (typeof value === 'function') return value as (row: Row, index: number) => unknown;\n if (typeof value === 'string') return (row: Row) => (isRecord(row) ? row[value] : undefined);\n throw invalid(`Column \"${header}\" needs a \\`value\\`: a property name or a function.`);\n });\n // Cells are checked when the table is serialised, with their row and column in the message.\n return {\n headers,\n rows: rows.map((row, index) => readers.map((read) => read(row, index) as TableCell)),\n };\n}\n","import { copyFailure } from '../core/errors';\nimport type { TableData } from './serialize';\nimport { parseInertHtml } from '../core/inert-html';\n\n/* ------------------------------------------------------------------ Types */\n\n/** A table read from pasted or dropped content. Every cell is a string. */\nexport interface ParsedTable extends TableData {\n /** The header row, when one was detected or requested; otherwise `null`. */\n readonly headers: readonly string[] | null;\n /** Data rows, all padded to `columnCount`. */\n readonly rows: readonly (readonly string[])[];\n readonly columnCount: number;\n /** Which clipboard flavour the table came from. */\n readonly source: 'html' | 'text';\n /** `true` when rows or columns were dropped to stay within the limits. Never silent. */\n readonly truncated: boolean;\n}\n\nexport interface ParseTableOptions {\n /**\n * `'auto'` (default): an HTML table's first row is the header when it sits in\n * `<thead>` or is made of `<th>` cells; plain text has no header.\n * `true`: the first row is always the header. `false`: never.\n */\n readonly headers?: 'auto' | boolean;\n /** Which flavour to read when both are present. Default `'html'`, which keeps merged cells and line breaks exact. */\n readonly prefer?: 'html' | 'text';\n /** Column separator for plain text. Default tab, what spreadsheets put on the clipboard. */\n readonly delimiter?: string;\n /** Merged cells: `'empty'` (default) fills the covered cells with `''`, as spreadsheets do; `'repeat'` copies the value. */\n readonly spans?: 'empty' | 'repeat';\n /** Trim spaces around plain-text cells. HTML cells are always normalised. Default `false`. */\n readonly trim?: boolean;\n /** Most rows kept (header included). Default 100,000. Extra rows set `truncated`. */\n readonly maxRows?: number;\n /** Most columns kept. Default 16,384, Excel's own limit. Extra columns set `truncated`. */\n readonly maxColumns?: number;\n /** Most cells kept. Default 1,000,000. */\n readonly maxCells?: number;\n /** Longest input read, in characters. Default 32 MiB. Longer input fails with `too-large`. */\n readonly maxLength?: number;\n}\n\n/** Plain text, or anything with `html` and `text`, such as a `PasteResult`. */\nexport type TableSource =\n | string\n | { readonly html?: string | null | undefined; readonly text?: string | null | undefined };\n\nexport const DEFAULT_PARSE_MAX_ROWS = 100_000;\nexport const DEFAULT_PARSE_MAX_COLUMNS = 16_384;\nexport const DEFAULT_PARSE_MAX_CELLS = 1_000_000;\nexport const DEFAULT_PARSE_MAX_LENGTH = 32 * 1024 * 1024;\n\n/* ---------------------------------------------------------------- Options */\n\ninterface Limits {\n readonly maxRows: number;\n readonly maxColumns: number;\n readonly maxCells: number;\n readonly maxLength: number;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction limit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw invalid(`\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\nfunction resolveLimits(options: ParseTableOptions): Limits {\n return {\n maxRows: limit(options.maxRows, DEFAULT_PARSE_MAX_ROWS, 'maxRows'),\n maxColumns: limit(options.maxColumns, DEFAULT_PARSE_MAX_COLUMNS, 'maxColumns'),\n maxCells: limit(options.maxCells, DEFAULT_PARSE_MAX_CELLS, 'maxCells'),\n maxLength: limit(options.maxLength, DEFAULT_PARSE_MAX_LENGTH, 'maxLength'),\n };\n}\n\nfunction checkLength(input: string, limits: Limits): void {\n if (input.length > limits.maxLength) {\n throw copyFailure(\n 'too-large',\n `The pasted content is ${String(input.length)} characters, over the limit of ${String(limits.maxLength)}.`,\n );\n }\n}\n\n/* ---------------------------------------------------------------- Shaping */\n\n/**\n * Applies the row, column and cell limits, pads ragged rows, splits off the header\n * and drops tables without a single non-empty cell.\n */\nfunction finish(\n grid: readonly (readonly string[])[],\n firstRowIsHeader: boolean,\n source: 'html' | 'text',\n limits: Limits,\n alreadyTruncated: boolean,\n): ParsedTable | null {\n let truncated = alreadyTruncated;\n // Both readers already stop at maxColumns, so the widest row is within it.\n let columnCount = 0;\n for (const row of grid) columnCount = Math.max(columnCount, row.length);\n let rowCount = Math.min(grid.length, limits.maxRows);\n if (columnCount > 0) rowCount = Math.min(rowCount, Math.floor(limits.maxCells / columnCount));\n if (rowCount < grid.length) truncated = true;\n\n const shaped: string[][] = [];\n let anyContent = false;\n for (let index = 0; index < rowCount; index++) {\n const row = grid[index] as readonly string[];\n const cells = Array.from({ length: columnCount }, (_, column) => row[column] ?? '');\n if (!anyContent && cells.some((cell) => cell !== '')) anyContent = true;\n shaped.push(cells);\n }\n if (!anyContent) return null;\n\n // `anyContent` means there is at least one row to take the header from.\n const headers = firstRowIsHeader ? (shaped.shift() as string[]) : null;\n return { headers, rows: shaped, columnCount, source, truncated };\n}\n\n/* ------------------------------------------------------------- Plain text */\n\n/**\n * Splits tab-separated text the way spreadsheets write it: a field that starts with\n * `\"` is quoted (`\"\"` is a literal quote) and may contain tabs and line breaks; rows\n * end in CRLF, LF or CR; the trailing line break spreadsheets add is ignored. A quote\n * that never closes is read as an ordinary character, as Excel does.\n */\nfunction splitDelimited(text: string, delimiter: string, trim: boolean, limits: Limits): { grid: string[][]; truncated: boolean } {\n const grid: string[][] = [];\n const length = text.length;\n let row: string[] = [];\n let field = '';\n let index = 0;\n let fieldStart = true;\n // After one unterminated quote, every later quote is literal too: this keeps the\n // scan linear on hostile input instead of re-reading to the end for each quote.\n let quoting = true;\n let cells = 0;\n const state = { full: false, truncated: false };\n\n const pushField = () => {\n if (row.length >= limits.maxColumns) state.truncated = true;\n else if (cells >= limits.maxCells) state.full = true;\n else {\n row.push(trim ? field.trim() : field);\n cells += 1;\n }\n field = '';\n fieldStart = true;\n };\n const pushRow = () => {\n pushField();\n grid.push(row);\n row = [];\n if (grid.length >= limits.maxRows) state.full = true;\n };\n\n while (index < length && !state.full) {\n const char = text[index] as string;\n\n if (fieldStart && quoting && char === '\"') {\n let value = '';\n let cursor = index + 1;\n let closed = false;\n while (cursor < length) {\n const inner = text[cursor] as string;\n if (inner === '\"') {\n if (text[cursor + 1] === '\"') {\n value += '\"';\n cursor += 2;\n continue;\n }\n closed = true;\n cursor += 1;\n break;\n }\n value += inner;\n cursor += 1;\n }\n if (!closed) {\n quoting = false; // Read this quote, and any later one, as a plain character.\n continue;\n }\n // Anything between the closing quote and the next separator is kept, as Excel does.\n field = value;\n fieldStart = false;\n index = cursor;\n continue;\n }\n\n if (char === delimiter) {\n pushField();\n index += 1;\n } else if (char === '\\r' || char === '\\n') {\n pushRow();\n index += char === '\\r' && text[index + 1] === '\\n' ? 2 : 1;\n } else {\n field += char;\n fieldStart = false;\n index += 1;\n }\n }\n\n if (state.full) {\n // Stopped early: say so when anything but a final line break was left unread.\n if (index < length && !/^(\\r\\n|\\r|\\n)$/.test(text.slice(index))) state.truncated = true;\n return { grid, truncated: state.truncated };\n }\n // The final line break closes the last row; there is no empty row after it.\n const last = text[length - 1];\n if (!(last === '\\n' || last === '\\r') || row.length > 0 || field !== '') pushRow();\n return { grid, truncated: state.truncated };\n}\n\n/**\n * Reads tab-separated (or `delimiter`-separated) text into a table.\n * Returns `null` when there is no non-empty cell.\n */\nexport function parseDelimited(text: string, options: ParseTableOptions = {}): ParsedTable | null {\n if (typeof text !== 'string') throw invalid('`parseDelimited` expects a string.');\n const limits = resolveLimits(options);\n checkLength(text, limits);\n const delimiter = options.delimiter ?? '\\t';\n if (typeof delimiter !== 'string' || delimiter.length !== 1 || delimiter === '\"' || delimiter === '\\r' || delimiter === '\\n') {\n throw invalid('`delimiter` must be one character other than a quote or a line break.');\n }\n if (text === '') return null;\n const { grid, truncated } = splitDelimited(text, delimiter, options.trim ?? false, limits);\n return finish(grid, options.headers === true, 'text', limits, truncated);\n}\n\n/* ------------------------------------------------------------------- HTML */\n\nconst SKIPPED = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT', 'HEAD', 'TITLE', 'OBJECT', 'IFRAME', 'SVG', 'MATH']);\nconst BLOCKS = new Set([\n 'ADDRESS', 'ARTICLE', 'ASIDE', 'BLOCKQUOTE', 'DD', 'DIV', 'DL', 'DT', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'FORM',\n 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HR', 'LI', 'MAIN', 'NAV', 'OL', 'P', 'PRE', 'SECTION', 'TABLE', 'TR', 'UL',\n]);\nconst HARD_BREAK = '\\uE000';\nconst SOFT_BREAK = '\\uE001';\n\nfunction isHidden(element: Element): boolean {\n if (element.hasAttribute('hidden')) return true;\n const style = element.getAttribute('style');\n return style !== null && /(^|;)\\s*display\\s*:\\s*none\\s*(;|$)/i.test(style);\n}\n\nfunction collectText(node: Node, out: string[]): void {\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === 3) {\n out.push((child as Text).data.replace(/[ \\t\\n\\r\\f]+/g, ' '));\n } else if (child.nodeType === 1) {\n const element = child as Element;\n const tag = element.tagName.toUpperCase();\n if (SKIPPED.has(tag) || isHidden(element)) continue;\n if (tag === 'BR') {\n out.push(HARD_BREAK);\n continue;\n }\n const block = BLOCKS.has(tag);\n // Cells of a nested table read as words, not run together.\n const cellLike = tag === 'TD' || tag === 'TH';\n if (block) out.push(SOFT_BREAK);\n else if (cellLike) out.push(' ');\n collectText(element, out);\n if (block) out.push(SOFT_BREAK);\n else if (cellLike) out.push(' ');\n }\n }\n}\n\n/** The text of one cell as it reads on screen: collapsed spaces, `<br>` and blocks as line breaks. */\nfunction cellText(cell: Element): string {\n const parts: string[] = [];\n collectText(cell, parts);\n return parts\n .join('')\n // Spaces from neighbouring elements collapse into one, as a browser renders them.\n .replace(/ {2,}/g, ' ')\n .replace(/ *\\uE001[\\uE001 ]*/g, SOFT_BREAK)\n .replace(/^\\uE001|\\uE001$/g, '')\n .replace(/[\\uE000\\uE001]/g, '\\n')\n .split('\\n')\n .map((line) => line.replace(/^ +| +$/g, '').replace(/\\u00A0/g, ' '))\n .join('\\n')\n .replace(/^\\n+|\\n+$/g, '');\n}\n\nfunction span(cell: Element, name: 'colspan' | 'rowspan', max: number): number {\n const value = Number.parseInt(cell.getAttribute(name) ?? '', 10);\n if (name === 'rowspan' && value === 0) return max;\n return Number.isFinite(value) && value >= 1 ? Math.min(value, max) : 1;\n}\n\nfunction isElement(value: unknown): value is Element {\n return typeof value === 'object' && value !== null && (value as { nodeType?: unknown }).nodeType === 1;\n}\n\nfunction findTable(root: Document | Element): HTMLTableElement | null {\n if (isElement(root) && root.tagName.toUpperCase() === 'TABLE' && (root as HTMLTableElement).rows.length > 0) {\n return root as HTMLTableElement;\n }\n // Document order: an outer table comes before the tables nested in it.\n for (const table of Array.from(root.getElementsByTagName('table'))) {\n if (table.rows.length > 0) return table;\n }\n return null;\n}\n\nfunction readGrid(\n table: HTMLTableElement,\n repeat: boolean,\n limits: Limits,\n): { grid: string[][]; headerRow: boolean; truncated: boolean } {\n const rows = Array.from(table.rows).filter((row) => !isHidden(row));\n const grid: (string | undefined)[][] = [];\n let truncated = rows.length > limits.maxRows;\n const rowLimit = Math.min(rows.length, limits.maxRows);\n // Merged cells can claim far more slots than the markup is long: budget every slot.\n let filled = 0;\n let full = false;\n\n for (let rowIndex = 0; rowIndex < rowLimit && !full; rowIndex++) {\n const row = rows[rowIndex] as HTMLTableRowElement;\n const line = (grid[rowIndex] ??= []);\n let column = 0;\n for (const cell of Array.from(row.cells)) {\n if (isHidden(cell)) continue;\n while (line[column] !== undefined) column++;\n if (column >= limits.maxColumns) {\n truncated = true;\n break;\n }\n const text = cellText(cell);\n const colSpan = span(cell, 'colspan', 1000);\n const rowSpan = span(cell, 'rowspan', rowLimit - rowIndex);\n for (let down = 0; down < rowSpan && !full; down++) {\n const target = (grid[rowIndex + down] ??= []);\n for (let across = 0; across < colSpan && column + across < limits.maxColumns; across++) {\n if (filled >= limits.maxCells) {\n full = true;\n break;\n }\n target[column + across] = down === 0 && across === 0 ? text : repeat ? text : '';\n filled += 1;\n }\n }\n if (full) {\n truncated = true;\n break;\n }\n if (column + colSpan > limits.maxColumns) truncated = true;\n column += colSpan;\n }\n }\n\n const first = rows[0];\n const headerRow =\n first !== undefined &&\n (first.parentElement?.tagName.toUpperCase() === 'THEAD' ||\n (first.cells.length > 0 && Array.from(first.cells).every((cell) => cell.tagName.toUpperCase() === 'TH')));\n return { grid: grid.map((line) => Array.from(line, (cell) => cell ?? '')), headerRow, truncated };\n}\n\nfunction parseHtmlString(html: string): Document | null {\n if (typeof DOMParser === 'undefined') return null;\n return parseInertHtml(html);\n}\n\n/**\n * Reads the first non-empty `<table>` from an HTML string (such as Excel, Google Sheets,\n * Word or a web page put on the clipboard) or from an element, which may be the table or\n * contain it. Merged cells, `<br>` line breaks and hidden rows and cells are handled.\n * Returns `null` without a table, without content, or on a server without `DOMParser`.\n */\nexport function parseHtmlTable(input: string | Element, options: ParseTableOptions = {}): ParsedTable | null {\n const limits = resolveLimits(options);\n let root: Document | Element | null;\n if (typeof input === 'string') {\n checkLength(input, limits);\n if (!/<table[\\s>]/i.test(input)) return null;\n root = parseHtmlString(input);\n } else if (isElement(input)) {\n root = input;\n } else {\n throw invalid('`parseHtmlTable` expects an HTML string or an element.');\n }\n const table = root ? findTable(root) : null;\n if (!table) return null;\n const { grid, headerRow, truncated } = readGrid(table, options.spans === 'repeat', limits);\n const headers = options.headers ?? 'auto';\n return finish(grid, headers === 'auto' ? headerRow : headers, 'html', limits, truncated);\n}\n\n/**\n * Reads a table from pasted content: a `PasteResult` (or any `{ html, text }`), or plain\n * text. The HTML flavour is preferred when it holds a table; otherwise the text is split\n * on tabs. Returns `null` when neither holds any cell content.\n *\n * ```ts\n * usePaste({ accept: ['html', 'text'], onPaste: (result) => setRows(parseTable(result)?.rows ?? []) });\n * ```\n *\n * Throws a `CopyFailure`: `too-large` past `maxLength`, `invalid-payload` for bad options.\n */\nexport function parseTable(source: TableSource, options: ParseTableOptions = {}): ParsedTable | null {\n if (typeof source === 'string') return parseDelimited(source, options);\n const candidate: unknown = source;\n if (typeof candidate !== 'object' || candidate === null) {\n throw invalid('`parseTable` expects a string or an object with `html` and/or `text`.');\n }\n const html = typeof source.html === 'string' ? source.html : null;\n const text = typeof source.text === 'string' ? source.text : null;\n const fromHtml = () => (html === null ? null : parseHtmlTable(html, options));\n const fromText = () => (text === null ? null : parseDelimited(text, options));\n return options.prefer === 'text' ? (fromText() ?? fromHtml()) : (fromHtml() ?? fromText());\n}\n\n/**\n * Reads a rendered `<table>` (or the first table inside `element`) as {@link TableData},\n * ready for `tablePayload`. Works with any library that renders real table markup.\n * Throws `invalid-payload` when there is no table with content.\n */\nexport function fromTableElement(element: Element, options: ParseTableOptions = {}): ParsedTable {\n const table = parseHtmlTable(element, options);\n if (!table) throw invalid('No table with content was found in the element.');\n return table;\n}\n","import { copyFailure } from '../core/errors';\n\n/** How to read one field of a record from a pasted table. */\nexport interface RecordField<Value = string> {\n /**\n * Header text that identifies the column; several for aliases. Matched ignoring case,\n * surrounding and repeated spaces, and full-width characters. Defaults to the key.\n */\n readonly header?: string | readonly string[];\n /** Turns the cell text into a value. Default: the text itself. A throw is reported in `errors`. */\n readonly parse?: (text: string, context: RecordParseContext) => Value;\n /** Report the column in `missing` when the table doesn't have it. Default `false`. */\n readonly required?: boolean;\n}\n\nexport interface RecordParseContext {\n /** Zero-based data row (the header row is not counted). */\n readonly row: number;\n readonly key: string;\n}\n\n/** Field definitions by record key. */\nexport type RecordSchema = Readonly<Record<string, RecordField<unknown>>>;\n\n/** The record a schema produces. A value is `undefined` when its column is missing or its `parse` threw. */\nexport type RecordOf<Schema extends RecordSchema> = {\n -readonly [Key in keyof Schema]: (Schema[Key] extends { readonly parse: (...args: never[]) => infer Value } ? Value : string) | undefined;\n};\n\nexport interface RecordError<Key extends string = string> {\n readonly row: number;\n readonly key: Key;\n readonly text: string;\n readonly cause: unknown;\n}\n\nexport interface RecordsResult<Schema extends RecordSchema> {\n readonly records: RecordOf<Schema>[];\n /** Required fields whose column was not found. */\n readonly missing: (keyof Schema & string)[];\n /** Cells whose `parse` threw. */\n readonly errors: RecordError<keyof Schema & string>[];\n /** `true` when nothing is missing and nothing failed to parse. */\n readonly ok: boolean;\n}\n\nexport interface ToRecordsOptions {\n /**\n * `'header'`: find columns by header text. `'position'`: the schema's key order is the\n * column order. `'auto'` (default): by header when the table has one, else by position.\n */\n readonly match?: 'auto' | 'header' | 'position';\n /** Skip rows whose cells are all empty. Default `true`. */\n readonly skipEmptyRows?: boolean;\n}\n\n/** Any table of strings, such as the result of `parseTable`. */\nexport interface StringTable {\n readonly headers?: readonly string[] | null | undefined;\n readonly rows: readonly (readonly string[])[];\n}\n\nconst normalize = (label: string): string => label.normalize('NFKC').trim().replace(/\\s+/g, ' ').toLowerCase();\n\n/**\n * Maps a pasted table onto typed records, for importing rows from Excel or Google Sheets.\n *\n * ```ts\n * const { records, missing, errors } = toRecords(parseTable(result)!, {\n * email: { header: ['Email', 'E-mail'], required: true },\n * seats: { header: 'Seats', parse: (text) => Number.parseInt(text, 10) },\n * });\n * // records: { email: string | undefined; seats: number | undefined }[]\n * ```\n */\nexport function toRecords<const Schema extends RecordSchema>(\n table: StringTable,\n schema: Schema,\n options: ToRecordsOptions = {},\n): RecordsResult<Schema> {\n const input: unknown = table;\n if (typeof input !== 'object' || input === null || !Array.isArray((input as { rows?: unknown }).rows)) {\n throw copyFailure('invalid-payload', '`toRecords` expects a table with a `rows` array.');\n }\n const keys = Object.keys(schema) as (keyof Schema & string)[];\n if (keys.length === 0) throw copyFailure('invalid-payload', '`toRecords` needs at least one field.');\n\n const headers = Array.isArray(table.headers) ? table.headers : null;\n const match = options.match ?? 'auto';\n const byHeader = match === 'header' || (match === 'auto' && headers !== null);\n if (byHeader && headers === null) {\n throw copyFailure('invalid-payload', 'Matching by header needs a table with headers (`parseTable(…, { headers: true })`).');\n }\n\n const normalizedHeaders = headers?.map((label) => normalize(String(label))) ?? [];\n // A loop, not Math.max(...rows): spreading 100k+ rows overflows the call stack.\n let width = headers?.length ?? 0;\n if (headers === null) for (const row of table.rows) width = Math.max(width, row.length);\n const columnOf = new Map<string, number>();\n const missing: (keyof Schema & string)[] = [];\n keys.forEach((key, position) => {\n const field = schema[key] as RecordField<unknown>;\n let column = -1;\n if (byHeader) {\n const wanted = field.header === undefined ? [key] : typeof field.header === 'string' ? [field.header] : field.header;\n for (const label of wanted) {\n column = normalizedHeaders.indexOf(normalize(label));\n if (column !== -1) break;\n }\n } else {\n column = position;\n }\n if (column === -1 || column >= width) {\n if (field.required === true) missing.push(key);\n } else {\n columnOf.set(key, column);\n }\n });\n\n const skipEmpty = options.skipEmptyRows ?? true;\n const records: RecordOf<Schema>[] = [];\n const errors: RecordError<keyof Schema & string>[] = [];\n table.rows.forEach((row, rowIndex) => {\n if (skipEmpty && row.every((cell) => cell === '')) return;\n const record: Record<string, unknown> = {};\n for (const key of keys) {\n const column = columnOf.get(key);\n if (column === undefined) {\n record[key] = undefined;\n continue;\n }\n const text = row[column] ?? '';\n const parse = (schema[key] as RecordField<unknown>).parse;\n if (!parse) {\n record[key] = text;\n continue;\n }\n try {\n record[key] = parse(text, { row: rowIndex, key });\n } catch (cause) {\n record[key] = undefined;\n errors.push({ row: rowIndex, key, text, cause });\n }\n }\n records.push(record as RecordOf<Schema>);\n });\n\n return { records, missing, errors, ok: missing.length === 0 && errors.length === 0 };\n}\n","import type { TableCell } from './serialize';\n\nfunction isDate(value: unknown): value is Date {\n return value instanceof Date || Object.prototype.toString.call(value) === '[object Date]';\n}\n\nfunction json(value: unknown): string {\n try {\n const encoded = JSON.stringify(value);\n return typeof encoded === 'string' ? encoded : '';\n } catch {\n // Circular structures and BigInt inside objects.\n return Object.prototype.toString.call(value);\n }\n}\n\n/** One list item as text. Nested lists and objects become JSON: no recursion, so cycles are safe. */\nfunction itemText(value: unknown): string {\n if (value === null || value === undefined) return '';\n switch (typeof value) {\n case 'string':\n return value;\n case 'number':\n case 'bigint':\n case 'boolean':\n return String(value);\n case 'function':\n case 'symbol':\n return '';\n }\n if (isDate(value)) return Number.isNaN(value.getTime()) ? '' : value.toISOString();\n return json(value);\n}\n\n/**\n * Turns whatever a grid holds into a cell: primitives and dates as they are, arrays as\n * a comma-separated list, other objects as JSON. Never throws, so one odd value can't\n * break a copy of thousands of rows.\n */\nexport function toCellValue(value: unknown): TableCell {\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'bigint':\n case 'boolean':\n case 'undefined':\n return value;\n case 'function':\n case 'symbol':\n return '';\n }\n if (value === null) return null;\n if (isDate(value)) return Number.isNaN(value.getTime()) ? '' : value;\n if (Array.isArray(value)) return value.map(itemText).join(', ');\n return json(value);\n}\n","import { copyFailure } from '../core/errors';\nimport { toCellValue } from './cell-value';\nimport type { TableCell, TableData } from './serialize';\n\n/*\n * AG Grid support without depending on AG Grid: these interfaces describe only the\n * methods used, so any GridApi from v31 onwards (Community or Enterprise) fits.\n */\n\nexport interface AgGridColumnLike {\n getColId(): string;\n}\n\nexport interface AgGridRowNodeLike {\n /** Position among displayed rows; `null` when filtered out or inside a collapsed group. */\n readonly rowIndex: number | null;\n readonly group?: boolean | undefined;\n}\n\nexport interface AgGridApiLike<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike> {\n getAllDisplayedColumns(): Column[];\n getDisplayNameForColumn(column: Column, location: 'csv'): string;\n getSelectedNodes(): Node[];\n getDisplayedRowCount(): number;\n getDisplayedRowAtIndex(index: number): Node | undefined;\n forEachNodeAfterFilterAndSort(callback: (node: Node, index: number) => void): void;\n forEachNode(callback: (node: Node, index: number) => void): void;\n /** v31.3+. */\n getCellValue?(params: { rowNode: Node; colKey: Column | string; useFormatter?: boolean }): unknown;\n /** v31–v32; removed in v33. */\n getValue?(colKey: Column | string, rowNode: Node): unknown;\n}\n\nexport interface FromAgGridOptions<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike> {\n /**\n * Which rows, in on-screen order:\n * - `'displayed'` (default): every row the grid displays after filtering, sorting and\n * grouping, across all pages.\n * - `'selected'`: selected rows that are currently displayed.\n * - `'filtered'`: rows passing the filter, in sort order, including those inside\n * collapsed groups.\n * - `'all'`: every row, in the order of your data.\n * - an array of row nodes, taken as given.\n */\n readonly rows?: 'displayed' | 'selected' | 'filtered' | 'all' | readonly Node[];\n /** Column ids to copy, in this order. Default: the displayed columns, minus the selection and row-number columns. */\n readonly columns?: readonly string[];\n /**\n * - `'auto'` (default): numbers, bigints and booleans raw, so spreadsheets can calculate\n * with them; everything else as the grid's `valueFormatter` shows it.\n * - `'raw'`: the underlying values. `'formatted'`: exactly what the grid shows.\n */\n readonly values?: 'auto' | 'raw' | 'formatted';\n /** Include group rows (Enterprise row grouping). Default `false`: only rows with data. */\n readonly includeGroupRows?: boolean;\n /** Header text for a column. Default: the grid's own name for exports. */\n readonly header?: (column: Column) => string;\n}\n\n/** Ids of AG Grid's own utility columns, which hold no data. */\nconst UTILITY_COLUMNS = new Set(['ag-Grid-SelectionColumn', 'ag-Grid-RowNumbersColumn']);\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction collectRows<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike>(\n api: AgGridApiLike<Node, Column>,\n rows: NonNullable<FromAgGridOptions<Node, Column>['rows']>,\n): Node[] {\n if (typeof rows !== 'string') {\n const list: unknown = rows;\n if (!Array.isArray(list)) throw invalid('`rows` must be \"displayed\", \"selected\", \"filtered\", \"all\" or an array of row nodes.');\n return [...rows];\n }\n const nodes: Node[] = [];\n switch (rows) {\n case 'displayed': {\n const count = api.getDisplayedRowCount();\n for (let index = 0; index < count; index++) {\n const node = api.getDisplayedRowAtIndex(index);\n if (node) nodes.push(node);\n }\n return nodes;\n }\n case 'selected':\n // Selection order is click order; copy in the order the rows appear instead.\n return api\n .getSelectedNodes()\n .filter((node): node is Node & { rowIndex: number } => node.rowIndex !== null)\n .sort((a, b) => a.rowIndex - b.rowIndex);\n case 'filtered':\n api.forEachNodeAfterFilterAndSort((node) => nodes.push(node));\n return nodes;\n case 'all':\n api.forEachNode((node) => nodes.push(node));\n return nodes;\n default:\n throw invalid(`Unknown \\`rows\\` option: ${JSON.stringify(rows)}.`);\n }\n}\n\n/**\n * Reads rows from an AG Grid (v31+, Community or Enterprise) as table data.\n *\n * ```ts\n * copy(() => tablePayload(fromAgGrid(gridRef.current!.api, { rows: 'selected' })));\n * ```\n *\n * Gives Community grids Excel-ready copy, which AG Grid only ships in Enterprise.\n */\nexport function fromAgGrid<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike>(\n api: AgGridApiLike<Node, Column>,\n options: FromAgGridOptions<Node, Column> = {},\n): TableData {\n const candidate: unknown = api;\n if (typeof candidate !== 'object' || candidate === null || typeof api.getAllDisplayedColumns !== 'function') {\n throw invalid('`fromAgGrid` expects an AG Grid API (v31 or later): `gridRef.current.api` or the API from `onGridReady`.');\n }\n\n const read: (node: Node, column: Column, useFormatter: boolean) => unknown =\n typeof api.getCellValue === 'function'\n ? (node, column, useFormatter) => api.getCellValue?.({ rowNode: node, colKey: column, useFormatter })\n : typeof api.getValue === 'function'\n ? (node, column) => api.getValue?.(column, node)\n : () => {\n throw invalid('This grid API has neither `getCellValue` nor `getValue`; AG Grid v31 or later is required.');\n };\n\n const displayed = api.getAllDisplayedColumns();\n let columns: Column[];\n if (options.columns) {\n const byId = new Map(displayed.map((column) => [column.getColId(), column]));\n columns = options.columns.map((id) => {\n const column = byId.get(id);\n if (!column) throw invalid(`Column \"${id}\" is not displayed in the grid.`);\n return column;\n });\n } else {\n columns = displayed.filter((column) => !UTILITY_COLUMNS.has(column.getColId()));\n }\n\n const values = options.values ?? 'auto';\n const cell = (node: Node, column: Column): TableCell => {\n if (values === 'formatted') return toCellValue(read(node, column, true));\n const raw = read(node, column, false);\n if (values === 'raw') return toCellValue(raw);\n const type = typeof raw;\n return type === 'number' || type === 'bigint' || type === 'boolean' ? toCellValue(raw) : toCellValue(read(node, column, true));\n };\n\n const includeGroups = options.includeGroupRows ?? false;\n const nodes = collectRows(api, options.rows ?? 'displayed').filter((node) => includeGroups || node.group !== true);\n\n return {\n headers: columns.map((column) => options.header?.(column) ?? api.getDisplayNameForColumn(column, 'csv')),\n rows: nodes.map((node) => columns.map((column) => cell(node, column))),\n };\n}\n","import { copyFailure } from '../core/errors';\nimport { toCellValue } from './cell-value';\nimport type { TableCell, TableData } from './serialize';\n\n/*\n * TanStack Table support without depending on it: only the methods used are described,\n * so tables from v8 and v9, in any framework adapter (React, Vue, Solid, Svelte,\n * Angular, Lit), and libraries built on it such as Material React Table and Mantine\n * React Table, all fit.\n */\n\nexport interface TanStackColumnLike {\n readonly id: string;\n readonly columnDef: { readonly header?: unknown };\n /** Absent on display columns (checkboxes, actions), which hold no data. */\n readonly accessorFn?: unknown;\n}\n\nexport interface TanStackRowLike {\n getValue(columnId: string): unknown;\n /** Present when the row selection feature is enabled. */\n getIsSelected?: () => boolean;\n}\n\nexport interface TanStackTableLike<Row extends TanStackRowLike, Column extends TanStackColumnLike> {\n getRowModel(): { readonly rows: readonly Row[] };\n getAllLeafColumns(): readonly Column[];\n /** Present when the column visibility feature is enabled (always in v8). */\n getVisibleLeafColumns?: () => readonly Column[];\n}\n\nexport interface FromTanStackTableOptions<Row extends TanStackRowLike, Column extends TanStackColumnLike> {\n /**\n * - `'visible'` (default): the rows the table renders now (`getRowModel()`): filtered,\n * sorted, grouped and paginated.\n * - `'selected'`: those of them that are selected.\n * - an array of rows, such as `table.getPrePaginationRowModel().rows` for every page.\n */\n readonly rows?: 'visible' | 'selected' | readonly Row[];\n /** Column ids to copy, in this order. Default: visible leaf columns that hold data. */\n readonly columns?: readonly string[];\n /** Header text for a column. Default: `columnDef.header` when it is a string, else the column id. */\n readonly header?: (column: Column) => string;\n /** The cell for a row and column. Default: `row.getValue(column.id)`. */\n readonly value?: (row: Row, column: Column) => TableCell;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/**\n * Reads rows from a TanStack Table instance (v8 or v9) as table data.\n *\n * ```ts\n * copy(() => tablePayload(fromTanStackTable(table, { rows: 'selected' })));\n * ```\n */\nexport function fromTanStackTable<Row extends TanStackRowLike, Column extends TanStackColumnLike>(\n table: TanStackTableLike<Row, Column>,\n options: FromTanStackTableOptions<Row, Column> = {},\n): TableData {\n const candidate: unknown = table;\n if (typeof candidate !== 'object' || candidate === null || typeof table.getRowModel !== 'function') {\n throw invalid('`fromTanStackTable` expects a TanStack Table instance (v8 or v9).');\n }\n\n const all = table.getAllLeafColumns();\n let columns: readonly Column[];\n if (options.columns) {\n const byId = new Map(all.map((column) => [column.id, column]));\n columns = options.columns.map((id) => {\n const column = byId.get(id);\n if (!column) throw invalid(`Column \"${id}\" does not exist in the table.`);\n return column;\n });\n } else {\n const visible = typeof table.getVisibleLeafColumns === 'function' ? table.getVisibleLeafColumns() : all;\n columns = visible.filter((column) => column.accessorFn !== undefined);\n }\n\n const selection = options.rows ?? 'visible';\n let rows: readonly Row[];\n if (selection === 'visible' || selection === 'selected') {\n rows = table.getRowModel().rows;\n if (selection === 'selected') {\n rows = rows.filter((row) => {\n if (typeof row.getIsSelected !== 'function') {\n throw invalid('Row selection is not enabled on this table: register the row selection feature, or pass `rows`.');\n }\n return row.getIsSelected();\n });\n }\n } else if (Array.isArray(selection)) {\n rows = selection;\n } else {\n throw invalid('`rows` must be \"visible\", \"selected\" or an array of rows.');\n }\n\n const header = (column: Column): string => {\n if (options.header) return options.header(column);\n const label = column.columnDef.header;\n return typeof label === 'string' ? label : column.id;\n };\n const value = options.value ?? ((row: Row, column: Column) => toCellValue(row.getValue(column.id)));\n\n return {\n headers: columns.map(header),\n rows: rows.map((row) => columns.map((column) => value(row, column))),\n };\n}\n"],"mappings":";;;;AAsEA,MAAa,0BAA0B;AAkBvC,MAAM,gBAAgB;AACtB,MAAM,cAAc;AACpB,MAAM,QAAsB;CAAE,MAAM;CAAI,MAAM;AAAO;AAErD,MAAMA,aAAW,YAAoB,YAAY,mBAAmB,OAAO;;AAG3E,SAAS,SAAS,OAAwB;CACxC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,OAAO,UAAU,WAAW,OAAO,UAAU,SAAS,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,OAAO;AACjG;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,OAAO,OAA6C;CAC3D,OAAO,MAAM,QAAQ,KAAK;AAC5B;AAEA,SAASC,SAAO,OAA+B;CAC7C,OAAO,iBAAiB,QAAQ,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AAC5E;AAEA,SAAS,aAAa,OAA2B,UAAkB,MAAsB;CACvF,IAAI,UAAU,KAAA,GAAW,OAAO;CA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SAAS,OAAO,EAAE,CAAC;CAEjG,OAAO;EACL,SAAS,QAAQ,IAAI,MAAM;EAC3B,MAAM,KAAK,KAAK,QAAQ,QAAQ,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAAC;CACrE;AACF"}
|
|
1
|
+
{"version":3,"file":"table.js","names":["invalid","isDate","invalid","invalid"],"sources":["../src/table/serialize.ts","../src/table/parse.ts","../src/table/records.ts","../src/table/cell-value.ts","../src/table/ag-grid.ts","../src/table/tanstack.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\nimport type { HtmlPayload, TextPayload } from '../core/payload';\n\n/* ------------------------------------------------------------------ Types */\n\n/**\n * What a table cell may hold. Numbers, bigints, booleans and dates stay typed\n * all the way to the spreadsheet; strings are kept as text.\n */\nexport type TableCell = string | number | bigint | boolean | Date | null | undefined;\n\n/** One row of cells, left to right. */\nexport type TableRow = readonly TableCell[];\n\n/**\n * A table as plain data: optional header labels and rows of cells.\n * Every helper in this module produces or consumes this shape, so the output of\n * `fromRows`, `fromAgGrid`, `fromTanStackTable` and `parseTable` can all be\n * copied with {@link tablePayload}.\n */\nexport interface TableData {\n readonly headers?: readonly string[] | null | undefined;\n readonly rows: readonly TableRow[];\n}\n\n/** Where a cell sits, passed to `formatCell`. Indexes are zero-based; `row` is -1 for the header row. */\nexport interface CellFormatContext {\n readonly row: number;\n readonly column: number;\n readonly header: string | undefined;\n}\n\nexport interface TableFormatOptions {\n /** Include the header row when the data has headers. Default `true`. */\n readonly headers?: boolean;\n /**\n * Neutralise text cells that a spreadsheet would run as a formula: those starting\n * with `=`, `+`, `-`, `@`, a tab or a line break (and their full-width forms), as\n * listed by OWASP's CSV Injection guidance. They get a leading `'`, which\n * spreadsheets treat as \"this is text\". Typed numbers are never touched, so\n * `-5` as a number stays a number. Default `true`; turn off only for trusted data.\n */\n readonly formulaGuard?: boolean;\n /**\n * Mark string cells as text in the HTML flavour (`mso-number-format:\"\\@\"`), so\n * Excel keeps `00123`, `1/2` or `1E5` exactly as written instead of converting them.\n * Typed numbers, booleans and dates are left for the spreadsheet to recognise.\n * Default `true`.\n */\n readonly preserveText?: boolean;\n /**\n * Custom text for a cell. Return `undefined` to use the default. The result is\n * still escaped, and guarded when the original value was text.\n * Defaults: `null`/`undefined` → empty, `Date` → ISO 8601 (invalid dates → empty),\n * everything else → `String(value)`.\n */\n readonly formatCell?: (value: TableCell, context: CellFormatContext) => string | undefined;\n /** Upper bound on cells (header included), checked before any work. Default 1,000,000. */\n readonly maxCells?: number;\n}\n\nexport interface TablePayloadOptions extends TableFormatOptions {\n /**\n * `'html'` (default): an HTML table plus a tab-separated plain-text fallback, which\n * degrades to the plain text where rich copy is unavailable.\n * `'text'`: tab-separated text only.\n */\n readonly format?: 'html' | 'text';\n}\n\nexport const DEFAULT_TABLE_MAX_CELLS = 1_000_000;\n\n/* --------------------------------------------------------------- Prepare */\n\n/** `text`: written as typed by a person. `value`: a number, bigint, boolean or date. */\ntype CellKind = 'text' | 'value';\n\ninterface PreparedCell {\n readonly text: string;\n readonly kind: CellKind;\n}\n\ninterface PreparedTable {\n readonly header: readonly PreparedCell[] | null;\n readonly body: readonly (readonly PreparedCell[])[];\n}\n\n// OWASP CSV Injection: = + - @ tab CR LF, and the full-width = + - @.\nconst FORMULA_START = /^[=+\\-@\\t\\r\\n=+-@]/;\nconst LINE_BREAKS = /\\r\\n?/g;\nconst EMPTY: PreparedCell = { text: '', kind: 'text' };\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/** Only called for values that are not null, undefined or a cell. */\nfunction typeName(value: unknown): string {\n if (Array.isArray(value)) return 'array';\n return typeof value === 'object' ? Object.prototype.toString.call(value).slice(8, -1) : typeof value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isList(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\nfunction isDate(value: unknown): value is Date {\n return value instanceof Date || Object.prototype.toString.call(value) === '[object Date]';\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw invalid(`\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\nfunction defaultText(value: unknown, where: string): { text: string; kind: CellKind } {\n if (value === null || value === undefined) return { text: '', kind: 'text' };\n switch (typeof value) {\n case 'string':\n return { text: value, kind: 'text' };\n case 'number':\n case 'bigint':\n case 'boolean':\n return { text: String(value), kind: 'value' };\n default:\n if (isDate(value)) {\n const time = value.getTime();\n return { text: Number.isNaN(time) ? '' : value.toISOString(), kind: 'value' };\n }\n throw invalid(\n `${where} is ${typeName(value)}, which has no text form. ` +\n 'Pass a string, number, bigint, boolean, Date, null or undefined, or convert it with `formatCell`.',\n );\n }\n}\n\nfunction prepare(data: TableData, options: TableFormatOptions): PreparedTable {\n // Validated as `unknown`: plain-JS callers and runtime data reach this too.\n const input: unknown = data;\n if (!isRecord(input) || !isList(input['rows'])) {\n throw invalid('Table data must be an object with a `rows` array.');\n }\n const rawHeaders = input['headers'];\n if (rawHeaders !== undefined && rawHeaders !== null && !isList(rawHeaders)) {\n throw invalid('`headers` must be an array of strings, null or undefined.');\n }\n const headers: readonly unknown[] | null = options.headers === false ? null : (rawHeaders ?? null);\n const rows: readonly unknown[] = input['rows'];\n\n let width = headers?.length ?? 0;\n const lines: (readonly unknown[])[] = [];\n for (const [index, row] of rows.entries()) {\n if (!isList(row)) throw invalid(`Row ${String(index + 1)} is not an array of cells.`);\n width = Math.max(width, row.length);\n lines.push(row);\n }\n if (width === 0) throw invalid('The table has no cells to copy.');\n\n const maxCells = resolveLimit(options.maxCells, DEFAULT_TABLE_MAX_CELLS, 'maxCells');\n const cellCount = (rows.length + (headers ? 1 : 0)) * width;\n if (cellCount > maxCells) {\n throw copyFailure(\n 'too-large',\n `The table has ${String(cellCount)} cells, over the limit of ${String(maxCells)}. Raise \\`maxCells\\` or copy fewer rows.`,\n );\n }\n\n const guard = options.formulaGuard ?? true;\n const formatCell = options.formatCell;\n\n const label = (column: number): string | undefined => {\n const value = headers?.[column];\n return typeof value === 'string' ? value : undefined;\n };\n\n const cell = (value: unknown, row: number, column: number): PreparedCell => {\n const where = row < 0 ? `Header ${String(column + 1)}` : `Cell at row ${String(row + 1)}, column ${String(column + 1)}`;\n const base = defaultText(value, where);\n let text = base.text;\n if (formatCell) {\n // `defaultText` has accepted the value, so it is a valid cell.\n const custom: unknown = formatCell(value as TableCell, { row, column, header: label(column) });\n if (custom !== undefined) {\n if (typeof custom !== 'string') throw invalid(`\\`formatCell\\` must return a string or undefined (${where}).`);\n text = custom;\n }\n }\n text = text.replace(LINE_BREAKS, '\\n');\n if (guard && base.kind === 'text' && FORMULA_START.test(text)) text = `'${text}`;\n return text === '' ? EMPTY : { text, kind: base.kind };\n };\n\n const header = headers\n ? Array.from({ length: width }, (_, column) => {\n const value = headers[column];\n if (value !== undefined && value !== null && typeof value !== 'string') {\n throw invalid(`Header ${String(column + 1)} must be a string (received ${typeName(value)}).`);\n }\n return cell(value ?? '', -1, column);\n })\n : null;\n\n const body = lines.map((row, rowIndex) => Array.from({ length: width }, (_, column) => cell(row[column], rowIndex, column)));\n\n return { header, body };\n}\n\n/* ----------------------------------------------------------------- Writers */\n\nconst NEEDS_QUOTES = /[\\t\\n\\r\"]/;\n\nfunction tsvField(text: string): string {\n return NEEDS_QUOTES.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text;\n}\n\nfunction toTsv(table: PreparedTable): string {\n const lines = table.header ? [table.header, ...table.body] : table.body;\n // Rows end in CRLF, as Excel writes them; line breaks inside a cell stay LF.\n const text = lines.map((row) => row.map((cell) => tsvField(cell.text)).join('\\t')).join('\\r\\n');\n // A one-column table ending in an empty cell would end in a bare line break, which\n // readers drop as the trailing newline. A quoted empty field keeps that last row.\n const last = lines.at(-1);\n return lines.length > 1 && last?.length === 1 && last[0]?.text === '' ? `${text}\"\"` : text;\n}\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = { '&': '&', '<': '<', '>': '>', '\"': '"' };\n\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"]/g, (char) => HTML_ESCAPES[char] as string);\n}\n\n// Whitespace HTML would otherwise collapse: leading, trailing, doubled, or tabs.\nconst SIGNIFICANT_SPACE = /^\\s|\\s$| {2}|\\t/;\n\nfunction htmlCell(tag: 'th' | 'td', cell: PreparedCell, preserveText: boolean): string {\n const styles: string[] = [];\n if (preserveText && cell.kind === 'text' && cell.text !== '') styles.push(\"mso-number-format:'\\\\@'\");\n if (SIGNIFICANT_SPACE.test(cell.text)) styles.push('white-space:pre-wrap');\n const style = styles.length > 0 ? ` style=\"${styles.join(';')}\"` : '';\n return `<${tag}${style}>${escapeHtml(cell.text).replace(/\\n/g, '<br>')}</${tag}>`;\n}\n\nfunction toHtml(table: PreparedTable, preserveText: boolean): string {\n const row = (cells: readonly PreparedCell[], tag: 'th' | 'td') =>\n `<tr>${cells.map((cell) => htmlCell(tag, cell, preserveText)).join('')}</tr>`;\n const head = table.header ? `<thead>${row(table.header, 'th')}</thead>` : '';\n return `<table>${head}<tbody>${table.body.map((cells) => row(cells, 'td')).join('')}</tbody></table>`;\n}\n\n/** `prepare` guarantees at least one line of at least one cell. */\nfunction hasContent(table: PreparedTable): boolean {\n const lines = table.header ? [table.header, ...table.body] : table.body;\n const first = lines[0] as readonly PreparedCell[];\n return lines.length > 1 || first.length > 1 || (first[0] as PreparedCell).text !== '';\n}\n\n/* -------------------------------------------------------------- Public API */\n\n/**\n * Tab-separated text, the format Excel, Google Sheets, Numbers and LibreOffice paste\n * straight into cells. Cells containing tabs, line breaks or quotes are quoted the\n * way Excel quotes them. Throws a `CopyFailure` (`invalid-payload` or `too-large`).\n */\nexport function tableToTsv(data: TableData, options: TableFormatOptions = {}): string {\n return toTsv(prepare(data, options));\n}\n\n/** An HTML `<table>`: what rich editors (Docs, Word, Notion, mail) and spreadsheets read first. */\nexport function tableToHtml(data: TableData, options: TableFormatOptions = {}): string {\n return toHtml(prepare(data, options), options.preserveText ?? true);\n}\n\n/**\n * A copy payload for a table, ready for `copy()`, `useCopyInterceptor` or `useDragCopy`.\n *\n * ```ts\n * copy(() => tablePayload(fromRows(invoices, columns)));\n * ```\n *\n * The default `html` format carries the HTML table and the tab-separated text in one\n * clipboard entry. Throws a `CopyFailure` for bad input; inside a `copy()` source that\n * becomes the copy's classified error.\n */\nexport function tablePayload(data: TableData, options: TablePayloadOptions & { readonly format: 'text' }): TextPayload;\nexport function tablePayload(data: TableData, options?: TablePayloadOptions & { readonly format?: 'html' }): HtmlPayload;\nexport function tablePayload(data: TableData, options?: TablePayloadOptions): HtmlPayload | TextPayload;\nexport function tablePayload(data: TableData, options: TablePayloadOptions = {}): HtmlPayload | TextPayload {\n const format: unknown = options.format ?? 'html';\n if (format !== 'html' && format !== 'text') {\n throw invalid(`\\`format\\` must be \"html\" or \"text\" (received ${JSON.stringify(format)}).`);\n }\n const table = prepare(data, options);\n if (!hasContent(table)) throw invalid('The table only contains one empty cell; there is nothing to copy.');\n const text = toTsv(table);\n return format === 'text' ? { kind: 'text', value: text } : { kind: 'html', html: toHtml(table, options.preserveText ?? true), text };\n}\n\n/* ------------------------------------------------------------------ Rows */\n\n/** Keys of `Row` whose values are valid cells. */\nexport type CellKey<Row> = {\n [K in keyof Row]-?: Row[K] extends TableCell ? K : never;\n}[keyof Row] &\n string;\n\n/** One output column for {@link fromRows}: a header and how to read the cell. */\nexport interface TableColumn<Row> {\n readonly header: string;\n /** A property of the row, or a function returning the cell. */\n readonly value: CellKey<Row> | ((row: Row, index: number) => TableCell);\n}\n\n/**\n * Turns your own row objects into {@link TableData}, choosing and ordering columns.\n *\n * ```ts\n * fromRows(users, [\n * { header: 'Name', value: 'name' },\n * { header: 'Joined', value: (user) => user.joinedAt },\n * ]);\n * ```\n */\nexport function fromRows<Row>(rows: readonly Row[], columns: readonly TableColumn<Row>[]): TableData {\n const rowList: unknown = rows;\n const columnList: unknown = columns;\n if (!isList(rowList)) throw invalid('`fromRows` expects an array of rows.');\n if (!isList(columnList) || columnList.length === 0) throw invalid('`fromRows` needs at least one column.');\n const headers: string[] = [];\n const readers = columnList.map((column, index): ((row: Row, index: number) => unknown) => {\n if (!isRecord(column) || typeof column['header'] !== 'string') {\n throw invalid(`Column ${String(index + 1)} needs a string \\`header\\`.`);\n }\n const header = column['header'];\n headers.push(header);\n const value = column['value'];\n if (typeof value === 'function') return value as (row: Row, index: number) => unknown;\n if (typeof value === 'string') return (row: Row) => (isRecord(row) ? row[value] : undefined);\n throw invalid(`Column \"${header}\" needs a \\`value\\`: a property name or a function.`);\n });\n // Cells are checked when the table is serialised, with their row and column in the message.\n return {\n headers,\n rows: rows.map((row, index) => readers.map((read) => read(row, index) as TableCell)),\n };\n}\n","import { copyFailure } from '../core/errors';\nimport type { TableData } from './serialize';\nimport { parseInertHtml } from '../core/inert-html';\n\n/* ------------------------------------------------------------------ Types */\n\n/** A table read from pasted or dropped content. Every cell is a string. */\nexport interface ParsedTable extends TableData {\n /** The header row, when one was detected or requested; otherwise `null`. */\n readonly headers: readonly string[] | null;\n /** Data rows, all padded to `columnCount`. */\n readonly rows: readonly (readonly string[])[];\n readonly columnCount: number;\n /** Which clipboard flavour the table came from. */\n readonly source: 'html' | 'text';\n /** `true` when rows or columns were dropped to stay within the limits. Never silent. */\n readonly truncated: boolean;\n}\n\nexport interface ParseTableOptions {\n /**\n * `'auto'` (default): an HTML table's first row is the header when it sits in\n * `<thead>` or is made of `<th>` cells; plain text has no header.\n * `true`: the first row is always the header. `false`: never.\n */\n readonly headers?: 'auto' | boolean;\n /** Which flavour to read when both are present. Default `'html'`, which keeps merged cells and line breaks exact. */\n readonly prefer?: 'html' | 'text';\n /** Column separator for plain text. Default tab, what spreadsheets put on the clipboard. */\n readonly delimiter?: string;\n /** Merged cells: `'empty'` (default) fills the covered cells with `''`, as spreadsheets do; `'repeat'` copies the value. */\n readonly spans?: 'empty' | 'repeat';\n /** Trim spaces around plain-text cells. HTML cells are always normalised. Default `false`. */\n readonly trim?: boolean;\n /** Most rows kept (header included). Default 100,000. Extra rows set `truncated`. */\n readonly maxRows?: number;\n /** Most columns kept. Default 16,384, Excel's own limit. Extra columns set `truncated`. */\n readonly maxColumns?: number;\n /** Most cells kept. Default 1,000,000. */\n readonly maxCells?: number;\n /** Longest input read, in characters. Default 32 MiB. Longer input fails with `too-large`. */\n readonly maxLength?: number;\n}\n\n/** Plain text, or anything with `html` and `text`, such as a `PasteResult`. */\nexport type TableSource =\n | string\n | { readonly html?: string | null | undefined; readonly text?: string | null | undefined };\n\nexport const DEFAULT_PARSE_MAX_ROWS = 100_000;\nexport const DEFAULT_PARSE_MAX_COLUMNS = 16_384;\nexport const DEFAULT_PARSE_MAX_CELLS = 1_000_000;\nexport const DEFAULT_PARSE_MAX_LENGTH: number = 32 * 1024 * 1024;\n\n/* ---------------------------------------------------------------- Options */\n\ninterface Limits {\n readonly maxRows: number;\n readonly maxColumns: number;\n readonly maxCells: number;\n readonly maxLength: number;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction limit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw invalid(`\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\nfunction resolveLimits(options: ParseTableOptions): Limits {\n return {\n maxRows: limit(options.maxRows, DEFAULT_PARSE_MAX_ROWS, 'maxRows'),\n maxColumns: limit(options.maxColumns, DEFAULT_PARSE_MAX_COLUMNS, 'maxColumns'),\n maxCells: limit(options.maxCells, DEFAULT_PARSE_MAX_CELLS, 'maxCells'),\n maxLength: limit(options.maxLength, DEFAULT_PARSE_MAX_LENGTH, 'maxLength'),\n };\n}\n\nfunction checkLength(input: string, limits: Limits): void {\n if (input.length > limits.maxLength) {\n throw copyFailure(\n 'too-large',\n `The pasted content is ${String(input.length)} characters, over the limit of ${String(limits.maxLength)}.`,\n );\n }\n}\n\n/* ---------------------------------------------------------------- Shaping */\n\n/**\n * Applies the row, column and cell limits, pads ragged rows, splits off the header\n * and drops tables without a single non-empty cell.\n */\nfunction finish(\n grid: readonly (readonly string[])[],\n firstRowIsHeader: boolean,\n source: 'html' | 'text',\n limits: Limits,\n alreadyTruncated: boolean,\n): ParsedTable | null {\n let truncated = alreadyTruncated;\n // Both readers already stop at maxColumns, so the widest row is within it.\n let columnCount = 0;\n for (const row of grid) columnCount = Math.max(columnCount, row.length);\n let rowCount = Math.min(grid.length, limits.maxRows);\n if (columnCount > 0) rowCount = Math.min(rowCount, Math.floor(limits.maxCells / columnCount));\n if (rowCount < grid.length) truncated = true;\n\n const shaped: string[][] = [];\n let anyContent = false;\n for (let index = 0; index < rowCount; index++) {\n const row = grid[index] as readonly string[];\n const cells = Array.from({ length: columnCount }, (_, column) => row[column] ?? '');\n if (!anyContent && cells.some((cell) => cell !== '')) anyContent = true;\n shaped.push(cells);\n }\n if (!anyContent) return null;\n\n // `anyContent` means there is at least one row to take the header from.\n const headers = firstRowIsHeader ? (shaped.shift() as string[]) : null;\n return { headers, rows: shaped, columnCount, source, truncated };\n}\n\n/* ------------------------------------------------------------- Plain text */\n\n/**\n * Splits tab-separated text the way spreadsheets write it: a field that starts with\n * `\"` is quoted (`\"\"` is a literal quote) and may contain tabs and line breaks; rows\n * end in CRLF, LF or CR; the trailing line break spreadsheets add is ignored. A quote\n * that never closes is read as an ordinary character, as Excel does.\n */\nfunction splitDelimited(text: string, delimiter: string, trim: boolean, limits: Limits): { grid: string[][]; truncated: boolean } {\n const grid: string[][] = [];\n const length = text.length;\n let row: string[] = [];\n let field = '';\n let index = 0;\n let fieldStart = true;\n // After one unterminated quote, every later quote is literal too: this keeps the\n // scan linear on hostile input instead of re-reading to the end for each quote.\n let quoting = true;\n let cells = 0;\n const state = { full: false, truncated: false };\n\n const pushField = () => {\n if (row.length >= limits.maxColumns) state.truncated = true;\n else if (cells >= limits.maxCells) state.full = true;\n else {\n row.push(trim ? field.trim() : field);\n cells += 1;\n }\n field = '';\n fieldStart = true;\n };\n const pushRow = () => {\n pushField();\n grid.push(row);\n row = [];\n if (grid.length >= limits.maxRows) state.full = true;\n };\n\n while (index < length && !state.full) {\n const char = text[index] as string;\n\n if (fieldStart && quoting && char === '\"') {\n let value = '';\n let cursor = index + 1;\n let closed = false;\n while (cursor < length) {\n const inner = text[cursor] as string;\n if (inner === '\"') {\n if (text[cursor + 1] === '\"') {\n value += '\"';\n cursor += 2;\n continue;\n }\n closed = true;\n cursor += 1;\n break;\n }\n value += inner;\n cursor += 1;\n }\n if (!closed) {\n quoting = false; // Read this quote, and any later one, as a plain character.\n continue;\n }\n // Anything between the closing quote and the next separator is kept, as Excel does.\n field = value;\n fieldStart = false;\n index = cursor;\n continue;\n }\n\n if (char === delimiter) {\n pushField();\n index += 1;\n } else if (char === '\\r' || char === '\\n') {\n pushRow();\n index += char === '\\r' && text[index + 1] === '\\n' ? 2 : 1;\n } else {\n field += char;\n fieldStart = false;\n index += 1;\n }\n }\n\n if (state.full) {\n // Stopped early: say so when anything but a final line break was left unread.\n if (index < length && !/^(\\r\\n|\\r|\\n)$/.test(text.slice(index))) state.truncated = true;\n return { grid, truncated: state.truncated };\n }\n // The final line break closes the last row; there is no empty row after it.\n const last = text[length - 1];\n if (!(last === '\\n' || last === '\\r') || row.length > 0 || field !== '') pushRow();\n return { grid, truncated: state.truncated };\n}\n\n/**\n * Reads tab-separated (or `delimiter`-separated) text into a table.\n * Returns `null` when there is no non-empty cell.\n */\nexport function parseDelimited(text: string, options: ParseTableOptions = {}): ParsedTable | null {\n if (typeof text !== 'string') throw invalid('`parseDelimited` expects a string.');\n const limits = resolveLimits(options);\n checkLength(text, limits);\n const delimiter = options.delimiter ?? '\\t';\n if (typeof delimiter !== 'string' || delimiter.length !== 1 || delimiter === '\"' || delimiter === '\\r' || delimiter === '\\n') {\n throw invalid('`delimiter` must be one character other than a quote or a line break.');\n }\n if (text === '') return null;\n const { grid, truncated } = splitDelimited(text, delimiter, options.trim ?? false, limits);\n return finish(grid, options.headers === true, 'text', limits, truncated);\n}\n\n/* ------------------------------------------------------------------- HTML */\n\nconst SKIPPED = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT', 'HEAD', 'TITLE', 'OBJECT', 'IFRAME', 'SVG', 'MATH']);\nconst BLOCKS = new Set([\n 'ADDRESS', 'ARTICLE', 'ASIDE', 'BLOCKQUOTE', 'DD', 'DIV', 'DL', 'DT', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'FORM',\n 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HR', 'LI', 'MAIN', 'NAV', 'OL', 'P', 'PRE', 'SECTION', 'TABLE', 'TR', 'UL',\n]);\nconst HARD_BREAK = '\\uE000';\nconst SOFT_BREAK = '\\uE001';\n\nfunction isHidden(element: Element): boolean {\n if (element.hasAttribute('hidden')) return true;\n const style = element.getAttribute('style');\n return style !== null && /(^|;)\\s*display\\s*:\\s*none\\s*(;|$)/i.test(style);\n}\n\nfunction collectText(node: Node, out: string[]): void {\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === 3) {\n out.push((child as Text).data.replace(/[ \\t\\n\\r\\f]+/g, ' '));\n } else if (child.nodeType === 1) {\n const element = child as Element;\n const tag = element.tagName.toUpperCase();\n if (SKIPPED.has(tag) || isHidden(element)) continue;\n if (tag === 'BR') {\n out.push(HARD_BREAK);\n continue;\n }\n const block = BLOCKS.has(tag);\n // Cells of a nested table read as words, not run together.\n const cellLike = tag === 'TD' || tag === 'TH';\n if (block) out.push(SOFT_BREAK);\n else if (cellLike) out.push(' ');\n collectText(element, out);\n if (block) out.push(SOFT_BREAK);\n else if (cellLike) out.push(' ');\n }\n }\n}\n\n/** The text of one cell as it reads on screen: collapsed spaces, `<br>` and blocks as line breaks. */\nfunction cellText(cell: Element): string {\n const parts: string[] = [];\n collectText(cell, parts);\n return parts\n .join('')\n // Spaces from neighbouring elements collapse into one, as a browser renders them.\n .replace(/ {2,}/g, ' ')\n .replace(/ *\\uE001[\\uE001 ]*/g, SOFT_BREAK)\n .replace(/^\\uE001|\\uE001$/g, '')\n .replace(/[\\uE000\\uE001]/g, '\\n')\n .split('\\n')\n .map((line) => line.replace(/^ +| +$/g, '').replace(/\\u00A0/g, ' '))\n .join('\\n')\n .replace(/^\\n+|\\n+$/g, '');\n}\n\nfunction span(cell: Element, name: 'colspan' | 'rowspan', max: number): number {\n const value = Number.parseInt(cell.getAttribute(name) ?? '', 10);\n if (name === 'rowspan' && value === 0) return max;\n return Number.isFinite(value) && value >= 1 ? Math.min(value, max) : 1;\n}\n\nfunction isElement(value: unknown): value is Element {\n return typeof value === 'object' && value !== null && (value as { nodeType?: unknown }).nodeType === 1;\n}\n\nfunction findTable(root: Document | Element): HTMLTableElement | null {\n if (isElement(root) && root.tagName.toUpperCase() === 'TABLE' && (root as HTMLTableElement).rows.length > 0) {\n return root as HTMLTableElement;\n }\n // Document order: an outer table comes before the tables nested in it.\n for (const table of Array.from(root.getElementsByTagName('table'))) {\n if (table.rows.length > 0) return table;\n }\n return null;\n}\n\nfunction readGrid(\n table: HTMLTableElement,\n repeat: boolean,\n limits: Limits,\n): { grid: string[][]; headerRow: boolean; truncated: boolean } {\n const rows = Array.from(table.rows).filter((row) => !isHidden(row));\n const grid: (string | undefined)[][] = [];\n let truncated = rows.length > limits.maxRows;\n const rowLimit = Math.min(rows.length, limits.maxRows);\n // Merged cells can claim far more slots than the markup is long: budget every slot.\n let filled = 0;\n let full = false;\n\n for (let rowIndex = 0; rowIndex < rowLimit && !full; rowIndex++) {\n const row = rows[rowIndex] as HTMLTableRowElement;\n const line = (grid[rowIndex] ??= []);\n let column = 0;\n for (const cell of Array.from(row.cells)) {\n if (isHidden(cell)) continue;\n while (line[column] !== undefined) column++;\n if (column >= limits.maxColumns) {\n truncated = true;\n break;\n }\n const text = cellText(cell);\n const colSpan = span(cell, 'colspan', 1000);\n const rowSpan = span(cell, 'rowspan', rowLimit - rowIndex);\n for (let down = 0; down < rowSpan && !full; down++) {\n const target = (grid[rowIndex + down] ??= []);\n for (let across = 0; across < colSpan && column + across < limits.maxColumns; across++) {\n if (filled >= limits.maxCells) {\n full = true;\n break;\n }\n target[column + across] = down === 0 && across === 0 ? text : repeat ? text : '';\n filled += 1;\n }\n }\n if (full) {\n truncated = true;\n break;\n }\n if (column + colSpan > limits.maxColumns) truncated = true;\n column += colSpan;\n }\n }\n\n const first = rows[0];\n const headerRow =\n first !== undefined &&\n (first.parentElement?.tagName.toUpperCase() === 'THEAD' ||\n (first.cells.length > 0 && Array.from(first.cells).every((cell) => cell.tagName.toUpperCase() === 'TH')));\n return { grid: grid.map((line) => Array.from(line, (cell) => cell ?? '')), headerRow, truncated };\n}\n\nfunction parseHtmlString(html: string): Document | null {\n if (typeof DOMParser === 'undefined') return null;\n return parseInertHtml(html);\n}\n\n/**\n * Reads the first non-empty `<table>` from an HTML string (such as Excel, Google Sheets,\n * Word or a web page put on the clipboard) or from an element, which may be the table or\n * contain it. Merged cells, `<br>` line breaks and hidden rows and cells are handled.\n * Returns `null` without a table, without content, or on a server without `DOMParser`.\n */\nexport function parseHtmlTable(input: string | Element, options: ParseTableOptions = {}): ParsedTable | null {\n const limits = resolveLimits(options);\n let root: Document | Element | null;\n if (typeof input === 'string') {\n checkLength(input, limits);\n if (!/<table[\\s>]/i.test(input)) return null;\n root = parseHtmlString(input);\n } else if (isElement(input)) {\n root = input;\n } else {\n throw invalid('`parseHtmlTable` expects an HTML string or an element.');\n }\n const table = root ? findTable(root) : null;\n if (!table) return null;\n const { grid, headerRow, truncated } = readGrid(table, options.spans === 'repeat', limits);\n const headers = options.headers ?? 'auto';\n return finish(grid, headers === 'auto' ? headerRow : headers, 'html', limits, truncated);\n}\n\n/**\n * Reads a table from pasted content: a `PasteResult` (or any `{ html, text }`), or plain\n * text. The HTML flavour is preferred when it holds a table; otherwise the text is split\n * on tabs. Returns `null` when neither holds any cell content.\n *\n * ```ts\n * usePaste({ accept: ['html', 'text'], onPaste: (result) => setRows(parseTable(result)?.rows ?? []) });\n * ```\n *\n * Throws a `CopyFailure`: `too-large` past `maxLength`, `invalid-payload` for bad options.\n */\nexport function parseTable(source: TableSource, options: ParseTableOptions = {}): ParsedTable | null {\n if (typeof source === 'string') return parseDelimited(source, options);\n const candidate: unknown = source;\n if (typeof candidate !== 'object' || candidate === null) {\n throw invalid('`parseTable` expects a string or an object with `html` and/or `text`.');\n }\n const html = typeof source.html === 'string' ? source.html : null;\n const text = typeof source.text === 'string' ? source.text : null;\n const fromHtml = () => (html === null ? null : parseHtmlTable(html, options));\n const fromText = () => (text === null ? null : parseDelimited(text, options));\n return options.prefer === 'text' ? (fromText() ?? fromHtml()) : (fromHtml() ?? fromText());\n}\n\n/**\n * Reads a rendered `<table>` (or the first table inside `element`) as {@link TableData},\n * ready for `tablePayload`. Works with any library that renders real table markup.\n * Throws `invalid-payload` when there is no table with content.\n */\nexport function fromTableElement(element: Element, options: ParseTableOptions = {}): ParsedTable {\n const table = parseHtmlTable(element, options);\n if (!table) throw invalid('No table with content was found in the element.');\n return table;\n}\n","import { copyFailure } from '../core/errors';\n\n/** How to read one field of a record from a pasted table. */\nexport interface RecordField<Value = string> {\n /**\n * Header text that identifies the column; several for aliases. Matched ignoring case,\n * surrounding and repeated spaces, and full-width characters. Defaults to the key.\n */\n readonly header?: string | readonly string[];\n /** Turns the cell text into a value. Default: the text itself. A throw is reported in `errors`. */\n readonly parse?: (text: string, context: RecordParseContext) => Value;\n /** Report the column in `missing` when the table doesn't have it. Default `false`. */\n readonly required?: boolean;\n}\n\nexport interface RecordParseContext {\n /** Zero-based data row (the header row is not counted). */\n readonly row: number;\n readonly key: string;\n}\n\n/** Field definitions by record key. */\nexport type RecordSchema = Readonly<Record<string, RecordField<unknown>>>;\n\n/** The record a schema produces. A value is `undefined` when its column is missing or its `parse` threw. */\nexport type RecordOf<Schema extends RecordSchema> = {\n -readonly [Key in keyof Schema]: (Schema[Key] extends { readonly parse: (...args: never[]) => infer Value } ? Value : string) | undefined;\n};\n\nexport interface RecordError<Key extends string = string> {\n readonly row: number;\n readonly key: Key;\n readonly text: string;\n readonly cause: unknown;\n}\n\nexport interface RecordsResult<Schema extends RecordSchema> {\n readonly records: RecordOf<Schema>[];\n /** Required fields whose column was not found. */\n readonly missing: (keyof Schema & string)[];\n /** Cells whose `parse` threw. */\n readonly errors: RecordError<keyof Schema & string>[];\n /** `true` when nothing is missing and nothing failed to parse. */\n readonly ok: boolean;\n}\n\nexport interface ToRecordsOptions {\n /**\n * `'header'`: find columns by header text. `'position'`: the schema's key order is the\n * column order. `'auto'` (default): by header when the table has one, else by position.\n */\n readonly match?: 'auto' | 'header' | 'position';\n /** Skip rows whose cells are all empty. Default `true`. */\n readonly skipEmptyRows?: boolean;\n}\n\n/** Any table of strings, such as the result of `parseTable`. */\nexport interface StringTable {\n readonly headers?: readonly string[] | null | undefined;\n readonly rows: readonly (readonly string[])[];\n}\n\nconst normalize = (label: string): string => label.normalize('NFKC').trim().replace(/\\s+/g, ' ').toLowerCase();\n\n/**\n * Maps a pasted table onto typed records, for importing rows from Excel or Google Sheets.\n *\n * ```ts\n * const { records, missing, errors } = toRecords(parseTable(result)!, {\n * email: { header: ['Email', 'E-mail'], required: true },\n * seats: { header: 'Seats', parse: (text) => Number.parseInt(text, 10) },\n * });\n * // records: { email: string | undefined; seats: number | undefined }[]\n * ```\n */\nexport function toRecords<const Schema extends RecordSchema>(\n table: StringTable,\n schema: Schema,\n options: ToRecordsOptions = {},\n): RecordsResult<Schema> {\n const input: unknown = table;\n if (typeof input !== 'object' || input === null || !Array.isArray((input as { rows?: unknown }).rows)) {\n throw copyFailure('invalid-payload', '`toRecords` expects a table with a `rows` array.');\n }\n const keys = Object.keys(schema) as (keyof Schema & string)[];\n if (keys.length === 0) throw copyFailure('invalid-payload', '`toRecords` needs at least one field.');\n\n const headers = Array.isArray(table.headers) ? table.headers : null;\n const match = options.match ?? 'auto';\n const byHeader = match === 'header' || (match === 'auto' && headers !== null);\n if (byHeader && headers === null) {\n throw copyFailure('invalid-payload', 'Matching by header needs a table with headers (`parseTable(…, { headers: true })`).');\n }\n\n const normalizedHeaders = headers?.map((label) => normalize(String(label))) ?? [];\n // A loop, not Math.max(...rows): spreading 100k+ rows overflows the call stack.\n let width = headers?.length ?? 0;\n if (headers === null) for (const row of table.rows) width = Math.max(width, row.length);\n const columnOf = new Map<string, number>();\n const missing: (keyof Schema & string)[] = [];\n keys.forEach((key, position) => {\n const field = schema[key] as RecordField<unknown>;\n let column = -1;\n if (byHeader) {\n const wanted = field.header === undefined ? [key] : typeof field.header === 'string' ? [field.header] : field.header;\n for (const label of wanted) {\n column = normalizedHeaders.indexOf(normalize(label));\n if (column !== -1) break;\n }\n } else {\n column = position;\n }\n if (column === -1 || column >= width) {\n if (field.required === true) missing.push(key);\n } else {\n columnOf.set(key, column);\n }\n });\n\n const skipEmpty = options.skipEmptyRows ?? true;\n const records: RecordOf<Schema>[] = [];\n const errors: RecordError<keyof Schema & string>[] = [];\n table.rows.forEach((row, rowIndex) => {\n if (skipEmpty && row.every((cell) => cell === '')) return;\n const record: Record<string, unknown> = {};\n for (const key of keys) {\n const column = columnOf.get(key);\n if (column === undefined) {\n record[key] = undefined;\n continue;\n }\n const text = row[column] ?? '';\n const parse = (schema[key] as RecordField<unknown>).parse;\n if (!parse) {\n record[key] = text;\n continue;\n }\n try {\n record[key] = parse(text, { row: rowIndex, key });\n } catch (cause) {\n record[key] = undefined;\n errors.push({ row: rowIndex, key, text, cause });\n }\n }\n records.push(record as RecordOf<Schema>);\n });\n\n return { records, missing, errors, ok: missing.length === 0 && errors.length === 0 };\n}\n","import type { TableCell } from './serialize';\n\nfunction isDate(value: unknown): value is Date {\n return value instanceof Date || Object.prototype.toString.call(value) === '[object Date]';\n}\n\nfunction json(value: unknown): string {\n try {\n const encoded = JSON.stringify(value);\n return typeof encoded === 'string' ? encoded : '';\n } catch {\n // Circular structures and BigInt inside objects.\n return Object.prototype.toString.call(value);\n }\n}\n\n/** One list item as text. Nested lists and objects become JSON: no recursion, so cycles are safe. */\nfunction itemText(value: unknown): string {\n if (value === null || value === undefined) return '';\n switch (typeof value) {\n case 'string':\n return value;\n case 'number':\n case 'bigint':\n case 'boolean':\n return String(value);\n case 'function':\n case 'symbol':\n return '';\n }\n if (isDate(value)) return Number.isNaN(value.getTime()) ? '' : value.toISOString();\n return json(value);\n}\n\n/**\n * Turns whatever a grid holds into a cell: primitives and dates as they are, arrays as\n * a comma-separated list, other objects as JSON. Never throws, so one odd value can't\n * break a copy of thousands of rows.\n */\nexport function toCellValue(value: unknown): TableCell {\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'bigint':\n case 'boolean':\n case 'undefined':\n return value;\n case 'function':\n case 'symbol':\n return '';\n }\n if (value === null) return null;\n if (isDate(value)) return Number.isNaN(value.getTime()) ? '' : value;\n if (Array.isArray(value)) return value.map(itemText).join(', ');\n return json(value);\n}\n","import { copyFailure } from '../core/errors';\nimport { toCellValue } from './cell-value';\nimport type { TableCell, TableData } from './serialize';\n\n/*\n * AG Grid support without depending on AG Grid: these interfaces describe only the\n * methods used, so any GridApi from v31 onwards (Community or Enterprise) fits.\n */\n\nexport interface AgGridColumnLike {\n getColId(): string;\n}\n\nexport interface AgGridRowNodeLike {\n /** Position among displayed rows; `null` when filtered out or inside a collapsed group. */\n readonly rowIndex: number | null;\n readonly group?: boolean | undefined;\n}\n\nexport interface AgGridApiLike<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike> {\n getAllDisplayedColumns(): Column[];\n getDisplayNameForColumn(column: Column, location: 'csv'): string;\n getSelectedNodes(): Node[];\n getDisplayedRowCount(): number;\n getDisplayedRowAtIndex(index: number): Node | undefined;\n forEachNodeAfterFilterAndSort(callback: (node: Node, index: number) => void): void;\n forEachNode(callback: (node: Node, index: number) => void): void;\n /** v31.3+. */\n getCellValue?(params: { rowNode: Node; colKey: Column | string; useFormatter?: boolean }): unknown;\n /** v31–v32; removed in v33. */\n getValue?(colKey: Column | string, rowNode: Node): unknown;\n}\n\nexport interface FromAgGridOptions<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike> {\n /**\n * Which rows, in on-screen order:\n * - `'displayed'` (default): every row the grid displays after filtering, sorting and\n * grouping, across all pages.\n * - `'selected'`: selected rows that are currently displayed.\n * - `'filtered'`: rows passing the filter, in sort order, including those inside\n * collapsed groups.\n * - `'all'`: every row, in the order of your data.\n * - an array of row nodes, taken as given.\n */\n readonly rows?: 'displayed' | 'selected' | 'filtered' | 'all' | readonly Node[];\n /** Column ids to copy, in this order. Default: the displayed columns, minus the selection and row-number columns. */\n readonly columns?: readonly string[];\n /**\n * - `'auto'` (default): numbers, bigints and booleans raw, so spreadsheets can calculate\n * with them; everything else as the grid's `valueFormatter` shows it.\n * - `'raw'`: the underlying values. `'formatted'`: exactly what the grid shows.\n */\n readonly values?: 'auto' | 'raw' | 'formatted';\n /** Include group rows (Enterprise row grouping). Default `false`: only rows with data. */\n readonly includeGroupRows?: boolean;\n /** Header text for a column. Default: the grid's own name for exports. */\n readonly header?: (column: Column) => string;\n}\n\n/** Ids of AG Grid's own utility columns, which hold no data. */\nconst UTILITY_COLUMNS = new Set(['ag-Grid-SelectionColumn', 'ag-Grid-RowNumbersColumn']);\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction collectRows<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike>(\n api: AgGridApiLike<Node, Column>,\n rows: NonNullable<FromAgGridOptions<Node, Column>['rows']>,\n): Node[] {\n if (typeof rows !== 'string') {\n const list: unknown = rows;\n if (!Array.isArray(list)) throw invalid('`rows` must be \"displayed\", \"selected\", \"filtered\", \"all\" or an array of row nodes.');\n return [...rows];\n }\n const nodes: Node[] = [];\n switch (rows) {\n case 'displayed': {\n const count = api.getDisplayedRowCount();\n for (let index = 0; index < count; index++) {\n const node = api.getDisplayedRowAtIndex(index);\n if (node) nodes.push(node);\n }\n return nodes;\n }\n case 'selected':\n // Selection order is click order; copy in the order the rows appear instead.\n return api\n .getSelectedNodes()\n .filter((node): node is Node & { rowIndex: number } => node.rowIndex !== null)\n .sort((a, b) => a.rowIndex - b.rowIndex);\n case 'filtered':\n api.forEachNodeAfterFilterAndSort((node) => nodes.push(node));\n return nodes;\n case 'all':\n api.forEachNode((node) => nodes.push(node));\n return nodes;\n default:\n throw invalid(`Unknown \\`rows\\` option: ${JSON.stringify(rows)}.`);\n }\n}\n\n/**\n * Reads rows from an AG Grid (v31+, Community or Enterprise) as table data.\n *\n * ```ts\n * copy(() => tablePayload(fromAgGrid(gridRef.current!.api, { rows: 'selected' })));\n * ```\n *\n * Gives Community grids Excel-ready copy, which AG Grid only ships in Enterprise.\n */\nexport function fromAgGrid<Node extends AgGridRowNodeLike, Column extends AgGridColumnLike>(\n api: AgGridApiLike<Node, Column>,\n options: FromAgGridOptions<Node, Column> = {},\n): TableData {\n const candidate: unknown = api;\n if (typeof candidate !== 'object' || candidate === null || typeof api.getAllDisplayedColumns !== 'function') {\n throw invalid('`fromAgGrid` expects an AG Grid API (v31 or later): `gridRef.current.api` or the API from `onGridReady`.');\n }\n\n const read: (node: Node, column: Column, useFormatter: boolean) => unknown =\n typeof api.getCellValue === 'function'\n ? (node, column, useFormatter) => api.getCellValue?.({ rowNode: node, colKey: column, useFormatter })\n : typeof api.getValue === 'function'\n ? (node, column) => api.getValue?.(column, node)\n : () => {\n throw invalid('This grid API has neither `getCellValue` nor `getValue`; AG Grid v31 or later is required.');\n };\n\n const displayed = api.getAllDisplayedColumns();\n let columns: Column[];\n if (options.columns) {\n const byId = new Map(displayed.map((column) => [column.getColId(), column]));\n columns = options.columns.map((id) => {\n const column = byId.get(id);\n if (!column) throw invalid(`Column \"${id}\" is not displayed in the grid.`);\n return column;\n });\n } else {\n columns = displayed.filter((column) => !UTILITY_COLUMNS.has(column.getColId()));\n }\n\n const values = options.values ?? 'auto';\n const cell = (node: Node, column: Column): TableCell => {\n if (values === 'formatted') return toCellValue(read(node, column, true));\n const raw = read(node, column, false);\n if (values === 'raw') return toCellValue(raw);\n const type = typeof raw;\n return type === 'number' || type === 'bigint' || type === 'boolean' ? toCellValue(raw) : toCellValue(read(node, column, true));\n };\n\n const includeGroups = options.includeGroupRows ?? false;\n const nodes = collectRows(api, options.rows ?? 'displayed').filter((node) => includeGroups || node.group !== true);\n\n return {\n headers: columns.map((column) => options.header?.(column) ?? api.getDisplayNameForColumn(column, 'csv')),\n rows: nodes.map((node) => columns.map((column) => cell(node, column))),\n };\n}\n","import { copyFailure } from '../core/errors';\nimport { toCellValue } from './cell-value';\nimport type { TableCell, TableData } from './serialize';\n\n/*\n * TanStack Table support without depending on it: only the methods used are described,\n * so tables from v8 and v9, in any framework adapter (React, Vue, Solid, Svelte,\n * Angular, Lit), and libraries built on it such as Material React Table and Mantine\n * React Table, all fit.\n */\n\nexport interface TanStackColumnLike {\n readonly id: string;\n readonly columnDef: { readonly header?: unknown };\n /** Absent on display columns (checkboxes, actions), which hold no data. */\n readonly accessorFn?: unknown;\n}\n\nexport interface TanStackRowLike {\n getValue(columnId: string): unknown;\n /** Present when the row selection feature is enabled. */\n getIsSelected?: () => boolean;\n}\n\nexport interface TanStackTableLike<Row extends TanStackRowLike, Column extends TanStackColumnLike> {\n getRowModel(): { readonly rows: readonly Row[] };\n getAllLeafColumns(): readonly Column[];\n /** Present when the column visibility feature is enabled (always in v8). */\n getVisibleLeafColumns?: () => readonly Column[];\n}\n\nexport interface FromTanStackTableOptions<Row extends TanStackRowLike, Column extends TanStackColumnLike> {\n /**\n * - `'visible'` (default): the rows the table renders now (`getRowModel()`): filtered,\n * sorted, grouped and paginated.\n * - `'selected'`: those of them that are selected.\n * - an array of rows, such as `table.getPrePaginationRowModel().rows` for every page.\n */\n readonly rows?: 'visible' | 'selected' | readonly Row[];\n /** Column ids to copy, in this order. Default: visible leaf columns that hold data. */\n readonly columns?: readonly string[];\n /** Header text for a column. Default: `columnDef.header` when it is a string, else the column id. */\n readonly header?: (column: Column) => string;\n /** The cell for a row and column. Default: `row.getValue(column.id)`. */\n readonly value?: (row: Row, column: Column) => TableCell;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/**\n * Reads rows from a TanStack Table instance (v8 or v9) as table data.\n *\n * ```ts\n * copy(() => tablePayload(fromTanStackTable(table, { rows: 'selected' })));\n * ```\n */\nexport function fromTanStackTable<Row extends TanStackRowLike, Column extends TanStackColumnLike>(\n table: TanStackTableLike<Row, Column>,\n options: FromTanStackTableOptions<Row, Column> = {},\n): TableData {\n const candidate: unknown = table;\n if (typeof candidate !== 'object' || candidate === null || typeof table.getRowModel !== 'function') {\n throw invalid('`fromTanStackTable` expects a TanStack Table instance (v8 or v9).');\n }\n\n const all = table.getAllLeafColumns();\n let columns: readonly Column[];\n if (options.columns) {\n const byId = new Map(all.map((column) => [column.id, column]));\n columns = options.columns.map((id) => {\n const column = byId.get(id);\n if (!column) throw invalid(`Column \"${id}\" does not exist in the table.`);\n return column;\n });\n } else {\n const visible = typeof table.getVisibleLeafColumns === 'function' ? table.getVisibleLeafColumns() : all;\n columns = visible.filter((column) => column.accessorFn !== undefined);\n }\n\n const selection = options.rows ?? 'visible';\n let rows: readonly Row[];\n if (selection === 'visible' || selection === 'selected') {\n rows = table.getRowModel().rows;\n if (selection === 'selected') {\n rows = rows.filter((row) => {\n if (typeof row.getIsSelected !== 'function') {\n throw invalid('Row selection is not enabled on this table: register the row selection feature, or pass `rows`.');\n }\n return row.getIsSelected();\n });\n }\n } else if (Array.isArray(selection)) {\n rows = selection;\n } else {\n throw invalid('`rows` must be \"visible\", \"selected\" or an array of rows.');\n }\n\n const header = (column: Column): string => {\n if (options.header) return options.header(column);\n const label = column.columnDef.header;\n return typeof label === 'string' ? label : column.id;\n };\n const value = options.value ?? ((row: Row, column: Column) => toCellValue(row.getValue(column.id)));\n\n return {\n headers: columns.map(header),\n rows: rows.map((row) => columns.map((column) => value(row, column))),\n };\n}\n"],"mappings":";;;;AAsEA,MAAa,0BAA0B;AAkBvC,MAAM,gBAAgB;AACtB,M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WAAW,OAAO,eAAe,KAAA,CAAS;CAGtE,MAAM,YAAY,QAAQ,QAAQ;CAClC,IAAI;CACJ,IAAI,cAAc,aAAa,cAAc,YAAY;EACvD,OAAO,MAAM,YAAY,CAAC,CAAC;EAC3B,IAAI,cAAc,YAChB,OAAO,KAAK,QAAQ,QAAQ;GAC1B,IAAI,OAAO,IAAI,kBAAkB,YAC/B,MAAM,QAAQ,iGAAiG;GAEjH,OAAO,IAAI,cAAc;EAC3B,CAAC;CAEL,OAAO,IAAI,MAAM,QAAQ,SAAS,GAChC,OAAO;MAEP,MAAM,QAAQ,+DAA2D;CAG3E,MAAM,UAAU,WAA2B;EACzC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,OAAO,MAAM;EAChD,MAAM,QAAQ,OAAO,UAAU;EAC/B,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO;CACpD;CACA,MAAM,QAAQ,QAAQ,WAAW,KAAU,WAAmB,YAAY,IAAI,SAAS,OAAO,EAAE,CAAC;CAEjG,OAAO;EACL,SAAS,QAAQ,IAAI,MAAM;EAC3B,MAAM,KAAK,KAAK,QAAQ,QAAQ,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAAC;CACrE;AACF"}
|
package/dist/testing.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const require_errors = require("./chunks/errors-
|
|
4
|
-
const require_paste_reader = require("./chunks/paste-reader-
|
|
3
|
+
const require_errors = require("./chunks/errors-DFmEAC4E.cjs");
|
|
4
|
+
const require_paste_reader = require("./chunks/paste-reader-BWQaYNaV.cjs");
|
|
5
5
|
//#region src/testing/index.ts
|
|
6
6
|
/**
|
|
7
7
|
* Builds a complete, self-consistent {@link PasteResult} with sensible defaults.
|
package/dist/testing.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
|
-
import { b as CopyFailure, r as CopyPayload, v as CopyError } from "./chunks/payload-
|
|
2
|
+
import { b as CopyFailure, r as CopyPayload, v as CopyError } from "./chunks/payload-qkAWVXWA.cjs";
|
|
3
3
|
import { f as PasteReadResult, l as PasteItem, m as PasteSource, p as PasteResult } from "./chunks/paste-reader-DcXnRWQr.cjs";
|
|
4
|
-
import { n as ClipboardAdapter } from "./chunks/clipboard-adapter-
|
|
5
|
-
import { n as PasteAdapter } from "./chunks/paste-adapter
|
|
4
|
+
import { n as ClipboardAdapter } from "./chunks/clipboard-adapter-CfaIbZpv.cjs";
|
|
5
|
+
import { n as PasteAdapter } from "./chunks/paste-adapter-B6eucH3E.cjs";
|
|
6
6
|
//#region src/testing/index.d.ts
|
|
7
7
|
/**
|
|
8
8
|
* Input for {@link createPasteResult}: every field is optional so callers
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
|
-
import { b as CopyFailure, r as CopyPayload, v as CopyError } from "./chunks/payload-
|
|
2
|
+
import { b as CopyFailure, r as CopyPayload, v as CopyError } from "./chunks/payload-CcvSx_Hq.js";
|
|
3
3
|
import { f as PasteReadResult, l as PasteItem, m as PasteSource, p as PasteResult } from "./chunks/paste-reader-DcXnRWQr.js";
|
|
4
|
-
import { n as ClipboardAdapter } from "./chunks/clipboard-adapter-
|
|
5
|
-
import { n as PasteAdapter } from "./chunks/paste-adapter-
|
|
4
|
+
import { n as ClipboardAdapter } from "./chunks/clipboard-adapter-Chm6zq60.js";
|
|
5
|
+
import { n as PasteAdapter } from "./chunks/paste-adapter-CfIDT3mp.js";
|
|
6
6
|
//#region src/testing/index.d.ts
|
|
7
7
|
/**
|
|
8
8
|
* Input for {@link createPasteResult}: every field is optional so callers
|
package/dist/testing.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { r as createCopyError, t as CopyFailure } from "./chunks/errors-
|
|
3
|
-
import { o as completePasteResult } from "./chunks/paste-reader-
|
|
2
|
+
import { r as createCopyError, t as CopyFailure } from "./chunks/errors-CT-FfUtU.js";
|
|
3
|
+
import { o as completePasteResult } from "./chunks/paste-reader-D6uOTDBM.js";
|
|
4
4
|
//#region src/testing/index.ts
|
|
5
5
|
/**
|
|
6
6
|
* Builds a complete, self-consistent {@link PasteResult} with sensible defaults.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-smart-copy",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.25.0",
|
|
4
4
|
"description": "Headless, type-safe clipboard interactions for React: copy and paste text, rich HTML, images, spreadsheet tables, typed application data, Markdown, code, privacy-safe images, links, sharing, colours, portable rich text, clean pastes from Word and Google Docs, safe file and folder drops with content-type checks, secret detection and redaction in pastes and copies, one-time codes read from pasted messages into accessible code fields with SMS autofill and WebOTP, numbers and amounts pasted and copied exactly across locales, and lists of e-mail recipients pasted from Outlook, Gmail and spreadsheets, checked for lookalike domains, with coordinated copy groups, SVG/DOM capture, Trojan Source and homoglyph detection, honest error states, retry and screen-reader announcements.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -368,13 +368,13 @@
|
|
|
368
368
|
},
|
|
369
369
|
"scripts": {
|
|
370
370
|
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsdown",
|
|
371
|
-
"typecheck": "tsc --noEmit",
|
|
371
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.lib.json",
|
|
372
372
|
"test": "vitest run",
|
|
373
373
|
"test:watch": "vitest",
|
|
374
374
|
"lint": "eslint .",
|
|
375
375
|
"lint:package": "publint --strict && attw --pack .",
|
|
376
376
|
"size": "size-limit",
|
|
377
|
-
"verify": "npm run lint && npm run typecheck && npm run test:coverage && npm run build && node scripts/check-dist.js && npm run lint:package && npm run types:consumer && npm run size",
|
|
377
|
+
"verify": "npm run lint && npm run typecheck && npm run test:coverage && npm run build && node scripts/check-dist.js && node scripts/check-docs.mjs && npm run lint:package && npm run types:consumer && npm run size",
|
|
378
378
|
"changeset": "changeset",
|
|
379
379
|
"release": "npm run verify && changeset publish",
|
|
380
380
|
"docs:install": "npm ci --prefix docs",
|
|
@@ -383,7 +383,10 @@
|
|
|
383
383
|
"test:coverage": "vitest run --coverage --exclude \"**/*.property.test.ts\" && npm run test:property",
|
|
384
384
|
"test:property": "vitest run property.test",
|
|
385
385
|
"types:consumer": "tsc -p consumer/tsconfig.bundler.json && tsc -p consumer/tsconfig.nodenext.json",
|
|
386
|
-
"test:e2e": "playwright test"
|
|
386
|
+
"test:e2e": "playwright test",
|
|
387
|
+
"check:docs": "node scripts/check-docs.mjs",
|
|
388
|
+
"corpus:accept": "node scripts/corpus-accept.mjs",
|
|
389
|
+
"bench": "npm run build && vitest run --config vitest.bench.config.ts --reporter=verbose"
|
|
387
390
|
},
|
|
388
391
|
"size-limit": [
|
|
389
392
|
{
|
|
@@ -702,5 +705,8 @@
|
|
|
702
705
|
"valibot": "1.5.0",
|
|
703
706
|
"vitest": "^5.0.5",
|
|
704
707
|
"zod": "^4.6.7"
|
|
708
|
+
},
|
|
709
|
+
"overrides": {
|
|
710
|
+
"minimatch": "11.0.3"
|
|
705
711
|
}
|
|
706
712
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-9h8sdFFX.js","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n"],"mappings":";;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,I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CAA+C,KAAK;EACnG,KAAK,cACH,OAAO,gBAAgB,WAAW,iBAAiB,KAAK,gBAAgB,KAAK;EAC/E,KAAK,gBACH,OAAO,gBAAgB,WAAW,iBAAiB,KAAK,cAAc,KAAK;EAC7E,SACE,OAAO,gBAAgB,WAAW,WAAW,iBAAiB,KAAK,iCAAiC,KAAK;CAC7G;AACF;AAEA,MAAM,oBAA6D;CACjE,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,0BAA0B;CAC1B,wBAAwB;CACxB,cAAc;CACd,aAAa;CACb,SAAS;CACT,SAAS;CACT,SAAS;AACX;AAEA,MAAM,qBAA8D;CAClE,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,0BAA0B;CAC1B,wBAAwB;CACxB,cAAc;CACd,aAAa;CACb,SAAS;CACT,SAAS;CACT,SAAS;AACX;;AAGA,SAAgB,kBAAkB,OAA0B;CAC1D,OAAO,kBAAkB,MAAM;AACjC;;AAGA,MAAM,oBAAsE;CAC1E,mBAAmB;CACnB,cAAc;CACd,aAAa;CACb,SAAS;AACX;;;;;AAMA,SAAgB,mBAAmB,OAAkB,QAA8B;CACjF,QAAQ,WAAW,SAAS,kBAAkB,MAAM,QAAQ,KAAA,MAAc,mBAAmB,MAAM;AACrG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-BwOF6T_M.cjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined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