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
@@ -1,4 +1,5 @@
1
1
  import { currentLocale, t } from "./locale.mjs";
2
+ import { canonicalDeclarations, describeCanonical, evaluateCanonical, httpUrl } from "./canonical.mjs";
2
3
 
3
4
  // 서버 HTML에 실제로 선언된 메타데이터만 읽습니다. JavaScript를 실행하지 않습니다.
4
5
  const HEAD_ELEMENTS = new Set("html head base basefont bgsound link meta noframes noscript script style template title".split(" "));
@@ -134,88 +135,14 @@ export function parseHtml(html) {
134
135
  return page;
135
136
  }
136
137
 
137
- export function httpUrl(value, base) {
138
- try {
139
- const url = new URL(value, base || undefined);
140
- return ["https:", "http:"].includes(url.protocol) ? url.href : null;
141
- } catch {
142
- return null;
143
- }
144
- }
145
-
146
- // 로컬 파일은 배포 호스트와 디렉터리를 모릅니다. 확정되는 URL 부분만 비교합니다.
147
- function canonicalTargetsCanAgree(values, scheme) {
148
- const fullUrls = new Set();
149
- const rootedPaths = new Set();
150
- const searches = new Set();
151
- const hashes = new Set();
152
- let longestSuffix = "";
153
- for (const value of values) {
154
- const ref = value.replace(/[\t\n\r]/g, "").replaceAll("\\", "/");
155
- const url = new URL(value, `${scheme}://example.invalid/`);
156
- const hasAuthority = /^(?:https?:)?\/\//i.test(ref);
157
- if (hasAuthority) fullUrls.add(url.href);
158
- hashes.add(url.hash);
159
- if (!ref.startsWith("#")) searches.add(url.search);
160
- if (/^[?#]/.test(ref)) continue; // 배포 페이지의 경로를 그대로 상속합니다.
161
- if (hasAuthority || ref.startsWith("/")) rootedPaths.add(url.pathname);
162
- // 상대 경로가 ../를 포함해도 루트에서 해석한 끝부분은 항상 동일합니다.
163
- const suffix = url.pathname;
164
- if (!longestSuffix.endsWith(suffix)) {
165
- if (!suffix.endsWith(longestSuffix)) return false;
166
- longestSuffix = suffix;
167
- }
168
- }
169
- const [rootedPath] = rootedPaths;
170
- return fullUrls.size <= 1 && rootedPaths.size <= 1 && searches.size <= 1 && hashes.size <= 1
171
- && (!rootedPath || rootedPath.endsWith(longestSuffix));
172
- }
138
+ export { canonicalDeclarations, httpUrl };
173
139
 
174
140
  // 한 개의 유효한 대상을 확인했을 때만 OG나 최종 응답 URL과 대조합니다.
175
- export function checkCanonical(page, add, pageUrl) {
176
- const report = (level, detail) => add(level, t("공통", "General"), "canonical", detail, "google-search");
141
+ export function checkCanonical(page, add, pageUrl, linkHeader = []) {
177
142
  const links = page.canonicalLinks ?? (page.canonical ? [{ href: page.canonical, inHead: true }] : []);
178
- const headLinks = links.filter(link => link.inHead);
179
- if (links.length > headLinks.length) report("FAIL", t("<head> 밖의 canonical 선언은 무시됨", "Canonical declarations outside <head> are ignored"));
180
- if (!headLinks.length) {
181
- if (!links.length) report("WARN", t("없음", "Missing"));
182
- return null;
183
- }
184
-
185
- const base = page.baseHref ? httpUrl(page.baseHref, pageUrl) || pageUrl : pageUrl;
186
- const targets = new Set();
187
- const unresolved = new Set();
188
- for (const { href } of headLinks) {
189
- const value = href?.trim();
190
- if (!value) {
191
- report("FAIL", t("href가 없거나 비어 있음", "Missing or empty href"));
192
- continue;
193
- }
194
- const relative = !/^[a-z][a-z\d+.\-]*:/i.test(value);
195
- const url = httpUrl(value, base);
196
- if (relative && !base && httpUrl(value, "https://example.invalid/")) {
197
- report("WARN", currentLocale() === "en" ? `Relative path: ${value} (no base URL to resolve it)` : `상대 경로: ${value} (기준 URL이 없어 최종 주소 미확인)`);
198
- unresolved.add(value);
199
- } else if (!url) {
200
- report("FAIL", currentLocale() === "en" ? `Invalid HTTP(S) URL: ${value}` : `잘못된 HTTP(S) URL: ${value}`);
201
- } else {
202
- if (relative) report("WARN", `${t("상대 경로", "Relative path")}: ${value} → ${url}`);
203
- targets.add(url);
204
- }
205
- }
206
- const declarations = [...targets, ...unresolved];
207
- if (declarations.length > 1 && !["https", "http"].some(scheme => canonicalTargetsCanAgree(declarations, scheme))) {
208
- report("FAIL", `${t("서로 다른 대표 URL 선언", "Conflicting canonical URLs")}: ${declarations.join(", ")}`);
209
- return null;
210
- }
211
- if (headLinks.length > 1) {
212
- const unique = targets.size + unresolved.size;
213
- report("WARN", unique === 1 ?
214
- t("canonical 중복 선언 — 한 태그만 유지 권장", "Duplicate canonical declarations. Keep one tag") :
215
- t("canonical 선언이 여러 개 — 대상 URL 확인 필요", "Multiple canonical declarations. Check the target URLs"));
143
+ const { findings, target } = evaluateCanonical({ links, baseHref: page.baseHref, pageUrl, linkHeader });
144
+ for (const finding of findings) {
145
+ add(finding.level, t("공통", "General"), "canonical", describeCanonical(finding, currentLocale()), "google-search");
216
146
  }
217
- if (unresolved.size) return null;
218
- const [target] = targets;
219
- if (pageUrl && target && target !== httpUrl(pageUrl)) report("INFO", `${t("다른 URL을 가리킴", "Points to another URL")}: ${target}`);
220
- return target ?? null;
147
+ return target;
221
148
  }
@@ -0,0 +1,181 @@
1
+ // 색인 지시자 수집과 상단 상태 판정. CLI·웹·확장 공용이며 의존성이 없다.
2
+ // 브라우저 확장은 이 파일의 사본(extension/index-status.mjs)을 읽는다.
3
+
4
+ // A bot-scoped noindex only applies to that bot. Keep every rule and its source
5
+ // so a later "index" cannot conceal an earlier restriction (or vice versa).
6
+ const metaScopes = new Set(["robots", "googlebot", "googlebot-news", "googlebot-image", "yeti", "bingbot", "applebot", "duckduckbot", "daum"]);
7
+ const valuedRules = new Set(["max-snippet", "max-image-preview", "max-video-preview", "unavailable_after", "ai-training", "ai-grounding"]);
8
+
9
+ // 지난 unavailable_after 날짜는 제외 지시와 같다. 해석할 수 없는 값은 판정하지 않는다.
10
+ export function isExclusion(value, now = Date.now()) {
11
+ if (/^(?:noindex|none)$/.test(value)) return true;
12
+ // 캡처가 줄바꿈까지 받아야 긴 공백 뒤의 줄바꿈에서 되돌아가며 느려지지 않는다.
13
+ const date = /^unavailable_after\s*:\s*([\s\S]+)$/.exec(value)?.[1];
14
+ const time = date ? Date.parse(date.toUpperCase()) : NaN;
15
+ return Number.isFinite(time) && time < now;
16
+ }
17
+
18
+ // 요일이 들어간 날짜(RFC 822·850)는 쉼표에서 잘리지 않게 잇는다.
19
+ function directives(text) {
20
+ const parts = [];
21
+ let weekday = false;
22
+ // 직전 조각만 검사해 긴 입력에도 선형 시간으로 처리한다.
23
+ for (const part of text.split(",")) {
24
+ if (weekday) parts[parts.length - 1] += `,${part}`;
25
+ else parts.push(part);
26
+ weekday = !weekday && /unavailable_after\s*:\s*(?:mon|tue|wed|thu|fri|sat|sun)[a-z]*\s*$/i.test(part);
27
+ }
28
+ return parts;
29
+ }
30
+
31
+ const MAX_EVIDENCE = 300;
32
+ const MAX_BLOCKS = 50;
33
+ const shortened = (text) => (text.length > MAX_EVIDENCE ? `${text.slice(0, MAX_EVIDENCE)}…` : text);
34
+
35
+ // 근거가 많으면 앞부분만 남긴다. 검색 봇별 첫 근거와 대상 범위를 구분할 수 없는 첫 근거는 항상 남긴다.
36
+ function listedBlocks(blocks) {
37
+ if (blocks.length <= MAX_BLOCKS) return blocks;
38
+ const essential = new Map();
39
+ for (const block of blocks) {
40
+ const key = Object.hasOwn(SEARCH_AGENTS, block.scope) ? `${block.scope}\u0000${Boolean(block.ambiguous)}` : block.ambiguous ? "ambiguous" : null;
41
+ if (key && !essential.has(key)) essential.set(key, block);
42
+ }
43
+ const kept = new Set(essential.values());
44
+ for (const block of blocks) {
45
+ if (kept.size >= MAX_BLOCKS) break;
46
+ kept.add(block);
47
+ }
48
+ return blocks.filter((block) => kept.has(block));
49
+ }
50
+
51
+ // mergedHeaders: Fetch API처럼 여러 X-Robots-Tag 줄이 쉼표로 합쳐진 값. 봇 접두어 뒤에 접두어 없이
52
+ // 이어지는 지시는 그 봇 전용인지 다음 줄의 공통 지시인지 구분할 수 없어 ambiguous로 표시한다.
53
+ export function indexingRules(metaTags, headerLines, { mergedHeaders = false } = {}) {
54
+ const rules = [];
55
+ function collect(scope, text, source, raw, ambiguous = false) {
56
+ const value = text.trim().toLowerCase();
57
+ if (!value) return;
58
+ // Plain directives may also be space-separated. Arguments of valued
59
+ // directives (for example a date) stay together.
60
+ const values = /^[a-z][a-z_-]*(?:\s+[a-z][a-z_-]*)*$/.test(value) ? value.split(/\s+/) : [value];
61
+ for (const directive of values) rules.push({ scope, value: directive, source, raw, ...(ambiguous && { ambiguous }) });
62
+ }
63
+ for (const { name, content } of metaTags) {
64
+ const scope = name?.trim().toLowerCase();
65
+ if (!metaScopes.has(scope) || !content) continue;
66
+ for (const part of directives(content)) collect(scope, part, "meta", content);
67
+ }
68
+ for (const line of headerLines) {
69
+ let scope = "robots";
70
+ for (const part of directives(line)) {
71
+ const prefix = /^\s*([\w*-]+)\s*:\s*(.*)$/.exec(part);
72
+ if (prefix && !valuedRules.has(prefix[1].toLowerCase())) {
73
+ scope = prefix[1].toLowerCase();
74
+ if (scope === "*") scope = "robots";
75
+ collect(scope, prefix[2], "X-Robots-Tag", line);
76
+ } else {
77
+ collect(scope, part, "X-Robots-Tag", line, mergedHeaders && scope !== "robots");
78
+ }
79
+ }
80
+ }
81
+ return rules;
82
+ }
83
+
84
+ export function normalizeIntent(intent) {
85
+ if (intent === true) return "index";
86
+ return intent === "index" || intent === "exclude" ? intent : "unspecified";
87
+ }
88
+
89
+ /**
90
+ * state: blocked(모든 로봇) · partial(특정 봇) · scope-unverified(대상 구분 불가) · open(지시 없음) · unverified(확인 불가)
91
+ * verdict: 색인 목표와 state를 합친 상단 상태
92
+ * bodyComplete: false면 본문 일부만 읽었다. 찾은 지시는 그대로 판정하지만 "지시 없음"은 확정하지 않는다.
93
+ */
94
+ export function indexingStatus({ rules, intent = "unspecified", headersObserved = true, httpStatus = null, bodyComplete = true, now = Date.now() }) {
95
+ const goal = normalizeIntent(intent);
96
+ // 같은 원문에서 온 같은 대상·종류의 지시는 근거 하나로 합친다. 지난 날짜가 여러 개여도 한 건이다.
97
+ const seen = new Map();
98
+ const blocks = [];
99
+ for (const { scope, value, source, raw = value, ambiguous } of rules) {
100
+ if (!isExclusion(value, now)) continue;
101
+ const kinds = seen.get(raw) ?? new Set();
102
+ // 대상 범위를 구분할 수 없는 지시는 같은 봇의 확정 지시와 따로 남긴다.
103
+ const kind = `${scope}\u0000${source}\u0000${value.startsWith("unavailable_after") ? "unavailable_after" : value}\u0000${Boolean(ambiguous)}`;
104
+ if (kinds.has(kind)) continue;
105
+ seen.set(raw, kinds.add(kind));
106
+ blocks.push({ scope: shortened(scope), directive: shortened(value), source, raw: shortened(raw), ...(ambiguous && { ambiguous }) });
107
+ }
108
+ const httpError = httpStatus !== null && (httpStatus < 200 || httpStatus >= 300);
109
+ const state = blocks.some((block) => block.scope === "robots") ? "blocked"
110
+ : blocks.some((block) => block.ambiguous) ? "scope-unverified"
111
+ : blocks.length ? "partial"
112
+ : httpError || !headersObserved || !bodyComplete ? "unverified" : "open";
113
+ let verdict;
114
+ if (state === "unverified" || state === "scope-unverified") verdict = state;
115
+ else if (goal === "exclude") verdict = { blocked: "intended-exclusion", partial: "intended-partial", open: "intended-but-open" }[state];
116
+ else if (state === "open") verdict = "open";
117
+ else verdict = goal === "index" ? "unintended-block" : "confirm-block";
118
+ const listed = listedBlocks(blocks);
119
+ return {
120
+ intent: goal, state, verdict, headersObserved, httpStatus, ...(!bodyComplete && { bodyComplete: false }),
121
+ blocks: listed, ...(listed.length < blocks.length && { omitted: blocks.length - listed.length }),
122
+ };
123
+ }
124
+
125
+ const SEARCH_AGENTS = {
126
+ robots: ["Googlebot", "Yeti", "Daum", "Bingbot"], googlebot: ["Googlebot"], "googlebot-news": ["Googlebot"],
127
+ yeti: ["Yeti"], daum: ["Daum"], bingbot: ["Bingbot"],
128
+ };
129
+
130
+ // 제외를 의도한 페이지를 robots.txt가 막으면 검색로봇이 noindex를 읽지 못할 수 있다.
131
+ export function unreadableExclusions(status, decisions) {
132
+ if (status.intent !== "exclude") return [];
133
+ const targets = new Set(status.blocks.flatMap((block) => SEARCH_AGENTS[block.scope] ?? []));
134
+ return [...targets].filter((agent) => decisions.some((entry) => entry.agent === agent && entry.decision === "blocked"));
135
+ }
136
+
137
+ const pick = (locale, ko, en) => (locale === "en" ? en : ko);
138
+
139
+ export function describeCrawlBlock(agents, locale) {
140
+ return pick(locale, `robots.txt가 ${agents.join(", ")}의 크롤링을 막아 noindex를 읽지 못할 수 있습니다. 제외가 목적이면 크롤링을 허용해 지시를 읽게 하세요.`,
141
+ `robots.txt blocks ${agents.join(", ")}, so the noindex may never be read. Allow crawling so the exclusion directive can be seen.`);
142
+ }
143
+
144
+ export function describeBlock(block, locale) {
145
+ const where = block.source === "meta" ? pick(locale, "robots 메타", "robots meta") : pick(locale, "HTTP X-Robots-Tag 헤더", "HTTP X-Robots-Tag header");
146
+ const target = block.scope === "robots" ? pick(locale, "모든 로봇", "all robots")
147
+ : block.ambiguous ? pick(locale, `${block.scope} 또는 모든 로봇(구분 불가)`, `${block.scope} or all robots (cannot tell)`) : block.scope;
148
+ return pick(locale, `${where} · 대상 ${target} · 지시값 ${block.directive} (원문: ${block.raw})`,
149
+ `${where} · Target ${target} · Directive ${block.directive} (raw: ${block.raw})`);
150
+ }
151
+
152
+ export function describeIndexing(status, locale) {
153
+ const titles = {
154
+ "unintended-block": pick(locale, "색인 차단 — 색인 대상 페이지가 검색에서 제외됩니다", "Indexing blocked — a page meant for search is excluded"),
155
+ "confirm-block": pick(locale, "색인 제외 지시 감지 — 의도한 제외인지 확인하세요", "Exclusion directive found — confirm that it is intended"),
156
+ "intended-exclusion": pick(locale, "의도한 색인 제외 — 모든 로봇에 제외 지시가 있습니다", "Intentionally excluded — an exclusion directive applies to all robots"),
157
+ "intended-partial": pick(locale, "제외 의도와 다름 — 일부 봇에만 제외 지시가 있어 다른 엔진은 색인할 수 있습니다", "Exclusion is incomplete — only some bots are excluded, so other engines may index the page"),
158
+ "intended-but-open": pick(locale, "제외 의도와 다름 — noindex 지시를 찾지 못했습니다", "Intended exclusion is missing — no noindex directive was found"),
159
+ open: pick(locale, "색인 제외 지시 없음", "No exclusion directive found"),
160
+ "scope-unverified": pick(locale, "색인 제외 지시의 대상 범위 미확인 — 합쳐진 X-Robots-Tag 헤더라 특정 봇 전용인지 모든 로봇 대상인지 구분할 수 없습니다", "Exclusion scope is unverified — merged X-Robots-Tag headers do not show whether it applies to one bot or to all"),
161
+ unverified: status.httpStatus !== null && (status.httpStatus < 200 || status.httpStatus >= 300)
162
+ ? pick(locale, `색인 지시 미확인 — 페이지가 HTTP ${status.httpStatus}를 반환했습니다`, `Indexing directives unverified — the page returned HTTP ${status.httpStatus}`)
163
+ : status.bodyComplete === false
164
+ ? pick(locale, "색인 지시 미확인 — 페이지가 잘려 읽은 범위에서는 제외 지시를 찾지 못했습니다", "Indexing directives unverified — the page was truncated and no exclusion directive was found in the part that was read")
165
+ : pick(locale, "색인 지시 일부 미확인 — HTTP 응답 헤더를 관측하지 않았습니다", "Indexing directives partly unverified — HTTP response headers were not observed"),
166
+ };
167
+ // 특정 봇에만 적용되는 지시는 대상 봇을 제목에 밝힌다.
168
+ if (status.state === "partial") {
169
+ const bots = [...new Set(status.blocks.map((block) => block.scope))].join(", ") + (status.omitted ? ", …" : "");
170
+ titles["unintended-block"] = pick(locale, `일부 봇 색인 차단 (${bots}) — 해당 봇은 이 페이지를 색인에서 제외합니다`, `Indexing blocked for some bots (${bots}) — those bots exclude this page`);
171
+ titles["confirm-block"] = pick(locale, `일부 봇 색인 제외 지시 (${bots}) — 의도한 제외인지 확인하세요`, `Exclusion directive for some bots (${bots}) — confirm that it is intended`);
172
+ }
173
+ const notes = [];
174
+ if (status.crawlBlocked?.length) notes.push(describeCrawlBlock(status.crawlBlocked, locale));
175
+ if (status.omitted) notes.push(pick(locale, `색인 제외 근거가 많아 ${status.omitted}건은 목록에서 생략했습니다.`, `${status.omitted} more exclusion directives are not listed.`));
176
+ if (status.intent === "exclude") notes.push(pick(locale, "이 페이지는 검색 제외를 의도한 페이지로 지정했습니다.", "This page is marked as intentionally excluded from search."));
177
+ if (!status.headersObserved) notes.push(pick(locale, "X-Robots-Tag 헤더는 미관측입니다.", "The X-Robots-Tag header was not observed."));
178
+ if (status.bodyComplete === false) notes.push(pick(locale, "본문의 앞부분만 읽어, 읽지 않은 부분의 robots 메타는 확인하지 않았습니다.", "Only the first part of the page was read, so robots meta tags in the rest were not checked."));
179
+ notes.push(pick(locale, "지시자 관측 결과이며 검색엔진의 실제 색인 상태는 각 콘솔에서 확인하세요.", "This reports observed directives. Check actual index status in each engine console."));
180
+ return { title: titles[status.verdict], note: notes.join(" ") };
181
+ }
@@ -1,48 +1,37 @@
1
1
  import { t } from "./locale.mjs";
2
- // A bot-scoped noindex only applies to that bot. Keep every rule and its source
3
- // so a later "index" cannot conceal an earlier restriction (or vice versa).
4
- const metaScopes = new Set(["robots", "googlebot", "googlebot-news", "googlebot-image", "yeti", "bingbot", "applebot", "duckduckbot", "daum"]);
5
- const valuedRules = new Set(["max-snippet", "max-image-preview", "max-video-preview", "unavailable_after", "ai-training", "ai-grounding"]);
2
+ import { indexingRules, indexingStatus, isExclusion, normalizeIntent } from "./index-status.mjs";
6
3
 
7
- export function indexingRules(metaTags, headerLines) {
8
- const rules = [];
9
- function collect(scope, text, source) {
10
- const value = text.trim().toLowerCase();
11
- if (!value) return;
12
- // Plain directives may also be space-separated. Arguments of valued
13
- // directives (for example a date) stay together.
14
- const values = /^[a-z][a-z_-]*(?:\s+[a-z][a-z_-]*)*$/.test(value) ? value.split(/\s+/) : [value];
15
- for (const directive of values) rules.push({ scope, value: directive, source });
16
- }
17
- for (const { name, content } of metaTags) {
18
- const scope = name?.trim().toLowerCase();
19
- if (!metaScopes.has(scope) || !content) continue;
20
- for (const part of content.split(",")) collect(scope, part, "meta");
21
- }
22
- for (const line of headerLines) {
23
- let scope = "robots";
24
- for (const part of line.split(",")) {
25
- const prefix = /^\s*([\w*-]+)\s*:\s*(.*)$/.exec(part);
26
- if (prefix && !valuedRules.has(prefix[1].toLowerCase())) {
27
- scope = prefix[1].toLowerCase();
28
- if (scope === "*") scope = "robots";
29
- collect(scope, prefix[2], "X-Robots-Tag");
30
- } else {
31
- collect(scope, part, "X-Robots-Tag");
32
- }
33
- }
34
- }
35
- return rules;
36
- }
4
+ export { indexingRules };
37
5
 
38
- export function reportIndexing(rules, add, expectIndexable) {
6
+ // intent: "index" | "exclude" | "unspecified". 기존 boolean(expectIndexable)도 받는다.
7
+ // status: 같은 rules의 indexingStatus() 결과. 제외 의도 지적은 상단 상태와 같은 판정을 따른다.
8
+ export function reportIndexing(rules, add, intent, status = indexingStatus({ rules, intent })) {
9
+ const goal = normalizeIntent(intent);
39
10
  let genericNoindex = false;
40
11
  for (const { scope, value, source } of rules) {
41
- const excluded = /^(?:noindex|none)$/.test(value);
12
+ const excluded = isExclusion(value);
42
13
  if (excluded && scope === "robots") genericNoindex = true;
43
- const level = excluded ? (expectIndexable ? "FAIL" : "WARN") : "INFO";
44
- const detail = `${scope}: ${value}` + (excluded ? t(" — 색인 제외 지시", " — indexing excluded by directive") : "");
45
- add(level, scope === "robots" ? t("공통", "General") : scope, source === "meta" ? "robots meta" : source, detail, "google-search");
14
+ const level = !excluded || goal === "exclude" ? "INFO" : goal === "index" ? "FAIL" : "WARN";
15
+ const note = !excluded ? ""
16
+ : goal === "exclude" ? t(" — 의도한 색인 제외", " — intended exclusion")
17
+ : t(" — 색인 제외 지시", " — indexing excluded by directive");
18
+ add(level, scope === "robots" ? t("공통", "General") : scope, source === "meta" ? "robots meta" : source, `${scope}: ${value}${note}`, "google-search");
19
+ }
20
+ if (goal === "exclude" && status.verdict !== "intended-exclusion") {
21
+ // 확인할 수 없는 상태는 noindex가 없다고 단정하지 않는다.
22
+ const unverified = status.verdict === "unverified";
23
+ add(unverified ? "INFO" : "WARN", t("공통", "General"), t("색인 제외 의도", "Exclusion intent"),
24
+ unverified ? unverifiedExclusion(status)
25
+ : t("검색 제외를 의도했지만 모든 로봇에 적용되는 noindex가 없습니다.", "Exclusion is intended, but no noindex applies to all robots."), "google-search");
46
26
  }
47
27
  return genericNoindex;
48
28
  }
29
+
30
+ function unverifiedExclusion({ httpStatus }) {
31
+ const httpError = httpStatus !== null && (httpStatus < 200 || httpStatus >= 300);
32
+ return httpError
33
+ ? t(`검색 제외를 의도했지만 페이지가 HTTP ${httpStatus}를 반환해 noindex 적용 여부를 확인하지 못했습니다.`,
34
+ `Exclusion is intended, but the page returned HTTP ${httpStatus}, so whether a noindex applies is unverified.`)
35
+ : t("검색 제외를 의도했습니다. HTML에서 noindex를 찾지 못했고 HTTP 응답 헤더를 관측하지 않아 적용 여부를 확인하지 못했습니다.",
36
+ "Exclusion is intended. The HTML has no noindex and HTTP response headers were not observed, so whether a noindex applies is unverified.");
37
+ }
@@ -1,7 +1,9 @@
1
1
  import { fetchResource } from "./fetch-page.mjs";
2
2
  import { parseHtml } from "./html.mjs";
3
3
  import { t } from "./locale.mjs";
4
- import { robotsAllowsPath, UA } from "./seo-check.mjs";
4
+ import { crawlLines, crawlSummary } from "./crawl-report.mjs";
5
+ import { evaluateRobots } from "./robots.mjs";
6
+ import { fetchRobots, UA } from "./seo-check.mjs";
5
7
  import { discoverCrawlSitemaps } from "./site-audit.mjs";
6
8
 
7
9
  const REDIRECTS = new Set([301, 302, 303, 307, 308]);
@@ -49,21 +51,19 @@ export async function crawlSite(start, maxPages, { sitemap } = {}) {
49
51
  sitemap: { sitemapsRead: 0, truncated: false, discoveryErrors: [], warnings: [] },
50
52
  orphanCheckComplete: false,
51
53
  };
52
- let robots = "", robotsAvailable = false;
53
- const robotsUrl = new URL("/robots.txt", seed);
54
- try {
55
- const { status, bytes } = await request(robotsUrl);
56
- if (status >= 200 && status < 300) robots = new TextDecoder().decode(bytes);
57
- else if (![404, 410].includes(status)) throw new Error(`HTTP ${status}`);
58
- robotsAvailable = true;
59
- } catch (error) {
60
- report.errors.push({ url: robotsUrl.href, error: error.message });
54
+ const robots = await fetchRobots(seed, { signal: AbortSignal.timeout(Math.max(1, Math.min(5000, deadline - Date.now()))) });
55
+ // 429를 제외한 4xx는 파일 없음(제한 없음)이다. 429·5xx·네트워크 실패처럼 규칙을 읽지 못하면 크롤링하지 않는다.
56
+ const robotsAvailable = ["read", "no-file"].includes(robots.fetch.state);
57
+ if (!robotsAvailable) {
58
+ const { url, status, error } = robots.fetch;
59
+ report.errors.push({ url, error: status ? `HTTP ${status}` : error });
61
60
  }
62
- const allowsPath = robotsAllowsPath(robots, UA.split("/")[0]);
61
+ const allowsPath = path => evaluateRobots(robots, UA.split("/")[0], path).decision !== "blocked";
63
62
  const allowRequest = url => robotsAvailable && url.origin === origin && allowsPath(url.pathname + url.search);
64
63
  if (!robotsAvailable) return { report, allowRequest, origin };
65
64
 
66
65
  let seedPage;
66
+ let sitemapHreflang;
67
67
  const reachable = new Set();
68
68
  const blocked = new Set();
69
69
  const parsed = new Set();
@@ -153,50 +153,20 @@ export async function crawlSite(start, maxPages, { sitemap } = {}) {
153
153
  finding.sources = [...(sources.get(finding.url) ?? [])];
154
154
  }
155
155
 
156
- const declared = [...robots.matchAll(/^\s*sitemap[ \t]*:[ \t]*([^#\r\n]+)/gim)]
157
- .map(([, raw]) => httpUrl(raw.trim())).filter(url => url?.origin === origin);
156
+ const declared = robots.sitemaps.map(raw => httpUrl(raw)).filter(url => url?.origin === origin);
158
157
  const roots = explicit ? [explicit] : declared.length ? declared : [new URL("/sitemap.xml", seed)];
159
158
  if (Date.now() < deadline) {
160
- const { urls, ...metadata } = await discoverCrawlSitemaps(roots, {
159
+ const { urls, hreflang, ...metadata } = await discoverCrawlSitemaps(roots, {
161
160
  allowRequest, optionalMissing: !explicit && !declared.length,
162
161
  signal: AbortSignal.timeout(Math.max(1, Math.min(10_000, deadline - Date.now()))),
163
162
  });
164
163
  report.sitemap = metadata;
164
+ sitemapHreflang = hreflang;
165
165
  report.orphanCheckComplete = !!seedPage && !!metadata.sitemapsRead && !metadata.truncated && !metadata.discoveryErrors.length &&
166
166
  !report.truncated && !report.errors.length && !report.redirectChains.some(chain => chain.issue === "limit");
167
167
  if (report.orphanCheckComplete) report.orphanPages = urls.filter(url => !reachable.has(url) && allowRequest(new URL(url)));
168
168
  }
169
- return { report, allowRequest, origin, seedPage };
170
- }
171
-
172
- export function crawlSummary(report) {
173
- const { visited, brokenLinks, redirectChains, orphanPages, orphanCheckComplete } = report;
174
- const orphans = orphanCheckComplete ? orphanPages.length : t("판정 보류", "not assessed");
175
- return t(
176
- `내부 링크 크롤링 · 방문 ${visited.length} · 깨진 링크 ${brokenLinks.length} · 리다이렉트 체인·루프 ${redirectChains.length} · 고아 페이지 ${orphans}`,
177
- `Internal link crawl · Visited ${visited.length} · Broken links ${brokenLinks.length} · Redirect chains and loops ${redirectChains.length} · Orphan pages ${orphans}`,
178
- );
169
+ return { report, allowRequest, origin, seedPage, hreflang: sitemapHreflang };
179
170
  }
180
171
 
181
- export function crawlLines(report) {
182
- const rows = [crawlSummary(report)];
183
- if (report.startStatus != null) rows.push(`${report.start} · HTTP ${report.startStatus}`);
184
- if (report.truncated) rows.push(t("크롤링 한도에 도달했습니다.", "Crawl limit reached."));
185
- for (const url of report.blocked) rows.push(t("robots.txt 차단", "Blocked by robots.txt") + ` · ${url}`);
186
- for (const { url, status, finalUrl, sources } of report.brokenLinks) {
187
- rows.push(t("깨진 링크", "Broken link") + ` · HTTP ${status} · ${url}${url === finalUrl ? "" : ` → ${finalUrl}`} · ${sources.join(", ")}`);
188
- }
189
- const reasons = {
190
- loop: t("루프", "Loop"), limit: t("홉 한도", "Hop limit"), blocked: t("robots.txt 차단", "Blocked by robots.txt"),
191
- external: t("다른 출처", "Off-origin"), invalid: t("잘못된 주소", "Invalid URL"),
192
- };
193
- for (const { chain, issue, destination } of report.redirectChains) {
194
- const steps = chain.map(({ status, url }) => `${status} ${url}`);
195
- if (issue && destination) steps.push(destination);
196
- rows.push(t("리다이렉트", "Redirect") + ` · ${steps.join(" → ")}${issue ? ` · ${reasons[issue]}` : ""}`);
197
- }
198
- for (const url of report.orphanPages) rows.push(t("고아 페이지", "Orphan page") + ` · ${url}`);
199
- for (const { url, error } of report.errors) rows.push(`${url} · ${error}`);
200
- for (const warning of report.sitemap.warnings) rows.push(warning);
201
- return rows;
202
- }
172
+ export { crawlLines, crawlSummary };
@@ -0,0 +1,93 @@
1
+ // HTTP Link 헤더(RFC 8288) 해석. CLI와 웹이 canonical·hreflang 판정에 같은 결과를 사용한다.
2
+ // 브라우저 확장은 hreflang 모듈의 의존 파일로 사본을 읽는다.
3
+
4
+ // RFC 3986: 퍼센트 인코딩의 16진수 대소문자와 비예약 문자의 인코딩 여부는 같은 URL이다.
5
+ export function normalizeEscapes(href) {
6
+ return href.replace(/%[\da-f]{2}/gi, (escape) => {
7
+ const char = String.fromCharCode(parseInt(escape.slice(1), 16));
8
+ return /[A-Za-z0-9._~-]/.test(char) ? char : escape.toUpperCase();
9
+ });
10
+ }
11
+
12
+ // 비교용 URL: 프래그먼트를 제외하고 퍼센트 인코딩 표기를 맞춘다.
13
+ export function comparableUrl(href) {
14
+ const url = new URL(href);
15
+ url.hash = "";
16
+ return normalizeEscapes(url.href);
17
+ }
18
+
19
+ export function webUrlOrNull(value, base) {
20
+ try {
21
+ const url = new URL(value, base || undefined);
22
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;
23
+ return url.href;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ function parseLine(line, out) {
30
+ let i = 0;
31
+ const space = () => { while (/\s/.test(line[i] ?? "")) i++; };
32
+ const until = (stop) => { const start = i; while (i < line.length && !stop.test(line[i])) i++; return line.slice(start, i); };
33
+ function quoted() {
34
+ let value = "";
35
+ for (i++; i < line.length && line[i] !== '"'; i++) {
36
+ if (line[i] === "\\" && i + 1 < line.length) i++;
37
+ value += line[i];
38
+ }
39
+ i++;
40
+ return value;
41
+ }
42
+ while (i < line.length) {
43
+ space();
44
+ if (line[i] !== "<") {
45
+ until(/[,<]/);
46
+ if (line[i] === ",") i++;
47
+ continue;
48
+ }
49
+ const end = line.indexOf(">", i + 1);
50
+ if (end < 0) return;
51
+ const href = line.slice(i + 1, end).trim();
52
+ i = end + 1;
53
+ const params = [];
54
+ while (i < line.length) {
55
+ space();
56
+ if (line[i] === ",") { i++; break; }
57
+ if (line[i] !== ";") { until(/[;,]/); continue; }
58
+ i++;
59
+ space();
60
+ const name = until(/[=;,]/).trim().toLowerCase();
61
+ let value = "";
62
+ if (line[i] === "=") {
63
+ i++;
64
+ space();
65
+ value = line[i] === '"' ? quoted() : until(/[;,]/).trim();
66
+ }
67
+ if (name) params.push([name, value]);
68
+ }
69
+ out.push({ href, params });
70
+ }
71
+ }
72
+
73
+ // HTTP 헤더는 latin1로 읽힌다. UTF-8 바이트가 그대로 온 값은 복원해 HTML 선언과 비교한다.
74
+ function utf8Line(line) {
75
+ if (!/[\x80-\xff]/.test(line) || /[^\x00-\xff]/.test(line)) return line;
76
+ try {
77
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(line, (char) => char.charCodeAt(0)));
78
+ } catch {
79
+ return line;
80
+ }
81
+ }
82
+
83
+ export function parseLinkHeader(values, baseUrl) {
84
+ const raw = [];
85
+ for (const line of [values].flat()) if (typeof line === "string") parseLine(utf8Line(line), raw);
86
+ // anchor가 있으면 다른 자원에 대한 관계이므로 이 페이지의 선언으로 보지 않는다.
87
+ return raw.filter(({ params }) => !params.some(([name]) => name === "anchor")).map(({ href, params }) => ({
88
+ href,
89
+ url: webUrlOrNull(href, baseUrl),
90
+ rels: (params.find(([name]) => name === "rel")?.[1] ?? "").toLowerCase().split(/\s+/).filter(Boolean),
91
+ hreflang: params.filter(([name]) => name === "hreflang").map(([, value]) => value.trim()).filter(Boolean),
92
+ }));
93
+ }
@@ -1,10 +1,11 @@
1
1
  import { once } from "node:events";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { createInterface } from "node:readline";
4
- import { t } from "./locale.mjs";
4
+ import { currentLocale, t } from "./locale.mjs";
5
5
  import { analyzeObservations } from "./observations.mjs";
6
+ import { buildReport } from "./report-input.mjs";
6
7
  import { run } from "./seo-check.mjs";
7
- import { auditSite } from "./site-audit.mjs";
8
+ import { auditSite, PAGE_BYTES, TIMEOUT_MS } from "./site-audit.mjs";
8
9
  import { compareReports } from "./visibility-comparison.mjs";
9
10
 
10
11
  const versions = ["2025-11-25", "2025-06-18"];
@@ -25,22 +26,58 @@ function tool(name, description, required, properties, runTool, openWorldHint =
25
26
  };
26
27
  }
27
28
 
29
+ const MAX_FILE_BYTES = 16 * 1024 * 1024;
30
+ const isWebAddress = (value) => typeof value === "string" && matches(value, url);
31
+
32
+ // 명령행 설정과 같은 형식을 받고, 파일 내용은 files에서 읽는다. 서버의 파일은 읽지 않는다.
33
+ function reportFromInline({ config, files = {} }) {
34
+ for (const [name, content] of Object.entries(files)) {
35
+ if (typeof content !== "string" || Buffer.byteLength(content) > MAX_FILE_BYTES) {
36
+ throw new Error(t(`files.${name}에는 16 MiB 이하의 문자열이 필요합니다.`, `files.${name} must be a string of at most 16 MiB.`));
37
+ }
38
+ }
39
+ const readText = async (name) => {
40
+ if (!Object.hasOwn(files, name)) throw new Error(t(`files에 ${name}의 내용이 필요합니다.`, `files must include the content of ${name}.`));
41
+ return files[name];
42
+ };
43
+ return buildReport(config, {
44
+ lang: config.locale === undefined ? currentLocale() : undefined,
45
+ readText,
46
+ readJson: async (name) => {
47
+ const content = await readText(name);
48
+ try { return JSON.parse(content.replace(/^\uFEFF/, "")); }
49
+ catch (error) { throw new Error(t(`JSON 형식 오류 (${name}): ${error.message}`, `Invalid JSON (${name}): ${error.message}`)); }
50
+ },
51
+ audit: () => {
52
+ const addresses = [config.targets ?? [], config.intentionallyExcluded ?? []];
53
+ if (!addresses.every((list) => Array.isArray(list) && list.every(isWebAddress)) || (config.sitemap !== undefined && !isWebAddress(config.sitemap))) {
54
+ throw new Error(t("targets, sitemap, intentionallyExcluded에는 HTTP(S) URL만 지정할 수 있습니다.", "targets, sitemap and intentionallyExcluded accept HTTP(S) URLs only."));
55
+ }
56
+ return auditSite({ targets: config.targets, sitemap: config.sitemap, limit: config.limit, expectIndexable: config.expectIndexable, intentionallyExcluded: config.intentionallyExcluded });
57
+ },
58
+ });
59
+ }
60
+
28
61
  const tools = new Map([
29
- tool("audit_url", "Audit one HTTP(S) page for technical SEO, indexing and llms.txt findings.", ["url"],
30
- { url, expectIndexable: boolean }, args =>
31
- run(args.url, { expectIndexable: args.expectIndexable, network: { maxBytes: 2 * 1024 * 1024, signal: AbortSignal.timeout(10000) } }), true),
62
+ tool("audit_url", "Audit one HTTP(S) page for technical SEO, indexing and llms.txt findings. Set expectIndexable for a page meant for search or expectExcluded for a page intentionally kept out of search; without either, noindex is reported for confirmation. Sitemaps and counterpart pages are not checked (use audit_site).", ["url"],
63
+ { url, expectIndexable: boolean, expectExcluded: boolean }, args => {
64
+ if (args.expectIndexable && args.expectExcluded) throw new Error(t("expectIndexable과 expectExcluded 중 하나만 지정하세요.", "Set only one of expectIndexable and expectExcluded."));
65
+ return run(args.url, { expectIndexable: args.expectIndexable, expectExcluded: args.expectExcluded, network: { maxBytes: PAGE_BYTES, signal: AbortSignal.timeout(TIMEOUT_MS) } });
66
+ }, true),
32
67
  tool("audit_site", "Audit HTTP(S) targets and discover pages from their sitemap or an explicit sitemap URL.", [],
33
- { targets: array(url, 100), sitemap: url, limit: { type: "integer", minimum: 1, maximum: 100 }, expectIndexable: boolean },
68
+ { targets: array(url, 100), sitemap: url, limit: { type: "integer", minimum: 1, maximum: 100 }, expectIndexable: boolean, intentionallyExcluded: array(url, 100) },
34
69
  args => {
35
70
  if (!args.targets?.length && !args.sitemap) throw new Error(t("targets 또는 sitemap을 지정하세요.", "Provide targets or sitemap."));
36
71
  return auditSite(args);
37
72
  }, true),
38
- tool("compare_reports", "Compare two inline Search Visibility report.json objects.", ["before", "after"],
73
+ tool("build_report", "Build a Search Visibility report.json from the CLI config settings, with each referenced file passed as text in files. Covers Search Console CSV, Google generative AI performance, Bing AI Performance, Naver Search Advisor, URL Inspection, AI answers and AI referrals, plus audits of HTTP(S) targets or a sitemap. Pass the result to compare_reports.", ["config"],
74
+ { config: object, files: object }, reportFromInline, true),
75
+ tool("compare_reports", "Compare two inline Search Visibility report.json objects (from build_report or the CLI). Changes are null, with reasons, when collection conditions differ or are not recorded. Inputs that are not compared are listed in notCompared.", ["before", "after"],
39
76
  { before: object, after: object }, ({ before, after }) => compareReports(before, after)),
40
77
  tool("analyze_observations", "Analyze recorded AI answers for brand mentions, citations and competitor gaps.", ["observations"],
41
78
  { brand: string, aliases: array(string, 100), domains: array(string, 100), ownedUrlPrefixes: array(string, 100),
42
79
  competitors: array({ ...object, description: "Each competitor has brand and optional aliases, domains and ownedUrlPrefixes." }, 100),
43
- observations: array({ ...object, description: "Each record has engine, query, observedAt, answer and sources (HTTP(S) URL array)." }, 10000) }, analyzeObservations),
80
+ observations: array({ ...object, description: "Each record has engine, query, observedAt, answer and sources (HTTP(S) URL array). Comparisons also need mode, locale, region and run (repetition number). status failed or no-answer records an attempt without answer and sources." }, 10000) }, analyzeObservations),
44
81
  ].map(entry => [entry.definition.name, entry]));
45
82
 
46
83
  function matches(value, schema) {