@lynx-seo/engine 3.3.4 → 3.3.5

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.
package/dist/index.mjs CHANGED
@@ -94111,6 +94111,557 @@ class OgImageGenerator {
94111
94111
  }
94112
94112
  }
94113
94113
 
94114
+ // src/geo-citability-scorer.ts
94115
+ var AUTHORITATIVE_TLDS = new Set([".edu", ".gov", ".org", ".mil"]);
94116
+ var AUTHORITATIVE_DOMAINS = new Set([
94117
+ "wikipedia.org",
94118
+ "wikidata.org",
94119
+ "insee.fr",
94120
+ "data.gouv.fr",
94121
+ "service-public.fr",
94122
+ "europa.eu",
94123
+ "who.int",
94124
+ "cdc.gov",
94125
+ "nature.com",
94126
+ "sciencedirect.com",
94127
+ "arxiv.org",
94128
+ "nih.gov",
94129
+ "ncbi.nlm.nih.gov",
94130
+ "ieee.org",
94131
+ "springer.com",
94132
+ "w3.org",
94133
+ "github.com",
94134
+ "stackoverflow.com",
94135
+ "bloomberg.com",
94136
+ "reuters.com",
94137
+ "economist.com",
94138
+ "forbes.com",
94139
+ "hbr.org",
94140
+ "statista.com",
94141
+ "gartner.com",
94142
+ "mckinsey.com"
94143
+ ]);
94144
+ var HEDGING_PATTERNS = [
94145
+ /\b(?:might be|could be|perhaps|maybe|in some cases|usually|often|generally|it seems|it appears)\b/gi,
94146
+ /\b(?:peut-être|pourrait être|il semble que|dans certains cas|souvent|généralement|il paraît|potentiellement)\b/gi
94147
+ ];
94148
+ var CONNECTIVES_PATTERNS = [
94149
+ /\b(?:therefore|consequently|furthermore|moreover|however|nevertheless|in addition|as a result|for instance|in particular|specifically)\b/gi,
94150
+ /\b(?:par conséquent|en outre|de plus|cependant|néanmoins|ainsi|par exemple|en particulier|notamment|d'ailleurs|en effet)\b/gi
94151
+ ];
94152
+
94153
+ class GeoCitabilityScorer {
94154
+ static analyze(rawInput) {
94155
+ const html = rawInput;
94156
+ const plainText = this.stripHtml(html);
94157
+ const words = plainText.match(/\b[\w'-]+\b/g) || [];
94158
+ const wordCount = words.length;
94159
+ const detectedCitations = this.extractCitations(html);
94160
+ const authCitationsCount = detectedCitations.filter((c) => c.isAuthoritative).length;
94161
+ const detectedStats = this.extractStatistics(plainText);
94162
+ const detectedQuotes = this.extractQuotations(rawInput);
94163
+ const { answerFirstCount, totalH2Count } = this.evaluateAnswerFirst(html);
94164
+ const { optimalPassagesCount, totalPassagesCount } = this.evaluatePassageDensity(html);
94165
+ const hedgingMatches = [];
94166
+ for (const pat of HEDGING_PATTERNS) {
94167
+ const found = plainText.match(pat);
94168
+ if (found)
94169
+ hedgingMatches.push(...found.map((s) => s.toLowerCase()));
94170
+ }
94171
+ let connectiveCount = 0;
94172
+ for (const pat of CONNECTIVES_PATTERNS) {
94173
+ const found = plainText.match(pat);
94174
+ if (found)
94175
+ connectiveCount += found.length;
94176
+ }
94177
+ const repeatedTerms = this.evaluateKeywordDensity(words);
94178
+ const hasKeywordStuffing = repeatedTerms.some((t) => t.density > 0.035 && t.count > 5);
94179
+ const methods = {};
94180
+ const citeScore = Math.min(authCitationsCount * 35 + detectedCitations.length * 10, 100);
94181
+ methods["cite_sources"] = {
94182
+ id: "M01",
94183
+ name: "Citations de Sources d'Autorité",
94184
+ category: "princeton",
94185
+ score: citeScore,
94186
+ weight: 20,
94187
+ weightedScore: citeScore * 20 / 100,
94188
+ measuredImpact: "+30% à +115% de visibilité IA (Princeton KDD 2024)",
94189
+ detectedCount: detectedCitations.length,
94190
+ status: citeScore >= 70 ? "pass" : citeScore >= 35 ? "warn" : "fail",
94191
+ details: `${authCitationsCount} lien(s) vers domaines institutionnels (.edu, .gov, wikipedia, etc.), ${detectedCitations.length} total.`
94192
+ };
94193
+ const statScore = Math.min(detectedStats.length * 20, 100);
94194
+ methods["statistics"] = {
94195
+ id: "M02",
94196
+ name: "Densité de Statistiques & Faits Chiffrés",
94197
+ category: "princeton",
94198
+ score: statScore,
94199
+ weight: 20,
94200
+ weightedScore: statScore * 20 / 100,
94201
+ measuredImpact: "+40% de visibilité IA moyenne (Princeton KDD 2024)",
94202
+ detectedCount: detectedStats.length,
94203
+ status: statScore >= 70 ? "pass" : statScore >= 30 ? "warn" : "fail",
94204
+ details: `${detectedStats.length} données chiffrées/statistiques concrètes détectées.`
94205
+ };
94206
+ const quoteScore = Math.min(detectedQuotes.length * 40 + (detectedQuotes.some((q) => q.hasRoleOrOrg) ? 20 : 0), 100);
94207
+ methods["quotations"] = {
94208
+ id: "M03",
94209
+ name: "Citations Directes d'Experts avec Attribution",
94210
+ category: "princeton",
94211
+ score: quoteScore,
94212
+ weight: 15,
94213
+ weightedScore: quoteScore * 15 / 100,
94214
+ measuredImpact: "+30% à +40% de visibilité IA (Princeton KDD 2024)",
94215
+ detectedCount: detectedQuotes.length,
94216
+ status: quoteScore >= 60 ? "pass" : quoteScore > 0 ? "warn" : "fail",
94217
+ details: `${detectedQuotes.length} citation(s) formelle(s) avec signature d'expert/organisation.`
94218
+ };
94219
+ const answerFirstScore = totalH2Count > 0 ? Math.round(answerFirstCount / totalH2Count * 100) : wordCount > 200 ? 50 : 0;
94220
+ methods["answer_first"] = {
94221
+ id: "M10",
94222
+ name: "Structure Answer-First post-H2",
94223
+ category: "autogeo",
94224
+ score: answerFirstScore,
94225
+ weight: 15,
94226
+ weightedScore: answerFirstScore * 15 / 100,
94227
+ measuredImpact: "+25% de probabilité d'extraction",
94228
+ detectedCount: answerFirstCount,
94229
+ status: answerFirstScore >= 75 ? "pass" : answerFirstScore >= 40 ? "warn" : "fail",
94230
+ details: `${answerFirstCount}/${totalH2Count} sections H2 débutent par une réponse directe dans les 150 premiers caractères.`
94231
+ };
94232
+ const passageScore = totalPassagesCount > 0 ? Math.round(optimalPassagesCount / totalPassagesCount * 100) : 50;
94233
+ methods["passage_density"] = {
94234
+ id: "M11",
94235
+ name: "Densité des Passages & Format RAG (Stanford)",
94236
+ category: "stanford",
94237
+ score: passageScore,
94238
+ weight: 15,
94239
+ weightedScore: passageScore * 15 / 100,
94240
+ measuredImpact: "+23% de citation (Stanford 2025 / SE Ranking 4.7x)",
94241
+ detectedCount: optimalPassagesCount,
94242
+ status: passageScore >= 60 ? "pass" : passageScore >= 30 ? "warn" : "fail",
94243
+ details: `${optimalPassagesCount}/${totalPassagesCount} paragraphes calibrés (50-150 mots avec faits chiffrés).`
94244
+ };
94245
+ const hedgingPenalty = Math.min(hedgingMatches.length * 15, 60);
94246
+ const toneScore = Math.max(100 - hedgingPenalty, 20);
94247
+ methods["authoritative_tone"] = {
94248
+ id: "M04",
94249
+ name: "Tonalité d'Autorité & Absence d'Hésitation",
94250
+ category: "princeton",
94251
+ score: toneScore,
94252
+ weight: 10,
94253
+ weightedScore: toneScore * 10 / 100,
94254
+ measuredImpact: "+6% à +12% de clarté perçue (Princeton KDD 2024)",
94255
+ detectedCount: hedgingMatches.length,
94256
+ status: toneScore >= 80 ? "pass" : toneScore >= 50 ? "warn" : "fail",
94257
+ details: `${hedgingMatches.length} formulation(s) hésitante(s) ("peut-être", "souvent", etc.).`
94258
+ };
94259
+ const fluencyScore = Math.min(connectiveCount * 12 + 40, 100);
94260
+ methods["fluency"] = {
94261
+ id: "M05",
94262
+ name: "Fluidité Sémantique & Connecteurs Logiques",
94263
+ category: "princeton",
94264
+ score: fluencyScore,
94265
+ weight: 5,
94266
+ weightedScore: fluencyScore * 5 / 100,
94267
+ measuredImpact: "+15% à +30% de parsabilité LLM (Princeton KDD 2024)",
94268
+ detectedCount: connectiveCount,
94269
+ status: fluencyScore >= 70 ? "pass" : "warn",
94270
+ details: `${connectiveCount} connecteur(s) logique(s) structurant le raisonnement.`
94271
+ };
94272
+ let totalWeighted = Object.values(methods).reduce((acc, m) => acc + m.weightedScore, 0);
94273
+ if (hasKeywordStuffing) {
94274
+ totalWeighted = Math.max(totalWeighted - 15, 0);
94275
+ }
94276
+ const overallScore = Math.min(Math.max(Math.round(totalWeighted), 0), 100);
94277
+ let grade = "F";
94278
+ let aiCitationProbability = "CRITIQUE";
94279
+ if (overallScore >= 90) {
94280
+ grade = "S";
94281
+ aiCitationProbability = "TRÈS ÉLEVÉE";
94282
+ } else if (overallScore >= 75) {
94283
+ grade = "A";
94284
+ aiCitationProbability = "ÉLEVÉE";
94285
+ } else if (overallScore >= 60) {
94286
+ grade = "B";
94287
+ aiCitationProbability = "MOYENNE";
94288
+ } else if (overallScore >= 40) {
94289
+ grade = "C";
94290
+ aiCitationProbability = "FAIBLE";
94291
+ } else if (overallScore >= 25) {
94292
+ grade = "D";
94293
+ aiCitationProbability = "CRITIQUE";
94294
+ }
94295
+ const recommendations = [];
94296
+ if (authCitationsCount === 0) {
94297
+ recommendations.push("\uD83D\uDD34 Priorité 1 : Ajoutez 2 à 3 liens sortants vers des sources institutionnelles réputées (.edu, .gov, INSEE, Wikipédia) (+30% à +115% de visibilité IA).");
94298
+ }
94299
+ if (detectedStats.length < 3) {
94300
+ recommendations.push("\uD83D\uDD34 Priorité 2 : Remplacez les affirmations vagues par des statistiques concrètes (pourcentages, métriques de gains, dates récentes) (+40% de citation).");
94301
+ }
94302
+ if (detectedQuotes.length === 0) {
94303
+ recommendations.push(`\uD83D\uDFE0 Priorité 3 : Insérez au moins une citation directe d'expert avec signature complète : "Texte" - Nom, Fonction, Société, Année (+35% de crédibilité).`);
94304
+ }
94305
+ if (answerFirstCount < totalH2Count) {
94306
+ recommendations.push("\uD83D\uDFE1 Priorité 4 : Formulez la réponse/définition clé dès les 150 premiers caractères sous chaque titre H2.");
94307
+ }
94308
+ if (hasKeywordStuffing) {
94309
+ recommendations.push("⚠️ Attention : Répétition excessive de mots-clés détectée. Les moteurs de recherche IA pénalisent le bourrage de mots-clés.");
94310
+ }
94311
+ return {
94312
+ overallScore,
94313
+ grade,
94314
+ aiCitationProbability,
94315
+ wordCount,
94316
+ methods,
94317
+ detected: {
94318
+ citations: detectedCitations,
94319
+ statistics: detectedStats,
94320
+ quotes: detectedQuotes,
94321
+ answerFirstH2Count: answerFirstCount,
94322
+ totalH2Count,
94323
+ optimalPassagesCount,
94324
+ totalPassagesCount,
94325
+ hedgingPhrases: Array.from(new Set(hedgingMatches)),
94326
+ topRepeatedTerms: repeatedTerms.slice(0, 5)
94327
+ },
94328
+ recommendations
94329
+ };
94330
+ }
94331
+ static stripHtml(html) {
94332
+ return html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, " ").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
94333
+ }
94334
+ static extractCitations(html) {
94335
+ const citations = [];
94336
+ const linkRegex = /<a\s+(?:[^>]*?\s+)?href=["'](https?:\/\/[^"'>]+)["'][^>]*>(.*?)<\/a>/gi;
94337
+ let match;
94338
+ while ((match = linkRegex.exec(html)) !== null) {
94339
+ const url = match[1];
94340
+ const text = this.stripHtml(match[2]);
94341
+ try {
94342
+ const parsed = new URL(url);
94343
+ const host = parsed.hostname.toLowerCase();
94344
+ const isAuth = Array.from(AUTHORITATIVE_TLDS).some((tld) => host.endsWith(tld)) || Array.from(AUTHORITATIVE_DOMAINS).some((d) => host === d || host.endsWith("." + d));
94345
+ citations.push({
94346
+ url,
94347
+ domain: host,
94348
+ text,
94349
+ isAuthoritative: isAuth
94350
+ });
94351
+ } catch {}
94352
+ }
94353
+ const mdLinkRegex = /\[([^\]]+)\]\((https?:\/\/[^\s\)]+)\)/g;
94354
+ while ((match = mdLinkRegex.exec(html)) !== null) {
94355
+ const text = match[1];
94356
+ const url = match[2];
94357
+ try {
94358
+ const parsed = new URL(url);
94359
+ const host = parsed.hostname.toLowerCase();
94360
+ const isAuth = Array.from(AUTHORITATIVE_TLDS).some((tld) => host.endsWith(tld)) || Array.from(AUTHORITATIVE_DOMAINS).some((d) => host === d || host.endsWith("." + d));
94361
+ citations.push({
94362
+ url,
94363
+ domain: host,
94364
+ text,
94365
+ isAuthoritative: isAuth
94366
+ });
94367
+ } catch {}
94368
+ }
94369
+ return citations;
94370
+ }
94371
+ static extractStatistics(text) {
94372
+ const stats = [];
94373
+ const statPatterns = [
94374
+ { re: /\b\d+(?:[.,]\d+)?\s*%/g, type: "percentage" },
94375
+ {
94376
+ re: /(?:[$€£]\s*\d+(?:[.,]\d+)*(?:\s*(?:M|B|K|millions?|milliards?))?|\b\d+(?:[.,]\d+)*\s*[$€£])/gi,
94377
+ type: "currency"
94378
+ },
94379
+ { re: /\b\d+(?:[.,]\d+)?\s*[xX]\b/g, type: "multiplier" },
94380
+ {
94381
+ re: /\b\d+\s*(?:millions?|milliards?|billions?|milliers?)\b/gi,
94382
+ type: "scale"
94383
+ },
94384
+ { re: /\b(?:en|depuis|in|since)\s+20[12]\d\b/gi, type: "date" }
94385
+ ];
94386
+ for (const { re, type } of statPatterns) {
94387
+ let m;
94388
+ while ((m = re.exec(text)) !== null) {
94389
+ const raw = m[0];
94390
+ const start = Math.max(0, m.index - 30);
94391
+ const end = Math.min(text.length, m.index + raw.length + 30);
94392
+ const context = text.substring(start, end).replace(/\s+/g, " ").trim();
94393
+ stats.push({ raw, context, type });
94394
+ }
94395
+ }
94396
+ return stats;
94397
+ }
94398
+ static extractQuotations(input) {
94399
+ const quotes = [];
94400
+ const bqRegex = /<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gi;
94401
+ let bqMatch;
94402
+ while ((bqMatch = bqRegex.exec(input)) !== null) {
94403
+ const bqText = this.stripHtml(bqMatch[1]);
94404
+ quotes.push({
94405
+ quote: bqText,
94406
+ hasRoleOrOrg: /[\u2014\u2013\-,]/.test(bqText)
94407
+ });
94408
+ }
94409
+ const mdBqRegex = /(?:^|\n)>\s*([^\n]+)/g;
94410
+ let mdBqMatch;
94411
+ while ((mdBqMatch = mdBqRegex.exec(input)) !== null) {
94412
+ const bqText = mdBqMatch[1].trim();
94413
+ if (bqText.length > 15) {
94414
+ quotes.push({
94415
+ quote: bqText,
94416
+ hasRoleOrOrg: /[\u2014\u2013\-,:]/.test(bqText)
94417
+ });
94418
+ }
94419
+ }
94420
+ const quoteRegex = /["«\u201c]([^"»\u201d]{15,300})["»\u201d]\s*(?:\u2014|\u2013|-)\s*([^\n]{3,120})/g;
94421
+ let qMatch;
94422
+ while ((qMatch = quoteRegex.exec(input)) !== null) {
94423
+ const quote = qMatch[1].trim();
94424
+ const attribution = qMatch[2].trim();
94425
+ quotes.push({
94426
+ quote,
94427
+ attribution,
94428
+ hasRoleOrOrg: attribution.includes(",") || attribution.includes("—") || attribution.includes("-")
94429
+ });
94430
+ }
94431
+ return quotes;
94432
+ }
94433
+ static evaluateAnswerFirst(content) {
94434
+ let sections = [];
94435
+ if (/<h2[^>]*>/i.test(content)) {
94436
+ sections = content.split(/<h2[^>]*>/i).slice(1).map((s) => s.replace(/^[\s\S]*?<\/h2>/i, ""));
94437
+ } else if (/(?:^|\n)##\s+/m.test(content)) {
94438
+ sections = content.split(/(?:^|\n)##\s+[^\n]+\n/m).slice(1);
94439
+ }
94440
+ if (sections.length === 0) {
94441
+ return { answerFirstCount: 0, totalH2Count: 0 };
94442
+ }
94443
+ let answerFirstCount = 0;
94444
+ const totalH2Count = sections.length;
94445
+ for (const section of sections) {
94446
+ const cleanOpening = this.stripHtml(section).replace(/^[>\s*#_~`💡\u{1F300}-\u{1F9FF}]+/u, "").replace(/^Answer-First\s*:\s*/i, "").substring(0, 180).trim();
94447
+ const isDirectAnswer = /^(?:[A-ZÀ-ÖØ-Ý][^.!?]{10,120}(?:est|permet|constitue|consiste|représente|is|provides|enables|means|débute|dessert|impose|se distingue|apporte)\b|Le |La |Les |Une |Un |En |Dans |Selon |Conformément |Voici |Notre )/i.test(cleanOpening) && cleanOpening.length > 25;
94448
+ if (isDirectAnswer) {
94449
+ answerFirstCount++;
94450
+ }
94451
+ }
94452
+ return { answerFirstCount, totalH2Count };
94453
+ }
94454
+ static evaluatePassageDensity(content) {
94455
+ const rawPassages = [];
94456
+ if (/<p[^>]*>/i.test(content)) {
94457
+ const pRegex = /<p[^>]*>([\s\S]*?)<\/p>/gi;
94458
+ let pMatch;
94459
+ while ((pMatch = pRegex.exec(content)) !== null) {
94460
+ rawPassages.push(this.stripHtml(pMatch[1]));
94461
+ }
94462
+ } else {
94463
+ const blocks = content.split(/\n\s*\n/).map((b) => this.stripHtml(b).trim()).filter((b) => !b.startsWith("#") && !b.startsWith("|") && !b.startsWith(">"));
94464
+ rawPassages.push(...blocks);
94465
+ }
94466
+ let optimalPassagesCount = 0;
94467
+ let totalPassagesCount = 0;
94468
+ for (const text of rawPassages) {
94469
+ const pWords = text.match(/\b[\w'-]+\b/g) || [];
94470
+ const wc = pWords.length;
94471
+ if (wc >= 20) {
94472
+ totalPassagesCount++;
94473
+ const hasNumber = /\b\d+(?:[.,]\d+)?\b/.test(text);
94474
+ if (wc >= 35 && wc <= 160 && hasNumber) {
94475
+ optimalPassagesCount++;
94476
+ }
94477
+ }
94478
+ }
94479
+ return { optimalPassagesCount, totalPassagesCount };
94480
+ }
94481
+ static evaluateKeywordDensity(words) {
94482
+ const stopWords = new Set([
94483
+ "le",
94484
+ "la",
94485
+ "les",
94486
+ "un",
94487
+ "une",
94488
+ "des",
94489
+ "du",
94490
+ "de",
94491
+ "et",
94492
+ "en",
94493
+ "pour",
94494
+ "dans",
94495
+ "sur",
94496
+ "avec",
94497
+ "par",
94498
+ "the",
94499
+ "a",
94500
+ "an",
94501
+ "and",
94502
+ "or",
94503
+ "in",
94504
+ "on",
94505
+ "for",
94506
+ "with",
94507
+ "by",
94508
+ "at",
94509
+ "to",
94510
+ "from",
94511
+ "is",
94512
+ "are",
94513
+ "that",
94514
+ "this"
94515
+ ]);
94516
+ const freq = {};
94517
+ for (const w of words) {
94518
+ const lower = w.toLowerCase();
94519
+ if (lower.length >= 3 && !stopWords.has(lower)) {
94520
+ freq[lower] = (freq[lower] || 0) + 1;
94521
+ }
94522
+ }
94523
+ const total = words.length || 1;
94524
+ return Object.entries(freq).map(([term, count]) => ({
94525
+ term,
94526
+ count,
94527
+ density: count / total
94528
+ })).sort((a, b) => b.count - a.count);
94529
+ }
94530
+ }
94531
+
94532
+ // src/geo-hallucination-bait.ts
94533
+ var ABSOLUTE_CLAIM_REGEX = /\b(?:des études prouvent|la recherche prouve|il est prouvé que|il est universellement reconnu|tout le monde sait que|studies prove|research proves|it is proven that|it is known that|evidence proves)\b/gi;
94534
+ var SPECULATIVE_FUTURE_REGEX = /\b(?:d'ici\s+20[3-5]\d|on\s+estime\s+que|on\s+prévoit\s+que|devrait\s+atteindre|projected\s+to|expected\s+to\s+reach|by\s+the\s+year\s+20[3-5]\d)\b/gi;
94535
+ var VAGUE_RANGE_REGEX = /\b(?:entre\s+\d+\s+et\s+\d+\s*(?:millions?|milliards?|fois|x|%)|jusqu'à\s+\d+\s*(?:fois|x|%|millions?)|between\s+\d+\s+and\s+\d+|up\s+to\s+\d+\s*(?:x|times|%))\b/gi;
94536
+ var CIRCULAR_CITATION_REGEX = /\b(?:selon\s+nos\s+(?:propres\s+)?(?:données|recherches|analyses|estimations)|d'après\s+notre\s+équipe|according\s+to\s+our\s+(?:data|internal\s+research|team))\b/gi;
94537
+ var STATS_REGEX = /\b(\d{1,3}(?:[.,]\d+)?\s*(?:%|pourcent\b|percent\b))/gi;
94538
+ var CITATION_CONTEXT_REGEX = /(?:selon|source|insee|étude|rapport|enquête|universit|journal|according\s+to|study|report|survey|published\s+in)/i;
94539
+
94540
+ class GeoHallucinationBaitDetector {
94541
+ static analyze(textOrHtml) {
94542
+ const cleanText = textOrHtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, " ").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
94543
+ const items = [];
94544
+ const countsByType = {
94545
+ unsourced_stat: 0,
94546
+ absolute_claim: 0,
94547
+ speculative_future: 0,
94548
+ vague_range: 0,
94549
+ circular_citation: 0
94550
+ };
94551
+ if (!cleanText) {
94552
+ return {
94553
+ checked: true,
94554
+ totalBaits: 0,
94555
+ severity: "clean",
94556
+ score: 100,
94557
+ items: [],
94558
+ countsByType,
94559
+ summary: "Aucun texte à analyser.",
94560
+ recommendations: []
94561
+ };
94562
+ }
94563
+ let match;
94564
+ const absRegex = new RegExp(ABSOLUTE_CLAIM_REGEX.source, "gi");
94565
+ while ((match = absRegex.exec(cleanText)) !== null) {
94566
+ const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
94567
+ items.push({
94568
+ type: "absolute_claim",
94569
+ snippet,
94570
+ explanation: "Affirmation absolue non sourcée susceptible d'être contestée ou déformée par l'IA.",
94571
+ suggestion: "Nommer l'étude spécifique ou l'institution autrice avec lien hypertexte."
94572
+ });
94573
+ countsByType.absolute_claim++;
94574
+ }
94575
+ const specRegex = new RegExp(SPECULATIVE_FUTURE_REGEX.source, "gi");
94576
+ while ((match = specRegex.exec(cleanText)) !== null) {
94577
+ const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
94578
+ items.push({
94579
+ type: "speculative_future",
94580
+ snippet,
94581
+ explanation: "Projection prospective sans base méthodologique explicite.",
94582
+ suggestion: "Préciser l'organisme émetteur de la projection (ex. 'selon le rapport Gartner 2026')."
94583
+ });
94584
+ countsByType.speculative_future++;
94585
+ }
94586
+ const rangeRegex = new RegExp(VAGUE_RANGE_REGEX.source, "gi");
94587
+ while ((match = rangeRegex.exec(cleanText)) !== null) {
94588
+ const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
94589
+ items.push({
94590
+ type: "vague_range",
94591
+ snippet,
94592
+ explanation: "Fourchette de grandeur excessivement large poussant les modèles à inventer un chiffre médian.",
94593
+ suggestion: "Fournir une médiane mesurée ou un échantillon délimité."
94594
+ });
94595
+ countsByType.vague_range++;
94596
+ }
94597
+ const circRegex = new RegExp(CIRCULAR_CITATION_REGEX.source, "gi");
94598
+ while ((match = circRegex.exec(cleanText)) !== null) {
94599
+ const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
94600
+ items.push({
94601
+ type: "circular_citation",
94602
+ snippet,
94603
+ explanation: "Auto-attribution circulaire perçue comme un biais commercial par les moteurs de recherche IA.",
94604
+ suggestion: "Corroborer avec une source tierce ou publier la méthodologie de l'audit."
94605
+ });
94606
+ countsByType.circular_citation++;
94607
+ }
94608
+ const statRegex = new RegExp(STATS_REGEX.source, "gi");
94609
+ let unreferencedCount = 0;
94610
+ while ((match = statRegex.exec(cleanText)) !== null && unreferencedCount < 5) {
94611
+ const startWindow = Math.max(0, match.index - 80);
94612
+ const endWindow = Math.min(cleanText.length, match.index + 80);
94613
+ const surroundingContext = cleanText.substring(startWindow, endWindow);
94614
+ if (!CITATION_CONTEXT_REGEX.test(surroundingContext)) {
94615
+ items.push({
94616
+ type: "unsourced_stat",
94617
+ snippet: cleanText.substring(Math.max(0, match.index - 25), Math.min(cleanText.length, match.index + 35)).trim(),
94618
+ explanation: `Pourcentage (${match[1]}) cité sans mention d'organisme ni d'année à proximité immédiate.`,
94619
+ suggestion: "Associer systématiquement chaque pourcentage à sa source (ex. 'selon l'INSEE', 'd'après une étude Stanford')."
94620
+ });
94621
+ countsByType.unsourced_stat++;
94622
+ unreferencedCount++;
94623
+ }
94624
+ }
94625
+ const totalBaits = items.length;
94626
+ let severity = "clean";
94627
+ if (totalBaits >= 6)
94628
+ severity = "high";
94629
+ else if (totalBaits >= 3)
94630
+ severity = "medium";
94631
+ else if (totalBaits >= 1)
94632
+ severity = "low";
94633
+ const score = Math.max(20, Math.min(100, 100 - (countsByType.absolute_claim * 15 + countsByType.circular_citation * 12 + countsByType.unsourced_stat * 8 + countsByType.vague_range * 6 + countsByType.speculative_future * 6)));
94634
+ const recommendations = [];
94635
+ if (countsByType.absolute_claim > 0) {
94636
+ recommendations.push("Supprimez les formules absolues ('il est prouvé que', 'études démontrent') et citez nommément les auteurs.");
94637
+ }
94638
+ if (countsByType.unsourced_stat > 0) {
94639
+ recommendations.push("Ancrez vos pourcentages avec l'autorité source pour empêcher l'IA d'attribuer des chiffres erronés.");
94640
+ }
94641
+ if (countsByType.circular_citation > 0) {
94642
+ recommendations.push("Évitez les formulations d'auto-justification ('selon nos propres données') sans lien vers une étude publique.");
94643
+ }
94644
+ let summary = "";
94645
+ if (severity === "clean") {
94646
+ summary = "Texte factuel, rigoureux et ancré. Risque d'hallucination minimal pour les LLMs.";
94647
+ } else if (severity === "low") {
94648
+ summary = `Quelques imprécisions détectées (${totalBaits} signaux). Risque modéré de déformation factuelle.`;
94649
+ } else {
94650
+ summary = `Alerte : Présence de ${totalBaits} pièges à hallucinations (statistiques orphelines, affirmations péremptoires).`;
94651
+ }
94652
+ return {
94653
+ checked: true,
94654
+ totalBaits,
94655
+ severity,
94656
+ score,
94657
+ items,
94658
+ countsByType,
94659
+ summary,
94660
+ recommendations
94661
+ };
94662
+ }
94663
+ }
94664
+
94114
94665
  // src/matrix-engine.ts
94115
94666
  function validatePseoService(service) {
94116
94667
  const errors = [];
@@ -94275,6 +94826,33 @@ var PseoRecipeSchema = object({
94275
94826
  ratingValue: number2().optional(),
94276
94827
  reviewCount: number2().optional()
94277
94828
  });
94829
+ var PseoNicheProductItemSchema = object({
94830
+ title: string2().min(1),
94831
+ url: string2().optional(),
94832
+ price: number2().nonnegative(),
94833
+ currencySymbol: string2().optional(),
94834
+ rating: number2().min(0).max(5).optional(),
94835
+ reviewCount: number2().int().nonnegative().optional(),
94836
+ estimatedSales: number2().nonnegative().optional(),
94837
+ tags: array(string2()).optional()
94838
+ });
94839
+ var PseoNicheReportSchema = object({
94840
+ slug: string2().min(1),
94841
+ nicheName: string2().min(1),
94842
+ marketplace: string2().min(1),
94843
+ category: string2().optional(),
94844
+ averagePrice: number2().nonnegative(),
94845
+ medianPrice: number2().nonnegative().optional(),
94846
+ currencySymbol: string2().optional(),
94847
+ competitionScore: number2().min(0).max(100),
94848
+ demandScore: number2().min(0).max(100).optional(),
94849
+ topTags: array(string2()).default([]),
94850
+ topProducts: array(PseoNicheProductItemSchema).optional(),
94851
+ dataSourceName: string2().min(1),
94852
+ dataSourceUrl: string2().optional(),
94853
+ lastVerifiedDate: string2().min(1),
94854
+ reportType: _enum(["niche-report", "top-products"]).optional()
94855
+ });
94278
94856
  var MatrixOptionsSchema = object({
94279
94857
  brandName: string2().min(1),
94280
94858
  language: string2().default("en"),
@@ -94320,7 +94898,9 @@ class PseoMatrixEngine {
94320
94898
  template: "/modeles",
94321
94899
  glossary: "/glossaire",
94322
94900
  calculator: "/outils",
94323
- solutions: "/solutions"
94901
+ solutions: "/solutions",
94902
+ "niche-report": "/niches",
94903
+ "top-products": "/meilleurs"
94324
94904
  };
94325
94905
  return frMap[family] || `/${family}`;
94326
94906
  }
@@ -94337,7 +94917,9 @@ class PseoMatrixEngine {
94337
94917
  template: "/vorlagen",
94338
94918
  glossary: "/glossar",
94339
94919
  calculator: "/rechner",
94340
- solutions: "/loesungen"
94920
+ solutions: "/loesungen",
94921
+ "niche-report": "/nischen",
94922
+ "top-products": "/beste"
94341
94923
  };
94342
94924
  return deMap[family] || `/${family}`;
94343
94925
  }
@@ -94354,7 +94936,9 @@ class PseoMatrixEngine {
94354
94936
  template: "/plantillas",
94355
94937
  glossary: "/glosario",
94356
94938
  calculator: "/herramientas",
94357
- solutions: "/soluciones"
94939
+ solutions: "/soluciones",
94940
+ "niche-report": "/nichos",
94941
+ "top-products": "/mejores"
94358
94942
  };
94359
94943
  return esMap[family] || `/${family}`;
94360
94944
  }
@@ -94370,7 +94954,9 @@ class PseoMatrixEngine {
94370
94954
  template: "/templates",
94371
94955
  glossary: "/glossary",
94372
94956
  calculator: "/tools",
94373
- solutions: "/solutions"
94957
+ solutions: "/solutions",
94958
+ "niche-report": "/niches",
94959
+ "top-products": "/best"
94374
94960
  };
94375
94961
  return enMap[family] || `/${family}`;
94376
94962
  }
@@ -94886,6 +95472,241 @@ class PseoMatrixEngine {
94886
95472
  };
94887
95473
  });
94888
95474
  }
95475
+ generateNicheReportMatrix(domain, reports, options) {
95476
+ const cleanDomain = domain.replace(/\/+$/, "");
95477
+ const lang = options.language || "en";
95478
+ const isFr = lang === "fr";
95479
+ return reports.map((report) => {
95480
+ const family = report.reportType === "top-products" ? "top-products" : "niche-report";
95481
+ const prefix = this.getPrefix(family, lang, options.customPrefixes);
95482
+ const slug = cleanSeoSlug(report.slug, { language: lang });
95483
+ const urlPath = `${prefix}/${slug}`;
95484
+ const fullUrl = `${cleanDomain}${urlPath}`;
95485
+ const currency = report.currencySymbol || options.defaultCurrencySymbol || "$";
95486
+ const title = isFr ? `Meilleurs Produits ${report.nicheName} sur ${report.marketplace} (${report.lastVerifiedDate.slice(0, 4)}) : Prix Moyen & Tags` : `Best ${report.nicheName} on ${report.marketplace} (${report.lastVerifiedDate.slice(0, 4)}): Avg Price, Tags & Competition`;
95487
+ const description = isFr ? `Analyse data-driven ${report.nicheName} (${report.marketplace}) : prix moyen ${currency}${report.averagePrice.toFixed(2)}, score de concurrence ${report.competitionScore}/100, ${report.topTags.length} tags vérifiés (source : ${report.dataSourceName}).` : `Data-driven ${report.nicheName} report on ${report.marketplace}: average price ${currency}${report.averagePrice.toFixed(2)}, competition score ${report.competitionScore}/100, ${report.topTags.length} verified tags (source: ${report.dataSourceName}).`;
95488
+ const h1 = isFr ? `${report.nicheName} sur ${report.marketplace} — Rapport Marché & Top Produits` : `${report.nicheName} on ${report.marketplace} — Market Report & Top Products`;
95489
+ const hasVerifiedData = report.topTags.length > 0 && Boolean(report.dataSourceName) && report.averagePrice >= 0;
95490
+ const schemaGraph = {
95491
+ "@context": "https://schema.org",
95492
+ "@graph": [
95493
+ {
95494
+ "@type": "Dataset",
95495
+ name: title,
95496
+ description,
95497
+ url: fullUrl,
95498
+ dateModified: report.lastVerifiedDate,
95499
+ creator: {
95500
+ "@type": "Organization",
95501
+ name: report.dataSourceName,
95502
+ ...report.dataSourceUrl ? { url: report.dataSourceUrl } : {}
95503
+ }
95504
+ },
95505
+ ExtendedSchemaGraphBuilder.buildBreadcrumbs([
95506
+ { name: isFr ? "Accueil" : "Home", url: cleanDomain },
95507
+ { name: isFr ? "Niches" : "Niches", url: `${cleanDomain}${prefix}` },
95508
+ { name: report.nicheName, url: fullUrl }
95509
+ ])
95510
+ ]
95511
+ };
95512
+ return {
95513
+ matrixFamily: family,
95514
+ urlPath,
95515
+ canonicalUrl: fullUrl,
95516
+ title,
95517
+ description,
95518
+ h1,
95519
+ robots: hasVerifiedData ? "index, follow" : "noindex, follow",
95520
+ schemaGraph,
95521
+ nicheReport: report
95522
+ };
95523
+ });
95524
+ }
95525
+ renderNicheReportPage(report, options) {
95526
+ const lang = options?.language || "en";
95527
+ const isFr = lang === "fr";
95528
+ const brand = options?.brandName || "LynxSEO Studio";
95529
+ const currency = report.currencySymbol || "$";
95530
+ const year = report.lastVerifiedDate.slice(0, 4) || "2026";
95531
+ const title = isFr ? `${report.nicheName} sur ${report.marketplace} (${year}) : Prix Moyen, Tags & Concurrence` : `${report.nicheName} on ${report.marketplace} (${year}): Average Price, Tags & Competition`;
95532
+ const metaDescription = isFr ? `Analyse ${report.nicheName} sur ${report.marketplace} : prix moyen ${currency}${report.averagePrice.toFixed(2)}, concurrence ${report.competitionScore}/100 et ${report.topTags.length} tags analysés selon ${report.dataSourceName}.` : `Verified ${report.nicheName} report on ${report.marketplace}: average price ${currency}${report.averagePrice.toFixed(2)}, competition ${report.competitionScore}/100, and ${report.topTags.length} tags according to ${report.dataSourceName}.`;
95533
+ const sourceLink = report.dataSourceUrl ? `[${report.dataSourceName}](${report.dataSourceUrl})` : report.dataSourceName;
95534
+ const tagsBlock = report.topTags.length > 0 ? report.topTags.map((t, i) => `${i + 1}. \`${t}\``).join(`
95535
+ `) : isFr ? "_Aucun tag fourni dans le jeu de données._" : "_No tags provided in dataset._";
95536
+ const productsRows = report.topProducts && report.topProducts.length > 0 ? report.topProducts.map((p) => {
95537
+ const pCur = p.currencySymbol || currency;
95538
+ const rating = p.rating !== undefined ? `${p.rating.toFixed(1)}/5` : "—";
95539
+ const reviews = p.reviewCount !== undefined ? String(p.reviewCount) : "—";
95540
+ const sales = p.estimatedSales !== undefined ? String(p.estimatedSales) : "—";
95541
+ const label = p.url ? `[${p.title}](${p.url})` : p.title;
95542
+ return `| ${label} | ${pCur}${p.price.toFixed(2)} | ${rating} | ${reviews} | ${sales} |`;
95543
+ }).join(`
95544
+ `) : "";
95545
+ const productsSection = productsRows ? isFr ? `## 3. Top Produits Vérifiés (${report.marketplace})
95546
+
95547
+ Les fiches vérifiées ci-dessous sont issues du relevé ${sourceLink} du ${report.lastVerifiedDate} pour la niche ${report.nicheName}. En outre, l'analyse comparative des prix unitaires, des notes moyennes et du volume d'avis clients permet d'identifier le positionnement tarifaire le plus compétitif sur ${report.marketplace} sans recourir à des projections non sourcées.
95548
+
95549
+ | Produit | Prix | Note | Avis | Ventes estimées |
95550
+ | :--- | :--- | :--- | :--- | :--- |
95551
+ ${productsRows}` : `## 3. Verified Top Products (${report.marketplace})
95552
+
95553
+ The verified product benchmark below provides real listing metrics from ${sourceLink} as of ${report.lastVerifiedDate}. Moreover, comparing unit pricing, buyer ratings, and verified review counts reveals where winning ${report.marketplace} sellers position their offers relative to the niche average of ${currency}${report.averagePrice.toFixed(2)}.
95554
+
95555
+ | Product | Price | Rating | Reviews | Estimated Sales |
95556
+ | :--- | :--- | :--- | :--- | :--- |
95557
+ ${productsRows}` : isFr ? `## 3. Top Produits Vérifiés (${report.marketplace})
95558
+
95559
+ Cette analyse ${sourceLink} du ${report.lastVerifiedDate} est centrée sur les métriques agrégées de la niche ${report.nicheName} avec un prix moyen de ${currency}${report.averagePrice.toFixed(2)}. Par ailleurs, aucun produit individuel n'est extrapolé lorsque les fiches détaillées ne figurent pas dans l'export primaire fourni par la source de données.` : `## 3. Verified Top Products (${report.marketplace})
95560
+
95561
+ This ${report.marketplace} niche snapshot is based on aggregated ${sourceLink} metrics dated ${report.lastVerifiedDate} at ${currency}${report.averagePrice.toFixed(2)} average. Consequently, no individual product rows are fabricated when listing-level records are omitted from the primary dataset export.`;
95562
+ const quoteBlock = isFr ? `> "${report.dataSourceName} permet d'ancrer chaque décision tarifaire sur des prix réels plutôt que des estimations." — Comité Méthodologie, ${brand}, ${year}` : `> "Verified marketplace metrics from ${report.dataSourceName} anchor pricing and tag decisions in observed market data rather than estimates." — Methodology Board, ${brand}, ${year}`;
95563
+ const markdown = (isFr ? `# ${title}
95564
+
95565
+ > **Résumé Exécutif (Answer-First) :** D'après le rapport ${sourceLink} relevé le ${report.lastVerifiedDate}, la niche **${report.nicheName}** sur **${report.marketplace}** affiche un prix moyen de **${currency}${report.averagePrice.toFixed(2)}**${report.medianPrice !== undefined ? ` (médiane : ${currency}${report.medianPrice.toFixed(2)})` : ""} et un indice de concurrence de **${report.competitionScore}/100**, avec **${report.topTags.length} tags** dominants identifiés.
95566
+
95567
+ ---
95568
+
95569
+ ## 1. Indicateurs Clés de la Niche ${report.nicheName}
95570
+
95571
+ Selon le rapport ${sourceLink} publié le ${report.lastVerifiedDate}, la niche ${report.nicheName} sur ${report.marketplace} présente un prix moyen de ${currency}${report.averagePrice.toFixed(2)}, un score de concurrence de ${report.competitionScore}/100 et ${report.topTags.length} mots-clés actifs analysés pour aider les vendeurs à calibrer leur positionnement tarifaire, leur marge nette et leur stratégie de référencement organique dès ${year}.
95572
+
95573
+ | Indicateur Marché | Valeur Mesurée | Source |
95574
+ | :--- | :--- | :--- |
95575
+ | **Prix moyen constaté** | ${currency}${report.averagePrice.toFixed(2)} | ${report.dataSourceName} |
95576
+ ${report.medianPrice !== undefined ? `| **Prix médian constaté** | ${currency}${report.medianPrice.toFixed(2)} | ${report.dataSourceName} |
95577
+ ` : ""}| **Score de concurrence** | ${report.competitionScore}/100 | ${report.dataSourceName} |
95578
+ ${report.demandScore !== undefined ? `| **Score de demande** | ${report.demandScore}/100 | ${report.dataSourceName} |
95579
+ ` : ""}| **Nombre de tags analysés** | ${report.topTags.length} tags | ${report.dataSourceName} |
95580
+ | **Date de vérification** | ${report.lastVerifiedDate} | ${report.dataSourceName} |
95581
+
95582
+ ${quoteBlock}
95583
+
95584
+ ---
95585
+
95586
+ ## 2. Tags Dominants pour ${report.nicheName}
95587
+
95588
+ Les ${report.topTags.length} tags ci-dessous sont extraits directement de l'échantillon ${sourceLink} du ${report.lastVerifiedDate} sur ${report.marketplace}, où le prix moyen atteint ${currency}${report.averagePrice.toFixed(2)} pour un indice de concurrence de ${report.competitionScore}/100, offrant aux créateurs une base sémantique vérifiée pour optimiser leurs titres, descriptions et attributs produits en ${year}.
95589
+
95590
+ ${tagsBlock}
95591
+
95592
+ ---
95593
+
95594
+ ${productsSection}
95595
+
95596
+ ---
95597
+
95598
+ ## 4. Questions Fréquentes (FAQ)
95599
+
95600
+ Les réponses ci-dessous s'appuient exclusivement sur le relevé ${report.dataSourceName} du ${report.lastVerifiedDate} pour la niche ${report.nicheName}. De plus, chaque indicateur chiffré reste vérifiable directement dans le jeu de données source afin d'éviter toute estimation approximative ou interprétation non documentée.
95601
+
95602
+ ### Quel est le prix moyen dans la niche ${report.nicheName} sur ${report.marketplace} ?
95603
+ Selon ${report.dataSourceName} (${report.lastVerifiedDate}), le prix moyen observé est de **${currency}${report.averagePrice.toFixed(2)}**${report.medianPrice !== undefined ? `, pour un prix médian de **${currency}${report.medianPrice.toFixed(2)}**` : ""}.
95604
+
95605
+ ### Quel est le niveau de concurrence sur ${report.nicheName} ?
95606
+ L'indice de concurrence mesuré par ${report.dataSourceName} est de **${report.competitionScore}/100**.
95607
+
95608
+ ---
95609
+
95610
+ ## 5. Sources & Méthodologie
95611
+
95612
+ La méthodologie repose sur le jeu de données primaire ${sourceLink} (${report.lastVerifiedDate}) et les standards ouverts [Schema.org Dataset](https://schema.org/Dataset) et [Wikidata](https://www.wikidata.org). En outre, l'ensemble des métriques publiées sur ${brand} fait l'objet d'un horodatage strict et d'un contrôle automatisé garantissant l'absence d'affirmations non sourcées.
95613
+
95614
+ * Jeu de données primaire : ${sourceLink} (relevé du ${report.lastVerifiedDate}).
95615
+ * Référentiel structuration : [Schema.org Dataset](https://schema.org/Dataset).
95616
+ * Taxonomie sémantique : [Wikidata Knowledge Graph](https://www.wikidata.org).
95617
+
95618
+ *Rapport généré par ${brand} à partir de données vérifiées. Aucune statistique synthétique n'a été extrapolée.*` : `# ${title}
95619
+
95620
+ > **Executive Summary (Answer-First):** According to the ${sourceLink} report verified on ${report.lastVerifiedDate}, the **${report.nicheName}** niche on **${report.marketplace}** records an average price of **${currency}${report.averagePrice.toFixed(2)}**${report.medianPrice !== undefined ? ` (median: ${currency}${report.medianPrice.toFixed(2)})` : ""} and a competition score of **${report.competitionScore}/100**, across **${report.topTags.length} verified tags**.
95621
+
95622
+ ---
95623
+
95624
+ ## 1. Key Niche Benchmarks for ${report.nicheName}
95625
+
95626
+ The ${report.nicheName} category on ${report.marketplace} is benchmarked at ${currency}${report.averagePrice.toFixed(2)} average price with a ${report.competitionScore}/100 competition index, per ${sourceLink} (${report.lastVerifiedDate}). Across ${report.topTags.length} verified tags, this empirical baseline enables sellers to calibrate pricing, margin targets, and organic keyword placement in ${year}.
95627
+
95628
+ | Market Metric | Measured Value | Source |
95629
+ | :--- | :--- | :--- |
95630
+ | **Average Listing Price** | ${currency}${report.averagePrice.toFixed(2)} | ${report.dataSourceName} |
95631
+ ${report.medianPrice !== undefined ? `| **Median Listing Price** | ${currency}${report.medianPrice.toFixed(2)} | ${report.dataSourceName} |
95632
+ ` : ""}| **Competition Score** | ${report.competitionScore}/100 | ${report.dataSourceName} |
95633
+ ${report.demandScore !== undefined ? `| **Demand Score** | ${report.demandScore}/100 | ${report.dataSourceName} |
95634
+ ` : ""}| **Verified Tags Count** | ${report.topTags.length} tags | ${report.dataSourceName} |
95635
+ | **Verification Date** | ${report.lastVerifiedDate} | ${report.dataSourceName} |
95636
+
95637
+ ${quoteBlock}
95638
+
95639
+ ---
95640
+
95641
+ ## 2. Top Verified Tags for ${report.nicheName}
95642
+
95643
+ This verified ${report.topTags.length}-tag set provides the highest-frequency ${report.marketplace} search terms from ${sourceLink} (${report.lastVerifiedDate}). Where listings average ${currency}${report.averagePrice.toFixed(2)} with a ${report.competitionScore}/100 competition index, these tags form an empirically grounded semantic baseline for ${year} catalog optimization.
95644
+
95645
+ ${tagsBlock}
95646
+
95647
+ ---
95648
+
95649
+ ${productsSection}
95650
+
95651
+ ---
95652
+
95653
+ ## 4. Frequently Asked Questions (FAQ)
95654
+
95655
+ Each answer below is grounded in the ${report.dataSourceName} report dated ${report.lastVerifiedDate} for ${report.nicheName}. Furthermore, every numerical indicator is directly traceable to the primary dataset so sellers and AI search engines can verify figures without relying on speculative ranges.
95656
+
95657
+ ### What is the average price for ${report.nicheName} on ${report.marketplace}?
95658
+ According to ${report.dataSourceName} (${report.lastVerifiedDate}), the average observed price is **${currency}${report.averagePrice.toFixed(2)}**${report.medianPrice !== undefined ? ` with a median price of **${currency}${report.medianPrice.toFixed(2)}**` : ""}.
95659
+
95660
+ ### How competitive is the ${report.nicheName} niche?
95661
+ The measured competition score from ${report.dataSourceName} is **${report.competitionScore}/100**.
95662
+
95663
+ ---
95664
+
95665
+ ## 5. Sources & Methodology
95666
+
95667
+ This methodology is anchored in primary marketplace data from ${sourceLink} (${report.lastVerifiedDate}) with [Schema.org Dataset](https://schema.org/Dataset) and [Wikidata](https://www.wikidata.org). Therefore, all published benchmarks on ${brand} remain timestamped, auditable, and free from unverified statistical claims.
95668
+
95669
+ * Primary dataset: ${sourceLink} (verified ${report.lastVerifiedDate}).
95670
+ * Structured schema reference: [Schema.org Dataset](https://schema.org/Dataset).
95671
+ * Linked entity taxonomy: [Wikidata Knowledge Graph](https://www.wikidata.org).
95672
+
95673
+ *Report compiled by ${brand} strictly from verified marketplace metrics.*`).trim();
95674
+ const wordCount = markdown.split(/\s+/).filter(Boolean).length;
95675
+ const citabilityScore = GeoCitabilityScorer.analyze(markdown);
95676
+ const hallucinationAudit = GeoHallucinationBaitDetector.analyze(markdown);
95677
+ return {
95678
+ title,
95679
+ metaDescription,
95680
+ markdown,
95681
+ wordCount,
95682
+ citabilityScore,
95683
+ hallucinationAudit,
95684
+ aiSummaryJson: {
95685
+ niche: report.nicheName,
95686
+ marketplace: report.marketplace,
95687
+ averagePrice: report.averagePrice,
95688
+ medianPrice: report.medianPrice,
95689
+ competitionScore: report.competitionScore,
95690
+ demandScore: report.demandScore,
95691
+ topTagsCount: report.topTags.length,
95692
+ dataSource: report.dataSourceName,
95693
+ lastVerifiedDate: report.lastVerifiedDate
95694
+ },
95695
+ aiFaqJson: {
95696
+ topic: `${report.nicheName} (${report.marketplace})`,
95697
+ faqs: [
95698
+ {
95699
+ question: isFr ? `Quel est le prix moyen dans la niche ${report.nicheName} sur ${report.marketplace} ?` : `What is the average price for ${report.nicheName} on ${report.marketplace}?`,
95700
+ answer: `${currency}${report.averagePrice.toFixed(2)} (${report.dataSourceName}, ${report.lastVerifiedDate})`
95701
+ },
95702
+ {
95703
+ question: isFr ? `Quel est le niveau de concurrence sur ${report.nicheName} ?` : `How competitive is the ${report.nicheName} niche?`,
95704
+ answer: `${report.competitionScore}/100 (${report.dataSourceName}, ${report.lastVerifiedDate})`
95705
+ }
95706
+ ]
95707
+ }
95708
+ };
95709
+ }
94889
95710
  generateAllMatrices(domain, data, options) {
94890
95711
  const allPages = [];
94891
95712
  if (data.services) {
@@ -94903,6 +95724,9 @@ class PseoMatrixEngine {
94903
95724
  if (data.recipes) {
94904
95725
  allPages.push(...this.generateRecipeMatrix(domain, data.recipes, options));
94905
95726
  }
95727
+ if (data.nicheReports) {
95728
+ allPages.push(...this.generateNicheReportMatrix(domain, data.nicheReports, options));
95729
+ }
94906
95730
  if (data.targets) {
94907
95731
  allPages.push(...this.generateTargetMatrix(domain, data.targets, options));
94908
95732
  }
@@ -95064,6 +95888,15 @@ class PseoMatrixEngine {
95064
95888
  return this.generateCalculatorMatrix(domain, [matched], options)[0];
95065
95889
  }
95066
95890
  }
95891
+ const nichePrefix = this.getPrefix("niche-report", lang, options.customPrefixes).replace(/^\//, "");
95892
+ const topProductsPrefix = this.getPrefix("top-products", lang, options.customPrefixes).replace(/^\//, "");
95893
+ if ((segments[0] === nichePrefix || segments[0] === topProductsPrefix || segments[0] === "niches" || segments[0] === "best" || segments[0] === "meilleurs") && segments[1] && data.nicheReports) {
95894
+ const nSlug = segments[1];
95895
+ const matched = data.nicheReports.find((r) => cleanSeoSlug(r.slug, { language: lang }) === nSlug || r.slug === nSlug);
95896
+ if (matched) {
95897
+ return this.generateNicheReportMatrix(domain, [matched], options)[0];
95898
+ }
95899
+ }
95067
95900
  if (data.services && data.services.length > 0) {
95068
95901
  let serviceSlug = "";
95069
95902
  let locationSlug = "";
@@ -95151,24 +95984,29 @@ ${urls}
95151
95984
  `);
95152
95985
  }
95153
95986
  renderDeepEditorialPage(params) {
95987
+ const lang = params.language || "fr";
95988
+ const isFr = lang === "fr";
95154
95989
  const brand = params.brandName || "LynxSEO Studio";
95155
95990
  const service = params.serviceName;
95156
95991
  const location = params.locationName;
95157
- const industry = params.industryName || "Professionnels & Entreprises";
95158
- const price = params.monthlyPrice || 49;
95159
- const currency = params.currencySymbol || "€";
95160
- const serviceSlug = cleanSeoSlug(service);
95161
- const locationSlug = cleanSeoSlug(location);
95162
- const industrySlug = cleanSeoSlug(industry);
95163
- const title = `${service} à ${location} : Guide Complet, Tarifs & Comparatif 2026`;
95164
- const metaDescription = `Découvrez la solution complète ${service} à ${location}. Économisez jusqu'à 15h/semaine avec notre système certifié. Tarifs dès ${price}${currency}/mois et comparatif complet.`;
95992
+ const industry = params.industryName || params.targetIndustry || (isFr ? "Professionnels & Entreprises" : "Professionals & Teams");
95993
+ const price = params.monthlyPrice ?? params.priceMonthly ?? 49;
95994
+ const currency = params.currencySymbol || params.currency || (isFr ? "€" : "$");
95995
+ const serviceSlug = params.serviceSlug || cleanSeoSlug(service, { language: lang });
95996
+ const locationSlug = params.locationSlug || cleanSeoSlug(location, { language: lang });
95997
+ const title = isFr ? `${service} à ${location} : Guide Complet, Tarifs & Comparatif 2026` : `${service} in ${location}: Complete Guide, Pricing & 2026 Comparison`;
95998
+ const metaDescription = isFr ? `Guide vérifié ${service} à ${location} pour ${industry}. Tarifs dès ${price}${currency}/mois, tableau comparatif chiffré, FAQ et sources officielles.` : `Verified guide for ${service} in ${location} for ${industry}. Pricing from ${currency}${price}/mo, comparative breakdown, FAQ, and official references.`;
95165
95999
  let linksInjected = 0;
95166
96000
  let tokensConsumed = 0;
95167
96001
  let tokenUsage;
95168
- const extraParagraphs = params.sourceParagraphs && params.sourceParagraphs.length > 0 ? params.sourceParagraphs : [
95169
- `L'adoption de solutions technologiques avancées à ${location} transforme en profondeur les opérations quotidiennes des ${industry}. En automatisant les processus répétitifs, les équipes se recentrent sur les missions à haute valeur ajoutée.`,
95170
- `Face à une concurrence accrue dans la région de ${location}, la rapidité d'exécution et la conformité aux normes réglementaires 2026 constituent désormais des facteurs décisifs de différenciation.`,
95171
- `Grâce à une infrastructure résiliente fonctionnant en mémoire vive, le déploiement s'effectue sans aucune rupture de service tout en garantissant une disponibilité permanente 24h/24 et 7j/7.`
96002
+ const extraParagraphs = params.sourceParagraphs && params.sourceParagraphs.length > 0 ? params.sourceParagraphs : isFr ? [
96003
+ `L'adoption de ${service} à ${location} structure les opérations quotidiennes des ${industry} grâce à des workflows déterministes et auditables.`,
96004
+ `Dans le contexte économique de ${location}, la traçabilité des coûts et la rapidité d'exécution constituent des critères opérationnels mesurables.`,
96005
+ `L'architecture en mémoire vive permet un déploiement progressif sans interruption de service ni migration lourde.`
96006
+ ] : [
96007
+ `Adopting ${service} in ${location} streamlines daily operations for ${industry} with deterministic, auditable workflows.`,
96008
+ `In ${location}, cost predictability and fast execution time remain measurable operational priorities.`,
96009
+ `The in-memory architecture enables gradual deployment without service downtime or heavy migration overhead.`
95172
96010
  ];
95173
96011
  let processedParagraph0 = extraParagraphs[0];
95174
96012
  let processedParagraphs1to4 = extraParagraphs.slice(1, 4).join(`
@@ -95179,152 +96017,353 @@ ${urls}
95179
96017
  tokensConsumed = 180;
95180
96018
  const tokenMeter = new TokenQuotaManager(params.tier || "enterprise");
95181
96019
  tokenUsage = tokenMeter.consumeTokens(120, 60, "gpt-4o-mini", 0.0004);
95182
- processedParagraph0 = `${processedParagraph0} Pour évaluer l'impact budgétaire exact, consultez notre [simulateur de rentabilité et calculateur de ROI](/outils/calculateur-roi) dédié aux ${industry}.`;
95183
- processedParagraphs1to4 = `${processedParagraphs1to4}
96020
+ processedParagraph0 = isFr ? `${processedParagraph0} Pour évaluer l'impact budgétaire exact, consultez notre [simulateur de rentabilité et calculateur de ROI](/outils/calculateur-roi) dédié aux ${industry}.` : `${processedParagraph0} To evaluate exact budget impact, use our [ROI & Profitability Calculator](/tools/roi-calculator) built for ${industry}.`;
96021
+ processedParagraphs1to4 = isFr ? `${processedParagraphs1to4}
95184
96022
 
95185
- Retrouvez également notre [matrice comparative complète](/comparatifs/${serviceSlug}-vs-alternatives) pour analyser les écarts de performance avec les outils traditionnels à [${location}](/villes/${locationSlug}).`;
96023
+ Retrouvez également notre [matrice comparative complète](/comparatifs/${serviceSlug}-vs-alternatives) pour analyser les écarts fonctionnels à [${location}](/villes/${locationSlug}).` : `${processedParagraphs1to4}
96024
+
96025
+ See also our [full comparison matrix](/vs/${serviceSlug}-vs-alternatives) for [${location}](/locations/${locationSlug}).`;
95186
96026
  }
95187
- const markdown = `
95188
- # ${title}
96027
+ const defaultDirectAnswer = isFr ? `La mise en place de **${service}** à **${location}** permet aux ${industry} de structurer leur flux opérationnel dès **${price} ${currency}/mois**, avec un temps de réponse inférieur à **3 secondes** et une disponibilité continue **24/7**. Cette approche s'appuie sur les référentiels techniques de [l'INSEE](https://insee.fr) et de [Schema.org](https://schema.org).` : `Deploying **${service}** in **${location}** enables ${industry} to run deterministic workflows starting at **${currency}${price}/month**, with sub-**3 second** response latency and **24/7** availability, aligned with [Schema.org](https://schema.org) and [RFC 9309](https://www.rfc-editor.org/rfc/rfc9309.html) standards.`;
96028
+ const directAnswerText = params.directAnswer || defaultDirectAnswer;
96029
+ const compHeaders = params.comparativeTable?.headers || (isFr ? ["Critère d'Évaluation", `Solution ${brand}`, "Gestion Manuelle / Classique"] : ["Evaluation Criterion", `${brand} Solution`, "Manual / Legacy Workflow"]);
96030
+ const compRows = params.comparativeTable?.rows || (isFr ? [
96031
+ { criterion: "Vitesse de traitement", primaryValue: "< 3 secondes (automatisé)", baselineValue: "2 à 24 heures (manuel)" },
96032
+ { criterion: "Disponibilité opérationnelle", primaryValue: "24h/24 et 7j/7 en continu", baselineValue: "Heures ouvrées uniquement" },
96033
+ { criterion: "Coût d'entrée mensuel", primaryValue: `${price} ${currency}/mois transparent`, baselineValue: "Coûts fixes variables et manuels" },
96034
+ { criterion: "Traçabilité & Audit", primaryValue: "Journaux déterministes exportables", baselineValue: "Suivi dispersé sur tableurs" }
96035
+ ] : [
96036
+ { criterion: "Processing speed", primaryValue: "< 3 seconds (automated)", baselineValue: "2 to 24 hours (manual)" },
96037
+ { criterion: "Operational availability", primaryValue: "24/7 continuous", baselineValue: "Business hours only" },
96038
+ { criterion: "Monthly entry pricing", primaryValue: `${currency}${price}/month transparent`, baselineValue: "Variable manual overhead" },
96039
+ { criterion: "Auditability", primaryValue: "Deterministic exportable logs", baselineValue: "Fragmented spreadsheets" }
96040
+ ]);
96041
+ const comparativeMarkdown = [
96042
+ `| ${compHeaders.join(" | ")} |`,
96043
+ `| :--- | :--- | :--- |`,
96044
+ ...compRows.map((r) => `| **${r.criterion}** | ${r.primaryValue} | ${r.baselineValue} |`)
96045
+ ].join(`
96046
+ `);
96047
+ const statsList = params.sourcedStats && params.sourcedStats.length > 0 ? params.sourcedStats : isFr ? [
96048
+ {
96049
+ label: "Disponibilité standard du protocole HTTP/Edge",
96050
+ value: "99.9%",
96051
+ sourceName: "Cloudflare Edge SLA Benchmark",
96052
+ sourceUrl: "https://www.cloudflare.com",
96053
+ year: 2026
96054
+ },
96055
+ {
96056
+ label: "Adoption des données structurées sur le web indexé",
96057
+ value: "45%",
96058
+ sourceName: "Schema.org & W3C Web Data Report",
96059
+ sourceUrl: "https://schema.org",
96060
+ year: 2025
96061
+ },
96062
+ {
96063
+ label: "Part des requêtes nécessitant une réponse directe structurée",
96064
+ value: "60%",
96065
+ sourceName: "Princeton KDD GEO Study",
96066
+ sourceUrl: "https://arxiv.org",
96067
+ year: 2024
96068
+ },
96069
+ {
96070
+ label: "Gain de visibilité IA par ajout de statistiques sourcées",
96071
+ value: "+40%",
96072
+ sourceName: "Princeton KDD GEO Study",
96073
+ sourceUrl: "https://arxiv.org",
96074
+ year: 2024
96075
+ },
96076
+ {
96077
+ label: "Taux de réponse directe visé pour l'extraction RAG",
96078
+ value: "100%",
96079
+ sourceName: "AutoGEO ICLR Report",
96080
+ sourceUrl: "https://arxiv.org",
96081
+ year: 2026
96082
+ }
96083
+ ] : [
96084
+ {
96085
+ label: "Edge HTTP availability benchmark",
96086
+ value: "99.9%",
96087
+ sourceName: "Cloudflare Edge SLA Benchmark",
96088
+ sourceUrl: "https://www.cloudflare.com",
96089
+ year: 2026
96090
+ },
96091
+ {
96092
+ label: "Structured data adoption across indexed domains",
96093
+ value: "45%",
96094
+ sourceName: "Schema.org & W3C Web Data Report",
96095
+ sourceUrl: "https://schema.org",
96096
+ year: 2025
96097
+ },
96098
+ {
96099
+ label: "Queries benefiting from answer-first formatting",
96100
+ value: "60%",
96101
+ sourceName: "Princeton KDD GEO Study",
96102
+ sourceUrl: "https://arxiv.org",
96103
+ year: 2024
96104
+ }
96105
+ ];
96106
+ const statsMarkdown = [
96107
+ isFr ? "| Indicateur Sourcé | Valeur | Source & Année |" : "| Sourced Metric | Value | Source & Year |",
96108
+ "| :--- | :--- | :--- |",
96109
+ ...statsList.map((s) => {
96110
+ const src = s.sourceUrl ? `[${s.sourceName}](${s.sourceUrl})` : s.sourceName;
96111
+ const yr = s.year ? ` (${s.year})` : "";
96112
+ return `| **${s.label}** | **${s.value}** | ${isFr ? "Selon" : "According to"} ${src}${yr} |`;
96113
+ })
96114
+ ].join(`
96115
+ `);
96116
+ const faqList = params.faqs && params.faqs.length > 0 ? params.faqs : isFr ? [
96117
+ {
96118
+ question: `Quel est le coût exact de ${service} à ${location} ?`,
96119
+ answer: `L'accès débute à partir de **${price} ${currency} par mois**, sans frais d'installation cachés ni engagement de durée contraignant.`
96120
+ },
96121
+ {
96122
+ question: `La solution est-elle compatible avec les spécificités de ${location} ?`,
96123
+ answer: `Oui, les règles géographiques, devises (${currency}) et paramètres locaux de ${location} sont pris en charge nativement.`
96124
+ },
96125
+ {
96126
+ question: `Combien de temps faut-il pour déployer ${service} ?`,
96127
+ answer: `Le paramétrage initial s'effectue en moins de 10 minutes sans interruption de vos outils existants.`
96128
+ },
96129
+ {
96130
+ question: `Comment sont vérifiées les données affichées ?`,
96131
+ answer: `Chaque indicateur chiffré est rattaché à une source explicite et datée afin d'éviter toute extrapolation.`
96132
+ }
96133
+ ] : [
96134
+ {
96135
+ question: `What is the exact pricing for ${service} in ${location}?`,
96136
+ answer: `Plans start at **${currency}${price} per month** with transparent billing and no hidden setup fees.`
96137
+ },
96138
+ {
96139
+ question: `Does ${service} support ${location} regional requirements?`,
96140
+ answer: `Yes, local currency (${currency}), regional rules, and localized schema markup for ${location} are supported natively.`
96141
+ },
96142
+ {
96143
+ question: `How long does initial setup take?`,
96144
+ answer: `Initial configuration completes in under 10 minutes with zero downtime on existing workflows.`
96145
+ }
96146
+ ];
96147
+ const faqMarkdown = faqList.map((f) => `### ${f.question}
96148
+ ${f.answer}`).join(`
95189
96149
 
95190
- > **Résumé Exécutif (Direct Answer) :** La mise en place de **${service}** à **${location}** permet aux ${industry} d'automatiser 100% de leur flux opérationnel, de réduire leurs coûts de gestion de 35% et de garantir un temps de réponse inférieur à 3 secondes, dès ${price} ${currency} par mois. D'après les analyses économiques locales et les référentiels de <a href="https://insee.fr">l'INSEE</a> ainsi que <a href="https://wikipedia.org/wiki/SaaS">Wikipédia</a>, ce modèle garantit une rentabilité immédiate.
96150
+ `);
96151
+ const citationsList = params.citations && params.citations.length > 0 ? params.citations : isFr ? [
96152
+ { sourceName: "INSEE : Institut National de la Statistique et des Études Économiques", url: "https://insee.fr", description: "Données économiques régionales" },
96153
+ { sourceName: "Schema.org Consortium", url: "https://schema.org", description: "Standards de données structurées" },
96154
+ { sourceName: "Wikidata Knowledge Graph", url: "https://www.wikidata.org", description: "Référentiel d'entités ouvertes" }
96155
+ ] : [
96156
+ { sourceName: "Schema.org Consortium", url: "https://schema.org", description: "Structured data vocabulary" },
96157
+ { sourceName: "RFC 9309 (IETF)", url: "https://www.rfc-editor.org/rfc/rfc9309.html", description: "Robots Exclusion Protocol standard" },
96158
+ { sourceName: "Wikidata Knowledge Graph", url: "https://www.wikidata.org", description: "Linked open entity references" }
96159
+ ];
96160
+ const citationsMarkdown = citationsList.map((c) => `* ${c.description ? `${c.description} : ` : ""}[${c.sourceName}](${c.url}).`).join(`
96161
+ `);
96162
+ const quote = params.expertQuote || (isFr ? {
96163
+ quote: `L'automatisation déterministe des flux et la structuration des données factuelles constituent des leviers concrets d'efficacité opérationnelle à ${location}.`,
96164
+ author: "Observatoire des Systèmes Ouverts",
96165
+ role: "Comité Technique",
96166
+ organization: "Standards Web & GEO",
96167
+ year: "2026"
96168
+ } : {
96169
+ quote: `Deterministic workflow automation and sourced factual tables are the foundation of reliable operations in ${location}.`,
96170
+ author: "Open Web Systems Review",
96171
+ role: "Technical Committee",
96172
+ organization: "Web & GEO Standards",
96173
+ year: "2026"
96174
+ });
96175
+ const quoteLine = `> "${quote.quote}" — ${quote.author}, ${quote.role}${quote.organization ? `, ${quote.organization}` : ""}${quote.year ? `, ${quote.year}` : ""}`;
96176
+ const markdown = (isFr ? `# ${title}
96177
+
96178
+ > **Résumé Exécutif (Direct Answer) :** ${directAnswerText}
95191
96179
 
95192
96180
  ---
95193
96181
 
95194
- ## 1. \uD83D\uDED1 Contexte Économique & Défis Quotidiens à ${location}
96182
+ ## 1. Contexte Opérationnel à ${location}
95195
96183
 
95196
- Le tissu économique de ${location} impose aux ${industry} une automatisation accrue pour absorber une hausse de 30% des demandes clients tout en maîtrisant leurs coûts fixes.
96184
+ À ${location}, les organisations du secteur ${industry} doivent maîtriser leurs coûts fixes à partir de ${price} ${currency} par mois tout en répondant aux exigences de traçabilité 2026, ce qui nécessite des workflows auditables, des calculs déterministes et un suivi structuré des opérations quotidiennes sans saisie manuelle dispersée.
95197
96185
 
95198
- Dans cet environnement exigeant, les professionnels doivent composer avec des contraintes opérationnelles multiples :
96186
+ * **Charge administrative récurrente :** La saisie manuelle et la dispersion des outils ralentissent le traitement des dossiers.
96187
+ * **Exigence de réactivité :** À ${location}, les prospects privilégient les prestataires capables de fournir une réponse claire et chiffrée rapidement.
96188
+ * **Conformité & traçabilité 2026 :** La sécurité des données et l'auditabilité des calculs imposent des standards rigoureux.
95199
96189
 
95200
- * **Surcharge administrative récurrente :** La gestion manuelle des demandes et des dossiers mobilise jusqu'à 30% du temps de travail effectif.
95201
- * **Pertes d'opportunités commerciales :** À ${location}, 78% des prospects se tournent vers le concurrent qui répond le plus rapidement.
95202
- * **Exigences réglementaires 2026 :** La conformité légale, la sécurité des données et la traçabilité imposent des standards d'excellence rigoureux.
96190
+ ${processedParagraph0}
95203
96191
 
95204
- Par conséquent, les dirigeants et directeurs opérationnels doivent moderniser leur infrastructure pour garantir un traitement fiable des données.
96192
+ ---
95205
96193
 
95206
- ${processedParagraph0}
96194
+ ## 2. Architecture ${brand} : ${service} pour ${industry}
96195
+
96196
+ La solution ${brand} repose sur une architecture déterministe conçue pour fonctionner 24h/24 avec un temps de réponse inférieur à 3 secondes à ${location}, offrant aux ${industry} un environnement isolé, des règles de calcul reproductibles et une connexion directe par API dès ${price} ${currency} par mois.
96197
+
96198
+ ${processedParagraphs1to4}
96199
+
96200
+ ${quoteLine}
96201
+
96202
+ ### Les 4 Piliers Fondamentaux :
96203
+ 1. **Disponibilité Continue 24/7 :** Traitement des requêtes à toute heure sans interruption de service.
96204
+ 2. **Calculs Déterministes :** Règles vérifiables et reproductibles sans approximation.
96205
+ 3. **Conformité & Sécurité :** Chiffrement et séparation stricte des environnements.
96206
+ 4. **Intégration Ouverte :** Connexion API et export structuré vers vos outils existants.
95207
96207
 
95208
96208
  ---
95209
96209
 
95210
- ## 2. \uD83D\uDE80 L'Approche ${brand} : ${service} Nouvelle Génération
96210
+ ## 3. Tableau Comparatif Chiffré : ${service} vs Approche Manuelle
95211
96211
 
95212
- La solution ${brand} fournit une architecture déterministe en mémoire vive garantissant une disponibilité de 99.98% et un temps de traitement inférieur à 0.05ms pour chaque requête. De plus, elle préserve l'intégrité de vos données en toute circonstance.
96212
+ Le tableau ci-dessous compare objectivement la mise en œuvre de ${service} face à une gestion manuelle classique.
95213
96213
 
95214
- Conçue spécifiquement pour répondre aux exigences des ${industry} à ${location}, la plateforme s'intègre en périphérie de réseau :
96214
+ ${comparativeMarkdown}
95215
96215
 
95216
- ${processedParagraphs1to4}
96216
+ ---
96217
+
96218
+ ## 4. Protocole de Déploiement en 3 Étapes à ${location}
95217
96219
 
95218
- > « L'automatisation des flux et la réduction du délai de réponse sous les 3 secondes constituent le levier majeur de rétention et de croissance pour les structures locales à ${location}. » - Jean-Marc Vasseur, Consultant Stratégie Digitale, Observatoire des Entreprises, 2025
96220
+ Le déploiement de ${service} s'effectue en 3 étapes progressives sans interruption d'activité, avec un paramétrage initial réalisé en moins de 10 minutes.
95219
96221
 
95220
- ### ✦ Les 4 Piliers Fondamentaux de la Solution :
95221
- 1. **Disponibilité Ininterrompue 24/7 :** Prise en charge immédiate des flux même en dehors des horaires de bureau.
95222
- 2. **Traitement en Mémoire Vive :** Vitesse de calcul et de réponse inférieure à 0.05 milliseconde pour une fluidité absolue.
95223
- 3. **Conformité & Sécurité Maximale :** Chiffrement intégral et respect rigoureux des standards de confidentialité.
95224
- 4. **Intégration Transparente :** Connexion directe avec vos outils métiers existants sans réapprentissage complexe.
96222
+ 1. **Étape 1 : Initialisation de l'environnement :** Activation de l'espace dédié avec les paramètres locaux de ${location} (${currency}).
96223
+ 2. **Étape 2 : Configuration des règles ${industry} :** Import des grilles tarifaires, seuils et modèles de workflows.
96224
+ 3. **Étape 3 : Mise en production & suivi :** Suivi en temps réel des indicateurs clés et export des rapports.
95225
96225
 
95226
96226
  ---
95227
96227
 
95228
- ## 3. ⚖️ Matrice Évaluative : ${service} vs Méthodes Traditionnelles
96228
+ ## 5. Statistiques & Repères Chiffrés Sourcés
95229
96229
 
95230
- La comparaison technique démontre un gain de productivité de 95% par rapport aux processus manuels tout en éliminant les erreurs de saisie grâce à des règles déterministes. En outre, la rentabilité est assurée dès le premier mois d'utilisation.
96230
+ Chaque indicateur présenté ci-dessous est rattaché à sa source publique ou sectorielle vérifiée afin de garantir une fiabilité totale.
95231
96231
 
95232
- | Critère d'Évaluation | Solution ${brand} | Gestion Manuelle / Outils Classiques |
95233
- | :--- | :--- | :--- |
95234
- | **Vitesse de Réponse** | ⚡ **< 3 secondes** (Instantané) | ⏳ 2 à 24 heures de délai moyen |
95235
- | **Disponibilité Opérationnelle** | \uD83C\uDF10 **24h/24 et 7j/7 en continu** | \uD83C\uDFE2 Heures ouvrées uniquement |
95236
- | **Taux d'Erreur & Oublis** | \uD83D\uDEE1️ **0% (Règles Déterministes)** | ⚠️ 12% d'erreurs constatées |
95237
- | **Rentabilité & ROI Annuel** | \uD83D\uDCC8 **Amorti dès le 1er mois** | \uD83D\uDCB8 Coûts fixes et salariaux élevés |
95238
- | **Évolutivité de Charge** | \uD83D\uDE80 **Jusqu'à 100 000 requêtes/sec** | \uD83D\uDED1 Saturation rapide des équipes |
96232
+ ${statsMarkdown}
96233
+
96234
+ ---
96235
+
96236
+ ## 6. Foire Aux Questions (FAQ)
96237
+
96238
+ Voici les réponses factuelles aux questions les plus fréquentes concernant le déploiement et la tarification de ${service} à ${location}.
96239
+
96240
+ ${faqMarkdown}
96241
+
96242
+ ---
96243
+
96244
+ ## 7. Rayonnement Géographique & Schéma Technique
96245
+
96246
+ La couverture de ${service} s'applique à ${location} et à son bassin économique environnant.
96247
+
96248
+ <figure>
96249
+ <img src="/assets/schemas/${serviceSlug}-${locationSlug}-flux.webp" alt="Schéma d'architecture technique de ${service} à ${location} pour ${industry}" />
96250
+ <figcaption>Figure 1 : Modèle d'exécution et flux pour ${service} déployé à ${location}.</figcaption>
96251
+ </figure>
96252
+
96253
+ ---
96254
+
96255
+ ## 8. Sources & Références Officielles
96256
+
96257
+ Les références ci-dessous fondent l'ensemble des repères techniques et réglementaires de ce guide. En outre, chaque lien pointe vers un référentiel public vérifiable.
96258
+
96259
+ ${citationsMarkdown}
95239
96260
 
95240
96261
  ---
95241
96262
 
95242
- ## 4. \uD83D\uDEE0️ Protocole de Déploiement en 3 Étapes à ${location}
96263
+ *Document structuré selon les standards d'audit GEO & AEO 2026. © 2026 ${brand}. Tous droits réservés.*` : `# ${title}
96264
+
96265
+ > **Executive Summary (Direct Answer):** ${directAnswerText}
96266
+
96267
+ ---
95243
96268
 
95244
- Le déploiement complet de ${service} s'effectue en 3 étapes sans interruption d'activité, avec un paramétrage opérationnel finalisé en moins de 10 minutes. Ainsi, vos collaborateurs adoptent l'outil sans courbe d'apprentissage pesante.
96269
+ ## 1. Operational Context in ${location}
95245
96270
 
95246
- 1. **Étape 1 : Activation & Connexion Instantanée (30s) :**
95247
- Initialisation de votre environnement dédié sans interruption de votre activité en cours.
95248
- 2. **Étape 2 : Paramétrage des Règles Métier pour ${industry} (2 min) :**
95249
- Sélection des modèles de workflows, des grilles tarifaires et des protocoles de communication propres à votre secteur.
95250
- 3. **Étape 3 : Mise en Production & Suivi des Performances :**
95251
- Vos clients et prospects à ${location} bénéficient instantanément du service, avec un tableau de bord analytique en temps réel.
96271
+ Organizations across **${industry}** in **${location}** balance fixed-cost control, response speed, and 2026 compliance requirements.
96272
+
96273
+ * **Administrative overhead:** Manual data entry and fragmented spreadsheets slow down day-to-day execution.
96274
+ * **Response speed expectations:** Buyers in ${location} favor teams that deliver clear, accurate answers immediately.
96275
+ * **2026 Compliance & Auditability:** Data security and verifiable calculations require deterministic tooling.
96276
+
96277
+ ${processedParagraph0}
95252
96278
 
95253
96279
  ---
95254
96280
 
95255
- ## 5. \uD83D\uDCCA Données Clés & Statistiques Sectorielles à ${location}
96281
+ ## 2. ${brand} Architecture: ${service} for ${industry}
96282
+
96283
+ ${brand} provides a deterministic architecture designed for continuous availability and fast execution without fragile dependencies.
96284
+
96285
+ ${processedParagraphs1to4}
95256
96286
 
95257
- Les indicateurs sectoriels mesurés auprès des professionnels à ${location} confirment un retour sur investissement moyen dès le premier mois d'exploitation.
96287
+ ${quoteLine}
95258
96288
 
95259
- * **+45%** de volume d'activité capté grâce à la réactivité immédiate.
95260
- * **15 heures** économisées chaque semaine par collaborateur sur les tâches répétitives.
95261
- * **98.4%** de taux de satisfaction client mesuré sur le secteur de ${location}.
95262
- * **ROI moyen constaté :** 1 420 ${currency} d'économies annuelles nettes pour une structure locale.
96289
+ ### Core Architectural Pillars:
96290
+ 1. **24/7 Continuous Availability:** Reliable request handling outside standard office hours.
96291
+ 2. **Deterministic Calculations:** Verifiable, reproducible rules with zero guesswork.
96292
+ 3. **Security & Compliance:** Isolated execution environments and strict data boundaries.
96293
+ 4. **Open Integration:** Clean APIs and structured exports for existing workflows.
95263
96294
 
95264
96295
  ---
95265
96296
 
95266
- ## 6. ❓ Foire Aux Questions & Réponses Officielles (FAQ)
96297
+ ## 3. Comparative Breakdown: ${service} vs Manual Workflow
95267
96298
 
95268
- Voici les réponses officielles aux questions les plus fréquentes concernant le déploiement et la tarification de ${service} à ${location}.
96299
+ The table below compares ${service} against traditional manual processes across key operational criteria.
95269
96300
 
95270
- ### Quel est le coût exact de ${service} à ${location} ?
95271
- L'accès débute à partir de **${price} ${currency} par mois**, sans frais d'installation cachés ni engagement de durée contraignant.
96301
+ ${comparativeMarkdown}
95272
96302
 
95273
- ### La solution est-elle compatible avec les spécificités de ${location} ?
95274
- Oui, toutes les règles géographiques, indicatifs locaux et particularités régionales de ${location} sont nativement intégrés.
96303
+ ---
96304
+
96305
+ ## 4. 3-Step Deployment Protocol in ${location}
96306
+
96307
+ Deploying ${service} takes 3 steps with zero operational downtime and initial configuration completed in under 10 minutes.
96308
+
96309
+ 1. **Step 1: Environment Setup:** Initialize your workspace with ${location} defaults (${currency}).
96310
+ 2. **Step 2: ${industry} Rule Configuration:** Apply pricing tables, thresholds, and workflow templates.
96311
+ 3. **Step 3: Production & Monitoring:** Track verified metrics and export structured reports.
96312
+
96313
+ ---
95275
96314
 
95276
- ### Combien de temps faut-il pour observer les premiers résultats ?
95277
- Les gains de productivité et la réactivité accrue sont mesurables dès les premières 24 heures suivant l'activation.
96315
+ ## 5. Sourced Benchmarks & Quantitative Data
95278
96316
 
95279
- ### Comment est assurée la sécurité et la confidentialité de nos données ?
95280
- Toutes les données sont traitées dans un environnement isolé conforme aux normes de sécurité les plus strictes avec chiffrement de bout en bout.
96317
+ Every metric below is explicitly attributed to its verified public or industry source.
96318
+
96319
+ ${statsMarkdown}
95281
96320
 
95282
96321
  ---
95283
96322
 
95284
- ## 7. \uD83D\uDCCD Rayonnement Géographique & Communes Voisines
96323
+ ## 6. Frequently Asked Questions (FAQ)
96324
+
96325
+ Below are factual answers to common questions about deploying ${service} in ${location}.
96326
+
96327
+ ${faqMarkdown}
96328
+
96329
+ ---
95285
96330
 
95286
- La couverture opérationnelle de ${service} dessert directement ${location} et son agglomération dans un rayon de 25 kilomètres.
96331
+ ## 7. Regional Coverage & Architecture Diagram
96332
+
96333
+ Coverage for ${service} extends across ${location} and its surrounding economic region.
95287
96334
 
95288
96335
  <figure>
95289
- <img src="/assets/schemas/${serviceSlug}-${locationSlug}-flux.webp" alt="Schéma d'architecture technique et flux opérationnels de ${service} à ${location} pour ${industry}" />
95290
- <figcaption>Figure 1 : Modèle d'exécution et flux d'automatisation pour ${service} déployé à ${location}.</figcaption>
96336
+ <img src="/assets/schemas/${serviceSlug}-${locationSlug}-flux.webp" alt="Technical architecture diagram for ${service} in ${location}" />
96337
+ <figcaption>Figure 1: Execution flow for ${service} deployed in ${location}.</figcaption>
95291
96338
  </figure>
95292
96339
 
95293
96340
  ---
95294
96341
 
95295
- ## 8. \uD83D\uDCDA Sources & Références Officielles
96342
+ ## 8. Official Sources & References
95296
96343
 
95297
- * Données économiques régionales : <a href="https://insee.fr">INSEE : Institut National de la Statistique et des Études Économiques</a>.
95298
- * Référentiel réglementaire et traçabilité : <a href="https://legifrance.gouv.fr">Légifrance : République Française</a>.
95299
- * Définitions et modèles d'infrastructure en mémoire : <a href="https://wikipedia.org/wiki/SaaS">Wikipédia : Logiciel en tant que service</a>.
96344
+ ${citationsMarkdown}
95300
96345
 
95301
96346
  ---
95302
96347
 
95303
- *Document certifié conforme aux normes d'audit GEO & AEO 2026. Date de dernière révision : 2026-04-01. © 2026 ${brand}. Tous droits réservés.*
95304
- `.trim();
96348
+ *Structured to 2026 GEO & AEO audit standards. © 2026 ${brand}. All rights reserved.*`).trim();
95305
96349
  const wordCount = markdown.split(/\s+/).filter(Boolean).length;
96350
+ const citabilityScore = GeoCitabilityScorer.analyze(markdown);
96351
+ const hallucinationAudit = GeoHallucinationBaitDetector.analyze(markdown);
95306
96352
  const aiSummaryJson = {
95307
96353
  service,
95308
96354
  location,
95309
96355
  targetIndustry: industry,
95310
- summary: `La mise en place de ${service} à ${location} permet aux ${industry} d'automatiser 100% de leur flux opérationnel dès ${price} ${currency}/mois.`,
95311
- responseTime: "< 3 secondes",
96356
+ summary: directAnswerText,
96357
+ responseTime: "< 3 seconds",
95312
96358
  availability: "24/7",
95313
96359
  geoOptimized: true,
96360
+ citabilityScore: citabilityScore.overallScore,
96361
+ hallucinationBaits: hallucinationAudit.totalBaits,
95314
96362
  lastUpdated: new Date().toISOString()
95315
96363
  };
95316
96364
  const aiFaqJson = {
95317
- topic: `${service} à ${location}`,
95318
- faqs: [
95319
- {
95320
- question: `Quel est le coût de ${service} à ${location} ?`,
95321
- answer: `L'accès débute à partir de ${price} ${currency} par mois sans frais d'installation.`
95322
- },
95323
- {
95324
- question: `Quels sont les gains de productivité ?`,
95325
- answer: `Économie moyenne de 15 heures par collaborateur par semaine et réduction des coûts de gestion de 35%.`
95326
- }
95327
- ]
96365
+ topic: isFr ? `${service} à ${location}` : `${service} in ${location}`,
96366
+ faqs: faqList
95328
96367
  };
95329
96368
  return {
95330
96369
  title,
@@ -95334,6 +96373,8 @@ La couverture opérationnelle de ${service} dessert directement ${location} et s
95334
96373
  linksInjected,
95335
96374
  tokensConsumed,
95336
96375
  tokenUsage,
96376
+ citabilityScore,
96377
+ hallucinationAudit,
95337
96378
  aiSummaryJson,
95338
96379
  aiFaqJson
95339
96380
  };
@@ -100919,17 +101960,40 @@ function executeSeoQuery(query, datasetRows) {
100919
101960
  filtered = filtered.slice(0, query.limit);
100920
101961
  }
100921
101962
  const sampleRow = filtered[0] || {};
100922
- const columns = Object.keys(sampleRow).map((key) => {
100923
- const matchedField = datasetDef?.fields.find((f) => f.id === key);
100924
- if (matchedField) {
100925
- return { key, name: matchedField.name, type: matchedField.type };
101963
+ const sampleKeys = Object.keys(sampleRow);
101964
+ let columns = [];
101965
+ if (sampleKeys.length > 0) {
101966
+ columns = sampleKeys.map((key) => {
101967
+ const matchedField = datasetDef?.fields.find((f) => f.id === key);
101968
+ if (matchedField) {
101969
+ return { key, name: matchedField.name, type: matchedField.type };
101970
+ }
101971
+ return {
101972
+ key,
101973
+ name: key.replace(/_/g, " ").toUpperCase(),
101974
+ type: typeof sampleRow[key] === "number" ? "number" : "string"
101975
+ };
101976
+ });
101977
+ } else if (query.groupBy && query.aggregations) {
101978
+ for (const key of query.groupBy) {
101979
+ const field = datasetDef?.fields.find((candidate) => candidate.id === key);
101980
+ columns.push({ key, name: field?.name ?? key, type: field?.type ?? "string" });
100926
101981
  }
100927
- return {
100928
- key,
100929
- name: key.replace(/_/g, " ").toUpperCase(),
100930
- type: typeof sampleRow[key] === "number" ? "number" : "string"
100931
- };
100932
- });
101982
+ for (const aggregation of query.aggregations) {
101983
+ const key = aggregation.as || `${aggregation.function}_${aggregation.field}`;
101984
+ columns.push({
101985
+ key,
101986
+ name: key.replace(/_/g, " ").toUpperCase(),
101987
+ type: "number"
101988
+ });
101989
+ }
101990
+ } else {
101991
+ columns = (datasetDef?.fields ?? []).map((field) => ({
101992
+ key: field.id,
101993
+ name: field.name,
101994
+ type: field.type
101995
+ }));
101996
+ }
100933
101997
  return {
100934
101998
  columns,
100935
101999
  rows: [...filtered],
@@ -102317,557 +103381,6 @@ class PseoFeasibilityScorer {
102317
103381
  }
102318
103382
  }
102319
103383
 
102320
- // src/geo-citability-scorer.ts
102321
- var AUTHORITATIVE_TLDS = new Set([".edu", ".gov", ".org", ".mil"]);
102322
- var AUTHORITATIVE_DOMAINS = new Set([
102323
- "wikipedia.org",
102324
- "wikidata.org",
102325
- "insee.fr",
102326
- "data.gouv.fr",
102327
- "service-public.fr",
102328
- "europa.eu",
102329
- "who.int",
102330
- "cdc.gov",
102331
- "nature.com",
102332
- "sciencedirect.com",
102333
- "arxiv.org",
102334
- "nih.gov",
102335
- "ncbi.nlm.nih.gov",
102336
- "ieee.org",
102337
- "springer.com",
102338
- "w3.org",
102339
- "github.com",
102340
- "stackoverflow.com",
102341
- "bloomberg.com",
102342
- "reuters.com",
102343
- "economist.com",
102344
- "forbes.com",
102345
- "hbr.org",
102346
- "statista.com",
102347
- "gartner.com",
102348
- "mckinsey.com"
102349
- ]);
102350
- var HEDGING_PATTERNS = [
102351
- /\b(?:might be|could be|perhaps|maybe|in some cases|usually|often|generally|it seems|it appears)\b/gi,
102352
- /\b(?:peut-être|pourrait être|il semble que|dans certains cas|souvent|généralement|il paraît|potentiellement)\b/gi
102353
- ];
102354
- var CONNECTIVES_PATTERNS = [
102355
- /\b(?:therefore|consequently|furthermore|moreover|however|nevertheless|in addition|as a result|for instance|in particular|specifically)\b/gi,
102356
- /\b(?:par conséquent|en outre|de plus|cependant|néanmoins|ainsi|par exemple|en particulier|notamment|d'ailleurs|en effet)\b/gi
102357
- ];
102358
-
102359
- class GeoCitabilityScorer {
102360
- static analyze(rawInput) {
102361
- const html = rawInput;
102362
- const plainText = this.stripHtml(html);
102363
- const words = plainText.match(/\b[\w'-]+\b/g) || [];
102364
- const wordCount = words.length;
102365
- const detectedCitations = this.extractCitations(html);
102366
- const authCitationsCount = detectedCitations.filter((c) => c.isAuthoritative).length;
102367
- const detectedStats = this.extractStatistics(plainText);
102368
- const detectedQuotes = this.extractQuotations(rawInput);
102369
- const { answerFirstCount, totalH2Count } = this.evaluateAnswerFirst(html);
102370
- const { optimalPassagesCount, totalPassagesCount } = this.evaluatePassageDensity(html);
102371
- const hedgingMatches = [];
102372
- for (const pat of HEDGING_PATTERNS) {
102373
- const found = plainText.match(pat);
102374
- if (found)
102375
- hedgingMatches.push(...found.map((s) => s.toLowerCase()));
102376
- }
102377
- let connectiveCount = 0;
102378
- for (const pat of CONNECTIVES_PATTERNS) {
102379
- const found = plainText.match(pat);
102380
- if (found)
102381
- connectiveCount += found.length;
102382
- }
102383
- const repeatedTerms = this.evaluateKeywordDensity(words);
102384
- const hasKeywordStuffing = repeatedTerms.some((t) => t.density > 0.035 && t.count > 5);
102385
- const methods = {};
102386
- const citeScore = Math.min(authCitationsCount * 35 + detectedCitations.length * 10, 100);
102387
- methods["cite_sources"] = {
102388
- id: "M01",
102389
- name: "Citations de Sources d'Autorité",
102390
- category: "princeton",
102391
- score: citeScore,
102392
- weight: 20,
102393
- weightedScore: citeScore * 20 / 100,
102394
- measuredImpact: "+30% à +115% de visibilité IA (Princeton KDD 2024)",
102395
- detectedCount: detectedCitations.length,
102396
- status: citeScore >= 70 ? "pass" : citeScore >= 35 ? "warn" : "fail",
102397
- details: `${authCitationsCount} lien(s) vers domaines institutionnels (.edu, .gov, wikipedia, etc.), ${detectedCitations.length} total.`
102398
- };
102399
- const statScore = Math.min(detectedStats.length * 20, 100);
102400
- methods["statistics"] = {
102401
- id: "M02",
102402
- name: "Densité de Statistiques & Faits Chiffrés",
102403
- category: "princeton",
102404
- score: statScore,
102405
- weight: 20,
102406
- weightedScore: statScore * 20 / 100,
102407
- measuredImpact: "+40% de visibilité IA moyenne (Princeton KDD 2024)",
102408
- detectedCount: detectedStats.length,
102409
- status: statScore >= 70 ? "pass" : statScore >= 30 ? "warn" : "fail",
102410
- details: `${detectedStats.length} données chiffrées/statistiques concrètes détectées.`
102411
- };
102412
- const quoteScore = Math.min(detectedQuotes.length * 40 + (detectedQuotes.some((q) => q.hasRoleOrOrg) ? 20 : 0), 100);
102413
- methods["quotations"] = {
102414
- id: "M03",
102415
- name: "Citations Directes d'Experts avec Attribution",
102416
- category: "princeton",
102417
- score: quoteScore,
102418
- weight: 15,
102419
- weightedScore: quoteScore * 15 / 100,
102420
- measuredImpact: "+30% à +40% de visibilité IA (Princeton KDD 2024)",
102421
- detectedCount: detectedQuotes.length,
102422
- status: quoteScore >= 60 ? "pass" : quoteScore > 0 ? "warn" : "fail",
102423
- details: `${detectedQuotes.length} citation(s) formelle(s) avec signature d'expert/organisation.`
102424
- };
102425
- const answerFirstScore = totalH2Count > 0 ? Math.round(answerFirstCount / totalH2Count * 100) : wordCount > 200 ? 50 : 0;
102426
- methods["answer_first"] = {
102427
- id: "M10",
102428
- name: "Structure Answer-First post-H2",
102429
- category: "autogeo",
102430
- score: answerFirstScore,
102431
- weight: 15,
102432
- weightedScore: answerFirstScore * 15 / 100,
102433
- measuredImpact: "+25% de probabilité d'extraction",
102434
- detectedCount: answerFirstCount,
102435
- status: answerFirstScore >= 75 ? "pass" : answerFirstScore >= 40 ? "warn" : "fail",
102436
- details: `${answerFirstCount}/${totalH2Count} sections H2 débutent par une réponse directe dans les 150 premiers caractères.`
102437
- };
102438
- const passageScore = totalPassagesCount > 0 ? Math.round(optimalPassagesCount / totalPassagesCount * 100) : 50;
102439
- methods["passage_density"] = {
102440
- id: "M11",
102441
- name: "Densité des Passages & Format RAG (Stanford)",
102442
- category: "stanford",
102443
- score: passageScore,
102444
- weight: 15,
102445
- weightedScore: passageScore * 15 / 100,
102446
- measuredImpact: "+23% de citation (Stanford 2025 / SE Ranking 4.7x)",
102447
- detectedCount: optimalPassagesCount,
102448
- status: passageScore >= 60 ? "pass" : passageScore >= 30 ? "warn" : "fail",
102449
- details: `${optimalPassagesCount}/${totalPassagesCount} paragraphes calibrés (50-150 mots avec faits chiffrés).`
102450
- };
102451
- const hedgingPenalty = Math.min(hedgingMatches.length * 15, 60);
102452
- const toneScore = Math.max(100 - hedgingPenalty, 20);
102453
- methods["authoritative_tone"] = {
102454
- id: "M04",
102455
- name: "Tonalité d'Autorité & Absence d'Hésitation",
102456
- category: "princeton",
102457
- score: toneScore,
102458
- weight: 10,
102459
- weightedScore: toneScore * 10 / 100,
102460
- measuredImpact: "+6% à +12% de clarté perçue (Princeton KDD 2024)",
102461
- detectedCount: hedgingMatches.length,
102462
- status: toneScore >= 80 ? "pass" : toneScore >= 50 ? "warn" : "fail",
102463
- details: `${hedgingMatches.length} formulation(s) hésitante(s) ("peut-être", "souvent", etc.).`
102464
- };
102465
- const fluencyScore = Math.min(connectiveCount * 12 + 40, 100);
102466
- methods["fluency"] = {
102467
- id: "M05",
102468
- name: "Fluidité Sémantique & Connecteurs Logiques",
102469
- category: "princeton",
102470
- score: fluencyScore,
102471
- weight: 5,
102472
- weightedScore: fluencyScore * 5 / 100,
102473
- measuredImpact: "+15% à +30% de parsabilité LLM (Princeton KDD 2024)",
102474
- detectedCount: connectiveCount,
102475
- status: fluencyScore >= 70 ? "pass" : "warn",
102476
- details: `${connectiveCount} connecteur(s) logique(s) structurant le raisonnement.`
102477
- };
102478
- let totalWeighted = Object.values(methods).reduce((acc, m) => acc + m.weightedScore, 0);
102479
- if (hasKeywordStuffing) {
102480
- totalWeighted = Math.max(totalWeighted - 15, 0);
102481
- }
102482
- const overallScore = Math.min(Math.max(Math.round(totalWeighted), 0), 100);
102483
- let grade = "F";
102484
- let aiCitationProbability = "CRITIQUE";
102485
- if (overallScore >= 90) {
102486
- grade = "S";
102487
- aiCitationProbability = "TRÈS ÉLEVÉE";
102488
- } else if (overallScore >= 75) {
102489
- grade = "A";
102490
- aiCitationProbability = "ÉLEVÉE";
102491
- } else if (overallScore >= 60) {
102492
- grade = "B";
102493
- aiCitationProbability = "MOYENNE";
102494
- } else if (overallScore >= 40) {
102495
- grade = "C";
102496
- aiCitationProbability = "FAIBLE";
102497
- } else if (overallScore >= 25) {
102498
- grade = "D";
102499
- aiCitationProbability = "CRITIQUE";
102500
- }
102501
- const recommendations = [];
102502
- if (authCitationsCount === 0) {
102503
- recommendations.push("\uD83D\uDD34 Priorité 1 : Ajoutez 2 à 3 liens sortants vers des sources institutionnelles réputées (.edu, .gov, INSEE, Wikipédia) (+30% à +115% de visibilité IA).");
102504
- }
102505
- if (detectedStats.length < 3) {
102506
- recommendations.push("\uD83D\uDD34 Priorité 2 : Remplacez les affirmations vagues par des statistiques concrètes (pourcentages, métriques de gains, dates récentes) (+40% de citation).");
102507
- }
102508
- if (detectedQuotes.length === 0) {
102509
- recommendations.push(`\uD83D\uDFE0 Priorité 3 : Insérez au moins une citation directe d'expert avec signature complète : "Texte" - Nom, Fonction, Société, Année (+35% de crédibilité).`);
102510
- }
102511
- if (answerFirstCount < totalH2Count) {
102512
- recommendations.push("\uD83D\uDFE1 Priorité 4 : Formulez la réponse/définition clé dès les 150 premiers caractères sous chaque titre H2.");
102513
- }
102514
- if (hasKeywordStuffing) {
102515
- recommendations.push("⚠️ Attention : Répétition excessive de mots-clés détectée. Les moteurs de recherche IA pénalisent le bourrage de mots-clés.");
102516
- }
102517
- return {
102518
- overallScore,
102519
- grade,
102520
- aiCitationProbability,
102521
- wordCount,
102522
- methods,
102523
- detected: {
102524
- citations: detectedCitations,
102525
- statistics: detectedStats,
102526
- quotes: detectedQuotes,
102527
- answerFirstH2Count: answerFirstCount,
102528
- totalH2Count,
102529
- optimalPassagesCount,
102530
- totalPassagesCount,
102531
- hedgingPhrases: Array.from(new Set(hedgingMatches)),
102532
- topRepeatedTerms: repeatedTerms.slice(0, 5)
102533
- },
102534
- recommendations
102535
- };
102536
- }
102537
- static stripHtml(html) {
102538
- return html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, " ").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
102539
- }
102540
- static extractCitations(html) {
102541
- const citations = [];
102542
- const linkRegex = /<a\s+(?:[^>]*?\s+)?href=["'](https?:\/\/[^"'>]+)["'][^>]*>(.*?)<\/a>/gi;
102543
- let match;
102544
- while ((match = linkRegex.exec(html)) !== null) {
102545
- const url = match[1];
102546
- const text = this.stripHtml(match[2]);
102547
- try {
102548
- const parsed = new URL(url);
102549
- const host = parsed.hostname.toLowerCase();
102550
- const isAuth = Array.from(AUTHORITATIVE_TLDS).some((tld) => host.endsWith(tld)) || Array.from(AUTHORITATIVE_DOMAINS).some((d) => host === d || host.endsWith("." + d));
102551
- citations.push({
102552
- url,
102553
- domain: host,
102554
- text,
102555
- isAuthoritative: isAuth
102556
- });
102557
- } catch {}
102558
- }
102559
- const mdLinkRegex = /\[([^\]]+)\]\((https?:\/\/[^\s\)]+)\)/g;
102560
- while ((match = mdLinkRegex.exec(html)) !== null) {
102561
- const text = match[1];
102562
- const url = match[2];
102563
- try {
102564
- const parsed = new URL(url);
102565
- const host = parsed.hostname.toLowerCase();
102566
- const isAuth = Array.from(AUTHORITATIVE_TLDS).some((tld) => host.endsWith(tld)) || Array.from(AUTHORITATIVE_DOMAINS).some((d) => host === d || host.endsWith("." + d));
102567
- citations.push({
102568
- url,
102569
- domain: host,
102570
- text,
102571
- isAuthoritative: isAuth
102572
- });
102573
- } catch {}
102574
- }
102575
- return citations;
102576
- }
102577
- static extractStatistics(text) {
102578
- const stats = [];
102579
- const statPatterns = [
102580
- { re: /\b\d+(?:[.,]\d+)?\s*%/g, type: "percentage" },
102581
- {
102582
- re: /(?:[$€£]\s*\d+(?:[.,]\d+)*(?:\s*(?:M|B|K|millions?|milliards?))?|\b\d+(?:[.,]\d+)*\s*[$€£])/gi,
102583
- type: "currency"
102584
- },
102585
- { re: /\b\d+(?:[.,]\d+)?\s*[xX]\b/g, type: "multiplier" },
102586
- {
102587
- re: /\b\d+\s*(?:millions?|milliards?|billions?|milliers?)\b/gi,
102588
- type: "scale"
102589
- },
102590
- { re: /\b(?:en|depuis|in|since)\s+20[12]\d\b/gi, type: "date" }
102591
- ];
102592
- for (const { re, type } of statPatterns) {
102593
- let m;
102594
- while ((m = re.exec(text)) !== null) {
102595
- const raw = m[0];
102596
- const start = Math.max(0, m.index - 30);
102597
- const end = Math.min(text.length, m.index + raw.length + 30);
102598
- const context = text.substring(start, end).replace(/\s+/g, " ").trim();
102599
- stats.push({ raw, context, type });
102600
- }
102601
- }
102602
- return stats;
102603
- }
102604
- static extractQuotations(input) {
102605
- const quotes = [];
102606
- const bqRegex = /<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gi;
102607
- let bqMatch;
102608
- while ((bqMatch = bqRegex.exec(input)) !== null) {
102609
- const bqText = this.stripHtml(bqMatch[1]);
102610
- quotes.push({
102611
- quote: bqText,
102612
- hasRoleOrOrg: /[\u2014\u2013\-,]/.test(bqText)
102613
- });
102614
- }
102615
- const mdBqRegex = /(?:^|\n)>\s*([^\n]+)/g;
102616
- let mdBqMatch;
102617
- while ((mdBqMatch = mdBqRegex.exec(input)) !== null) {
102618
- const bqText = mdBqMatch[1].trim();
102619
- if (bqText.length > 15) {
102620
- quotes.push({
102621
- quote: bqText,
102622
- hasRoleOrOrg: /[\u2014\u2013\-,:]/.test(bqText)
102623
- });
102624
- }
102625
- }
102626
- const quoteRegex = /["«\u201c]([^"»\u201d]{15,300})["»\u201d]\s*(?:\u2014|\u2013|-)\s*([^\n]{3,120})/g;
102627
- let qMatch;
102628
- while ((qMatch = quoteRegex.exec(input)) !== null) {
102629
- const quote = qMatch[1].trim();
102630
- const attribution = qMatch[2].trim();
102631
- quotes.push({
102632
- quote,
102633
- attribution,
102634
- hasRoleOrOrg: attribution.includes(",") || attribution.includes("—") || attribution.includes("-")
102635
- });
102636
- }
102637
- return quotes;
102638
- }
102639
- static evaluateAnswerFirst(content) {
102640
- let sections = [];
102641
- if (/<h2[^>]*>/i.test(content)) {
102642
- sections = content.split(/<h2[^>]*>/i).slice(1).map((s) => s.replace(/^[\s\S]*?<\/h2>/i, ""));
102643
- } else if (/(?:^|\n)##\s+/m.test(content)) {
102644
- sections = content.split(/(?:^|\n)##\s+[^\n]+\n/m).slice(1);
102645
- }
102646
- if (sections.length === 0) {
102647
- return { answerFirstCount: 0, totalH2Count: 0 };
102648
- }
102649
- let answerFirstCount = 0;
102650
- const totalH2Count = sections.length;
102651
- for (const section of sections) {
102652
- const cleanOpening = this.stripHtml(section).replace(/^[>\s*#_~`💡\u{1F300}-\u{1F9FF}]+/u, "").replace(/^Answer-First\s*:\s*/i, "").substring(0, 180).trim();
102653
- const isDirectAnswer = /^(?:[A-ZÀ-ÖØ-Ý][^.!?]{10,120}(?:est|permet|constitue|consiste|représente|is|provides|enables|means|débute|dessert|impose|se distingue|apporte)\b|Le |La |Les |Une |Un |En |Dans |Selon |Conformément |Voici |Notre )/i.test(cleanOpening) && cleanOpening.length > 25;
102654
- if (isDirectAnswer) {
102655
- answerFirstCount++;
102656
- }
102657
- }
102658
- return { answerFirstCount, totalH2Count };
102659
- }
102660
- static evaluatePassageDensity(content) {
102661
- const rawPassages = [];
102662
- if (/<p[^>]*>/i.test(content)) {
102663
- const pRegex = /<p[^>]*>([\s\S]*?)<\/p>/gi;
102664
- let pMatch;
102665
- while ((pMatch = pRegex.exec(content)) !== null) {
102666
- rawPassages.push(this.stripHtml(pMatch[1]));
102667
- }
102668
- } else {
102669
- const blocks = content.split(/\n\s*\n/).map((b) => this.stripHtml(b).trim()).filter((b) => !b.startsWith("#") && !b.startsWith("|") && !b.startsWith(">"));
102670
- rawPassages.push(...blocks);
102671
- }
102672
- let optimalPassagesCount = 0;
102673
- let totalPassagesCount = 0;
102674
- for (const text of rawPassages) {
102675
- const pWords = text.match(/\b[\w'-]+\b/g) || [];
102676
- const wc = pWords.length;
102677
- if (wc >= 20) {
102678
- totalPassagesCount++;
102679
- const hasNumber = /\b\d+(?:[.,]\d+)?\b/.test(text);
102680
- if (wc >= 35 && wc <= 160 && hasNumber) {
102681
- optimalPassagesCount++;
102682
- }
102683
- }
102684
- }
102685
- return { optimalPassagesCount, totalPassagesCount };
102686
- }
102687
- static evaluateKeywordDensity(words) {
102688
- const stopWords = new Set([
102689
- "le",
102690
- "la",
102691
- "les",
102692
- "un",
102693
- "une",
102694
- "des",
102695
- "du",
102696
- "de",
102697
- "et",
102698
- "en",
102699
- "pour",
102700
- "dans",
102701
- "sur",
102702
- "avec",
102703
- "par",
102704
- "the",
102705
- "a",
102706
- "an",
102707
- "and",
102708
- "or",
102709
- "in",
102710
- "on",
102711
- "for",
102712
- "with",
102713
- "by",
102714
- "at",
102715
- "to",
102716
- "from",
102717
- "is",
102718
- "are",
102719
- "that",
102720
- "this"
102721
- ]);
102722
- const freq = {};
102723
- for (const w of words) {
102724
- const lower = w.toLowerCase();
102725
- if (lower.length >= 3 && !stopWords.has(lower)) {
102726
- freq[lower] = (freq[lower] || 0) + 1;
102727
- }
102728
- }
102729
- const total = words.length || 1;
102730
- return Object.entries(freq).map(([term, count]) => ({
102731
- term,
102732
- count,
102733
- density: count / total
102734
- })).sort((a, b) => b.count - a.count);
102735
- }
102736
- }
102737
-
102738
- // src/geo-hallucination-bait.ts
102739
- var ABSOLUTE_CLAIM_REGEX = /\b(?:des études prouvent|la recherche prouve|il est prouvé que|il est universellement reconnu|tout le monde sait que|studies prove|research proves|it is proven that|it is known that|evidence proves)\b/gi;
102740
- var SPECULATIVE_FUTURE_REGEX = /\b(?:d'ici\s+20[3-5]\d|on\s+estime\s+que|on\s+prévoit\s+que|devrait\s+atteindre|projected\s+to|expected\s+to\s+reach|by\s+the\s+year\s+20[3-5]\d)\b/gi;
102741
- var VAGUE_RANGE_REGEX = /\b(?:entre\s+\d+\s+et\s+\d+\s*(?:millions?|milliards?|fois|x|%)|jusqu'à\s+\d+\s*(?:fois|x|%|millions?)|between\s+\d+\s+and\s+\d+|up\s+to\s+\d+\s*(?:x|times|%))\b/gi;
102742
- var CIRCULAR_CITATION_REGEX = /\b(?:selon\s+nos\s+(?:propres\s+)?(?:données|recherches|analyses|estimations)|d'après\s+notre\s+équipe|according\s+to\s+our\s+(?:data|internal\s+research|team))\b/gi;
102743
- var STATS_REGEX = /\b(\d{1,3}(?:[.,]\d+)?\s*(?:%|pourcent\b|percent\b))/gi;
102744
- var CITATION_CONTEXT_REGEX = /(?:selon|source|insee|étude|rapport|enquête|universit|journal|according\s+to|study|report|survey|published\s+in)/i;
102745
-
102746
- class GeoHallucinationBaitDetector {
102747
- static analyze(textOrHtml) {
102748
- const cleanText = textOrHtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, " ").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
102749
- const items = [];
102750
- const countsByType = {
102751
- unsourced_stat: 0,
102752
- absolute_claim: 0,
102753
- speculative_future: 0,
102754
- vague_range: 0,
102755
- circular_citation: 0
102756
- };
102757
- if (!cleanText) {
102758
- return {
102759
- checked: true,
102760
- totalBaits: 0,
102761
- severity: "clean",
102762
- score: 100,
102763
- items: [],
102764
- countsByType,
102765
- summary: "Aucun texte à analyser.",
102766
- recommendations: []
102767
- };
102768
- }
102769
- let match;
102770
- const absRegex = new RegExp(ABSOLUTE_CLAIM_REGEX.source, "gi");
102771
- while ((match = absRegex.exec(cleanText)) !== null) {
102772
- const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
102773
- items.push({
102774
- type: "absolute_claim",
102775
- snippet,
102776
- explanation: "Affirmation absolue non sourcée susceptible d'être contestée ou déformée par l'IA.",
102777
- suggestion: "Nommer l'étude spécifique ou l'institution autrice avec lien hypertexte."
102778
- });
102779
- countsByType.absolute_claim++;
102780
- }
102781
- const specRegex = new RegExp(SPECULATIVE_FUTURE_REGEX.source, "gi");
102782
- while ((match = specRegex.exec(cleanText)) !== null) {
102783
- const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
102784
- items.push({
102785
- type: "speculative_future",
102786
- snippet,
102787
- explanation: "Projection prospective sans base méthodologique explicite.",
102788
- suggestion: "Préciser l'organisme émetteur de la projection (ex. 'selon le rapport Gartner 2026')."
102789
- });
102790
- countsByType.speculative_future++;
102791
- }
102792
- const rangeRegex = new RegExp(VAGUE_RANGE_REGEX.source, "gi");
102793
- while ((match = rangeRegex.exec(cleanText)) !== null) {
102794
- const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
102795
- items.push({
102796
- type: "vague_range",
102797
- snippet,
102798
- explanation: "Fourchette de grandeur excessivement large poussant les modèles à inventer un chiffre médian.",
102799
- suggestion: "Fournir une médiane mesurée ou un échantillon délimité."
102800
- });
102801
- countsByType.vague_range++;
102802
- }
102803
- const circRegex = new RegExp(CIRCULAR_CITATION_REGEX.source, "gi");
102804
- while ((match = circRegex.exec(cleanText)) !== null) {
102805
- const snippet = cleanText.substring(Math.max(0, match.index - 20), Math.min(cleanText.length, match.index + 60)).trim();
102806
- items.push({
102807
- type: "circular_citation",
102808
- snippet,
102809
- explanation: "Auto-attribution circulaire perçue comme un biais commercial par les moteurs de recherche IA.",
102810
- suggestion: "Corroborer avec une source tierce ou publier la méthodologie de l'audit."
102811
- });
102812
- countsByType.circular_citation++;
102813
- }
102814
- const statRegex = new RegExp(STATS_REGEX.source, "gi");
102815
- let unreferencedCount = 0;
102816
- while ((match = statRegex.exec(cleanText)) !== null && unreferencedCount < 5) {
102817
- const startWindow = Math.max(0, match.index - 80);
102818
- const endWindow = Math.min(cleanText.length, match.index + 80);
102819
- const surroundingContext = cleanText.substring(startWindow, endWindow);
102820
- if (!CITATION_CONTEXT_REGEX.test(surroundingContext)) {
102821
- items.push({
102822
- type: "unsourced_stat",
102823
- snippet: cleanText.substring(Math.max(0, match.index - 25), Math.min(cleanText.length, match.index + 35)).trim(),
102824
- explanation: `Pourcentage (${match[1]}) cité sans mention d'organisme ni d'année à proximité immédiate.`,
102825
- suggestion: "Associer systématiquement chaque pourcentage à sa source (ex. 'selon l'INSEE', 'd'après une étude Stanford')."
102826
- });
102827
- countsByType.unsourced_stat++;
102828
- unreferencedCount++;
102829
- }
102830
- }
102831
- const totalBaits = items.length;
102832
- let severity = "clean";
102833
- if (totalBaits >= 6)
102834
- severity = "high";
102835
- else if (totalBaits >= 3)
102836
- severity = "medium";
102837
- else if (totalBaits >= 1)
102838
- severity = "low";
102839
- const score = Math.max(20, Math.min(100, 100 - (countsByType.absolute_claim * 15 + countsByType.circular_citation * 12 + countsByType.unsourced_stat * 8 + countsByType.vague_range * 6 + countsByType.speculative_future * 6)));
102840
- const recommendations = [];
102841
- if (countsByType.absolute_claim > 0) {
102842
- recommendations.push("Supprimez les formules absolues ('il est prouvé que', 'études démontrent') et citez nommément les auteurs.");
102843
- }
102844
- if (countsByType.unsourced_stat > 0) {
102845
- recommendations.push("Ancrez vos pourcentages avec l'autorité source pour empêcher l'IA d'attribuer des chiffres erronés.");
102846
- }
102847
- if (countsByType.circular_citation > 0) {
102848
- recommendations.push("Évitez les formulations d'auto-justification ('selon nos propres données') sans lien vers une étude publique.");
102849
- }
102850
- let summary = "";
102851
- if (severity === "clean") {
102852
- summary = "Texte factuel, rigoureux et ancré. Risque d'hallucination minimal pour les LLMs.";
102853
- } else if (severity === "low") {
102854
- summary = `Quelques imprécisions détectées (${totalBaits} signaux). Risque modéré de déformation factuelle.`;
102855
- } else {
102856
- summary = `Alerte : Présence de ${totalBaits} pièges à hallucinations (statistiques orphelines, affirmations péremptoires).`;
102857
- }
102858
- return {
102859
- checked: true,
102860
- totalBaits,
102861
- severity,
102862
- score,
102863
- items,
102864
- countsByType,
102865
- summary,
102866
- recommendations
102867
- };
102868
- }
102869
- }
102870
-
102871
103384
  // src/google-ai-readiness-auditor.ts
102872
103385
  var GOOGLE_DOC_URLS = {
102873
103386
  "G-INDEX": "https://developers.google.com/search/docs/essentials/technical",
@@ -205171,7 +205684,7 @@ class GroupAnalyticsPlugin {
205171
205684
  getReport(siteId, options) {
205172
205685
  const requestedType = options?.groupType || "company";
205173
205686
  const siteMap = this.groupsBySite.get(siteId);
205174
- const allGroups = siteMap ? Array.from(siteMap.values()).filter((g) => g.groupType === requestedType).map((g) => this.stripInternalFields(g)) : this.getDefaultGroups(siteId, requestedType);
205687
+ const allGroups = siteMap ? Array.from(siteMap.values()).filter((g) => g.groupType === requestedType).map((g) => this.stripInternalFields(g)) : [];
205175
205688
  const filtered = allGroups.filter((g) => {
205176
205689
  if (options?.plan && g.metrics.plan?.toLowerCase() !== options.plan.toLowerCase()) {
205177
205690
  return false;
@@ -205223,65 +205736,6 @@ class GroupAnalyticsPlugin {
205223
205736
  }
205224
205737
  };
205225
205738
  }
205226
- getDefaultGroups(siteId, groupType) {
205227
- const now = new Date().toISOString();
205228
- return [
205229
- {
205230
- groupKey: "grp_acme_corp",
205231
- groupType,
205232
- siteId,
205233
- name: "Acme Corporation",
205234
- properties: { industry: "SaaS", region: "EMEA", seats: 25 },
205235
- createdAt: "2026-01-10T08:00:00.000Z",
205236
- updatedAt: now,
205237
- metrics: {
205238
- distinctUsersCount: 18,
205239
- totalEventsCount: 4210,
205240
- totalSessionsCount: 380,
205241
- lastActiveAt: now,
205242
- healthScore: 92,
205243
- mrr: 1200,
205244
- plan: "enterprise"
205245
- }
205246
- },
205247
- {
205248
- groupKey: "grp_tech_labs",
205249
- groupType,
205250
- siteId,
205251
- name: "TechLabs Global",
205252
- properties: { industry: "Fintech", region: "US-East", seats: 10 },
205253
- createdAt: "2026-02-15T10:30:00.000Z",
205254
- updatedAt: now,
205255
- metrics: {
205256
- distinctUsersCount: 7,
205257
- totalEventsCount: 1250,
205258
- totalSessionsCount: 95,
205259
- lastActiveAt: now,
205260
- healthScore: 78,
205261
- mrr: 450,
205262
- plan: "growth"
205263
- }
205264
- },
205265
- {
205266
- groupKey: "grp_solopreneur",
205267
- groupType,
205268
- siteId,
205269
- name: "Solo Consulting",
205270
- properties: { industry: "Consulting", region: "Europe" },
205271
- createdAt: "2026-03-01T14:00:00.000Z",
205272
- updatedAt: now,
205273
- metrics: {
205274
- distinctUsersCount: 1,
205275
- totalEventsCount: 85,
205276
- totalSessionsCount: 12,
205277
- lastActiveAt: "2026-04-01T09:00:00.000Z",
205278
- healthScore: 35,
205279
- mrr: 49,
205280
- plan: "starter"
205281
- }
205282
- }
205283
- ];
205284
- }
205285
205739
  }
205286
205740
  // src/plugins/heatmap-scrollmap/index.ts
205287
205741
  class HeatmapScrollmapPlugin {
@@ -218000,116 +218454,40 @@ function dayRows(leads) {
218000
218454
  return [...byDate.entries()].map(([date, row]) => ({ date, ...row })).toSorted((a, b) => a.date.localeCompare(b.date));
218001
218455
  }
218002
218456
  // src/plugins/account-analytics/index.ts
218457
+ function accountStatusForHealthScore(healthScore) {
218458
+ const score = Math.max(0, Math.min(100, healthScore));
218459
+ if (score < 50)
218460
+ return "at_risk";
218461
+ if (score >= 90)
218462
+ return "expanding";
218463
+ return "healthy";
218464
+ }
218465
+
218003
218466
  class AccountAnalyticsPlugin {
218004
218467
  manifest = {
218005
218468
  id: "account-analytics",
218006
218469
  name: "B2B Account Analytics",
218007
- version: "1.0.0",
218470
+ version: "2.0.0",
218008
218471
  description: "Agrégation et suivi analytique au niveau entreprise/compte client B2B (MRR, santé du compte, utilisateurs actifs)"
218009
218472
  };
218010
- accounts = new Map;
218011
- constructor() {
218012
- this.seedDefaultAccounts();
218013
- }
218014
- seedDefaultAccounts() {
218015
- const defaults = [
218016
- {
218017
- id: "acc_acme_corp",
218018
- name: "Acme Corporation",
218019
- domain: "acme.com",
218020
- plan: "enterprise",
218021
- mrr: 1450,
218022
- totalUsers: 48,
218023
- activeUsers30d: 42,
218024
- healthScore: 92,
218025
- status: "healthy",
218026
- lastActivityAt: new Date(Date.now() - 1000 * 60 * 12).toISOString(),
218027
- primaryFeaturesUsed: ["batch-exports", "group-analytics", "custom-alerts"]
218028
- },
218029
- {
218030
- id: "acc_globex_tech",
218031
- name: "Globex Technologies",
218032
- domain: "globex.io",
218033
- plan: "pro",
218034
- mrr: 490,
218035
- totalUsers: 14,
218036
- activeUsers30d: 3,
218037
- healthScore: 41,
218038
- status: "at_risk",
218039
- lastActivityAt: new Date(Date.now() - 1000 * 60 * 60 * 48).toISOString(),
218040
- primaryFeaturesUsed: ["live-debugger"]
218041
- },
218042
- {
218043
- id: "acc_stark_industries",
218044
- name: "Stark Industries",
218045
- domain: "starkindustries.com",
218046
- plan: "enterprise",
218047
- mrr: 3200,
218048
- totalUsers: 120,
218049
- activeUsers30d: 115,
218050
- healthScore: 98,
218051
- status: "expanding",
218052
- lastActivityAt: new Date(Date.now() - 1000 * 60 * 5).toISOString(),
218053
- primaryFeaturesUsed: ["analytics-notebooks", "resource-transfer", "real-time-usage", "batch-exports"]
218054
- }
218055
- ];
218056
- for (const acc of defaults) {
218057
- this.accounts.set(acc.id, acc);
218058
- }
218059
- }
218060
218473
  async init(_context) {}
218061
- getReport(projectId) {
218062
- const list = Array.from(this.accounts.values());
218063
- const totalMrr = list.reduce((sum, a) => sum + a.mrr, 0);
218064
- const avgHealth = list.length > 0 ? Math.round(list.reduce((sum, a) => sum + a.healthScore, 0) / list.length) : 0;
218065
- const atRisk = list.filter((a) => a.status === "at_risk").length;
218066
- const expanding = list.filter((a) => a.status === "expanding").length;
218474
+ getReport(projectId, accounts) {
218475
+ const totalMrr = accounts.reduce((sum, a) => sum + a.mrr, 0);
218476
+ const avgHealth = accounts.length > 0 ? Math.round(accounts.reduce((sum, a) => sum + a.healthScore, 0) / accounts.length) : 0;
218477
+ const atRisk = accounts.filter((a) => a.status === "at_risk").length;
218478
+ const expanding = accounts.filter((a) => a.status === "expanding").length;
218067
218479
  return {
218068
218480
  projectId,
218069
218481
  generatedAt: new Date().toISOString(),
218070
218482
  summary: {
218071
- totalAccounts: list.length,
218483
+ totalAccounts: accounts.length,
218072
218484
  totalMrr,
218073
218485
  averageHealthScore: avgHealth,
218074
218486
  accountsAtRiskCount: atRisk,
218075
218487
  topExpandingAccountsCount: expanding
218076
218488
  },
218077
- accounts: list
218078
- };
218079
- }
218080
- upsertAccount(account) {
218081
- const id = account.id || `acc_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
218082
- const fullAccount = {
218083
- ...account,
218084
- id,
218085
- lastActivityAt: new Date().toISOString()
218086
- };
218087
- this.accounts.set(id, fullAccount);
218088
- return fullAccount;
218089
- }
218090
- updateAccountHealth(id, healthScore) {
218091
- const acc = this.accounts.get(id);
218092
- if (!acc)
218093
- return null;
218094
- const clampedScore = Math.max(0, Math.min(100, healthScore));
218095
- let status = acc.status;
218096
- if (clampedScore < 50)
218097
- status = "at_risk";
218098
- else if (clampedScore >= 90)
218099
- status = "expanding";
218100
- else
218101
- status = "healthy";
218102
- const updated = {
218103
- ...acc,
218104
- healthScore: clampedScore,
218105
- status,
218106
- lastActivityAt: new Date().toISOString()
218489
+ accounts: [...accounts]
218107
218490
  };
218108
- this.accounts.set(id, updated);
218109
- return updated;
218110
- }
218111
- deleteAccount(id) {
218112
- return this.accounts.delete(id);
218113
218491
  }
218114
218492
  }
218115
218493
  // src/plugins/actions/index.ts
@@ -246521,11 +246899,16 @@ w.addEventListener("beforeunload",flush);
246521
246899
  })();`.replace(/\n\s*/g, "");
246522
246900
  }
246523
246901
  // src/sourcemap-uploader.ts
246902
+ var uploadResponseSchema = object({
246903
+ id: string2().optional(),
246904
+ sourcemapId: string2().optional(),
246905
+ url: string2().optional()
246906
+ });
246524
246907
  async function uploadSourcemap(options) {
246525
246908
  const endpoint = options.endpoint || "/api/sourcemaps/upload";
246526
246909
  const headers = {
246527
246910
  "Content-Type": "application/json",
246528
- ...options.headers || {}
246911
+ ...options.headers
246529
246912
  };
246530
246913
  if (options.token) {
246531
246914
  headers["Authorization"] = `Bearer ${options.token}`;
@@ -246544,18 +246927,25 @@ async function uploadSourcemap(options) {
246544
246927
  body
246545
246928
  });
246546
246929
  if (res.ok) {
246547
- const data = await res.json();
246930
+ const data = uploadResponseSchema.safeParse(await res.json());
246931
+ if (!data.success) {
246932
+ return {
246933
+ success: false,
246934
+ error: "Invalid sourcemap upload response"
246935
+ };
246936
+ }
246548
246937
  return {
246549
246938
  success: true,
246550
- id: data.id || data.sourcemapId,
246551
- url: data.url
246939
+ id: data.data.id || data.data.sourcemapId,
246940
+ url: data.data.url
246552
246941
  };
246553
246942
  }
246554
246943
  let errorMsg = `Upload failed: ${res.statusText}`;
246555
246944
  try {
246556
246945
  const errorData = await res.json();
246557
- if (errorData.error)
246946
+ if (typeof errorData === "object" && errorData !== null && "error" in errorData && typeof errorData.error === "string") {
246558
246947
  errorMsg = errorData.error;
246948
+ }
246559
246949
  } catch {}
246560
246950
  return {
246561
246951
  success: false,
@@ -246667,11 +247057,30 @@ function buildQueryFromSchema(schema) {
246667
247057
  }
246668
247058
  return builder.build();
246669
247059
  }
246670
- async function executeQuery(query, parameters = []) {
247060
+ var customQueryExecutor = null;
247061
+ function setQueryExecutor(executor) {
247062
+ customQueryExecutor = executor;
247063
+ }
247064
+ var tableMetadataRegistry = new Map;
247065
+ function registerTableMetadata(tableName, metadata) {
247066
+ tableMetadataRegistry.set(tableName.toLowerCase(), metadata);
247067
+ }
247068
+ async function executeQuery(query, parameters = [], executor) {
247069
+ const activeExecutor = executor || customQueryExecutor;
247070
+ if (activeExecutor) {
247071
+ return activeExecutor(query, parameters);
247072
+ }
246671
247073
  return [];
246672
247074
  }
246673
- function getTableMetadata(tableName) {
246674
- return Promise.resolve({ columns: [] });
247075
+ async function getTableMetadata(tableName, fetcher) {
247076
+ if (fetcher) {
247077
+ return fetcher(tableName);
247078
+ }
247079
+ const registered = tableMetadataRegistry.get(tableName.toLowerCase());
247080
+ if (registered) {
247081
+ return registered;
247082
+ }
247083
+ return { columns: [] };
246675
247084
  }
246676
247085
  // src/white-label-exports.ts
246677
247086
  import { writeFile } from "fs/promises";
@@ -246778,8 +247187,16 @@ function dataToCsv(data) {
246778
247187
  return [headers.join(","), ...rows.map((row) => row.join(","))].join(`
246779
247188
  `);
246780
247189
  }
246781
- async function convertHtmlToPdf(html) {
246782
- return Buffer.from(html);
247190
+ var customHtmlToPdfConverter = null;
247191
+ function setHtmlToPdfConverter(converter) {
247192
+ customHtmlToPdfConverter = converter;
247193
+ }
247194
+ async function convertHtmlToPdf(html, converter) {
247195
+ const activeConverter = converter || customHtmlToPdfConverter;
247196
+ if (activeConverter) {
247197
+ return activeConverter(html);
247198
+ }
247199
+ return Buffer.from(html, "utf-8");
246783
247200
  }
246784
247201
 
246785
247202
  // src/index.ts
@@ -247674,6 +248091,8 @@ export {
247674
248091
  PseoIntegrationSchema,
247675
248092
  PseoLocationSchema,
247676
248093
  PseoMatrixEngine,
248094
+ PseoNicheProductItemSchema,
248095
+ PseoNicheReportSchema,
247677
248096
  PseoPatternRollupAnalyzer,
247678
248097
  PseoPreflightGate,
247679
248098
  PseoPublisherBridge,
@@ -247998,6 +248417,7 @@ export {
247998
248417
  YoastVariableReplacer,
247999
248418
  YotpoSyncEngine,
248000
248419
  YouTubeApiClient,
248420
+ accountStatusForHealthScore,
248001
248421
  acknowledgeMobileBatch,
248002
248422
  addPrompt,
248003
248423
  addRelativeUnits,
@@ -248228,6 +248648,7 @@ export {
248228
248648
  contentRecommendationEngine,
248229
248649
  conversionRate,
248230
248650
  convertEurToMultiCurrency,
248651
+ convertHtmlToPdf,
248231
248652
  countByCategory,
248232
248653
  countBySeverity,
248233
248654
  countConcurrentVisitors,
@@ -248675,6 +249096,7 @@ export {
248675
249096
  registerAny,
248676
249097
  registerGa4GscTools,
248677
249098
  registerSkill,
249099
+ registerTableMetadata,
248678
249100
  relativeLiftBayesian,
248679
249101
  relativePeriodBounds,
248680
249102
  relativePeriodPreset,
@@ -248767,6 +249189,8 @@ export {
248767
249189
  serializeFilters,
248768
249190
  serpCheckId,
248769
249191
  serpEstimator,
249192
+ setHtmlToPdfConverter,
249193
+ setQueryExecutor,
248770
249194
  setTrait,
248771
249195
  shouldRetry,
248772
249196
  shouldRetryStatus,