@umituz/web-seo 2.2.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import type { RouteMeta } from "./types.js";
2
+ export declare const injectRouteMeta: (htmlTemplate: string, meta: RouteMeta, siteUrl: string, routePath: string) => string;
@@ -0,0 +1,109 @@
1
+ const escapeHtml = (text) => text
2
+ .replace(/&/g, "&")
3
+ .replace(/</g, "&lt;")
4
+ .replace(/>/g, "&gt;")
5
+ .replace(/"/g, "&quot;")
6
+ .replace(/'/g, "&#039;");
7
+ const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8
+ const upsertTag = (html, regex, newTag) => {
9
+ if (regex.test(html)) {
10
+ return html.replace(regex, newTag);
11
+ }
12
+ const headClosingIndex = html.toLowerCase().indexOf("</head>");
13
+ if (headClosingIndex !== -1) {
14
+ return `${html.slice(0, headClosingIndex)} ${newTag}\n ${html.slice(headClosingIndex)}`;
15
+ }
16
+ return `${html}\n${newTag}`;
17
+ };
18
+ const upsertMetaTag = (html, attributeName, attributeValue, content) => {
19
+ const safeAttrValue = escapeRegex(attributeValue);
20
+ const regex = new RegExp(`<meta\\s+[^>]*?${attributeName}=["']${safeAttrValue}["'][^>]*?\\/?>`, "i");
21
+ const newTag = `<meta ${attributeName}="${attributeValue}" content="${escapeHtml(content)}" />`;
22
+ return upsertTag(html, regex, newTag);
23
+ };
24
+ export const injectRouteMeta = (htmlTemplate, meta, siteUrl, routePath) => {
25
+ let html = htmlTemplate;
26
+ const normalizedSiteUrl = siteUrl.replace(/\/$/, "");
27
+ const normalizedRoutePath = routePath.startsWith("/") ? routePath : `/${routePath}`;
28
+ const canonicalUrl = meta.canonical ??
29
+ `${normalizedSiteUrl}${normalizedRoutePath === "/" ? "" : normalizedRoutePath}`;
30
+ if (meta.lang) {
31
+ const htmlTagRegex = /<html([^>]*)>/i;
32
+ const match = html.match(htmlTagRegex);
33
+ if (match) {
34
+ let attrs = match[1];
35
+ if (/lang=["'][^"']*["']/i.test(attrs)) {
36
+ attrs = attrs.replace(/lang=["'][^"']*["']/i, `lang="${escapeHtml(meta.lang)}"`);
37
+ }
38
+ else {
39
+ attrs = `${attrs} lang="${escapeHtml(meta.lang)}"`;
40
+ }
41
+ html = html.replace(htmlTagRegex, `<html${attrs}>`);
42
+ }
43
+ }
44
+ if (meta.title) {
45
+ const titleRegex = /<title[^>]*>[\s\S]*?<\/title>/i;
46
+ const newTitle = `<title>${escapeHtml(meta.title)}</title>`;
47
+ html = upsertTag(html, titleRegex, newTitle);
48
+ }
49
+ if (meta.description) {
50
+ html = upsertMetaTag(html, "name", "description", meta.description);
51
+ }
52
+ if (meta.keywords) {
53
+ const kwString = Array.isArray(meta.keywords)
54
+ ? meta.keywords.join(", ")
55
+ : meta.keywords;
56
+ if (kwString) {
57
+ html = upsertMetaTag(html, "name", "keywords", kwString);
58
+ }
59
+ }
60
+ if (meta.robots) {
61
+ html = upsertMetaTag(html, "name", "robots", meta.robots);
62
+ }
63
+ const canonicalRegex = /<link\s+[^>]*?rel=["']canonical["'][^>]*?\/?>/i;
64
+ const newCanonical = `<link rel="canonical" href="${escapeHtml(canonicalUrl)}" />`;
65
+ html = upsertTag(html, canonicalRegex, newCanonical);
66
+ const ogTitle = meta.og?.title ?? meta.title;
67
+ if (ogTitle)
68
+ html = upsertMetaTag(html, "property", "og:title", ogTitle);
69
+ const ogDesc = meta.og?.description ?? meta.description;
70
+ if (ogDesc)
71
+ html = upsertMetaTag(html, "property", "og:description", ogDesc);
72
+ const ogUrl = meta.og?.url ?? canonicalUrl;
73
+ if (ogUrl)
74
+ html = upsertMetaTag(html, "property", "og:url", ogUrl);
75
+ const ogType = meta.og?.type ?? "website";
76
+ if (ogType)
77
+ html = upsertMetaTag(html, "property", "og:type", ogType);
78
+ if (meta.og?.siteName) {
79
+ html = upsertMetaTag(html, "property", "og:site_name", meta.og.siteName);
80
+ }
81
+ if (meta.og?.image) {
82
+ html = upsertMetaTag(html, "property", "og:image", meta.og.image);
83
+ }
84
+ const twCard = meta.twitter?.card ?? "summary_large_image";
85
+ if (twCard)
86
+ html = upsertMetaTag(html, "name", "twitter:card", twCard);
87
+ const twTitle = meta.twitter?.title ?? meta.title;
88
+ if (twTitle)
89
+ html = upsertMetaTag(html, "name", "twitter:title", twTitle);
90
+ const twDesc = meta.twitter?.description ?? meta.description;
91
+ if (twDesc)
92
+ html = upsertMetaTag(html, "name", "twitter:description", twDesc);
93
+ const twImage = meta.twitter?.image ?? meta.og?.image;
94
+ if (twImage)
95
+ html = upsertMetaTag(html, "name", "twitter:image", twImage);
96
+ if (meta.twitter?.site) {
97
+ html = upsertMetaTag(html, "name", "twitter:site", meta.twitter.site);
98
+ }
99
+ if (meta.twitter?.creator) {
100
+ html = upsertMetaTag(html, "name", "twitter:creator", meta.twitter.creator);
101
+ }
102
+ if (meta.jsonLd) {
103
+ const jsonString = JSON.stringify(meta.jsonLd, null, 2);
104
+ const jsonLdTag = `<script type="application/ld+json" data-seo="true">\n${jsonString}\n </script>`;
105
+ const existingJsonLdRegex = /<script\s+[^>]*?type=["']application\/ld\+json["'][^>]*>[\s\S]*?<\/script>/i;
106
+ html = upsertTag(html, existingJsonLdRegex, jsonLdTag);
107
+ }
108
+ return html;
109
+ };
@@ -1,3 +1,4 @@
1
1
  export { viteSEOPlugin } from "./plugin.js";
2
+ export { injectRouteMeta } from "./html-rewriter.js";
2
3
  export { quickSEOSetup } from "./presets.js";
3
- export type { ViteSEOPluginOptions, SitemapRouteItem, SitemapChangeFreq } from "./types.js";
4
+ export type { ViteSEOPluginOptions, SitemapRouteItem, SitemapChangeFreq, RouteMeta, PrerenderOptions, } from "./types.js";
@@ -1,2 +1,3 @@
1
1
  export { viteSEOPlugin } from "./plugin.js";
2
+ export { injectRouteMeta } from "./html-rewriter.js";
2
3
  export { quickSEOSetup } from "./presets.js";
@@ -1,8 +1,11 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import { generateRobotsTxt } from "./robots-generator.js";
2
4
  import { discoverRoutesFromBuild, generateSitemapXML } from "./sitemap-generator.js";
5
+ import { injectRouteMeta } from "./html-rewriter.js";
3
6
  const PLUGIN_NAME = "umituz-web-seo";
4
7
  export const viteSEOPlugin = (options) => {
5
- const { siteUrl, routes: manualRoutes = [], discoverRoutes = false, sitemap: sitemapOptions = {}, robotsTxt: robotsOptions = {}, silent = false, } = options;
8
+ const { siteUrl, routes: manualRoutes = [], discoverRoutes = false, sitemap: sitemapOptions = {}, robotsTxt: robotsOptions = {}, prerender, silent = false, } = options;
6
9
  const sitemapFilename = sitemapOptions.filename ?? "sitemap.xml";
7
10
  const robotsFilename = robotsOptions.filename ?? "robots.txt";
8
11
  const normalizedSiteUrl = siteUrl.replace(/\/$/, "");
@@ -59,12 +62,44 @@ export const viteSEOPlugin = (options) => {
59
62
  });
60
63
  },
61
64
  closeBundle() {
65
+ const outDir = pluginState.outDir ?? "dist";
66
+ const generatedHtmlPages = [];
67
+ if (prerender?.routes && Object.keys(prerender.routes).length > 0) {
68
+ const indexPath = path.resolve(outDir, "index.html");
69
+ if (fs.existsSync(indexPath)) {
70
+ const templateHtml = fs.readFileSync(indexPath, "utf-8");
71
+ for (const [routePath, routeMeta] of Object.entries(prerender.routes)) {
72
+ const mergedMeta = { ...prerender.fallbackMeta, ...routeMeta };
73
+ const renderedHtml = injectRouteMeta(templateHtml, mergedMeta, normalizedSiteUrl, routePath);
74
+ const cleanPath = routePath.replace(/^\/+/, "").replace(/\/+$/, "");
75
+ if (cleanPath === "") {
76
+ fs.writeFileSync(indexPath, renderedHtml, "utf-8");
77
+ generatedHtmlPages.push("index.html");
78
+ }
79
+ else {
80
+ const targetDir = path.resolve(outDir, cleanPath);
81
+ if (!fs.existsSync(targetDir)) {
82
+ fs.mkdirSync(targetDir, { recursive: true });
83
+ }
84
+ const targetFile = path.resolve(targetDir, "index.html");
85
+ fs.writeFileSync(targetFile, renderedHtml, "utf-8");
86
+ const directHtmlFile = path.resolve(outDir, `${cleanPath}.html`);
87
+ fs.writeFileSync(directHtmlFile, renderedHtml, "utf-8");
88
+ generatedHtmlPages.push(`${cleanPath}/index.html`);
89
+ }
90
+ }
91
+ }
92
+ }
62
93
  if (silent)
63
94
  return;
64
95
  console.log(`\n${"=".repeat(50)}`);
65
96
  console.log("SEO files generated:");
66
97
  console.log(` ${sitemapFilename}`);
67
98
  console.log(` ${robotsFilename}`);
99
+ if (generatedHtmlPages.length > 0) {
100
+ console.log(`Pre-rendered HTML routes (${generatedHtmlPages.length}):`);
101
+ generatedHtmlPages.forEach((p) => console.log(` ${p}`));
102
+ }
68
103
  console.log(`${"=".repeat(50)}\n`);
69
104
  },
70
105
  };
@@ -5,6 +5,35 @@ export interface SitemapRouteItem {
5
5
  changefreq?: SitemapChangeFreq;
6
6
  lastmod?: string;
7
7
  }
8
+ export interface RouteMeta {
9
+ title?: string;
10
+ description?: string;
11
+ keywords?: string[] | string;
12
+ canonical?: string;
13
+ robots?: string;
14
+ lang?: string;
15
+ og?: {
16
+ title?: string;
17
+ description?: string;
18
+ image?: string;
19
+ type?: string;
20
+ url?: string;
21
+ siteName?: string;
22
+ };
23
+ twitter?: {
24
+ card?: string;
25
+ title?: string;
26
+ description?: string;
27
+ image?: string;
28
+ site?: string;
29
+ creator?: string;
30
+ };
31
+ jsonLd?: Record<string, unknown> | Array<Record<string, unknown>>;
32
+ }
33
+ export interface PrerenderOptions {
34
+ routes?: Record<string, RouteMeta>;
35
+ fallbackMeta?: RouteMeta;
36
+ }
8
37
  export interface ViteSEOPluginOptions {
9
38
  siteUrl: string;
10
39
  routes?: Array<string | SitemapRouteItem>;
@@ -23,5 +52,6 @@ export interface ViteSEOPluginOptions {
23
52
  sitemap?: string;
24
53
  crawlDelay?: number;
25
54
  };
55
+ prerender?: PrerenderOptions;
26
56
  silent?: boolean;
27
57
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-seo",
3
- "version": "2.2.0",
3
+ "version": "2.3.1",
4
4
  "description": "Comprehensive SEO solution for React Vite applications with structured data, performance hints, and build-time optimization",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",