linshenkx/prompt-optimizer · error · Error

variables.importer.errors.invalidVariableName

Error message

variables.importer.errors.invalidVariableName

What it means

While iterating CSV data rows, each variable name must match /^[a-zA-Z_][a-zA-Z0-9_]*$/ — it must start with a letter or underscore and contain only letters, digits, and underscores. A row whose name cell violates this (e.g. contains a dot, dash, space, or starts with a digit) aborts the entire import with this error, echoing the offending name.

Source

Thrown at packages/ui/src/components/variable/VariableImporter.vue:273

  const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
  const nameIndex = headers.findIndex(h => ['name', 'key', 'variable'].includes(h.toLowerCase()))
  const valueIndex = headers.findIndex(h => ['value', 'val'].includes(h.toLowerCase()))
  
  if (nameIndex === -1 || valueIndex === -1) {
    throw new Error(t('variables.importer.errors.csvRequiredColumns'))
  }
  
  const variables: Record<string, string> = {}
  
  for (let i = 1; i < lines.length; i++) {
    const cells = lines[i].split(',').map(c => c.trim().replace(/"/g, ''))
    if (cells.length > Math.max(nameIndex, valueIndex)) {
      const name = cells[nameIndex]
      const value = cells[valueIndex]
      if (name && value !== undefined) {
        // 验证变量名格式
        if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
          throw new Error(t('variables.importer.errors.invalidVariableName', { name }))
        }
        variables[name] = value
      }
    }
  }
  
  return variables
}

const parseTxtVariables = (content: string): Record<string, string> => {
  const variables: Record<string, string> = {}
  const lines = content.trim().split('\n')
  
  for (const line of lines) {
    const trimmedLine = line.trim()
    if (!trimmedLine || trimmedLine.startsWith('#')) continue
    
    const separatorIndex = Math.max(

View on GitHub (pinned to 3e677b1d9f)

Solutions

  1. Fix the offending variable name in the CSV to match ^[a-zA-Z_][a-zA-Z0-9_]*$ (use underscore instead of dash/space).
  2. Sanitize names during import instead of throwing: name = name.replace(/[^a-zA-Z0-9_]/g, '_') with a warning, if business rules allow.
  3. Collect all invalid names first and report them together rather than failing on the first one.

Example fix

// before
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
  throw new Error(t('variables.importer.errors.invalidVariableName', { name }))
}
// after (sanitize or skip)
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
  invalidNames.push(name)
  continue
}
Defensive patterns

Strategy: validation

Validate before calling

const VALID_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/
const rows = parseRows(content)
const invalid = rows.filter(r => r.name && !VALID_NAME.test(r.name))
if (invalid.length) {
  showError(`Invalid variable names: ${invalid.map(r => r.name).join(', ')}`)
  return
}

Type guard

const isValidVariableName = (name: string): boolean =>
  /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)

Try / catch

try { parseCsvVariables(content) } catch (e) { if (e instanceof Error && e.message.includes('invalidVariableName')) { /* extract name, offer to auto-replace invalid chars with '_' */ } else throw e }

Prevention

When it happens

Trigger: A CSV row like 'my-var,value', '1key,value', 'user name,value', or a name cell with invisible characters/BOM. Note only rows where the name cell is truthy are validated, so empty name cells are silently skipped.

Common situations: Names imported from systems that allow dashes or dots (env-file exporters, spreadsheet users typing 'First Name'), localized keyboards inserting non-ASCII characters, or trailing whitespace inside quotes.

Related errors


AI-assisted analysis of linshenkx/prompt-optimizer@3e677b1d9f (2026-08-27). Data as JSON: /api/errors/ceb0fc74ab6ad0e2. Report an issue: GitHub.