aeo.js 0.0.1 → 0.0.3

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 (70) hide show
  1. package/README.md +303 -6
  2. package/dist/angular.d.mts +29 -0
  3. package/dist/angular.d.ts +29 -0
  4. package/dist/angular.js +1314 -0
  5. package/dist/angular.js.map +1 -0
  6. package/dist/angular.mjs +1310 -0
  7. package/dist/angular.mjs.map +1 -0
  8. package/dist/astro.d.mts +15 -0
  9. package/dist/astro.d.ts +15 -0
  10. package/dist/astro.js +1421 -0
  11. package/dist/astro.js.map +1 -0
  12. package/dist/astro.mjs +1414 -0
  13. package/dist/astro.mjs.map +1 -0
  14. package/dist/cli.d.mts +1 -0
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +1880 -2
  17. package/dist/cli.js.map +1 -0
  18. package/dist/cli.mjs +1878 -0
  19. package/dist/cli.mjs.map +1 -0
  20. package/dist/index.d.mts +191 -0
  21. package/dist/index.d.ts +191 -1
  22. package/dist/index.js +1829 -1
  23. package/dist/index.js.map +1 -0
  24. package/dist/index.mjs +1801 -1
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/next.d.mts +18 -0
  27. package/dist/next.d.ts +18 -0
  28. package/dist/next.js +1302 -0
  29. package/dist/next.js.map +1 -0
  30. package/dist/next.mjs +1295 -0
  31. package/dist/next.mjs.map +1 -0
  32. package/dist/nuxt.d.mts +13 -0
  33. package/dist/nuxt.d.ts +13 -0
  34. package/dist/nuxt.js +1344 -0
  35. package/dist/nuxt.js.map +1 -0
  36. package/dist/nuxt.mjs +1337 -0
  37. package/dist/nuxt.mjs.map +1 -0
  38. package/dist/react.d.mts +10 -0
  39. package/dist/react.d.ts +10 -0
  40. package/dist/react.js +1023 -0
  41. package/dist/react.js.map +1 -0
  42. package/dist/react.mjs +1020 -0
  43. package/dist/react.mjs.map +1 -0
  44. package/dist/types-Cn_Qbkmg.d.mts +166 -0
  45. package/dist/types-Cn_Qbkmg.d.ts +166 -0
  46. package/dist/vite.d.mts +5 -0
  47. package/dist/vite.d.ts +5 -0
  48. package/dist/vite.js +1370 -0
  49. package/dist/vite.js.map +1 -0
  50. package/dist/vite.mjs +1366 -0
  51. package/dist/vite.mjs.map +1 -0
  52. package/dist/vue.d.mts +19 -0
  53. package/dist/vue.d.ts +19 -0
  54. package/dist/vue.js +1078 -0
  55. package/dist/vue.js.map +1 -0
  56. package/dist/vue.mjs +1072 -0
  57. package/dist/vue.mjs.map +1 -0
  58. package/dist/webpack.d.mts +11 -0
  59. package/dist/webpack.d.ts +11 -0
  60. package/dist/webpack.js +1179 -0
  61. package/dist/webpack.js.map +1 -0
  62. package/dist/webpack.mjs +1173 -0
  63. package/dist/webpack.mjs.map +1 -0
  64. package/dist/widget.d.mts +37 -0
  65. package/dist/widget.d.ts +37 -0
  66. package/dist/widget.js +1004 -0
  67. package/dist/widget.js.map +1 -0
  68. package/dist/widget.mjs +1001 -0
  69. package/dist/widget.mjs.map +1 -0
  70. package/package.json +110 -10
