search-visibility 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.es.md +36 -1
  3. package/README.ja.md +36 -1
  4. package/README.ko.md +42 -6
  5. package/README.md +42 -6
  6. package/README.zh.md +36 -1
  7. package/package.json +2 -1
  8. package/skills/seo-orchestrator/scripts/ai-performance.mjs +107 -0
  9. package/skills/seo-orchestrator/scripts/canonical.mjs +175 -0
  10. package/skills/seo-orchestrator/scripts/command.mjs +6 -0
  11. package/skills/seo-orchestrator/scripts/comparison-pairs.mjs +89 -0
  12. package/skills/seo-orchestrator/scripts/crawl-report.mjs +34 -0
  13. package/skills/seo-orchestrator/scripts/fetch-page.mjs +2 -5
  14. package/skills/seo-orchestrator/scripts/hreflang.mjs +273 -0
  15. package/skills/seo-orchestrator/scripts/html.mjs +7 -80
  16. package/skills/seo-orchestrator/scripts/index-status.mjs +181 -0
  17. package/skills/seo-orchestrator/scripts/indexing.mjs +28 -39
  18. package/skills/seo-orchestrator/scripts/internal-crawl.mjs +16 -46
  19. package/skills/seo-orchestrator/scripts/link-header.mjs +93 -0
  20. package/skills/seo-orchestrator/scripts/mcp.mjs +45 -8
  21. package/skills/seo-orchestrator/scripts/naver-advisor.mjs +147 -0
  22. package/skills/seo-orchestrator/scripts/observations.mjs +42 -8
  23. package/skills/seo-orchestrator/scripts/report-html.mjs +35 -0
  24. package/skills/seo-orchestrator/scripts/report-input.mjs +142 -0
  25. package/skills/seo-orchestrator/scripts/report-sources.mjs +202 -0
  26. package/skills/seo-orchestrator/scripts/robots.mjs +270 -0
  27. package/skills/seo-orchestrator/scripts/scope.mjs +185 -0
  28. package/skills/seo-orchestrator/scripts/search-performance.mjs +1 -1
  29. package/skills/seo-orchestrator/scripts/seo-check.mjs +199 -269
  30. package/skills/seo-orchestrator/scripts/site-audit.mjs +102 -46
  31. package/skills/seo-orchestrator/scripts/structured-data.mjs +316 -0
  32. package/skills/seo-orchestrator/scripts/url-inspection.mjs +150 -0
  33. package/skills/seo-orchestrator/scripts/visibility-comparison.mjs +218 -39
  34. package/skills/seo-orchestrator/scripts/visibility-report.mjs +71 -48
  35. package/skills/seo-orchestrator/scripts/visibility.mjs +53 -50
