import {
  stripInlineMarks
} from "./chunk-NMKKU2UG.js";

// src/utils/parse-markdown-table.ts
function parseCells(line) {
  const trimmed = line.trim();
  const stripped = trimmed.startsWith("|") ? trimmed.slice(1) : trimmed;
  const withoutTrailing = stripped.endsWith("|") ? stripped.slice(0, -1) : stripped;
  return withoutTrailing.split("|").map((cell) => cell.trim());
}
function isSeparatorRow(line) {
  const cells = parseCells(line);
  return cells.length > 0 && cells.every((cell) => /^:?-{1,}:?$/.test(cell));
}
function isTableRow(line) {
  return line.includes("|");
}
var TABLE_TITLE_PREFIX = "<!-- table-title:";
var TABLE_TITLE_SUFFIX = "-->";
function extractTableTitle(line) {
  const trimmed = line.trim();
  if (!trimmed.startsWith(TABLE_TITLE_PREFIX) || !trimmed.endsWith(TABLE_TITLE_SUFFIX)) {
    return void 0;
  }
  return trimmed.slice(TABLE_TITLE_PREFIX.length, -TABLE_TITLE_SUFFIX.length).trim() || void 0;
}
function parseMarkdownTable(markdown, tableIndex = 0) {
  const lines = markdown.split("\n");
  let tableCount = 0;
  for (let i = 0; i < lines.length - 1; i++) {
    const headerLine = lines[i];
    const separatorLine = lines[i + 1];
    if (!isTableRow(headerLine) || !isSeparatorRow(separatorLine)) {
      continue;
    }
    if (tableCount === tableIndex) {
      const columns = parseCells(headerLine).map(stripInlineMarks);
      const rows = [];
      const title = i > 0 ? extractTableTitle(lines[i - 1]) : void 0;
      for (let j = i + 2; j < lines.length; j++) {
        if (!isTableRow(lines[j]) || isSeparatorRow(lines[j])) {
          break;
        }
        const trimmedLine = lines[j].trim();
        if (trimmedLine === "") {
          break;
        }
        rows.push(parseCells(lines[j]).map(stripInlineMarks));
      }
      return { columns, rows, ...title ? { title } : {} };
    }
    tableCount++;
  }
  return null;
}

// src/utils/escape-csv-field.ts
var FORMULA_TRIGGERS = /* @__PURE__ */ new Set(["=", "+", "@", "	", "\r"]);
function escapeCsvField(field) {
  const needsNeutralise = field.length > 0 && FORMULA_TRIGGERS.has(field[0]);
  const safeField = needsNeutralise ? `	${field}` : field;
  if (needsNeutralise || safeField.includes(",") || safeField.includes('"') || safeField.includes("\n") || safeField.includes("\r")) {
    return `"${safeField.replace(/"/g, '""')}"`;
  }
  return safeField;
}

// src/utils/convert-table-to-csv.ts
function convertTableToCSV(table) {
  const headerRow = table.columns.map(escapeCsvField).join(",");
  const dataRows = table.rows.map((row) => row.map(escapeCsvField).join(","));
  return [headerRow, ...dataRows].join("\r\n");
}

export {
  parseMarkdownTable,
  escapeCsvField,
  convertTableToCSV
};
//# sourceMappingURL=chunk-JJUIBBBU.js.map