@umituz/web-seo 2.0.12 → 2.0.14

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.
@@ -12,5 +12,5 @@ interface JsonLdProps {
12
12
  /** Unique identifier for this JSON-LD block (for debugging) */
13
13
  id?: string;
14
14
  }
15
- export declare const JsonLd: React.FC<JsonLdProps>;
15
+ export declare const JsonLd: ({ data, strategy, id }: JsonLdProps) => null;
16
16
  export default JsonLd;
@@ -4,17 +4,33 @@
4
4
  * React component for injecting JSON-LD structured data into the page.
5
5
  * Supports all Schema.org types with automatic validation.
6
6
  */
7
- import { useEffect, useRef } from "react";
7
+ import { useEffect, useRef, useMemo } from "react";
8
+ // Generate a stable hash from JSON-LD data for consistent identification
9
+ const generateDataId = (data) => {
10
+ const str = JSON.stringify(data);
11
+ let hash = 0;
12
+ for (let i = 0; i < str.length; i++) {
13
+ const char = str.charCodeAt(i);
14
+ hash = ((hash << 5) - hash) + char;
15
+ hash = hash & hash; // Convert to 32-bit integer
16
+ }
17
+ return `jsonld-${Math.abs(hash).toString(36)}`;
18
+ };
8
19
  export const JsonLd = ({ data, strategy = "afterInteractive", id }) => {
9
20
  const scriptRef = useRef(null);
21
+ // Generate stable IDs for data items
22
+ const dataIds = useMemo(() => {
23
+ const dataArray = Array.isArray(data) ? data : [data];
24
+ return dataArray.map((item) => id ? `${id}-${dataArray.indexOf(item)}` : generateDataId(item));
25
+ }, [data, id]);
10
26
  useEffect(() => {
11
27
  if (typeof document === "undefined")
12
28
  return;
13
29
  // Convert single object to array for uniform handling
14
30
  const dataArray = Array.isArray(data) ? data : [data];
15
- // Remove existing scripts with the same data to avoid duplicates
16
- dataArray.forEach((jsonData) => {
17
- const existingScript = document.querySelector(`script[type="application/ld+json"][data-seo-id="${id || JSON.stringify(jsonData)}"]`);
31
+ // Remove existing scripts with matching IDs
32
+ dataIds.forEach((dataId) => {
33
+ const existingScript = document.querySelector(`script[type="application/ld+json"][data-seo-id="${dataId}"]`);
18
34
  if (existingScript) {
19
35
  existingScript.remove();
20
36
  }
@@ -25,12 +41,7 @@ export const JsonLd = ({ data, strategy = "afterInteractive", id }) => {
25
41
  script.type = "application/ld+json";
26
42
  script.textContent = JSON.stringify(jsonData);
27
43
  // Add identifier for duplicate detection and debugging
28
- if (id) {
29
- script.setAttribute("data-seo-id", `${id}-${index}`);
30
- }
31
- else {
32
- script.setAttribute("data-seo-id", JSON.stringify(jsonData));
33
- }
44
+ script.setAttribute("data-seo-id", dataIds[index]);
34
45
  script.setAttribute("data-seo-strategy", strategy);
35
46
  document.head.appendChild(script);
36
47
  if (index === 0) {
@@ -39,14 +50,14 @@ export const JsonLd = ({ data, strategy = "afterInteractive", id }) => {
39
50
  });
40
51
  // Cleanup function
41
52
  return () => {
42
- dataArray.forEach((jsonData) => {
43
- const script = document.querySelector(`script[type="application/ld+json"][data-seo-id="${id || JSON.stringify(jsonData)}"]`);
53
+ dataIds.forEach((dataId) => {
54
+ const script = document.querySelector(`script[type="application/ld+json"][data-seo-id="${dataId}"]`);
44
55
  if (script) {
45
56
  script.remove();
46
57
  }
47
58
  });
48
59
  };
49
- }, [data, strategy, id]);
60
+ }, [data, strategy, dataIds]);
50
61
  return null;
51
62
  };
52
63
  export default JsonLd;
@@ -1,3 +1,2 @@
1
- import React from "react";
2
1
  import type { SEOptions } from "../types/index.js";
3
- export declare const SEO: React.FC<SEOptions>;
2
+ export declare const SEO: (props: SEOptions) => null;
@@ -2,6 +2,7 @@ interface I18nInstance {
2
2
  language?: string;
3
3
  t: (key: string) => string;
4
4
  on: (event: string, callback: () => void) => void;
5
+ off?: (event: string, callback: () => void) => void;
5
6
  }
6
7
  interface SEOConfig {
7
8
  i18n?: I18nInstance;
@@ -11,5 +12,5 @@ interface SEOConfig {
11
12
  canonicalPrefix?: string;
12
13
  twitterHandle?: string;
13
14
  }
14
- export declare const initSEO: (config: SEOConfig) => void;
15
+ export declare const initSEO: (config: SEOConfig) => (() => void);
15
16
  export {};
@@ -1,9 +1,9 @@
1
1
  import { updateSEO } from "../utils/dom.js";
2
2
  export const initSEO = (config) => {
3
3
  if (typeof window === "undefined")
4
- return;
4
+ return () => { };
5
5
  const update = () => {
6
- const lang = config.i18n?.language ? config.i18n.language.split("-")[0] || "en" : "en";
6
+ const lang = config.i18n?.language ? config.i18n.language.split("-")[0] : "en";
7
7
  const title = config.i18n ? config.i18n.t(config.titleKey || "app.title") : document.title;
8
8
  const description = config.i18n ? config.i18n.t(config.descriptionKey || "app.description") : "";
9
9
  const canonical = config.canonicalPrefix ? `${config.canonicalPrefix}/${lang}` : undefined;
@@ -31,4 +31,10 @@ export const initSEO = (config) => {
31
31
  if (config.i18n && typeof config.i18n.on === "function") {
32
32
  config.i18n.on("languageChanged", update);
33
33
  }
34
+ // Return cleanup function
35
+ return () => {
36
+ if (config.i18n && typeof config.i18n.off === "function") {
37
+ config.i18n.off("languageChanged", update);
38
+ }
39
+ };
34
40
  };
@@ -4,16 +4,35 @@
4
4
  * React hook for managing JSON-LD structured data.
5
5
  * Provides a programmatic way to add/update/remove structured data.
6
6
  */
7
- import { useEffect, useCallback } from "react";
7
+ import { useEffect, useCallback, useMemo } from "react";
8
+ // Generate a stable hash from JSON-LD data for consistent identification
9
+ const generateDataId = (data) => {
10
+ const str = JSON.stringify(data);
11
+ let hash = 0;
12
+ for (let i = 0; i < str.length; i++) {
13
+ const char = str.charCodeAt(i);
14
+ hash = ((hash << 5) - hash) + char;
15
+ hash = hash & hash; // Convert to 32-bit integer
16
+ }
17
+ return `jsonld-${Math.abs(hash).toString(36)}`;
18
+ };
8
19
  export const useJsonLd = (data, options) => {
9
20
  const { strategy = "afterInteractive", id } = options || {};
21
+ // Generate stable IDs for data items
22
+ const dataIds = useMemo(() => {
23
+ const dataArray = Array.isArray(data) ? data : [data];
24
+ return dataArray.map((item) => id ? `${id}-${dataArray.indexOf(item)}` : generateDataId(item));
25
+ }, [data, id]);
10
26
  const injectJsonLd = useCallback((jsonData) => {
11
27
  if (typeof document === "undefined")
12
28
  return;
13
29
  const dataArray = Array.isArray(jsonData) ? jsonData : [jsonData];
30
+ const ids = Array.isArray(jsonData) && !id
31
+ ? dataArray.map(generateDataId)
32
+ : dataIds;
14
33
  dataArray.forEach((item, index) => {
15
34
  // Remove existing script if present
16
- const existingScript = document.querySelector(`script[type="application/ld+json"][data-seo-id="${id || JSON.stringify(item)}"]`);
35
+ const existingScript = document.querySelector(`script[type="application/ld+json"][data-seo-id="${ids[index]}"]`);
17
36
  if (existingScript) {
18
37
  existingScript.remove();
19
38
  }
@@ -21,22 +40,21 @@ export const useJsonLd = (data, options) => {
21
40
  const script = document.createElement("script");
22
41
  script.type = "application/ld+json";
23
42
  script.textContent = JSON.stringify(item);
24
- if (id) {
25
- script.setAttribute("data-seo-id", `${id}-${index}`);
26
- }
27
- else {
28
- script.setAttribute("data-seo-id", JSON.stringify(item));
29
- }
43
+ script.setAttribute("data-seo-id", ids[index]);
30
44
  script.setAttribute("data-seo-strategy", strategy);
31
45
  document.head.appendChild(script);
32
46
  });
33
- }, [id, strategy]);
47
+ }, [id, strategy, dataIds]);
34
48
  const removeJsonLd = useCallback(() => {
35
49
  if (typeof document === "undefined")
36
50
  return;
37
- const scripts = document.querySelectorAll(`script[type="application/ld+json"][data-seo-id*="${id || ''}"]`);
38
- scripts.forEach((script) => script.remove());
39
- }, [id]);
51
+ dataIds.forEach((dataId) => {
52
+ const script = document.querySelector(`script[type="application/ld+json"][data-seo-id="${dataId}"]`);
53
+ if (script) {
54
+ script.remove();
55
+ }
56
+ });
57
+ }, [dataIds]);
40
58
  useEffect(() => {
41
59
  if (data) {
42
60
  injectJsonLd(data);
@@ -18,6 +18,14 @@ const escapeHTML = (str) => {
18
18
  .replace(/"/g, "&quot;")
19
19
  .replace(/'/g, "&#39;");
20
20
  };
21
+ /**
22
+ * Escape JSON content for safe inclusion in HTML script tags
23
+ * Prevents script breakage from </script> sequences in JSON data
24
+ */
25
+ const escapeJSONForScript = (json) => {
26
+ // Replace </script> with <\/script> to prevent breaking out of script tag
27
+ return json.replace(/<\/script>/gi, "<\\/script>");
28
+ };
21
29
  /**
22
30
  * Render SEO options to HTML strings for server-side rendering
23
31
  */
@@ -190,7 +198,9 @@ export const renderSEO = (options) => {
190
198
  // JSON-LD
191
199
  if (options.jsonLd && options.jsonLd.length > 0) {
192
200
  options.jsonLd.forEach((data) => {
193
- jsonLdScripts.push(`<script type="application/ld+json">${JSON.stringify(data)}</script>`);
201
+ const json = JSON.stringify(data);
202
+ const safeJson = escapeJSONForScript(json);
203
+ jsonLdScripts.push(`<script type="application/ld+json">${safeJson}</script>`);
194
204
  });
195
205
  }
196
206
  return {
@@ -240,8 +250,12 @@ export const hydrateSEO = (serializedData) => {
240
250
  return;
241
251
  }
242
252
  // Import updateSEO dynamically to avoid circular dependencies
243
- import("../utils/dom.js").then(({ updateSEO }) => {
253
+ import("../utils/dom.js")
254
+ .then(({ updateSEO }) => {
244
255
  updateSEO(options);
256
+ })
257
+ .catch((error) => {
258
+ console.error("[SEO] Failed to load updateSEO:", error);
245
259
  });
246
260
  };
247
261
  /**
@@ -148,8 +148,6 @@ export interface SEOptions {
148
148
  maskIcon?: string;
149
149
  themeColor?: string;
150
150
  viewport?: string;
151
- additionalMetaTags?: MetaTag[];
152
- additionalLinkTags?: LinkTag[];
153
151
  }
154
152
  export interface OpenGraphImage {
155
153
  url: string;
@@ -138,32 +138,6 @@ export const updateSEO = (options) => {
138
138
  setOpenGraph(options.openGraph);
139
139
  // Twitter Card
140
140
  setTwitterCard(options.twitter, options.openGraph);
141
- // Additional Meta Tags (backward compatibility)
142
- if (options.additionalMetaTags && Array.isArray(options.additionalMetaTags)) {
143
- options.additionalMetaTags.forEach((m) => {
144
- if (m.name)
145
- setMetaTag("name", m.name, m.content);
146
- if (m.property)
147
- setMetaTag("property", m.property, m.content);
148
- });
149
- }
150
- // Additional Link Tags (backward compatibility)
151
- if (options.additionalLinkTags && Array.isArray(options.additionalLinkTags)) {
152
- options.additionalLinkTags.forEach((link) => {
153
- const attrs = { rel: link.rel, href: link.href };
154
- if (link.type)
155
- attrs.type = link.type;
156
- if (link.sizes)
157
- attrs.sizes = link.sizes;
158
- if (link.media)
159
- attrs.media = link.media;
160
- if (link.crossOrigin)
161
- attrs.crossorigin = link.crossOrigin;
162
- if (link.as)
163
- attrs.as = link.as;
164
- setLinkTag(attrs);
165
- });
166
- }
167
141
  };
168
142
  /**
169
143
  * Remove all SEO meta tags added by this library
@@ -13,6 +13,7 @@ export const setMetaTag = (attrName, attrValue, content) => {
13
13
  if (!element) {
14
14
  element = document.createElement("meta");
15
15
  element.setAttribute(attrName, attrValue);
16
+ element.setAttribute("data-seo", "true");
16
17
  document.head.appendChild(element);
17
18
  }
18
19
  if (content) {
@@ -39,10 +40,13 @@ export const setLinkTag = (attrs) => {
39
40
  let element = document.querySelector(selector);
40
41
  if (!element) {
41
42
  element = document.createElement("link");
43
+ element.setAttribute("data-seo", "true");
42
44
  document.head.appendChild(element);
43
45
  }
44
46
  Object.entries(attrs).forEach(([key, value]) => {
45
- element.setAttribute(key, value);
47
+ if (element) {
48
+ element.setAttribute(key, value);
49
+ }
46
50
  });
47
51
  };
48
52
  /**
@@ -11,4 +11,4 @@ export declare const setOpenGraph: (openGraph: SEOptions["openGraph"]) => void;
11
11
  /**
12
12
  * Set Twitter Card tags
13
13
  */
14
- export declare const setTwitterCard: (twitter: SEOptions["twitter"], __openGraphImage?: SEOptions["openGraph"]) => void;
14
+ export declare const setTwitterCard: (twitter: SEOptions["twitter"], _openGraph?: SEOptions["openGraph"]) => void;
@@ -89,7 +89,7 @@ export const setOpenGraph = (openGraph) => {
89
89
  /**
90
90
  * Set Twitter Card tags
91
91
  */
92
- export const setTwitterCard = (twitter, __openGraphImage) => {
92
+ export const setTwitterCard = (twitter, _openGraph) => {
93
93
  if (!twitter)
94
94
  return;
95
95
  const setTW = (name, content) => {
@@ -14,9 +14,7 @@ const validateRequired = (value, fieldName, strict = false) => {
14
14
  if (strict) {
15
15
  throw new Error(message);
16
16
  }
17
- if (typeof console !== "undefined" && console.warn) {
18
- console.warn(message);
19
- }
17
+ console.warn(message);
20
18
  return false;
21
19
  }
22
20
  return true;
@@ -38,6 +38,8 @@ export interface ViteSEOPluginOptions {
38
38
  /** Crawl delay */
39
39
  crawlDelay?: number;
40
40
  };
41
+ /** Suppress console output */
42
+ silent?: boolean;
41
43
  }
42
44
  export declare const viteSEOPlugin: (options: ViteSEOPluginOptions) => Plugin;
43
45
  export default viteSEOPlugin;
@@ -87,8 +87,11 @@ const discoverRoutesFromBuild = (outDir) => {
87
87
  }
88
88
  });
89
89
  }
90
- catch {
91
- // Directory doesn't exist or isn't accessible yet
90
+ catch (error) {
91
+ // Directory doesn't exist or isn't accessible yet - silently skip
92
+ if (error.code !== 'ENOENT') {
93
+ console.warn(`[vite-plugin-seo] Warning: Could not traverse directory ${dir}:`, error);
94
+ }
92
95
  }
93
96
  };
94
97
  traverseDirectory(outDir);
@@ -98,7 +101,7 @@ const discoverRoutesFromBuild = (outDir) => {
98
101
  // Main Plugin
99
102
  // ============================================================================
100
103
  export const viteSEOPlugin = (options) => {
101
- const { siteUrl, routes: manualRoutes = [], discoverRoutes = false, sitemap: sitemapOptions = {}, robotsTxt: robotsOptions = {}, } = options;
104
+ const { siteUrl, routes: manualRoutes = [], discoverRoutes = false, sitemap: sitemapOptions = {}, robotsTxt: robotsOptions = {}, silent = false, } = options;
102
105
  const sitemapFilename = sitemapOptions.filename || "sitemap.xml";
103
106
  const robotsFilename = robotsOptions.filename || "robots.txt";
104
107
  // Store plugin state
@@ -152,11 +155,13 @@ export const viteSEOPlugin = (options) => {
152
155
  },
153
156
  closeBundle() {
154
157
  // Log generated files
155
- console.log(`\n${"=".repeat(50)}`);
156
- console.log(`🚀 SEO files generated:`);
157
- console.log(` 📄 ${sitemapFilename}`);
158
- console.log(` 🤖 ${robotsFilename}`);
159
- console.log(`${"=".repeat(50)}\n`);
158
+ if (!silent) {
159
+ console.log(`\n${"=".repeat(50)}`);
160
+ console.log(`🚀 SEO files generated:`);
161
+ console.log(` 📄 ${sitemapFilename}`);
162
+ console.log(` 🤖 ${robotsFilename}`);
163
+ console.log(`${"=".repeat(50)}\n`);
164
+ }
160
165
  },
161
166
  };
162
167
  };
package/dist/index.d.ts CHANGED
@@ -8,6 +8,5 @@ export { generateArticleSchema, generateProductSchema, generateOrganizationSchem
8
8
  export { validateSEO, auditSEO, isValidUrl, validateUrl, validateTitleLength, validateDescriptionLength, validateOpenGraphImage, validateHreflangEntry, truncateForSEO, generateSlug, } from "./domains/seo/utils/validation/validators.js";
9
9
  export { renderSEO, generateHead, extractSEOData, hydrateSEO, renderAsHelmet, } from "./domains/seo/ssr/renderer.js";
10
10
  export { serializeSEO, deserializeSEO, serializeSEOToBase64, deserializeSEOFromBase64, compressSEO, serializeSEOToQueryString, deserializeSEOFromQueryString, safeDeserializeSEO, } from "./domains/seo/ssr/serializer.js";
11
- export { viteSEOPlugin, quickSEOSetup, } from "./domains/seo/vite/plugin.js";
12
11
  export type { MetaTag, LinkTag, ScriptTag, SEOptions, SEOConfig, RobotsMeta, RobotsDirective, HreflangEntry, PreloadHint, PreconnectOrigin, DnsPrefetchDomain, ArticleMeta, ProductMeta, BreadcrumbItem, OpenGraphImage, SEOValidationResult, } from "./domains/seo/types/index.js";
13
12
  export type { JsonLdTypes, ArticleJsonLd, ProductJsonLd, OrganizationJsonLd, LocalBusinessJsonLd, BreadcrumbJsonLd, FAQJsonLd, WebSiteJsonLd, PersonJsonLd, VideoJsonLd, SchemaType, SchemaGeneratorOptions, } from "./domains/seo/types/schema.js";
package/dist/index.js CHANGED
@@ -15,5 +15,3 @@ export { validateSEO, auditSEO, isValidUrl, validateUrl, validateTitleLength, va
15
15
  // SSR
16
16
  export { renderSEO, generateHead, extractSEOData, hydrateSEO, renderAsHelmet, } from "./domains/seo/ssr/renderer.js";
17
17
  export { serializeSEO, deserializeSEO, serializeSEOToBase64, deserializeSEOFromBase64, compressSEO, serializeSEOToQueryString, deserializeSEOFromQueryString, safeDeserializeSEO, } from "./domains/seo/ssr/serializer.js";
18
- // Vite Plugin
19
- export { viteSEOPlugin, quickSEOSetup, } from "./domains/seo/vite/plugin.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-seo",
3
- "version": "2.0.12",
3
+ "version": "2.0.14",
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",
@@ -73,8 +73,8 @@
73
73
  },
74
74
  "devDependencies": {
75
75
  "@types/node": "^25.5.0",
76
- "@types/react": "^18.3.2",
77
- "@types/react-dom": "^18.3.0",
76
+ "@types/react": "^19.2.14",
77
+ "@types/react-dom": "^19.2.3",
78
78
  "@typescript-eslint/eslint-plugin": "^8.57.1",
79
79
  "@typescript-eslint/parser": "^8.57.1",
80
80
  "eslint": "^8.57.0",