@@ -0,0 +1,147 @@
1
+ // 네이버 서치어드바이저 화면에서 기록한 수집·색인·웹 검색 수치를 단계별로 정리한다.
2
+ // 단계마다 모집단과 기준일이 다르므로 전환율을 계산하지 않는다.
3
+ import { t } from "./locale.mjs";
4
+ import { calendarDate, compareScopes, optionalText, parsePeriod, rejectUnknownKeys, requireObject } from "./scope.mjs";
5
+
6
+ const COMMON = ["report", "period", "updatedAt", "device", "aggregation"];
7
+ const STAGES = { crawl: ["errors"], index: ["metrics"], webSearch: ["impressions", "clicks"] };
8
+
9
+ function count(value, field) {
10
+ if (value === undefined || value === null) return null;
11
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(t(`${field}에는 0 이상의 정수를 입력하세요. 수집하지 않은 값은 생략합니다.`, `${field} must be a nonnegative integer. Omit values that were not collected.`));
12
+ return value;
13
+ }
14
+
15
+ function items(value, field, key, shape) {
16
+ if (!Array.isArray(value) || !value.length) throw new Error(t(`${field}에는 항목이 있는 배열을 입력하세요.`, `${field} must be a nonempty array.`));
17
+ const seen = new Set();
18
+ return value.map((entry, index) => {
19
+ const at = `${field}[${index}]`;
20
+ requireObject(entry, at);
21
+ rejectUnknownKeys(entry, Object.keys(shape), at);
22
+ const result = Object.fromEntries(Object.entries(shape).map(([name, read]) => [name, read(entry[name], `${at}.${name}`)]));
23
+ if (!result[key]) throw new Error(t(`${at}.${key}에는 화면에 표시된 이름을 입력하세요.`, `${at}.${key} must be the name shown on screen.`));
24
+ if (seen.has(result[key])) throw new Error(t(`${at}.${key}가 중복됩니다.`, `${at}.${key} is duplicated.`));
25
+ seen.add(result[key]);
26
+ return result;
27
+ });
28
+ }
29
+
30
+ function category(value, field) {
31
+ const text = optionalText(value, field);
32
+ if (text !== null && !["robots", "other"].includes(text)) throw new Error(t(`${field}에는 robots 또는 other를 입력하세요.`, `${field} must be robots or other.`));
33
+ return text;
34
+ }
35
+
36
+ function record(stage, value, field) {
37
+ requireObject(value, field);
38
+ rejectUnknownKeys(value, [...COMMON, ...STAGES[stage]], field);
39
+ const base = {
40
+ report: optionalText(value.report, `${field}.report`),
41
+ period: parsePeriod(value.period, `${field}.period`),
42
+ updatedAt: value.updatedAt === undefined || value.updatedAt === null ? null : calendarDate(value.updatedAt, `${field}.updatedAt`),
43
+ device: optionalText(value.device, `${field}.device`),
44
+ aggregation: optionalText(value.aggregation, `${field}.aggregation`),
45
+ };
46
+ if (!base.report) throw new Error(t(`${field}.report에는 보고서 이름을 입력하세요.`, `${field}.report must name the report.`));
47
+ if (stage === "crawl") {
48
+ const errors = items(value.errors, `${field}.errors`, "type", { type: optionalText, count, category });
49
+ // 분류를 생략하면 이름에 로봇(robots)이 들어간 오류를 차단 규칙 관련으로 본다.
50
+ return { ...base, errors: errors.map((error) => ({ ...error, category: error.category ?? (/robots|로봇/i.test(error.type) ? "robots" : "other") })) };
51
+ }
52
+ if (stage === "index") return { ...base, metrics: items(value.metrics, `${field}.metrics`, "name", { name: optionalText, value: count }) };
53
+ return { ...base, impressions: count(value.impressions, `${field}.impressions`), clicks: count(value.clicks, `${field}.clicks`) };
54
+ }
55
+
56
+ // 조회 기간의 끝으로 정렬하고, 같으면 업데이트 기준일로 정렬한다.
57
+ const order = (entry) => `${entry.period?.end ?? entry.updatedAt ?? ""}\u0000${entry.updatedAt ?? ""}`;
58
+
59
+ // 같은 보고서·기기·집계 단위의 가장 최근 두 기록을 비교한다.
60
+ function crawlTrends(entries) {
61
+ const groups = new Map();
62
+ for (const entry of entries) {
63
+ const key = JSON.stringify([entry.report, entry.device, entry.aggregation]);
64
+ groups.set(key, [...(groups.get(key) ?? []), entry]);
65
+ }
66
+ return [...groups.values()].map((group) => {
67
+ const sorted = [...group].sort((a, b) => order(a).localeCompare(order(b)));
68
+ const latest = sorted.at(-1);
69
+ const previous = sorted.at(-2) ?? null;
70
+ // 수집 현황에는 기기 구분이 없을 수 있어, 한쪽이라도 기록했을 때 기기를 대조한다.
71
+ const fields = ["report", "aggregation", ...(previous?.device || latest.device ? ["device"] : [])];
72
+ const comparison = previous ? compareScopes(previous, latest, fields) : { status: "unverified", reasons: [{ code: "missing-previous" }] };
73
+ const types = [...new Set([...(previous?.errors ?? []), ...latest.errors].map((error) => error.type))];
74
+ return {
75
+ report: latest.report, device: latest.device, aggregation: latest.aggregation,
76
+ previous: previous && { period: previous.period, updatedAt: previous.updatedAt },
77
+ latest: { period: latest.period, updatedAt: latest.updatedAt },
78
+ ...comparison,
79
+ errors: types.map((type) => {
80
+ const a = previous?.errors.find((error) => error.type === type);
81
+ const b = latest.errors.find((error) => error.type === type);
82
+ const before = a?.count ?? null;
83
+ const after = b?.count ?? null;
84
+ const delta = comparison.status === "comparable" && before !== null && after !== null ? after - before : null;
85
+ return { type, category: (b ?? a).category, before, after, delta };
86
+ }),
87
+ };
88
+ });
89
+ }
90
+
91
+ function nextActions(stages, trends) {
92
+ const actions = [];
93
+ // 기록 묶음이 둘 이상이면 어느 기기·보고서의 값인지 함께 적는다.
94
+ const observed = (kind) => trends.flatMap((trend) => trend.errors
95
+ .filter((error) => (error.category === "robots") === (kind === "robots") && error.after > 0)
96
+ .map((error) => ({ ...error, label: trends.length > 1 ? `${error.type} (${trend.device ?? trend.report})` : error.type })));
97
+ const robots = observed("robots");
98
+ for (const increased of [true, false]) {
99
+ const matched = robots.filter((error) => (error.delta > 0) === increased);
100
+ if (matched.length) actions.push({ code: "check-robots", types: matched.map((error) => error.label), increased });
101
+ }
102
+ const other = observed("other");
103
+ if (other.length) actions.push({ code: "check-crawl-errors", types: other.map((error) => error.label) });
104
+ const has = {
105
+ crawl: stages.crawl.some((entry) => entry.errors.some((error) => error.count !== null)),
106
+ index: stages.index.some((entry) => entry.metrics.some((metric) => metric.value !== null)),
107
+ webSearch: stages.webSearch.some((entry) => entry.impressions !== null || entry.clicks !== null),
108
+ };
109
+ if (has.index && has.webSearch) actions.push({ code: "review-web-performance" });
110
+ for (const stage of Object.keys(has)) if (!has[stage]) actions.push({ code: "not-collected", stage });
111
+ return actions;
112
+ }
113
+
114
+ export function parseNaverAdvisor(input) {
115
+ requireObject(input, "naverSearchAdvisor");
116
+ rejectUnknownKeys(input, ["site", ...Object.keys(STAGES)], "naverSearchAdvisor");
117
+ const site = optionalText(input.site, "naverSearchAdvisor.site");
118
+ if (!site) throw new Error(t("naverSearchAdvisor.site에는 서치어드바이저에 등록한 사이트를 입력하세요.", "naverSearchAdvisor.site must name the site registered in Search Advisor."));
119
+ const stages = Object.fromEntries(Object.keys(STAGES).map((stage) => {
120
+ const list = input[stage] ?? [];
121
+ if (!Array.isArray(list)) throw new Error(t(`naverSearchAdvisor.${stage}에는 배열을 입력하세요.`, `naverSearchAdvisor.${stage} must be an array.`));
122
+ return [stage, list.map((entry, index) => record(stage, entry, `naverSearchAdvisor.${stage}[${index}]`))];
123
+ }));
124
+ if (Object.values(stages).every((list) => !list.length)) {
125
+ throw new Error(t("naverSearchAdvisor에 crawl, index, webSearch 중 기록을 하나 이상 입력하세요.", "naverSearchAdvisor needs at least one crawl, index or webSearch record."));
126
+ }
127
+ const trends = crawlTrends(stages.crawl);
128
+ return { site, ...stages, trends, actions: nextActions(stages, trends) };
129
+ }
130
+
131
+ export function stageName(stage) {
132
+ return { crawl: t("수집", "Crawl"), index: t("색인", "Index"), webSearch: t("웹 검색 실적", "Web search performance") }[stage];
133
+ }
134
+
135
+ export function actionText(action) {
136
+ const types = action.types?.join(", ");
137
+ switch (action.code) {
138
+ case "check-robots": return action.increased
139
+ ? t(`차단 규칙 확인: ${types} 오류가 늘었습니다. robots.txt와 로봇 메타를 확인하세요.`, `Check blocking rules: ${types} increased. Review robots.txt and robots meta.`)
140
+ : t(`차단 규칙 확인: ${types} 오류가 관측됐습니다. robots.txt와 로봇 메타를 확인하세요.`, `Check blocking rules: ${types} was observed. Review robots.txt and robots meta.`);
141
+ case "check-crawl-errors": return t(`수집 오류 확인: ${types}`, `Check crawl errors: ${types}`);
142
+ case "review-web-performance": return t("웹 검색 조회 기간과 페이지별 실적을 검토하세요. 사이트 합계만으로 특정 URL의 미색인 원인을 판단할 수 없습니다.",
143
+ "Review the web search period and per-page performance. Site totals cannot explain why a specific URL is not indexed.");
144
+ case "not-collected": return t(`${stageName(action.stage)} 자료 미수집: 서치어드바이저에서 확인해 기록하세요.`, `${stageName(action.stage)} data not collected: check Search Advisor and record it.`);
145
+ default: return action.code;
146
+ }
147
+ }
@@ -1,5 +1,4 @@
1
1
  import { t, currentLocale } from "./locale.mjs";
