최초 커밋 — 기존 코드 전체 + 문서 체계 신설

git 저장소가 없어 히스토리·협업 기반이 아예 없던 상태를 연다.
함께 문서를 재편했다. 그동안 문서가 있어도 "이 제품이 뭘 푸는가"와
"어떻게 도는가"를 담은 문서가 없어서, 목표 문장이 backend/frontend
README 두 곳에 복붙돼 있었다 — 상위 문서가 없어 아래로 샌 것이다.

신설
  README.md               레포 진입점 + 문서 지도 + 문서 규칙 4가지
  AGENTS.md               에이전트·신규 합류자용 함정 목록과 규약
                          (CLAUDE.md 는 여기로 걸린 심볼릭 링크)
  docs/PRODUCT.md         제품 정의 — 문제·사용자·원칙·**non-goals**·성공 기준
  docs/ARCHITECTURE.md    payload 경계·발행 파이프라인·서빙 결정·앱 분리 설계

이동
  backend/docs/DECISIONS.md → docs/DECISIONS.md
    백엔드만의 결정이 아니다. 게다가 코드 주석 ~25곳이 이미
    `docs/DECISIONS.md` 로 적고 있어 레포 루트 기준으로는 그게 맞다.

갱신
  docs/DEPLOY.md          서빙 결정 반영 — nginx 정적 서빙이 지금 경로(3절),
                          Azure 는 나중에 켤 때(4절)로 분리
  docs/ARCHITECTURE.md    사이트 = 한 장(2026-08-31) 구조 반영
  docs/COLLECTION_SEO_AEO_FLOW.md
                          robots.txt·sitemap.xml 은 오리진 루트에만 굽는다는 점 명시
  frontend/site/scripts/prerender.ts
                          헤더 주석의 렌더 보고서 경로가 실제(422줄)와 달라 수정

.gitignore
  ★ CLAUDE.md 를 더 이상 무시하지 않는다. 에이전트 지침은 팀과 모든
    에이전트가 공유하는 규약이라 커밋해야 한다 — 무시하면 클론한 사람이
    "배포 후 republish_all.py 필수" 같은 함정을 전달받지 못한다.
    개인용 오버라이드는 ~/.claude/CLAUDE.md 에 둔다.
