@umituz/web-seo 1.0.5 → 2.0.4

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 (47) hide show
  1. package/README.md +433 -0
  2. package/dist/domains/seo/components/JsonLd.d.ts +17 -0
  3. package/dist/domains/seo/components/JsonLd.d.ts.map +1 -0
  4. package/dist/domains/seo/components/JsonLd.js +52 -0
  5. package/dist/domains/seo/components/SEO.d.ts +4 -0
  6. package/dist/domains/seo/components/SEO.d.ts.map +1 -0
  7. package/dist/domains/seo/components/SEO.js +48 -0
  8. package/dist/domains/seo/core/init.d.ts +16 -0
  9. package/dist/domains/seo/core/init.d.ts.map +1 -0
  10. package/dist/domains/seo/core/init.js +34 -0
  11. package/dist/domains/seo/hooks/useJsonLd.d.ts +19 -0
  12. package/dist/domains/seo/hooks/useJsonLd.d.ts.map +1 -0
  13. package/dist/domains/seo/hooks/useJsonLd.js +53 -0
  14. package/dist/domains/seo/hooks/useSEO.d.ts +3 -0
  15. package/dist/domains/seo/hooks/useSEO.d.ts.map +1 -0
  16. package/dist/domains/seo/hooks/useSEO.js +47 -0
  17. package/dist/domains/seo/index.d.ts +15 -0
  18. package/dist/domains/seo/index.d.ts.map +1 -0
  19. package/dist/domains/seo/index.js +21 -0
  20. package/dist/domains/seo/ssr/renderer.d.ts +58 -0
  21. package/dist/domains/seo/ssr/renderer.d.ts.map +1 -0
  22. package/dist/domains/seo/ssr/renderer.js +242 -0
  23. package/dist/domains/seo/ssr/serializer.d.ts +71 -0
  24. package/dist/domains/seo/ssr/serializer.d.ts.map +1 -0
  25. package/dist/domains/seo/ssr/serializer.js +175 -0
  26. package/dist/domains/seo/types/index.d.ts +190 -0
  27. package/dist/domains/seo/types/index.d.ts.map +1 -0
  28. package/dist/domains/seo/types/index.js +1 -0
  29. package/dist/domains/seo/types/schema.d.ts +212 -0
  30. package/dist/domains/seo/types/schema.d.ts.map +1 -0
  31. package/dist/domains/seo/types/schema.js +4 -0
  32. package/dist/domains/seo/utils/dom.d.ts +22 -0
  33. package/dist/domains/seo/utils/dom.d.ts.map +1 -0
  34. package/dist/domains/seo/utils/dom.js +537 -0
  35. package/dist/domains/seo/utils/schema.d.ts +135 -0
  36. package/dist/domains/seo/utils/schema.d.ts.map +1 -0
  37. package/dist/domains/seo/utils/schema.js +321 -0
  38. package/dist/domains/seo/utils/validators.d.ts +39 -0
  39. package/dist/domains/seo/utils/validators.d.ts.map +1 -0
  40. package/dist/domains/seo/utils/validators.js +364 -0
  41. package/dist/domains/seo/vite/plugin.d.ts +61 -0
  42. package/dist/domains/seo/vite/plugin.d.ts.map +1 -0
  43. package/dist/domains/seo/vite/plugin.js +215 -0
  44. package/dist/index.d.ts +2 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +6 -0
  47. package/package.json +34 -5
