(function () { // 기본 설정값 const DEFAULT_CONFIG = { apiUrl: "", sections: {}, images: {}, copy: {}, theme: {}, galleries: {}, lead: {}, assetBaseUrl: "", ui: { basic: true, pc: { sideFixed: false, sideToggle: false, bottomFixed: false, bottomToggle: false, bottomQuick: false, wingBanner: false, videoWingBanner: false, }, }, }; // 순수 객체인지 확인 const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value); // 빈 값인지 확인 const isBlank = (value) => value === undefined || value === null || value === ""; // 절대경로 URL 체크 const ABSOLUTE_URL_RE = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i; // 끝 슬래시 제거 function trimSlash(value = "") { return String(value).replace(/\/+$/, ""); } // 앞 슬래시 제거 function normalizeRelativePath(value = "") { return String(value).replace(/^\/+/, ""); } // 이미지/파일 경로 생성 function resolveAssetPath(path, fallback = "") { const source = isBlank(path) ? fallback : path; if (isBlank(source)) return ""; const raw = String(source).trim(); if ( ABSOLUTE_URL_RE.test(raw) || raw.startsWith("data:") || raw.startsWith("blob:") || raw.startsWith("tel:") || raw.startsWith("mailto:") || raw.startsWith("#") || raw.startsWith("?") ) { return raw; } const assetBaseUrl = trimSlash(config.assetBaseUrl || ""); const relativePath = normalizeRelativePath(raw); return assetBaseUrl ? `${assetBaseUrl}/${relativePath}` : relativePath; } // 설정값 깊은 병합 function deepMerge(base, override) { const output = { ...(isPlainObject(base) ? base : {}) }; if (!isPlainObject(override)) return output; Object.entries(override).forEach(([key, value]) => { if (isPlainObject(value) && isPlainObject(output[key])) { output[key] = deepMerge(output[key], value); return; } output[key] = value; }); return output; } // 이미지 override 적용 function resolveAssetOverride(key, fallback = "") { const images = isPlainObject(config.images) ? config.images : {}; const byKey = images[key]; if (!isBlank(byKey)) return resolveAssetPath(byKey, fallback); return resolveAssetPath(fallback); } // API 응답 정규화 function normalizeApiPayload(payload) { const raw = isPlainObject(payload?.data) ? payload.data : isPlainObject(payload) ? payload : {}; const { site: _ignored, ...rest } = raw; return rest; } // 최종 설정 생성 let config = deepMerge(DEFAULT_CONFIG, window.VendingConfig || {}); // 테마 CSS 변수 매핑 const THEME_CSS_VAR_MAP = { main1: "--color-main1", main2: "--color-main2", main3: "--color-main3", }; // 이미지 CSS 변수 매핑 const ASSET_CSS_VAR_MAP = { subPageNavBg: { cssVar: "--asset-sub-page-nav-bg", fallback: "img/sub-page/nav-bg.jpg", }, quickBottomBubbleModalBg: { cssVar: "--asset-quick-bottom-modal-bg", fallback: "", }, premiumDevelopBg: { cssVar: "--asset-premium-develop-bg", fallback: "", }, }; // CSS 배경 변수 적용 function setCssBackgroundVar(root, cssVar, path) { if (isBlank(path)) { root.style.removeProperty(cssVar); return; } root.style.setProperty( cssVar, `url("${String(path).replace(/"/g, '\\"')}")`, ); } // 테마/이미지 변수 적용 function applyTheme() { if (typeof document === "undefined" || !document.documentElement) return; const theme = isPlainObject(config.theme) ? config.theme : {}; const root = document.documentElement; Object.entries(THEME_CSS_VAR_MAP).forEach(([key, cssVar]) => { const next = theme[key]; if (isBlank(next)) root.style.removeProperty(cssVar); else root.style.setProperty(cssVar, next); }); Object.entries(ASSET_CSS_VAR_MAP).forEach(([key, meta]) => { setCssBackgroundVar( root, meta.cssVar, resolveAssetOverride(key, meta.fallback), ); }); const ogImage = document.querySelector('meta[property="og:image"]'); if (ogImage) { ogImage.setAttribute( "content", resolveAssetOverride("ogThumbnail", "Thumbnail-banner.png"), ); } } // 설정 경로 읽기 function readPath(path) { return String(path) .split(".") .reduce((carry, key) => { if (!isPlainObject(carry) && !Array.isArray(carry)) return undefined; return carry[key]; }, config); } // 설정값 읽기 function value(path, fallback) { const resolved = readPath(path); return isBlank(resolved) ? fallback : resolved; } // 이미지 경로 읽기 function asset(key, fallback) { return resolveAssetOverride(key, fallback); } // 문구 읽기 function copy(key, fallback) { const copies = isPlainObject(config.copy) ? config.copy : {}; const byKey = copies[key]; return isBlank(byKey) ? fallback : byKey; } // 섹션 노출 여부 function section(key, fallback = true) { const resolved = value(`sections.${key}`, fallback); if (typeof resolved === "string") { const normalized = resolved.trim().toLowerCase(); if (["false", "0", "none", "off", "hidden"].includes(normalized)) { return false; } if (["true", "1", "block", "flex", "on", "show"].includes(normalized)) { return true; } } return Boolean(resolved); } // 갤러리 이미지 배열 변환 function resolveGallery(list = []) { if (!Array.isArray(list)) return []; return list.map((item) => resolveAssetPath(item)).filter(Boolean); } // 문의 API 설정 function getLeadConfig() { const lead = isPlainObject(config.lead) ? config.lead : {}; return { apiUrl: String(lead.apiUrl || "").trim(), publicFormKey: String(lead.publicFormKey || "").trim(), successMessage: String(lead.successMessage || "문의가 접수되었습니다.").trim(), failureMessage: String( lead.failureMessage || "문의 접수에 실패했습니다. 잠시 후 다시 시도해 주세요.", ).trim(), }; } // UI 설정 읽기 function getUiConfig() { const raw = isPlainObject(config.ui) ? config.ui : {}; const merged = deepMerge(DEFAULT_CONFIG.ui, raw); if (typeof raw.basic !== "boolean" && typeof raw.mode === "string") { merged.basic = raw.mode !== "pc"; } return merged; } // 기본형 여부 function isBasicMode() { return getUiConfig().basic !== false; } // PC형 여부 function isPcMode() { return getUiConfig().basic === false; } // 데스크톱 여부 function isDesktop() { return ( typeof window !== "undefined" && window.matchMedia("(min-width: 991px)").matches ); } // PC 템플릿 사용 여부 function shouldUsePcTemplate() { return isPcMode() && isDesktop(); } // PC 옵션 활성 여부 function isPcFeatureEnabled(key) { const ui = getUiConfig(); return Boolean(ui.pc && ui.pc[key]); } // 원격 설정 불러오기 async function loadRemoteConfig() { const metaApiUrl = document.querySelector('meta[name="vending-config-api"]')?.content || ""; const apiUrl = config.apiUrl || metaApiUrl; if (!apiUrl) { applyTheme(); return config; } try { const response = await fetch(apiUrl, { cache: "no-store", credentials: config.credentials || "same-origin", headers: { Accept: "application/json", }, }); if (!response.ok) throw new Error(`HTTP ${response.status}`); config = deepMerge(config, normalizeApiPayload(await response.json())); } catch (error) { console.warn("[VendingRuntime] 설정 API를 불러오지 못했습니다.", error); } applyTheme(); return config; } // 설정 준비 Promise const ready = loadRemoteConfig(); // 외부 공개 API window.VendingRuntime = { ready, getConfig: async () => { await ready; return config; }, asset, assetPath: resolveAssetPath, resolveGallery, section, value, copy, getLeadConfig, getUiConfig, isBasicMode, isPcMode, isDesktop, shouldUsePcTemplate, isPcFeatureEnabled, applyTheme, }; })();