search-visibility 1.2.0 → 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 +43 -0
  2. package/README.es.md +39 -3
  3. package/README.ja.md +39 -3
  4. package/README.ko.md +47 -10
  5. package/README.md +47 -10
  6. package/README.zh.md +39 -3
  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 +203 -263
  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,202 @@
1
+ // 운영자가 제공한 검색 콘솔 자료(Google URL 검사, AI 실적, 네이버 단계)의 HTML 섹션.
2
+ import { t } from "./locale.mjs";
3
+ import { html, number, rateText, sourceLink } from "./report-html.mjs";
4
+ import { comparableValue, describeReason, fieldLabel, periodText, statusLabel, valueText } from "./scope.mjs";
5
+ import { comparisonText, inspectionStatusText } from "./url-inspection.mjs";
6
+ import { actionText, stageName } from "./naver-advisor.mjs";
7
+
8
+ const notProvided = () => t("미제공", "Not provided");
9
+ const notRecorded = () => t("미기록", "Not recorded");
10
+ // 실제 0과 값이 없는 상태를 구분해 표시한다.
11
+ const amount = (value, missing = notRecorded) => (value === null || value === undefined ? missing() : number(value));
12
+
13
+ function table(caption, headings, rows) {
14
+ // 좁은 화면에서는 단어 중간에서 끊지 않고 표 안에서 가로로 스크롤한다.
15
+ return `<div class="scroll" tabindex="0" role="region" aria-label="${html(caption)}"><table><caption>${html(caption)}</caption><thead><tr>${headings.map((heading) => `<th scope="col">${html(heading)}</th>`).join("")}</tr></thead>
16
+ <tbody>${rows.map(([first, ...rest]) => `<tr><th scope="row">${first}</th>${rest.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`;
17
+ }
18
+
19
+ export function scopeTable(caption, scope) {
20
+ const fields = ["property", "reportType", "searchType", "aggregation", "timeZone", "filters", "period", "recordedAt"];
21
+ return table(caption, [t("조회 조건", "Condition"), t("값", "Value")],
22
+ fields.map((field) => [html(fieldLabel(field)), html(valueText(field, scope?.[field] ?? null))]));
23
+ }
24
+
25
+ // 검색 유형이 기록됐고 웹이 아니면 false, 기록이 없으면 null.
26
+ const isWebSearch = (scope) => (scope?.searchType ? /^(?:web\b|웹|ウェブ|网页|網頁)/i.test(scope.searchType) : null);
27
+
28
+ function sameRange(web, ai) {
29
+ if (isWebSearch(web) === false) {
30
+ return t(`가져온 CSV는 웹 검색 유형이 아닌 ${web.searchType} 자료이므로 생성형 AI 노출과 같은 범위가 아닙니다.`, `The imported CSV covers ${web.searchType}, not the Web search type, so it is not the same scope as generative AI impressions.`);
31
+ }
32
+ const fields = ["property", "timeZone", "filters", "period", "searchType"];
33
+ // 전후 비교와 같은 정규화로 값을 대조한다.
34
+ const value = (scope, field) => {
35
+ if (field === "period") return scope?.period?.complete === true ? `${scope.period.start}/${scope.period.end}` : null;
36
+ const raw = scope?.[field] ?? null;
37
+ if (raw === null) return null;
38
+ return field === "searchType" && isWebSearch(scope) && /^(?:web|웹|ウェブ|网页|網頁)$/i.test(raw) ? "web" : comparableValue(field, raw);
39
+ };
40
+ const unknown = fields.filter((field) => value(web, field) === null || value(ai, field) === null);
41
+ const differing = fields.filter((field) => !unknown.includes(field) && value(web, field) !== value(ai, field));
42
+ if (!unknown.length && !differing.length) {
43
+ return t("웹 검색과 생성형 AI 자료의 속성·기간·시간대·필터·검색 유형 기록이 같습니다. 차원과 집계 단위는 대조하지 않습니다.",
44
+ "The Web search and generative AI records share the same property, period, time zone, filters and search type. Dimensions and aggregation are not compared.");
45
+ }
46
+ const names = (list) => list.map((field) => (field === "period" ? `${fieldLabel(field)}(${t("완료된 기간", "completed")})` : fieldLabel(field))).join(", ");
47
+ return [
48
+ t("웹 검색 총노출과 생성형 AI 노출의 범위가 같은지 확인되지 않았습니다.", "The Web search and generative AI records are not confirmed to cover the same scope."),
49
+ differing.length ? `${t("다름", "Different")}: ${names(differing)}` : "",
50
+ unknown.length ? `${t("미기록", "Not recorded")}: ${names(unknown)}` : "",
51
+ ].filter(Boolean).join(" · ");
52
+ }
53
+
54
+ export function aiPerformanceSection(performance, searchPerformance, ai) {
55
+ if (!performance) return "";
56
+ const { google, bing } = performance;
57
+ const period = (scope) => `${t("조회 기간", "Period")} ${periodText(scope?.period)}`;
58
+ const rows = [];
59
+ const dimensions = { page: t("페이지", "Page"), country: t("국가", "Country"), device: t("기기", "Device"), date: t("날짜", "Date") };
60
+ if (google) {
61
+ const name = t("Google 생성형 AI 실적(검색)", "Google generative AI performance (Search)");
62
+ rows.push(
63
+ [name, t("속성 전체 노출수(차트 합계)", "Property-wide impressions (chart total)"), amount(google.totalImpressions, notProvided), t("노출", "Impressions"), html(period(google.scope))],
64
+ [name, t("가져온 표의 행 합계", "Sum of imported table rows"), amount(google.rowImpressions, notProvided), t("노출", "Impressions"),
65
+ html(t(`${dimensions[google.dimension]}별 ${google.rowCount}행(값 없음 ${google.rowsWithoutImpressions}행). 속성 전체 합계와 집계 단위가 다를 수 있음`,
66
+ `${google.rowCount} ${google.dimension} rows (${google.rowsWithoutImpressions} without a value). Aggregation can differ from the property total`))],
67
+ [name, t("클릭수", "Clicks"), notProvided(), t("클릭", "Clicks"), "—"],
68
+ [name, "CTR", notProvided(), "%", "—"],
69
+ );
70
+ }
71
+ if (searchPerformance) {
72
+ const web = isWebSearch(searchPerformance.scope);
73
+ const relation = web === false
74
+ ? t(`검색 유형 ${searchPerformance.scope.searchType}: 웹 검색 유형이 아닌 합계이며 생성형 AI 노출과 더하지 않음`, `Search type ${searchPerformance.scope.searchType}: not a Web search total; not added to generative AI impressions`)
75
+ : web ? t("웹 검색 유형의 합계에는 AI 기능 노출이 포함되므로 생성형 AI 노출과 더하지 않음", "Web search totals include AI feature impressions, so they are not added to generative AI impressions")
76
+ : t("검색 유형 미기록. 웹 검색 유형의 합계라면 AI 기능 노출이 이미 포함되므로 생성형 AI 노출과 더하지 않음", "Search type not recorded. A Web search total already includes AI feature impressions, so it is not added to generative AI impressions");
77
+ const dimension = { page: t("페이지", "page"), query: t("검색어", "query"), date: t("날짜", "date") }[searchPerformance.dimension] ?? searchPerformance.dimension;
78
+ const sum = t(`가져온 CSV의 ${dimension}별 ${searchPerformance.rowCount}행 합계이며 속성 전체(차트) 합계와 다를 수 있음`,
79
+ `Sum of ${searchPerformance.rowCount} ${dimension} rows in the imported CSV; it can differ from the property chart total`);
80
+ rows.push([t("Google 검색 결과 실적(가져온 CSV)", "Google Search results performance (imported CSV)"), t("총노출수", "Total impressions"),
81
+ searchPerformance.rowCount ? number(searchPerformance.impressions) : t("미제공(집계할 행 없음)", "Not provided (no rows)"), t("노출", "Impressions"),
82
+ html(`${sum}. ${relation}`)]);
83
+ }
84
+ if (bing) {
85
+ const name = "Bing AI Performance";
86
+ rows.push([name, "Total Citations", amount(bing.totalCitations, notProvided), t("인용", "Citations"), html(`${period(bing.scope)} · ${t("선택 기간의 전체 인용", "All citations in the selected period")}`)]);
87
+ for (const entry of bing.citationShare) {
88
+ const scope = html(`${t("분모: 해당 grounding query에서 모든 사이트에 귀속된 인용", "Denominator: citations attributed to all sites for this grounding query")} · ${period(entry)} · ${fieldLabel("filters")} ${valueText("filters", entry.filters)}`);
89
+ const label = `Citation Share · ${html(entry.groundingQuery)}`;
90
+ rows.push([name, label, entry.shareText === null ? notProvided() : html(entry.shareText), "%", scope]);
91
+ if (entry.citations !== null) rows.push([name, `${t("인용 수", "Citations")} · ${html(entry.groundingQuery)}`, number(entry.citations), t("인용", "Citations"), html(period(entry))]);
92
+ }
93
+ }
94
+ rows.push([t("직접 수집한 답변", "Directly observed answers"), t("소유 출처 인용률", "Owned-source citation rate"),
95
+ ai.citationRate === null || ai.citationRate === undefined ? t("측정 안 됨", "Not measured") : `${rateText(ai.citationRate)} (${number(ai.citations)}/${number(ai.sampleSize)})`, "%",
96
+ html(t(`분모: 관측 답변 ${ai.sampleSize}건. 분자: 소유 URL을 한 번 이상 인용한 답변`, `Denominator: ${ai.sampleSize} observed answers. Numerator: answers citing an owned URL at least once`))]);
97
+ const [heading, ...columns] = [t("출처", "Source"), t("지표", "Metric"), t("값", "Value"), t("단위", "Unit"), t("분모·범위", "Denominator and scope")];
98
+ const googleRows = google ? google.rows.slice(0, 10) : [];
99
+ return `<section aria-labelledby="ai-performance"><h2 id="ai-performance">${t("출처별 AI 노출·인용", "AI impressions and citations by source")}</h2>
100
+ <p>${t("출처마다 단위와 분모가 다르므로 값을 합치거나 서로 나누지 않습니다.", "Units and denominators differ by source, so values are neither added nor divided across sources.")}</p>
101
+ ${table(t("출처별 지표", "Metrics by source"), [heading, ...columns], rows.map(([source, ...rest]) => [html(source), ...rest]))}
102
+ ${google && searchPerformance?.rowCount ? `<p class="note">${html(sameRange(searchPerformance.scope, google.scope))}</p>` : ""}
103
+ ${google ? `${googleRows.length ? table(t(`생성형 AI 노출 상위 ${googleRows.length}행`, `Top ${googleRows.length} rows by generative AI impressions`),
104
+ [dimensions[google.dimension], t("노출수", "Impressions")], googleRows.map((row) => [html(row.label), amount(row.impressions, notProvided)])) : ""}
105
+ <p class="note">${t("Search Console 내보내기는 화면의 ‘~’, ‘-’ 값을 0으로 저장할 수 있습니다. 0의 의미가 중요하면 화면에서 확인하세요.", "Search Console exports can store on-screen “~” or “-” values as 0. Check the interface when the meaning of a zero matters.")}</p>
106
+ ${scopeTable(t("Google 생성형 AI 조회 조건", "Google generative AI query conditions"), google.scope)}` : ""}
107
+ ${bing ? scopeTable(t("Bing AI Performance 조회 조건", "Bing AI Performance query conditions"), bing.scope) : ""}</section>`;
108
+ }
109
+
110
+ export function naverSection(naver) {
111
+ if (!naver) return "";
112
+ const meta = (entry) => [html(entry.report), html(periodText(entry.period)), html(entry.updatedAt ?? notRecorded()), html(entry.device ?? notRecorded()), html(entry.aggregation ?? notRecorded())];
113
+ const headings = [t("보고서 이름", "Report"), t("조회 기간", "Period"), t("업데이트 기준일", "Updated as of"), t("기기", "Device"), t("집계 단위", "Aggregation")];
114
+ const missing = (stage) => `<p class="notice">${stageName(stage)}: ${t("미수집", "Not collected")}</p>`;
115
+ const crawl = naver.crawl.length
116
+ ? table(t("수집 오류 기록", "Crawl error records"), [...headings, t("오류 유형", "Error type"), t("건수", "Count")],
117
+ naver.crawl.flatMap((entry) => entry.errors.map((error) => [...meta(entry), html(error.type), amount(error.count)])))
118
+ : missing("crawl");
119
+ const trends = naver.trends.map((trend) => `<h4>${html(trend.report)} · ${html(trend.device ?? notRecorded())}</h4>
120
+ <p><strong>${html(statusLabel(trend.status))}</strong>${trend.reasons.length ? ` — ${trend.reasons.map((reason) => html(describeReason(reason))).join(" · ")}` : ""}</p>
121
+ ${table(t("오류 추이", "Error trend"), [t("오류 유형", "Error type"), `${t("이전", "Previous")} (${periodText(trend.previous?.period)})`, `${t("최근", "Latest")} (${periodText(trend.latest.period)})`, t("증감", "Change")],
122
+ trend.errors.map((error) => [html(error.type), amount(error.before), amount(error.after), error.delta === null ? "—" : `${error.delta > 0 ? "+" : ""}${number(error.delta)}`]))}`).join("");
123
+ const index = naver.index.length
124
+ ? table(t("색인 지표", "Index metrics"), [...headings, t("화면의 지표 이름", "Metric name on screen"), t("값", "Value")],
125
+ naver.index.flatMap((entry) => entry.metrics.map((metric) => [...meta(entry), html(metric.name), amount(metric.value)])))
126
+ : missing("index");
127
+ const web = naver.webSearch.length
128
+ ? table(t("웹 검색 노출·클릭", "Web search impressions and clicks"), [...headings, t("노출수", "Impressions"), t("클릭수", "Clicks")],
129
+ naver.webSearch.map((entry) => [...meta(entry), amount(entry.impressions), amount(entry.clicks)]))
130
+ : missing("webSearch");
131
+ return `<section aria-labelledby="naver"><h2 id="naver">${t("네이버 서치어드바이저 단계별 현황", "Naver Search Advisor by stage")}</h2>
132
+ <p>${html(naver.site)}</p>
133
+ <h3>${t("다음에 확인할 것", "Next checks")}</h3><ul>${naver.actions.map((action) => `<li>${html(actionText(action))}</li>`).join("")}</ul>
134
+ <p class="note">${t("단계마다 대상과 기준일이 달라 단계 간 전환율을 계산하지 않습니다. 웹 검색 지표에는 VIEW·블로그·검색 광고가 포함되지 않으며, AI 브리핑 직접 관측은 AI 답변 관측에서 따로 집계합니다.",
135
+ "Each stage has its own population and reference date, so no stage-to-stage conversion is calculated. Web search metrics exclude VIEW, blog and ad areas. Observed AI Briefing answers are tallied separately under AI answer observations.")}</p>
136
+ <h3>${stageName("crawl")}</h3>${crawl}${trends}
137
+ <h3>${stageName("index")}</h3>${index}
138
+ <h3>${stageName("webSearch")}</h3>${web}</section>`;
139
+ }
140
+
141
+ function inspectionDetails(record) {
142
+ const { index, current, comparisons } = record;
143
+ const value = (entry) => (entry ? html(entry) : notRecorded());
144
+ const declared = (entries) => (!current.observed || current.reason ? t("미관측", "Not observed")
145
+ : entries.length ? entries.map(({ url, href }) => (url ? sourceLink(url) : `${html(href)} (${t("해석 불가", "unresolved")})`)).join("<br>") : t("선언 없음", "None declared"));
146
+ const note = !current.observed
147
+ ? (current.reason === "fetch-error" ? `${t("현재 페이지 수집 실패", "The current page could not be fetched")}: ${html(current.error)}` : t("이번 실행에서 이 URL을 점검하지 않아 저장된 검사 결과만 표시합니다.", "This URL was not audited in this run, so only the saved inspection is shown."))
148
+ : `${t("현재 응답", "Current response")}: HTTP ${html(current.status)}${current.reason === "redirect" ? ` · ${t("리다이렉트 대상", "Redirected to")} ${sourceLink(current.finalUrl)}` : ""}${current.checkedAt ? ` · <time>${html(current.checkedAt)}</time>` : ""}`;
149
+ return `<details open><summary>${html(record.inspectionUrl)} <small>· ${html(inspectionStatusText(record.status))}</small></summary>
150
+ <p>${note}</p>
151
+ ${record.indexFlags?.length ? `<p class="notice">${t("확인할 색인 상태", "Index state to check")}: ${record.indexFlags.map(({ field, value }) =>
152
+ `<code>${html(field === "currentNoindex" ? t("현재 noindex", "current noindex") : field)}</code> ${html(value)}`).join(" · ")}</p>` : ""}
153
+ ${table("canonical", [t("출처", "Source"), "URL"], [
154
+ [t("Google이 선택한 canonical (googleCanonical)", "Google-selected canonical (googleCanonical)"), value(index.googleCanonical)],
155
+ [t("Google 수집 당시 사용자 선언 (userCanonical)", "User-declared canonical at crawl time (userCanonical)"), value(index.userCanonical)],
156
+ [t("현재 HTML <head>", "Current HTML <head>"), declared(current.html)],
157
+ [t("현재 HTTP Link 헤더", "Current HTTP Link header"), declared(current.header)],
158
+ ])}
159
+ ${table(t("대조 결과", "Comparisons"), [t("비교", "Comparison"), t("결과", "Result")], [
160
+ [t("배포 후 재수집", "Recrawl after deployment"), html(comparisonText(comparisons.recrawl))],
161
+ [t("현재 선언 ↔ Google 선택", "Current declaration ↔ Google selection"), html(comparisonText(comparisons.currentVsGoogle))],
162
+ [t("수집 당시 선언 ↔ Google 선택", "Declaration at crawl ↔ Google selection"), html(comparisonText(comparisons.userVsGoogle))],
163
+ [t("현재 선언 ↔ 수집 당시 선언", "Current declaration ↔ declaration at crawl"), html(comparisonText(comparisons.currentVsUser))],
164
+ ])}
165
+ ${table(t("색인 검사 값", "Index status values"), [t("항목", "Field"), t("값", "Value")], [
166
+ [t("배포 시각", "Deployed at"), value(record.deployedAt)],
167
+ [t("마지막 크롤링", "Last crawl"), value(index.lastCrawlTime)],
168
+ [t("검사 시각", "Inspected at"), value(record.inspectedAt)],
169
+ ...["verdict", "coverageState", "pageFetchState", "indexingState", "robotsTxtState", "crawledAs"].map((key) => [`<code>${key}</code>`, value(index[key])]),
170
+ ])}</details>`;
171
+ }
172
+
173
+ export function inspectionSection(records) {
174
+ if (!records) return "";
175
+ return `<section aria-labelledby="url-inspection"><h2 id="url-inspection">${t("Google URL 검사 대조", "Google URL Inspection comparison")}</h2>
176
+ <p>${t("URL Inspection API 값은 Google 색인에 있는 버전의 정보이며 실시간 테스트가 아닙니다. 현재 선언은 이번 점검 시점의 응답입니다.",
177
+ "URL Inspection API values describe the version in the Google index, not a live test. Current declarations come from the response fetched in this run.")}</p>
178
+ ${records.map(inspectionDetails).join("")}</section>`;
179
+ }
180
+
181
+ export function sourceLinks(report) {
182
+ return [
183
+ report.aiPerformance && ["ai-performance", t("AI 실적", "AI performance")],
184
+ report.naverSearchAdvisor && ["naver", t("네이버 단계", "Naver stages")],
185
+ report.urlInspection && ["url-inspection", t("URL 검사", "URL Inspection")],
186
+ ].filter(Boolean).map(([id, label]) => `<a href="#${id}">${html(label)}</a>`).join("");
187
+ }
188
+
189
+ export function summaryLines(report) {
190
+ const { aiPerformance, urlInspection, naverSearchAdvisor } = report;
191
+ const lines = [];
192
+ if (urlInspection) {
193
+ lines.push(`${t(`URL 검사 ${urlInspection.length}건`, `URL inspections: ${urlInspection.length}`)} · ${urlInspection.map((r) => inspectionStatusText(r.status)).join(" / ")}`);
194
+ }
195
+ if (aiPerformance?.google) {
196
+ const { totalImpressions, rowImpressions } = aiPerformance.google;
197
+ lines.push(`${t("Google 생성형 AI 노출", "Google generative AI impressions")} · ${t("속성 합계", "property total")} ${amount(totalImpressions, notProvided)} · ${t("행 합계", "row sum")} ${amount(rowImpressions, notProvided)}`);
198
+ }
199
+ if (aiPerformance?.bing) lines.push(`Bing AI Performance · Total Citations ${amount(aiPerformance.bing.totalCitations, notProvided)} · Citation Share ${aiPerformance.bing.citationShare.length}${t("개 질의", " queries")}`);
200
+ if (naverSearchAdvisor) lines.push(`${t("네이버 서치어드바이저", "Naver Search Advisor")} · ${naverSearchAdvisor.actions.map(actionText).join(" / ")}`);
201
+ return lines;
202
+ }
@@ -0,0 +1,270 @@
1
+ // robots.txt 판정 — CLI·웹·확장이 같은 입력에 같은 결과를 내도록 의존성 없이 작성한다.
2
+ // 브라우저 확장은 이 파일의 사본(extension/robots.mjs)을 읽는다. 수정하면 `npm run sync:extension`.
3
+
4
+ // 모든 채널이 점검하는 크롤러. level은 차단했을 때의 지적 수준이며 INFO는 문제로 세지 않는다.
5
+ const crawler = (agent, role, level, skill, ko, en, note = "") => ({ agent, role, level, skill, ko, en, note });
6
+ export const CRAWLERS = [
7
+ crawler("Googlebot", "search", "FAIL", "google-search", "Google 검색", "Google Search", "Brave Search·Applebot도 Googlebot 규칙에 영향받음"),
8
+ crawler("Yeti", "search", "FAIL", "naver-search", "네이버 검색", "Naver Search"),
9
+ crawler("Daum", "search", "FAIL", "daum-search", "다음 검색", "Daum Search"),
10
+ crawler("Bingbot", "search", "FAIL", "other-search-engines", "Bing 검색", "Bing Search", "DuckDuckGo 일반 결과도 대부분 Bing 기반"),
11
+ crawler("Applebot", "search", "WARN", "other-search-engines", "Apple 검색", "Apple Search", "Safari·Spotlight·Siri"),
12
+ crawler("DuckDuckBot", "search", "WARN", "other-search-engines", "DuckDuckGo 검색", "DuckDuckGo Search"),
13
+ crawler("OAI-SearchBot", "ai-search", "WARN", "ai-crawlers", "ChatGPT 검색", "ChatGPT Search", "ChatGPT 검색 답변에서 빠짐"),
14
+ crawler("ChatGPT-User", "ai-user", "WARN", "ai-crawlers", "ChatGPT 사용자 요청", "ChatGPT User Requests", "ChatGPT 사용자 요청 열람 불가"),
15
+ crawler("Claude-SearchBot", "ai-search", "WARN", "ai-crawlers", "Claude 검색", "Claude Search", "Claude 검색 품질용 색인에서 빠짐"),
16
+ crawler("Claude-User", "ai-user", "WARN", "ai-crawlers", "Claude 사용자 요청", "Claude User Requests", "Claude 사용자 요청 열람 불가"),
17
+ crawler("PerplexityBot", "ai-search", "WARN", "ai-crawlers", "Perplexity 검색", "Perplexity Search", "Perplexity 검색에서 빠짐"),
18
+ crawler("Perplexity-User", "ai-user", "WARN", "ai-crawlers", "Perplexity 사용자 요청", "Perplexity User Requests", "Perplexity 사용자 요청(대체로 robots 무시)"),
19
+ crawler("meta-webindexer", "ai-search", "WARN", "ai-crawlers", "Meta AI 검색", "Meta AI Search", "Meta AI 검색 인용에서 빠짐"),
20
+ crawler("MistralAI-Index", "ai-search", "WARN", "ai-crawlers", "Mistral 검색", "Mistral Search", "Mistral 검색에서 빠짐"),
21
+ crawler("MistralAI-User", "ai-user", "WARN", "ai-crawlers", "Mistral 사용자 요청", "Mistral User Requests", "Mistral 사용자 요청 열람 불가"),
22
+ crawler("Google-Extended", "ai-grounding", "WARN", "ai-crawlers", "Gemini 그라운딩·학습", "Gemini Grounding/Training", "Gemini 앱·Vertex AI의 Google 검색 그라운딩에서 빠짐(Google 검색 자체엔 영향 없음)"),
23
+ crawler("GPTBot", "ai-training", "INFO", "ai-crawlers", "OpenAI 학습", "OpenAI Training", "OpenAI 학습 제외"),
24
+ crawler("ClaudeBot", "ai-training", "INFO", "ai-crawlers", "Anthropic 학습", "Anthropic Training", "Anthropic 학습 제외"),
25
+ crawler("Applebot-Extended", "ai-training", "INFO", "ai-crawlers", "Apple 학습", "Apple Training", "Apple 생성형 모델 학습 제외"),
26
+ crawler("meta-externalagent", "ai-training", "INFO", "ai-crawlers", "Meta 학습", "Meta Training", "Meta 학습 제외"),
27
+ crawler("MistralAI-Training", "ai-training", "INFO", "ai-crawlers", "Mistral 학습", "Mistral Training", "Mistral 학습 제외"),
28
+ crawler("__usage_ai-training", "ai-training", "INFO", "ai-crawlers", "Microsoft AI 학습", "Microsoft AI Training", "Microsoft AI 학습 제외(2027-02-01부터 반영)"),
29
+ crawler("TelegramBot", "social", "WARN", "social-preview", "텔레그램 미리보기", "Telegram Preview", "Telegram 링크 미리보기"),
30
+ crawler("Discordbot", "social", "WARN", "social-preview", "디스코드 임베드", "Discord Embed", "Discord 임베드 미리보기"),
31
+ crawler("facebookexternalhit", "social", "FAIL", "social-preview", "Threads · Meta 공유", "Threads / Meta Share", "Meta 링크 미리보기"),
32
+ crawler("Twitterbot", "social", "FAIL", "social-preview", "X (Twitter) 카드", "X / Twitter Card", "X 카드"),
33
+ crawler("Slackbot-LinkExpanding", "social", "WARN", "social-preview", "Slack 링크 미리보기", "Slack Unfurl", "Slack 링크 미리보기"),
34
+ crawler("LinkedInBot", "social", "WARN", "social-preview", "LinkedIn 공유", "LinkedIn Share", "LinkedIn 공유 미리보기"),
35
+ ];
36
+
37
+ // 지정한 용도의 봇 중 차단된 봇과 그 지적 수준. INFO 봇(학습용)은 문제로 세지 않는다.
38
+ // privatePage: 색인 대상으로 지정하지 않은 noindex 페이지. User-agent: * 차단은 지적하지 않고 공개 의도 확인 대상으로 따로 돌려준다.
39
+ export function blockedCrawlers(evaluated, roles, { privatePage = false } = {}) {
40
+ const blocked = evaluated.filter((bot) => roles.includes(bot.role) && bot.level !== "INFO" && bot.decision === "blocked");
41
+ const counted = privatePage ? blocked.filter((bot) => bot.via !== "*") : blocked;
42
+ return {
43
+ agents: counted.map((bot) => bot.agent), level: counted.some((bot) => bot.level === "FAIL") ? "FAIL" : counted.length ? "WARN" : null,
44
+ privateAgents: blocked.filter((bot) => !counted.includes(bot)).map((bot) => bot.agent),
45
+ };
46
+ }
47
+
48
+ export function describePrivateAccess(agents, locale) {
49
+ return pick(locale, `User-agent: * 규칙으로 차단: ${agents.join(", ")}. 페이지에도 noindex가 있어 공개 의도 확인 필요`,
50
+ `Blocked by the User-agent: * rules: ${agents.join(", ")}. The page also declares noindex. Confirm whether it should be public`);
51
+ }
52
+
53
+ // Google 문서: robots.txt는 500KiB까지 읽고 그 뒤의 내용은 무시한다. 모든 채널이 같은 범위를 판정한다.
54
+ export const ROBOTS_BYTES = 500 * 1024;
55
+
56
+ function limitRobots(text) {
57
+ const bytes = new TextEncoder().encode(text);
58
+ if (bytes.length <= ROBOTS_BYTES) return { text, truncated: false };
59
+ const head = new TextDecoder().decode(bytes.subarray(0, ROBOTS_BYTES));
60
+ // 상한에 걸려 잘린 마지막 줄은 규칙으로 읽지 않는다.
61
+ return { text: head.slice(0, Math.max(head.lastIndexOf("\n"), head.lastIndexOf("\r")) + 1), truncated: true };
62
+ }
63
+
64
+ // "googlebot/1.2", "googlebot*" 같은 표기는 제품 토큰만 비교한다.
65
+ // 외부 파일의 긴 줄에도 선형 시간으로 처리하도록 문자열 연산을 쓴다.
66
+ function agentToken(value) {
67
+ const token = value.toLowerCase();
68
+ const slash = token.indexOf("/", 1);
69
+ if (slash > 0) return token.slice(0, slash);
70
+ let end = token.length;
71
+ while (end > 1 && token[end - 1] === "*") end--;
72
+ return token.slice(0, end);
73
+ }
74
+
75
+ export function parseRobots(text) {
76
+ const groups = [];
77
+ const sitemaps = [];
78
+ let current = null;
79
+ for (const raw of String(text ?? "").split(/\r\n|\r|\n/)) {
80
+ const comment = raw.indexOf("#");
81
+ const match = (comment < 0 ? raw : raw.slice(0, comment)).trim().match(/^([a-zA-Z-]+)\s*:(.*)$/s);
82
+ if (!match) continue;
83
+ const key = match[1].toLowerCase();
84
+ const value = match[2].trim();
85
+ if (key === "user-agent") {
86
+ if (!current || current.rules.length) {
87
+ current = { agents: [], rules: [] };
88
+ groups.push(current);
89
+ }
90
+ current.agents.push(agentToken(value));
91
+ } else if ((key === "allow" || key === "disallow") && current) current.rules.push({ type: key, path: value });
92
+ else if (key === "sitemap" && value) sitemaps.push(value);
93
+ }
94
+ return { groups, sitemaps };
95
+ }
96
+
97
+ // RFC 9309: 비 ASCII는 UTF-8 퍼센트 인코딩으로, 인코딩된 비예약 ASCII는 원래 문자로 비교한다.
98
+ // %2F 같은 예약 문자는 /와 다르며, 유니코드 경로의 대소문자도 보존한다.
99
+ export function normalizeRobotsPath(path) {
100
+ return path.replace(/%[\da-f]{2}|[^\x21-\x7e]/giu, (part) => {
101
+ if (!part.startsWith("%")) return encodeURIComponent(part);
102
+ const char = String.fromCharCode(parseInt(part.slice(1), 16));
103
+ return /[a-zA-Z0-9._~-]/.test(char) ? char : part.toUpperCase();
104
+ });
105
+ }
106
+
107
+ // 규칙은 경로와 쿼리에 적용한다. 프래그먼트는 요청에 포함되지 않는다.
108
+ export function robotsPathFor(url) {
109
+ const parsed = new URL(url);
110
+ return parsed.pathname + parsed.search;
111
+ }
112
+
113
+ // 앞에서부터 일치시키고, * 사이의 리터럴은 순서대로 찾는다. 마지막 $는 쿼리를 포함한 URL 끝을 뜻한다.
114
+ function matchesRobotsPath(pattern, path) {
115
+ const exact = pattern.endsWith("$");
116
+ const pieces = (exact ? pattern.slice(0, -1) : pattern).split("*");
117
+ const first = pieces.shift();
118
+ if (!path.startsWith(first)) return false;
119
+ if (!pieces.length) return !exact || path.length === first.length;
120
+
121
+ const last = exact ? pieces.pop() : "";
122
+ if (!path.endsWith(last)) return false;
123
+ let cursor = first.length;
124
+ for (const piece of pieces) {
125
+ const found = path.indexOf(piece, cursor);
126
+ if (found < 0) return false;
127
+ cursor = found + piece.length;
128
+ }
129
+ return cursor <= path.length - last.length;
130
+ }
131
+
132
+ function matchingGroupName(groups, agent) {
133
+ let best = "";
134
+ for (const group of groups) {
135
+ for (const name of group.agents) {
136
+ if (name !== "*" && name.length > best.length && agent.startsWith(name)) best = name;
137
+ }
138
+ }
139
+ return best;
140
+ }
141
+
142
+ // path는 normalizeRobotsPath를 거친 값이다.
143
+ export function decideRobotsPath(groups, agent, path) {
144
+ const name = agent.toLowerCase();
145
+ let groupName = matchingGroupName(groups, name);
146
+ let via = "own";
147
+ if (!groupName && name === "applebot") {
148
+ groupName = matchingGroupName(groups, "googlebot");
149
+ via = "fallback";
150
+ }
151
+ if (!groupName) {
152
+ groupName = "*";
153
+ via = groups.some((g) => g.agents.includes("*")) ? "*" : null;
154
+ }
155
+ let rule = null;
156
+ let bestLength = -1;
157
+ for (const group of groups) {
158
+ if (!group.agents.includes(groupName)) continue;
159
+ for (const candidate of group.rules) {
160
+ if (!candidate.path || !candidate.path.startsWith("/")) continue;
161
+ const pattern = normalizeRobotsPath(candidate.path);
162
+ if (!matchesRobotsPath(pattern, path)) continue;
163
+ const length = pattern.replace(/%[\da-f]{2}/gi, "_").length;
164
+ if (length > bestLength || (length === bestLength && candidate.type === "allow")) {
165
+ bestLength = length;
166
+ rule = candidate;
167
+ }
168
+ }
169
+ }
170
+ return { blocked: rule?.type === "disallow", via, groupName, rule };
171
+ }
172
+
173
+ // read: 2xx 규칙을 읽음 · no-file: 429를 제외한 4xx
174
+ // 나머지는 규칙을 읽지 못한 상태다. 이때 봇의 허용 여부는 판정하지 않는다.
175
+ export function robotsFetchState({ status = null, errorKind = null } = {}) {
176
+ if (errorKind === "timeout") return "timeout";
177
+ if (errorKind || !status) return "network-error";
178
+ if (status >= 200 && status < 300) return "read";
179
+ if (status === 429) return "rate-limited";
180
+ if (status >= 400 && status < 500) return "no-file";
181
+ if (status >= 500) return "server-error";
182
+ return "redirect";
183
+ }
184
+
185
+ export function readRobots({ url = null, status = null, body = "", contentType = "", error = null, errorKind = null, truncated = false } = {}) {
186
+ const state = robotsFetchState({ status, errorKind });
187
+ const limited = state === "read" ? limitRobots(String(body ?? "")) : { text: "", truncated: false };
188
+ const parsed = state === "read" ? parseRobots(limited.text) : { groups: [], sitemaps: [] };
189
+ return {
190
+ fetch: {
191
+ url, status: status || null, state, error: error || null,
192
+ html: state === "read" && /text\/html/i.test(contentType),
193
+ ...(state === "read" && (truncated || limited.truncated) && { truncated: true }),
194
+ },
195
+ ...parsed,
196
+ };
197
+ }
198
+
199
+ // 조회 실패 처리 방식은 문서를 확인한 엔진에만 적용한다. 그 밖의 봇은 RFC 9309를 근거로 표시한다.
200
+ const DOCUMENTED_ENGINES = new Map([["googlebot", "google"], ["google-extended", "google"], ["yeti", "naver"]]);
201
+
202
+ export function robotsEngine(agent) {
203
+ return DOCUMENTED_ENGINES.get(agent.toLowerCase()) ?? "rfc9309";
204
+ }
205
+
206
+ export function evaluateRobots(source, agent, path) {
207
+ const state = source.fetch.state;
208
+ if (state === "read") {
209
+ const { blocked, via, groupName, rule } = decideRobotsPath(source.groups, agent, normalizeRobotsPath(path));
210
+ return {
211
+ decision: blocked ? "blocked" : "allowed", allowed: !blocked,
212
+ basis: rule ? "rule" : "no-matching-rule", via, group: via ? groupName : null,
213
+ rule: rule ? { type: rule.type, path: rule.path } : null, reference: null,
214
+ };
215
+ }
216
+ const missing = state === "no-file";
217
+ return {
218
+ decision: missing ? "allowed" : "unknown", allowed: missing ? true : null,
219
+ basis: missing ? "no-file" : "unread", via: null, group: null, rule: null, reference: robotsEngine(agent),
220
+ };
221
+ }
222
+
223
+ const pick = (locale, ko, en) => (locale === "en" ? en : ko);
224
+
225
+ export function describeRobotsFetch({ fetch }, locale) {
226
+ const { state, status, error } = fetch;
227
+ const http = status ? `HTTP ${status}` : "";
228
+ switch (state) {
229
+ case "read": return pick(locale, `${http} · 규칙을 읽음`, `${http} · Rules read`) +
230
+ (fetch.truncated ? pick(locale, " · 500KiB를 넘는 부분은 읽지 않음(Google 문서의 상한, 다른 엔진의 상한은 미확인)", " · Content beyond 500 KiB was not read (Google's documented limit; other engines' limits were not verified)") : "");
231
+ case "no-file": return pick(locale, `${http} · robots.txt 파일 없음`, `${http} · No robots.txt file`);
232
+ case "rate-limited": return pick(locale, `${http} · 요청량 제한으로 규칙을 읽지 못함`, `${http} · Rate limited; rules were not read`);
233
+ case "server-error": return pick(locale, `${http} · 서버 오류로 규칙을 읽지 못함`, `${http} · Server error; rules were not read`);
234
+ case "timeout": return pick(locale, "응답 시간 초과로 규칙을 읽지 못함", "Timed out; rules were not read");
235
+ case "redirect": return pick(locale, `${http} · 리다이렉트를 끝까지 따라가지 못해 규칙을 읽지 못함`, `${http} · Redirect not resolved; rules were not read`);
236
+ default: return pick(locale, `네트워크 오류로 규칙을 읽지 못함${error ? ` (${error})` : ""}`, `Network error; rules were not read${error ? ` (${error})` : ""}`);
237
+ }
238
+ }
239
+
240
+ // 문서화된 처리 방식(2026-12-01 확인, REFERENCES.md). 이번 점검에서 실제 봇의 접근이나 이전에 저장한 사본은 관측하지 않는다.
241
+ export function describeRobotsHandling({ fetch }, engine, locale) {
242
+ const { state, status } = fetch;
243
+ if (state === "read") return "";
244
+ if (state === "no-file") {
245
+ if (engine === "google") return pick(locale, "Google 문서: 429를 제외한 4xx는 크롤링 제한 규칙이 없는 것으로 처리", "Google documentation: 4xx responses other than 429 are treated as no crawl restrictions");
246
+ if (engine === "naver") return pick(locale, "네이버 문서: 4xx는 모두 허용", "Naver documentation: 4xx allows all crawling");
247
+ return pick(locale, "RFC 9309: 파일을 이용할 수 없으면(4xx) 크롤러가 접근할 수 있음. 이 봇의 개별 문서는 확인하지 않음", "RFC 9309: crawlers may access resources when the file is unavailable (4xx). Bot-specific documentation was not verified");
248
+ }
249
+ const unreachable = ["server-error", "timeout", "network-error"].includes(state);
250
+ if (engine === "google" && (unreachable || state === "rate-limited")) {
251
+ return pick(locale, "Google 문서: 429·5xx·네트워크 오류·타임아웃은 서버 오류로 처리. 처음 12시간은 크롤링을 멈추고 재시도하며, 이후 30일까지 마지막 정상 사본을 사용(사본이 없으면 제한 없음으로 간주)",
252
+ "Google documentation: 429, 5xx, network errors and timeouts are server errors. Crawling pauses for the first 12 hours, then the last good copy is used for up to 30 days (no restrictions are assumed without a copy)");
253
+ }
254
+ if (engine === "naver" && state === "server-error") {
255
+ return pick(locale, "네이버 문서: 5xx는 모두 허용하지 않음(이전에 정상 수집한 규칙이 있으면 일시 사용 가능)", "Naver documentation: 5xx disallows all crawling (previously fetched rules may be used temporarily)");
256
+ }
257
+ if (engine === "rfc9309" && unreachable) {
258
+ return pick(locale, "그 밖의 봇: 개별 문서 미확인. 표준(RFC 9309)은 서버·네트워크 오류를 전체 차단으로 간주", "Other bots: bot-specific documentation not verified. RFC 9309 assumes a full disallow on server or network errors");
259
+ }
260
+ const name = { google: "Google", naver: pick(locale, "네이버", "Naver") }[engine] ?? pick(locale, "그 밖의 봇", "Other bots");
261
+ return pick(locale, `${name}: ${status ? `HTTP ${status}` : "이 오류"} 처리 방식을 따로 설명한 문서를 확인하지 못함`, `${name}: no verified documentation specific to ${status ? `HTTP ${status}` : "this error"}`);
262
+ }
263
+
264
+ export function describeRobotsDecision(result, locale) {
265
+ const verdict = result.decision === "blocked" ? pick(locale, "차단", "Blocked")
266
+ : result.decision === "allowed" ? pick(locale, "허용", "Allowed") : pick(locale, "미확인", "Unverified");
267
+ if (result.basis === "rule") return `${verdict} (User-agent: ${result.group}, ${result.rule.type}: ${result.rule.path})`;
268
+ if (result.basis === "no-matching-rule") return `${verdict} (${pick(locale, "일치하는 규칙 없음", "No matching rule")}${result.group ? `, User-agent: ${result.group}` : ""})`;
269
+ return verdict;
270
+ }