Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

fix(semrush): decode quoted CSV reports without corrupting fields

Rudy Celekli88a4923633a6
diff --git a/tests/semrush-csv.test.cjs b/tests/semrush-csv.test.cjs
new file mode 100644
index 0000000..a0b1a83
--- /dev/null
+++ b/tests/semrush-csv.test.cjs
@@ -0,0 +1,26 @@
+const { test } = require('node:test')
+const assert = require('node:assert/strict')
+const { spawnSync } = require('node:child_process')
+const path = require('node:path')
+
+const cli = path.resolve(__dirname, '../tools/clis/semrush.js')
+function run(csv, options = {}) {
+ const source = `global.fetch = async () => ({ok: ${options.ok !== false}, status: ${options.status || 200}, text: async () => ${JSON.stringify(csv)}}); process.argv = ['node', ${JSON.stringify(cli)}, 'domain', 'organic', '--domain', 'example.com']; require(${JSON.stringify(cli)});`
+ const result = spawnSync(process.execPath, ['-e', source], {encoding: 'utf8', env: {...process.env, SEMRUSH_API_KEY: 'fixture-key'}})
+ assert.equal(result.status, 0, result.stderr)
+ return JSON.parse(result.stdout)
+}
+test('export_escape quoted headers and values become clean JSON fields', () => {
+ assert.deepEqual(run('"Keyword";"Position"\r\n"summer shoes";"3"\r\n'), [{'Keyword':'summer shoes','Position':'3'}])
+})
+test('semicolon, doubled quote, and line breaks inside quotes stay in their cell', () => {
+ assert.deepEqual(run('"Keyword";"URL"\r\n"say ""hello""; today\nnew line";"https://example.com/a;b"\r\n'), [{'Keyword':'say "hello"; today\nnew line','URL':'https://example.com/a;b'}])
+})
+test('unquoted reports, empty cells and blank rows retain their semantics', () => {
+ assert.deepEqual(run('Keyword;Position;URL\r\n shoes ;0;\r\n\r\n'), [{'Keyword':' shoes ','Position':'0','URL':''}])
+})
+test('header-only reports remain empty and provider errors remain diagnostics', () => {
+ assert.deepEqual(run('"Keyword";"Position"\r\n'), [])
+ assert.deepEqual(run('ERROR 50 :: NOTHING FOUND'), {error:'ERROR 50 :: NOTHING FOUND'})
+ assert.deepEqual(run('invalid key', {ok:false,status:403}), {error:'invalid key',status:403})
+})
diff --git a/tools/clis/semrush.js b/tools/clis/semrush.js
index 8ba985c..9e5adf7 100755
--- a/tools/clis/semrush.js
+++ b/tools/clis/semrush.js
@@ -9,20 +9,39 @@ if (!API_KEY) {
}
function parseCSV(text) {
- const lines = text.trim().split('\n')
- if (lines.length < 2) return []
- const headers = lines[0].split(';')
- const rows = []
- for (let i = 1; i < lines.length; i++) {
- if (!lines[i].trim()) continue
- const values = lines[i].split(';')
- const row = {}
- for (let j = 0; j < headers.length; j++) {
- row[headers[j]] = values[j] || ''
+ const records = []
+ let values = []
+ let value = ''
+ let quoted = false
+ const finishRecord = () => {
+ values.push(value)
+ if (values.some(cell => cell.trim())) records.push(values)
+ values = []
+ value = ''
+ }
+ for (let i = 0; i < text.length; i++) {
+ const char = text[i]
+ if (char === '"') {
+ if (quoted && text[i + 1] === '"') {
+ value += '"'
+ i++
+ } else {
+ quoted = !quoted
+ }
+ } else if (!quoted && char === ';') {
+ values.push(value)
+ value = ''
+ } else if (!quoted && (char === '\n' || char === '\r')) {
+ finishRecord()
+ if (char === '\r' && text[i + 1] === '\n') i++
+ } else {
+ value += char
}
- rows.push(row)
}
- return rows
+ if (value || values.length) finishRecord()
+ const [headers, ...rows] = records
+ if (!headers) return []
+ return rows.map(cells => Object.fromEntries(headers.map((header, index) => [header, cells[index] || ''])))
}
async function api(params) {
diff --git a/tools/integrations/semrush.md b/tools/integrations/semrush.md
index 2c3d7fd..06009e0 100644
--- a/tools/integrations/semrush.md
+++ b/tools/integrations/semrush.md
@@ -119,3 +119,9 @@ Use country code: `us`, `uk`, `de`, `fr`, `ca`, `au`, etc.
- programmatic-seo
- content-strategy
- competitors
+
+### CLI CSV decoding
+
+The [Semrush CLI](../clis/semrush.js) requests `export_escape=1` and decodes the
+semicolon-separated report into JSON objects. Quoted headers/cells, escaped
+quotes, and line breaks inside cells are preserved as field values.