2
- import { domainToASCII } from "node:url";
3
2
 
4
3
  function requiredText(value, field) {
5
4
  if (typeof value !== "string" || !value.trim()) throw new Error((currentLocale() === "en" ? `${field} must be a nonempty string.` : `${field}에는 문자열을 입력하세요.`));
@@ -21,11 +20,16 @@ function parseSource(value, field) {
21
20
  return url;
22
21
  }
23
22
 
23
+ // node:url의 domainToASCII와 같은 WHATWG 호스트 해석. 브라우저에서도 동작한다.
24
+ function asciiDomain(input) {
25
+ try { return new URL(`http://${input}`).hostname; } catch { return ""; }
26
+ }
27
+
24
28
  function canonicalDomain(value) {
25
29
  const input = requiredText(value, "domains");
26
- // domainToASCII also accepts some URL delimiters and strips the suffix.
30
+ // The URL parser also accepts some delimiters and strips the suffix.
27
31
  if (/[\s:/@?#%\\]/u.test(input)) throw new Error((currentLocale() === "en" ? `Use hostnames in domains: ${input}` : `domains에는 URL 대신 호스트명을 입력하세요: ${input}`));
28
- const domain = domainToASCII(input).replace(/\.$/, "");
32
+ const domain = asciiDomain(input).replace(/\.$/, "");
29
33
  const labels = domain.split(".");
30
34
  if (domain.length > 253 || labels.length < 2 ||
31
35
  !labels.every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))) {
@@ -70,6 +74,22 @@ function termPattern(term) {
70
74
  return new RegExp(`(?<!${word})${escaped}(?=(?:${particle})?(?!${word}))`, "iu");
71
75
  }
72
76
 
77
+ // 답변을 얻지 못한 시도. 언급률·인용률의 표본에서 제외하고 따로 센다.
78
+ const UNANSWERED = new Set(["failed", "no-answer"]);
79
+
80
+ // 전후 비교의 짝을 맞추는 수집 조건. 형식이 맞지 않는 mode·region·run은 기록하지 않아 "조건 미확인"이 된다.
81
+ function conditions(row, record, field) {
82
+ for (const name of ["model", "locale"]) {
83
+ if (row[name] !== undefined) record[name] = requiredText(row[name], field + "." + name);
84
+ }
85
+ for (const name of ["mode", "region"]) {
86
+ if (typeof row[name] === "string" && row[name].trim()) record[name] = row[name].trim();
87
+ }
88
+ const run = typeof row.run === "string" && /^\d+$/.test(row.run.trim()) ? Number(row.run) : row.run;
89
+ if (Number.isSafeInteger(run) && run >= 1) record.run = run;
90
+ return record;
91
+ }
92
+
73
93
  function wilsonInterval(successes, sampleSize) {
74
94
  if (!sampleSize) return null;
75
95
  const z = 1.959963984540054;
@@ -148,13 +168,26 @@ export function analyzeObservations({ brand, aliases, domains, ownedUrlPrefixes,
148
168
  const rivalRecords = rivals.map(() => []);
149
169
  const citationGaps = [];
150
170
  const engines = new Map();
171
+ const failures = [];
151
172
 
152
- const records = observations.map((row, index) => {
173
+ const records = observations.flatMap((row, index) => {
153
174
  const field = `observations[${index}]`;
154
175
  if (!row || typeof row !== "object" || Array.isArray(row)) throw new Error((currentLocale() === "en" ? `${field} must be an observation object.` : `${field}에는 관측 레코드를 입력하세요.`));
155
176
  const engine = requiredText(row.engine, field + ".engine");
156
177
  const query = requiredText(row.query, field + ".query");
157
178
  const observedAt = observationDate(row.observedAt, field + ".observedAt");
179
+ // failed·no-answer 외의 값은 기존처럼 답변 레코드로 읽는다.
180
+ const status = row.status;
181
+ if (UNANSWERED.has(status)) {
182
+ if (row.answer !== undefined || row.sources !== undefined) {
183
+ throw new Error(t(`${field}: ${status} 시도에는 answer와 sources를 넣지 않습니다. 답변을 받았지만 출처가 없으면 sources: []를 사용하세요.`,
184
+ `${field}: a ${status} attempt must omit answer and sources. For an answer without citations, use sources: [].`));
185
+ }
186
+ const failure = conditions(row, { engine, query, observedAt, status }, field);
187
+ if (row.reason !== undefined) failure.reason = requiredText(row.reason, field + ".reason");
188
+ failures.push(failure);
189
+ return [];
190
+ }
158
191
  const answer = requiredText(row.answer, field + ".answer").normalize("NFKC");
159
192
  // 링크 대상의 호스트·경로에 있는 이름은 답변 본문의 브랜드 언급에서 제외한다.
160
193
  const body = answer.replace(/https?:\/\/[^\s<>()\[\]{}]+/giu, " ");
@@ -165,9 +198,7 @@ export function analyzeObservations({ brand, aliases, domains, ownedUrlPrefixes,
165
198
  }
166
199
  const record = { engine, query, observedAt, ...own.match(body, urls), sources: [...urls.keys()] };
167
200
  if (row.evidenceUrl !== undefined) record.evidenceUrl = parseSource(row.evidenceUrl, field + ".evidenceUrl").href;
168
- for (const name of ["model", "locale"]) {
169
- if (row[name] !== undefined) record[name] = requiredText(row[name], field + "." + name);
170
- }
201
+ conditions(row, record, field);
171
202
  const citedCompetitors = [];
172
203
  rivals.forEach((rival, index) => {
173
204
  const result = rival.match(body, urls);
@@ -181,7 +212,7 @@ export function analyzeObservations({ brand, aliases, domains, ownedUrlPrefixes,
181
212
  const engineKey = engine.normalize("NFKC").toLowerCase();
182
213
  if (!engines.has(engineKey)) engines.set(engineKey, []);
183
214
  engines.get(engineKey).push(record);
184
- return record;
215
+ return [record];
185
216
  });
186
217
 
187
218
  const byEngine = [...engines.values()].map(rows => ({
@@ -189,6 +220,9 @@ export function analyzeObservations({ brand, aliases, domains, ownedUrlPrefixes,
189
220
  }));
190
221
  const summary = summarize(records, own.tracksCitations);
191
222
  const report = { ...summary, byEngine, records };
223
+ if (failures.length) report.failures = failures;
224
+ // 언급·인용 판정에 쓴 설정. 전후 비교에서 같은 판정 기준인지 확인한다.
225
+ if (brandName) report.definition = { brand: brandName, ...own.definition };
192
226
  if (rivals.length) {
193
227
  const brands = [summary, ...rivals.map((rival, index) => summarize(rivalRecords[index], rival.tracksCitations))];
194
228
  const totalMentions = brands.reduce((total, row) => total + row.mentions, 0);
@@ -0,0 +1,35 @@
1
+ // HTML 보고서가 공유하는 이스케이프와 표시 형식.
2
+ import { currentLocale, t } from "./locale.mjs";
3
+
4
+ const escapeChars = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
5
+ const formats = Object.fromEntries(["ko", "en"].map((locale) => {
6
+ const tag = locale === "ko" ? "ko-KR" : "en-US";
7
+ return [locale, {
8
+ percent: new Intl.NumberFormat(tag, { style: "percent", maximumFractionDigits: 1 }),
9
+ number: new Intl.NumberFormat(tag),
10
+ }];
11
+ }));
12
+
13
+ export function number(value) {
14
+ return formats[currentLocale()].number.format(value);
15
+ }
16
+
17
+ export function rateText(rate) {
18
+ return Number.isFinite(rate) ? formats[currentLocale()].percent.format(rate) : t("측정 안 됨", "Not measured");
19
+ }
20
+
21
+ export function html(value) {
22
+ return String(value ?? "").replace(/[&<>"']/g, (char) => escapeChars[char]);
23
+ }
24
+
25
+ export function sourceLink(source) {
26
+ try {
27
+ const url = new URL(source);
28
+ if (["http:", "https:"].includes(url.protocol) && !url.username && !url.password) {
29
+ return `<a href="${html(url.href)}" rel="noreferrer">${html(source)}</a>`;
30
+ }
31
+ } catch {
32
+ // A saved report can also contain a source that is no longer a usable URL.
33
+ }
34
+ return html(source);
35
+ }
@@ -0,0 +1,142 @@
1
+ // 설정 객체와 자료 읽기 함수로 report.json을 만든다. CLI·MCP·웹·확장이 같은 설정 규칙을 쓴다.
2
+ // 브라우저에서도 읽으므로 Node 전용 API를 쓰지 않는다.
3
+ import { currentLocale, t, validateLocale, withLocale } from "./locale.mjs";
4
+ import { analyzeObservations } from "./observations.mjs";
5
+ import { parseSearchPerformance } from "./search-performance.mjs";
6
+ import { parseScope } from "./scope.mjs";
7
+ import { parseBingAiPerformance, parseGoogleAiPerformance } from "./ai-performance.mjs";
8
+ import { parseNaverAdvisor } from "./naver-advisor.mjs";
9
+ import { analyzeUrlInspections, parseUrlInspections } from "./url-inspection.mjs";
10
+ import { parseAiReferrals } from "./ai-referrals.mjs";
11
+
12
+ export const CONFIG_KEYS = ["brand", "aliases", "domains", "ownedUrlPrefixes", "competitors", "targets", "sitemap", "limit", "expectIndexable", "intentionallyExcluded", "observations", "searchConsole", "aiReferrals", "googleAiPerformance", "bingAiPerformance", "naverSearchAdvisor", "urlInspection", "sample", "locale"];
13
+
14
+ // 사이트 지적의 판정 규칙이 바뀌면 올린다. 버전이 다른 보고서의 지적 건수는 비교하지 않는다.
15
+ export const RULESET = 3;
16
+ const isEntry = (value) => typeof value === "string" && Boolean(value.trim());
17
+
18
+ // 페이지 점검 설정의 형식. 페이지를 점검하지 않는 화면에서도 CLI·MCP와 같은 설정을 받고 같은 설정을 거절한다.
19
+ export function checkSiteSettings({ targets = [], limit = 25, expectIndexable = false, intentionallyExcluded = [] }) {
20
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error(t("limit은 1~100 사이 정수여야 합니다.", "limit must be an integer from 1 to 100."));
21
+ if (!Array.isArray(targets)) throw new Error(t("targets는 URL 또는 로컬 HTML 경로의 배열이어야 합니다.", "targets must be an array of URLs or local HTML paths."));
22
+ if (typeof expectIndexable !== "boolean") throw new Error(t("expectIndexable은 true 또는 false여야 합니다.", "expectIndexable must be true or false."));
23
+ if (!Array.isArray(intentionallyExcluded) || !intentionallyExcluded.every(isEntry)) {
24
+ throw new Error(t("intentionallyExcluded는 URL 또는 로컬 HTML 경로의 배열이어야 합니다.", "intentionallyExcluded must be an array of URLs or local HTML paths."));
25
+ }
26
+ }
27
+
28
+ // 설정에서 파일을 가리키는 값. 자료를 직접 올려 받는 화면과 도구가 필요한 파일을 알 수 있게 한다.
29
+ export function configFileReferences(config) {
30
+ const references = [];
31
+ for (const key of ["observations", "aiReferrals", "bingAiPerformance", "naverSearchAdvisor"]) {
32
+ if (typeof config?.[key] === "string") references.push(config[key]);
33
+ }
34
+ for (const key of ["searchConsole", "googleAiPerformance"]) {
35
+ const value = config?.[key];
36
+ const file = typeof value === "string" ? value : value?.file;
37
+ if (typeof file === "string") references.push(file);
38
+ }
39
+ for (const file of [config?.urlInspection ?? []].flat()) {
40
+ if (typeof file === "string") references.push(file);
41
+ }
42
+ return references;
43
+ }
44
+
45
+ /**
46
+ * readText(ref)·readJson(ref): 설정에 적힌 파일 값의 내용을 돌려준다.
47
+ * audit(config, locale): 페이지를 점검해 site 객체를 돌려준다. 점검할 수 없는 환경에서는 생략한다.
48
+ */
49
+ export async function buildReport(config, { lang, ...sources }) {
50
+ return withLocale(lang ?? "ko", () => {
51
+ if (config && Object.hasOwn(config, "locale")) validateLocale(config.locale);
52
+ const locale = lang ?? config?.locale ?? "ko";
53
+ return withLocale(locale, () => collect(config, locale, sources));
54
+ });
55
+ }
56
+
57
+ // 페이지를 점검하지 않는 환경의 site 객체.
58
+ function unauditedSite(config) {
59
+ checkSiteSettings(config);
60
+ if ((config.targets ?? []).some((target) => !isEntry(target))) throw new Error(t("targets 항목에 빈 값이 있습니다.", "targets contains an empty entry."));
61
+ if (config.sitemap !== undefined && !(isEntry(config.sitemap) && /^https?:\/\//i.test(config.sitemap))) {
62
+ throw new Error(t("HTTP(S) 절대 URL을 입력하세요.", "Enter an absolute HTTP(S) URL."));
63
+ }
64
+ const requested = Boolean(config.targets?.length || config.sitemap);
65
+ return {
66
+ ruleset: RULESET, pages: [], limit: config.limit ?? 25, truncated: false, sitemapsRead: 0, discoveryErrors: [],
67
+ warnings: requested ? [t("이 화면에서는 targets·sitemap의 페이지를 점검하지 않았습니다. 페이지 점검과 URL 검사의 현재 선언 대조는 CLI 또는 MCP에서 실행하세요.",
68
+ "Pages in targets and sitemap were not audited here. Run page audits and the comparison with current URL declarations in the CLI or MCP.")] : [],
69
+ };
70
+ }
71
+
72
+ async function collect(config, locale, { readText, readJson, audit, referrals }) {
73
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(t("설정은 JSON 객체여야 합니다.", "Config must be a JSON object."));
74
+ const keys = new Set(CONFIG_KEYS);
75
+ for (const key of Object.keys(config)) {
76
+ if (!keys.has(key)) throw new Error((currentLocale() === "en" ? `Unknown config setting: ${key}` : `알 수 없는 설정: ${key}`));
77
+ }
78
+ if (config.sample !== undefined && typeof config.sample !== "boolean") throw new Error(t("sample은 true 또는 false여야 합니다.", "sample must be true or false."));
79
+ const observations = typeof config.observations === "string" ? await readJson(config.observations) : config.observations;
80
+ const ai = analyzeObservations({
81
+ brand: config.brand, aliases: config.aliases, domains: config.domains,
82
+ ownedUrlPrefixes: config.ownedUrlPrefixes, competitors: config.competitors, observations,
83
+ });
84
+ // CSV 입력은 경로 문자열 또는 { file, ...조회 조건 } 객체로 받는다.
85
+ async function csvInput(value, message) {
86
+ const { file, ...settings } = typeof value === "string" ? { file: value } : value && typeof value === "object" && !Array.isArray(value) ? value : {};
87
+ if (typeof file !== "string" || !file.trim()) throw new Error(message);
88
+ return { text: await readText(file), settings };
89
+ }
90
+ async function jsonInput(value, name) {
91
+ if (typeof value !== "string" || !value.trim()) throw new Error(t(`${name}에는 JSON 파일 경로가 필요합니다.`, `${name} must be a JSON file path.`));
92
+ return readJson(value);
93
+ }
94
+ let searchPerformance = null;
95
+ if (config.searchConsole !== undefined) {
96
+ const { text, settings } = await csvInput(config.searchConsole, t("searchConsole에는 CSV 파일 경로가 필요합니다.", "searchConsole must be a CSV file path."));
97
+ searchPerformance = parseSearchPerformance(text);
98
+ if (Object.keys(settings).length) searchPerformance.scope = parseScope(settings, "searchConsole");
99
+ }
100
+ let google = null;
101
+ if (config.googleAiPerformance !== undefined) {
102
+ const { text, settings } = await csvInput(config.googleAiPerformance, t("googleAiPerformance에는 CSV 파일 경로가 필요합니다.", "googleAiPerformance must be a CSV file path."));
103
+ google = parseGoogleAiPerformance(text, settings);
104
+ }
105
+ const bing = config.bingAiPerformance === undefined ? null
106
+ : parseBingAiPerformance(await jsonInput(config.bingAiPerformance, "bingAiPerformance"));
107
+ const aiPerformance = google || bing ? { google, bing } : null;
108
+ const naver = config.naverSearchAdvisor === undefined ? null
109
+ : parseNaverAdvisor(await jsonInput(config.naverSearchAdvisor, "naverSearchAdvisor"));
110
+ let inspections = null;
111
+ if (config.urlInspection !== undefined) {
112
+ const files = [config.urlInspection].flat();
113
+ if (!files.length) throw new Error(t("urlInspection에는 JSON 파일 경로가 필요합니다.", "urlInspection must be a JSON file path."));
114
+ inspections = [];
115
+ for (const file of files) inspections.push(...parseUrlInspections(await jsonInput(file, "urlInspection"), file));
116
+ }
117
+ // referrals: 명령행처럼 설정 밖에서 지정한 AI 유입 자료의 파일 값. 설정의 aiReferrals보다 우선한다.
118
+ const referralFile = referrals ?? config.aiReferrals;
119
+ let aiReferrals = null;
120
+ if (referralFile !== undefined) {
121
+ if (typeof referralFile !== "string" || !referralFile.trim()) {
122
+ throw new Error(t("AI 유입 자료의 파일 경로를 지정하세요.", "Specify a file path for AI referrals."));
123
+ }
124
+ aiReferrals = parseAiReferrals(await readText(referralFile));
125
+ }
126
+ const site = audit ? await audit(config, locale) : unauditedSite(config);
127
+ const requested = audit && config.sitemap;
128
+ if (!site.pages.length && !site.crawl && !requested && !ai.sampleSize && !ai.failures && !searchPerformance && !aiReferrals &&
129
+ !aiPerformance && !naver && !inspections?.length) {
130
+ if (!audit && (config.targets?.length || config.sitemap)) {
131
+ throw new Error(t("targets·sitemap의 페이지는 이 화면에서 점검할 수 없습니다. 자료 파일을 추가하거나 CLI 또는 MCP에서 실행하세요.",
132
+ "Pages in targets and sitemap cannot be audited here. Add a data file, or run this config in the CLI or MCP."));
133
+ }
134
+ throw new Error(t("targets, sitemap, observations, searchConsole, aiReferrals, googleAiPerformance, bingAiPerformance, naverSearchAdvisor 또는 urlInspection 중 점검할 자료를 지정하세요.",
135
+ "Specify at least one input: targets, sitemap, observations, searchConsole, aiReferrals, googleAiPerformance, bingAiPerformance, naverSearchAdvisor or urlInspection."));
136
+ }
137
+ return {
138
+ schemaVersion: 1, locale, generatedAt: new Date().toISOString(), brand: config.brand || "", sample: config.sample === true, site, searchPerformance, ai,
139
+ ...(aiReferrals && { aiReferrals }), ...(aiPerformance && { aiPerformance }), ...(naver && { naverSearchAdvisor: naver }),
140
+ ...(inspections && { urlInspection: analyzeUrlInspections(inspections, site.pages) }),
141
+ };
142
+ }