@@ -0,0 +1,364 @@
1
+ /**
2
+ * SEO Validators
3
+ *
4
+ * Validation utilities for SEO configuration and content.
5
+ * Helps catch common SEO issues before they affect search rankings.
6
+ */
7
+ // ============================================================================
8
+ // URL Validation
9
+ // ============================================================================
10
+ export const isValidUrl = (url) => {
11
+ if (!url)
12
+ return false;
13
+ try {
14
+ const parsed = new URL(url);
15
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ };
21
+ export const validateUrl = (url, fieldName = "URL") => {
22
+ if (!url) {
23
+ return `${fieldName} is required`;
24
+ }
25
+ if (!isValidUrl(url)) {
26
+ return `${fieldName} must be a valid HTTP/HTTPS URL`;
27
+ }
28
+ return null;
29
+ };
30
+ // ============================================================================
31
+ // Content Length Validation
32
+ // ============================================================================
33
+ export const TITLE_MIN_LENGTH = 30;
34
+ export const TITLE_MAX_LENGTH = 60;
35
+ export const DESCRIPTION_MIN_LENGTH = 120;
36
+ export const DESCRIPTION_MAX_LENGTH = 160;
37
+ export const validateTitleLength = (title) => {
38
+ if (!title) {
39
+ return "Title is required";
40
+ }
41
+ if (title.length < TITLE_MIN_LENGTH) {
42
+ return `Title is too short (${title.length} chars). Recommended: ${TITLE_MIN_LENGTH}-${TITLE_MAX_LENGTH} chars`;
43
+ }
44
+ if (title.length > TITLE_MAX_LENGTH) {
45
+ return `Title is too long (${title.length} chars). Recommended: ${TITLE_MIN_LENGTH}-${TITLE_MAX_LENGTH} chars`;
46
+ }
47
+ return null;
48
+ };
49
+ export const validateDescriptionLength = (description) => {
50
+ if (!description) {
51
+ return "Description is required";
52
+ }
53
+ if (description.length < DESCRIPTION_MIN_LENGTH) {
54
+ return `Description is too short (${description.length} chars). Recommended: ${DESCRIPTION_MIN_LENGTH}-${DESCRIPTION_MAX_LENGTH} chars`;
55
+ }
56
+ if (description.length > DESCRIPTION_MAX_LENGTH) {
57
+ return `Description is too long (${description.length} chars). Recommended: ${DESCRIPTION_MIN_LENGTH}-${DESCRIPTION_MAX_LENGTH} chars`;
58
+ }
59
+ return null;
60
+ };
61
+ // ============================================================================
62
+ // Image Validation for Social Sharing
63
+ // ============================================================================
64
+ export const OG_IMAGE_MIN_WIDTH = 1200;
65
+ export const OG_IMAGE_MIN_HEIGHT = 630;
66
+ export const OG_IMAGE_MAX_SIZE = 8 * 1024 * 1024; // 8MB
67
+ export const validateOpenGraphImage = (imageUrl, width, height, size) => {
68
+ if (!imageUrl) {
69
+ return "Open Graph image URL is required";
70
+ }
71
+ if (!isValidUrl(imageUrl)) {
72
+ return "Open Graph image URL must be valid";
73
+ }
74
+ if (width !== undefined && width < OG_IMAGE_MIN_WIDTH) {
75
+ return `Open Graph image width should be at least ${OG_IMAGE_MIN_WIDTH}px (current: ${width}px)`;
76
+ }
77
+ if (height !== undefined && height < OG_IMAGE_MIN_HEIGHT) {
78
+ return `Open Graph image height should be at least ${OG_IMAGE_MIN_HEIGHT}px (current: ${height}px)`;
79
+ }
80
+ if (size !== undefined && size > OG_IMAGE_MAX_SIZE) {
81
+ return `Open Graph image size should not exceed ${OG_IMAGE_MAX_SIZE / 1024 / 1024}MB`;
82
+ }
83
+ return null;
84
+ };
85
+ // ============================================================================
86
+ // Hreflang Validation
87
+ // ============================================================================
88
+ export const isValidLanguageCode = (code) => {
89
+ // Check if it's a valid language code (e.g., "en", "en-US", "x-default")
90
+ const langCodeRegex = /^(?:[a-z]{2,3}(?:-[A-Z]{2})?|x-default)$/;
91
+ return langCodeRegex.test(code);
92
+ };
93
+ export const validateHreflangEntry = (entry) => {
94
+ if (!entry.lang) {
95
+ return "Hreflang language code is required";
96
+ }
97
+ if (!isValidLanguageCode(entry.lang)) {
98
+ return `Invalid language code: ${entry.lang}`;
99
+ }
100
+ const urlError = validateUrl(entry.url, "Hreflang URL");
101
+ if (urlError) {
102
+ return urlError;
103
+ }
104
+ return null;
105
+ };
106
+ // ============================================================================
107
+ // JSON-LD Validation
108
+ // ============================================================================
109
+ export const validateJsonLd = (jsonLd) => {
110
+ const errors = [];
111
+ // Check @context
112
+ if (!jsonLd["@context"]) {
113
+ errors.push('JSON-LD must have a "@context" property');
114
+ }
115
+ // Check @type
116
+ if (!jsonLd["@type"]) {
117
+ errors.push('JSON-LD must have a "@type" property');
118
+ }
119
+ // Type-specific validation
120
+ const type = jsonLd["@type"];
121
+ switch (type) {
122
+ case "Article":
123
+ case "NewsArticle":
124
+ case "BlogPosting": {
125
+ const article = jsonLd;
126
+ if (!article.headline)
127
+ errors.push("Article must have a headline");
128
+ if (!article.image)
129
+ errors.push("Article must have an image");
130
+ if (!article.datePublished)
131
+ errors.push("Article must have datePublished");
132
+ if (!article.author)
133
+ errors.push("Article must have an author");
134
+ if (!article.publisher)
135
+ errors.push("Article must have a publisher");
136
+ break;
137
+ }
138
+ case "Product": {
139
+ const product = jsonLd;
140
+ if (!product.name)
141
+ errors.push("Product must have a name");
142
+ if (!product.offers)
143
+ errors.push("Product must have offers");
144
+ break;
145
+ }
146
+ case "Organization": {
147
+ const org = jsonLd;
148
+ if (!org.name)
149
+ errors.push("Organization must have a name");
150
+ break;
151
+ }
152
+ case "BreadcrumbList": {
153
+ const breadcrumb = jsonLd;
154
+ if (!breadcrumb.itemListElement || breadcrumb.itemListElement.length === 0) {
155
+ errors.push("BreadcrumbList must have itemListElement");
156
+ }
157
+ break;
158
+ }
159
+ case "FAQPage": {
160
+ const faq = jsonLd;
161
+ if (!faq.mainEntity || faq.mainEntity.length === 0) {
162
+ errors.push("FAQPage must have mainEntity");
163
+ }
164
+ break;
165
+ }
166
+ case "VideoObject": {
167
+ const video = jsonLd;
168
+ if (!video.name)
169
+ errors.push("Video must have a name");
170
+ if (!video.thumbnailUrl)
171
+ errors.push("Video must have thumbnailUrl");
172
+ if (!video.uploadDate)
173
+ errors.push("Video must have uploadDate");
174
+ break;
175
+ }
176
+ }
177
+ return errors;
178
+ };
179
+ // ============================================================================
180
+ // Comprehensive SEO Validation
181
+ // ============================================================================
182
+ export const validateSEO = (options) => {
183
+ const errors = [];
184
+ const warnings = [];
185
+ const suggestions = [];
186
+ // Title validation
187
+ if (options.title) {
188
+ const titleError = validateTitleLength(options.title);
189
+ if (titleError) {
190
+ if (options.title === "" || !options.title) {
191
+ errors.push(titleError);
192
+ }
193
+ else {
194
+ warnings.push(titleError);
195
+ }
196
+ }
197
+ }
198
+ else {
199
+ errors.push("Title is missing");
200
+ }
201
+ // Description validation
202
+ if (options.description) {
203
+ const descError = validateDescriptionLength(options.description);
204
+ if (descError) {
205
+ if (options.description === "" || !options.description) {
206
+ errors.push(descError);
207
+ }
208
+ else {
209
+ warnings.push(descError);
210
+ }
211
+ }
212
+ }
213
+ else {
214
+ warnings.push("Description is missing");
215
+ }
216
+ // Canonical URL validation
217
+ if (options.canonical) {
218
+ const canonicalError = validateUrl(options.canonical, "Canonical URL");
219
+ if (canonicalError) {
220
+ errors.push(canonicalError);
221
+ }
222
+ }
223
+ else {
224
+ suggestions.push("Add a canonical URL to prevent duplicate content issues");
225
+ }
226
+ // Language validation
227
+ if (!options.lang) {
228
+ warnings.push("Language attribute is missing");
229
+ suggestions.push('Add lang attribute (e.g., <html lang="en">)');
230
+ }
231
+ // Open Graph validation
232
+ if (!options.openGraph) {
233
+ suggestions.push("Add Open Graph tags for better social media sharing");
234
+ }
235
+ else {
236
+ if (!options.openGraph.image) {
237
+ suggestions.push("Add Open Graph image for better social media previews");
238
+ }
239
+ else {
240
+ const imageError = validateOpenGraphImage(typeof options.openGraph.image === "string"
241
+ ? options.openGraph.image
242
+ : options.openGraph.image[0]?.url || "");
243
+ if (imageError) {
244
+ warnings.push(imageError);
245
+ }
246
+ }
247
+ }
248
+ // Twitter Card validation
249
+ if (!options.twitter) {
250
+ suggestions.push("Add Twitter Card tags for better Twitter sharing");
251
+ }
252
+ // Hreflang validation
253
+ if (options.hreflang && options.hreflang.length > 0) {
254
+ options.hreflang.forEach((entry, index) => {
255
+ const error = validateHreflangEntry(entry);
256
+ if (error) {
257
+ errors.push(`Hreflang entry ${index + 1}: ${error}`);
258
+ }
259
+ });
260
+ // Check for x-default
261
+ const hasDefault = options.hreflang.some((entry) => entry.lang === "x-default");
262
+ if (!hasDefault) {
263
+ suggestions.push('Add hreflang="x-default" for language fallback');
264
+ }
265
+ }
266
+ // JSON-LD validation
267
+ if (options.jsonLd && options.jsonLd.length > 0) {
268
+ options.jsonLd.forEach((jsonLd, index) => {
269
+ const jsonLdErrors = validateJsonLd(jsonLd);
270
+ jsonLdErrors.forEach((error) => {
271
+ errors.push(`JSON-LD entry ${index + 1}: ${error}`);
272
+ });
273
+ });
274
+ }
275
+ else {
276
+ suggestions.push("Add JSON-LD structured data for rich snippets in search results");
277
+ }
278
+ // Favicon validation
279
+ if (!options.favicon) {
280
+ suggestions.push("Add a favicon for better brand recognition in browser tabs");
281
+ }
282
+ // Theme color validation
283
+ if (!options.themeColor) {
284
+ suggestions.push("Add a theme color for better mobile browser integration");
285
+ }
286
+ // Performance hints
287
+ if (!options.preconnect || options.preconnect.length === 0) {
288
+ suggestions.push("Add preconnect hints for external resources to improve performance");
289
+ }
290
+ return {
291
+ valid: errors.length === 0,
292
+ errors,
293
+ warnings,
294
+ suggestions,
295
+ };
296
+ };
297
+ // ============================================================================
298
+ // SEO Audit
299
+ // ============================================================================
300
+ export const auditSEO = (options) => {
301
+ const result = validateSEO(options);
302
+ // Console output in development
303
+ if (typeof console !== "undefined") {
304
+ const style = {
305
+ error: "color: #d32f2f; font-weight: bold;",
306
+ warning: "color: #f57c00; font-weight: bold;",
307
+ success: "color: #388e3c; font-weight: bold;",
308
+ info: "color: #1976d2; font-weight: bold;",
309
+ };
310
+ console.group("%c🔍 SEO Audit Results", style.info);
311
+ if (result.valid) {
312
+ console.log("%c✅ All required SEO elements are present!", style.success);
313
+ }
314
+ else {
315
+ console.log("%c❌ SEO validation failed", style.error);
316
+ }
317
+ if (result.errors.length > 0) {
318
+ console.group("%c🚨 Errors (must fix)", style.error);
319
+ result.errors.forEach((error) => console.error(error));
320
+ console.groupEnd();
321
+ }
322
+ if (result.warnings.length > 0) {
323
+ console.group("%c⚠️ Warnings (should fix)", style.warning);
324
+ result.warnings.forEach((warning) => console.warn(warning));
325
+ console.groupEnd();
326
+ }
327
+ if (result.suggestions.length > 0) {
328
+ console.group("%c💡 Suggestions (nice to have)", style.info);
329
+ result.suggestions.forEach((suggestion) => console.log(suggestion));
330
+ console.groupEnd();
331
+ }
332
+ console.groupEnd();
333
+ }
334
+ return result;
335
+ };
336
+ // ============================================================================
337
+ // Helper Functions
338
+ // ============================================================================
339
+ /**
340
+ * Truncate text to fit within SEO best practices
341
+ */
342
+ export const truncateForSEO = {
343
+ title: (text) => {
344
+ if (text.length <= TITLE_MAX_LENGTH)
345
+ return text;
346
+ return text.substring(0, TITLE_MAX_LENGTH - 3) + "...";
347
+ },
348
+ description: (text) => {
349
+ if (text.length <= DESCRIPTION_MAX_LENGTH)
350
+ return text;
351
+ return text.substring(0, DESCRIPTION_MAX_LENGTH - 3) + "...";
352
+ },
353
+ };
354
+ /**
355
+ * Generate a slug from text for URL-friendly content
356
+ */
357
+ export const generateSlug = (text) => {
358
+ return text
359
+ .toLowerCase()
360
+ .trim()
361
+ .replace(/[^\w\s-]/g, "")
362
+ .replace(/[\s_-]+/g, "-")
363
+ .replace(/^-+|-+$/g, "");
364
+ };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Vite SEO Plugin
3
+ *
4
+ * Build-time SEO optimization plugin for Vite applications.
5
+ * Generates sitemap.xml, robots.txt, and other SEO assets.
6
+ */
7
+ import type { Plugin } from "vite";
8
+ export interface ViteSEOPluginOptions {
9
+ /** Base URL of your site (e.g., https://example.com) */
10
+ siteUrl: string;
11
+ /** Array of routes to include in sitemap */
12
+ routes?: string[];
13
+ /** Automatically discover routes from build output */
14
+ discoverRoutes?: boolean;
15
+ /** Sitemap options */
16
+ sitemap?: {
17
+ /** Output filename */
18
+ filename?: string;
19
+ /** Changefreq for all URLs */
20
+ changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
21
+ /** Priority for all URLs (0.0-1.0) */
22
+ priority?: number;
23
+ /** Last modified date */
24
+ lastmod?: string;
25
+ };
26
+ /** Robots.txt options */
27
+ robotsTxt?: {
28
+ /** Output filename */
29
+ filename?: string;
30
+ /** User-agent rules */
31
+ userAgent?: string | Record<string, string[]>;
32
+ /** Disallow rules */
33
+ disallow?: string | string[];
34
+ /** Allow rules */
35
+ allow?: string | string[];
36
+ /** Sitemap location */
37
+ sitemap?: string;
38
+ /** Crawl delay */
39
+ crawlDelay?: number;
40
+ };
41
+ }
42
+ export declare const viteSEOPlugin: (options: ViteSEOPluginOptions) => Plugin;
43
+ export default viteSEOPlugin;
44
+ /**
45
+ * Quick setup for common SEO scenarios
46
+ */
47
+ export declare const quickSEOSetup: {
48
+ /**
49
+ * Basic setup for a simple website
50
+ */
51
+ basic: (siteUrl: string, routes?: string[]) => Plugin<any>;
52
+ /**
53
+ * Setup for a blog
54
+ */
55
+ blog: (siteUrl: string, routes?: string[]) => Plugin<any>;
56
+ /**
57
+ * Setup for an e-commerce site
58
+ */
59
+ ecommerce: (siteUrl: string, routes?: string[]) => Plugin<any>;
60
+ };
61
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../../src/domains/seo/vite/plugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAC;AAQnD,MAAM,WAAW,oBAAoB;IACnC,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,sDAAsD;IACtD,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,sBAAsB;IACtB,OAAO,CAAC,EAAE;QACR,sBAAsB;QACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,8BAA8B;QAC9B,UAAU,CAAC,EAAE,QAAQ,GAAG,QAAQ,GAAG,OAAO,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,GAAG,OAAO,CAAC;QACvF,sCAAsC;QACtC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,yBAAyB;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;IACF,yBAAyB;IACzB,SAAS,CAAC,EAAE;QACV,sBAAsB;QACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,uBAAuB;QACvB,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;QAC9C,qBAAqB;QACrB,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;QAC7B,kBAAkB;QAClB,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;QAC1B,uBAAuB;QACvB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,kBAAkB;QAClB,UAAU,CAAC,EAAE,MAAM,CAAC;KACrB,CAAC;CACH;AAyHD,eAAO,MAAM,aAAa,GAAI,SAAS,oBAAoB,KAAG,MA+E7D,CAAC;AAEF,eAAe,aAAa,CAAC;AAM7B;;GAEG;AACH,eAAO,MAAM,aAAa;IACxB;;OAEG;qBACc,MAAM,WAAW,MAAM,EAAE;IAc1C;;OAEG;oBACa,MAAM,WAAW,MAAM,EAAE;IAczC;;OAEG;yBACkB,MAAM,WAAW,MAAM,EAAE;CAc/C,CAAC"}
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Vite SEO Plugin
3
+ *
4
+ * Build-time SEO optimization plugin for Vite applications.
5
+ * Generates sitemap.xml, robots.txt, and other SEO assets.
6
+ */
7
+ import * as fs from "fs";
8
+ import * as path from "path";
9
+ const generateSitemapXML = (urls) => {
10
+ const urlElements = urls
11
+ .map((url) => ` <url>
12
+ <loc>${escapeXML(url.loc)}</loc>
13
+ ${url.lastmod ? `<lastmod>${url.lastmod}</lastmod>` : ""}
14
+ ${url.changefreq ? `<changefreq>${url.changefreq}</changefreq>` : ""}
15
+ ${url.priority !== undefined ? `<priority>${url.priority}</priority>` : ""}
16
+ </url>`)
17
+ .join("\n");
18
+ return `<?xml version="1.0" encoding="UTF-8"?>
19
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
20
+ ${urlElements}
21
+ </urlset>`;
22
+ };
23
+ const escapeXML = (str) => {
24
+ return str
25
+ .replace(/&/g, "&amp;")
26
+ .replace(/</g, "&lt;")
27
+ .replace(/>/g, "&gt;")
28
+ .replace(/"/g, "&quot;")
29
+ .replace(/'/g, "&apos;");
30
+ };
31
+ // ============================================================================
32
+ // Robots.txt Generation
33
+ // ============================================================================
34
+ const generateRobotsTxt = (options) => {
35
+ const lines = [];
36
+ if (!options)
37
+ return "";
38
+ // User-agent
39
+ if (typeof options.userAgent === "string") {
40
+ lines.push(`User-agent: ${options.userAgent}`);
41
+ }
42
+ else if (typeof options.userAgent === "object") {
43
+ Object.entries(options.userAgent).forEach(([agent, rules]) => {
44
+ lines.push(`User-agent: ${agent}`);
45
+ rules.forEach((rule) => lines.push(rule));
46
+ });
47
+ }
48
+ else {
49
+ lines.push("User-agent: *");
50
+ }
51
+ // Disallow
52
+ if (options.disallow) {
53
+ const disallowRules = Array.isArray(options.disallow) ? options.disallow : [options.disallow];
54
+ disallowRules.forEach((rule) => lines.push(`Disallow: ${rule}`));
55
+ }
56
+ // Allow
57
+ if (options.allow) {
58
+ const allowRules = Array.isArray(options.allow) ? options.allow : [options.allow];
59
+ allowRules.forEach((rule) => lines.push(`Allow: ${rule}`));
60
+ }
61
+ // Crawl delay
62
+ if (options.crawlDelay) {
63
+ lines.push(`Crawl-delay: ${options.crawlDelay}`);
64
+ }
65
+ // Sitemap
66
+ if (options.sitemap) {
67
+ lines.push(`Sitemap: ${options.sitemap}`);
68
+ }
69
+ return lines.join("\n") + "\n";
70
+ };
71
+ // ============================================================================
72
+ // Route Discovery
73
+ // ============================================================================
74
+ const discoverRoutesFromBuild = (outDir) => {
75
+ const routes = new Set("/");
76
+ const traverseDirectory = (dir, basePath = "") => {
77
+ try {
78
+ const files = fs.readdirSync(dir);
79
+ files.forEach((file) => {
80
+ const fullPath = path.join(dir, file);
81
+ const stat = fs.statSync(fullPath);
82
+ if (stat.isDirectory()) {
83
+ traverseDirectory(fullPath, path.join(basePath, file));
84
+ }
85
+ else if (file === "index.html") {
86
+ routes.add(basePath || "/");
87
+ }
88
+ });
89
+ }
90
+ catch (_error) {
91
+ // Directory doesn't exist or isn't accessible yet
92
+ }
93
+ };
94
+ traverseDirectory(outDir);
95
+ return Array.from(routes);
96
+ };
97
+ // ============================================================================
98
+ // Main Plugin
99
+ // ============================================================================
100
+ export const viteSEOPlugin = (options) => {
101
+ const { siteUrl, routes: manualRoutes = [], discoverRoutes = false, sitemap: sitemapOptions = {}, robotsTxt: robotsOptions = {}, } = options;
102
+ const sitemapFilename = sitemapOptions.filename || "sitemap.xml";
103
+ const robotsFilename = robotsOptions.filename || "robots.txt";
104
+ return {
105
+ name: "vite-plugin-seo",
106
+ enforce: "post",
107
+ configResolved(config) {
108
+ // Store resolved config for later use
109
+ this.publicDir = config.publicDir;
110
+ this.outDir = config.build.outDir;
111
+ },
112
+ generateBundle(_input, _bundle) {
113
+ const outDir = this.outDir || "dist";
114
+ // Collect routes
115
+ let routes = [...manualRoutes];
116
+ if (discoverRoutes) {
117
+ const discoveredRoutes = discoverRoutesFromBuild(outDir);
118
+ routes = [...new Set([...routes, ...discoveredRoutes])];
119
+ }
120
+ // Ensure at least the root route
121
+ if (routes.length === 0) {
122
+ routes.push("/");
123
+ }
124
+ // Generate sitemap
125
+ const sitemapUrls = routes.map((route) => ({
126
+ loc: `${siteUrl.replace(/\/$/, "")}${route}`,
127
+ lastmod: sitemapOptions.lastmod,
128
+ changefreq: sitemapOptions.changefreq,
129
+ priority: sitemapOptions.priority,
130
+ }));
131
+ const sitemapXML = generateSitemapXML(sitemapUrls);
132
+ // Add sitemap to bundle
133
+ this.emitFile({
134
+ type: "asset",
135
+ fileName: sitemapFilename,
136
+ source: sitemapXML,
137
+ });
138
+ // Generate robots.txt
139
+ const robotsTxtContent = generateRobotsTxt({
140
+ siteUrl,
141
+ ...robotsOptions,
142
+ sitemap: robotsOptions.sitemap || `${siteUrl.replace(/\/$/, "")}/${sitemapFilename}`,
143
+ });
144
+ // Add robots.txt to bundle
145
+ this.emitFile({
146
+ type: "asset",
147
+ fileName: robotsFilename,
148
+ source: robotsTxtContent,
149
+ });
150
+ },
151
+ closeBundle() {
152
+ // Log generated files
153
+ console.log(`\n${"=".repeat(50)}`);
154
+ console.log(`🚀 SEO files generated:`);
155
+ console.log(` 📄 ${sitemapFilename}`);
156
+ console.log(` 🤖 ${robotsFilename}`);
157
+ console.log(`${"=".repeat(50)}\n`);
158
+ },
159
+ };
160
+ };
161
+ export default viteSEOPlugin;
162
+ // ============================================================================
163
+ // Convenience Exports
164
+ // ============================================================================
165
+ /**
166
+ * Quick setup for common SEO scenarios
167
+ */
168
+ export const quickSEOSetup = {
169
+ /**
170
+ * Basic setup for a simple website
171
+ */
172
+ basic: (siteUrl, routes) => viteSEOPlugin({
173
+ siteUrl,
174
+ routes,
175
+ discoverRoutes: true,
176
+ sitemap: {
177
+ changefreq: "weekly",
178
+ priority: 0.8,
179
+ },
180
+ robotsTxt: {
181
+ disallow: ["/api", "/admin"],
182
+ },
183
+ }),
184
+ /**
185
+ * Setup for a blog
186
+ */
187
+ blog: (siteUrl, routes) => viteSEOPlugin({
188
+ siteUrl,
189
+ routes: ["/", routes || []].flat(),
190
+ discoverRoutes: true,
191
+ sitemap: {
192
+ changefreq: "daily",
193
+ priority: 0.9,
194
+ },
195
+ robotsTxt: {
196
+ disallow: ["/api", "/admin", "/private"],
197
+ },
198
+ }),
199
+ /**
200
+ * Setup for an e-commerce site
201
+ */
202
+ ecommerce: (siteUrl, routes) => viteSEOPlugin({
203
+ siteUrl,
204
+ routes: ["/", routes || []].flat(),
205
+ discoverRoutes: true,
206
+ sitemap: {
207
+ changefreq: "hourly",
208
+ priority: 1.0,
209
+ },
210
+ robotsTxt: {
211
+ disallow: ["/api", "/admin", "/cart", "/checkout", "/account"],
212
+ crawlDelay: 1,
213
+ },
214
+ }),
215
+ };
@@ -0,0 +1,2 @@
1
+ export * from "./domains/seo/index.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,cAAc,wBAAwB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // ============================================================================
2
+ // Main Package Exports (Backward Compatible)
3
+ // Redirects to domain-based structure
4
+ // ============================================================================
5
+ // Re-export everything from SEO domain
6
+ export * from "./domains/seo/index.js";