All files / src/shared/lib/scriptDataTable csv.ts

94.55% Statements 139/147
90.76% Branches 118/130
100% Functions 25/25
95.03% Lines 134/141

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 3112x 2x   2x                                                 2x       6x 6x         2x 33x 33x 21x   12x           2x         33x 33x 12x 1x   11x 1x       10x     55x 33x 12x     21x 30x 30x   21x 19x   21x 16x     21x 10x   11x 2x   9x 1x   8x     2x 17x 4x   13x     2x 3x     2x       35x 35x 35x 32x   3x 1x   2x 2x 1x   1x     2x 23x 23x 23x 23x   23x 695x 695x   695x 6x     6x 1x   5x   6x     689x 1x 688x 68x 68x 620x 25x 25x 25x 25x 595x 595x       23x 23x   48x     2x         5x 1x         5x 5x   5x     6x         5x 5x 5x 6x 6x 1x 1x 1x       5x   5x   5x     2x         23x 1x           23x 23x       23x 23x   33x 23x 23x   33x     33x           33x 33x         28x 20x               8x 8x 1x   7x           7x 2x   7x 7x                 17x 18x     35x       17x           17x       17x 1x     16x 1x     15x          
import { constantName } from "shared/lib/entities/entitiesHelpers";
import l10n from "shared/lib/lang/l10n";
import { Constant, VariableType } from "shared/lib/resources/types";
import {
  isScriptDataTable,
  ScriptDataTable,
} from "shared/lib/scriptDataTable/types";
import { ScriptVariableElement } from "shared/lib/scriptValue/types";
 
export type DataTableCSVVariable = {
  id: string;
  name: string;
  type: VariableType;
  length?: number;
};
 
export type NewDataTableCSVVariable = {
  placeholder: string;
  name: string;
  type: VariableType;
  length?: number;
};
 
export type ScriptDataTableImport = {
  dataTable: ScriptDataTable;
  newVariables: NewDataTableCSVVariable[];
};
 
const scriptDataTableVariableToCSV = (
  variable: ScriptVariableElement,
  variablesLookup: Record<string, DataTableCSVVariable | undefined>,
): string => {
  const variableName = variablesLookup[variable.value]?.name ?? variable.value;
  return variable.index
    ? `${variableName}[${variable.index.value}]`
    : variableName;
};
 
const parseCSVVariable = (value: string): { name: string; index?: number } => {
  const match = value.match(/^(.*)\[(-?\d+)\]$/);
  if (!match) {
    return { name: value };
  }
  return {
    name: match[1],
    index: Number(match[2]),
  };
};
 
const resolveCSVVariable = (
  name: string,
  index: number | undefined,
  availableVariables: DataTableCSVVariable[],
): DataTableCSVVariable | undefined => {
  const expectedType: VariableType = index === undefined ? "number" : "array";
  const validateMatch = (variable: DataTableCSVVariable) => {
    if (variable.type !== expectedType) {
      throw new Error(l10n("ERROR_DATA_TABLE_CSV_VARIABLE_TYPE", { name }));
    }
    if (index !== undefined && index >= (variable.length ?? 1)) {
      throw new Error(
        l10n("ERROR_DATA_TABLE_CSV_ARRAY_INDEX", { name, index }),
      );
    }
    return variable;
  };
 
  const idMatch = availableVariables.find((variable) => variable.id === name);
  if (idMatch) {
    return validateMatch(idMatch);
  }
 
  const nameMatches = availableVariables.filter((variable) => {
    const isGlobal = !/^[LTV]\d+$/.test(variable.id);
    return isGlobal && variable.name === name;
  });
  const typeMatches = nameMatches.filter(
    (variable) => variable.type === expectedType,
  );
  const compatibleMatches = typeMatches.filter(
    (variable) => index === undefined || index < (variable.length ?? 1),
  );
 
  if (compatibleMatches.length > 0) {
    return compatibleMatches[0];
  }
  if (typeMatches.length > 0 && index !== undefined) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_ARRAY_INDEX", { name, index }));
  }
  if (nameMatches.length > 0) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_VARIABLE_TYPE", { name }));
  }
  return undefined;
};
 
const escapeCSVValue = (value: string): string => {
  if (value.includes(",") || value.includes('"') || value.includes("\n")) {
    return `"${value.replace(/"/g, '""')}"`;
  }
  return value;
};
 
const isEngineConstantSymbol = (value: string) => {
  return value.startsWith("engine::");
};
 
const parseCSVCellValue = (
  value: string | undefined,
  reverseConstantsLookup: Record<string, string>,
) => {
  const trimmedValue = (value ?? "").trim();
  const numValue = Number(trimmedValue);
  if (!isNaN(numValue)) {
    return { type: "number" as const, value: numValue };
  }
  if (isEngineConstantSymbol(trimmedValue)) {
    return { type: "constant" as const, value: trimmedValue };
  }
  const constantId = reverseConstantsLookup[trimmedValue];
  if (constantId) {
    return { type: "constant" as const, value: constantId };
  }
  return { type: "number" as const, value: 0 };
};
 