This commit is contained in:
minaChoi committed 2026-08-31 13:57:59 +09:00
commit 6784e59ca5
713 files changed
+68390

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
import type {SitePayload} from '@o2o/shared';
import {collectJsonLd} from './jsonld';
import type {PageMeta} from './meta';
/**
* <head> 를 문자열로 만든다.
*
* 리액트 컴포넌트가 아니라 문자열인 이유: 프리렌더가 정적 HTML 파일을 직접 쓰기 때문이다.
* 헬멧류 라이브러리를 끼우면 하이드레이션 이후에 head 가 바뀌는데,
* 그 시점엔 크롤러가 이미 원본 HTML 을 읽고 떠난 뒤다.
*/
const ESCAPE_MAP: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
};
export function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (char) => ESCAPE_MAP[char]);
}
/**
* JSON-LD 안의 `</script`, `<!--` 은 스크립트 블록을 조기 종료시킨다.
* HTML 이스케이프가 아니라 유니코드 이스케이프로 막는다 — JSON 값 자체는 그대로 유지된다.
*/
function serializeJsonLd(node: unknown): string {
return JSON.stringify(node)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026');
}
function tag(name: string, attrs: Record<string, string | undefined>): string {
const rendered = Object.entries(attrs)
.filter(([, value]) => value != null && value !== '')
.map(([key, value]) => `${key}="${escapeHtml(String(value))}"`)
.join(' ');
return ` <${name} ${rendered} />`;
}
export interface HeadOptions {
payload: SitePayload;
meta: PageMeta;
/** 클라이언트 번들 경로(하이드레이션용). manifest 에서 읽어 넘긴다. */
scriptSrc?: string;
cssHrefs?: string[];
}
/** 템플릿 색을 CSS 변수로. 사장님이 고른 색이 여기서 실제 페이지 색이 된다. */
export function themeStyle(payload: SitePayload): string {
const {colors} = payload.theme;
return [
' <style>',
' :root {',
` --tpl-primary: ${colors.primary};`,
` --tpl-secondary: ${colors.secondary};`,
` --tpl-bg: ${colors.bg};`,
` --tpl-card: ${colors.card};`,
` --tpl-text: ${colors.text};`,
` --tpl-accent: ${colors.accent};`,
' }',
' </style>',
].join('\n');
}
export function renderHead({payload, meta, scriptSrc, cssHrefs = []}: HeadOptions): string {
const {place, site} = payload;
// 사이트가 호스트 하나 아래 `/s/<slug>` 로 놓이므로, 정적 파일 링크도 그 아래를 가리켜야 한다.
const base = site.basePath.replace(/\/+$/, '');
const jsonLd = collectJsonLd(payload, {title: meta.title, description: meta.description});
const lines: string[] = [
' <meta charset="UTF-8" />',
' <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />',
` <title>${escapeHtml(meta.title)}</title>`,
tag('meta', {name: 'description', content: meta.description}),
tag('link', {rel: 'canonical', href: meta.canonical}),
// 색인을 막을 이유가 없다 — 이 사이트는 색인되라고 존재한다.
tag('meta', {
name: 'robots',
content: 'index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1',
}),
tag('meta', {'http-equiv': 'content-language', content: 'ko-KR'}),
// 신선도 — AI 검색이 오래된 페이지를 뒤로 미룬다.
tag('meta', {name: 'dateModified', content: site.updatedAt}),
tag('meta', {name: 'datePublished', content: site.publishedAt}),
// Open Graph
tag('meta', {property: 'og:type', content: 'website'}),
tag('meta', {property: 'og:site_name', content: place.name}),
tag('meta', {property: 'og:locale', content: 'ko_KR'}),
tag('meta', {property: 'og:title', content: meta.title}),
tag('meta', {property: 'og:description', content: meta.description}),
tag('meta', {property: 'og:url', content: meta.canonical}),
tag('meta', {property: 'og:image', content: meta.ogImage}),
tag('meta', {property: 'og:image:alt', content: meta.ogImageAlt}),
// Twitter
tag('meta', {name: 'twitter:card', content: meta.ogImage ? 'summary_large_image' : 'summary'}),
tag('meta', {name: 'twitter:title', content: meta.title}),
tag('meta', {name: 'twitter:description', content: meta.description}),
tag('meta', {name: 'twitter:image', content: meta.ogImage}),
];
// 지역 메타 — 네이버·다음이 읽고, 지역 질의 매칭에 쓰인다.
if (place.latitude != null && place.longitude != null) {
lines.push(
tag('meta', {name: 'geo.position', content: `${place.latitude};${place.longitude}`}),
tag('meta', {name: 'ICBM', content: `${place.latitude}, ${place.longitude}`}),
);
}
// geo.region 은 ISO 3166-2 코드를 기대한다 — 지역명을 그대로 넣으면(`KR-경기`) 아무도 못 읽는다.
if (place.addressRegionCode) {
lines.push(tag('meta', {name: 'geo.region', content: place.addressRegionCode}));
}
if (place.addressLocality || place.addressRegion) {
lines.push(tag('meta', {name: 'geo.placename', content: place.name}));
}
lines.push(
' <link rel="preconnect" href="https://fonts.googleapis.com" />',
' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />',
' <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300..900&family=Noto+Serif+KR:wght@300..700&display=swap" rel="stylesheet" />',
// 기계용 파일을 head 에서도 가리킨다 — llms.txt 는 아직 표준이 아니라 링크로 힌트를 준다.
tag('link', {rel: 'sitemap', type: 'application/xml', href: `${base}/sitemap.xml`}),
tag('link', {rel: 'alternate', type: 'text/plain', href: `${base}/llms.txt`, title: 'LLM 요약'}),
);
cssHrefs.forEach((href) => lines.push(tag('link', {rel: 'stylesheet', href})));
lines.push(themeStyle(payload));
jsonLd.forEach((node) => {
lines.push(
` <script type="application/ld+json">${serializeJsonLd(node)}</script>`,
);
});
if (scriptSrc) {
lines.push(` <script type="module" src="${escapeHtml(scriptSrc)}"></script>`);
}
return lines.filter(Boolean).join('\n');
}
+7
View File
@@ -0,0 +1,7 @@
export * from './jsonld';
export * from './meta';
export * from './head';
export * from './robots';
export * from './sitemap';
export * from './llms';
export * from './verify';
+286
View File
@@ -0,0 +1,286 @@
import {
PlaceCategory,
factBool,
factValue,
joinUrl,
sanitizeUnits,
selectPublishable,
selectPublishableFaqs,
type FactEntry,
type SitePayload,
} from '@o2o/shared';
/**
* 구조화 데이터(JSON-LD).
*
* 이 프로젝트의 목표 문장 그대로 — "AI 검색이 이 가게를 공식 홈페이지 기준으로 설명하게 만드는 것".
* 그 설명의 재료가 여기서 나간다.
*
* ★ 두 가지를 절대 어기지 않는다.
* 1) 화면에 없는 값을 JSON-LD 에 넣지 않는다. 어긋나면 구조화 데이터 스팸으로 취급되고,
* 백엔드 발행 게이트도 JSONLD_MISMATCH 로 막는다.
* 2) 확인되지 않은 fact 는 넣지 않는다. 전부 selectPublishable() 을 통과한 값만 쓴다.
* "값이 없다"와 "확인 전이라 가렸다"를 구분하지 않고, 둘 다 그냥 내보내지 않는다.
*/
/** 업종 → Schema.org 최상위 타입. 업종이 늘면 여기 한 줄만 는다. */
export const SCHEMA_TYPE: Record<PlaceCategory, string> = {
[PlaceCategory.LODGING]: 'LodgingBusiness',
[PlaceCategory.CAFE]: 'CafeOrCoffeeShop',
[PlaceCategory.RESTAURANT]: 'Restaurant',
[PlaceCategory.TOUR_ACTIVITY]: 'TouristAttraction',
};
/** 업종 → 하위 단위의 Schema.org 타입과 URL 경로. */
export const UNIT_SPEC: Record<PlaceCategory, {type: string; path: string; label: string}> = {
[PlaceCategory.LODGING]: {type: 'HotelRoom', path: 'rooms', label: '객실'},
[PlaceCategory.CAFE]: {type: 'MenuItem', path: 'menu', label: '메뉴'},
[PlaceCategory.RESTAURANT]: {type: 'MenuItem', path: 'menu', label: '메뉴'},
[PlaceCategory.TOUR_ACTIVITY]: {type: 'Product', path: 'programs', label: '프로그램'},
};
export type Json = Record<string, unknown>;
/** null·undefined·빈 문자열·빈 배열 키를 통째로 뺀다. 빈 값이 실린 JSON-LD 는 감점이다. */
function compact<T extends Json>(input: T): T {
const out: Json = {};
for (const [key, value] of Object.entries(input)) {
if (value == null || value === '') continue;
if (Array.isArray(value) && value.length === 0) continue;
out[key] = value;
}
return out as T;
}
function siteUrl(payload: SitePayload, ...parts: string[]): string {
return joinUrl(payload.site.origin, payload.site.basePath, ...parts);
}
/**
* amenityFeature — bool 타입 fact 를 시설 목록으로 옮긴다.
* 확인된 것만 들어가고, false 도 그대로 실린다("반려동물 불가"는 중요한 답이다).
*/
function amenityFeatures(facts: FactEntry[]): Json[] {
return selectPublishable(facts)
.filter((fact) => fact.type === 'bool')
.map((fact) =>
compact({
'@type': 'LocationFeatureSpecification',
name: fact.label,
value: factBool(facts, fact.key) ?? undefined,
}),
);
}
function postalAddress(payload: SitePayload): Json | undefined {
const {place} = payload;
const street = place.roadAddress ?? place.address;
if (!street) return undefined;
return compact({
'@type': 'PostalAddress',
streetAddress: street,
addressLocality: place.addressLocality,
addressRegion: place.addressRegion,
postalCode: place.postalCode,
addressCountry: 'KR',
});
}
function geoCoordinates(payload: SitePayload): Json | undefined {
const {latitude, longitude} = payload.place;
if (latitude == null || longitude == null) return undefined;
return {'@type': 'GeoCoordinates', latitude, longitude};
}
/** 대표 이미지 우선, 대체 텍스트가 있는 것만. alt 없는 이미지는 애초에 렌더도 안 한다. */
function imageUrls(payload: SitePayload, limit = 6): string[] {
return payload.media
.filter((m) => m.alt?.trim())
.sort((a, b) => Number(Boolean(b.isPrimary)) - Number(Boolean(a.isPrimary)))
.slice(0, limit)
.map((m) => m.url);
}
/** 확정된 채널만 sameAs 로 나간다 — 확정 전 URL 은 동명 업소일 수 있다. */
function sameAs(payload: SitePayload): string[] {
return payload.links.filter((link) => link.confirmed && link.url).map((link) => link.url);
}
/** 숙박의 체크인·체크아웃은 Schema.org 에 전용 속성이 있다. 있으면 반드시 채운다. */
function lodgingExtras(payload: SitePayload): Json {
const {facts} = payload;
return {
checkinTime: factValue(facts, 'check_in_time'),
checkoutTime: factValue(facts, 'check_out_time'),
petsAllowed: factBool(facts, 'pet_allowed'),
numberOfRooms: payload.units.length || undefined,
smokingAllowed: factBool(facts, 'smoking'),
};
}
function categoryExtras(payload: SitePayload): Json {
if (payload.place.category === PlaceCategory.LODGING) return lodgingExtras(payload);
const hours = factValue(payload.facts, 'business_hours') ?? factValue(payload.facts, 'open_hours');
return {
openingHours: hours,
servesCuisine: factValue(payload.facts, 'cuisine'),
acceptsReservations: factBool(payload.facts, 'reservation'),
};
}
/** 하위 단위(객실·메뉴·프로그램). 확인된 fact 만 스펙으로 붙는다. */
function unitNodes(payload: SitePayload): Json[] {
const spec = UNIT_SPEC[payload.place.category];
const mediaById = new Map(payload.media.map((m) => [m.mediaId, m]));
return sanitizeUnits(payload.units).map((unit) =>
compact({
'@type': spec.type,
'@id': `${siteUrl(payload, spec.path, unit.slug)}#unit`,
name: unit.name,
url: siteUrl(payload, spec.path, unit.slug),
description: factValue(unit.facts, 'room_intro') ?? factValue(unit.facts, 'description'),
occupancy: occupancy(unit.facts),
bed: factValue(unit.facts, 'bed_type'),
floorSize: floorSize(unit.facts),
amenityFeature: amenityFeatures(unit.facts),
image: unit.mediaIds
.map((id) => mediaById.get(id))
.filter((m) => m?.alt?.trim())
.map((m) => m!.url),
}),
);
}
function occupancy(facts: FactEntry[]): Json | undefined {
const max = factValue(facts, 'max_capacity');
if (!max) return undefined;
return compact({
'@type': 'QuantitativeValue',
value: Number(max) || undefined,
minValue: Number(factValue(facts, 'standard_capacity')) || undefined,
unitText: '명',
});
}
function floorSize(facts: FactEntry[]): Json | undefined {
const size = factValue(facts, 'room_size');
if (!size) return undefined;
return {'@type': 'QuantitativeValue', value: Number(size) || size, unitCode: 'MTK'};
}
/** 사업장 본체. 모든 페이지에 같은 @id 로 실린다 — AI 가 페이지들을 한 업소로 묶는 열쇠다. */
export function businessJsonLd(payload: SitePayload): Json {
const {place, narrative} = payload;
const spec = UNIT_SPEC[place.category];
return compact({
'@context': 'https://schema.org',
'@type': SCHEMA_TYPE[place.category] ?? 'LocalBusiness',
'@id': `${siteUrl(payload)}#business`,
name: place.name,
alternateName: place.englishName,
url: siteUrl(payload),
description: narrative.summary ?? narrative.about[0],
telephone: place.phone,
email: place.email,
address: postalAddress(payload),
geo: geoCoordinates(payload),
image: imageUrls(payload),
priceRange: priceRange(payload),
amenityFeature: amenityFeatures(payload.facts),
sameAs: sameAs(payload),
[spec.type === 'MenuItem' ? 'hasMenu' : 'containsPlace']: unitNodes(payload),
...categoryExtras(payload),
});
}
/** 최저~최고 요금. 단위 fact 의 숫자만 모은다 — 확인 안 된 요금은 애초에 안 들어온다. */
function priceRange(payload: SitePayload): string | undefined {
const prices = sanitizeUnits(payload.units)
.flatMap((unit) =>
['weekday_price', 'weekend_price', 'peak_price', 'price'].map((key) =>
Number(factValue(unit.facts, key)),
),
)
.filter((n) => Number.isFinite(n) && n > 0);
if (prices.length === 0) return undefined;
const min = Math.min(...prices);
const max = Math.max(...prices);
const fmt = (n: number) => n.toLocaleString('ko-KR');
return min === max ? `${fmt(min)}원` : `${fmt(min)}원 ~ ${fmt(max)}원`;
}
/**
* FAQPage — AEO 에서 가장 크게 먹히는 마크업.
* "체크인 몇 시예요?" 같은 질문에 이 홈페이지가 답으로 잡히는 자리다.
* 확인된 FAQ 가 하나도 없으면 아예 내보내지 않는다(빈 FAQPage 는 감점).
*/
export function faqJsonLd(payload: SitePayload): Json | null {
const faqs = selectPublishableFaqs(payload.faqs);
if (faqs.length === 0) return null;
return {
'@context': 'https://schema.org',
'@type': 'FAQPage',
'@id': `${siteUrl(payload, 'faq')}#faq`,
mainEntity: faqs.map((faq) => ({
'@type': 'Question',
name: faq.question,
acceptedAnswer: {'@type': 'Answer', text: faq.answer},
})),
};
}
export function websiteJsonLd(payload: SitePayload): Json {
return compact({
'@context': 'https://schema.org',
'@type': 'WebSite',
'@id': `${siteUrl(payload)}#website`,
name: payload.place.name,
url: siteUrl(payload),
inLanguage: 'ko-KR',
publisher: {'@id': `${siteUrl(payload)}#business`},
});
}
/** 이 페이지가 언제 기준인지. AI 검색은 신선도를 본다 — 없으면 오래된 페이지로 취급된다. */
export function webPageJsonLd(
payload: SitePayload,
page: {title: string; description: string},
): Json {
return compact({
'@context': 'https://schema.org',
'@type': 'WebPage',
'@id': `${siteUrl(payload)}#webpage`,
url: siteUrl(payload),
name: page.title,
description: page.description,
inLanguage: 'ko-KR',
isPartOf: {'@id': `${siteUrl(payload)}#website`},
about: {'@id': `${siteUrl(payload)}#business`},
datePublished: payload.site.publishedAt,
dateModified: payload.site.updatedAt,
});
}
/** 한 페이지에 실릴 JSON-LD 전부. null 은 걸러진다. */
/**
* 이 사이트가 내보내는 구조화 데이터 전부.
*
* ★ 사이트가 한 장이라 BreadcrumbList 를 뺐다 — 상위 페이지가 없는 곳의 빵부스러기는
* 자기 자신 하나뿐이라 아무 정보도 주지 않는다.
* ★ FAQPage 는 조건 없이 싣는다. 예전에는 페이지마다 실을지 골랐는데, 이제 한 장이라
* FAQ 가 있으면 그 한 장에 있는 것이다.
*/
export function collectJsonLd(
payload: SitePayload,
page: {title: string; description: string},
): Json[] {
return [
businessJsonLd(payload),
websiteJsonLd(payload),
webPageJsonLd(payload, page),
payload.faqs.length > 0 ? faqJsonLd(payload) : null,
].filter((node): node is Json => node !== null);
}
+148
View File
@@ -0,0 +1,148 @@
import {
factText,
joinUrl,
sanitizeUnits,
selectPublishable,
selectPublishableFaqs,
type SitePayload,
} from '@o2o/shared';
import {SCHEMA_TYPE, UNIT_SPEC} from './jsonld';
/**
* llms.txt — LLM 이 이 가게를 설명할 때 쓸 사실 목록.
*
* HTML 을 파싱하지 않고도 한 파일에서 필요한 사실을 다 얻게 한다.
* (llmstxt.org 의 마크다운 관례를 따르되, 내용은 우리 규칙을 따른다.)
*
* ★ 규칙 세 가지.
* 1) 확인된 fact 만 쓴다 — selectPublishable() 을 통과하지 못한 값은 한 줄도 안 들어간다.
* 2) 사실만 쓴다. "아름다운", "최고의" 같은 형용사를 쓰지 않는다.
* LLM 이 그대로 인용하면 그게 광고가 되고, 광고는 신뢰를 깎는다.
* 3) 모르는 것은 "정보 없음"이라고 쓴다. 빈칸으로 두면 LLM 이 추측으로 메운다 —
* 그 추측이 헛걸음을 만든다.
*/
export function renderLlmsTxt(payload: SitePayload): string {
const {place, site, narrative} = payload;
const url = (...parts: string[]) => joinUrl(site.origin, site.basePath, ...parts);
const facts = selectPublishable(payload.facts);
const spec = UNIT_SPEC[place.category];
const lines: string[] = [];
lines.push(`# ${place.name}`);
if (place.englishName) lines.push(`> ${place.englishName}`);
lines.push('');
lines.push(
`이 문서는 ${place.name}의 공식 홈페이지가 제공하는 사실 목록입니다. ` +
`모든 항목은 사업자 확인을 거쳤으며, 확인되지 않은 정보는 포함하지 않습니다.`,
);
lines.push('');
lines.push(`- 공식 홈페이지: ${url()}`);
lines.push(`- 업종 분류: ${SCHEMA_TYPE[place.category] ?? 'LocalBusiness'}`);
lines.push(`- 최종 확인: ${site.updatedAt}`);
lines.push('');
// ── 기본 정보 ────────────────────────────────────────
lines.push('## 기본 정보');
lines.push('');
pushFact(lines, '상호', place.name);
pushFact(lines, '주소', place.roadAddress ?? place.address);
pushFact(lines, '전화', place.phone);
pushFact(lines, '이메일', place.email);
if (place.latitude != null && place.longitude != null) {
pushFact(lines, '좌표', `${place.latitude}, ${place.longitude}`);
}
lines.push('');
// ── 확인된 이용 정보 ──────────────────────────────────
if (facts.length > 0) {
lines.push('## 이용 정보');
lines.push('');
for (const fact of facts) {
const value = factText(payload.facts, fact.key);
if (!value) continue;
lines.push(`- ${fact.label}: ${formatValue(fact.type, value)}`);
}
lines.push('');
}
// ── 하위 단위(객실·메뉴·프로그램) ──────────────────────
const units = sanitizeUnits(payload.units);
if (units.length > 0) {
lines.push(`## ${spec.label}`);
lines.push('');
for (const unit of units) {
lines.push(`### ${unit.name}`);
lines.push(`- 상세: ${url(spec.path, unit.slug)}`);
for (const fact of unit.facts) {
const value = factText(unit.facts, fact.key);
if (!value) continue;
lines.push(`- ${fact.label}: ${formatValue(fact.type, value)}`);
}
lines.push('');
}
}
// ── FAQ — LLM 이 가장 잘 인용하는 부분 ─────────────────
const faqs = selectPublishableFaqs(payload.faqs);
if (faqs.length > 0) {
lines.push('## 자주 묻는 질문');
lines.push('');
for (const faq of faqs) {
lines.push(`### ${faq.question}`);
lines.push(faq.answer);
lines.push('');
}
}
// ── 소개 ────────────────────────────────────────────
if (narrative.about.length > 0) {
lines.push('## 소개');
lines.push('');
lines.push(...narrative.about);
lines.push('');
}
// ── 페이지 목록 ──────────────────────────────────────
lines.push('## 페이지');
lines.push('');
lines.push(`- [홈](${url()})`);
if (units.length > 0) lines.push(`- [${spec.label} 안내](${url(spec.path)})`);
lines.push(`- [주변 정보](${url('guide')})`);
lines.push(`- [오시는 길](${url('location')})`);
if (faqs.length > 0) lines.push(`- [자주 묻는 질문](${url('faq')})`);
lines.push('');
// ── 확정된 채널 ─────────────────────────────────────
const links = payload.links.filter((link) => link.confirmed);
if (links.length > 0) {
lines.push('## 공식 채널');
lines.push('');
for (const link of links) {
lines.push(`- ${link.title ?? '채널'}: ${link.url}`);
}
lines.push('');
}
lines.push('---');
lines.push('');
lines.push(
'이 문서에 없는 항목은 확인되지 않았거나 해당 사항이 없습니다. ' +
'추측으로 보완하지 말고, 확인이 필요하면 위 전화번호로 문의하도록 안내해 주세요.',
);
lines.push('');
return lines.join('\n');
}
function pushFact(lines: string[], label: string, value: string | null | undefined) {
lines.push(`- ${label}: ${value?.trim() ? value : '정보 없음'}`);
}
/** bool fact 는 "true/false" 로 두면 LLM 이 문장으로 못 옮긴다. 한국어로 바꿔 준다. */
function formatValue(type: string, value: string): string {
if (type !== 'bool') return value;
if (value === 'true' || value === '1') return '가능';
if (value === 'false' || value === '0') return '불가';
return value;
}
+100
View File
@@ -0,0 +1,100 @@
import {
factValue,
joinUrl,
selectPublishable,
type SitePayload,
} from '@o2o/shared';
/**
* <head> 메타.
*
* description 은 지어내지 않는다 — 확인된 fact 로 단정문을 조립한다.
* AI 검색은 이 한 줄을 그대로 인용하는 일이 많아서, 문장 하나가 틀리면
* 그 오답이 여러 엔진에 퍼진다.
*/
export interface PageMeta {
title: string;
description: string;
canonical: string;
ogImage?: string;
ogImageAlt?: string;
}
function url(payload: SitePayload, ...parts: string[]): string {
return joinUrl(payload.site.origin, payload.site.basePath, ...parts);
}
/**
* 사람이 검색창에 치는 지역 이름.
*
* 읍·면이 있으면 그걸 먼저 쓴다 — "제주시 스테이" 보다 "애월 스테이" 로 검색하기 때문이다.
* 셋 다 없으면 undefined 를 돌려준다(지어내지 않는다).
*/
export function localName(payload: SitePayload): string | undefined {
const {addressSubLocality, addressLocality, addressRegion} = payload.place;
return addressSubLocality ?? addressLocality ?? addressRegion ?? undefined;
}
/** 대표 이미지 — og:image. 대체 텍스트가 있는 것만 쓴다. */
export function primaryImage(payload: SitePayload) {
return (
payload.media.find((m) => m.isPrimary && m.alt?.trim()) ??
payload.media.find((m) => m.alt?.trim())
);
}
/**
* 사실만으로 만드는 한 줄 요약.
*
* "제주 애월에 있는 달빛스테이 제주입니다. 체크인 16:00, 체크아웃 11:00. 반려동물 동반 불가."
* 형용사를 붙이지 않는다 — 확인된 값이 그대로 문장이 된다.
*/
export function factualSummary(payload: SitePayload): string {
const {place, facts} = payload;
const parts: string[] = [];
const where = place.addressLocality ?? place.addressRegion ?? place.roadAddress ?? place.address;
parts.push(where ? `${where}에 있는 ${place.name}입니다.` : `${place.name}입니다.`);
const checkIn = factValue(facts, 'check_in_time');
const checkOut = factValue(facts, 'check_out_time');
if (checkIn && checkOut) parts.push(`체크인 ${checkIn}, 체크아웃 ${checkOut}.`);
const hours = factValue(facts, 'business_hours') ?? factValue(facts, 'open_hours');
if (hours) parts.push(`영업시간 ${hours}.`);
const pet = factValue(facts, 'pet_allowed');
if (pet === 'false') parts.push('반려동물 동반 불가.');
if (pet === 'true') parts.push('반려동물 동반 가능.');
const parking = factValue(facts, 'parking');
if (parking === 'true') {
const capacity = factValue(facts, 'parking_capacity');
parts.push(capacity ? `주차 ${capacity}대 가능.` : '주차 가능.');
}
if (place.phone) parts.push(`문의 ${place.phone}.`);
return parts.join(' ');
}
/** 160자 안쪽으로 줄인다. 단어 중간에서 자르지 않는다. */
function clamp(text: string, max = 160): string {
if (text.length <= max) return text;
const cut = text.slice(0, max);
const lastSpace = cut.lastIndexOf(' ');
return `${(lastSpace > max * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`;
}
export function homeMeta(payload: SitePayload): PageMeta {
const image = primaryImage(payload);
return {
// 제목에 지역을 넣는다 — "애월 스테이" 같은 지역 질의에 걸리는 자리다.
title: [payload.place.name, localName(payload)].filter(Boolean).join(' · '),
description: clamp(payload.narrative.summary ?? factualSummary(payload)),
canonical: url(payload),
ogImage: image?.url,
ogImageAlt: image?.alt,
};
}
+65
View File
@@ -0,0 +1,65 @@
/**
* AI 크롤러를 **명시적으로 허용**하는 robots.txt.
*
* 보통 사이트들은 이 봇들을 막는다(학습 데이터로 쓰이는 게 싫어서).
* 우리는 반대다 — 이 서비스의 목표가 "AI 검색이 이 가게를 공식 홈페이지 기준으로
* 설명하게 만드는 것"이라, 읽히지 않으면 존재 이유가 없다.
* 기본값(=명시 없음)에 맡기지 않고 이름을 하나씩 적는 이유는,
* 일부 봇이 와일드카드보다 자기 이름 규칙을 우선으로 보기 때문이다.
*/
const AI_CRAWLERS = [
'GPTBot', // OpenAI 학습·검색
'OAI-SearchBot', // ChatGPT search
'ChatGPT-User', // ChatGPT 가 사용자를 대신해 여는 요청
'ClaudeBot', // Anthropic
'Claude-Web',
'anthropic-ai',
'PerplexityBot',
'Perplexity-User',
'Google-Extended', // Gemini / AI Overviews
'Applebot-Extended', // Apple Intelligence
'CCBot', // Common Crawl — 다수 모델의 상류 데이터
'Bytespider',
'Amazonbot',
'meta-externalagent',
'cohere-ai',
];
const SEARCH_CRAWLERS = [
'Googlebot',
'Bingbot',
'Yeti', // 네이버
'Daumoa', // 다음
];
/** 크롤러 허용 블록 — 루트용과 사이트용이 같은 목록을 쓴다. */
function allowBlocks(): string[] {
const blocks: string[] = ['User-agent: *', 'Allow: /', ''];
for (const bot of [...SEARCH_CRAWLERS, ...AI_CRAWLERS]) {
blocks.push(`User-agent: ${bot}`, 'Allow: /', '');
}
return blocks;
}
/**
* **오리진 루트의** robots.txt — 실제로 읽히는 유일한 robots.txt.
*
* ★ robots.txt 는 오리진 루트(`https://host/robots.txt`)에서만 읽힌다(RFC 9309).
* 발행 사이트는 `<host>/s/<slug>/` 아래에 있어서 사이트별 robots.txt 는 **아무도 읽지 않는다** —
* AI 크롤러를 아무리 명시 허용해도 파일이 그 자리에 있으면 효과가 0이다.
* 그래서 프리렌더가 사이트를 다 구운 뒤 여기서 루트 파일을 한 장 더 쓴다.
*
* ★ Sitemap 도 여기서만 전달된다. 사이트별 sitemap.xml 은 사이트맵 인덱스가 묶는다.
*/
export function renderRootRobotsTxt(origin: string): string {
const base = origin.replace(/\/+$/, '');
return [
'# 이 호스트의 사이트는 검색·AI 답변에 인용되기 위해 존재합니다.',
'# 아래 크롤러를 명시적으로 허용합니다.',
'',
...allowBlocks(),
`Sitemap: ${base}/sitemap.xml`,
'',
].join('\n');
}
+42
View File
@@ -0,0 +1,42 @@
import {escapeHtml} from './head';
export interface SiteEntry {
/** 사이트 홈 주소. 사이트가 한 장이라 이게 그 사이트의 유일한 URL 이다. */
loc: string;
/** 마지막 발행 시각(ISO). */
lastmod?: string;
}
/**
* 오리진 루트의 사이트맵 — 이 호스트의 **모든 사이트**를 한 파일에 담는다.
*
* ★ 예전에는 사이트마다 `sitemap.xml` 을 굽고 루트에 사이트맵 인덱스를 뒀다.
* 사이트가 한 장이 되면서 그 구조가 낭비가 됐다 — URL 한 줄짜리 파일이 사이트 수만큼
* 생기고, 인덱스는 그걸 다시 1,000줄로 가리킨다. 크롤러 왕복만 두 배가 된다.
*
* ★ 규격 상한은 파일당 URL 50,000개 · 압축 전 50MB 다. 그 선을 넘으면 그때
* 사이트맵을 여러 개로 쪼개고 인덱스를 되살린다(지금 구조에서 어렵지 않다).
*/
export function renderSiteUrlset(entries: SiteEntry[]): string {
const urls = entries
.map((entry) =>
[
' <url>',
` <loc>${escapeHtml(entry.loc)}</loc>`,
entry.lastmod ? ` <lastmod>${entry.lastmod}</lastmod>` : '',
' <changefreq>weekly</changefreq>',
' </url>',
]
.filter(Boolean)
.join('\n'),
)
.join('\n');
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
urls,
'</urlset>',
'',
].join('\n');
}
+171
View File
@@ -0,0 +1,171 @@
/**
* 구조화 데이터 ↔ 화면 값 대조 — ★ 절대규칙 3.
*
* 이 검증기가 절대 하면 안 되는 것:
* 1. JSON-LD 에만 있고 화면에 없는 값을 통과시키는 것 (검색엔진에 거짓을 심는다)
* 2. JSON-LD 가 **자기 자신**(script 블록)을 근거로 통과하는 것 (검사가 무의미해진다)
* 3. 화면이 뒷받침하는 사실을 표기 차이만으로 막는 것 (멀쩡한 사이트가 발행 못 한다)
*
* ★ 이 검사는 백엔드에 있었지만, 백엔드는 **자기만의 HTML** 을 따로 구워 그걸 봤다.
* 방문자가 보는 페이지는 이 렌더러가 굽는다 — 검사는 나갈 그 HTML 에 대고 해야 한다.
*/
import {describe, expect, it} from 'vitest';
import {verifyJsonLd, verifyGeo, visibleText} from './verify';
/** 사업장 페이지 한 장. 화면에 보이는 값만 본문에 넣는다. */
function page(body: string, head = ''): string {
return [
'<!doctype html><html><head>',
'<script type="application/ld+json">{"@type":"LodgingBusiness","telephone":"02-0000-0000"}</script>',
'<style>.x{color:red}</style>',
head,
'</head><body><div id="root">',
body,
'</div></body></html>',
].join('');
}
const BODY = [
'<h1>조이모텔</h1>',
'<p>전화 031-722-1942</p>',
'<p>경기도 성남시 중원구 A로 1</p>',
'<p>입실 15:00 / 퇴실 11:00</p>',
'<p>주중 20,000원</p><p>주말 60,000원</p>',
'<span>와이파이</span><span>주차 가능</span>',
'<p>디럭스룸</p>',
].join('');
describe('visibleText', () => {
it('script 를 걷어낸다 — JSON-LD 가 자기 자신을 근거로 통과하면 검사가 무의미해진다', () => {
expect(visibleText(page(BODY))).not.toContain('02-0000-0000');
});
it('style 과 태그를 걷어내고 텍스트만 남긴다', () => {
const text = visibleText(page(BODY));
expect(text).not.toContain('color:red');
expect(text).toContain('조이모텔');
});
it('HTML 엔티티를 되돌린다 — 화면에는 원문자가 보인다', () => {
expect(visibleText(page('<p>A&amp;B</p>'))).toContain('A&B');
});
});
describe('verifyJsonLd — 거짓을 잡는다', () => {
it('화면에 없는 전화번호를 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', telephone: '02-1234-5678'},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('telephone');
});
it('화면에 없는 편의시설을 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', amenityFeature: [{name: '와이파이'}, {name: '수영장'}]},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('수영장');
});
it('화면에 없는 객실 요금을 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', makesOffer: [{name: '디럭스룸', price: 99000}]},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('99');
});
it('화면에 없는 이미지 URL 을 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', image: ['https://cdn.example.com/없는사진.jpg']},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('image');
});
});
describe('verifyJsonLd — 사실은 통과시킨다', () => {
it('화면에 있는 값은 통과한다', () => {
expect(
verifyJsonLd(page(BODY), [
{
'@type': 'LodgingBusiness',
name: '조이모텔',
telephone: '031-722-1942',
checkinTime: '15:00',
amenityFeature: [{name: '와이파이'}, {name: '주차 가능'}],
},
]),
).toEqual([]);
});
it('이미지 URL 은 본문 텍스트가 아니라 요소 속성에서 찾는다', () => {
const html = page(`${BODY}<img src="https://cdn.example.com/a.jpg" alt="객실" />`);
expect(
verifyJsonLd(html, [{'@type': 'LodgingBusiness', image: ['https://cdn.example.com/a.jpg']}]),
).toEqual([]);
});
it('숫자는 1,000 단위 표기로도 찾는다 — 화면이 그렇게 그린다', () => {
expect(
verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', makesOffer: [{name: '디럭스룸', price: 20000}]},
]),
).toEqual([]);
});
it('페이지 메타 노드(WebPage·WebSite)는 본문 대조 대상이 아니다', () => {
// name·description·datePublished 는 <title>·<meta> 로 나가는 값이지 본문 문장이 아니다.
// 이걸 본문에서 찾으면 멀쩡한 사이트가 전부 실패한다.
expect(
verifyJsonLd(page(BODY), [
{'@type': 'WebPage', name: '본문에 없는 제목', description: '본문에 없는 설명'},
{'@type': 'WebSite', name: '본문에 없는 사이트명'},
]),
).toEqual([]);
});
it('bool 값과 좌표는 본문 대조에서 뺀다(따로 검사한다)', () => {
expect(
verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', petsAllowed: false, geo: {latitude: 37.1, longitude: 127.1}},
]),
).toEqual([]);
});
});
describe('verifyJsonLd — 합성값', () => {
it('priceRange 는 양끝이 다 보이면 통과한다', () => {
// 객실 요금에서 계산한 요약이다. 화면에는 20,000원·60,000원 이 각각 나온다.
expect(
verifyJsonLd(page(BODY), [{'@type': 'LodgingBusiness', priceRange: '20,000원 ~ 60,000원'}]),
).toEqual([]);
});
it('priceRange 한쪽이 화면에 없으면 그 조각을 사유로 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', priceRange: '20,000원 ~ 99,000원'},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('99,000원');
expect(problems[0]).not.toContain('20,000원');
});
});
describe('verifyGeo', () => {
it('좌표가 payload 와 같으면 통과', () => {
expect(verifyGeo([{geo: {latitude: 37.1, longitude: 127.1}}], 37.1, 127.1)).toEqual([]);
});
it('좌표가 어긋나면 잡는다 — 지도 핀이 엉뚱한 데 찍히는 것도 거짓이다', () => {
const problems = verifyGeo([{geo: {latitude: 37.9, longitude: 127.1}}], 37.1, 127.1);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('latitude');
});
it('payload 에 좌표가 없는데 구조화 데이터가 주장하면 잡는다', () => {
expect(verifyGeo([{geo: {latitude: 37.1, longitude: 127.1}}], undefined, undefined)).toHaveLength(2);
});
});
+223
View File
@@ -0,0 +1,223 @@
/**
* 구조화 데이터 ↔ 화면 값 대조. **★ 절대규칙 3 을 코드로 강제하는 자리다.**
*
* JSON-LD 는 AI 검색이 읽는 값이고 화면은 사람이 읽는 값이다. 둘이 다르면
* '검색엔진에만 다른 말을 하는' 상태가 된다 — 클로킹으로 취급될 수 있고, 무엇보다 거짓이다.
*
* ★ 왜 여기(렌더러 안)에 있나
* 예전에는 백엔드가 **자기만의 HTML 을 따로 구워** 그걸 대조했다. 방문자가 보는 페이지는
* 이 렌더러가 굽는데, 검사는 아무도 안 보는 페이지에 대고 하고 있었다 — 두 렌더러가
* 어긋나는 순간 게이트는 통과인데 실제 페이지는 다른 내용이 된다.
* 검사는 **나갈 바로 그 HTML** 에 대고 해야 의미가 있다.
*
* ★ 검사 방식
* JSON-LD 의 모든 스칼라 값이 화면 텍스트(또는 src/href)에 나타나는지 본다.
* 나타나지 않으면 "화면에 없는 것을 구조화 데이터가 주장하고 있다" 는 뜻이고, 그게 거짓이다.
*/
import type {Json} from './jsonld';
/** 화면에 텍스트로 나타나지 않는 구조·메타 값. 대조 대상에서 제외한다. */
const STRUCTURAL = new Set([
'@context',
'@type',
'@id',
'priceCurrency',
'addressCountry',
'inLanguage',
// 좌표는 지도 핀용 메타지 본문에 쓸 값이 아니다. 대신 payload 와 직접 대조한다(verifyGeo).
'latitude',
'longitude',
]);
/** 이름과 값을 따로 대조하는 서브트리. 일반 순회에서는 건너뛴다. */
const SPECIAL_SUBTREE = new Set(['amenityFeature', 'makesOffer', 'geo']);
/**
* **페이지를 설명하는** 노드. 본문 대조 대상이 아니다.
*
* ★ 이게 왜 필요한가
* WebPage 의 name·description·datePublished 는 `<title>` 과 `<meta>` 로 나가는 값이지
* 본문에 찍히는 문장이 아니다. 이걸 본문에서 찾으면 멀쩡한 사이트가 전부 실패한다.
* 대조해야 할 것은 **사업장에 대한 주장**(상호·주소·전화·가격·편의시설)과 FAQ 문답이다.
* 그것들이 화면에 없으면서 구조화 데이터에만 있으면 그게 거짓이다.
*/
const PAGE_META_TYPES = new Set(['WebPage', 'WebSite', 'BreadcrumbList', 'ImageObject']);
/**
* **합성값** 속성. 통째로는 화면에 없고, 구성 요소가 각각 화면에 있으면 통과다.
*
* 예: priceRange `'20,000원 ~ 60,000원'` 는 객실 요금에서 계산한 요약이다. 화면에는
* `20,000원` 과 `60,000원` 이 각 객실 카드에 따로 나온다 — 두 끝값이 다 보이면
* 그 범위는 화면이 뒷받침하는 주장이다. 통짜 비교를 고집하면 사실인 값이 발행을 막는다.
* ★ 대신 **구성 요소가 하나라도 화면에 없으면 실패**다 — 검사를 느슨하게 하는 게 아니다.
*/
const COMPOSITE_PROPS = new Set(['priceRange']);
/** 합성값을 구성 요소로 쪼갠다(범위 구분자·쉼표 기준). 빈 조각은 버린다. */
function splitComposite(token: string): string[] {
return token
.split(/\s*[~–—]\s*|\s+-\s+/)
.map((part) => part.trim())
.filter(Boolean);
}
const SCRIPT_RE = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style>/gi;
const TAG_RE = /<[^>]+>/g;
const ENTITIES: Record<string, string> = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
'&nbsp;': ' ',
};
function unescapeHtml(value: string): string {
return value
.replace(/&(?:amp|lt|gt|quot|#39|nbsp);/g, (m) => ENTITIES[m] ?? m)
.replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
.replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)));
}
/**
* 화면에 실제로 보이는 텍스트.
*
* ★ script(= JSON-LD 자신)와 style 을 먼저 걷어낸다. 이걸 안 하면 JSON-LD 가
* 자기 자신을 근거로 통과해버려 검사가 통째로 무의미해진다.
*/
export function visibleText(html: string): string {
const body = html.replace(SCRIPT_RE, ' ').replace(STYLE_RE, ' ').replace(TAG_RE, ' ');
return unescapeHtml(body).replace(/\s+/g, ' ').trim();
}
/** 리스트 인덱스를 건너뛴 실제 속성 이름. */
function propName(path: string[]): string {
for (let i = path.length - 1; i >= 0; i -= 1) {
if (!/^\d+$/.test(path[i])) return path[i];
}
return path[path.length - 1] ?? '';
}
type Scalar = string | number | boolean;
function* iterScalars(node: unknown, path: string[] = []): Generator<[string[], Scalar]> {
if (Array.isArray(node)) {
for (let i = 0; i < node.length; i += 1) yield* iterScalars(node[i], [...path, String(i)]);
return;
}
if (node && typeof node === 'object') {
for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
if (SPECIAL_SUBTREE.has(key)) continue;
yield* iterScalars(value, [...path, key]);
}
return;
}
if (node === null || node === undefined) return;
yield [path, node as Scalar];
}
/** 숫자를 화면 표기(1,000 단위 구분)로. 화면이 그렇게 그리므로 대조도 같은 표기를 본다. */
function asShown(value: Scalar): string[] {
if (typeof value === 'number' && Number.isFinite(value)) {
return [String(value), value.toLocaleString('ko-KR')];
}
return [String(value)];
}
/**
* JSON-LD 값이 전부 화면에 나타나는지 대조한다. 불일치 목록을 돌려준다(비면 통과).
*
* @param html 실제로 나갈 페이지 HTML
* @param nodes 그 페이지에 실린 JSON-LD 노드 전부
*/
export function verifyJsonLd(html: string, nodes: Json[]): string[] {
const text = visibleText(html);
const problems: string[] = [];
const seen = new Set<string>();
const report = (message: string) => {
// 같은 값이 여러 노드에 반복되면(name 은 사업장·WebSite·WebPage 에 다 있다)
// 같은 사유가 여러 번 쌓인다 — 운영자가 볼 목록이지 통계가 아니다.
if (seen.has(message)) return;
seen.add(message);
problems.push(message);
};
for (const node of nodes) {
// 페이지 메타 노드는 head 로 나가는 값이라 본문에 없다 — 대조하면 전부 오탐이 된다.
if (PAGE_META_TYPES.has(String(node['@type'] ?? ''))) continue;
for (const [path, value] of iterScalars(node)) {
const prop = propName(path);
if (STRUCTURAL.has(prop) || value === '' || typeof value === 'boolean') continue;
const token = String(value);
// URL·이미지는 본문 텍스트가 아니라 요소 속성(src/href)에 있다.
if (token.startsWith('http://') || token.startsWith('https://')) {
if (!html.includes(token)) report(`${prop}: '${token}' 이 화면에 없다`);
continue;
}
if (asShown(value).some((shown) => text.includes(shown))) continue;
if (COMPOSITE_PROPS.has(prop)) {
// 구성 요소가 전부 화면에 있으면 통과. 하나라도 없으면 그 조각을 사유로 남긴다.
const parts = splitComposite(token);
const missing = parts.filter((part) => !text.includes(part));
if (parts.length > 1 && missing.length === 0) continue;
report(`${prop}: '${missing.join(' · ') || token}' 이 화면에 없다`);
continue;
}
report(`${prop}: '${token}' 이 화면에 없다`);
}
// 편의시설·가격은 이름과 값을 따로 본다(구조가 name/value 쌍이라 일반 순회로는 약하다).
for (const feature of asArray(node.amenityFeature)) {
const name = String(feature?.name ?? '');
if (name && !text.includes(name)) report(`amenityFeature[${name}]: 화면에 없다`);
}
for (const offer of asArray(node.makesOffer)) {
const name = String(offer?.name ?? '');
if (name && !text.includes(name)) report(`makesOffer[${name}]: 화면에 없다`);
const price = offer?.price;
if (price !== undefined && price !== null && !asShown(price as Scalar).some((s) => text.includes(s))) {
report(`makesOffer[${name}].price: '${price}' 이 화면에 없다`);
}
}
}
return problems;
}
function asArray(value: unknown): Record<string, unknown>[] {
if (Array.isArray(value)) return value.filter((v) => v && typeof v === 'object');
if (value && typeof value === 'object') return [value as Record<string, unknown>];
return [];
}
/**
* 좌표가 payload 와 같은지. 지도 핀이 엉뚱한 데 찍히는 것도 거짓 정보다.
*
* 좌표는 화면 텍스트로 나오지 않아 본문 대조로는 확인할 수 없다 —
* 검사에서 빼는 것과 검사를 안 하는 것은 다르므로, 원본과 직접 맞춘다.
*/
export function verifyGeo(nodes: Json[], latitude?: number, longitude?: number): string[] {
const problems: string[] = [];
const TOLERANCE = 1e-6;
for (const node of nodes) {
const geo = node.geo as Record<string, unknown> | undefined;
if (!geo) continue;
const pairs: [string, unknown, number | undefined][] = [
['latitude', geo.latitude, latitude],
['longitude', geo.longitude, longitude],
];
for (const [name, shown, source] of pairs) {
if (source === undefined || typeof shown !== 'number' || Math.abs(shown - source) > TOLERANCE) {
problems.push(`geo.${name}: 구조화 데이터 ${String(shown)} != payload ${String(source)}`);
}
}
}
return problems;
}