Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

test(server): Resolves the remaining server-side gaps from #125. (#256)

Pallavi Kumaridbc0e185b2e1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7e72474dd..0db7b6cc4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -29,7 +29,7 @@ jobs:
- name: Vitest tests
run: yarn test
server:
- name: server — lint & format
+ name: server — lint, format & test
runs-on: ubuntu-latest
defaults:
run:
@@ -44,3 +44,5 @@ jobs:
- run: npm ci
- run: npm run lint
- run: npm run format:check
+ - name: Vitest tests
+ run: npm run test
diff --git a/server/src/lib/cloro-scraper.test.js b/server/src/lib/cloro-scraper.test.js
new file mode 100644
index 000000000..292deb86c
--- /dev/null
+++ b/server/src/lib/cloro-scraper.test.js
@@ -0,0 +1,172 @@
+import { describe, it, expect } from 'vitest';
+import { parseScraperResponse } from './cloro-scraper.js';
+
+describe('cloro-scraper – parseScraperResponse', () => {
+ describe('chatgpt-shopping', () => {
+ it('should parse text, citations, model, shopping_cards and inline_products', () => {
+ const result = {
+ markdown: 'Hello shopping world',
+ model: 'gpt-5-3-mini',
+ sources: [
+ { url: 'https://a.com', label: 'A' },
+ { url: 'https://b.com', label: 'B' },
+ ],
+ shoppingCards: [{ id: 'card1' }],
+ inlineProducts: [{ id: 'prod1' }],
+ };
+
+ const parsed = parseScraperResponse(result, 'chatgpt-shopping');
+
+ expect(parsed.text).toBe('Hello shopping world');
+ expect(parsed.citations).toEqual([
+ { url: 'https://a.com', title: 'A', startIndex: 0, endIndex: 50 },
+ { url: 'https://b.com', title: 'B', startIndex: 100, endIndex: 150 },
+ ]);
+ expect(parsed.model).toBe('gpt-5-3-mini');
+ expect(parsed.shopping_cards).toEqual([{ id: 'card1' }]);
+ expect(parsed.inline_products).toEqual([{ id: 'prod1' }]);
+ });
+
+ it('should fall back to text when markdown is missing', () => {
+ const result = { text: 'fallback text', sources: [] };
+ const parsed = parseScraperResponse(result, 'chatgpt-shopping');
+ expect(parsed.text).toBe('fallback text');
+ });
+
+ it('should default model to gpt-5-3-mini when missing', () => {
+ const result = { markdown: 'hi', sources: [] };
+ const parsed = parseScraperResponse(result, 'chatgpt-shopping');
+ expect(parsed.model).toBe('gpt-5-3-mini');
+ });
+
+ it('should default shopping_cards and inline_products to empty arrays', () => {
+ const result = { markdown: 'hi', sources: [] };
+ const parsed = parseScraperResponse(result, 'chatgpt-shopping');
+ expect(parsed.shopping_cards).toEqual([]);
+ expect(parsed.inline_products).toEqual([]);
+ });
+ });
+
+ describe('google-aio', () => {
+ it('should parse aioverview text and citations', () => {
+ const result = {
+ aioverview: {
+ markdown: 'AI overview text',
+ sources: [{ url: 'https://x.com', label: 'X' }],
+ },
+ };
+
+ const parsed = parseScraperResponse(result, 'google-aio');
+
+ expect(parsed.text).toBe('AI overview text');
+ expect(parsed.citations).toEqual([
+ { url: 'https://x.com', title: 'X', startIndex: 0, endIndex: 50 },
+ ]);
+ expect(parsed.model).toBe('google-aio');
+ expect(parsed.shopping_cards).toEqual([]);
+ });
+
+ it('should fall back to text inside aioverview when markdown is missing', () => {
+ const result = {
+ aioverview: {
+ text: 'fallback aio text',
+ sources: [],
+ },
+ };
+
+ const parsed = parseScraperResponse(result, 'google-aio');
+ expect(parsed.text).toBe('fallback aio text');
+ });
+
+ it('should throw when aioverview is missing', () => {
+ const result = { markdown: 'no aioverview here', sources: [] };
+ expect(() => parseScraperResponse(result, 'google-aio')).toThrow(
+ 'Google did not return an AI Overview for this query',
+ );
+ });
+ });
+
+ describe('google-aimode', () => {
+ it('should use result.result when present', () => {
+ const inner = {
+ markdown: 'ai mode text',
+ sources: [{ url: 'https://y.com', label: 'Y' }],
+ shoppingCards: [{ sku: 'abc' }],
+ };
+
+ const parsed = parseScraperResponse({ result: inner }, 'google-aimode');
+
+ expect(parsed.text).toBe('ai mode text');
+ expect(parsed.citations).toEqual([
+ { url: 'https://y.com', title: 'Y', startIndex: 0, endIndex: 50 },
+ ]);
+ expect(parsed.model).toBe('google-aimode');
+ expect(parsed.shopping_cards).toEqual([{ sku: 'abc' }]);
+ });
+
+ it('should fall back to root result when result.result is absent', () => {
+ const result = {
+ markdown: 'root aimode text',
+ sources: [{ url: 'https://z.com', label: 'Z' }],
+ shoppingCards: [],
+ };
+
+ const parsed = parseScraperResponse(result, 'google-aimode');
+ expect(parsed.text).toBe('root aimode text');
+ expect(parsed.citations).toEqual([
+ { url: 'https://z.com', title: 'Z', startIndex: 0, endIndex: 50 },
+ ]);
+ expect(parsed.shopping_cards).toEqual([]);
+ });
+
+ it('should normalize missing sources to empty array', () => {
+ const result = { result: { markdown: 'no sources', shoppingCards: [] } };
+ const parsed = parseScraperResponse(result, 'google-aimode');
+ expect(parsed.citations).toEqual([]);
+ });
+ });
+
+ describe('default / other providers', () => {
+ it('should parse text, citations and model', () => {
+ const result = {
+ markdown: 'generic text',
+ model: 'gpt-4',
+ sources: [
+ { url: 'https://foo.com', label: 'Foo' },
+ { url: 'https://bar.com', label: 'Bar' },
+ ],
+ shopping_cards: [{ id: 's1' }],
+ };
+
+ const parsed = parseScraperResponse(result, 'perplexity-web');
+
+ expect(parsed.text).toBe('generic text');
+ expect(parsed.citations).toEqual([
+ { url: 'https://foo.com', title: 'Foo', startIndex: 0, endIndex: 50 },
+ { url: 'https://bar.com', title: 'Bar', startIndex: 100, endIndex: 150 },
+ ]);
+ expect(parsed.model).toBe('gpt-4');
+ expect(parsed.shopping_cards).toEqual([{ id: 's1' }]);
+ });
+
+ it('should fall back to text when markdown is missing', () => {
+ const parsed = parseScraperResponse({ text: 'text only', sources: [] }, 'copilot-web');
+ expect(parsed.text).toBe('text only');
+ });
+
+ it('should fall back to scraperId as model when model is missing', () => {
+ const parsed = parseScraperResponse({ markdown: 'no model', sources: [] }, 'grok-web');
+ expect(parsed.model).toBe('grok-web');
+ });
+
+ it('should normalize missing sources to empty citations', () => {
+ const parsed = parseScraperResponse({ markdown: 'no sources', model: 'x' }, 'gemini-web');
+ expect(parsed.citations).toEqual([]);
+ });
+
+ it('should default shopping_cards to empty array when neither key is present', () => {
+ const parsed = parseScraperResponse({ markdown: 'no cards', sources: [] }, 'gemini-web');
+ expect(parsed.shopping_cards).toEqual([]);
+ });
+ });
+});
diff --git a/server/src/lib/cloro-webhook-verify.test.js b/server/src/lib/cloro-webhook-verify.test.js
new file mode 100644
index 000000000..973032049
--- /dev/null
+++ b/server/src/lib/cloro-webhook-verify.test.js
@@ -0,0 +1,129 @@
+import { describe, it, expect } from 'vitest';
+import { verifyCloroWebhook } from './cloro-webhook-verify.js';
+
+function buildSignature(secret, rawBody, timestamp) {
+ const hmac = require('crypto')
+ .createHmac('sha256', secret)
+ .update(`${timestamp}.`)
+ .update(rawBody)
+ .digest('hex');
+ return `v1=${hmac}`;
+}
+
+describe('cloro-webhook-verify', () => {
+ const secret = 'whsec_test_secret';
+ const rawBody = Buffer.from('{"event":"test"}');
+
+ it('should verify a valid webhook signature', () => {
+ const now = 1_700_000_000_000;
+ const ts = Math.floor(now / 1000);
+ const sig = buildSignature(secret, rawBody, ts);
+
+ const result = verifyCloroWebhook({
+ rawBody,
+ signatureHeader: sig,
+ timestampHeader: String(ts),
+ secret,
+ nowMs: now,
+ });
+
+ expect(result.ok).toBe(true);
+ });
+
+ it('should reject missing signature header', () => {
+ const result = verifyCloroWebhook({
+ rawBody,
+ signatureHeader: undefined,
+ timestampHeader: '1700000000',
+ secret,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.status).toBe(401);
+ expect(result.reason).toBe('missing signature headers');
+ });
+
+ it('should reject missing timestamp header', () => {
+ const result = verifyCloroWebhook({
+ rawBody,
+ signatureHeader: 'v1=abc',
+ timestampHeader: undefined,
+ secret,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.status).toBe(401);
+ expect(result.reason).toBe('missing signature headers');
+ });
+
+ it('should reject an invalid timestamp', () => {
+ const result = verifyCloroWebhook({
+ rawBody,
+ signatureHeader: 'v1=abc',
+ timestampHeader: 'not-a-number',
+ secret,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.status).toBe(400);
+ expect(result.reason).toBe('invalid timestamp');
+ });
+
+ it('should reject a stale timestamp', () => {
+ const now = 1_700_000_000_000;
+ const staleTs = Math.floor(now / 1000) - 600;
+ const sig = buildSignature(secret, rawBody, staleTs);
+
+ const result = verifyCloroWebhook({
+ rawBody,
+ signatureHeader: sig,
+ timestampHeader: String(staleTs),
+ secret,
+ nowMs: now,
+ toleranceSeconds: 300,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.status).toBe(400);
+ expect(result.reason).toBe('stale timestamp');
+ });
+
+ it('should reject a signature mismatch', () => {
+ const now = 1_700_000_000_000;
+ const ts = Math.floor(now / 1000);
+ const badSig = 'v1=0000000000000000000000000000000000000000000000000000000000000000';
+
+ const result = verifyCloroWebhook({
+ rawBody,
+ signatureHeader: badSig,
+ timestampHeader: String(ts),
+ secret,
+ nowMs: now,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.status).toBe(401);
+ expect(result.reason).toBe('signature mismatch');
+ });
+
+ it('should strip v1= prefix from signature', () => {
+ const now = 1_700_000_000_000;
+ const ts = Math.floor(now / 1000);
+ const hmac = require('crypto')
+ .createHmac('sha256', secret)
+ .update(`${ts}.`)
+ .update(rawBody)
+ .digest('hex');
+ const sig = `v1=${hmac}`;
+
+ const result = verifyCloroWebhook({
+ rawBody,
+ signatureHeader: sig,
+ timestampHeader: String(ts),
+ secret,
+ nowMs: now,
+ });
+
+ expect(result.ok).toBe(true);
+ });
+});
diff --git a/server/src/lib/dataforseo-codes.test.js b/server/src/lib/dataforseo-codes.test.js
new file mode 100644
index 000000000..0bf9a7ed1
--- /dev/null
+++ b/server/src/lib/dataforseo-codes.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest';
+import { regionToLocationCode, languageToCode } from './dataforseo-codes.js';
+
+describe('dataforseo-codes', () => {
+ describe('regionToLocationCode', () => {
+ it('should map uppercase region codes', () => {
+ expect(regionToLocationCode('US')).toBe(2840);
+ expect(regionToLocationCode('GB')).toBe(2826);
+ expect(regionToLocationCode('DE')).toBe(2276);
+ });
+
+ it('should be case-insensitive', () => {
+ expect(regionToLocationCode('us')).toBe(2840);
+ expect(regionToLocationCode('gb')).toBe(2826);
+ expect(regionToLocationCode('De')).toBe(2276);
+ });
+
+ it('should return undefined for unknown regions', () => {
+ expect(regionToLocationCode('XX')).toBeUndefined();
+ expect(regionToLocationCode('Mars')).toBeUndefined();
+ });
+
+ it('should return undefined for null/undefined input', () => {
+ expect(regionToLocationCode(null)).toBeUndefined();
+ expect(regionToLocationCode(undefined)).toBeUndefined();
+ expect(regionToLocationCode('')).toBeUndefined();
+ });
+ });
+
+ describe('languageToCode', () => {
+ it('should map supported language codes', () => {
+ expect(languageToCode('en')).toBe('en');
+ expect(languageToCode('de')).toBe('de');
+ expect(languageToCode('ja')).toBe('ja');
+ });
+
+ it('should be case-insensitive', () => {
+ expect(languageToCode('EN')).toBe('en');
+ expect(languageToCode('De')).toBe('de');
+ expect(languageToCode('JA')).toBe('ja');
+ });
+
+ it('should return undefined for unsupported languages', () => {
+ expect(languageToCode('zh')).toBeUndefined();
+ expect(languageToCode('pt-br')).toBeUndefined();
+ });
+
+ it('should return undefined for null/undefined input', () => {
+ expect(languageToCode(null)).toBeUndefined();
+ expect(languageToCode(undefined)).toBeUndefined();
+ expect(languageToCode('')).toBeUndefined();
+ });
+ });
+});
diff --git a/server/src/lib/shopping-cards.test.js b/server/src/lib/shopping-cards.test.js
index 38f11149c..2d0040cae 100644
--- a/server/src/lib/shopping-cards.test.js
+++ b/server/src/lib/shopping-cards.test.js
@@ -1,5 +1,11 @@
import { describe, it, expect } from 'vitest';
-import { normalizeShoppingCards, parseCopilotCard } from './shopping-cards.js';
+import {
+ parsePerplexityCard,
+ parseAiModeCard,
+ parseCopilotCard,
+ normalizeShoppingCards,
+ matchCardBrand,
+} from './shopping-cards.js';
// The documented Copilot response shape: a `shoppingProducts` wrapper whose
// `products[]` holds the real cards. See Cloro docs — "Shopping cards".
@@ -21,8 +27,6 @@ const copilotWrapper = {
canTrackPrice: true,
},
{
- // Real-world TR shape: no `currency`, only `currencySymbol`; brand only
- // present in the name; rating absent.
position: 2,
url: 'https://www.occasion.com.tr/nike-air-max-1-kadin-beyaz-sneaker/?utm_source=copilot.com',
name: 'Nike W Air Max 1 Kadın Beyaz Sneaker',
@@ -41,7 +45,7 @@ describe('normalizeShoppingCards — Copilot wrapper', () => {
expect(cards).toHaveLength(2);
});
- it('extracts the product title from `name` (not "Unknown Product")', () => {
+ it('extracts the product title from `name`', () => {
expect(cards[0].product_title).toBe('Microsoft Surface Laptop Studio 2');
expect(cards[1].product_title).toBe('Nike W Air Max 1 Kadın Beyaz Sneaker');
});
@@ -54,7 +58,7 @@ describe('normalizeShoppingCards — Copilot wrapper', () => {
expect(cards[0].price_amount).toBe(1999.99);
expect(cards[0].price_currency).toBe('USD');
expect(cards[1].price_amount).toBe(4720);
- expect(cards[1].price_currency).toBe('TRY'); // derived from "₺"
+ expect(cards[1].price_currency).toBe('TRY');
});
it('reads the first image url + merchant domain', () => {
@@ -83,3 +87,154 @@ describe('parseCopilotCard — bare product (already flat)', () => {
expect(card.position).toBe(0);
});
});
+
+describe('shopping-cards – parsePerplexityCard', () => {
+ it('should map snake_case fields', () => {
+ const card = {
+ title: 'Widget',
+ brand: 'Acme',
+ price: '$19.99',
+ image_url: 'https://img.example.com/x.jpg',
+ url: 'https://shop.example.com/p/1',
+ rating: 4.5,
+ review_count: 120,
+ };
+ const result = parsePerplexityCard(card, 0);
+ expect(result.product_title).toBe('Widget');
+ expect(result.product_brand).toBe('Acme');
+ expect(result.price_amount).toBeCloseTo(19.99);
+ expect(result.price_currency).toBe('USD');
+ expect(result.merchant_domain).toBe('shop.example.com');
+ expect(result.rating).toBeCloseTo(4.5);
+ expect(result.review_count).toBe(120);
+ expect(result.position).toBe(0);
+ });
+
+ it('should fall back to alternate title/brand keys', () => {
+ const card = {
+ name: 'Gadget',
+ merchant: 'Acme Inc',
+ price: null,
+ image: null,
+ link: null,
+ };
+ const result = parsePerplexityCard(card, 2);
+ expect(result.product_title).toBe('Gadget');
+ expect(result.product_brand).toBe('Acme Inc');
+ });
+});
+
+describe('shopping-cards – parseAiModeCard', () => {
+ it('should map camelCase fields', () => {
+ const card = {
+ title: 'Gadget',
+ brand: 'Acme',
+ price: 'EUR 29,90',
+ imageUrl: 'https://img.example.com/y.jpg',
+ url: 'https://store.example.com/p/2',
+ rating: '4.0',
+ reviewCount: '80',
+ };
+ const result = parseAiModeCard(card, 1);
+ expect(result.product_title).toBe('Gadget');
+ expect(result.product_brand).toBe('Acme');
+ expect(result.price_amount).toBeCloseTo(29.9);
+ expect(result.price_currency).toBe('EUR');
+ expect(result.rating).toBeCloseTo(4.0);
+ expect(result.review_count).toBe(80);
+ });
+});
+
+describe('shopping-cards – parseCopilotCard', () => {
+ it('should map Copilot-specific camelCase fields', () => {
+ const card = {
+ productName: 'Thing',
+ productBrand: 'Acme Co',
+ price: 39.99,
+ imageUrl: null,
+ productUrl: 'https://acme.co/item/3',
+ rating: 3.5,
+ reviewsCount: 42,
+ };
+ const result = parseCopilotCard(card, 3);
+ expect(result.product_title).toBe('Thing');
+ expect(result.product_brand).toBe('Acme Co');
+ expect(result.price_amount).toBeCloseTo(39.99);
+ expect(result.merchant_domain).toBe('acme.co');
+ expect(result.review_count).toBe(42);
+ });
+});
+
+describe('shopping-cards – normalizeShoppingCards', () => {
+ it('should return [] for non-array input', () => {
+ expect(normalizeShoppingCards('perplexity-web', null)).toEqual([]);
+ expect(normalizeShoppingCards('perplexity-web', undefined)).toEqual([]);
+ expect(normalizeShoppingCards('perplexity-web', '')).toEqual([]);
+ });
+
+ it('should return [] for unsupported platforms', () => {
+ expect(normalizeShoppingCards('chatgpt-web', [{ title: 'X' }])).toEqual([]);
+ });
+
+ it('should normalize an array of Perplexity cards', () => {
+ const cards = [
+ { title: 'A', brand: 'B', price: '$1', url: 'https://a.com', rating: 5, review_count: 10 },
+ null,
+ 'not-an-object',
+ ];
+ const result = normalizeShoppingCards('perplexity-web', cards);
+ expect(result).toHaveLength(1);
+ expect(result[0].product_title).toBe('A');
+ expect(result[0].position).toBe(0);
+ });
+});
+
+describe('shopping-cards – matchCardBrand', () => {
+ const brand = { brandId: 'brand-1', brandName: 'Acme', domains: ['acme.com'] };
+ const competitors = [{ id: 'comp-1', name: 'Globex', domain: 'globex.com' }];
+
+ it('should match brand by product_title', () => {
+ const card = { product_title: 'Acme Widget', merchant_domain: null };
+ expect(matchCardBrand(card, brand, competitors)).toEqual({
+ matched_brand_id: 'brand-1',
+ matched_brand_role: 'own',
+ });
+ });
+
+ it('should match brand by merchant_domain', () => {
+ const card = { product_title: 'Random', merchant_domain: 'acme.com' };
+ expect(matchCardBrand(card, brand, competitors)).toEqual({
+ matched_brand_id: 'brand-1',
+ matched_brand_role: 'own',
+ });
+ });
+
+ it('should match competitor by name', () => {
+ const card = { product_title: 'Globex Thing', merchant_domain: null };
+ expect(matchCardBrand(card, brand, competitors)).toEqual({
+ matched_brand_id: 'comp-1',
+ matched_brand_role: 'competitor',
+ });
+ });
+
+ it('should match competitor by domain', () => {
+ const card = { product_title: 'Random', merchant_domain: 'globex.com' };
+ expect(matchCardBrand(card, brand, competitors)).toEqual({
+ matched_brand_id: 'comp-1',
+ matched_brand_role: 'competitor',
+ });
+ });
+
+ it('should return other when no match', () => {
+ const card = { product_title: 'Unknown', merchant_domain: 'other.com' };
+ expect(matchCardBrand(card, brand, competitors)).toEqual({
+ matched_brand_id: null,
+ matched_brand_role: 'other',
+ });
+ });
+
+ it('should be case-insensitive for brand name matching', () => {
+ const card = { product_title: 'ACME product', merchant_domain: null };
+ expect(matchCardBrand(card, brand, competitors).matched_brand_role).toBe('own');
+ });
+});
diff --git a/server/src/lib/tracking-pipeline.test.js b/server/src/lib/tracking-pipeline.test.js
new file mode 100644
index 000000000..d2488e617
--- /dev/null
+++ b/server/src/lib/tracking-pipeline.test.js
@@ -0,0 +1,127 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { runPrompt } from './openai-tracker.js';
+import { parseResponse } from './response-parser.js';
+
+vi.mock('./openai-tracker.js', () => ({
+ runPrompt: vi.fn(),
+}));
+
+describe('test-tracking pipeline (mocked)', () => {
+ const brand = {
+ brandName: 'Empler AI',
+ domains: ['empler.ai'],
+ };
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it('should parse a tracked response with brand mentions and citations', async () => {
+ const mockResponse = {
+ text: 'Empler AI is a great platform for automation. Visit empler.ai for more.',
+ citations: [
+ { url: 'https://empler.ai/about', title: 'Empler AI About' },
+ { url: 'https://other.com/review', title: 'Review' },
+ ],
+ model: 'gpt-5-chat-latest',
+ };
+
+ runPrompt.mockResolvedValue(mockResponse);
+
+ const response = await runPrompt('Best AI automation platforms');
+ const metrics = parseResponse(response, brand);
+
+ expect(metrics.mentionCount).toBeGreaterThan(0);
+ expect(metrics.citationCount).toBeGreaterThanOrEqual(0);
+ expect(metrics.visibilityScore).toBeGreaterThanOrEqual(0);
+ expect(metrics.visibilityScore).toBeLessThanOrEqual(100);
+ });
+
+ it('should handle a response with no brand mentions', async () => {
+ const mockResponse = {
+ text: 'Some other platform is popular in this space.',
+ citations: [{ url: 'https://other.com', title: 'Other' }],
+ model: 'gpt-5-chat-latest',
+ };
+
+ runPrompt.mockResolvedValue(mockResponse);
+
+ const response = await runPrompt('Best AI automation platforms');
+ const metrics = parseResponse(response, brand);
+
+ expect(metrics.mentionCount).toBe(0);
+ expect(metrics.citationCount).toBe(0);
+ expect(metrics.visibilityScore).toBe(0);
+ expect(metrics.sentiment).toBe('neutral');
+ });
+
+ it('should handle a response with brand mentions but no citations', async () => {
+ const mockResponse = {
+ text: 'Empler AI offers strong automation features.',
+ citations: [],
+ model: 'gpt-5-chat-latest',
+ };
+
+ runPrompt.mockResolvedValue(mockResponse);
+
+ const response = await runPrompt('Best AI automation platforms');
+ const metrics = parseResponse(response, brand);
+
+ expect(metrics.mentionCount).toBeGreaterThan(0);
+ expect(metrics.citationCount).toBe(0);
+ });
+
+ it('should handle a response with citations but no brand mentions', async () => {
+ const mockResponse = {
+ text: 'Several tools exist for this use case.',
+ citations: [
+ { url: 'https://other.com', title: 'Other Tool' },
+ { url: 'https://another.com', title: 'Another' },
+ ],
+ model: 'gpt-5-chat-latest',
+ };
+
+ runPrompt.mockResolvedValue(mockResponse);
+
+ const response = await runPrompt('Best AI automation platforms');
+ const metrics = parseResponse(response, brand);
+
+ expect(metrics.mentionCount).toBe(0);
+ expect(metrics.citationCount).toBe(0);
+ expect(metrics.visibilityScore).toBe(0);
+ });
+
+ it('should correctly score a strong brand presence response', async () => {
+ const mockResponse = {
+ text: 'Empler AI, found at empler.ai, is the top choice. Empler AI leads the market.',
+ citations: [
+ { url: 'https://empler.ai', title: 'Empler AI' },
+ { url: 'https://news.com/empler-ai-review', title: 'Review' },
+ ],
+ model: 'gpt-5-chat-latest',
+ };
+
+ runPrompt.mockResolvedValue(mockResponse);
+
+ const response = await runPrompt('Best AI automation platforms');
+ const metrics = parseResponse(response, brand);
+
+ expect(metrics.mentionCount).toBeGreaterThanOrEqual(2);
+ expect(metrics.citationCount).toBeGreaterThanOrEqual(1);
+ expect(metrics.visibilityScore).toBeGreaterThan(30);
+ });
+
+ it('should pass through the model name from the response', async () => {
+ const mockResponse = {
+ text: 'Empler AI is great.',
+ citations: [],
+ model: 'gpt-5-chat-latest',
+ };
+
+ runPrompt.mockResolvedValue(mockResponse);
+
+ const response = await runPrompt('Best AI automation platforms');
+
+ expect(response.model).toBe('gpt-5-chat-latest');
+ });
+});
diff --git a/server/src/lib/volumes-pipeline.test.js b/server/src/lib/volumes-pipeline.test.js
new file mode 100644
index 000000000..8f66f91d1
--- /dev/null
+++ b/server/src/lib/volumes-pipeline.test.js
@@ -0,0 +1,97 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { getSearchVolumes } from './dataforseo.js';
+import { resolveModel } from './ai-provider.js';
+import { regionToLocationCode } from './dataforseo-codes.js';
+
+vi.mock('./dataforseo.js', () => ({
+ getSearchVolumes: vi.fn(),
+}));
+
+vi.mock('./ai-provider.js', () => ({
+ resolveModel: vi.fn(),
+}));
+
+const AI_VOLUME_MULTIPLIER = parseFloat(process.env.AI_VOLUME_MULTIPLIER || '0.15');
+
+describe('test-volumes pipeline (mocked)', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it('should fetch and return volumes from DataForSEO', async () => {
+ const mockVolumes = {
+ 'best crm software': { volume: 5000, competitionIndex: 80, competition: 'HIGH' },
+ 'crm tools comparison': { volume: 2000, competitionIndex: 60, competition: 'MEDIUM' },
+ };
+
+ getSearchVolumes.mockResolvedValue(mockVolumes);
+
+ const volumes = await getSearchVolumes(['best crm software', 'crm tools comparison'], {
+ locationCode: 2840,
+ languageCode: 'en',
+ });
+
+ expect(volumes).toEqual(mockVolumes);
+ expect(getSearchVolumes).toHaveBeenCalledTimes(1);
+ });
+
+ it('should compute estimated AI volume from Google volumes', async () => {
+ const mockVolumes = {
+ 'keyword one': { volume: 10000, competitionIndex: 70, competition: 'HIGH' },
+ 'keyword two': { volume: 5000, competitionIndex: 50, competition: 'MEDIUM' },
+ };
+
+ getSearchVolumes.mockResolvedValue(mockVolumes);
+
+ const volumes = await getSearchVolumes(['keyword one', 'keyword two']);
+ const totalGoogleVolume = Object.values(volumes).reduce((sum, v) => sum + v.volume, 0);
+ const estAiVolume = Math.round(totalGoogleVolume * AI_VOLUME_MULTIPLIER);
+
+ expect(totalGoogleVolume).toBe(15000);
+ expect(estAiVolume).toBeCloseTo(2250);
+ });
+
+ it('should handle zero volumes gracefully', async () => {
+ const mockVolumes = {
+ 'rare term': { volume: 0, competitionIndex: 0, competition: null },
+ };
+
+ getSearchVolumes.mockResolvedValue(mockVolumes);
+
+ const volumes = await getSearchVolumes(['rare term']);
+ const totalGoogleVolume = Object.values(volumes).reduce((sum, v) => sum + v.volume, 0);
+ const estAiVolume = Math.round(totalGoogleVolume * AI_VOLUME_MULTIPLIER);
+
+ expect(totalGoogleVolume).toBe(0);
+ expect(estAiVolume).toBe(0);
+ });
+
+ it('should map region codes correctly for DataForSEO', () => {
+ expect(regionToLocationCode('US')).toBe(2840);
+ expect(regionToLocationCode('GB')).toBe(2826);
+ expect(regionToLocationCode('DE')).toBe(2276);
+ });
+
+ it('should resolve the default model when no model string is provided', () => {
+ resolveModel.mockReturnValue('mock-model-instance');
+
+ const model = resolveModel();
+
+ expect(model).toBe('mock-model-instance');
+ });
+
+ it('should pass through keywords to getSearchVolumes', async () => {
+ getSearchVolumes.mockResolvedValue({});
+
+ const keywords = ['best crm software', 'crm tools comparison'];
+ await getSearchVolumes(keywords, {
+ locationCode: 2840,
+ languageCode: 'en',
+ });
+
+ expect(getSearchVolumes).toHaveBeenCalledWith(keywords, {
+ locationCode: 2840,
+ languageCode: 'en',
+ });
+ });
+});
diff --git a/server/src/test-tracking.js b/server/src/test-tracking.js
deleted file mode 100644
index a6e8dfa0f..000000000
--- a/server/src/test-tracking.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Quick test script for the prompt tracking pipeline.
- * Run: node src/test-tracking.js
- *
- * Tests: OpenAI Responses API (web_search) -> response parser -> console output
- * No Redis or Supabase required.
- */
-
-import 'dotenv/config';
-import { runPrompt } from './lib/openai-tracker.js';
-import { parseResponse } from './lib/response-parser.js';
-
-const TEST_PROMPT = 'Best AI automation platforms for sales and marketing teams';
-const TEST_BRAND = {
- brandName: 'Empler AI',
- domains: ['empler.ai'],
-};
-
-async function main() {
- console.log('=== Prompt Tracking Test ===\n');
- console.log(`Prompt: "${TEST_PROMPT}"`);
- console.log(`Brand: ${TEST_BRAND.brandName}`);
- console.log(`Domains: ${TEST_BRAND.domains.join(', ')}`);
- console.log(`Model: gpt-5-chat-latest (default)\n`);
- console.log('Calling OpenAI Responses API with web_search...\n');
-
- const startTime = Date.now();
-
- try {
- const response = await runPrompt(TEST_PROMPT);
- const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
-
- console.log(`--- Response (${elapsed}s) ---`);
- console.log(response.text.slice(0, 500));
- if (response.text.length > 500) console.log(`... (${response.text.length} chars total)`);
- console.log();
-
- console.log(`--- Citations (${response.citations.length}) ---`);
- for (const cite of response.citations.slice(0, 5)) {
- console.log(` ${cite.title || 'No title'}`);
- console.log(` ${cite.url}`);
- console.log();
- }
- if (response.citations.length > 5) {
- console.log(` ... and ${response.citations.length - 5} more`);
- }
-
- const metrics = parseResponse(response, TEST_BRAND);
- console.log('--- Metrics ---');
- console.log(` Mention Count: ${metrics.mentionCount}`);
- console.log(` Citation Count: ${metrics.citationCount}`);
- console.log(` Sentiment: ${metrics.sentiment}`);
- console.log(` Visibility Score: ${metrics.visibilityScore}/100`);
- console.log(` Model Used: ${response.model}`);
- console.log('\nTest completed successfully!');
- } catch (err) {
- console.error('Test failed:', err.message);
- if (err.message.includes('API key')) {
- console.error('\nMake sure OPENAI_API_KEY is set in .env');
- }
- process.exit(1);
- }
-}
-
-main();
diff --git a/server/src/test-volumes.js b/server/src/test-volumes.js
deleted file mode 100644
index bd957f941..000000000
--- a/server/src/test-volumes.js
+++ /dev/null
@@ -1,141 +0,0 @@
-import 'dotenv/config';
-import { generateObject } from 'ai';
-import { z } from 'zod';
-import { resolveModel } from './lib/ai-provider.js';
-import { getSearchVolumes } from './lib/dataforseo.js';
-
-const AI_VOLUME_MULTIPLIER = parseFloat(process.env.AI_VOLUME_MULTIPLIER || '0.15');
-
-const intentKeywordSchema = z.object({
- intent: z.enum([
- 'comparison',
- 'how-to',
- 'what-is',
- 'best-top',
- 'vs-review',
- 'recommendation',
- 'problem-solving',
- ]),
- keywords: z.array(z.string()).length(5),
-});
-
-const INTENT_SYSTEM_PROMPT = `You are a keyword research expert. Given an AI search prompt, you must:
-1. Determine the primary search intent (comparison, how-to, what-is, best-top, vs-review, recommendation, or problem-solving).
-2. Generate exactly 5 short keyword phrases (2-5 words each) that a user would type into Google when searching for the same topic.
-
-Rules:
-- Keywords must be generic — no brand names.
-- Keywords should be realistic, high-volume Google search queries.
-- Each keyword must be unique and cover a slightly different angle of the same topic.
-- Use lowercase only.`;
-
-async function testDataForSEO() {
- console.log('=== Test 1: DataForSEO Connection ===\n');
-
- try {
- const volumes = await getSearchVolumes(['best crm software', 'crm tools comparison'], {
- locationCode: 2840,
- languageCode: 'en',
- });
- console.log('DataForSEO volumes:', volumes);
- console.log('OK - DataForSEO connection works!\n');
- return true;
- } catch (err) {
- console.error('FAIL - DataForSEO error:', err.message, '\n');
- return false;
- }
-}
-
-async function testLLMExtraction() {
- console.log('=== Test 2: LLM Intent + Keyword Extraction ===\n');
-
- const testPrompt = 'Best CRM software for small businesses';
-
- try {
- const aiModel = resolveModel();
- const { object } = await generateObject({
- model: aiModel,
- schema: intentKeywordSchema,
- system: INTENT_SYSTEM_PROMPT,
- prompt: `Analyze this AI search prompt and extract intent + 5 Google keywords:\n\n"${testPrompt}"`,
- });
-
- console.log('Prompt:', testPrompt);
- console.log('Intent:', object.intent);
- console.log('Keywords:', object.keywords);
- console.log('OK - LLM extraction works!\n');
- return object;
- } catch (err) {
- console.error('FAIL - LLM error:', err.message, '\n');
- return null;
- }
-}
-
-async function testFullPipeline() {
- console.log('=== Test 3: Full Pipeline (LLM + DataForSEO + Calculation) ===\n');
-
- const testPrompt = 'How to improve website SEO ranking';
-
- try {
- const aiModel = resolveModel();
- const { object: intentResult } = await generateObject({
- model: aiModel,
- schema: intentKeywordSchema,
- system: INTENT_SYSTEM_PROMPT,
- prompt: `Analyze this AI search prompt and extract intent + 5 Google keywords:\n\n"${testPrompt}"`,
- });
-
- console.log('Prompt:', testPrompt);
- console.log('Intent:', intentResult.intent);
- console.log('Keywords:', intentResult.keywords);
-
- const volumes = await getSearchVolumes(intentResult.keywords, {
- locationCode: 2840,
- languageCode: 'en',
- });
-
- console.log('\nGoogle Volumes:');
- for (const [kw, data] of Object.entries(volumes)) {
- console.log(
- ` "${kw}": ${data.volume.toLocaleString()}/mo (competition: ${data.competition ?? 'n/a'})`,
- );
- }
-
- const totalGoogleVolume = Object.values(volumes).reduce((sum, v) => sum + v.volume, 0);
- const estAiVolume = Math.round(totalGoogleVolume * AI_VOLUME_MULTIPLIER);
-
- console.log(`\nTotal Google Volume: ${totalGoogleVolume.toLocaleString()}/mo`);
- console.log(
- `AI Multiplier: ${AI_VOLUME_MULTIPLIER} (${(AI_VOLUME_MULTIPLIER * 100).toFixed(0)}%)`,
- );
- console.log(`Est. AI Volume: ${estAiVolume.toLocaleString()}/mo`);
- console.log('\nOK - Full pipeline works!');
- } catch (err) {
- console.error('FAIL - Pipeline error:', err.message);
- }
-}
-
-async function main() {
- console.log('Prompt Volumes System - Test Suite\n');
- console.log(`DATAFORSEO_LOGIN: ${process.env.DATAFORSEO_LOGIN ? 'SET' : 'MISSING'}`);
- console.log(`DATAFORSEO_PASSWORD: ${process.env.DATAFORSEO_PASSWORD ? 'SET' : 'MISSING'}`);
- console.log(`AI_VOLUME_MULTIPLIER: ${AI_VOLUME_MULTIPLIER}`);
- console.log(`OPENAI_API_KEY: ${process.env.OPENAI_API_KEY ? 'SET' : 'MISSING'}`);
- console.log('');
-
- const dfOk = await testDataForSEO();
- if (!dfOk) {
- console.log('Stopping — fix DataForSEO credentials first.');
- process.exit(1);
- }
-
- const llmResult = await testLLMExtraction();
- if (!llmResult) {
- console.log('Stopping — fix AI provider config first.');
- process.exit(1);
- }
-
- await testFullPipeline();
-}
-
-main().catch(console.error);