/** * WebMCP(브라우저 AI 에이전트 도구) 개별형 어댑터. * 코어(shopby-webmcp.js)는 async 로 따로 로드되며, 이 파일은 전역 큐(window.shopbyWebMcp)로만 코어와 통신한다. * * 몰에서 끄려면 custom-common.js 에 아래를 넣는다 (로드 순서와 관계없이 큐로 처리된다). * window.shopbyWebMcp = window.shopbyWebMcp || []; * window.shopbyWebMcp.push(['configure', { enabled: false }]); * 도구 일부만 끄려면 { disabledTools: ['clear_cart'] } 처럼 도구 이름을 넘긴다. */ (() => { const CURRENCY = 'KRW'; const CONFIRM_MODAL_TAG = 'shopby-confirm'; const GUEST_CART_KEY = 'GUEST_CART'; const UNAUTHORIZED = 401; // 회원 서버 장바구니는 쓰기 직후 조회가 옛 상태를 줄 수 있다 (실측: 통합형 DELETE /cart 200 직후 30ms 안의 GET 3회가 모두 // 삭제 전 상태, 개별형도 POST /cart 직후 같은 지연). 통합형 스킨 삭제 버튼은 약 240ms 뒤 재조회로 회복하므로 그보다 조금 늦게 1회만 다시 갱신한다 const CART_REFRESH_RETRY_DELAY_MS = 300; // 스킨 CART_STORAGE.MAX_QUANTITY — 어댑터 전용 헬퍼(getCartAction() 기본값)·몰 설정이 없을 때의 비회원 보관 상한 const DEFAULT_GUEST_CART_MAX_QUANTITY = 10; // 유입 채널 형식 검사(설계 R-5) — 형식에 맞지 않는 값은 싣지 않는다 const CHANNEL_TYPE_PATTERN = /^[A-Za-z0-9_-]{1,50}$/; // navigate 용 회원 화면 (D-17) — PAGE 상수는 vanilla-components 와 따로 배포되므로 어댑터가 경로를 직접 갖는다 const MY_PAGE_ROUTES = { coupons: '/pages/my/coupon-list.html', points: '/pages/my/accumulation-list.html', likes: '/pages/my/like-product-list.html', }; // 코어 routes 계약 — {name} 자리표시자는 코어가 encodeURIComponent 로 채운다 const createRoutes = (PAGE) => ({ main: PAGE.MAIN, productDetail: `${PAGE.PRODUCT_DETAIL}?productNo={productNo}`, search: `${PAGE.PRODUCT_LIST}?keywords={keyword}`, cart: PAGE.CART, orderSheet: `${PAGE.ORDER_SHEET_FORM}?ordersheetNo={orderSheetNo}`, orders: PAGE.ORDER_LIST, orderDetail: `${PAGE.ORDER_DETAIL}?orderNo={orderNo}`, myPage: PAGE.MY_PAGE, ...MY_PAGE_ROUTES, }); const toPositiveInteger = (value) => { const number = Number(value); return Number.isInteger(number) && number > 0 ? number : null; }; const pageTypeOf = (pathname, PAGE) => { if (pathname === PAGE.MAIN || pathname === '/index.html') { return 'main'; } const types = [ [PAGE.PRODUCT_DETAIL, 'product'], [PAGE.PRODUCT_LIST, 'search'], [PAGE.CART, 'cart'], [PAGE.ORDER_SHEET_FORM, 'orderSheet'], [PAGE.ORDER_COMPLETE, 'orderComplete'], [PAGE.ORDER_LIST, 'orders'], [PAGE.ORDER_DETAIL, 'orderDetail'], ]; const found = types.find(([path]) => path === pathname); return found ? found[1] : 'etc'; }; // 주문완료 페이지는 orderNo 를 넣어 get_order_detail 이 번호 없이도 동작하게 한다 const resolvePage = ({ pathname, search }, PAGE) => { const type = pageTypeOf(pathname, PAGE); const params = new URLSearchParams(search); const page = { type }; if (type === 'product') { const productNo = toPositiveInteger(params.get('productNo')); if (productNo !== null) { page.productNo = productNo; } } if (type === 'orderComplete' && params.get('orderNo')) { page.orderNo = params.get('orderNo'); } return page; }; const createAbortError = () => new DOMException('The operation was aborted.', 'AbortError'); const throwIfAborted = (signal) => { if (signal?.aborted) { throw createAbortError(); } }; // 스킨 헬퍼는 { error: { serverError: { ...본문, status } } } 컨텍스트를 던진다. // 코어 오류 정규화가 읽는 status·code·message 객체로 바꾼다 (상태 코드가 없으면 코어가 INTERNAL_ERROR 로 본다). const shapeError = (source, clientError) => { const shaped = { code: source.code ?? clientError?.code, message: source.message ?? clientError?.description, }; if (typeof source.status === 'number') { shaped.status = source.status; } return shaped; }; // 네트워크 오류(TypeError)·AbortError 는 코어가 그대로 판정하도록 넘긴다 const isNativeError = (error) => error instanceof Error || error?.name === 'AbortError'; const toAdapterError = (error) => { const serverError = error?.error?.serverError ?? error?.serverError; if (!serverError && isNativeError(error)) { return error; } return shapeError(serverError ?? error ?? {}, error?.error); }; // 코어 오류 정규화가 읽는 모양 — 기본 어댑터의 ShopApiError 와 같은 status·code·message(·unreadable) const httpFailure = (status, body, extra = {}) => ({ status, code: body?.code, message: body?.message, ...extra }); // 헬퍼 호출은 취소할 수 없으므로 호출 전후로 signal 을 확인한다 const runHelper = async (ctx, call) => { throwIfAborted(ctx?.signal); let result; try { result = await call(); } catch (error) { throw toAdapterError(error); } throwIfAborted(ctx?.signal); return result; }; const escapeHtml = (text) => String(text).replace( /[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]) ); const cartOptionsOf = (cart) => [...(cart?.deliveryGroups ?? []).flatMap((group) => group.orderProducts ?? []), ...(cart?.invalidProducts ?? [])] .filter(Boolean) .flatMap((product) => (product.orderProductOptions ?? []).map((option) => ({ cartNo: option.cartNo, productNo: product.productNo ?? option.productNo, optionNo: option.optionNo, orderCnt: option.orderCnt, optionInputs: option.optionInputs ?? [], baseProductNo: option.baseProductNo, })) ); // 추가상품 품목은 본상품 번호(baseProductNo)를 남겨야 장바구니·주문서에서 본상품에 묶인다 const withBaseProductNo = (line, baseProductNo) => typeof baseProductNo === 'number' ? { ...line, baseProductNo } : line; const withChannelType = (target, channelType) => (channelType ? { ...target, channelType } : target); const toCartLoad = ({ productNo, optionNo, orderCnt, baseProductNo }, channelType) => withChannelType(withBaseProductNo({ productNo, optionNo, orderCnt, optionInputs: [] }, baseProductNo), channelType); const validChannelType = (value) => (typeof value === 'string' && CHANNEL_TYPE_PATTERN.test(value) ? value : null); // 현재 주소의 channelType 쿼리 우선, 없거나 형식에 맞지 않으면 쿠키(utils.getChannelType). 둘 다 아니면 생략 (D-12) const readChannelType = (win, utils) => { const fromQuery = validChannelType(new URLSearchParams(win.location?.search ?? '').get('channelType')); if (fromQuery) { return fromQuery; } try { return typeof utils.getChannelType === 'function' ? validChannelType(utils.getChannelType()) : null; } catch (e) { return null; } }; // 스킨 ADD_GUEST_CART 병합 규칙 — 기존 행마다 같은 optionNo·양쪽 텍스트 옵션 없음·baseProductNo 엄격 일치인 첫 품목과 합친다. // 어느 기존 행과도 합쳐지지 않는 품목 수가 새로 생길 행 수다 const countNewGuestRows = (stored, loads) => { const merged = new Set( stored .map((row) => loads.findIndex( (load) => load.optionNo === row.optionNo && !load.optionInputs?.length && !row.optionInputs?.length && row.baseProductNo === load.baseProductNo ) ) .filter((index) => index !== -1) ); return loads.length - merged.size; }; // 코어가 add_to_cart 의 CART_FULL 로 바꾸는 형식 — 상태 코드 없는 Error + code·data (통합형 어댑터와 같음) const cartFullError = (itemCount, maxItems) => Object.assign(new Error('The guest cart is full.'), { code: 'CART_FULL', data: { itemCount, maxItems } }); const createConfirm = ({ EventManager, win }) => (message) => { // 확인 모달 모듈이 없는 화면에서는 이벤트에 응답할 리스너가 없어 영원히 기다리게 된다 if (!win.document?.querySelector(CONFIRM_MODAL_TAG)) { return Promise.resolve(win.confirm(message) === true); } return new Promise((resolve) => { let settled = false; const dismiss = () => settle(false); function settle(value) { if (settled) { return; } settled = true; // EventManager.fire 는 리스너 배열을 그대로 순회한다 — 순회 중에 off 하면 뒤 리스너를 건너뛰므로 순회가 끝난 뒤 해제한다 Promise.resolve().then(() => { EventManager.off('MODAL_CONFIRM_OPEN', dismiss); EventManager.off('MODAL_CONFIRM_CLOSE', dismiss); }); resolve(value); } EventManager.fire('MODAL_CONFIRM_OPEN', { message: escapeHtml(message), confirmLabel: '확인', cancelLabel: '취소', onConfirm: () => settle(true), onCancel: () => settle(false), }); // 자기 자신의 열림 이벤트에 걸리지 않게 연 뒤에 듣는다. 다른 확인 창이 덮거나 밖에서 닫으면 거절로 본다 EventManager.on('MODAL_CONFIRM_OPEN', dismiss); EventManager.on('MODAL_CONFIRM_CLOSE', dismiss); }); }; /** * 코어 Adapter 구현. * - 장바구니·주문서 변경: 기존 액션(getCartAction·getOrderSheetActions) — 비회원 장바구니와 배지 갱신을 그대로 따른다 * - 장바구니 조회: 회원은 기본 어댑터 getCart, 비회원은 비회원 장바구니 계산 API — 스킨 조회(fetchCartDetail)는 * 장바구니 화면의 상품·체크 상태·결제 금액 이벤트를 발생시켜 화면을 이 어댑터의 상태로 덮는다 * - 조회: 코어 기본 어댑터(createShopApiAdapter) — 스킨 조회 액션은 성공 시 화면 이벤트(QUERY_PRODUCT_DETAIL 등)를 * 발생시켜, 에이전트가 다른 상품을 조회하면 지금 보고 있는 화면이 그 상품으로 바뀐다 * 401 이면 스킨 토큰 갱신(utils.renewAccessToken) 1회 뒤 1회 재시도한다 * - 재입고 알림(requestRestockAlert)은 이름·연락처 입력이 필요해 구현하지 않는다 */ const createWebMcpAdapter = ({ skin, win, getCommonData, getPageHandlers = () => null }) => { const { actions, utils, constants, EventManager } = skin; const { PAGE } = constants; let cartAction = null; let orderSheetAction = null; let shopApi = null; let shopApiSource = null; const requireCommonData = () => { const commonData = getCommonData(); if (!commonData?.clientId) { throw new Error('WebMCP adapter is not ready: common data is missing'); } return commonData; }; // 장바구니 화면은 페이지 헬퍼의 cartAction 으로 변경한다 — 어댑터 전용 헬퍼는 변경 성공 때 자기 상태(기본 전체 체크)로 // 장바구니 이벤트를 발생시켜, 사용자가 해제한 체크가 refreshCart 전까지 잠깐 다시 켜진다 const pageCart = () => { const getPageCartAction = getPageHandlers()?.getCartAction; return (typeof getPageCartAction === 'function' ? getPageCartAction() : null) || null; }; const cart = () => { const pageCartAction = pageCart(); if (pageCartAction) { return pageCartAction; } cartAction = cartAction || actions.getCartAction(); return cartAction; }; // 실제로 담기를 부를 헬퍼의 비회원 보관 상한 — 페이지 헬퍼는 몰 설정(cartConfig.storageMaxQuantity, 없으면 10), // 어댑터 전용 헬퍼는 getCartAction() 기본값 10. 0 이면 스킨도 자르지 않는다 const guestCartLimit = () => { if (!pageCart()) { return DEFAULT_GUEST_CART_MAX_QUANTITY; } return getCommonData()?.mallConfig?.cartConfig?.storageMaxQuantity ?? DEFAULT_GUEST_CART_MAX_QUANTITY; }; const channelType = () => readChannelType(win, utils); const orderSheet = () => { if (!orderSheetAction) { const { clientId, env } = requireCommonData(); orderSheetAction = actions.getOrderSheetActions({ clientId, env }); } return orderSheetAction; }; const api = () => { const commonData = requireCommonData(); const createShopApiAdapter = win.ShopbyWebMCP?.createShopApiAdapter; if (typeof createShopApiAdapter !== 'function') { throw new Error('WebMCP adapter is not ready: core is not loaded'); } if (!shopApi || shopApiSource !== commonData) { shopApiSource = commonData; shopApi = createShopApiAdapter({ clientId: commonData.clientId, platform: commonData.platform, baseUrl: constants.API_BASE_URL_MAP.SHOP[commonData.env], getAccessToken: () => utils.memberAuth.get(), }); } return shopApi; }; // 기본 어댑터의 fetch 는 스킨 fetch 래퍼의 401 갱신 대상(baseURL 옵션이 있는 요청)이 아니라서 여기서 갱신한다. // 갱신은 동시에 여러 건이 401 을 받아도 한 번만 하고, 재시도는 호출당 한 번뿐이다. let renewing = null; const renewOnce = () => { if (!renewing) { renewing = (async () => { try { await utils.renewAccessToken(); } finally { renewing = null; } })(); } return renewing; }; // 토큰이 바뀌었을 때만 갱신 성공으로 본다 — 갱신 응답이 실패면 renewAccessToken 은 토큰을 바꾸지 않고 끝난다 const renewedSince = async (tokenBefore) => { try { await renewOnce(); } catch (e) { return false; } const tokenAfter = utils.memberAuth.get(); return Boolean(tokenAfter) && tokenAfter !== tokenBefore; }; const canRenew = (error, token) => error?.status === UNAUTHORIZED && Boolean(token) && typeof utils.renewAccessToken === 'function'; // 재시도도 401 이면 처음 오류를 던져 코어가 NOT_SIGNED_IN 으로 처리하게 한다 const retry = async (method, args, firstError) => { try { return await api()[method](...args); } catch (retryError) { throw retryError?.status === UNAUTHORIZED ? firstError : retryError; } }; const read = (method) => async (...args) => { const signal = args[args.length - 1]?.signal; const token = utils.memberAuth.get(); try { return await api()[method](...args); } catch (error) { if (!canRenew(error, token)) { throw error; } const renewed = await renewedSince(token); throwIfAborted(signal); if (!renewed) { throw error; } return retry(method, args, error); } }; const isSignedIn = () => utils.isSignedIn() === true; // 스킨 CartHelper.getGuestCarts(packages/shared/helpers/order/CartHelper/CartHelper.ts)와 같은 저장소·만료 판정. // 스킨은 담을 때 expireDate 를 getMilliseconds()(현재 초의 밀리초 0~999) + 보관 기간으로 저장하고(ADD_GUEST_CART) // 읽을 때도 같은 값과 비교한다. getTime() 과 비교하면 스킨이 저장한 품목이 전부 만료로 빠져 화면 장바구니와 달라지므로 // 시각이 아닌 스킨 기준값을 그대로 쓴다 const readGuestCarts = () => { let items = null; try { items = JSON.parse(win.localStorage.getItem(constants.GUEST_CART ?? GUEST_CART_KEY) ?? '[]'); } catch (e) { items = null; } const skinExpireBase = new Date().getMilliseconds(); return Array.isArray(items) ? items.filter(({ expireDate }) => (expireDate === null ? true : expireDate > skinExpireBase)) : []; }; const parseJson = (text) => { try { return { ok: true, data: text ? JSON.parse(text) : null }; } catch (e) { return { ok: false, data: null }; } }; // 스킨 장바구니 헬퍼가 비회원 장바구니를 계산할 때 부르는 것과 같은 API. 저장소는 읽기만 한다 const requestGuestCart = async (ctx) => { const { clientId, platform, env } = requireCommonData(); const response = await win.fetch( `${constants.API_BASE_URL_MAP.SHOP[env]}/guest/cart?divideInvalidProducts=true`, { method: 'POST', headers: { Version: '1.0', clientId, platform, 'Content-Type': 'application/json' }, body: JSON.stringify(readGuestCarts()), signal: ctx?.signal, } ); const parsed = parseJson(await response.text()); if (!response.ok) { throw httpFailure(response.status, parsed.data); } if (!parsed.ok) { throw httpFailure(response.status, null, { unreadable: true }); } return parsed.data; }; const readMemberCart = read('getCart'); // 장바구니 화면은 자기 페이지 헬퍼로 다시 그리는 refreshCart 를 넘긴다(체크 상태 유지). 그 밖의 화면은 배지만 갱신한다 const refreshCartView = () => { try { const refreshCart = getPageHandlers()?.refreshCart; if (typeof refreshCart === 'function') { refreshCart(); return; } cart().fetchCartCount(); } catch (e) { // 화면 갱신 실패가 도구 결과로 번지지 않게 한다 } }; const getCartData = (ctx) => (isSignedIn() ? readMemberCart(ctx) : requestGuestCart(ctx)); // 코어가 같은 호출에서 이미 읽은 장바구니(ctx.cart)가 있으면 다시 조회하지 않는다 (update_cart_item·checkout_cart) const cartDataFor = (ctx) => (ctx && 'cart' in ctx ? Promise.resolve(ctx.cart) : getCartData(ctx)); return { currency: CURRENCY, isSignedIn, // 비회원은 기존 화면처럼 로그인 화면을 거쳐 주문서로 간다 (비회원 주문 선택 포함) navigate: (url) => { const target = new URL(url, win.location.origin); const next = target.pathname === PAGE.ORDER_SHEET_FORM && !isSignedIn() ? `${PAGE.SIGN_IN}?from=${encodeURIComponent(url)}` : url; win.location.assign(next); }, confirm: createConfirm({ EventManager, win }), // 회원은 서버 조회 지연에 대비해 한 번 더 갱신한다 — 그때 장바구니 화면 핸들러가 없으면 배지만 갱신한다 onCartChanged: () => { refreshCartView(); if (isSignedIn()) { win.setTimeout(refreshCartView, CART_REFRESH_RETRY_DELAY_MS); } }, searchProducts: read('searchProducts'), getProductDetail: read('getProductDetail'), getOrders: read('getOrders'), getOrderDetail: read('getOrderDetail'), getCategories: read('getCategories'), getProductReviews: read('getProductReviews'), getProductCoupons: read('getProductCoupons'), downloadCoupon: read('downloadCoupon'), getRelatedProducts: read('getRelatedProducts'), likeProduct: read('likeProduct'), // 주문서 금액 조회 (D-14). 스킨 주문서 액션은 화면 상태를 바꿀 수 있어 기본 어댑터로 조회한다 getOrderSheet: read('getOrderSheet'), // 회원 전용 API. 장바구니 화면 헬퍼의 미리보기는 실패를 「함께 삭제 없음」으로 바꾸므로 기본 어댑터로 직접 묻는다 getCartDeletionPreview: read('getCartDeletionPreview'), getCart: getCartData, // 비회원은 스킨 ADD_GUEST_CART 가 상한을 넘으면 앞(오래된 것)부터 잘라내므로, 넘을 담기는 부르기 전에 거절한다 // — 확인을 거치지 않는 삭제 경로를 만들지 않는다 (설계 6절, 보안 재판정 B1 Tampering) addToCart: (items, ctx) => { const channel = channelType(); const loads = items.map((item) => toCartLoad(item, channel)); if (!isSignedIn()) { const limit = guestCartLimit(); const stored = readGuestCarts(); if (limit && stored.length + countNewGuestRows(stored, loads) > limit) { return Promise.reject(cartFullError(stored.length, limit)); } } return runHelper(ctx, () => cart().addToCart(loads)); }, // PUT /cart 는 텍스트 옵션 입력값도 함께 받으므로 지금 값을 유지해 보낸다 updateCartItems: async (changes, ctx) => { const options = cartOptionsOf(await cartDataFor(ctx)); return runHelper(ctx, () => cart().modifyCart( changes.map(({ cartNo, orderCnt }) => ({ cartNo, orderCnt, optionInputs: options.find((option) => option.cartNo === cartNo)?.optionInputs ?? [], })) ) ); }, removeCartItems: (cartNos, ctx) => runHelper(ctx, () => cart().deleteCartNos(cartNos)), clearCart: async (ctx) => { const cartNos = cartOptionsOf(await getCartData(ctx)).map((option) => option.cartNo); return cartNos.length > 0 ? runHelper(ctx, () => cart().deleteCartNos(cartNos)) : null; }, // 주문서 생성 액션은 products 가 필수라 cartNos 주문도 장바구니에서 품목을 찾아 함께 보낸다 (장바구니 화면과 같은 요청). // standaloneCartNos 는 본상품 없이 주문하는 선택 추가상품 — 관계를 풀어 일반 상품으로 보낸다 // 유입 채널은 products[]·최상위에 싣는다. 최상위 trackingKey 는 makeOrderSheet(OrderSheetHelper)가 쿠키로 채운다 createOrderSheet: async (query, ctx) => { const channel = channelType(); let payload; if (Array.isArray(query.cartNos)) { const options = cartOptionsOf(await cartDataFor(ctx)); const standalone = query.standaloneCartNos ?? []; const products = query.cartNos .map((cartNo) => options.find((option) => option.cartNo === cartNo)) .filter(Boolean) .map(({ cartNo, productNo, optionNo, orderCnt, optionInputs, baseProductNo }) => withChannelType( withBaseProductNo( { productNo, optionNo, orderCnt, optionInputs }, standalone.includes(cartNo) ? null : baseProductNo ), channel ) ); payload = { cartNos: query.cartNos, products }; } else { payload = { cartNos: null, products: query.products.map((item) => toCartLoad(item, channel)) }; } const result = await runHelper(ctx, () => orderSheet().makeOrderSheet(withChannelType(payload, channel))); return result?.data; }, }; }; // 옵션 트리에서 optionNo 까지의 경로(단계별 노드)를 찾는다 const isLeafOf = (node, optionNo) => node.optionNo === optionNo && !(node.children ?? []).length; const findOptionPath = (nodes, optionNo) => { for (const node of nodes ?? []) { if (isLeafOf(node, optionNo)) { return [node]; } const rest = findOptionPath(node.children, optionNo); if (rest) { return [node, ...rest]; } } return null; }; const listOf = (data) => { if (Array.isArray(data)) { return data; } return data ? [data] : []; }; const quantityOf = (controller, optionNo) => (controller.quantities ?? []).find((quantity) => quantity.optionNo === optionNo); // 컨트롤러들의 선택 가능 옵션(optionNo 기준 한 번씩)과 현재 선택(수량) const selectionOf = (list) => { const seen = new Set(); const options = list .flatMap((controller) => controller.originOption?.flatOptions ?? []) .filter((option) => { if (seen.has(option.optionNo)) { return false; } seen.add(option.optionNo); return true; }) .map(({ optionNo, value, label, stockCnt, addPrice, saleType, forcedSoldOut }) => ({ optionNo, value, label, stockCnt, addPrice, saleType, forcedSoldOut, })); const selected = list.flatMap((controller) => (controller.quantities ?? []).map(({ optionNo, count }) => ({ optionNo, quantity: count })) ); return { options, selected }; }; /** * 상품 상세 옵션 선택 핸들러 (설계 U-4). * 상품 상세 페이지가 옵션 셀렉트 변경 때 쓰는 경로와 같다 — 옵션 컨트롤러의 selectOption·changeCount 를 부르고 * fetchOptionSelector() 로 QUERY_OPTION_CONTROLLER 를 발생시켜 선택 옵션 목록·금액을 다시 그린다. * 추가상품(D-9)은 getExtraProductOptionAction() 의 컨트롤러로 같은 방식으로 바꾸고 fetchExtraProductOptionSelector() 로 다시 그린다. * 추가상품 컨트롤러는 productNo 가 문자열이고, 필수 옵션 상품은 한 추가상품이 여러 컨트롤러로 나뉜다. */ const createProductOptionHandlers = ({ productNo, productOptionAction, extraProductOptionAction }) => { const controllers = () => listOf(productOptionAction.fetchOptionSelector()?.data); const extraControllers = () => listOf(extraProductOptionAction?.fetchExtraProductOptionSelector()?.data); const extraProductsOf = (list) => [...new Set(list.map((controller) => Number(controller.productNo)))].map((extraProductNo) => ({ productNo: extraProductNo, ...selectionOf(list.filter((controller) => Number(controller.productNo) === extraProductNo)), })); const getSelection = () => { const selection = { productNo, ...selectionOf(controllers()) }; return extraProductOptionAction ? { ...selection, extraProducts: extraProductsOf(extraControllers()) } : selection; }; // 고르지 않았으면 단계마다 선택한다. 옵션 단계가 없는 상품(단일·기본 옵션)은 이미 수량 목록에 있다 const selectInto = (list, optionNo) => { const existing = list.find((controller) => quantityOf(controller, optionNo)); if (existing) { return existing; } for (const controller of list) { const levels = controller.options ?? []; const path = findOptionPath(levels[0]?.children, optionNo); if (path) { path.forEach((node, index) => controller.selectOption({ labelId: levels[index].id, optionId: node.id, index }) ); return controller; } } return null; }; const isExtraTarget = (targetNo) => Boolean(extraProductOptionAction) && typeof targetNo === 'number' && targetNo !== Number(productNo); const selectOptions = ({ optionNo, quantity, productNo: targetNo }) => { const isExtra = isExtraTarget(targetNo); const list = isExtra ? extraControllers().filter((candidate) => Number(candidate.productNo) === targetNo) : controllers(); const controller = selectInto(list, optionNo); if (!controller) { throw new Error(`Option ${optionNo} is not available on this page`); } const current = quantityOf(controller, optionNo); if (current && current.count !== quantity) { controller.changeCount({ optionId: current.id, count: quantity }); } if (isExtra) { extraProductOptionAction.fetchExtraProductOptionSelector(); } else { productOptionAction.fetchOptionSelector(); } }; return { getSelection, selectOptions }; }; const isQueue = (value) => Array.isArray(value) || typeof value?.push === 'function'; // 코어 init 은 첫 번째만 받아들인다. setPage 는 PAGE_LOAD_COMPLETED(공통 데이터 준비) 뒤에만 보낸다 const install = ({ win, skin }) => { const { EventManager, constants } = skin; let loaded = false; let commonData = null; let handlers = {}; // 코어가 로드되면 전역이 코어 큐로 바뀌므로 보낼 때마다 다시 읽는다 const send = (command) => { if (!isQueue(win.shopbyWebMcp)) { win.shopbyWebMcp = []; } win.shopbyWebMcp.push(command); }; // 코어 PageHandlers 계약(상품 상세 옵션)만 setPage 로 보낸다. refreshCart 는 어댑터 안에서만 쓴다 const productHandlers = () => { const { getSelection, selectOptions } = handlers; return getSelection && selectOptions ? { getSelection, selectOptions } : null; }; const currentPage = () => { const page = resolvePage(win.location, constants.PAGE); const pageHandlers = page.type === 'product' ? productHandlers() : null; return pageHandlers ? { ...page, handlers: pageHandlers } : page; }; const adapter = createWebMcpAdapter({ skin, win, getCommonData: () => commonData, getPageHandlers: () => handlers, }); send(['init', { routes: createRoutes(constants.PAGE), adapter }]); EventManager.on('PAGE_LOAD_COMPLETED', (data) => { loaded = true; commonData = data ?? null; send(['setPage', currentPage()]); }); skin.webMcp = { createProductOptionHandlers, setPageHandlers: (pageHandlers) => { handlers = { ...handlers, ...pageHandlers }; if (loaded) { send(['setPage', currentPage()]); } }, }; }; if (typeof module === 'object' && module && module.exports) { module.exports = { CART_REFRESH_RETRY_DELAY_MS, createRoutes, resolvePage, createWebMcpAdapter, createProductOptionHandlers, install, }; return; } try { install({ win: window, skin: ShopbySkin }); } catch (e) { // 도구 연결 실패가 화면 동작으로 번지지 않게 한다 — 이 경우 도구만 등록되지 않는다 } })();