package/dist/cli.mjs ADDED
@@ -0,0 +1,1878 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, writeFileSync, mkdirSync, readFileSync, readdirSync, statSync, copyFileSync } from 'fs';
3
+ import { join, dirname, extname, relative } from 'path';
4
+ import 'minimatch';
5
+ import { createHash } from 'crypto';
6
+
7
+ // src/core/robots.ts
8
+ var AI_CRAWLERS = [
9
+ "GPTBot",
10
+ "OAI-SearchBot",
11
+ "ChatGPT-User",
12
+ "ClaudeBot",
13
+ "Claude-Web",
14
+ "anthropic-ai",
15
+ "PerplexityBot",
16
+ "Google-Extended",
17
+ "Gemini-Deep-Research",
18
+ "Bingbot",
19
+ "FacebookBot",
20
+ "meta-externalagent",
21
+ "Amazonbot",
22
+ "Applebot",
23
+ "DeepSeekBot",
24
+ "Bytespider",
25
+ "cohere-ai",
26
+ "CCBot",
27
+ "DiffBot",
28
+ "YouBot",
29
+ "FirecrawlAgent",
30
+ "Crawl4AI",
31
+ "BraveBot",
32
+ "SemrushBot",
33
+ "AhrefsBot",
34
+ "MJ12bot",
35
+ "DotBot",
36
+ "DataForSeoBot",
37
+ "Screaming Frog SEO Spider",
38
+ "SEOkicks",
39
+ "SEMrushBot",
40
+ "BLEXBot",
41
+ "Yandex",
42
+ "Baiduspider",
43
+ "Sogou",
44
+ "Exabot",
45
+ "facebookexternalhit",
46
+ "LinkedInBot",
47
+ "WhatsApp",
48
+ "Slackbot",
49
+ "TwitterBot",
50
+ "TelegramBot",
51
+ "Discordbot",
52
+ "PinterestBot",
53
+ "TumblrBot",
54
+ "ViberBot",
55
+ "SkypeUriPreview",
56
+ "redditbot",
57
+ "Snapchat",
58
+ "TikTok"
59
+ ];
60
+ function generateRobotsTxt(config) {
61
+ const lines = [
62
+ "# robots.txt generated by aeo.js",
63
+ "# Allow AI crawlers to index this site",
64
+ "",
65
+ "# Traditional search engines",
66
+ "User-agent: Googlebot",
67
+ "Allow: /",
68
+ "",
69
+ "User-agent: Bingbot",
70
+ "Allow: /",
71
+ "",
72
+ "# AI crawlers and answer engines"
73
+ ];
74
+ for (const crawler of AI_CRAWLERS) {
75
+ lines.push(`User-agent: ${crawler}`);
76
+ lines.push("Allow: /");
77
+ lines.push("");
78
+ }
79
+ lines.push("# Default for all other bots");
80
+ lines.push("User-agent: *");
81
+ lines.push("Allow: /");
82
+ lines.push("");
83
+ if (config.url) {
84
+ lines.push(`Sitemap: ${config.url}/sitemap.xml`);
85
+ }
86
+ lines.push("");
87
+ lines.push("# AEO (Answer Engine Optimization) files");
88
+ lines.push("# These help LLMs understand your content better");
89
+ lines.push(`# ${config.url}/llms.txt`);
90
+ lines.push(`# ${config.url}/llms-full.txt`);
91
+ lines.push(`# ${config.url}/docs.json`);
92
+ lines.push(`# ${config.url}/ai-index.json`);
93
+ return lines.join("\n");
94
+ }
95
+
96
+ // src/core/detect.ts
97
+ function detectFramework(projectRoot = process.cwd()) {
98
+ const packageJson = readPackageJson(projectRoot);
99
+ const dependencies = {
100
+ ...packageJson.dependencies,
101
+ ...packageJson.devDependencies
102
+ };
103
+ if (dependencies["next"]) {
104
+ return {
105
+ framework: "next",
106
+ contentDir: "app",
107
+ outDir: "out"
108
+ };
109
+ }
110
+ if (dependencies["nuxt"] || dependencies["@nuxt/kit"]) {
111
+ return {
112
+ framework: "nuxt",
113
+ contentDir: "content",
114
+ outDir: ".output/public"
115
+ };
116
+ }
117
+ if (dependencies["astro"] || dependencies["@astrojs/astro"]) {
118
+ return {
119
+ framework: "astro",
120
+ contentDir: "src/content",
121
+ outDir: "dist"
122
+ };
123
+ }
124
+ if (dependencies["@remix-run/dev"]) {
125
+ return {
126
+ framework: "remix",
127
+ contentDir: "app",
128
+ outDir: "build/client"
129
+ };
130
+ }
131
+ if (dependencies["@sveltejs/kit"]) {
132
+ return {
133
+ framework: "sveltekit",
134
+ contentDir: "src",
135
+ outDir: "build"
136
+ };
137
+ }
138
+ if (dependencies["@angular/core"]) {
139
+ return {
140
+ framework: "angular",
141
+ contentDir: "src",
142
+ outDir: "dist"
143
+ };
144
+ }
145
+ if (dependencies["@docusaurus/core"]) {
146
+ return {
147
+ framework: "docusaurus",
148
+ contentDir: "docs",
149
+ outDir: "build"
150
+ };
151
+ }
152
+ if (dependencies["vite"]) {
153
+ return {
154
+ framework: "vite",
155
+ contentDir: "src",
156
+ outDir: "dist"
157
+ };
158
+ }
159
+ return {
160
+ framework: "unknown",
161
+ contentDir: "src",
162
+ outDir: "dist"
163
+ };
164
+ }
165
+ function resolveConfig(config = {}) {
166
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M;
167
+ const frameworkInfo = detectFramework();
168
+ return {
169
+ title: config.title || "My Site",
170
+ description: config.description || "",
171
+ url: config.url || "https://example.com",
172
+ contentDir: config.contentDir || frameworkInfo.contentDir,
173
+ outDir: config.outDir || frameworkInfo.outDir,
174
+ pages: config.pages || [],
175
+ generators: {
176
+ robotsTxt: ((_a = config.generators) == null ? void 0 : _a.robotsTxt) !== false,
177
+ llmsTxt: ((_b = config.generators) == null ? void 0 : _b.llmsTxt) !== false,
178
+ llmsFullTxt: ((_c = config.generators) == null ? void 0 : _c.llmsFullTxt) !== false,
179
+ rawMarkdown: ((_d = config.generators) == null ? void 0 : _d.rawMarkdown) !== false,
180
+ manifest: ((_e = config.generators) == null ? void 0 : _e.manifest) !== false,
181
+ sitemap: ((_f = config.generators) == null ? void 0 : _f.sitemap) !== false,
182
+ aiIndex: ((_g = config.generators) == null ? void 0 : _g.aiIndex) !== false,
183
+ schema: ((_h = config.generators) == null ? void 0 : _h.schema) !== false
184
+ },
185
+ robots: {
186
+ allow: ((_i = config.robots) == null ? void 0 : _i.allow) || ["/"],
187
+ disallow: ((_j = config.robots) == null ? void 0 : _j.disallow) || [],
188
+ crawlDelay: ((_k = config.robots) == null ? void 0 : _k.crawlDelay) || 0,
189
+ sitemap: ((_l = config.robots) == null ? void 0 : _l.sitemap) || ""
190
+ },
191
+ schema: {
192
+ enabled: ((_m = config.schema) == null ? void 0 : _m.enabled) !== false,
193
+ organization: {
194
+ name: ((_o = (_n = config.schema) == null ? void 0 : _n.organization) == null ? void 0 : _o.name) || config.title || "My Site",
195
+ url: ((_q = (_p = config.schema) == null ? void 0 : _p.organization) == null ? void 0 : _q.url) || config.url || "https://example.com",
196
+ logo: ((_s = (_r = config.schema) == null ? void 0 : _r.organization) == null ? void 0 : _s.logo) || "",
197
+ sameAs: ((_u = (_t = config.schema) == null ? void 0 : _t.organization) == null ? void 0 : _u.sameAs) || []
198
+ },
199
+ defaultType: ((_v = config.schema) == null ? void 0 : _v.defaultType) || "WebPage"
200
+ },
201
+ og: {
202
+ enabled: ((_w = config.og) == null ? void 0 : _w.enabled) !== false,
203
+ image: ((_x = config.og) == null ? void 0 : _x.image) || "",
204
+ twitterHandle: ((_y = config.og) == null ? void 0 : _y.twitterHandle) || "",
205
+ type: ((_z = config.og) == null ? void 0 : _z.type) || "website"
206
+ },
207
+ widget: {
208
+ enabled: ((_A = config.widget) == null ? void 0 : _A.enabled) !== false,
209
+ position: ((_B = config.widget) == null ? void 0 : _B.position) || "bottom-right",
210
+ theme: {
211
+ background: ((_D = (_C = config.widget) == null ? void 0 : _C.theme) == null ? void 0 : _D.background) || "rgba(18, 18, 24, 0.9)",
212
+ text: ((_F = (_E = config.widget) == null ? void 0 : _E.theme) == null ? void 0 : _F.text) || "#C0C0C5",
213
+ accent: ((_H = (_G = config.widget) == null ? void 0 : _G.theme) == null ? void 0 : _H.accent) || "#E8E8EA",
214
+ badge: ((_J = (_I = config.widget) == null ? void 0 : _I.theme) == null ? void 0 : _J.badge) || "#4ADE80"
215
+ },
216
+ humanLabel: ((_K = config.widget) == null ? void 0 : _K.humanLabel) || "Human",
217
+ aiLabel: ((_L = config.widget) == null ? void 0 : _L.aiLabel) || "AI",
218
+ showBadge: ((_M = config.widget) == null ? void 0 : _M.showBadge) !== false
219
+ }
220
+ };
221
+ }
222
+ function parseFrontmatter(content) {
223
+ const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)/);
224
+ if (frontmatterMatch) {
225
+ const frontmatterStr = frontmatterMatch[1];
226
+ const contentWithoutFrontmatter = frontmatterMatch[2];
227
+ const frontmatter = {};
228
+ const lines = frontmatterStr.split("\n");
229
+ for (const line of lines) {
230
+ const [key, ...valueParts] = line.split(":");
231
+ if (key && valueParts.length > 0) {
232
+ const value = valueParts.join(":").trim();
233
+ frontmatter[key.trim()] = value.replace(/^["']|["']$/g, "");
234
+ }
235
+ }
236
+ return { frontmatter, content: contentWithoutFrontmatter };
237
+ }
238
+ return { frontmatter: {}, content };
239
+ }
240
+ function bumpHeadings(content, levels = 1) {
241
+ return content.replace(/^(#{1,6})\s/gm, (match, hashes) => {
242
+ const newLevel = Math.min(hashes.length + levels, 6);
243
+ return "#".repeat(newLevel) + " ";
244
+ });
245
+ }
246
+ function extractTitle(content) {
247
+ const h1Match = content.match(/^#\s+(.+)$/m);
248
+ if (h1Match) return h1Match[1];
249
+ const h2Match = content.match(/^##\s+(.+)$/m);
250
+ if (h2Match) return h2Match[1];
251
+ const firstLine = content.split("\n")[0];
252
+ return firstLine.slice(0, 100);
253
+ }
254
+ function readPackageJson(projectRoot = process.cwd()) {
255
+ const packageJsonPath = join(projectRoot, "package.json");
256
+ if (!existsSync(packageJsonPath)) {
257
+ return {};
258
+ }
259
+ try {
260
+ const content = readFileSync(packageJsonPath, "utf-8");
261
+ return JSON.parse(content);
262
+ } catch {
263
+ return {};
264
+ }
265
+ }
266
+
267
+ // src/core/llms-txt.ts
268
+ function collectMarkdownFiles(dir, base = dir) {
269
+ const files = [];
270
+ try {
271
+ const entries = readdirSync(dir);
272
+ for (const entry of entries) {
273
+ const fullPath = join(dir, entry);
274
+ const stat = statSync(fullPath);
275
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
276
+ files.push(...collectMarkdownFiles(fullPath, base));
277
+ } else if (stat.isFile() && (extname(entry) === ".md" || extname(entry) === ".mdx")) {
278
+ const content = readFileSync(fullPath, "utf-8");
279
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
280
+ const relativePath = relative(base, fullPath);
281
+ files.push({
282
+ path: relativePath,
283
+ content: mainContent,
284
+ title: frontmatter.title || extractTitle(mainContent),
285
+ description: frontmatter.description,
286
+ frontmatter
287
+ });
288
+ }
289
+ }
290
+ } catch (error) {
291
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
292
+ }
293
+ return files;
294
+ }
295
+ function generateLlmsTxt(config) {
296
+ const lines = [
297
+ `# ${config.title}`,
298
+ ""
299
+ ];
300
+ if (config.description) {
301
+ lines.push(`> ${config.description}`);
302
+ lines.push("");
303
+ }
304
+ lines.push("## About");
305
+ lines.push("");
306
+ lines.push("This file provides a structured overview of the documentation and content available on this site,");
307
+ lines.push("optimized for consumption by Large Language Models (LLMs) and AI assistants.");
308
+ lines.push("");
309
+ if (config.pages && config.pages.length > 0) {
310
+ lines.push("## Pages");
311
+ lines.push("");
312
+ for (const page of config.pages) {
313
+ const url = `${config.url}${page.pathname === "/" ? "" : page.pathname}`;
314
+ const title = page.title || page.pathname;
315
+ lines.push(`- [${title}](${url})`);
316
+ if (page.description) {
317
+ lines.push(` ${page.description}`);
318
+ }
319
+ }
320
+ lines.push("");
321
+ }
322
+ const markdownFiles = collectMarkdownFiles(config.contentDir);
323
+ if (markdownFiles.length > 0) {
324
+ lines.push("## Documentation");
325
+ lines.push("");
326
+ const grouped = {};
327
+ for (const file of markdownFiles) {
328
+ const dir = file.path.split("/")[0] || "root";
329
+ if (!grouped[dir]) grouped[dir] = [];
330
+ grouped[dir].push(file);
331
+ }
332
+ for (const [dir, files] of Object.entries(grouped)) {
333
+ lines.push(`### ${dir === "root" ? "Main Documentation" : dir}`);
334
+ lines.push("");
335
+ for (const file of files) {
336
+ const url = `${config.url}/${file.path.replace(/\.mdx?$/, "")}`;
337
+ lines.push(`- [${file.title}](${url})`);
338
+ if (file.description) {
339
+ lines.push(` ${file.description}`);
340
+ }
341
+ }
342
+ lines.push("");
343
+ }
344
+ }
345
+ lines.push("## Quick Links");
346
+ lines.push("");
347
+ lines.push(`- Full Documentation: ${config.url}/llms-full.txt`);
348
+ lines.push(`- Documentation Manifest: ${config.url}/docs.json`);
349
+ lines.push(`- AI-Optimized Index: ${config.url}/ai-index.json`);
350
+ lines.push(`- Sitemap: ${config.url}/sitemap.xml`);
351
+ lines.push("");
352
+ lines.push("## For LLMs");
353
+ lines.push("");
354
+ lines.push("To get the complete documentation in a single file, request:");
355
+ lines.push(`${config.url}/llms-full.txt`);
356
+ lines.push("");
357
+ lines.push("For structured access to individual pages with metadata:");
358
+ lines.push(`${config.url}/docs.json`);
359
+ lines.push("");
360
+ lines.push("For RAG (Retrieval Augmented Generation) systems:");
361
+ lines.push(`${config.url}/ai-index.json`);
362
+ lines.push("");
363
+ lines.push("---");
364
+ lines.push("Generated by aeo.js - Answer Engine Optimization for the modern web");
365
+ lines.push("Learn more at https://aeojs.org");
366
+ return lines.join("\n");
367
+ }
368
+ function collectAndConcatenateMarkdown(dir, base = dir) {
369
+ const sections = [];
370
+ try {
371
+ const entries = readdirSync(dir).sort();
372
+ for (const entry of entries) {
373
+ const fullPath = join(dir, entry);
374
+ const stat = statSync(fullPath);
375
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
376
+ const subSections = collectAndConcatenateMarkdown(fullPath, base);
377
+ if (subSections.length > 0) {
378
+ sections.push(...subSections);
379
+ }
380
+ } else if (stat.isFile() && (extname(entry) === ".md" || extname(entry) === ".mdx")) {
381
+ const content = readFileSync(fullPath, "utf-8");
382
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
383
+ const relativePath = relative(base, fullPath);
384
+ const sectionLines = [
385
+ "---",
386
+ "",
387
+ `# ${frontmatter.title || relativePath}`,
388
+ "",
389
+ `Source: ${relativePath}`,
390
+ ""
391
+ ];
392
+ if (frontmatter.description) {
393
+ sectionLines.push(`> ${frontmatter.description}`);
394
+ sectionLines.push("");
395
+ }
396
+ const bumpedContent = bumpHeadings(mainContent, 1);
397
+ sectionLines.push(bumpedContent);
398
+ sectionLines.push("");
399
+ sections.push(sectionLines.join("\n"));
400
+ }
401
+ }
402
+ } catch (error) {
403
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
404
+ }
405
+ return sections;
406
+ }
407
+ function generateLlmsFullTxt(config) {
408
+ const lines = [
409
+ `# ${config.title} - Complete Documentation`,
410
+ "",
411
+ `This file contains all documentation concatenated into a single file for easy consumption by LLMs.`,
412
+ ""
413
+ ];
414
+ if (config.description) {
415
+ lines.push(`> ${config.description}`);
416
+ lines.push("");
417
+ }
418
+ lines.push("## Table of Contents");
419
+ lines.push("");
420
+ lines.push("This document includes all content from this project.");
421
+ lines.push("Each section is separated by a horizontal rule (---) for easy parsing.");
422
+ lines.push("");
423
+ let hasContent = false;
424
+ if (config.pages && config.pages.length > 0) {
425
+ for (const page of config.pages) {
426
+ const url = `${config.url}${page.pathname === "/" ? "" : page.pathname}`;
427
+ const title = page.title || page.pathname;
428
+ const sectionLines = [
429
+ "---",
430
+ "",
431
+ `# ${title}`,
432
+ "",
433
+ `URL: ${url}`,
434
+ ""
435
+ ];
436
+ if (page.description) {
437
+ sectionLines.push(`> ${page.description}`);
438
+ sectionLines.push("");
439
+ }
440
+ if (page.content) {
441
+ sectionLines.push(page.content);
442
+ sectionLines.push("");
443
+ }
444
+ lines.push(sectionLines.join("\n"));
445
+ hasContent = true;
446
+ }
447
+ }
448
+ const sections = collectAndConcatenateMarkdown(config.contentDir);
449
+ if (sections.length > 0) {
450
+ lines.push(...sections);
451
+ hasContent = true;
452
+ }
453
+ if (!hasContent) {
454
+ lines.push("---");
455
+ lines.push("");
456
+ lines.push(`# ${config.title}`);
457
+ lines.push("");
458
+ lines.push(`URL: ${config.url}`);
459
+ lines.push("");
460
+ if (config.description) {
461
+ lines.push(config.description);
462
+ lines.push("");
463
+ }
464
+ }
465
+ lines.push("---");
466
+ lines.push("");
467
+ lines.push("## About This Document");
468
+ lines.push("");
469
+ lines.push("This concatenated documentation file is generated automatically by aeo.js");
470
+ lines.push("to make it easier for AI systems to understand the complete context of this project.");
471
+ lines.push("");
472
+ lines.push(`For a structured index, see: ${config.url}/llms.txt`);
473
+ lines.push(`For individual files, see: ${config.url}/docs.json`);
474
+ lines.push("");
475
+ lines.push("Generated by aeo.js - https://aeojs.org");
476
+ return lines.join("\n");
477
+ }
478
+ function ensureDir(path) {
479
+ mkdirSync(path, { recursive: true });
480
+ }
481
+ function copyMarkdownFiles(config) {
482
+ const copiedFiles = [];
483
+ function copyRecursive(dir, base = config.contentDir) {
484
+ try {
485
+ const entries = readdirSync(dir);
486
+ for (const entry of entries) {
487
+ const fullPath = join(dir, entry);
488
+ const stat = statSync(fullPath);
489
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
490
+ copyRecursive(fullPath, base);
491
+ } else if (stat.isFile() && extname(entry) === ".md") {
492
+ const relativePath = relative(base, fullPath);
493
+ const destPath = join(config.outDir, relativePath);
494
+ ensureDir(dirname(destPath));
495
+ try {
496
+ copyFileSync(fullPath, destPath);
497
+ copiedFiles.push({
498
+ source: fullPath,
499
+ destination: destPath
500
+ });
501
+ } catch (error) {
502
+ console.warn(`Warning: Could not copy ${fullPath}:`, error);
503
+ }
504
+ }
505
+ }
506
+ } catch (error) {
507
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
508
+ }
509
+ }
510
+ copyRecursive(config.contentDir);
511
+ return copiedFiles;
512
+ }
513
+ function generatePageMarkdownFiles(config) {
514
+ const generated = [];
515
+ const pages = config.pages || [];
516
+ for (const page of pages) {
517
+ if (!page.content) continue;
518
+ const pageTitle = page.title || (page.pathname === "/" ? config.title : void 0);
519
+ let filename;
520
+ if (page.pathname === "/") {
521
+ filename = "index.md";
522
+ } else {
523
+ const clean = page.pathname.replace(/^\//, "").replace(/\/$/, "");
524
+ filename = clean.includes("/") ? `${clean}.md` : `${clean}.md`;
525
+ }
526
+ const destPath = join(config.outDir, filename);
527
+ const pageUrl = page.pathname === "/" ? config.url : `${config.url.replace(/\/$/, "")}${page.pathname}`;
528
+ const lines = [];
529
+ lines.push("---");
530
+ if (pageTitle) lines.push(`title: "${pageTitle}"`);
531
+ if (page.description) lines.push(`description: "${page.description}"`);
532
+ lines.push(`url: ${pageUrl}`);
533
+ lines.push(`source: ${pageUrl}`);
534
+ lines.push(`generated_by: aeo.js`);
535
+ lines.push("---", "");
536
+ if (pageTitle) {
537
+ lines.push(`# ${pageTitle}`, "");
538
+ }
539
+ if (page.description) {
540
+ lines.push(`${page.description}`, "");
541
+ }
542
+ if (page.content) {
543
+ lines.push(page.content);
544
+ }
545
+ const content = lines.join("\n");
546
+ ensureDir(dirname(destPath));
547
+ try {
548
+ writeFileSync(destPath, content, "utf-8");
549
+ generated.push({ pathname: page.pathname, destination: destPath });
550
+ } catch {
551
+ }
552
+ }
553
+ return generated;
554
+ }
555
+ function collectManifestEntries(dir, config, base = dir) {
556
+ const entries = [];
557
+ try {
558
+ const files = readdirSync(dir);
559
+ for (const file of files) {
560
+ const fullPath = join(dir, file);
561
+ const stat = statSync(fullPath);
562
+ if (stat.isDirectory() && !file.startsWith(".") && file !== "node_modules") {
563
+ entries.push(...collectManifestEntries(fullPath, config, base));
564
+ } else if (stat.isFile() && (extname(file) === ".md" || extname(file) === ".mdx")) {
565
+ const content = readFileSync(fullPath, "utf-8");
566
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
567
+ const relativePath = relative(base, fullPath);
568
+ const urlPath = relativePath.replace(/\.mdx?$/, "");
569
+ entries.push({
570
+ url: `${config.url}/${urlPath}`,
571
+ title: frontmatter.title || extractTitle(mainContent),
572
+ description: frontmatter.description,
573
+ lastModified: stat.mtime.toISOString()
574
+ });
575
+ }
576
+ }
577
+ } catch (error) {
578
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
579
+ }
580
+ return entries;
581
+ }
582
+ function generateManifest(config) {
583
+ const entries = [];
584
+ if (config.pages && config.pages.length > 0) {
585
+ for (const page of config.pages) {
586
+ entries.push({
587
+ url: `${config.url}${page.pathname === "/" ? "" : page.pathname}`,
588
+ title: page.title || page.pathname,
589
+ description: page.description
590
+ });
591
+ }
592
+ }
593
+ entries.push(...collectManifestEntries(config.contentDir, config));
594
+ const manifest = {
595
+ version: "1.0",
596
+ generated: (/* @__PURE__ */ new Date()).toISOString(),
597
+ site: {
598
+ title: config.title,
599
+ description: config.description,
600
+ url: config.url
601
+ },
602
+ documents: entries.sort((a, b) => a.url.localeCompare(b.url)),
603
+ metadata: {
604
+ totalDocuments: entries.length,
605
+ generator: "aeo.js",
606
+ generatorUrl: "https://aeojs.org"
607
+ }
608
+ };
609
+ return JSON.stringify(manifest, null, 2);
610
+ }
611
+ function collectUrls(dir, config, base = dir) {
612
+ const urls = [];
613
+ try {
614
+ const entries = readdirSync(dir);
615
+ for (const entry of entries) {
616
+ const fullPath = join(dir, entry);
617
+ const stat = statSync(fullPath);
618
+ if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
619
+ urls.push(...collectUrls(fullPath, config, base));
620
+ } else if (stat.isFile() && (extname(entry) === ".md" || extname(entry) === ".mdx" || extname(entry) === ".html")) {
621
+ const relativePath = relative(base, fullPath);
622
+ const urlPath = relativePath.replace(/\.(md|mdx|html)$/, "");
623
+ urls.push(`${config.url}/${urlPath}`);
624
+ }
625
+ }
626
+ } catch (error) {
627
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
628
+ }
629
+ return urls;
630
+ }
631
+ function escapeXml(str) {
632
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
633
+ }
634
+ function generateSitemap(config) {
635
+ const urls = [];
636
+ if (config.pages && config.pages.length > 0) {
637
+ for (const page of config.pages) {
638
+ urls.push(`${config.url}${page.pathname === "/" ? "" : page.pathname}`);
639
+ }
640
+ }
641
+ if (config.contentDir) {
642
+ urls.push(...collectUrls(config.contentDir, config));
643
+ }
644
+ const lines = [
645
+ '<?xml version="1.0" encoding="UTF-8"?>',
646
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
647
+ ];
648
+ urls.push(config.url);
649
+ const uniqueUrls = [...new Set(urls)].sort();
650
+ for (const url of uniqueUrls) {
651
+ lines.push(" <url>");
652
+ lines.push(` <loc>${escapeXml(url)}</loc>`);
653
+ lines.push(` <lastmod>${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}</lastmod>`);
654
+ lines.push(" <changefreq>weekly</changefreq>");
655
+ lines.push(" <priority>0.8</priority>");
656
+ lines.push(" </url>");
657
+ }
658
+ lines.push("</urlset>");
659
+ return lines.join("\n");
660
+ }
661
+ function extractKeywords(content) {
662
+ const words = content.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((word) => word.length > 3);
663
+ const wordCount = {};
664
+ for (const word of words) {
665
+ wordCount[word] = (wordCount[word] || 0) + 1;
666
+ }
667
+ return Object.entries(wordCount).sort((a, b) => b[1] - a[1]).slice(0, 10).map(([word]) => word);
668
+ }
669
+ function chunkContent(content, maxLength = 2e3) {
670
+ const chunks = [];
671
+ const paragraphs = content.split("\n\n");
672
+ let currentChunk = "";
673
+ for (const paragraph of paragraphs) {
674
+ if (currentChunk.length + paragraph.length > maxLength && currentChunk.length > 0) {
675
+ chunks.push(currentChunk.trim());
676
+ currentChunk = "";
677
+ }
678
+ currentChunk += paragraph + "\n\n";
679
+ }
680
+ if (currentChunk.trim()) {
681
+ chunks.push(currentChunk.trim());
682
+ }
683
+ return chunks;
684
+ }
685
+ function collectAIIndexEntries(dir, config, base = dir) {
686
+ const entries = [];
687
+ try {
688
+ const files = readdirSync(dir);
689
+ for (const file of files) {
690
+ const fullPath = join(dir, file);
691
+ const stat = statSync(fullPath);
692
+ if (stat.isDirectory() && !file.startsWith(".") && file !== "node_modules") {
693
+ entries.push(...collectAIIndexEntries(fullPath, config, base));
694
+ } else if (stat.isFile() && (extname(file) === ".md" || extname(file) === ".mdx")) {
695
+ const content = readFileSync(fullPath, "utf-8");
696
+ const { frontmatter, content: mainContent } = parseFrontmatter(content);
697
+ const relativePath = relative(base, fullPath);
698
+ const urlPath = relativePath.replace(/\.mdx?$/, "");
699
+ const url = `${config.url}/${urlPath}`;
700
+ const chunks = chunkContent(mainContent);
701
+ const title = frontmatter.title || extractTitle(mainContent);
702
+ const keywords = extractKeywords(mainContent);
703
+ chunks.forEach((chunk, index) => {
704
+ const id = createHash("sha256").update(`${url}-${index}`).digest("hex").slice(0, 16);
705
+ entries.push({
706
+ id,
707
+ url,
708
+ title: chunks.length > 1 ? `${title} (Part ${index + 1})` : title,
709
+ content: chunk,
710
+ description: frontmatter.description,
711
+ keywords,
712
+ metadata: {
713
+ ...frontmatter,
714
+ chunkIndex: index,
715
+ totalChunks: chunks.length,
716
+ sourcePath: relativePath
717
+ }
718
+ });
719
+ });
720
+ }
721
+ }
722
+ } catch (error) {
723
+ console.warn(`Warning: Could not read directory ${dir}:`, error);
724
+ }
725
+ return entries;
726
+ }
727
+ function generateAIIndex(config) {
728
+ const entries = [];
729
+ if (config.pages && config.pages.length > 0) {
730
+ for (const page of config.pages) {
731
+ const url = `${config.url}${page.pathname === "/" ? "" : page.pathname}`;
732
+ const title = page.title || page.pathname;
733
+ const content = page.content || "";
734
+ if (content) {
735
+ const chunks = chunkContent(content);
736
+ const keywords = extractKeywords(content);
737
+ chunks.forEach((chunk, index2) => {
738
+ const id = createHash("sha256").update(`${url}-${index2}`).digest("hex").slice(0, 16);
739
+ entries.push({
740
+ id,
741
+ url,
742
+ title: chunks.length > 1 ? `${title} (Part ${index2 + 1})` : title,
743
+ content: chunk,
744
+ description: page.description,
745
+ keywords,
746
+ metadata: {
747
+ chunkIndex: index2,
748
+ totalChunks: chunks.length,
749
+ sourcePath: page.pathname
750
+ }
751
+ });
752
+ });
753
+ } else {
754
+ const id = createHash("sha256").update(url).digest("hex").slice(0, 16);
755
+ entries.push({
756
+ id,
757
+ url,
758
+ title,
759
+ content: page.description || title,
760
+ description: page.description,
761
+ keywords: []
762
+ });
763
+ }
764
+ }
765
+ }
766
+ entries.push(...collectAIIndexEntries(config.contentDir, config));
767
+ const index = {
768
+ version: "1.0",
769
+ generated: (/* @__PURE__ */ new Date()).toISOString(),
770
+ site: {
771
+ title: config.title,
772
+ description: config.description,
773
+ url: config.url
774
+ },
775
+ entries: entries.sort((a, b) => a.id.localeCompare(b.id)),
776
+ metadata: {
777
+ totalEntries: entries.length,
778
+ generator: "aeo.js",
779
+ generatorUrl: "https://aeojs.org",
780
+ embedding: {
781
+ recommended: "text-embedding-ada-002",
782
+ dimensions: 1536
783
+ }
784
+ }
785
+ };
786
+ return JSON.stringify(index, null, 2);
787
+ }
788
+
789
+ // src/core/schema.ts
790
+ function generateSchema(config) {
791
+ const output = generateSchemaObjects(config);
792
+ return JSON.stringify(output, null, 2);
793
+ }
794
+ function generateSchemaObjects(config) {
795
+ const siteSchemas = generateSiteSchemas(config);
796
+ const pageSchemas = {};
797
+ for (const page of config.pages) {
798
+ const schemas = generatePageSchemas(page, config);
799
+ if (schemas.length > 0) {
800
+ pageSchemas[page.pathname] = schemas;
801
+ }
802
+ }
803
+ return { site: siteSchemas, pages: pageSchemas };
804
+ }
805
+ function generateSiteSchemas(config) {
806
+ const schemas = [];
807
+ schemas.push({
808
+ "@context": "https://schema.org",
809
+ "@type": "WebSite",
810
+ name: config.title,
811
+ description: config.description || void 0,
812
+ url: config.url
813
+ });
814
+ const org = config.schema.organization;
815
+ if (org.name || org.sameAs.length > 0) {
816
+ const orgSchema = {
817
+ "@context": "https://schema.org",
818
+ "@type": "Organization",
819
+ name: org.name,
820
+ url: org.url
821
+ };
822
+ if (org.logo) orgSchema.logo = org.logo;
823
+ if (org.sameAs.length > 0) orgSchema.sameAs = org.sameAs;
824
+ schemas.push(orgSchema);
825
+ }
826
+ return schemas;
827
+ }
828
+ function generatePageSchemas(page, config) {
829
+ const schemas = [];
830
+ const pageUrl = page.pathname === "/" ? config.url : `${config.url.replace(/\/$/, "")}${page.pathname}`;
831
+ const faqItems = detectFaqPatterns(page.content || "");
832
+ if (faqItems.length > 0) {
833
+ schemas.push({
834
+ "@context": "https://schema.org",
835
+ "@type": "FAQPage",
836
+ mainEntity: faqItems.map(({ question, answer }) => ({
837
+ "@type": "Question",
838
+ name: question,
839
+ acceptedAnswer: {
840
+ "@type": "Answer",
841
+ text: answer
842
+ }
843
+ }))
844
+ });
845
+ }
846
+ const pageType = config.schema.defaultType;
847
+ const pageSchema = {
848
+ "@context": "https://schema.org",
849
+ "@type": pageType,
850
+ name: page.title || config.title,
851
+ url: pageUrl
852
+ };
853
+ if (page.description) pageSchema.description = page.description;
854
+ if (pageType === "Article") {
855
+ pageSchema.headline = page.title || config.title;
856
+ pageSchema.author = {
857
+ "@type": "Organization",
858
+ name: config.schema.organization.name
859
+ };
860
+ }
861
+ schemas.push(pageSchema);
862
+ if (page.pathname !== "/") {
863
+ const breadcrumbs = generateBreadcrumbs(page.pathname, config);
864
+ if (breadcrumbs.length > 1) {
865
+ schemas.push({
866
+ "@context": "https://schema.org",
867
+ "@type": "BreadcrumbList",
868
+ itemListElement: breadcrumbs.map((crumb, i) => ({
869
+ "@type": "ListItem",
870
+ position: i + 1,
871
+ name: crumb.name,
872
+ item: crumb.url
873
+ }))
874
+ });
875
+ }
876
+ }
877
+ return schemas;
878
+ }
879
+ function generateBreadcrumbs(pathname, config) {
880
+ const baseUrl = config.url.replace(/\/$/, "");
881
+ const parts = pathname.split("/").filter(Boolean);
882
+ const crumbs = [
883
+ { name: "Home", url: baseUrl + "/" }
884
+ ];
885
+ let currentPath = "";
886
+ for (const part of parts) {
887
+ currentPath += "/" + part;
888
+ crumbs.push({
889
+ name: part.charAt(0).toUpperCase() + part.slice(1).replace(/-/g, " "),
890
+ url: baseUrl + currentPath
891
+ });
892
+ }
893
+ return crumbs;
894
+ }
895
+ function detectFaqPatterns(content) {
896
+ const items = [];
897
+ const lines = content.split("\n");
898
+ for (let i = 0; i < lines.length; i++) {
899
+ const line = lines[i].trim();
900
+ const headingMatch = line.match(/^#{1,6}\s+(.+\?)\s*$/);
901
+ if (headingMatch) {
902
+ const answerLines = [];
903
+ for (let j = i + 1; j < lines.length; j++) {
904
+ const nextLine = lines[j].trim();
905
+ if (!nextLine) {
906
+ if (answerLines.length > 0) break;
907
+ continue;
908
+ }
909
+ if (/^#{1,6}\s/.test(nextLine)) break;
910
+ answerLines.push(nextLine);
911
+ }
912
+ if (answerLines.length > 0) {
913
+ items.push({
914
+ question: headingMatch[1],
915
+ answer: answerLines.join(" ").slice(0, 500)
916
+ });
917
+ }
918
+ }
919
+ }
920
+ return items;
921
+ }
922
+ async function generateAEOFiles(configOrRoot, maybeConfig) {
923
+ var _a;
924
+ let config;
925
+ if (typeof configOrRoot === "string") {
926
+ config = resolveConfig({ ...maybeConfig, outDir: configOrRoot });
927
+ } else if (configOrRoot && typeof configOrRoot === "object" && "generators" in configOrRoot && typeof ((_a = configOrRoot.generators) == null ? void 0 : _a.robotsTxt) === "boolean") {
928
+ config = configOrRoot;
929
+ } else {
930
+ config = resolveConfig(configOrRoot);
931
+ }
932
+ const outDir = config.outDir;
933
+ const files = [];
934
+ const errors = [];
935
+ if (!existsSync(outDir)) {
936
+ mkdirSync(outDir, { recursive: true });
937
+ }
938
+ if (config.generators.robotsTxt) {
939
+ try {
940
+ const content = generateRobotsTxt(config);
941
+ writeFileSync(join(outDir, "robots.txt"), content, "utf-8");
942
+ files.push("robots.txt");
943
+ } catch (e) {
944
+ errors.push(`robots.txt: ${e.message}`);
945
+ }
946
+ }
947
+ if (config.generators.llmsTxt) {
948
+ try {
949
+ const content = generateLlmsTxt(config);
950
+ writeFileSync(join(outDir, "llms.txt"), content, "utf-8");
951
+ files.push("llms.txt");
952
+ } catch (e) {
953
+ errors.push(`llms.txt: ${e.message}`);
954
+ }
955
+ }
956
+ if (config.generators.llmsFullTxt) {
957
+ try {
958
+ const content = generateLlmsFullTxt(config);
959
+ writeFileSync(join(outDir, "llms-full.txt"), content, "utf-8");
960
+ files.push("llms-full.txt");
961
+ } catch (e) {
962
+ errors.push(`llms-full.txt: ${e.message}`);
963
+ }
964
+ }
965
+ if (config.generators.rawMarkdown) {
966
+ try {
967
+ const generated = generatePageMarkdownFiles(config);
968
+ for (const f of generated) {
969
+ files.push(f.destination);
970
+ }
971
+ } catch (e) {
972
+ errors.push(`page-markdown: ${e.message}`);
973
+ }
974
+ try {
975
+ const copied = copyMarkdownFiles(config);
976
+ for (const f of copied) {
977
+ files.push(f.destination);
978
+ }
979
+ } catch (e) {
980
+ errors.push(`raw-markdown: ${e.message}`);
981
+ }
982
+ }
983
+ if (config.generators.manifest) {
984
+ try {
985
+ const content = generateManifest(config);
986
+ writeFileSync(join(outDir, "docs.json"), content, "utf-8");
987
+ files.push("docs.json");
988
+ } catch (e) {
989
+ errors.push(`docs.json: ${e.message}`);
990
+ }
991
+ }
992
+ if (config.generators.sitemap) {
993
+ try {
994
+ const content = generateSitemap(config);
995
+ writeFileSync(join(outDir, "sitemap.xml"), content, "utf-8");
996
+ files.push("sitemap.xml");
997
+ } catch (e) {
998
+ errors.push(`sitemap.xml: ${e.message}`);
999
+ }
1000
+ }
1001
+ if (config.generators.aiIndex) {
1002
+ try {
1003
+ const content = generateAIIndex(config);
1004
+ writeFileSync(join(outDir, "ai-index.json"), content, "utf-8");
1005
+ files.push("ai-index.json");
1006
+ } catch (e) {
1007
+ errors.push(`ai-index.json: ${e.message}`);
1008
+ }
1009
+ }
1010
+ if (config.generators.schema && config.schema.enabled) {
1011
+ try {
1012
+ const content = generateSchema(config);
1013
+ writeFileSync(join(outDir, "schema.json"), content, "utf-8");
1014
+ files.push("schema.json");
1015
+ } catch (e) {
1016
+ errors.push(`schema.json: ${e.message}`);
1017
+ }
1018
+ }
1019
+ return { files, errors };
1020
+ }
1021
+
1022
+ // src/core/audit.ts
1023
+ function auditSite(config) {
1024
+ const categories = [];
1025
+ const issues = [];
1026
+ const suggestions = [];
1027
+ categories.push(auditAIAccess(config, issues));
1028
+ categories.push(auditContentStructure(config, issues, suggestions));
1029
+ categories.push(auditSchemaPresence(config, issues, suggestions));
1030
+ categories.push(auditMetaQuality(config, issues, suggestions));
1031
+ categories.push(auditCitability(config, issues, suggestions));
1032
+ const score = categories.reduce((sum, c) => sum + c.score, 0);
1033
+ return { score, categories, issues, suggestions };
1034
+ }
1035
+ function auditAIAccess(config, issues) {
1036
+ const checks = [];
1037
+ config.outDir;
1038
+ const robotsEnabled = config.generators.robotsTxt;
1039
+ checks.push({ label: "robots.txt generation enabled", passed: robotsEnabled, points: robotsEnabled ? 4 : 0 });
1040
+ if (!robotsEnabled) {
1041
+ issues.push({ category: "AI Access", severity: "error", message: "robots.txt generation is disabled", fix: "Set generators.robotsTxt: true" });
1042
+ }
1043
+ const llmsEnabled = config.generators.llmsTxt;
1044
+ checks.push({ label: "llms.txt generation enabled", passed: llmsEnabled, points: llmsEnabled ? 4 : 0 });
1045
+ if (!llmsEnabled) {
1046
+ issues.push({ category: "AI Access", severity: "error", message: "llms.txt generation is disabled \u2014 AI crawlers won't find your content summary", fix: "Set generators.llmsTxt: true" });
1047
+ }
1048
+ const sitemapEnabled = config.generators.sitemap;
1049
+ checks.push({ label: "sitemap.xml generation enabled", passed: sitemapEnabled, points: sitemapEnabled ? 4 : 0 });
1050
+ if (!sitemapEnabled) {
1051
+ issues.push({ category: "AI Access", severity: "warning", message: "sitemap.xml generation is disabled", fix: "Set generators.sitemap: true" });
1052
+ }
1053
+ const aiIndexEnabled = config.generators.aiIndex;
1054
+ checks.push({ label: "ai-index.json generation enabled", passed: aiIndexEnabled, points: aiIndexEnabled ? 4 : 0 });
1055
+ if (!aiIndexEnabled) {
1056
+ issues.push({ category: "AI Access", severity: "warning", message: "ai-index.json generation is disabled", fix: "Set generators.aiIndex: true" });
1057
+ }
1058
+ const hasBlockingRules = config.robots.disallow.includes("/") || config.robots.disallow.includes("/*");
1059
+ const noBlocking = !hasBlockingRules;
1060
+ checks.push({ label: "No blanket disallow rules blocking AI crawlers", passed: noBlocking, points: noBlocking ? 4 : 0 });
1061
+ if (hasBlockingRules) {
1062
+ issues.push({ category: "AI Access", severity: "error", message: "robots.txt has blanket disallow (/ or /*) which blocks AI crawlers", fix: "Remove overly broad disallow rules from robots.disallow" });
1063
+ }
1064
+ return {
1065
+ name: "AI Access",
1066
+ score: checks.reduce((s, c) => s + c.points, 0),
1067
+ maxScore: 20,
1068
+ checks
1069
+ };
1070
+ }
1071
+ function auditContentStructure(config, issues, suggestions) {
1072
+ const checks = [];
1073
+ const pages = config.pages;
1074
+ const hasPages = pages.length > 0;
1075
+ checks.push({ label: "Pages are defined", passed: hasPages, points: hasPages ? 4 : 0 });
1076
+ if (!hasPages) {
1077
+ issues.push({ category: "Content Structure", severity: "error", message: "No pages defined \u2014 AEO files will have no content", fix: "Add pages to your config or ensure your framework plugin scans pages" });
1078
+ }
1079
+ const pagesWithContent = pages.filter((p) => p.content && p.content.length > 50);
1080
+ const hasContent = pagesWithContent.length > 0;
1081
+ checks.push({ label: "Pages have extractable content", passed: hasContent, points: hasContent ? 4 : 0 });
1082
+ if (!hasContent && hasPages) {
1083
+ issues.push({ category: "Content Structure", severity: "warning", message: "No pages have substantial text content (>50 chars)", fix: "Ensure pages have meaningful text content for AI extraction" });
1084
+ }
1085
+ const headingPattern = /^#{1,6}\s|<h[1-6]/m;
1086
+ const pagesWithHeadings = pagesWithContent.filter((p) => headingPattern.test(p.content || ""));
1087
+ const hasHeadings = pagesWithHeadings.length >= Math.max(1, Math.floor(pagesWithContent.length * 0.5));
1088
+ checks.push({ label: "Content uses heading hierarchy", passed: hasHeadings, points: hasHeadings ? 4 : 0 });
1089
+ if (!hasHeadings && pagesWithContent.length > 0) {
1090
+ suggestions.push("Add structured headings (H1-H6) to improve AI content extraction");
1091
+ }
1092
+ const goodParagraphLength = pagesWithContent.every((p) => {
1093
+ const paragraphs = (p.content || "").split(/\n\n+/).filter((p2) => p2.trim().length > 20);
1094
+ if (paragraphs.length === 0) return true;
1095
+ const avgWords = paragraphs.reduce((sum, para) => sum + para.split(/\s+/).length, 0) / paragraphs.length;
1096
+ return avgWords <= 200;
1097
+ });
1098
+ checks.push({ label: "Paragraphs are reasonable length (<200 words avg)", passed: goodParagraphLength, points: goodParagraphLength ? 4 : 0 });
1099
+ if (!goodParagraphLength) {
1100
+ suggestions.push("Break up long paragraphs (>200 words) for better AI extraction \u2014 aim for 100-167 words");
1101
+ }
1102
+ const multiplePages = pages.length >= 3;
1103
+ checks.push({ label: "Site has 3+ pages for comprehensive coverage", passed: multiplePages, points: multiplePages ? 4 : 0 });
1104
+ if (!multiplePages && hasPages) {
1105
+ suggestions.push("Add more pages to improve site coverage for AI crawlers");
1106
+ }
1107
+ return {
1108
+ name: "Content Structure",
1109
+ score: checks.reduce((s, c) => s + c.points, 0),
1110
+ maxScore: 20,
1111
+ checks
1112
+ };
1113
+ }
1114
+ function auditSchemaPresence(config, issues, suggestions) {
1115
+ const checks = [];
1116
+ const schemaEnabled = config.schema.enabled && config.generators.schema;
1117
+ checks.push({ label: "Schema.org/JSON-LD generation enabled", passed: schemaEnabled, points: schemaEnabled ? 4 : 0 });
1118
+ if (!schemaEnabled) {
1119
+ issues.push({ category: "Schema Presence", severity: "error", message: "Schema.org generation is disabled", fix: "Set schema.enabled: true and generators.schema: true" });
1120
+ }
1121
+ const hasOrgName = config.schema.organization.name !== "" && config.schema.organization.name !== "My Site";
1122
+ checks.push({ label: "Organization name configured", passed: hasOrgName, points: hasOrgName ? 4 : 0 });
1123
+ if (!hasOrgName) {
1124
+ issues.push({ category: "Schema Presence", severity: "warning", message: "Organization name is not configured (using default)", fix: "Set schema.organization.name to your actual organization name" });
1125
+ }
1126
+ const hasLogo = !!config.schema.organization.logo;
1127
+ checks.push({ label: "Organization logo URL set", passed: hasLogo, points: hasLogo ? 4 : 0 });
1128
+ if (!hasLogo) {
1129
+ suggestions.push("Add schema.organization.logo for richer search results and AI knowledge");
1130
+ }
1131
+ const hasSameAs = config.schema.organization.sameAs.length > 0;
1132
+ checks.push({ label: "Social profiles linked (sameAs)", passed: hasSameAs, points: hasSameAs ? 4 : 0 });
1133
+ if (!hasSameAs) {
1134
+ issues.push({ category: "Schema Presence", severity: "warning", message: "No social profiles (sameAs) \u2014 critical for GEO/E-E-A-T signals", fix: "Add schema.organization.sameAs with social profile URLs" });
1135
+ }
1136
+ const hasRealUrl = config.url !== "https://example.com" && config.url !== "";
1137
+ checks.push({ label: "Site URL is configured (not default)", passed: hasRealUrl, points: hasRealUrl ? 4 : 0 });
1138
+ if (!hasRealUrl) {
1139
+ issues.push({ category: "Schema Presence", severity: "error", message: "Site URL is still the default (https://example.com)", fix: "Set url to your actual site URL" });
1140
+ }
1141
+ return {
1142
+ name: "Schema Presence",
1143
+ score: checks.reduce((s, c) => s + c.points, 0),
1144
+ maxScore: 20,
1145
+ checks
1146
+ };
1147
+ }
1148
+ function auditMetaQuality(config, issues, suggestions) {
1149
+ const checks = [];
1150
+ const titleLen = config.title.length;
1151
+ const goodTitle = titleLen >= 10 && titleLen <= 70;
1152
+ checks.push({ label: "Site title is 10-70 characters", passed: goodTitle, points: goodTitle ? 4 : 0 });
1153
+ if (titleLen < 10) {
1154
+ issues.push({ category: "Meta Quality", severity: "warning", message: `Site title is too short (${titleLen} chars)`, fix: "Use a descriptive title between 10-70 characters" });
1155
+ } else if (titleLen > 70) {
1156
+ suggestions.push(`Site title is long (${titleLen} chars) \u2014 consider shortening to under 70`);
1157
+ }
1158
+ const descLen = config.description.length;
1159
+ const goodDesc = descLen >= 50 && descLen <= 200;
1160
+ checks.push({ label: "Site description is 50-200 characters", passed: goodDesc, points: goodDesc ? 4 : 0 });
1161
+ if (descLen === 0) {
1162
+ issues.push({ category: "Meta Quality", severity: "error", message: "No site description configured", fix: "Add a description (50-200 characters)" });
1163
+ } else if (descLen < 50) {
1164
+ issues.push({ category: "Meta Quality", severity: "warning", message: `Description is too short (${descLen} chars)`, fix: "Expand description to 50-200 characters" });
1165
+ }
1166
+ const ogEnabled = config.og.enabled;
1167
+ checks.push({ label: "Open Graph meta tags enabled", passed: ogEnabled, points: ogEnabled ? 4 : 0 });
1168
+ if (!ogEnabled) {
1169
+ issues.push({ category: "Meta Quality", severity: "warning", message: "OG meta tags are disabled \u2014 social sharing and AI previews will be limited", fix: "Set og.enabled: true" });
1170
+ }
1171
+ const pagesWithTitles = config.pages.filter((p) => p.title && p.title.length > 0);
1172
+ const titleCoverage = config.pages.length > 0 ? pagesWithTitles.length / config.pages.length : 0;
1173
+ const goodTitleCoverage = titleCoverage >= 0.8;
1174
+ checks.push({ label: "80%+ of pages have titles", passed: goodTitleCoverage, points: goodTitleCoverage ? 4 : 0 });
1175
+ if (!goodTitleCoverage && config.pages.length > 0) {
1176
+ issues.push({ category: "Meta Quality", severity: "warning", message: `Only ${pagesWithTitles.length}/${config.pages.length} pages have titles`, fix: "Add titles to all pages" });
1177
+ }
1178
+ const pagesWithDesc = config.pages.filter((p) => p.description && p.description.length > 0);
1179
+ const descCoverage = config.pages.length > 0 ? pagesWithDesc.length / config.pages.length : 0;
1180
+ const goodDescCoverage = descCoverage >= 0.5;
1181
+ checks.push({ label: "50%+ of pages have descriptions", passed: goodDescCoverage, points: goodDescCoverage ? 4 : 0 });
1182
+ if (!goodDescCoverage && config.pages.length > 0) {
1183
+ suggestions.push(`Only ${pagesWithDesc.length}/${config.pages.length} pages have descriptions \u2014 add per-page descriptions`);
1184
+ }
1185
+ return {
1186
+ name: "Meta Quality",
1187
+ score: checks.reduce((s, c) => s + c.points, 0),
1188
+ maxScore: 20,
1189
+ checks
1190
+ };
1191
+ }
1192
+ function auditCitability(config, issues, suggestions) {
1193
+ const checks = [];
1194
+ const allContent = config.pages.map((p) => p.content || "").join("\n\n");
1195
+ const directAnswerPattern = /^[A-Z][^.!?]{20,150}[.!?]/m;
1196
+ const hasDirectAnswers = directAnswerPattern.test(allContent);
1197
+ checks.push({ label: "Content has direct answer patterns", passed: hasDirectAnswers, points: hasDirectAnswers ? 4 : 0 });
1198
+ if (!hasDirectAnswers) {
1199
+ suggestions.push("Add self-contained factual statements that AI can cite directly");
1200
+ }
1201
+ const statPattern = /\d+%|\$[\d,.]+|\d{4}|\d+\s*(million|billion|thousand|users|customers|downloads)/i;
1202
+ const hasStats = statPattern.test(allContent);
1203
+ checks.push({ label: "Content includes statistics/factual claims", passed: hasStats, points: hasStats ? 4 : 0 });
1204
+ if (!hasStats) {
1205
+ suggestions.push("Include concrete statistics, numbers, and dates \u2014 AI favors content with factual claims");
1206
+ }
1207
+ const faqPattern = /^#{1,6}\s+.+\?\s*$/m;
1208
+ const hasFaq = faqPattern.test(allContent);
1209
+ checks.push({ label: "Content has FAQ patterns (question headings)", passed: hasFaq, points: hasFaq ? 4 : 0 });
1210
+ if (!hasFaq) {
1211
+ suggestions.push("Add FAQ sections with question headings \u2014 these generate FAQPage schema automatically");
1212
+ }
1213
+ const listPattern = /^[\s]*[-*+]\s|^\d+\.\s/m;
1214
+ const hasLists = listPattern.test(allContent);
1215
+ checks.push({ label: "Content uses lists for structured information", passed: hasLists, points: hasLists ? 4 : 0 });
1216
+ if (!hasLists) {
1217
+ suggestions.push("Use bullet or numbered lists for key information \u2014 improves AI extraction");
1218
+ }
1219
+ const wordCount = allContent.split(/\s+/).filter((w) => w.length > 0).length;
1220
+ const substantialContent = wordCount >= 500;
1221
+ checks.push({ label: "Total content is substantial (500+ words)", passed: substantialContent, points: substantialContent ? 4 : 0 });
1222
+ if (!substantialContent) {
1223
+ issues.push({ category: "Citability", severity: "warning", message: `Total content is only ${wordCount} words`, fix: "Add more content \u2014 aim for at least 500 words across all pages" });
1224
+ }
1225
+ return {
1226
+ name: "Citability",
1227
+ score: checks.reduce((s, c) => s + c.points, 0),
1228
+ maxScore: 20,
1229
+ checks
1230
+ };
1231
+ }
1232
+ function formatAuditReport(result) {
1233
+ const lines = [];
1234
+ const grade = getGrade(result.score);
1235
+ lines.push(`GEO Readiness Score: ${result.score}/100 (${grade})`);
1236
+ lines.push("\u2550".repeat(50));
1237
+ lines.push("");
1238
+ for (const cat of result.categories) {
1239
+ lines.push(`${cat.name}: ${cat.score}/${cat.maxScore}`);
1240
+ const bar = "\u2588".repeat(cat.score) + "\u2591".repeat(cat.maxScore - cat.score);
1241
+ lines.push(` ${bar}`);
1242
+ for (const check of cat.checks) {
1243
+ lines.push(` ${check.passed ? "+" : "-"} ${check.label}`);
1244
+ }
1245
+ lines.push("");
1246
+ }
1247
+ if (result.issues.length > 0) {
1248
+ lines.push("Issues:");
1249
+ for (const issue of result.issues) {
1250
+ const icon = issue.severity === "error" ? "!" : issue.severity === "warning" ? "~" : "i";
1251
+ lines.push(` ${icon} [${issue.category}] ${issue.message}`);
1252
+ if (issue.fix) lines.push(` Fix: ${issue.fix}`);
1253
+ }
1254
+ lines.push("");
1255
+ }
1256
+ if (result.suggestions.length > 0) {
1257
+ lines.push("Suggestions:");
1258
+ for (const suggestion of result.suggestions) {
1259
+ lines.push(` * ${suggestion}`);
1260
+ }
1261
+ lines.push("");
1262
+ }
1263
+ return lines.join("\n");
1264
+ }
1265
+ function getGrade(score) {
1266
+ if (score >= 90) return "Excellent";
1267
+ if (score >= 75) return "Good";
1268
+ if (score >= 50) return "Fair";
1269
+ if (score >= 25) return "Needs Work";
1270
+ return "Poor";
1271
+ }
1272
+
1273
+ // src/core/citability.ts
1274
+ function scorePageCitability(page) {
1275
+ const content = page.content || "";
1276
+ const dimensions = [];
1277
+ const hints = [];
1278
+ dimensions.push(scoreAnswerBlocks(content, hints));
1279
+ dimensions.push(scoreSelfContainment(content, hints));
1280
+ dimensions.push(scoreStatisticalDensity(content, hints));
1281
+ dimensions.push(scoreStructureQuality(content, hints));
1282
+ const score = dimensions.reduce((sum, d) => sum + d.score, 0);
1283
+ return {
1284
+ pathname: page.pathname,
1285
+ score,
1286
+ dimensions,
1287
+ hints
1288
+ };
1289
+ }
1290
+ function scoreSiteCitability(config) {
1291
+ const pages = config.pages.map((p) => scorePageCitability(p));
1292
+ const averageScore = pages.length > 0 ? Math.round(pages.reduce((sum, p) => sum + p.score, 0) / pages.length) : 0;
1293
+ return { averageScore, pages };
1294
+ }
1295
+ function scoreAnswerBlocks(content, hints) {
1296
+ if (!content.trim()) {
1297
+ return { name: "Answer Blocks", score: 0, maxScore: 25, details: "No content" };
1298
+ }
1299
+ const paragraphs = splitParagraphs(content);
1300
+ let answerCount = 0;
1301
+ for (let i = 0; i < paragraphs.length; i++) {
1302
+ const para = paragraphs[i];
1303
+ const words = para.text.split(/\s+/).length;
1304
+ if (para.text.startsWith("#") || words < 15) continue;
1305
+ const startsWithSubject = /^[A-Z][a-z]/.test(para.text) && !/^(This|That|These|Those|It|They|We|He|She|I)\b/.test(para.text);
1306
+ const goodLength = words >= 20 && words <= 200;
1307
+ if (startsWithSubject && goodLength) {
1308
+ answerCount++;
1309
+ }
1310
+ }
1311
+ const answerRatio = paragraphs.length > 0 ? answerCount / Math.max(paragraphs.filter((p) => !p.text.startsWith("#")).length, 1) : 0;
1312
+ let score = 0;
1313
+ if (answerCount >= 3 && answerRatio >= 0.5) score = 25;
1314
+ else if (answerCount >= 2 && answerRatio >= 0.3) score = 20;
1315
+ else if (answerCount >= 1) score = 12;
1316
+ else score = 0;
1317
+ if (answerCount === 0) {
1318
+ hints.push({ type: "warning", message: "No direct answer paragraphs found \u2014 add self-contained factual paragraphs that start with a clear subject" });
1319
+ }
1320
+ for (const para of paragraphs) {
1321
+ const words = para.text.split(/\s+/).length;
1322
+ if (words > 200 && !para.text.startsWith("#")) {
1323
+ hints.push({ type: "suggestion", message: `Paragraph at line ${para.line} is ${words} words \u2014 split for better AI extraction (aim for <200)`, line: para.line });
1324
+ }
1325
+ }
1326
+ return { name: "Answer Blocks", score, maxScore: 25, details: `${answerCount} answer-quality paragraphs found` };
1327
+ }
1328
+ function scoreSelfContainment(content, hints) {
1329
+ if (!content.trim()) {
1330
+ return { name: "Self-Containment", score: 0, maxScore: 25, details: "No content" };
1331
+ }
1332
+ const paragraphs = splitParagraphs(content).filter((p) => !p.text.startsWith("#") && p.text.split(/\s+/).length >= 10);
1333
+ if (paragraphs.length === 0) {
1334
+ return { name: "Self-Containment", score: 5, maxScore: 25, details: "No substantial paragraphs" };
1335
+ }
1336
+ const contextPatterns = [
1337
+ /^(As mentioned|As noted|As described|As shown|As stated|As discussed)\b/i,
1338
+ /^(However|Furthermore|Moreover|Additionally|In addition|Nevertheless)\b/,
1339
+ /\b(above|below|previously|the following|as follows|see also)\b/i,
1340
+ /^(This|That|These|Those|It) (is|was|are|were|has|have|will|can|should|means)\b/
1341
+ ];
1342
+ let contextDependentCount = 0;
1343
+ for (const para of paragraphs) {
1344
+ const isContextDependent = contextPatterns.some((p) => p.test(para.text));
1345
+ if (isContextDependent) {
1346
+ contextDependentCount++;
1347
+ }
1348
+ }
1349
+ const selfContainedRatio = 1 - contextDependentCount / paragraphs.length;
1350
+ let score;
1351
+ if (selfContainedRatio >= 0.8) score = 25;
1352
+ else if (selfContainedRatio >= 0.6) score = 18;
1353
+ else if (selfContainedRatio >= 0.4) score = 12;
1354
+ else score = 5;
1355
+ if (contextDependentCount > 0) {
1356
+ hints.push({ type: "suggestion", message: `${contextDependentCount} paragraph(s) depend on surrounding context \u2014 rephrase to be self-contained for better AI citation` });
1357
+ }
1358
+ return { name: "Self-Containment", score, maxScore: 25, details: `${Math.round(selfContainedRatio * 100)}% of paragraphs are self-contained` };
1359
+ }
1360
+ function scoreStatisticalDensity(content, hints) {
1361
+ if (!content.trim()) {
1362
+ return { name: "Statistical Density", score: 0, maxScore: 25, details: "No content" };
1363
+ }
1364
+ const patterns = {
1365
+ percentages: /\d+(\.\d+)?%/g,
1366
+ currencies: /\$[\d,.]+|\€[\d,.]+|£[\d,.]+/g,
1367
+ years: /\b(19|20)\d{2}\b/g,
1368
+ quantities: /\b\d+[\s,]*(million|billion|thousand|hundred|K|M|B)\b/gi,
1369
+ metrics: /\b\d+(\.\d+)?\s*(users|customers|downloads|visitors|employees|countries|cities|hours|minutes|seconds|pages|files|requests)\b/gi,
1370
+ comparisons: /\b\d+x\b|\b\d+(\.\d+)?%\s*(faster|slower|more|less|better|worse|increase|decrease|growth|reduction)\b/gi
1371
+ };
1372
+ let totalMatches = 0;
1373
+ for (const [, pattern] of Object.entries(patterns)) {
1374
+ const matches = content.match(pattern);
1375
+ if (matches) totalMatches += matches.length;
1376
+ }
1377
+ const words = content.split(/\s+/).length;
1378
+ const density = words > 0 ? totalMatches / (words / 100) : 0;
1379
+ let score;
1380
+ if (density >= 3) score = 25;
1381
+ else if (density >= 1.5) score = 20;
1382
+ else if (density >= 0.5) score = 12;
1383
+ else if (totalMatches > 0) score = 6;
1384
+ else score = 0;
1385
+ if (totalMatches === 0) {
1386
+ hints.push({ type: "suggestion", message: "No statistics or factual claims found \u2014 AI favors content with concrete numbers, percentages, and dates" });
1387
+ }
1388
+ return { name: "Statistical Density", score, maxScore: 25, details: `${totalMatches} statistical claims (${density.toFixed(1)} per 100 words)` };
1389
+ }
1390
+ function scoreStructureQuality(content, hints) {
1391
+ if (!content.trim()) {
1392
+ return { name: "Structure Quality", score: 0, maxScore: 25, details: "No content" };
1393
+ }
1394
+ let points = 0;
1395
+ const details = [];
1396
+ const headings = content.match(/^#{1,6}\s.+$/gm) || [];
1397
+ if (headings.length > 0) {
1398
+ points += 7;
1399
+ details.push(`${headings.length} headings`);
1400
+ } else {
1401
+ hints.push({ type: "warning", message: "No headings found \u2014 add H1-H6 headings to structure content for AI extraction" });
1402
+ }
1403
+ const listItems = content.match(/^[\s]*[-*+]\s.+$|^\d+\.\s.+$/gm) || [];
1404
+ if (listItems.length >= 3) {
1405
+ points += 6;
1406
+ details.push(`${listItems.length} list items`);
1407
+ } else if (listItems.length > 0) {
1408
+ points += 3;
1409
+ details.push(`${listItems.length} list items`);
1410
+ } else {
1411
+ hints.push({ type: "suggestion", message: "No lists found \u2014 use bullet or numbered lists for key information" });
1412
+ }
1413
+ const paragraphs = splitParagraphs(content).filter((p) => !p.text.startsWith("#") && p.text.split(/\s+/).length >= 10);
1414
+ const avgWords = paragraphs.length > 0 ? paragraphs.reduce((sum, p) => sum + p.text.split(/\s+/).length, 0) / paragraphs.length : 0;
1415
+ if (avgWords > 0 && avgWords <= 167) {
1416
+ points += 6;
1417
+ details.push(`avg ${Math.round(avgWords)} words/paragraph`);
1418
+ } else if (avgWords > 0 && avgWords <= 250) {
1419
+ points += 3;
1420
+ details.push(`avg ${Math.round(avgWords)} words/paragraph (aim for <167)`);
1421
+ }
1422
+ const hasSummary = /^(#{1,3}\s*)?(summary|tl;?dr|overview|introduction|key takeaways|in brief)\s*$/im.test(content);
1423
+ const firstPara = paragraphs[0];
1424
+ const hasShortIntro = firstPara && firstPara.text.split(/\s+/).length <= 60;
1425
+ if (hasSummary) {
1426
+ points += 6;
1427
+ details.push("has summary section");
1428
+ } else if (hasShortIntro) {
1429
+ points += 3;
1430
+ details.push("has short intro");
1431
+ } else {
1432
+ hints.push({ type: "suggestion", message: "Add a summary or TL;DR section at the top \u2014 helps AI extract the key message" });
1433
+ }
1434
+ return { name: "Structure Quality", score: Math.min(points, 25), maxScore: 25, details: details.join(", ") || "minimal structure" };
1435
+ }
1436
+ function splitParagraphs(content) {
1437
+ const lines = content.split("\n");
1438
+ const paragraphs = [];
1439
+ let currentText = "";
1440
+ let currentLine = 1;
1441
+ for (let i = 0; i < lines.length; i++) {
1442
+ const line = lines[i].trim();
1443
+ if (line === "") {
1444
+ if (currentText) {
1445
+ paragraphs.push({ text: currentText.trim(), line: currentLine });
1446
+ currentText = "";
1447
+ }
1448
+ } else {
1449
+ if (!currentText) currentLine = i + 1;
1450
+ currentText += (currentText ? " " : "") + line;
1451
+ }
1452
+ }
1453
+ if (currentText) {
1454
+ paragraphs.push({ text: currentText.trim(), line: currentLine });
1455
+ }
1456
+ return paragraphs;
1457
+ }
1458
+ function formatPageCitability(result) {
1459
+ const lines = [];
1460
+ lines.push(`Page: ${result.pathname} \u2014 Score: ${result.score}/100`);
1461
+ lines.push("\u2500".repeat(40));
1462
+ for (const dim of result.dimensions) {
1463
+ const bar = "\u2588".repeat(dim.score) + "\u2591".repeat(dim.maxScore - dim.score);
1464
+ lines.push(` ${dim.name}: ${dim.score}/${dim.maxScore} ${bar}`);
1465
+ lines.push(` ${dim.details}`);
1466
+ }
1467
+ if (result.hints.length > 0) {
1468
+ lines.push("");
1469
+ lines.push(" Hints:");
1470
+ for (const hint of result.hints) {
1471
+ const icon = hint.type === "error" ? "!" : hint.type === "warning" ? "~" : "*";
1472
+ const loc = hint.line ? ` (line ${hint.line})` : "";
1473
+ lines.push(` ${icon} ${hint.message}${loc}`);
1474
+ }
1475
+ }
1476
+ return lines.join("\n");
1477
+ }
1478
+
1479
+ // src/core/platform-hints.ts
1480
+ function generatePlatformHints(audit, citability) {
1481
+ const hints = [];
1482
+ hints.push(chatgptHints(audit, citability));
1483
+ hints.push(perplexityHints(audit, citability));
1484
+ hints.push(googleAIHints(audit));
1485
+ hints.push(bingCopilotHints(audit, citability));
1486
+ return hints;
1487
+ }
1488
+ function chatgptHints(audit, citability) {
1489
+ const tips = [];
1490
+ const aiAccess = audit.categories.find((c) => c.name === "AI Access");
1491
+ const schema = audit.categories.find((c) => c.name === "Schema Presence");
1492
+ const content = audit.categories.find((c) => c.name === "Content Structure");
1493
+ const llmsCheck = aiAccess == null ? void 0 : aiAccess.checks.find((c) => c.label.includes("llms.txt"));
1494
+ if (!(llmsCheck == null ? void 0 : llmsCheck.passed)) {
1495
+ tips.push("Enable llms.txt \u2014 ChatGPT uses this to understand your site content");
1496
+ }
1497
+ const robotsCheck = aiAccess == null ? void 0 : aiAccess.checks.find((c) => c.label.includes("blanket disallow"));
1498
+ if (!(robotsCheck == null ? void 0 : robotsCheck.passed)) {
1499
+ tips.push("Allow GPTBot in robots.txt \u2014 blanket disallow blocks ChatGPT crawling");
1500
+ }
1501
+ if (schema && schema.score < 12) {
1502
+ tips.push("Add Article or WebPage schema \u2014 helps ChatGPT extract structured content");
1503
+ }
1504
+ if (citability && citability.averageScore < 50) {
1505
+ tips.push("Improve answer blocks \u2014 ChatGPT citations favor self-contained factual paragraphs");
1506
+ }
1507
+ if (content && content.score < 12) {
1508
+ tips.push("Add more structured content \u2014 headings and paragraphs help SearchGPT parse your pages");
1509
+ }
1510
+ if (tips.length === 0) tips.push("Your site is well-optimized for ChatGPT/SearchGPT");
1511
+ return {
1512
+ platform: "ChatGPT / SearchGPT",
1513
+ status: tips.length <= 1 ? "good" : tips.length <= 3 ? "needs-work" : "critical",
1514
+ tips
1515
+ };
1516
+ }
1517
+ function perplexityHints(audit, citability) {
1518
+ const tips = [];
1519
+ const meta = audit.categories.find((c) => c.name === "Meta Quality");
1520
+ const citabilityScore = audit.categories.find((c) => c.name === "Citability");
1521
+ if (citabilityScore && citabilityScore.score < 12) {
1522
+ tips.push("Add statistical claims and concrete data \u2014 Perplexity favors cite-able facts");
1523
+ }
1524
+ if (meta && meta.score < 12) {
1525
+ tips.push("Improve page titles and descriptions \u2014 Perplexity uses meta tags for source attribution");
1526
+ }
1527
+ const faqCheck = citabilityScore == null ? void 0 : citabilityScore.checks.find((c) => c.label.includes("FAQ"));
1528
+ if (!(faqCheck == null ? void 0 : faqCheck.passed)) {
1529
+ tips.push("Add FAQ sections with question headings \u2014 Perplexity surfaces Q&A content prominently");
1530
+ }
1531
+ if (citability && citability.averageScore < 40) {
1532
+ tips.push("Improve self-contained paragraphs \u2014 Perplexity extracts and cites individual passages");
1533
+ }
1534
+ if (tips.length === 0) tips.push("Your site is well-optimized for Perplexity");
1535
+ return {
1536
+ platform: "Perplexity",
1537
+ status: tips.length <= 1 ? "good" : tips.length <= 3 ? "needs-work" : "critical",
1538
+ tips
1539
+ };
1540
+ }
1541
+ function googleAIHints(audit, citability) {
1542
+ const tips = [];
1543
+ const schema = audit.categories.find((c) => c.name === "Schema Presence");
1544
+ const orgCheck = schema == null ? void 0 : schema.checks.find((c) => c.label.includes("Organization"));
1545
+ if (!(orgCheck == null ? void 0 : orgCheck.passed)) {
1546
+ tips.push("Configure Organization name \u2014 Google AI uses this for E-E-A-T authority signals");
1547
+ }
1548
+ const sameAsCheck = schema == null ? void 0 : schema.checks.find((c) => c.label.includes("sameAs"));
1549
+ if (!(sameAsCheck == null ? void 0 : sameAsCheck.passed)) {
1550
+ tips.push("Add sameAs social profiles \u2014 critical for Google Knowledge Panel and E-E-A-T");
1551
+ }
1552
+ const logoCheck = schema == null ? void 0 : schema.checks.find((c) => c.label.includes("logo"));
1553
+ if (!(logoCheck == null ? void 0 : logoCheck.passed)) {
1554
+ tips.push("Add Organization logo \u2014 enhances Google search presence and AI Overviews");
1555
+ }
1556
+ const schemaEnabled = schema == null ? void 0 : schema.checks.find((c) => c.label.includes("JSON-LD"));
1557
+ if (!(schemaEnabled == null ? void 0 : schemaEnabled.passed)) {
1558
+ tips.push("Enable Schema.org/JSON-LD \u2014 Google AI Overviews heavily rely on structured data");
1559
+ }
1560
+ if (tips.length === 0) tips.push("Your site is well-optimized for Google AI Overviews");
1561
+ return {
1562
+ platform: "Google AI Overviews",
1563
+ status: tips.length <= 1 ? "good" : tips.length <= 3 ? "needs-work" : "critical",
1564
+ tips
1565
+ };
1566
+ }
1567
+ function bingCopilotHints(audit, citability) {
1568
+ const tips = [];
1569
+ const aiAccess = audit.categories.find((c) => c.name === "AI Access");
1570
+ const meta = audit.categories.find((c) => c.name === "Meta Quality");
1571
+ const robotsCheck = aiAccess == null ? void 0 : aiAccess.checks.find((c) => c.label.includes("blanket disallow"));
1572
+ if (!(robotsCheck == null ? void 0 : robotsCheck.passed)) {
1573
+ tips.push("Remove blanket disallow \u2014 Bing Copilot requires Bingbot access");
1574
+ }
1575
+ const sitemapCheck = aiAccess == null ? void 0 : aiAccess.checks.find((c) => c.label.includes("sitemap"));
1576
+ if (!(sitemapCheck == null ? void 0 : sitemapCheck.passed)) {
1577
+ tips.push("Enable sitemap.xml \u2014 Bing Copilot relies on sitemaps for content discovery");
1578
+ }
1579
+ const ogCheck = meta == null ? void 0 : meta.checks.find((c) => c.label.includes("Open Graph"));
1580
+ if (!(ogCheck == null ? void 0 : ogCheck.passed)) {
1581
+ tips.push("Enable OG meta tags \u2014 Bing Copilot uses OG metadata for rich answers");
1582
+ }
1583
+ if (citability && citability.averageScore < 40) {
1584
+ tips.push("Improve content structure \u2014 Bing Copilot favors well-organized content with clear answers");
1585
+ }
1586
+ if (tips.length === 0) tips.push("Your site is well-optimized for Bing Copilot");
1587
+ return {
1588
+ platform: "Bing Copilot",
1589
+ status: tips.length <= 1 ? "good" : tips.length <= 3 ? "needs-work" : "critical",
1590
+ tips
1591
+ };
1592
+ }
1593
+
1594
+ // src/core/report.ts
1595
+ function generateReport(config) {
1596
+ const audit = auditSite(config);
1597
+ const citability = scoreSiteCitability(config);
1598
+ const platformHints = generatePlatformHints(audit, citability);
1599
+ return {
1600
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1601
+ site: {
1602
+ title: config.title,
1603
+ url: config.url,
1604
+ pageCount: config.pages.length
1605
+ },
1606
+ audit,
1607
+ citability,
1608
+ platformHints
1609
+ };
1610
+ }
1611
+ function formatReportMarkdown(report) {
1612
+ const lines = [];
1613
+ lines.push(`# AEO/GEO Report \u2014 ${report.site.title}`);
1614
+ lines.push("");
1615
+ lines.push(`Generated: ${report.generatedAt}`);
1616
+ lines.push(`URL: ${report.site.url}`);
1617
+ lines.push(`Pages: ${report.site.pageCount}`);
1618
+ lines.push("");
1619
+ lines.push("## GEO Readiness Score");
1620
+ lines.push("");
1621
+ lines.push(formatAuditReport(report.audit));
1622
+ lines.push("");
1623
+ lines.push("## AI Citability");
1624
+ lines.push("");
1625
+ lines.push(`Average Citability Score: ${report.citability.averageScore}/100`);
1626
+ lines.push("");
1627
+ for (const page of report.citability.pages) {
1628
+ lines.push(formatPageCitability(page));
1629
+ lines.push("");
1630
+ }
1631
+ lines.push("## Platform Optimization");
1632
+ lines.push("");
1633
+ for (const hint of report.platformHints) {
1634
+ const statusIcon = hint.status === "good" ? "+" : hint.status === "needs-work" ? "~" : "!";
1635
+ lines.push(`### ${statusIcon} ${hint.platform} (${hint.status})`);
1636
+ lines.push("");
1637
+ for (const tip of hint.tips) {
1638
+ lines.push(`- ${tip}`);
1639
+ }
1640
+ lines.push("");
1641
+ }
1642
+ return lines.join("\n");
1643
+ }
1644
+ function formatReportJson(report) {
1645
+ return JSON.stringify(report, null, 2);
1646
+ }
1647
+ var VERSION = "0.0.2";
1648
+ var HELP = `
1649
+ aeo.js v${VERSION} \u2014 Answer Engine Optimization for the modern web
1650
+
1651
+ Usage:
1652
+ npx aeo.js <command> [options]
1653
+
1654
+ Commands:
1655
+ generate Generate all AEO files (robots.txt, llms.txt, sitemap.xml, etc.)
1656
+ init Create an aeo.config.ts configuration file
1657
+ check Validate AEO setup + GEO readiness score (0-100)
1658
+ report Full AEO/GEO report with citability scores and platform hints
1659
+
1660
+ Options:
1661
+ --out <dir> Output directory (default: auto-detected)
1662
+ --url <url> Site URL (default: https://example.com)
1663
+ --title <title> Site title (default: My Site)
1664
+ --no-widget Disable widget generation
1665
+ --json Output audit results as JSON (check command)
1666
+ --help, -h Show this help message
1667
+ --version, -v Show version
1668
+
1669
+ Examples:
1670
+ npx aeo.js generate
1671
+ npx aeo.js generate --url https://mysite.com --title "My Site"
1672
+ npx aeo.js init
1673
+ npx aeo.js check
1674
+ npx aeo.js check --json
1675
+ npx aeo.js report
1676
+ npx aeo.js report --json
1677
+ `;
1678
+ function parseArgs(args) {
1679
+ let command = "help";
1680
+ const flags = {};
1681
+ for (let i = 0; i < args.length; i++) {
1682
+ const arg = args[i];
1683
+ if (arg === "--help" || arg === "-h") {
1684
+ flags.help = true;
1685
+ } else if (arg === "--version" || arg === "-v") {
1686
+ flags.version = true;
1687
+ } else if (arg === "--no-widget") {
1688
+ flags.noWidget = true;
1689
+ } else if (arg === "--json") {
1690
+ flags.json = true;
1691
+ } else if (arg.startsWith("--") && i + 1 < args.length) {
1692
+ const key = arg.slice(2);
1693
+ flags[key] = args[++i];
1694
+ } else if (!arg.startsWith("-") && command === "help") {
1695
+ command = arg;
1696
+ }
1697
+ }
1698
+ return { command, flags };
1699
+ }
1700
+ async function cmdGenerate(flags) {
1701
+ const framework = detectFramework();
1702
+ console.log(`[aeo.js] Detected framework: ${framework.framework}`);
1703
+ const config = resolveConfig({
1704
+ title: typeof flags.title === "string" ? flags.title : void 0,
1705
+ url: typeof flags.url === "string" ? flags.url : void 0,
1706
+ outDir: typeof flags.out === "string" ? flags.out : void 0,
1707
+ widget: flags.noWidget ? { enabled: false } : void 0
1708
+ });
1709
+ console.log(`[aeo.js] Output directory: ${config.outDir}`);
1710
+ console.log(`[aeo.js] Generating AEO files...`);
1711
+ const result = await generateAEOFiles(config);
1712
+ if (result.files.length > 0) {
1713
+ console.log(`[aeo.js] Generated ${result.files.length} files:`);
1714
+ for (const file of result.files) {
1715
+ console.log(` - ${file}`);
1716
+ }
1717
+ } else {
1718
+ console.log("[aeo.js] No files generated.");
1719
+ }
1720
+ if (result.errors.length > 0) {
1721
+ console.error(`[aeo.js] ${result.errors.length} error(s):`);
1722
+ for (const error of result.errors) {
1723
+ console.error(` - ${error}`);
1724
+ }
1725
+ process.exit(1);
1726
+ }
1727
+ }
1728
+ function cmdInit() {
1729
+ const configPath = join(process.cwd(), "aeo.config.ts");
1730
+ if (existsSync(configPath)) {
1731
+ console.error("[aeo.js] aeo.config.ts already exists. Remove it first to reinitialize.");
1732
+ process.exit(1);
1733
+ }
1734
+ const template = `import { defineConfig } from 'aeo.js';
1735
+
1736
+ export default defineConfig({
1737
+ // Required
1738
+ title: 'My Site',
1739
+ url: 'https://example.com',
1740
+
1741
+ // Optional
1742
+ description: 'A site optimized for AI discovery',
1743
+
1744
+ // Toggle individual generators
1745
+ generators: {
1746
+ robotsTxt: true,
1747
+ llmsTxt: true,
1748
+ llmsFullTxt: true,
1749
+ rawMarkdown: true,
1750
+ manifest: true,
1751
+ sitemap: true,
1752
+ aiIndex: true,
1753
+ },
1754
+
1755
+ // Customize robots.txt
1756
+ robots: {
1757
+ allow: ['/'],
1758
+ disallow: ['/admin'],
1759
+ crawlDelay: 0,
1760
+ },
1761
+
1762
+ // Widget configuration
1763
+ widget: {
1764
+ enabled: true,
1765
+ position: 'bottom-right',
1766
+ humanLabel: 'Human',
1767
+ aiLabel: 'AI',
1768
+ showBadge: true,
1769
+ theme: {
1770
+ background: 'rgba(18, 18, 24, 0.9)',
1771
+ text: '#C0C0C5',
1772
+ accent: '#E8E8EA',
1773
+ badge: '#4ADE80',
1774
+ },
1775
+ },
1776
+ });
1777
+ `;
1778
+ writeFileSync(configPath, template, "utf-8");
1779
+ console.log("[aeo.js] Created aeo.config.ts");
1780
+ console.log("[aeo.js] Edit the config and run `npx aeo.js generate` to generate AEO files.");
1781
+ }
1782
+ function cmdCheck(flags) {
1783
+ const framework = detectFramework();
1784
+ const config = resolveConfig({
1785
+ title: typeof flags.title === "string" ? flags.title : void 0,
1786
+ url: typeof flags.url === "string" ? flags.url : void 0,
1787
+ outDir: typeof flags.out === "string" ? flags.out : void 0
1788
+ });
1789
+ const auditResult = auditSite(config);
1790
+ if (flags.json) {
1791
+ console.log(JSON.stringify({ framework: framework.framework, config: { title: config.title, url: config.url, outDir: config.outDir }, audit: auditResult }, null, 2));
1792
+ return;
1793
+ }
1794
+ console.log(`[aeo.js] AEO Configuration Check`);
1795
+ console.log(`${"\u2500".repeat(40)}`);
1796
+ console.log(` Framework: ${framework.framework}`);
1797
+ console.log(` Content dir: ${config.contentDir}`);
1798
+ console.log(` Output dir: ${config.outDir}`);
1799
+ console.log(` Title: ${config.title}`);
1800
+ console.log(` URL: ${config.url}`);
1801
+ console.log(` Widget: ${config.widget.enabled ? "enabled" : "disabled"}`);
1802
+ console.log();
1803
+ console.log(` Generators:`);
1804
+ const generators = [
1805
+ ["robots.txt", config.generators.robotsTxt],
1806
+ ["llms.txt", config.generators.llmsTxt],
1807
+ ["llms-full.txt", config.generators.llmsFullTxt],
1808
+ ["raw markdown", config.generators.rawMarkdown],
1809
+ ["docs.json", config.generators.manifest],
1810
+ ["sitemap.xml", config.generators.sitemap],
1811
+ ["ai-index.json", config.generators.aiIndex],
1812
+ ["schema.json", config.generators.schema]
1813
+ ];
1814
+ for (const [name, enabled] of generators) {
1815
+ console.log(` ${enabled ? "+" : "-"} ${name}`);
1816
+ }
1817
+ const configPath = join(process.cwd(), "aeo.config.ts");
1818
+ const configPathJs = join(process.cwd(), "aeo.config.js");
1819
+ const hasConfig = existsSync(configPath) || existsSync(configPathJs);
1820
+ console.log();
1821
+ if (hasConfig) {
1822
+ console.log(` Config file: found`);
1823
+ } else {
1824
+ console.log(` Config file: not found (using defaults)`);
1825
+ console.log(` Run \`npx aeo.js init\` to create one.`);
1826
+ }
1827
+ console.log();
1828
+ console.log(formatAuditReport(auditResult));
1829
+ }
1830
+ function cmdReport(flags) {
1831
+ const config = resolveConfig({
1832
+ title: typeof flags.title === "string" ? flags.title : void 0,
1833
+ url: typeof flags.url === "string" ? flags.url : void 0,
1834
+ outDir: typeof flags.out === "string" ? flags.out : void 0
1835
+ });
1836
+ const report = generateReport(config);
1837
+ if (flags.json) {
1838
+ console.log(formatReportJson(report));
1839
+ } else {
1840
+ console.log(formatReportMarkdown(report));
1841
+ }
1842
+ }
1843
+ async function main() {
1844
+ const args = process.argv.slice(2);
1845
+ const { command, flags } = parseArgs(args);
1846
+ if (flags.version) {
1847
+ console.log(VERSION);
1848
+ return;
1849
+ }
1850
+ if (flags.help || command === "help") {
1851
+ console.log(HELP);
1852
+ return;
1853
+ }
1854
+ switch (command) {
1855
+ case "generate":
1856
+ await cmdGenerate(flags);
1857
+ break;
1858
+ case "init":
1859
+ cmdInit();
1860
+ break;
1861
+ case "check":
1862
+ cmdCheck(flags);
1863
+ break;
1864
+ case "report":
1865
+ cmdReport(flags);
1866
+ break;
1867
+ default:
1868
+ console.error(`Unknown command: ${command}`);
1869
+ console.log(HELP);
1870
+ process.exit(1);
1871
+ }
1872
+ }
1873
+ main().catch((error) => {
1874
+ console.error("[aeo.js] Fatal error:", error.message);
1875
+ process.exit(1);
1876
+ });
1877
+ //# sourceMappingURL=cli.mjs.map
1878
+ //# sourceMappingURL=cli.mjs.map