seomd-cli 1.4.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/PROVIDER_SPEC.md +125 -0
  2. package/README.md +54 -190
  3. package/SKILL.md +44 -0
  4. package/bin/seomd.js +79 -31
  5. package/package.json +11 -7
  6. package/src/commands/analyze.js +90 -90
  7. package/src/commands/check.js +301 -0
  8. package/src/commands/doctor.js +109 -0
  9. package/src/commands/generate.js +215 -0
  10. package/src/commands/init.js +170 -66
  11. package/src/commands/status.js +92 -76
  12. package/src/commands/sync.js +84 -70
  13. package/src/commands/validate.js +52 -25
  14. package/src/generators/directory.js +46 -114
  15. package/src/generators/reverse.js +46 -56
  16. package/src/generators/seomd.js +226 -44
  17. package/src/providers/http.js +67 -0
  18. package/src/providers/index.js +194 -0
  19. package/src/utils/agent-wiring.js +97 -0
  20. package/src/utils/api-client.js +14 -56
  21. package/src/utils/constants.js +110 -12
  22. package/src/utils/migrate.js +99 -0
  23. package/src/utils/parser.js +114 -25
  24. package/src/utils/placeholders.js +31 -0
  25. package/src/utils/repo-scanner.js +207 -0
  26. package/src/utils/writeback.js +171 -82
  27. package/src/validators/seomd.js +263 -93
  28. package/scripts/release-contributors.js +0 -196
  29. package/scripts/release-notes.js +0 -194
  30. package/src/templates/blog/SEO.REVERSE.md +0 -176
  31. package/src/templates/blog/SEO.md +0 -233
  32. package/src/templates/ecommerce/SEO.REVERSE.md +0 -199
  33. package/src/templates/ecommerce/SEO.md +0 -239
  34. package/src/templates/local/SEO.REVERSE.md +0 -222
  35. package/src/templates/local/SEO.md +0 -245
  36. package/src/templates/marketplace/SEO.REVERSE.md +0 -222
  37. package/src/templates/marketplace/SEO.md +0 -245
  38. package/src/templates/saas/SEO.REVERSE.md +0 -268
  39. package/src/templates/saas/SEO.md +0 -257
@@ -1,155 +1,87 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'path';
3
- import { REQUIRED_PAGES } from '../utils/constants.js';
4
3
 
