@contentisking/seomcp 0.0.0-stage → 0.1.33

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 (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +98 -0
  3. package/README.md +292 -2
  4. package/dist/auth/google.d.ts +18 -0
  5. package/dist/auth/google.js +117 -0
  6. package/dist/auth/google.js.map +1 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +77 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/config.d.ts +61 -0
  11. package/dist/config.js +92 -0
  12. package/dist/config.js.map +1 -0
  13. package/dist/core/analysis.d.ts +64 -0
  14. package/dist/core/analysis.js +106 -0
  15. package/dist/core/analysis.js.map +1 -0
  16. package/dist/core/bing.d.ts +33 -0
  17. package/dist/core/bing.js +95 -0
  18. package/dist/core/bing.js.map +1 -0
  19. package/dist/core/dates.d.ts +20 -0
  20. package/dist/core/dates.js +34 -0
  21. package/dist/core/dates.js.map +1 -0
  22. package/dist/core/errors.d.ts +10 -0
  23. package/dist/core/errors.js +11 -0
  24. package/dist/core/errors.js.map +1 -0
  25. package/dist/core/fetch-page.d.ts +38 -0
  26. package/dist/core/fetch-page.js +144 -0
  27. package/dist/core/fetch-page.js.map +1 -0
  28. package/dist/core/ga.d.ts +51 -0
  29. package/dist/core/ga.js +131 -0
  30. package/dist/core/ga.js.map +1 -0
  31. package/dist/core/geo.d.ts +256 -0
  32. package/dist/core/geo.js +395 -0
  33. package/dist/core/geo.js.map +1 -0
  34. package/dist/core/google-errors.d.ts +11 -0
  35. package/dist/core/google-errors.js +33 -0
  36. package/dist/core/google-errors.js.map +1 -0
  37. package/dist/core/google-rich-results.d.ts +20 -0
  38. package/dist/core/google-rich-results.js +114 -0
  39. package/dist/core/google-rich-results.js.map +1 -0
  40. package/dist/core/gsc.d.ts +24 -0
  41. package/dist/core/gsc.js +110 -0
  42. package/dist/core/gsc.js.map +1 -0
  43. package/dist/core/html.d.ts +76 -0
  44. package/dist/core/html.js +288 -0
  45. package/dist/core/html.js.map +1 -0
  46. package/dist/core/pagespeed.d.ts +105 -0
  47. package/dist/core/pagespeed.js +183 -0
  48. package/dist/core/pagespeed.js.map +1 -0
  49. package/dist/core/schema-validate.d.ts +63 -0
  50. package/dist/core/schema-validate.js +384 -0
  51. package/dist/core/schema-validate.js.map +1 -0
  52. package/dist/core/site-trust.d.ts +32 -0
  53. package/dist/core/site-trust.js +102 -0
  54. package/dist/core/site-trust.js.map +1 -0
  55. package/dist/core/technical.d.ts +160 -0
  56. package/dist/core/technical.js +329 -0
  57. package/dist/core/technical.js.map +1 -0
  58. package/dist/core/types.d.ts +124 -0
  59. package/dist/core/types.js +3 -0
  60. package/dist/core/types.js.map +1 -0
  61. package/dist/data/schema-vocab.json +1 -0
  62. package/dist/doctor.d.ts +13 -0
  63. package/dist/doctor.js +167 -0
  64. package/dist/doctor.js.map +1 -0
  65. package/dist/index.d.ts +22 -0
  66. package/dist/index.js +22 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/links.d.ts +26 -0
  69. package/dist/links.js +36 -0
  70. package/dist/links.js.map +1 -0
  71. package/dist/prompts/geo.d.ts +2 -0
  72. package/dist/prompts/geo.js +124 -0
  73. package/dist/prompts/geo.js.map +1 -0
  74. package/dist/server.d.ts +8 -0
  75. package/dist/server.js +69 -0
  76. package/dist/server.js.map +1 -0
  77. package/dist/setup/clients.d.ts +69 -0
  78. package/dist/setup/clients.js +156 -0
  79. package/dist/setup/clients.js.map +1 -0
  80. package/dist/setup/prompt.d.ts +20 -0
  81. package/dist/setup/prompt.js +80 -0
  82. package/dist/setup/prompt.js.map +1 -0
  83. package/dist/setup/wizard.d.ts +5 -0
  84. package/dist/setup/wizard.js +369 -0
  85. package/dist/setup/wizard.js.map +1 -0
  86. package/dist/tools/bing.d.ts +3 -0
  87. package/dist/tools/bing.js +72 -0
  88. package/dist/tools/bing.js.map +1 -0
  89. package/dist/tools/ga.d.ts +3 -0
  90. package/dist/tools/ga.js +150 -0
  91. package/dist/tools/ga.js.map +1 -0
  92. package/dist/tools/geo.d.ts +3 -0
  93. package/dist/tools/geo.js +28 -0
  94. package/dist/tools/geo.js.map +1 -0
  95. package/dist/tools/gsc.d.ts +3 -0
  96. package/dist/tools/gsc.js +146 -0
  97. package/dist/tools/gsc.js.map +1 -0
  98. package/dist/tools/pagespeed.d.ts +3 -0
  99. package/dist/tools/pagespeed.js +42 -0
  100. package/dist/tools/pagespeed.js.map +1 -0
  101. package/dist/tools/schema.d.ts +3 -0
  102. package/dist/tools/schema.js +38 -0
  103. package/dist/tools/schema.js.map +1 -0
  104. package/dist/tools/shared.d.ts +44 -0
  105. package/dist/tools/shared.js +49 -0
  106. package/dist/tools/shared.js.map +1 -0
  107. package/dist/tools/technical.d.ts +3 -0
  108. package/dist/tools/technical.js +25 -0
  109. package/dist/tools/technical.js.map +1 -0
  110. package/dist/version.d.ts +1 -0
  111. package/dist/version.js +4 -0
  112. package/dist/version.js.map +1 -0
  113. package/package.json +93 -4
@@ -0,0 +1,183 @@
1
+ import { chromeuxreport } from '@googleapis/chromeuxreport';
2
+ import { pagespeedonline } from '@googleapis/pagespeedonline';
3
+ import { SeoMcpError } from './errors.js';
4
+ import { googleError } from './google-errors.js';
5
+ /** Soglie ufficiali dei Web Vitals (buono ≤ good, scarso > poor). */
6
+ export const THRESHOLDS = {
7
+ largest_contentful_paint: { good: 2500, poor: 4000, unit: 'ms' },
8
+ interaction_to_next_paint: { good: 200, poor: 500, unit: 'ms' },
9
+ cumulative_layout_shift: { good: 0.1, poor: 0.25, unit: '' },
10
+ first_contentful_paint: { good: 1800, poor: 3000, unit: 'ms' },
11
+ experimental_time_to_first_byte: { good: 800, poor: 1800, unit: 'ms' },
12
+ };
13
+ const CRUX_METRICS = Object.keys(THRESHOLDS);
14
+ const CORE_WEB_VITALS = ['largest_contentful_paint', 'interaction_to_next_paint', 'cumulative_layout_shift'];
15
+ export function rate(metric, value) {
16
+ const t = THRESHOLDS[metric];
17
+ if (!t)
18
+ return undefined;
19
+ return value <= t.good ? 'buono' : value <= t.poor ? 'da migliorare' : 'scarso';
20
+ }
21
+ export class PageSpeedClient {
22
+ psi;
23
+ crux;
24
+ hasKey;
25
+ constructor(apiKey, apis) {
26
+ this.hasKey = Boolean(apiKey);
27
+ this.psi = apis?.psi ?? pagespeedonline({ version: 'v5', auth: apiKey });
28
+ this.crux = apis?.crux ?? chromeuxreport({ version: 'v1', auth: apiKey });
29
+ }
30
+ /** Test Lighthouse tramite PageSpeed Insights. Richiede 10-30 secondi. */
31
+ async analyze(url, strategy = 'mobile', categories = ['performance', 'seo']) {
32
+ assertHttpUrl(url);
33
+ const res = await this.call('PageSpeed Insights API', () => this.psi.pagespeedapi.runpagespeed({ url, strategy: strategy.toUpperCase(), category: categories.map((c) => c.toUpperCase().replace('-', '_')), locale: 'it' }, { timeout: 90_000 }));
34
+ const lr = res.data.lighthouseResult ?? {};
35
+ const audits = lr.audits ?? {};
36
+ const cats = (lr.categories ?? {});
37
+ const scores = {};
38
+ for (const c of categories) {
39
+ const s = cats[c]?.score;
40
+ if (typeof s === 'number')
41
+ scores[c] = Math.round(s * 100);
42
+ }
43
+ const lab = {};
44
+ for (const id of ['largest-contentful-paint', 'cumulative-layout-shift', 'total-blocking-time', 'first-contentful-paint', 'speed-index']) {
45
+ const a = audits[id];
46
+ if (a?.displayValue)
47
+ lab[id] = { value: a.displayValue, numeric: a.numericValue ?? undefined };
48
+ }
49
+ const opportunities = Object.entries(audits)
50
+ .map(([id, a]) => ({ id, a, savings: Number(a.details?.overallSavingsMs ?? 0) }))
51
+ .filter(({ a, savings }) => savings > 0 && (a.score ?? 1) < 1)
52
+ .sort((x, y) => y.savings - x.savings)
53
+ .slice(0, 8)
54
+ .map(({ id, a, savings }) => ({ id, title: a.title ?? id, savingsMs: Math.round(savings), displayValue: a.displayValue ?? undefined }));
55
+ const seoIssues = (cats.seo?.auditRefs ?? [])
56
+ .map((r) => r.id ?? '')
57
+ .filter((id) => audits[id] && audits[id].score === 0)
58
+ .map((id) => ({ id, title: audits[id]?.title ?? id }));
59
+ return { url, strategy, scores, lab, opportunities, seoIssues, fieldData: fieldData(res.data) };
60
+ }
61
+ /** Dati reali degli ultimi 28 giorni per un URL o un'origine. */
62
+ async query(target, formFactor = 'PHONE') {
63
+ this.requireKey();
64
+ const t = cruxTarget(target);
65
+ const res = await this.call('Chrome UX Report API', () => this.crux.records.queryRecord({ requestBody: { ...t.body, formFactor: formFactor === 'ALL' ? undefined : formFactor, metrics: CRUX_METRICS } }), t.label);
66
+ const rec = res.data.record ?? {};
67
+ const metrics = {};
68
+ for (const [name, m] of Object.entries(rec.metrics ?? {})) {
69
+ const p75 = Number(m.percentiles?.p75);
70
+ if (!Number.isFinite(p75))
71
+ continue;
72
+ const d = (m.histogram ?? []).map((b) => Number(b.density ?? 0));
73
+ metrics[name] = {
74
+ p75,
75
+ rating: rate(name, p75),
76
+ distribution: { buono: round(d[0] ?? 0), 'da migliorare': round(d[1] ?? 0), scarso: round(d[2] ?? 0) },
77
+ };
78
+ }
79
+ const cwv = CORE_WEB_VITALS.filter((n) => metrics[n]);
80
+ return {
81
+ target: t.label,
82
+ formFactor,
83
+ period: period(rec.collectionPeriod),
84
+ metrics,
85
+ // Senza INP (siti con poche interazioni) la valutazione si basa su LCP e CLS.
86
+ coreWebVitalsPassed: cwv.length >= 2 ? cwv.every((n) => metrics[n]?.rating === 'buono') : undefined,
87
+ };
88
+ }
89
+ /** Andamento settimanale del 75° percentile, fino a 40 periodi. */
90
+ async history(target, formFactor = 'PHONE', weeks = 25) {
91
+ this.requireKey();
92
+ const t = cruxTarget(target);
93
+ const res = await this.call('Chrome UX Report API', () => this.crux.records.queryHistoryRecord({
94
+ requestBody: {
95
+ ...t.body,
96
+ formFactor: formFactor === 'ALL' ? undefined : formFactor,
97
+ metrics: CORE_WEB_VITALS,
98
+ collectionPeriodCount: Math.min(Math.max(weeks, 1), 40),
99
+ },
100
+ }), t.label);
101
+ const rec = res.data.record ?? {};
102
+ const periods = rec.collectionPeriods ?? [];
103
+ const series = Object.fromEntries(Object.entries(rec.metrics ?? {}).map(([name, m]) => [name, (m.percentilesTimeseries?.p75s ?? []).map((v) => (v == null ? null : Number(v)))]));
104
+ return {
105
+ target: t.label,
106
+ formFactor,
107
+ weeks: periods.map((p, i) => ({
108
+ lastDate: formatDate(p.lastDate),
109
+ p75: Object.fromEntries(Object.entries(series).map(([name, values]) => [name, values[i] ?? null])),
110
+ })),
111
+ };
112
+ }
113
+ requireKey() {
114
+ if (!this.hasKey) {
115
+ throw new SeoMcpError('NOT_CONFIGURED', 'Il Chrome UX Report richiede una API key di Google Cloud.', 'Crea una API key in Google Cloud Console (API e servizi → Credenziali), abilita "Chrome UX Report API" e impostala in SEOMCP_GOOGLE_API_KEY.');
116
+ }
117
+ }
118
+ async call(apiName, fn, target) {
119
+ try {
120
+ return await fn();
121
+ }
122
+ catch (err) {
123
+ const e = err;
124
+ if (apiName === 'Chrome UX Report API' && e.response?.status === 404) {
125
+ throw new SeoMcpError('INVALID_INPUT', `Nessun dato reale per ${target ?? 'questo indirizzo'} nel Chrome UX Report.`, "Google pubblica i dati solo per URL e siti con abbastanza visite da Chrome. Prova con l'origine (tutto il sito) invece della singola pagina, oppure usa psi_analyze per un test di laboratorio.");
126
+ }
127
+ if (apiName === 'PageSpeed Insights API' && e.response?.status === 429 && !this.hasKey) {
128
+ throw new SeoMcpError('QUOTA_EXCEEDED', 'Quota gratuita di PageSpeed Insights esaurita.', 'Senza API key la quota è molto bassa. Crea una API key gratuita, abilita "PageSpeed Insights API" e impostala in SEOMCP_GOOGLE_API_KEY.');
129
+ }
130
+ throw googleError(err, {
131
+ apiName,
132
+ permissionMessage: `La API key non può usare la ${apiName}.`,
133
+ permissionHint: `Controlla che la ${apiName} sia abilitata nel progetto della chiave e che le restrizioni della chiave la includano.`,
134
+ });
135
+ }
136
+ }
137
+ }
138
+ function assertHttpUrl(url) {
139
+ let u;
140
+ try {
141
+ u = new URL(url);
142
+ }
143
+ catch {
144
+ throw new SeoMcpError('INVALID_INPUT', `URL non valido: ${url}`);
145
+ }
146
+ if (u.protocol !== 'https:' && u.protocol !== 'http:')
147
+ throw new SeoMcpError('INVALID_INPUT', 'Sono ammessi solo URL http e https.');
148
+ }
149
+ function cruxTarget(target) {
150
+ if (target.url) {
151
+ assertHttpUrl(target.url);
152
+ return { body: { url: target.url }, label: target.url };
153
+ }
154
+ if (target.origin) {
155
+ assertHttpUrl(target.origin);
156
+ const origin = new URL(target.origin).origin;
157
+ return { body: { origin }, label: origin };
158
+ }
159
+ throw new SeoMcpError('INVALID_INPUT', 'Indica url (una pagina) oppure origin (tutto il sito, es. https://www.esempio.it).');
160
+ }
161
+ function fieldData(data) {
162
+ const src = data.loadingExperience?.metrics ? { scope: 'url', le: data.loadingExperience } : data.originLoadingExperience?.metrics ? { scope: 'origin', le: data.originLoadingExperience } : undefined;
163
+ if (!src)
164
+ return undefined;
165
+ const metrics = {};
166
+ for (const [name, m] of Object.entries(src.le.metrics ?? {})) {
167
+ if (typeof m.percentile === 'number')
168
+ metrics[name] = { p75: m.percentile, category: m.category ?? undefined };
169
+ }
170
+ return { scope: src.scope, overall: src.le.overall_category ?? undefined, metrics };
171
+ }
172
+ function formatDate(d) {
173
+ if (!d?.year)
174
+ return '';
175
+ return `${d.year}-${String(d.month ?? 1).padStart(2, '0')}-${String(d.day ?? 1).padStart(2, '0')}`;
176
+ }
177
+ function period(p) {
178
+ return p ? { firstDate: formatDate(p.firstDate), lastDate: formatDate(p.lastDate) } : undefined;
179
+ }
180
+ function round(n) {
181
+ return Math.round(n * 1000) / 1000;
182
+ }
183
+ //# sourceMappingURL=pagespeed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pagespeed.js","sourceRoot":"","sources":["../../src/core/pagespeed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAA0B,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,eAAe,EAA2B,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AAE,OAAO,EAAE,CAAC;IACxB,OAAO,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;AACrG,CAAC;AAED,SAAS,MAAM,CAAC,CAA6C;IAC3D,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAClG,CAAC;AAED,SAAS,KAAK,CAAC,CAAS;IACtB,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;AACrC,CAAC"}
@@ -0,0 +1,63 @@
1
+ export type Severity = 'errore' | 'avviso' | 'info';
2
+ export interface Issue {
3
+ severity: Severity;
4
+ path: string;
5
+ message: string;
6
+ suggestion?: string;
7
+ }
8
+ export interface RichResultCheck {
9
+ feature: string;
10
+ type: string;
11
+ path: string;
12
+ /** true se tutte le proprietà obbligatorie sono presenti. */
13
+ eligible: boolean;
14
+ missingRequired: string[];
15
+ missingRecommended: string[];
16
+ docs: string;
17
+ note?: string;
18
+ }
19
+ export interface GroupedIssue extends Issue {
20
+ /** Quante volte compare la stessa segnalazione (es. in ogni recensione). */
21
+ count: number;
22
+ }
23
+ export interface RichResultGroup extends RichResultCheck {
24
+ count: number;
25
+ eligibleCount: number;
26
+ }
27
+ export interface ValidationReport {
28
+ vocabulary: string;
29
+ blocks: number;
30
+ /** Tipi trovati, con il numero di oggetti per tipo (anche annidati). */
31
+ types: Record<string, number>;
32
+ topLevelItems: {
33
+ path: string;
34
+ types: string[];
35
+ }[];
36
+ issues: GroupedIssue[];
37
+ richResults: RichResultGroup[];
38
+ summary: {
39
+ errors: number;
40
+ warnings: number;
41
+ info: number;
42
+ };
43
+ }
44
+ export interface PageContext {
45
+ url?: string;
46
+ /** Testo visibile della pagina, per verificare che FAQ e simili siano mostrati davvero. */
47
+ visibleText?: string;
48
+ title?: string;
49
+ h1?: string;
50
+ microdataItems?: number;
51
+ now?: Date;
52
+ }
53
+ /** Il tipo e tutti i suoi antenati (Restaurant → FoodEstablishment → LocalBusiness → …). */
54
+ export declare function ancestors(type: string): Set<string>;
55
+ export declare const isSubtypeOf: (type: string, parent: string) => boolean;
56
+ /** Valida blocchi JSON-LD già letti (e il numero di blocchi non interpretabili). */
57
+ export declare function validateJsonLd(blocks: unknown[], parseErrors: number, ctx?: PageContext): ValidationReport;
58
+ /** Estrae i blocchi da JSON-LD incollato: un oggetto, un array o uno o più <script>. */
59
+ export declare function parseJsonLdInput(input: string): {
60
+ blocks: unknown[];
61
+ parseErrors: number;
62
+ };
63
+ export declare const VOCABULARY_VERSION: string;
@@ -0,0 +1,384 @@
1
+ import vocab from '../data/schema-vocab.json' with { type: 'json' };
2
+ import { RICH_RESULT_RULES } from './google-rich-results.js';
3
+ const V = vocab;
4
+ // ─── Vocabolario ───────────────────────────────────────────────────────────
5
+ const DATE_TYPES = new Set(['Date', 'DateTime', 'Time']);
6
+ const TEXTLIKE = new Set(['Text', 'URL', 'CssSelectorType', 'XPathType', 'PronounceableText']);
7
+ const NUMERIC = new Set(['Number', 'Integer', 'Float']);
8
+ const ancestorsCache = new Map();
9
+ /** Il tipo e tutti i suoi antenati (Restaurant → FoodEstablishment → LocalBusiness → …). */
10
+ export function ancestors(type) {
11
+ const cached = ancestorsCache.get(type);
12
+ if (cached)
13
+ return cached;
14
+ const out = new Set();
15
+ const stack = [type];
16
+ while (stack.length) {
17
+ const t = stack.pop();
18
+ if (out.has(t))
19
+ continue;
20
+ out.add(t);
21
+ for (const p of V.types[t]?.p ?? [])
22
+ stack.push(p);
23
+ }
24
+ ancestorsCache.set(type, out);
25
+ return out;
26
+ }
27
+ export const isSubtypeOf = (type, parent) => ancestors(type).has(parent);
28
+ /** Distanza di Levenshtein, per suggerire la correzione di un refuso. */
29
+ function distance(a, b) {
30
+ const dp = Array.from({ length: b.length + 1 }, (_, i) => i);
31
+ for (let i = 1; i <= a.length; i++) {
32
+ let prev = dp[0];
33
+ dp[0] = i;
34
+ for (let j = 1; j <= b.length; j++) {
35
+ const tmp = dp[j];
36
+ dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
37
+ prev = tmp;
38
+ }
39
+ }
40
+ return dp[b.length];
41
+ }
42
+ function suggest(name, candidates) {
43
+ const lower = name.toLowerCase();
44
+ const exactCase = candidates.find((c) => c.toLowerCase() === lower);
45
+ if (exactCase)
46
+ return exactCase;
47
+ let best;
48
+ let bestD = Infinity;
49
+ for (const c of candidates) {
50
+ if (Math.abs(c.length - name.length) > 3)
51
+ continue;
52
+ const d = distance(lower, c.toLowerCase());
53
+ if (d < bestD) {
54
+ bestD = d;
55
+ best = c;
56
+ }
57
+ }
58
+ return bestD <= Math.max(2, Math.floor(name.length / 4)) ? best : undefined;
59
+ }
60
+ const TYPE_NAMES = Object.keys(V.types);
61
+ const PROP_NAMES = Object.keys(V.props);
62
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
63
+ const asArray = (v) => (Array.isArray(v) ? v : v === undefined || v === null ? [] : [v]);
64
+ function typeNames(node) {
65
+ return asArray(node['@type']).map((t) => String(t).replace(/^(https?:\/\/)?schema\.org\//, '').replace(/^schema:/, ''));
66
+ }
67
+ function isSchemaContext(ctx) {
68
+ if (typeof ctx === 'string')
69
+ return /^https?:\/\/schema\.org\/?$/.test(ctx.trim());
70
+ if (Array.isArray(ctx))
71
+ return ctx.some(isSchemaContext);
72
+ if (isObj(ctx))
73
+ return isSchemaContext(ctx['@vocab']);
74
+ return false;
75
+ }
76
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
77
+ const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/;
78
+ const ISO_TIME = /^\d{2}:\d{2}(:\d{2})?(Z|[+-]\d{2}:?\d{2})?$/;
79
+ class Validator {
80
+ ctx;
81
+ issues = [];
82
+ items = [];
83
+ nodes = [];
84
+ ids = new Set();
85
+ refs = [];
86
+ constructor(ctx) {
87
+ this.ctx = ctx;
88
+ }
89
+ add(severity, path, message, suggestion) {
90
+ this.issues.push({ severity, path, message, ...(suggestion ? { suggestion } : {}) });
91
+ }
92
+ topLevel(value, path) {
93
+ for (const [i, item] of asArray(value).entries()) {
94
+ const p = Array.isArray(value) ? `${path}[${i}]` : path;
95
+ if (!isObj(item)) {
96
+ this.add('errore', p, 'Il blocco JSON-LD deve contenere un oggetto.');
97
+ continue;
98
+ }
99
+ if (!isSchemaContext(item['@context'])) {
100
+ this.add(item['@context'] ? 'errore' : 'avviso', p, item['@context'] ? `@context non punta a schema.org: ${JSON.stringify(item['@context'])}.` : '@context mancante: senza, i motori potrebbero non riconoscere il vocabolario.', 'Usa "@context": "https://schema.org".');
101
+ }
102
+ if (Array.isArray(item['@graph'])) {
103
+ item['@graph'].forEach((n, j) => {
104
+ if (isObj(n))
105
+ this.node(n, `${p}.@graph[${j}]`, true);
106
+ else
107
+ this.add('errore', `${p}.@graph[${j}]`, 'Elemento di @graph non valido.');
108
+ });
109
+ }
110
+ else
111
+ this.node(item, p, true);
112
+ }
113
+ }
114
+ node(node, path, topLevel) {
115
+ const keys = Object.keys(node).filter((k) => !k.startsWith('@'));
116
+ if (typeof node['@id'] === 'string') {
117
+ if (keys.length === 0 && !node['@type']) {
118
+ this.refs.push({ id: node['@id'], path });
119
+ return;
120
+ }
121
+ this.ids.add(node['@id']);
122
+ }
123
+ const types = typeNames(node);
124
+ if (!types.length) {
125
+ if (topLevel)
126
+ this.add('errore', path, 'Manca @type: il motore non sa che cosa descrive questo oggetto.');
127
+ return;
128
+ }
129
+ this.items.push({ path, types });
130
+ this.nodes.push({ node, types, path, topLevel });
131
+ const known = [];
132
+ for (const t of types) {
133
+ const def = V.types[t];
134
+ if (!def) {
135
+ this.add('errore', `${path}.@type`, `Il tipo "${t}" non esiste in schema.org.`, suggest(t, TYPE_NAMES) && `Forse intendevi "${suggest(t, TYPE_NAMES)}"?`);
136
+ continue;
137
+ }
138
+ known.push(t);
139
+ if (def.s)
140
+ this.add('avviso', `${path}.@type`, `Il tipo "${t}" è superato.`, `Usa "${def.s}".`);
141
+ if (def.pn)
142
+ this.add('info', `${path}.@type`, `Il tipo "${t}" è in fase di proposta (pending): i motori potrebbero ignorarlo.`);
143
+ }
144
+ const allAncestors = new Set(known.flatMap((t) => [...ancestors(t)]));
145
+ for (const key of keys) {
146
+ const p = `${path}.${key}`;
147
+ // Annotazioni delle azioni (es. "query-input" in SearchAction): sintassi valida di schema.org.
148
+ const action = /^(.+)-(input|output)$/.exec(key);
149
+ if (action && V.props[action[1]])
150
+ continue;
151
+ const prop = V.props[key];
152
+ if (!prop) {
153
+ const s = suggest(key, PROP_NAMES);
154
+ this.add('errore', p, `La proprietà "${key}" non esiste in schema.org.`, s && `Forse intendevi "${s}"?`);
155
+ continue;
156
+ }
157
+ if (prop.s)
158
+ this.add('avviso', p, `La proprietà "${key}" è superata.`, `Usa "${prop.s}".`);
159
+ if (known.length && !prop.d.some((d) => allAncestors.has(d))) {
160
+ this.add('avviso', p, `"${key}" non è prevista per ${known.join('/')}. È ammessa per: ${prop.d.slice(0, 6).join(', ')}${prop.d.length > 6 ? '…' : ''}.`);
161
+ }
162
+ for (const [i, v] of asArray(node[key]).entries())
163
+ this.value(v, prop.r, Array.isArray(node[key]) ? `${p}[${i}]` : p, key);
164
+ }
165
+ }
166
+ value(v, ranges, path, prop) {
167
+ const rangeSet = new Set(ranges);
168
+ const acceptsText = ranges.some((r) => TEXTLIKE.has(r) || isSubtypeOf(r, 'Text'));
169
+ if (isObj(v)) {
170
+ const types = typeNames(v);
171
+ if (types.length && ranges.length) {
172
+ const ok = types.some((t) => V.types[t] && ranges.some((r) => isSubtypeOf(t, r)));
173
+ if (!ok && types.every((t) => V.types[t])) {
174
+ this.add('avviso', path, `Valore di tipo ${types.join('/')}, ma "${prop}" si aspetta: ${ranges.join(', ')}.`);
175
+ }
176
+ }
177
+ this.node(v, path, false);
178
+ return;
179
+ }
180
+ if (typeof v === 'string') {
181
+ const s = v.trim();
182
+ if (!s) {
183
+ this.add('avviso', path, `"${prop}" è vuota.`);
184
+ return;
185
+ }
186
+ const onlyDates = ranges.length > 0 && ranges.every((r) => DATE_TYPES.has(r));
187
+ if (onlyDates) {
188
+ const okFormat = (rangeSet.has('Date') && (ISO_DATE.test(s) || ISO_DATETIME.test(s))) || (rangeSet.has('DateTime') && ISO_DATETIME.test(s)) || (rangeSet.has('Time') && ISO_TIME.test(s));
189
+ if (!okFormat && ISO_DATETIME.test(s.replace(' ', 'T'))) {
190
+ this.add('avviso', path, `"${prop}" usa uno spazio tra data e ora ("${s.slice(0, 40)}"): lo standard ISO 8601 prevede la "T".`, `Scrivi "${s.replace(' ', 'T')}".`);
191
+ return;
192
+ }
193
+ if (!okFormat)
194
+ this.add('errore', path, `"${prop}" deve essere una data in formato ISO 8601, trovato "${s.slice(0, 40)}".`, 'Esempio: "2026-09-28" oppure "2026-09-28T10:30:00+02:00".');
195
+ return;
196
+ }
197
+ const onlyUrl = ranges.length > 0 && ranges.every((r) => r === 'URL');
198
+ if ((onlyUrl || prop === 'url' || prop === 'sameAs' || prop === 'logo' || prop === 'image') && !/^https?:\/\//i.test(s)) {
199
+ this.add(onlyUrl ? 'avviso' : 'info', path, `"${prop}" dovrebbe essere un URL assoluto, trovato "${s.slice(0, 60)}".`);
200
+ return;
201
+ }
202
+ // Enumerazioni: "https://schema.org/InStock" oppure "InStock".
203
+ const enumRanges = ranges.filter((r) => isSubtypeOf(r, 'Enumeration'));
204
+ if (enumRanges.length && !acceptsText) {
205
+ const member = s.replace(/^(https?:\/\/)?schema\.org\//, '');
206
+ const cls = V.members[member];
207
+ if (!cls || !enumRanges.some((r) => isSubtypeOf(cls, r))) {
208
+ const options = Object.entries(V.members).filter(([, c]) => enumRanges.some((r) => isSubtypeOf(c, r))).map(([m]) => m);
209
+ this.add('avviso', path, `"${s}" non è un valore previsto per "${prop}".`, options.length ? `Valori ammessi: ${options.slice(0, 8).join(', ')}${options.length > 8 ? '…' : ''} (es. "https://schema.org/${options[0]}").` : undefined);
210
+ }
211
+ }
212
+ return;
213
+ }
214
+ if (typeof v === 'number') {
215
+ const quantity = ranges.some((r) => r === 'QuantitativeValue' || r === 'MonetaryAmount' || isSubtypeOf(r, 'Quantity'));
216
+ if (ranges.length && !quantity && !ranges.some((r) => NUMERIC.has(r) || TEXTLIKE.has(r) || isSubtypeOf(r, 'Number'))) {
217
+ this.add('avviso', path, `"${prop}" è un numero, ma si aspetta: ${ranges.join(', ')}.`);
218
+ }
219
+ return;
220
+ }
221
+ if (typeof v === 'boolean') {
222
+ if (ranges.length && !ranges.includes('Boolean') && !acceptsText)
223
+ this.add('avviso', path, `"${prop}" è un booleano, ma si aspetta: ${ranges.join(', ')}.`);
224
+ }
225
+ }
226
+ finish() {
227
+ for (const r of this.refs) {
228
+ if (!this.ids.has(r.id))
229
+ this.add('info', r.path, `Riferimento a "${r.id}", non definito in questa pagina.`);
230
+ }
231
+ this.consistency();
232
+ }
233
+ consistency() {
234
+ const now = this.ctx.now ?? new Date();
235
+ for (const { node, types, path } of this.nodes) {
236
+ const pub = typeof node['datePublished'] === 'string' ? Date.parse(node['datePublished']) : NaN;
237
+ const mod = typeof node['dateModified'] === 'string' ? Date.parse(node['dateModified']) : NaN;
238
+ if (!Number.isNaN(pub) && !Number.isNaN(mod) && mod < pub)
239
+ this.add('errore', `${path}.dateModified`, 'dateModified è precedente a datePublished.');
240
+ for (const [k, t] of [['datePublished', pub], ['dateModified', mod]]) {
241
+ if (!Number.isNaN(t) && t > now.getTime() + 86_400_000)
242
+ this.add('avviso', `${path}.${k}`, `${k} è nel futuro.`);
243
+ }
244
+ const text = this.ctx.visibleText ? normalize(this.ctx.visibleText) : undefined;
245
+ if (text && types.includes('FAQPage')) {
246
+ for (const [i, q] of asArray(node['mainEntity']).entries()) {
247
+ const name = isObj(q) && typeof q['name'] === 'string' ? q['name'] : undefined;
248
+ if (name && !text.includes(normalize(name).slice(0, 60))) {
249
+ this.add('avviso', `${path}.mainEntity[${i}]`, `La domanda "${name.slice(0, 80)}" non compare nel testo visibile della pagina: Google richiede che il contenuto delle FAQ sia visibile.`);
250
+ }
251
+ }
252
+ }
253
+ const headline = typeof node['headline'] === 'string' ? node['headline'] : undefined;
254
+ if (headline && this.ctx.h1 && types.some((t) => isSubtypeOf(t, 'Article'))) {
255
+ const overlap = tokenOverlap(headline, this.ctx.h1);
256
+ if (overlap < 0.5)
257
+ this.add('info', `${path}.headline`, `headline e H1 hanno poche parole in comune (${Math.round(overlap * 100)}%): headline "${headline.slice(0, 70)}", H1 "${this.ctx.h1.slice(0, 70)}".`);
258
+ }
259
+ }
260
+ }
261
+ }
262
+ function normalize(s) {
263
+ return s.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
264
+ }
265
+ function tokenOverlap(a, b) {
266
+ const ta = new Set(normalize(a).split(' ').filter((w) => w.length > 2));
267
+ const tb = new Set(normalize(b).split(' ').filter((w) => w.length > 2));
268
+ if (!ta.size || !tb.size)
269
+ return 1;
270
+ let common = 0;
271
+ for (const w of ta)
272
+ if (tb.has(w))
273
+ common++;
274
+ return common / Math.min(ta.size, tb.size);
275
+ }
276
+ // ─── Requisiti Google ──────────────────────────────────────────────────────
277
+ function hasPath(node, path) {
278
+ const [head, ...rest] = path.split('.');
279
+ const values = asArray(node[head]).filter((v) => v !== '' && v !== null);
280
+ if (!values.length)
281
+ return false;
282
+ if (!rest.length)
283
+ return true;
284
+ // Per gli elenchi (es. itemListElement) ogni elemento deve avere la proprietà.
285
+ return values.every((v) => isObj(v) && hasPath(v, rest.join('.')));
286
+ }
287
+ const satisfied = (node, spec) => spec.split('|').some((alt) => hasPath(node, alt));
288
+ function checkRule(node, rule, path) {
289
+ const missingRequired = rule.required.filter((r) => !satisfied(node, r));
290
+ return {
291
+ feature: rule.feature,
292
+ type: rule.type,
293
+ path,
294
+ eligible: missingRequired.length === 0,
295
+ missingRequired,
296
+ missingRecommended: rule.recommended.filter((r) => !satisfied(node, r)),
297
+ docs: rule.docs,
298
+ ...(rule.note ? { note: rule.note } : {}),
299
+ };
300
+ }
301
+ // ─── API ───────────────────────────────────────────────────────────────────
302
+ /** Valida blocchi JSON-LD già letti (e il numero di blocchi non interpretabili). */
303
+ export function validateJsonLd(blocks, parseErrors, ctx = {}) {
304
+ const v = new Validator(ctx);
305
+ for (let i = 0; i < parseErrors; i++)
306
+ v.add('errore', `blocco non valido ${i + 1}`, 'Un blocco <script type="application/ld+json"> contiene JSON non valido ed è ignorato dai motori.', 'Controlla virgole finali, virgolette e parentesi.');
307
+ blocks.forEach((b, i) => v.topLevel(b, `blocco[${i}]`));
308
+ v.finish();
309
+ if (!blocks.length && !parseErrors) {
310
+ v.add(ctx.microdataItems ? 'info' : 'avviso', 'pagina', ctx.microdataItems ? `Nessun JSON-LD, ma ${ctx.microdataItems} elementi microdata: il validatore controlla solo JSON-LD, il formato consigliato da Google.` : 'Nessun dato strutturato JSON-LD trovato.');
311
+ }
312
+ // Per ogni oggetto vale solo la regola più specifica (Recipe, non anche HowTo; LocalBusiness, non anche Organization).
313
+ const perNode = [];
314
+ for (const { node, types, path, topLevel } of v.nodes) {
315
+ const matching = RICH_RESULT_RULES.filter((rule) => (!rule.topLevelOnly || topLevel) && types.some((t) => V.types[t] && isSubtypeOf(t, rule.type)));
316
+ const specific = matching.filter((r) => !matching.some((o) => o !== r && isSubtypeOf(o.type, r.type)));
317
+ for (const rule of specific)
318
+ perNode.push(checkRule(node, rule, path));
319
+ }
320
+ const count = (s) => v.issues.filter((i) => i.severity === s).length;
321
+ const types = {};
322
+ for (const it of v.items)
323
+ for (const t of it.types)
324
+ types[t] = (types[t] ?? 0) + 1;
325
+ return {
326
+ vocabulary: `schema.org ${V.version} (${V.date})`,
327
+ blocks: blocks.length,
328
+ types,
329
+ topLevelItems: v.nodes.filter((n) => n.topLevel).map((n) => ({ path: n.path, types: n.types })),
330
+ issues: groupIssues(v.issues),
331
+ richResults: groupRichResults(perNode),
332
+ summary: { errors: count('errore'), warnings: count('avviso'), info: count('info') },
333
+ };
334
+ }
335
+ /** Raggruppa segnalazioni identiche che differiscono solo per l'indice (es. review[0], review[1]…). */
336
+ function groupIssues(issues) {
337
+ const map = new Map();
338
+ for (const i of issues) {
339
+ const key = `${i.severity}|${i.path.replace(/\[\d+\]/g, '[*]')}|${i.message.replace(/\d+/g, '#')}`;
340
+ const g = map.get(key);
341
+ if (g)
342
+ g.count++;
343
+ else
344
+ map.set(key, { ...i, count: 1 });
345
+ }
346
+ const order = { errore: 0, avviso: 1, info: 2 };
347
+ return [...map.values()].sort((a, b) => order[a.severity] - order[b.severity]);
348
+ }
349
+ function groupRichResults(checks) {
350
+ const map = new Map();
351
+ for (const c of checks) {
352
+ const key = `${c.feature}|${c.path.replace(/\[\d+\]/g, '[*]')}`;
353
+ const g = map.get(key);
354
+ if (!g) {
355
+ map.set(key, { ...c, count: 1, eligibleCount: c.eligible ? 1 : 0 });
356
+ continue;
357
+ }
358
+ g.count++;
359
+ if (c.eligible)
360
+ g.eligibleCount++;
361
+ g.eligible = g.eligible && c.eligible;
362
+ g.missingRequired = [...new Set([...g.missingRequired, ...c.missingRequired])];
363
+ g.missingRecommended = [...new Set([...g.missingRecommended, ...c.missingRecommended])];
364
+ }
365
+ return [...map.values()];
366
+ }
367
+ /** Estrae i blocchi da JSON-LD incollato: un oggetto, un array o uno o più <script>. */
368
+ export function parseJsonLdInput(input) {
369
+ const scripts = [...input.matchAll(/<script[^>]*>([\s\S]*?)<\/script>/gi)].map((m) => m[1] ?? '');
370
+ const sources = scripts.length ? scripts : [input];
371
+ const blocks = [];
372
+ let parseErrors = 0;
373
+ for (const src of sources) {
374
+ try {
375
+ blocks.push(JSON.parse(src));
376
+ }
377
+ catch {
378
+ parseErrors++;
379
+ }
380
+ }
381
+ return { blocks, parseErrors };
382
+ }
383
+ export const VOCABULARY_VERSION = V.version;
384
+ //# sourceMappingURL=schema-validate.js.map