{"version":3,"file":"csv.cjs","names":[],"sources":["../../src/utils/csv.ts"],"sourcesContent":["/**\n * @tempest-limits param-count — `downloadCsv(rows, columns, \"usuarios.csv\")` reads\n * in the order the sentence does, and its two trailing parameters have defaults,\n * so the common call passes three. Wrapping them in an object would break every\n * caller of a published export for no gain in what the call site says.\n */\n// CSV that survives contact with real data. Every app writes this by hand and\n// every hand-written version gets the same two things wrong: a value containing\n// the delimiter splits the row, and a value containing a quote breaks the quoting\n// it was supposed to be protected by. Both are one-liners in RFC 4180 and neither\n// is obvious until a customer's name has a comma in it.\n\nimport { shareOrDownloadBlob } from \"../share/share-or-download\";\n\n/**\n * Byte order mark, as the character `String.prototype` sees it.\n *\n * Excel on a pt-BR install reads a BOM-less UTF-8 file as Latin-1 and turns\n * every accented name into mojibake. It is three bytes to avoid a support\n * ticket, so it is on by default.\n */\nconst BOM = \"\\uFEFF\";\n\n/** One column of the exported file. */\nexport interface CsvColumn<T> {\n    /** Property of the row this column reads from. Doubles as the column key. */\n    key: keyof T;\n    /** Column heading, written to the first line. */\n    header: string;\n    /**\n     * Value for the file. Defaults to `String(row[key])`, with nullish becoming an\n     * empty field.\n     *\n     * A `DataTableColumn` renders cells to `ReactNode`, which cannot be written to\n     * a text file — a badge or a link would serialize as `[object Object]`. Give\n     * the column this accessor and the export says what the badge said.\n     */\n    csv?: (row: T) => string | number | boolean | null | undefined;\n}\n\n/** Options for {@link toCsv}. */\nexport interface CsvOptions {\n    /**\n     * Field separator. Default `\",\"`.\n     *\n     * Use `\";\"` for Excel on a locale whose decimal separator is the comma —\n     * which is every pt-BR install — otherwise it opens the file in one column.\n     */\n    delimiter?: \",\" | \";\";\n    /** Prefix the output with a UTF-8 BOM. Default `true`. */\n    bom?: boolean;\n}\n\n/**\n * Quote one field per RFC 4180.\n *\n * A field is quoted when it contains the delimiter, a double quote, or a line\n * break; inside a quoted field, each double quote is doubled. Fields that need\n * none of this are written bare, which keeps the common file readable.\n *\n * @param value - The already-stringified field.\n * @param delimiter - The separator in use, which decides part of the quoting.\n * @returns The field, quoted if it has to be.\n */\nfunction escapeField(value: string, delimiter: string): string {\n    const mustQuote =\n        value.includes(delimiter) ||\n        value.includes('\"') ||\n        value.includes(\"\\n\") ||\n        value.includes(\"\\r\");\n    if (!mustQuote) return value;\n    return `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\n/**\n * Stringify one cell, keeping the difference between \"no value\" and \"zero\".\n *\n * `null` and `undefined` become an empty field; `0` and `false` are values\n * somebody chose and are written out. Getting this backwards is how an export\n * ends up under-reporting every row that legitimately holds a zero.\n *\n * @param value - The raw cell value.\n * @returns The text to write.\n */\nfunction cellText(value: unknown): string {\n    if (value === null || value === undefined) return \"\";\n    if (value instanceof Date) return value.toISOString();\n    return String(value);\n}\n\n/**\n * Serialize rows to CSV text, RFC 4180 style.\n *\n * Rows are separated by `\\r\\n` — the RFC's terminator and the one Excel is least\n * surprised by. A row is emitted for the header even when `rows` is empty, so the\n * person who opens the file sees which columns they asked for instead of a blank\n * document.\n *\n * @example\n * const csv = toCsv(users, [\n *     { key: \"name\", header: \"Nome\" },\n *     { key: \"email\", header: \"E-mail\" },\n *     { key: \"plan\", header: \"Plano\", csv: (user) => user.plan.label },\n * ]);\n *\n * @param rows - The rows to export.\n * @param columns - Columns, in the order they should appear.\n * @param options - Delimiter and BOM.\n * @returns The complete file contents.\n */\nexport function toCsv<T>(\n    rows: readonly T[],\n    columns: readonly CsvColumn<T>[],\n    options: CsvOptions = {},\n): string {\n    const { delimiter = \",\", bom = true } = options;\n\n    const lines = [columns.map((column) => escapeField(column.header, delimiter)).join(delimiter)];\n\n    for (const row of rows) {\n        const cells = columns.map((column) => {\n            const raw = column.csv\n                ? column.csv(row)\n                : (row as Record<string, unknown>)[column.key as string];\n            return escapeField(cellText(raw), delimiter);\n        });\n        lines.push(cells.join(delimiter));\n    }\n\n    return `${bom ? BOM : \"\"}${lines.join(\"\\r\\n\")}`;\n}\n\n/**\n * Build a CSV and hand it to the user.\n *\n * Goes through {@link shareOrDownloadBlob}, so on a phone it opens the native\n * share sheet and everywhere else it downloads — the same path every other\n * generated artifact in the SDK takes, instead of a fourth hand-rolled `<a\n * download>`.\n *\n * @example\n * await downloadCsv(users, COLUMNS, \"usuarios.csv\");\n *\n * @param rows - The rows to export.\n * @param columns - Columns, in the order they should appear.\n * @param fileName - File name offered to the user. Default `\"export.csv\"`.\n * @param options - Delimiter and BOM, forwarded to {@link toCsv}.\n * @returns A promise that resolves once the share or download completes.\n */\nexport async function downloadCsv<T>(\n    rows: readonly T[],\n    columns: readonly CsvColumn<T>[],\n    fileName = \"export.csv\",\n    options: CsvOptions = {},\n): Promise<void> {\n    const blob = new Blob([toCsv(rows, columns, options)], {\n        type: \"text/csv;charset=utf-8\",\n    });\n    await shareOrDownloadBlob(blob, fileName);\n}\n"],"mappings":"kDAqBA,IAAM,EAAM,IA2CZ,SAAS,EAAY,EAAe,EAA2B,CAO3D,OALI,EAAM,SAAS,CAAS,GACxB,EAAM,SAAS,GAAG,GAClB,EAAM,SAAS;CAAI,GACnB,EAAM,SAAS,IAAI,EAEhB,IAAI,EAAM,WAAW,IAAK,IAAI,EAAE,GADhB,CAE3B,CAYA,SAAS,EAAS,EAAwB,CAGtC,OAFI,GAAU,KAAoC,GAC9C,aAAiB,KAAa,EAAM,YAAY,EAC7C,OAAO,CAAK,CACvB,CAsBA,SAAgB,EACZ,EACA,EACA,EAAsB,CAAC,EACjB,CACN,GAAM,CAAE,YAAY,IAAK,MAAM,IAAS,EAElC,EAAQ,CAAC,EAAQ,IAAK,GAAW,EAAY,EAAO,OAAQ,CAAS,CAAC,CAAC,CAAC,KAAK,CAAS,CAAC,EAE7F,IAAK,IAAM,KAAO,EAAM,CACpB,IAAM,EAAQ,EAAQ,IAAK,GAIhB,EAAY,EAHP,EAAO,IACb,EAAO,IAAI,CAAG,EACb,EAAgC,EAAO,IACf,EAAG,CAAS,CAC9C,EACD,EAAM,KAAK,EAAM,KAAK,CAAS,CAAC,CACpC,CAEA,MAAO,GAAG,EAAM,EAAM,KAAK,EAAM,KAAK;CAAM,GAChD,CAmBA,eAAsB,EAClB,EACA,EACA,EAAW,aACX,EAAsB,CAAC,EACV,CACb,IAAM,EAAO,IAAI,KAAK,CAAC,EAAM,EAAM,EAAS,CAAO,CAAC,EAAG,CACnD,KAAM,wBACV,CAAC,EACD,MAAM,EAAA,oBAAoB,EAAM,CAAQ,CAC5C"}