4
+ /**
5
+ * Creates the .seo/ intelligence workspace directory with a README.
6
+ * Does NOT pre-create empty placeholder page files — per-page playbooks
7
+ * are materialized on demand when `analyze` or `sync` runs.
8
+ *
9
+ * @param {string} cwd - Project root directory
10
+ * @param {object} answers - Scaffolding inputs (brand, domain)
11
+ */
5
12
  export async function createSeomdDir(cwd, answers) {
6
- const { site_type, brand, domain } = answers;
7
- const pages = REQUIRED_PAGES[site_type] || REQUIRED_PAGES.saas;
13
+ const { brand, domain } = answers;
8
14
  const seomdDir = path.join(cwd, '.seo');
9
15
 
10
- // Create directory structure
11
16
  await fs.ensureDir(path.join(seomdDir, 'pages'));
12
17
 
13
- // Create README inside .seo/
14
- await fs.writeFile(
15
- path.join(seomdDir, 'README.md'),
16
- generateSeomdReadme(brand, domain),
17
- 'utf8'
18
- );
19
-
20
- // Create placeholder page files
21
- for (const page of pages) {
22
- await fs.writeFile(
23
- path.join(seomdDir, 'pages', `${page.id}.md`),
24
- generatePagePlaceholder(page, brand),
25
- 'utf8'
26
- );
18
+ const readmePath = path.join(seomdDir, 'README.md');
19
+ if (!(await fs.pathExists(readmePath))) {
20
+ await fs.writeFile(readmePath, generateSeomdReadme(brand, domain), 'utf8');
27
21
  }
28
22
  }
29
23
 
30
24
  function generateSeomdReadme(brand, domain) {
31
25
  return `# .seo/
32
26
 
33
- AI search optimization workspace for **${brand}** (${domain})
27
+ AI search & citation intelligence workspace for **${brand}** (${domain})
34
28
  Generated by SEO.md CLI — https://seomd.dev
35
29
 
36
30
  ## What is this?
37
31
 
38
- \`.seo/\` stores platform-generated intelligence from citation audits, competitor analysis, and reverse-engineered playbooks. It lives alongside your source code so SEO strategy is version-controlled and reviewable in PRs.
32
+ \`.seo/\` stores provider-generated intelligence from citation audits, competitor analysis, and reverse-engineered playbooks. It lives alongside your source code so SEO/AEO strategy and diffs are version-controlled and reviewable in PRs.
39
33
 
40
34
  ## Directory Structure
41
35
 
42
36
  \`\`\`
43
37
  .seo/
44
- ├── pages/ # per-page reverse-engineer analysis
45
- ├── STATUS.yml # gap scores and citation metrics (platform generated)
46
- └── REVERSE.md # competitor playbooks (platform generated)
38
+ ├── pages/ # per-page playbooks (created on analyze/sync)
39
+ ├── STATUS.yml # gap scores and citation metrics (provider generated)
40
+ └── REVERSE.md # competitor playbooks (provider generated)
47
41
  \`\`\`
48
42
 
49
- ## Git behavior
43
+ ## Local Commands (Zero API Key Required)
50
44
 
51
- | Path | Git | Why |
52
- |------|-----|-----|
53
- | \`.seo/pages/\` | tracked | actionable playbooks belong in code review |
54
- | \`.seo/STATUS.yml\` | tracked | gap scores represent current project state |
55
- | \`.seo/REVERSE.md\` | tracked | competitor intel is project state |
56
-
57
- ## How to configure SEO.md
58
-
59
- \`SEO.md\` is your declarative configuration file. It tells the AI optimization platform exactly what you care about. Here is a guide on how to fill it out:
60
-
61
- ### 1. Intent (Queries)
62
- Add queries your buyers actually type into AI engines. Think about what someone asks ChatGPT or Perplexity when they are looking for a solution like yours.
63
-
64
- ### 2. Pages
65
- Declare the key pages on your site. For each page, set its priority and status (\`live | draft | planned\`). The platform will scan these and generate playbooks for each one.
45
+ \`\`\`bash
46
+ # Validate SEO.md syntax and schema
47
+ npx seomd-cli validate
66
48
 
67
- ### 3. AI Engine Optimization (AEO) Rules
68
- Set the strict guidelines you want your writers or AI to follow (e.g. \`answer_first_format: true\`).
49
+ # Audit local HTML / build output or localhost against SEO.md
50
+ npx seomd-cli check ./out
51
+ npx seomd-cli check http://localhost:3000
69
52
 
70
- ### 4. Platform Connection
71
- To enable live writebacks, connect your platform:
72
- 1. Connect at https://seomd.dev/connect
73
- 2. Add \`SEOMD_API_KEY\` to your \`.env\`
74
- 3. Run \`npx seomd analyze\`
53
+ # Generate robots.txt, llms.txt, or JSON-LD from SEO.md
54
+ npx seomd-cli generate robots --out public/robots.txt
55
+ npx seomd-cli generate llms --out public/llms.txt
56
+ npx seomd-cli generate schema
75
57
 
76
- **Note: Never commit your API key to version control.**
58
+ # Check repo health, agent wiring, and provider config
59
+ npx seomd-cli doctor
60
+ \`\`\`
77
61
 
78
- ## When to run what
62
+ ## Live Intelligence Commands (Requires a Connected Provider)
79
63
 
80
64
  \`\`\`bash
81
- # First full audit — scans all pages + intents
82
- npx seomd analyze
65
+ # Run a live AI citation audit
66
+ npx seomd-cli analyze
83
67
 
84
- # Refresh from cached platform data (no new scan)
85
- npx seomd sync
68
+ # Pull cached provider intelligence
69
+ npx seomd-cli sync
86
70
 
87
- # Check current gap scores without modifying files
88
- npx seomd status
89
- npx seomd status --json
71
+ # View current citation rates and gap scores
72
+ npx seomd-cli status
73
+ npx seomd-cli status --json
90
74
  \`\`\`
91
75
 
92
- | Command | Use when |
93
- |---------|----------|
94
- | \`analyze\` | You want a fresh audit, new competitor data, or updated playbooks |
95
- | \`sync\` | You just want the latest cached data from your platform |
96
- | \`status\` | You want a quick health check without writebacks |
76
+ ## File Ownership
97
77
 
98
- ## Reading a page playbook
99
-
100
- Each \`pages/<id>.md\` contains:
101
-
102
- - **why_page_won** — what top-cited competitors do right
103
- - **citation_hooks** — patterns to replicate
104
- - **gaps_for_brand** — where your page falls short
105
- - **remediation_playbook** — step-by-step fixes with effort/impact
106
- - **fastest_win** — highest ROI action to take now
107
- - **suggested_content_outline** — ready-to-use outline for your writer or AI
108
-
109
- ## File ownership
110
-
111
- | File/dir | Owner | Editable? |
112
- |-----------|-------|----------|
78
+ | Path | Owner | Editable? |
79
+ |------|-------|-----------|
113
80
  | \`SEO.md\` | you | yes |
114
- | \`.seo/STATUS.yml\` | platform | no |
115
- | \`.seo/REVERSE.md\` | platform | no |
116
- | \`.seo/pages/*.md\` | platform | no |
117
-
118
- Platform-generated files are overwritten on each \`analyze\` or \`sync\`.
119
- `;
120
- }
121
-
122
- function generatePagePlaceholder(page, brand) {
123
- const date = new Date().toISOString().split('T')[0];
124
- return `# ${page.id}
125
-
126
- ## Page: ${page.url}
127
-
128
- ### Priority: ${page.priority}
129
-
130
- ### Last analyzed: null
131
-
132
- ### Run \`npx seomd analyze --page ${page.url}\` to populate
133
-
134
- brand: "${brand}"
135
- page_id: ${page.id}
136
- url: ${page.url}
137
- status: planned
138
- citation_rate: null
139
- gap_score: null
140
- top_cited_competitor: null
141
- last_analyzed: null
142
-
143
- why_page_won: []
144
- citation_hooks: []
145
- gaps_for_brand: []
146
- remediation_playbook: []
147
-
148
- fastest_win:
149
- action: null
150
- estimated_gap_score_improvement: null
151
- effort: null
81
+ | \`.seo/STATUS.yml\` | provider | no |
82
+ | \`.seo/REVERSE.md\` | provider | no |
83
+ | \`.seo/pages/*.md\` | provider | no |
152
84
 
153
- suggested_content_outline: []
85
+ Provider-generated files are updated on each \`analyze\` or \`sync\`.
154
86
  `;
155
87
  }
@@ -1,62 +1,52 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
4
-
5
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
1
+ import YAML from 'yaml';
2
+ import { SPEC_VERSION, VALID_SITE_TYPES } from '../utils/constants.js';
3
+ import { normalizeDomain } from './seomd.js';
6
4
 
7
5
  /**
8
- * Generates the content of the seo.reverse.md file by reading the corresponding site type template
9
- * and substituting placeholders.
10
- *
11
- * @param {any} answers - Scaffolding inputs (brand, domain, primary_keyword, site_type, competitors)
12
- * @returns {string} The filled template content
6
+ * Generates the initial .seo/REVERSE.md scaffold using safe YAML serialization.
7
+ *
8
+ * @param {object} answers - Scaffolding inputs (brand, domain, site_type, competitors)
9
+ * @returns {string}
13
10
  */
14
11
  export function generateReverseMd(answers) {
15
- const { site_type, domain, brand, competitors } = answers;
16
- const competitorList = Array.isArray(competitors) ? competitors : [];
17
-
18
- // Resolve template file path
19
- const templatePath = path.join(__dirname, '../templates', site_type, 'SEO.REVERSE.md');
20
-
21
- if (!fs.existsSync(templatePath)) {
22
- throw new Error(`Template not found for site type: ${site_type}`);
23
- }
24
-
25
- let content = fs.readFileSync(templatePath, 'utf8');
26
-
27
- const date = new Date().toISOString().split('T')[0];
28
- const brandLower = brand.toLowerCase();
29
- const brandSnake = brandLower.replace(/\s+/g, '_');
30
- const primaryCompetitor = competitorList[0] || '[competitor]';
31
-
32
- // Formatting YAML blocks for competitors
33
- let reverseCompetitors = '';
34
- if (competitorList.length > 0) {
35
- reverseCompetitors = competitorList.map(c => ` - domain: ${c}
36
- overall_citation_rate: null
37
- strongest_intent_category: null
38
- weakest_intent_category: null
39
- top_cited_pages: []
40
- citation_patterns: []
41
- last_analyzed: null`).join('\n\n');
42
- } else {
43
- reverseCompetitors = ` - domain: [competitor]
44
- overall_citation_rate: null
45
- strongest_intent_category: null
46
- weakest_intent_category: null
47
- top_cited_pages: []
48
- citation_patterns: []
49
- last_analyzed: null`;
12
+ const siteType = answers.site_type || 'saas';
13
+ if (!VALID_SITE_TYPES.includes(siteType)) {
14
+ throw new Error(`Invalid site type '${siteType}'. Must be one of: ${VALID_SITE_TYPES.join(', ')}`);
50
15
  }
51
16
 
52
- // Perform simple string replacements
53
- content = content
54
- .replaceAll('{{brand}}', brand)
55
- .replaceAll('{{brand_lower_snake}}', brandSnake)
56
- .replaceAll('{{domain}}', domain)
57
- .replaceAll('{{primary_competitor}}', primaryCompetitor)
58
- .replaceAll('{{date}}', date)
59
- .replaceAll('{{reverse_competitors}}', reverseCompetitors);
60
-
61
- return content;
62
- }
17
+ const domain = normalizeDomain(answers.domain || 'example.com');
18
+ const brand = String(answers.brand || 'My Brand').trim();
19
+ const competitorList = Array.isArray(answers.competitors)
20
+ ? answers.competitors.map(normalizeDomain).filter(Boolean)
21
+ : [];
22
+
23
+ const doc = {
24
+ spec: SPEC_VERSION,
25
+ domain,
26
+ brand,
27
+ primary_competitor: competitorList[0] || null,
28
+ last_analyzed: null,
29
+ next_analysis: null,
30
+ source: null,
31
+ pages: [],
32
+ competitors: competitorList.map((c) => ({
33
+ domain: c,
34
+ overall_citation_rate: null,
35
+ strongest_intent_category: null,
36
+ weakest_intent_category: null,
37
+ top_cited_pages: [],
38
+ citation_patterns: [],
39
+ last_analyzed: null,
40
+ })),
41
+ };
42
+
43
+ const header = [
44
+ '# .seo/REVERSE.md',
45
+ '#',
46
+ '# Auto-generated by your connected SEO.md provider.',
47
+ '# Do not edit manually — run `npx seomd-cli analyze` or `npx seomd-cli sync` to update.',
48
+ '',
49
+ ].join('\n');
50
+
51
+ return `${header}\n${YAML.stringify(doc, { lineWidth: 100 })}`;
52
+ }
@@ -1,55 +1,237 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
1
+ import YAML from 'yaml';
2
+ import {
3
+ SPEC_VERSION,
4
+ INTENT_PRIORITIES,
5
+ REQUIRED_PAGES,
6
+ SCHEMA_TYPES,
7
+ SITE_TYPE_PROFILES,
8
+ VALID_SITE_TYPES,
9
+ } from '../utils/constants.js';
10
+ import { routeToPageId } from '../utils/repo-scanner.js';
4
11
 
5
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
-
7
- function getBrandName(domain) {
8
- return domain
9
- .replace(/^(https?:\/\/)?(www\.)?/, '')
12
+ function getBrandNameFromDomain(domain) {
13
+ return String(domain || '')
14
+ .replace(/^(https?:\/\/)?(www\.)?/i, '')
15
+ .replace(/\/.*$/, '')
10
16
  .replace(/\.[a-z]{2,6}(\.[a-z]{2,6})?$/i, '');
11
17
  }
12
18
 
13
19
  /**
14
- * Generates the content of the seo.md file by reading the corresponding site type template
15
- * and substituting placeholders.
16
- *
17
- * @param {any} answers - Scaffolding inputs (brand, domain, primary_keyword, site_type, competitors)
18
- * @returns {string} The filled template content
20
+ * Normalizes a domain string by stripping protocol, leading/trailing slashes, and whitespace.
19
21
  */
20
- export function generateSeoMd(answers) {
21
- const { site_type, domain, brand, primary_keyword, competitors } = answers;
22
- const competitorList = Array.isArray(competitors) ? competitors : [];
22
+ export function normalizeDomain(domain) {
23
+ return String(domain || '')
24
+ .trim()
25
+ .replace(/^<|>$/g, '')
26
+ .replace(/^https?:\/\//i, '')
27
+ .replace(/\/+$/, '');
28
+ }
29
+
30
+ /**
31
+ * Generates a v2.0.0 SEO.md file (YAML frontmatter + agent-readable Markdown body).
32
+ * Safely serializes all user inputs via YAML.stringify (zero YAML injection).
33
+ *
34
+ * @param {object} answers
35
+ * @param {object} [repoInfo] - Optional output from scanRepo()
36
+ * @returns {string}
37
+ */
38
+ export function generateSeoMd(answers, repoInfo = null) {
39
+ const siteType = answers.site_type || 'saas';
40
+ if (!VALID_SITE_TYPES.includes(siteType)) {
41
+ throw new Error(`Invalid site type '${siteType}'. Must be one of: ${VALID_SITE_TYPES.join(', ')}`);
42
+ }
43
+
44
+ const profile = SITE_TYPE_PROFILES[siteType];
45
+ const priorities = INTENT_PRIORITIES[siteType];
46
+ const domain = normalizeDomain(answers.domain || 'example.com');
47
+ const brand = String(answers.brand || 'My Brand').trim();
48
+ const brandLower = brand.toLowerCase();
49
+ const primaryKeyword = String(answers.primary_keyword || profile.defaultKeyword).trim();
50
+ const competitorList = Array.isArray(answers.competitors)
51
+ ? answers.competitors.map(normalizeDomain).filter(Boolean)
52
+ : [];
53
+ const year = new Date().getFullYear();
54
+ // Founder-curated values carried over from an existing SEO.md (v1 or v2) on re-init
55
+ const carry = answers.carry || {};
23
56
 
24
- // Resolve template file path
25
- const templatePath = path.join(__dirname, '../templates', site_type, 'SEO.md');
57
+ // Build intent queries tailored to site type
58
+ const comparisonQueries = competitorList.length > 0
59
+ ? [
60
+ ...competitorList.map((c) => `${getBrandNameFromDomain(c)} vs ${brandLower}`),
61
+ profile.comparisonSuffix(primaryKeyword),
62
+ ]
63
+ : [
64
+ `${brandLower} alternatives`,
65
+ profile.comparisonSuffix(primaryKeyword),
66
+ ];
26
67
 
27
- if (!fs.existsSync(templatePath)) {
28
- throw new Error(`Template not found for site type: ${site_type}`);
68
+ const intent = {
69
+ informational: {
70
+ priority: priorities.informational,
71
+ queries: [
72
+ `what is ${primaryKeyword}`,
73
+ `how does ${primaryKeyword} work`,
74
+ ],
75
+ },
76
+ comparison: {
77
+ priority: priorities.comparison,
78
+ queries: comparisonQueries,
79
+ },
80
+ transactional: {
81
+ priority: priorities.transactional,
82
+ queries: profile.transactionalQueries(brandLower),
83
+ },
84
+ reputational: {
85
+ priority: priorities.reputational,
86
+ queries: [
87
+ `${brandLower} reviews`,
88
+ `is ${brandLower} legit`,
89
+ ],
90
+ },
91
+ category: {
92
+ priority: priorities.category,
93
+ queries: profile.categoryQuery(primaryKeyword, year),
94
+ },
95
+ };
96
+ if (carry.intent) {
97
+ for (const [category, kept] of Object.entries(carry.intent)) {
98
+ intent[category] = {
99
+ priority: kept.priority || intent[category]?.priority || 'medium',
100
+ queries: kept.queries,
101
+ };
102
+ }
29
103
  }
30
104
 
31
- let content = fs.readFileSync(templatePath, 'utf8');
105
+ // Merge discovered live routes with recommended site-type pages
106
+ const recommendedPages = REQUIRED_PAGES[siteType] || REQUIRED_PAGES.saas;
107
+ const discoveredRoutes = Array.isArray(repoInfo?.routes) ? repoInfo.routes : [];
108
+ const discoveredSet = new Set(discoveredRoutes.map((r) => r.toLowerCase()));
32
109
 
33
- const date = new Date().toISOString().split('T')[0];
34
- const brandLower = brand.toLowerCase();
35
- const brandSnake = brandLower.replace(/\s+/g, '_');
36
-
37
- // Formatting YAML blocks for competitors
38
- const competitorTerms = competitorList.map(c => ` - "${getBrandName(c)} alternative"`).join('\n') || ' []';
39
- const comparisonQueries = competitorList.map(c => ` - "${getBrandName(c)} vs ${brandLower}"`).join('\n') || ` - "${brandLower} vs [competitor]"`;
40
- const toMonitor = competitorList.map(c => ` - ${c}`).join('\n') || ' []';
41
-
42
- // Perform simple string replacements
43
- content = content
44
- .replaceAll('{{brand}}', brand)
45
- .replaceAll('{{brand_lower}}', brandLower)
46
- .replaceAll('{{brand_lower_snake}}', brandSnake)
47
- .replaceAll('{{domain}}', domain)
48
- .replaceAll('{{primary_keyword}}', primary_keyword)
49
- .replaceAll('{{date}}', date)
50
- .replaceAll('{{competitor_terms}}', competitorTerms)
51
- .replaceAll('{{competitors_comparison_queries}}', comparisonQueries)
52
- .replaceAll('{{competitors_to_monitor}}', toMonitor);
53
-
54
- return content;
55
- }
110
+ const pages = [];
111
+ const seenUrls = new Set();
112
+ const seenIds = new Set();
113
+
114
+ // Pages declared in an existing SEO.md come first, keeping their keywords
115
+ for (const kept of carry.pages || []) {
116
+ const urlKey = kept.url.toLowerCase();
117
+ if (seenUrls.has(urlKey)) continue;
118
+ let id = kept.id || routeToPageId(kept.url);
119
+ if (seenIds.has(id)) id = `${id}-${pages.length + 1}`;
120
+ pages.push({
121
+ id,
122
+ url: kept.url,
123
+ status: discoveredSet.has(urlKey) ? 'live' : kept.status,
124
+ priority: kept.priority ?? pages.length + 1,
125
+ keyword: kept.keyword,
126
+ });
127
+ seenUrls.add(urlKey);
128
+ seenIds.add(id);
129
+ }
130
+
131
+ // Then add recommended pages (marking as 'live' if discovered in repo)
132
+ for (const rec of recommendedPages) {
133
+ if (seenUrls.has(rec.url.toLowerCase())) continue;
134
+ const isLive = discoveredSet.has(rec.url.toLowerCase());
135
+ pages.push({
136
+ id: rec.id,
137
+ url: rec.url,
138
+ status: isLive ? 'live' : 'planned',
139
+ priority: carry.pages ? pages.length + 1 : rec.priority,
140
+ keyword: rec.url === '/' ? primaryKeyword : null,
141
+ });
142
+ seenUrls.add(rec.url.toLowerCase());
143
+ seenIds.add(rec.id);
144
+ }
145
+
146
+ // Then append any additional discovered live routes (capped at 20 total to keep manifest concise)
147
+ let nextPriority = Math.max(0, ...pages.map((p) => Number(p.priority) || 0)) + 1;
148
+ for (const route of discoveredRoutes) {
149
+ if (pages.length >= 20) break;
150
+ if (seenUrls.has(route.toLowerCase())) continue;
151
+ let id = routeToPageId(route);
152
+ if (seenIds.has(id)) {
153
+ id = `${id}-${nextPriority}`;
154
+ }
155
+ pages.push({
156
+ id,
157
+ url: route,
158
+ status: 'live',
159
+ priority: nextPriority++,
160
+ keyword: null,
161
+ });
162
+ seenUrls.add(route.toLowerCase());
163
+ seenIds.add(id);
164
+ }
165
+
166
+ const frontmatter = {
167
+ spec: SPEC_VERSION,
168
+ site: {
169
+ brand,
170
+ domain,
171
+ canonical: `https://${domain}`,
172
+ type: siteType,
173
+ locale: carry.locale || 'en-US',
174
+ },
175
+ keywords: {
176
+ primary: primaryKeyword,
177
+ secondary: carry.secondary || [],
178
+ negative: carry.negative || profile.negativeKeywords,
179
+ },
180
+ competitors: competitorList.map((c) => ({ domain: c })),
181
+ intent,
182
+ pages,
183
+ schema: {
184
+ types: SCHEMA_TYPES[siteType] || SCHEMA_TYPES.saas,
185
+ },
186
+ crawl: {
187
+ sitemap: '/sitemap.xml',
188
+ robots: '/robots.txt',
189
+ llms_txt: '/llms.txt',
190
+ allow_ai_bots: true,
191
+ disallow: profile.disallow,
192
+ },
193
+ provider: {
194
+ name: answers.provider || null,
195
+ endpoint: carry.providerEndpoint || null,
196
+ },
197
+ };
198
+
199
+ const yamlBlock = YAML.stringify(frontmatter, { lineWidth: 100 }).trimEnd();
200
+
201
+ const rulesMarkdown = profile.agentRules.map((rule) => `- ${rule}`).join('\n');
202
+ const negativeMarkdown = frontmatter.keywords.negative.map((kw) => `\`${kw}\``).join(', ');
203
+ const promptLines = [
204
+ `- **Category:** ${intent.category.queries.map((q) => `"${q}"`).join(', ')}`,
205
+ `- **Comparison:** ${intent.comparison.queries.map((q) => `"${q}"`).join(', ')}`,
206
+ `- **Transactional:** ${intent.transactional.queries.map((q) => `"${q}"`).join(', ')}`,
207
+ ].join('\n');
208
+
209
+ const body = `# SEO.md — ${brand}
210
+
211
+ > Open standard for search & AI-citation configuration (spec v${SPEC_VERSION} — https://seomd.dev).
212
+ > Coding agents: read this file and matching playbooks in \`.seo/pages/\` before creating or editing public pages.
213
+
214
+ ## Canonical Product Facts
215
+ - **One-liner:** ${carry.tagline ? `${brand} — ${carry.tagline}` : `${brand} — replace with a clear, factual 1-sentence description of what you offer.`}
216
+ - **Primary category:** ${primaryKeyword}
217
+ - **Pricing / offer:** Add real pricing or offer facts here so coding agents never invent vague copy.
218
+ - **Proof points:** Add concrete, verifiable metrics, certifications, or customer outcomes.
219
+
220
+ ## Target Buyer Prompts (AI Search)
221
+ ${promptLines}
222
+
223
+ ## Page & AEO Rules (For Coding Agents)
224
+ ${rulesMarkdown}
225
+
226
+ ## Do Not Claim
227
+ - Avoid diluting intent with negative terms: ${negativeMarkdown}.
228
+ - Never fabricate competitor pricing, benchmarks, or unverified customer quotes.
229
+
230
+ ## Live Intelligence
231
+ - Metrics & gap scores: \`.seo/STATUS.yml\`
232
+ - Competitor reverse-engineering: \`.seo/REVERSE.md\`
233
+ - Per-page playbooks: \`.seo/pages/<id>.md\`
234
+ `;
235
+
236
+ return `---\n${yamlBlock}\n---\n\n${body}`;
237
+ }
@@ -0,0 +1,67 @@
1
+ import axios from 'axios';
2
+
3
+ const getDashboardUrlFromApi = (apiUrl, explicitDashboardUrl = null) => {
4
+ if (explicitDashboardUrl) return explicitDashboardUrl;
5
+ if (apiUrl && (apiUrl.includes('127.0.0.1') || apiUrl.includes('localhost'))) {
6
+ return 'http://localhost:3000';
7
+ }
8
+ if (apiUrl && apiUrl.includes('api.foxcite.com')) {
9
+ return 'https://app.foxcite.com';
10
+ }
11
+ return 'https://seomd.dev';
12
+ };
13
+
14
+ /**
15
+ * Creates a fresh axios client using runtime credentials (never frozen at import time).
16
+ */
17
+ export function createHttpClient({
18
+ baseURL,
19
+ apiKey = null,
20
+ paymentToken = null,
21
+ domain = null,
22
+ dashboardUrl = null,
23
+ timeout = 300000,
24
+ }) {
25
+ const client = axios.create({
26
+ baseURL,
27
+ timeout,
28
+ headers: {
29
+ 'Content-Type': 'application/json',
30
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
31
+ ...(paymentToken ? { 'x-payment-token': paymentToken } : {}),
32
+ ...(domain ? { 'x-seomd-domain': domain } : {}),
33
+ },
34
+ });
35
+
36
+ client.interceptors.response.use(
37
+ (response) => response,
38
+ (error) => {
39
+ if (error.response) {
40
+ const status = error.response.status;
41
+ const detail = error.response.data?.detail || error.response.data?.message || error.message;
42
+
43
+ if (status === 401) {
44
+ return Promise.reject(
45
+ new Error('Authentication failed: Invalid or missing API key (SEOMD_API_KEY).')
46
+ );
47
+ }
48
+ if (status === 402) {
49
+ const dashUrl = getDashboardUrlFromApi(baseURL, dashboardUrl);
50
+ return Promise.reject(
51
+ new Error(
52
+ `Insufficient scan credits.\n\n` +
53
+ `For Humans: Recharge credits or upgrade your plan:\n` +
54
+ ` ${dashUrl}/billing\n\n` +
55
+ `For Programmatic Agents:\n` +
56
+ ` Set SEOMD_PAYMENT_TOKEN in your environment to pay-per-scan inline via x402.`
57
+ )
58
+ );
59
+ }
60
+ return Promise.reject(new Error(`API Error (${status}): ${detail}`));
61
+ }
62
+ return Promise.reject(new Error(`Network Error: ${error.message}`));
63
+ }
64
+ );
65
+
66
+ return client;
67
+ }