const parseCSV = (csv: string): string[][] => {
  const rows: string[][] = [];
  let row: string[] = [];
  let value = "";
  let inQuotes = false;
 
  for (let i = 0; i < csv.length; i++) {
    const char = csv[i];
    const nextChar = csv[i + 1];
 
    if (inQuotes) {
      Iif (char === '"' && nextChar === '"') {
        value += '"';
        i++;
      } else if (char === '"') {
        inQuotes = false;
      } else {
        value += char;
      }
      continue;
    }
 
    if (char === '"') {
      inQuotes = true;
    } else if (char === ",") {
      row.push(value);
      value = "";
    } else if (char === "\n") {
      row.push(value);
      rows.push(row);
      row = [];
      value = "";
    } else Eif (char !== "\r") {
      value += char;
    }
  }
 
  row.push(value);
  rows.push(row);
 
  return rows.filter((row) => row.length > 1 || row[0].trim().length > 0);
};
 
export const scriptDataTableToCSV = (
  data: ScriptDataTable,
  constants: Constant[],
  variables: DataTableCSVVariable[],
): string => {
  const constantsLookup = Object.fromEntries(
    constants.map((constant, constantIndex) => [
      constant.id,
      constantName(constant, constantIndex),
    ]),
  );
  const variablesLookup = Object.fromEntries(
    variables.map((variable) => [variable.id, variable]),
  );
  const header = [
    data.label ?? "",
    ...data.variables.map((variable) =>
      scriptDataTableVariableToCSV(variable, variablesLookup),
    ),
  ]
    .map(escapeCSVValue)
    .join(",");
  const rows = data.rows.map((row, index) => {
    const label = row.label ?? `Row ${index + 1}`;
    const values = row.values.map((value) => {
      Iif (value === undefined) return "";
      if (value.type === "constant") {
        const constant = constantsLookup[value.value];
        Eif (constant) {
          return escapeCSVValue(constant);
        }
        return escapeCSVValue(value.value);
      }
      return value.value.toString();
    });
    return [escapeCSVValue(label), ...values].join(",");
  });
  return [header, ...rows].join("\n");
};
 
export const csvToScriptDataTable = (
  csv: string,
  constants: Constant[],
  availableVariables: DataTableCSVVariable[],
): ScriptDataTableImport => {
  const reverseConstantsLookup = Object.fromEntries(
    constants.map((constant, constantIndex) => [
      constantName(constant, constantIndex),
      constant.id,
    ]),
  );
 
  const csvRows = parseCSV(csv);
  Iif (csvRows.length === 0) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_NO_ROW_DATA"));
  }
 
  const [header, ...rows] = csvRows;
  const parsedVariables = header
    .slice(1)
    .map((value) => parseCSVVariable(value.trim()));
  const newVariablesLookup = new Map<string, NewDataTableCSVVariable>();
  const variables = parsedVariables.map<ScriptVariableElement>(
    ({ name, index }) => {
      Iif (!name) {
        throw new Error(l10n("ERROR_DATA_TABLE_CSV_INVALID"));
      }
      Iif (index !== undefined && index < 0) {
        throw new Error(
          l10n("ERROR_DATA_TABLE_CSV_ARRAY_INDEX", { name, index }),
        );
      }
      const expectedType: VariableType =
        index === undefined ? "number" : "array";
      const existingVariable = resolveCSVVariable(
        name,
        index,
        availableVariables,
      );
      if (existingVariable) {
        return {
          type: "variable",
          value: existingVariable.id,
          index:
            index === undefined ? undefined : { type: "number", value: index },
        };
      }
 
      const previousNewVariable = newVariablesLookup.get(name);
      if (previousNewVariable && previousNewVariable.type !== expectedType) {
        throw new Error(l10n("ERROR_DATA_TABLE_CSV_VARIABLE_TYPE", { name }));
      }
      const newVariable = previousNewVariable ?? {
        placeholder: `__new_variable_${newVariablesLookup.size}`,
        name,
        type: expectedType,
        length: expectedType === "array" ? 1 : undefined,
      };
      if (index !== undefined) {
        newVariable.length = Math.max(newVariable.length ?? 1, index + 1);
      }
      newVariablesLookup.set(name, newVariable);
      return {
        type: "variable",
        value: newVariable.placeholder,
        index:
          index === undefined ? undefined : { type: "number", value: index },
      };
    },
  );
 
  const dataRows = rows.map(([label = "", ...values]) => {
    return {
      label: label.trim(),
      values: variables.map((_, index) =>
        parseCSVCellValue(values[index], reverseConstantsLookup),
      ),
    };
  });
  const dataTable: ScriptDataTable = {
    label: header[0].trim() || undefined,
    variables,
    rows: dataRows,
  };
 
  Iif (!isScriptDataTable(dataTable)) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_INVALID"));
  }
 
  if (dataTable.variables.length === 0) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_NO_VARIABLES"));
  }
 
  if (dataTable.rows.length === 0) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_NO_ROW_DATA"));
  }
 
  return {
    dataTable,
    newVariables: Array.from(newVariablesLookup.values()),
  };
};