@adstage/web-sdk 2.3.7 → 2.4.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.
package/dist/index.esm.js CHANGED
@@ -1,6 +1,3 @@
1
- import { jsx } from 'react/jsx-runtime';
2
- import { createContext, useState, useEffect, useContext } from 'react';
3
-
4
1
  // 광고 타입 정의
5
2
  var AdType;
6
3
  (function (AdType) {
@@ -20,8 +17,15 @@ var Platform;
20
17
  // 광고 이벤트 타입
21
18
  var AdEventType;
22
19
  (function (AdEventType) {
23
- AdEventType["VIEWABLE"] = "VIEWABLE";
20
+ AdEventType["IMPRESSION"] = "IMPRESSION";
24
21
  AdEventType["CLICK"] = "CLICK";
22
+ AdEventType["HOVER"] = "HOVER";
23
+ AdEventType["VIEWABLE"] = "VIEWABLE";
24
+ AdEventType["VIEWABLE_IMPRESSION"] = "VIEWABLE_IMPRESSION";
25
+ AdEventType["COMPLETED"] = "COMPLETED";
26
+ AdEventType["VIDEO_START"] = "VIDEO_START";
27
+ AdEventType["VIDEO_COMPLETE"] = "VIDEO_COMPLETE";
28
+ AdEventType["ERROR"] = "ERROR";
25
29
  })(AdEventType || (AdEventType = {}));
26
30
  // 디바이스 타입
27
31
  var DeviceType;
@@ -31,6 +35,86 @@ var DeviceType;
31
35
  DeviceType["TABLET"] = "TABLET";
32
36
  })(DeviceType || (DeviceType = {}));
33
37
 
38
+ /**
39
+ * VIEWABLE 이벤트 추적 및 중복 방지 관리 클래스
40
+ * - 메모리 기반 중복 확인
41
+ * - 세션 스토리지 기반 영구 추적
42
+ * - 자동 정리 기능
43
+ * - ViewabilityTracker와 함께 사용하여 중복 viewable 이벤트 방지
44
+ */
45
+ class ViewableEventTracker {
46
+ /**
47
+ * 중복 viewable 이벤트 여부 확인
48
+ */
49
+ static isDuplicateViewable(adId, slotId, debug = false) {
50
+ const key = `${adId}_${slotId}`;
51
+ const now = Date.now();
52
+ // 메모리 기반 중복 확인 (새로고침 시 초기화됨)
53
+ const lastViewable = ViewableEventTracker.viewableTracker.get(key);
54
+ if (lastViewable && (now - lastViewable) < ViewableEventTracker.VIEWABLE_COOLDOWN) {
55
+ if (debug) {
56
+ console.log(`Duplicate viewable blocked for ad ${adId} in slot ${slotId}. Cooldown: ${Math.round((ViewableEventTracker.VIEWABLE_COOLDOWN - (now - lastViewable)) / 1000)}s remaining`);
57
+ }
58
+ return true;
59
+ }
60
+ // 세션 스토리지 기반 중복 확인 (새로고침 시에도 유지)
61
+ const sessionKey = `adstage_viewable_${key}`;
62
+ const sessionViewable = sessionStorage.getItem(sessionKey);
63
+ if (sessionViewable) {
64
+ const sessionTime = parseInt(sessionViewable, 10);
65
+ if (!isNaN(sessionTime) && (now - sessionTime) < ViewableEventTracker.VIEWABLE_COOLDOWN) {
66
+ if (debug) {
67
+ console.log(`Session-based duplicate viewable blocked for ad ${adId} in slot ${slotId}. Cooldown: ${Math.round((ViewableEventTracker.VIEWABLE_COOLDOWN - (now - sessionTime)) / 1000)}s remaining`);
68
+ }
69
+ // 메모리에도 기록하여 이후 요청 최적화
70
+ ViewableEventTracker.viewableTracker.set(key, sessionTime);
71
+ return true;
72
+ }
73
+ }
74
+ // viewable 이벤트 시점 기록 (메모리 + 세션 스토리지)
75
+ ViewableEventTracker.viewableTracker.set(key, now);
76
+ sessionStorage.setItem(sessionKey, now.toString());
77
+ // 오래된 세션 스토리지 데이터 정리 (선택적)
78
+ ViewableEventTracker.cleanupOldViewables();
79
+ return false;
80
+ }
81
+ /**
82
+ * 오래된 viewable 추적 데이터 정리
83
+ */
84
+ static cleanupOldViewables() {
85
+ const now = Date.now();
86
+ const cleanupThreshold = ViewableEventTracker.VIEWABLE_COOLDOWN * 2; // 쿨다운의 2배 시간이 지난 데이터 정리
87
+ // 세션 스토리지 정리
88
+ for (let i = 0; i < sessionStorage.length; i++) {
89
+ const key = sessionStorage.key(i);
90
+ if (key && key.startsWith('adstage_viewable_')) {
91
+ const timestamp = sessionStorage.getItem(key);
92
+ if (timestamp) {
93
+ const time = parseInt(timestamp, 10);
94
+ if (!isNaN(time) && (now - time) > cleanupThreshold) {
95
+ sessionStorage.removeItem(key);
96
+ i--; // 인덱스 조정
97
+ }
98
+ }
99
+ }
100
+ }
101
+ // 메모리 정리
102
+ for (const [key, timestamp] of ViewableEventTracker.viewableTracker.entries()) {
103
+ if ((now - timestamp) > cleanupThreshold) {
104
+ ViewableEventTracker.viewableTracker.delete(key);
105
+ }
106
+ }
107
+ }
108
+ /**
109
+ * 모든 추적 데이터 정리
110
+ */
111
+ static clear() {
112
+ ViewableEventTracker.viewableTracker.clear();
113
+ }
114
+ }
115
+ ViewableEventTracker.viewableTracker = new Map();
116
+ ViewableEventTracker.VIEWABLE_COOLDOWN = 300000; // 5분 쿨다운
117
+
34
118
  /**
35
119
  * SSR 안전한 DOM API 래퍼 클래스
36
120
  * 서버사이드 렌더링 환경에서 DOM API 접근 시 오류를 방지합니다.
@@ -318,453 +402,1050 @@ class DOMUtils {
318
402
  }
319
403
 
320
404
  /**
321
- * 기본 광고 렌더러 추상 클래스
405
+ * 디바이스 정보 수집 클래스
406
+ * - 브라우저 환경 정보 수집
407
+ * - 디바이스 ID 생성 및 관리
408
+ * - 세션 ID 생성 및 관리
322
409
  */
323
- class BaseAdRenderer {
324
- constructor(trackEvent) {
325
- this.trackEvent = trackEvent;
326
- }
410
+ class DeviceInfoCollector {
327
411
  /**
328
- * 공통 클릭 이벤트 핸들러 (SSR 안전)
412
+ * 디바이스 ID 생성 반환 (SSR 안전)
329
413
  */
330
- addClickHandler(element, ad, slot) {
331
- DOMUtils.safeAddEventListener(element, 'click', () => {
332
- this.trackEvent?.(ad._id, slot.id, 'CLICK');
333
- if (ad.linkUrl) {
334
- DOMUtils.safeWindowOpen(ad.linkUrl, '_blank');
335
- }
336
- });
414
+ static generateDeviceId() {
415
+ if (!DOMUtils.isBrowser())
416
+ return 'ssr_device_' + Date.now();
417
+ const stored = localStorage.getItem('adstage_device_id');
418
+ if (stored)
419
+ return stored;
420
+ const deviceId = 'device_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
421
+ localStorage.setItem('adstage_device_id', deviceId);
422
+ return deviceId;
337
423
  }
338
424
  /**
339
- * 공통 스타일 적용 유틸리티 (SSR 안전)
425
+ * 세션 ID 생성 반환 (SSR 안전)
340
426
  */
341
- applyStyles(element, styles) {
342
- DOMUtils.safeApplyStyles(element, styles);
427
+ static generateSessionId() {
428
+ if (!DOMUtils.isBrowser())
429
+ return 'ssr_session_' + Date.now();
430
+ const stored = sessionStorage.getItem('adstage_session_id');
431
+ if (stored)
432
+ return stored;
433
+ const sessionId = 'session_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
434
+ sessionStorage.setItem('adstage_session_id', sessionId);
435
+ return sessionId;
343
436
  }
344
437
  /**
345
- * 크기 파싱 유틸리티 (px, %, number 지원)
438
+ * 모바일 디바이스 여부 확인
346
439
  */
347
- parseSizeValue(value) {
348
- if (!value)
349
- return undefined;
350
- if (typeof value === 'number') {
351
- return value > 0 ? `${value}px` : undefined;
352
- }
353
- if (typeof value === 'string') {
354
- const trimmed = value.trim();
355
- if (!trimmed)
356
- return undefined;
357
- // 퍼센트 값 처리
358
- if (trimmed.endsWith('%')) {
359
- const percent = parseFloat(trimmed);
360
- return !isNaN(percent) && percent > 0 ? trimmed : undefined;
361
- }
362
- // px 값 처리 (px 단위 포함/미포함 모두 지원)
363
- const numValue = trimmed.endsWith('px')
364
- ? parseFloat(trimmed.slice(0, -2))
365
- : parseFloat(trimmed);
366
- return !isNaN(numValue) && numValue > 0 ? `${numValue}px` : undefined;
367
- }
368
- return undefined;
440
+ static isMobile() {
441
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
369
442
  }
370
443
  /**
371
- * 기본 컨테이너 스타일 (사용자 지정 크기만 적용)
444
+ * 플랫폼 타입 반환 (서버 enum에 맞춤)
372
445
  */
373
- getBaseContainerStyles(slot) {
374
- const styles = {
375
- cursor: 'pointer',
376
- position: 'relative',
377
- overflow: 'hidden',
378
- };
379
- // 사용자가 지정한 크기가 있을 때만 적용
380
- const parsedWidth = this.parseSizeValue(slot.width);
381
- const parsedHeight = this.parseSizeValue(slot.height);
382
- if (parsedWidth) {
383
- styles.width = parsedWidth;
384
- }
385
- if (parsedHeight) {
386
- styles.height = parsedHeight;
446
+ static getPlatform() {
447
+ const userAgent = navigator.userAgent.toLowerCase();
448
+ if (/iphone|ipad|ipod/.test(userAgent)) {
449
+ return 'ios';
387
450
  }
388
- return styles;
389
- }
390
- /**
391
- * 이미지 스타일 (고유 사이즈 유지, 사용자 지정 크기 우선)
392
- */
393
- getImageStyles(slot) {
394
- const styles = {
395
- display: 'block',
396
- 'object-position': 'center', // 🎯 이미지 항상 중앙 정렬
397
- };
398
- // 사용자가 컨테이너 크기를 지정했는지 확인
399
- const parsedWidth = this.parseSizeValue(slot?.width);
400
- const parsedHeight = this.parseSizeValue(slot?.height);
401
- const hasUserDefinedSize = parsedWidth || parsedHeight;
402
- if (hasUserDefinedSize) {
403
- // 🎯 사용자가 크기를 지정한 경우: 컨테이너에 꽉 차도록 설정
404
- styles.width = '100%';
405
- styles.height = '100%';
406
- styles['object-fit'] = 'cover'; // 컨테이너에 꽉 찬 상태로 비율 유지
407
- styles['object-position'] = 'center';
451
+ if (/android/.test(userAgent)) {
452
+ return 'android';
408
453
  }
409
- else {
410
- // 사용자가 크기를 지정하지 않은 경우: 원본 이미지 크기 유지
411
- styles['max-width'] = '100%';
412
- styles.height = 'auto';
454
+ if (DeviceInfoCollector.isMobile()) {
455
+ return 'web'; // 모바일
413
456
  }
414
- return styles;
457
+ return 'desktop'; // 데스크톱 웹
415
458
  }
416
459
  /**
417
- * 기본 폰트 스타일
460
+ * 완전한 디바이스 정보 수집
418
461
  */
419
- getBaseFontStyles() {
462
+ static collectDeviceInfo() {
463
+ const viewportInfo = DOMUtils.getViewportInfo();
420
464
  return {
421
- 'font-family': 'Arial, sans-serif',
422
- 'line-height': '1.4',
423
- 'word-break': 'keep-all',
465
+ deviceId: DeviceInfoCollector.generateDeviceId(),
466
+ sessionId: DeviceInfoCollector.generateSessionId(),
467
+ osVersion: DOMUtils.isBrowser() ? navigator.platform : 'SSR',
468
+ deviceModel: DOMUtils.isBrowser() ? navigator.platform : 'SSR',
469
+ appVersion: '1.0.0',
470
+ sdkVersion: '1.0.0',
471
+ language: DOMUtils.isBrowser() ? (navigator.language || 'ko') : 'ko',
472
+ country: 'KR', // 기본값
473
+ ipAddress: '', // 서버에서 자동으로 설정됨
474
+ userAgent: DOMUtils.isBrowser() ? navigator.userAgent : 'SSR',
475
+ timezone: DOMUtils.isBrowser() ? Intl.DateTimeFormat().resolvedOptions().timeZone : 'UTC',
476
+ viewportWidth: viewportInfo.width,
477
+ viewportHeight: viewportInfo.height,
478
+ screenWidth: DOMUtils.isBrowser() ? screen.width : 0,
479
+ screenHeight: DOMUtils.isBrowser() ? screen.height : 0,
480
+ colorDepth: DOMUtils.isBrowser() ? screen.colorDepth : 24,
481
+ pixelRatio: viewportInfo.pixelRatio,
482
+ connectionType: DOMUtils.isBrowser() ? (navigator.connection?.effectiveType || 'unknown') : 'unknown',
483
+ platform: DeviceInfoCollector.getPlatform(),
424
484
  };
425
485
  }
426
486
  /**
427
- * 이미지 요소 생성 (SSR 안전)
428
- */
429
- createImageElement(imageUrl, alt = '', slot) {
430
- const img = DOMUtils.safeCreateElement('img');
431
- if (!img)
432
- return null;
433
- img.src = imageUrl;
434
- img.alt = alt;
435
- this.applyStyles(img, this.getImageStyles(slot));
436
- return img;
437
- }
438
- /**
439
- * 텍스트 요소 생성 (SSR 안전)
487
+ * 슬롯 위치 정보 가져오기 (SSR 안전)
440
488
  */
441
- createTextElement(text, tag = 'div', additionalStyles = {}) {
442
- const element = DOMUtils.safeCreateElement(tag);
489
+ static getSlotPosition(containerId) {
490
+ const element = DOMUtils.safeGetElementById(containerId);
443
491
  if (!element)
444
- return null;
445
- DOMUtils.safeSetTextContent(element, text);
446
- this.applyStyles(element, {
447
- ...this.getBaseFontStyles(),
448
- ...additionalStyles,
449
- });
450
- return element;
492
+ return 'unknown';
493
+ const rect = element.getBoundingClientRect();
494
+ const scrollInfo = DOMUtils.getScrollInfo();
495
+ return `x:${Math.round(rect.left)},y:${Math.round(rect.top + scrollInfo.scrollTop)}`;
451
496
  }
497
+ }
498
+
499
+ /**
500
+ * AdStage SDK - API 헤더 유틸리티
501
+ * 공통 헤더 생성 로직
502
+ */
503
+ class ApiHeaders {
452
504
  /**
453
- * 플레이스홀더 요소 생성
505
+ * 표준 API 헤더 생성
454
506
  */
455
- createPlaceholder(slot, text = '광고') {
456
- let placeholder = DOMUtils.safeCreateElement('div');
457
- // SSR 환경에서 DOM을 사용할 수 없는 경우, 런타임에 생성되도록 함
458
- if (!placeholder) {
459
- // SSR에서는 빈 div를 반환하되, 브라우저에서는 제대로 작동하도록 함
460
- if (typeof document !== 'undefined') {
461
- placeholder = document.createElement('div');
462
- }
463
- else {
464
- // SSR 환경에서는 더미 객체 반환 (타입 단언 사용)
465
- placeholder = {};
466
- }
507
+ static create(apiKey, options) {
508
+ if (!apiKey) {
509
+ throw new Error('API key is required');
467
510
  }
468
- // DOM이 사용 가능한 경우에만 스타일 적용
469
- if (DOMUtils.canUseDOM() && placeholder) {
470
- this.applyStyles(placeholder, {
471
- ...this.getBaseContainerStyles(slot),
472
- background: '#f8f9fa',
473
- display: 'flex',
474
- 'align-items': 'center',
475
- 'justify-content': 'center',
476
- color: '#6c757d',
477
- ...this.getBaseFontStyles(),
478
- // 플레이스홀더는 최소 크기 보장
479
- 'min-width': '100px',
480
- 'min-height': '100px',
481
- });
482
- DOMUtils.safeSetTextContent(placeholder, text);
511
+ const headers = {
512
+ 'x-api-key': apiKey,
513
+ 'Content-Type': options?.contentType || 'application/json'
514
+ };
515
+ // User-Agent는 이벤트 추적에서 실제로 사용됨
516
+ if (typeof navigator !== 'undefined') {
517
+ headers['User-Agent'] = options?.userAgent || navigator.userAgent;
483
518
  }
484
- return placeholder;
519
+ // X-Current-URL은 현재 서버에서 사용하지 않으므로 제거
520
+ // 필요시 이벤트 데이터 body에 포함
521
+ return headers;
485
522
  }
486
- }
487
-
488
- /**
489
- * 배너 광고 렌더러 - 이미지만 표시
490
- */
491
- class BannerAdRenderer extends BaseAdRenderer {
492
- render(ad, slot) {
493
- const adElement = DOMUtils.safeCreateElement('div');
494
- if (!adElement) {
495
- // SSR 환경에서는 기본 div 반환
496
- return document.createElement('div');
497
- }
498
- // 기본 컨테이너 스타일 적용 (불필요한 스타일 제거)
499
- this.applyStyles(adElement, this.getBaseContainerStyles(slot));
500
- // 배너 광고는 이미지만 표시
501
- if (!ad.imageUrl) {
502
- // 이미지가 없는 경우 플레이스홀더 반환
503
- const placeholder = this.createPlaceholder(slot, '배너 광고');
504
- return placeholder || adElement;
505
- }
506
- const img = this.createImageElement(ad.imageUrl, '', slot);
507
- if (img) {
508
- DOMUtils.safeAppendChild(adElement, img);
509
- // 클릭 이벤트 추가
510
- this.addClickHandler(adElement, ad, slot);
523
+ /**
524
+ * 이벤트 추적용 헤더 생성
525
+ * User-Agent는 서버에서 실제로 사용됨
526
+ */
527
+ static createForEvents(apiKey, eventData) {
528
+ const baseHeaders = ApiHeaders.create(apiKey);
529
+ // User-Agent 오버라이드 (서버에서 실제 사용)
530
+ if (eventData?.userAgent) {
531
+ baseHeaders['User-Agent'] = eventData.userAgent;
511
532
  }
512
- return adElement;
533
+ // 다른 정보들은 HTTP 헤더가 아닌 이벤트 데이터 body에 포함하는 것이 적절
534
+ // (currentUrl, referrer 등은 POST body로 전송)
535
+ return baseHeaders;
513
536
  }
514
537
  }
515
538
 
516
539
  /**
517
- * 텍스트 광고 렌더러 - textContent만 표시
540
+ * 광고 이벤트 추적 관리 클래스
541
+ * - 광고 전용 이벤트 추적 및 전송
542
+ * - Viewable 이벤트 중복 방지 통합
543
+ * - 광고 서버 API 통신
518
544
  */
519
- class TextAdRenderer extends BaseAdRenderer {
520
- render(ad, slot) {
521
- let adElement = DOMUtils.safeCreateElement('div');
522
- if (!adElement) {
523
- return this.createPlaceholder(slot, '텍스트 광고');
524
- }
525
- // 기본 컨테이너 스타일
526
- const containerStyles = {
527
- ...this.getBaseContainerStyles(slot),
528
- padding: '20px',
529
- background: 'transparent',
530
- display: 'flex',
531
- 'align-items': 'center',
532
- 'justify-content': 'center',
533
- // text-align은 사용자가 설정할 수 있도록 기본값에서 제외
534
- ...this.getBaseFontStyles(),
535
- };
536
- // 사용자가 크기를 지정하지 않은 경우 컨텐츠에 맞춤
537
- if (!slot.width || slot.width === 0) {
538
- containerStyles.display = 'inline-flex';
539
- containerStyles['white-space'] = 'nowrap';
540
- containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
541
- }
542
- // height만 자동인 경우 줄바꿈 허용
543
- if ((slot.width && slot.width !== 0) && (!slot.height || slot.height === 0)) {
544
- containerStyles['white-space'] = 'normal';
545
- containerStyles['min-height'] = 'auto';
546
- containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
547
- }
548
- this.applyStyles(adElement, containerStyles);
549
- // 텍스트 광고는 textContent만 표시
550
- if (!ad.textContent) {
551
- // 텍스트가 없는 경우 플레이스홀더 반환
552
- return this.createPlaceholder(slot, '텍스트 광고');
553
- }
554
- // 텍스트 콘텐츠 생성
555
- const textContent = this.createTextElement(ad.textContent, 'div', {
556
- 'font-size': '16px',
557
- 'font-weight': '500',
558
- color: '#212529',
559
- width: '100%', // 전체 너비 사용하여 텍스트 정렬이 적용되도록 함
560
- });
561
- if (textContent) {
562
- adElement.appendChild(textContent);
563
- }
564
- // 사용자가 text-align을 지정했는지 확인하고 레이아웃 조정
565
- setTimeout(() => {
566
- if (!adElement || typeof window === 'undefined')
567
- return;
568
- const computedStyle = window.getComputedStyle(adElement);
569
- const textAlign = computedStyle.textAlign;
570
- // 사용자가 text-align을 설정했고, width가 없는 경우
571
- if (textAlign && textAlign !== 'start' && textAlign !== 'left' && (!slot.width || slot.width === 0)) {
572
- // 블록 레벨로 변경하여 text-align이 제대로 작동하도록 함
573
- adElement.style.display = 'block';
574
- adElement.style.whiteSpace = 'normal';
575
- // 최소 너비 설정 (텍스트가 한 줄일 때를 위해)
576
- if (textContent) {
577
- const textRect = textContent.getBoundingClientRect();
578
- if (textRect.width > 0) {
579
- adElement.style.minWidth = `${textRect.width}px`;
580
- }
545
+ class AdvertisementEventTracker {
546
+ constructor(baseUrl, apiKey, debug, slots) {
547
+ this.baseUrl = baseUrl;
548
+ this.apiKey = apiKey;
549
+ this.debug = debug;
550
+ this.slots = slots;
551
+ }
552
+ /**
553
+ * 광고 이벤트 추적 - viewability 데이터 지원
554
+ */
555
+ async trackAdvertisementEvent(adId, slotId, eventType, additionalData) {
556
+ try {
557
+ // VIEWABLE 이벤트의 경우 중복 확인
558
+ if (eventType === AdEventType.VIEWABLE) {
559
+ if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this.debug)) {
560
+ return; // 중복 viewable 이벤트이므로 추적하지 않음
581
561
  }
582
562
  }
583
- }, 0);
584
- // 클릭 이벤트 추가
585
- this.addClickHandler(adElement, ad, slot);
586
- return adElement;
587
- }
588
- }
589
-
590
- /**
591
- * 네이티브 광고 렌더러 - 이미지 + textContent 표시
592
- */
593
- class NativeAdRenderer extends BaseAdRenderer {
594
- render(ad, slot) {
595
- const adElement = DOMUtils.safeCreateElement('div');
596
- if (!adElement) {
597
- return document.createElement('div');
563
+ // 현재 슬롯 정보 가져오기
564
+ const slot = this.slots.get(slotId);
565
+ // 디바이스 정보 수집
566
+ const deviceInfo = DeviceInfoCollector.collectDeviceInfo();
567
+ // 광고 이벤트 데이터 구성 (DTO 구조에 맞춤)
568
+ const eventData = {
569
+ // 서버에서 자동 설정: orgId, advertisementId, action
570
+ // 하지만 DTO 검증을 위해 임시값 제공
571
+ orgId: 'temp', // 서버에서 API 키로부터 덮어씀
572
+ advertisementId: adId, // 서버에서 URL 파라미터로부터 덮어씀
573
+ action: eventType, // 서버에서 URL 파라미터로부터 덮어씀
574
+ // 필수 필드들
575
+ adType: slot?.adType || 'BANNER',
576
+ platform: deviceInfo.platform,
577
+ // 디바이스 정보는 deviceInfo 객체로 래핑
578
+ deviceInfo: deviceInfo,
579
+ // 페이지 및 슬롯 정보
580
+ pageUrl: DOMUtils.getPageInfo().url,
581
+ pageTitle: DOMUtils.getPageInfo().title,
582
+ referrer: DOMUtils.getPageInfo().referrer,
583
+ slotId,
584
+ slotPosition: DeviceInfoCollector.getSlotPosition(slot?.containerId || ''),
585
+ slotWidth: AdvertisementEventTracker.parseNumericValue(slot?.width),
586
+ slotHeight: AdvertisementEventTracker.parseNumericValue(slot?.height),
587
+ sessionId: deviceInfo.sessionId,
588
+ // 성능 메트릭
589
+ pageLoadTime: performance.now(),
590
+ // 추가 메타데이터
591
+ metadata: {
592
+ eventType,
593
+ sdkVersion: '1.0.0',
594
+ timestamp: Date.now(),
595
+ },
596
+ // viewable 관련 추가 데이터 (DTO 필드명과 매칭)
597
+ ...(additionalData?.viewabilityMetrics && {
598
+ isViewable: additionalData.viewabilityMetrics.isViewable,
599
+ exposureTime: additionalData.viewabilityMetrics.exposureTime,
600
+ maxVisibilityRatio: additionalData.viewabilityMetrics.maxVisibilityRatio,
601
+ firstViewableTime: additionalData.viewabilityMetrics.firstViewableTime,
602
+ // IAB 표준 준수 여부
603
+ iabCompliant: additionalData.viewabilityMetrics.isViewable,
604
+ }),
605
+ // fraud 관련 데이터 (DTO 필드명과 매칭)
606
+ ...(additionalData?.fraudScore !== undefined && {
607
+ fraudScore: additionalData.fraudScore,
608
+ fraudReasons: additionalData.fraudReasons,
609
+ riskLevel: additionalData.riskLevel,
610
+ }),
611
+ };
612
+ await fetch(`${this.baseUrl}/advertisements/events/${adId}/${eventType}`, {
613
+ method: 'POST',
614
+ headers: ApiHeaders.createForEvents(this.apiKey, eventData),
615
+ body: JSON.stringify(eventData),
616
+ });
617
+ if (this.debug) {
618
+ console.log(`Tracked advertisement event: ${eventType} for ad ${adId}`, eventData);
619
+ }
598
620
  }
599
- // 컨테이너 스타일 적용 (불필요한 스타일 제거)
600
- this.applyStyles(adElement, this.getBaseContainerStyles(slot));
601
- // 네이티브 광고는 이미지만 표시
602
- if (!ad.imageUrl) {
603
- // 이미지가 없는 경우 플레이스홀더 반환
604
- const placeholder = this.createPlaceholder(slot, '네이티브 광고');
605
- return placeholder || adElement;
621
+ catch (error) {
622
+ console.error('Failed to track advertisement event:', error);
606
623
  }
607
- // 이미지 생성 (고유 사이즈 또는 사용자 지정 크기)
608
- const img = this.createImageElement(ad.imageUrl, '', slot);
609
- if (img) {
610
- DOMUtils.safeAppendChild(adElement, img);
611
- // 클릭 이벤트 추가
612
- this.addClickHandler(adElement, ad, slot);
624
+ }
625
+ /**
626
+ * 크기 값을 숫자로 변환 (서버 API용)
627
+ */
628
+ static parseNumericValue(value) {
629
+ if (typeof value === 'number') {
630
+ return value;
613
631
  }
614
- return adElement;
632
+ if (typeof value === 'string') {
633
+ // px 단위 제거하고 숫자만 추출
634
+ const numericValue = parseFloat(value.replace(/px$/, ''));
635
+ return isNaN(numericValue) ? 0 : numericValue;
636
+ }
637
+ return 0; // 기본값
615
638
  }
616
639
  }
617
640
 
618
641
  /**
619
- * 비디오 광고 렌더러 - 비디오 또는 이미지 표시
642
+ * IAB 표준 준수 viewable impression 측정
620
643
  */
621
- class VideoAdRenderer extends BaseAdRenderer {
622
- render(ad, slot) {
623
- let adElement = DOMUtils.safeCreateElement('div');
624
- if (!adElement) {
625
- return this.createPlaceholder(slot, '비디오 광고');
626
- }
627
- // 컨테이너 스타일 적용 (불필요한 스타일 제거)
628
- this.applyStyles(adElement, {
629
- ...this.getBaseContainerStyles(slot),
630
- background: '#000',
631
- });
632
- // 비디오 광고는 비디오만 표시
633
- if (!ad.videoUrl) {
634
- // 비디오가 없는 경우 플레이스홀더 반환
635
- return this.createPlaceholder(slot, '비디오 광고');
636
- }
637
- const video = this.createVideoElement(ad.videoUrl, ad, slot);
638
- if (video) {
639
- adElement.appendChild(video);
640
- }
641
- // 클릭 이벤트 추가
642
- this.addClickHandler(adElement, ad, slot);
643
- return adElement;
644
+ // 광고 타입별 IAB 표준 설정
645
+ const VIEWABILITY_STANDARDS = {
646
+ BANNER: {
647
+ threshold: 0.5,
648
+ minDuration: 1000,
649
+ maxMeasureTime: 30000
650
+ },
651
+ VIDEO: {
652
+ threshold: 0.5,
653
+ minDuration: 2000,
654
+ maxMeasureTime: 60000
655
+ },
656
+ NATIVE: {
657
+ threshold: 0.5,
658
+ minDuration: 1000,
659
+ maxMeasureTime: 30000
660
+ },
661
+ INTERSTITIAL: {
662
+ threshold: 0.5,
663
+ minDuration: 1000,
664
+ maxMeasureTime: 10000
665
+ },
666
+ TEXT: {
667
+ threshold: 0.5,
668
+ minDuration: 1000,
669
+ maxMeasureTime: 30000
670
+ },
671
+ POPUP: {
672
+ threshold: 0.5,
673
+ minDuration: 1000,
674
+ maxMeasureTime: 10000
644
675
  }
645
- /**
646
- * 비디오 요소 생성
647
- */
648
- createVideoElement(videoUrl, ad, slot) {
649
- const video = DOMUtils.safeCreateElement('video');
650
- if (!video)
651
- return null;
652
- video.src = videoUrl;
653
- video.controls = true;
654
- // 비디오도 이미지와 같은 스타일 적용
655
- this.applyStyles(video, this.getImageStyles(slot));
656
- // 비디오 이벤트 추적
657
- video.addEventListener('play', () => {
658
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
659
- });
660
- video.addEventListener('ended', () => {
661
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
662
- });
663
- return video;
676
+ };
677
+ class ViewabilityTracker {
678
+ constructor(element, adType, onViewable) {
679
+ this.observer = null;
680
+ this.viewabilityTimer = null;
681
+ this.maxVisibilityTimer = null;
682
+ this.startTime = 0;
683
+ this.maxVisibilityRatio = 0;
684
+ this.firstViewableTime = null;
685
+ this.isViewableAchieved = false;
686
+ this.element = element;
687
+ this.config = VIEWABILITY_STANDARDS[adType] || VIEWABILITY_STANDARDS.BANNER;
688
+ this.onViewableCallback = onViewable;
689
+ this.startTime = performance.now();
690
+ this.initIntersectionObserver();
691
+ this.initMaxMeasureTimer();
664
692
  }
665
- }
666
-
667
- /**
668
- * 전면/팝업 광고 렌더러 - 핵심 콘텐츠만 표시
669
- */
670
- class InterstitialAdRenderer extends BaseAdRenderer {
671
- render(ad, slot) {
672
- let adElement = DOMUtils.safeCreateElement('div');
673
- if (!adElement) {
674
- return this.createPlaceholder(slot, '전면 광고');
693
+ initIntersectionObserver() {
694
+ // IntersectionObserver 지원 확인
695
+ if (!('IntersectionObserver' in window)) {
696
+ console.warn('IntersectionObserver not supported, viewability tracking disabled');
697
+ return;
675
698
  }
676
- // 컨테이너 스타일 적용 (불필요한 스타일 제거)
677
- this.applyStyles(adElement, {
678
- ...this.getBaseContainerStyles(slot),
679
- display: 'flex',
680
- 'flex-direction': 'column',
699
+ this.observer = new IntersectionObserver((entries) => this.handleIntersection(entries), {
700
+ threshold: [0, 0.1, 0.25, 0.5, 0.75, 1.0],
701
+ rootMargin: '0px'
681
702
  });
682
- // 우선순위: 1. 이미지, 2. 비디오, 3. 텍스트
683
- if (ad.imageUrl) {
684
- const img = this.createImageElement(ad.imageUrl, '', slot);
685
- if (img) {
686
- adElement.appendChild(img);
703
+ this.observer.observe(this.element);
704
+ }
705
+ handleIntersection(entries) {
706
+ entries.forEach(entry => {
707
+ const visibilityRatio = entry.intersectionRatio;
708
+ const isVisible = this.isDocumentVisible();
709
+ // 최대 가시성 비율 추적
710
+ this.maxVisibilityRatio = Math.max(this.maxVisibilityRatio, visibilityRatio);
711
+ // Viewable 조건 확인 (50% 이상 + 문서 가시성)
712
+ if (visibilityRatio >= this.config.threshold && isVisible) {
713
+ this.startViewabilityTimer();
687
714
  }
688
- }
689
- else if (ad.videoUrl) {
690
- // 이미지가 없고 비디오가 있는 경우
691
- const video = this.createVideoElement(ad.videoUrl, ad, slot);
692
- if (video) {
693
- adElement.appendChild(video);
715
+ else {
716
+ this.stopViewabilityTimer();
694
717
  }
718
+ });
719
+ }
720
+ isDocumentVisible() {
721
+ // 단순한 문서 가시성 확인
722
+ return !document.hidden && document.visibilityState === 'visible';
723
+ }
724
+ startViewabilityTimer() {
725
+ if (this.viewabilityTimer || this.isViewableAchieved)
726
+ return;
727
+ if (this.firstViewableTime === null) {
728
+ this.firstViewableTime = performance.now();
695
729
  }
696
- else {
697
- // 모든 콘텐츠가 없는 경우
698
- return this.createPlaceholder(slot, '전면 광고');
730
+ this.viewabilityTimer = setTimeout(() => {
731
+ this.onViewabilityAchieved();
732
+ }, this.config.minDuration);
733
+ }
734
+ stopViewabilityTimer() {
735
+ if (this.viewabilityTimer) {
736
+ clearTimeout(this.viewabilityTimer);
737
+ this.viewabilityTimer = null;
699
738
  }
700
- // 클릭 이벤트 추가
701
- this.addClickHandler(adElement, ad, slot);
702
- return adElement;
703
739
  }
704
- /**
705
- * 비디오 요소 생성
706
- */
707
- createVideoElement(videoUrl, ad, slot) {
708
- const video = DOMUtils.safeCreateElement('video');
709
- if (!video)
710
- return null;
711
- video.src = videoUrl;
712
- video.controls = true;
713
- // 비디오도 이미지와 같은 스타일 적용
714
- this.applyStyles(video, this.getImageStyles(slot));
715
- // 비디오 이벤트 추적
716
- video.addEventListener('play', () => {
717
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
718
- });
719
- video.addEventListener('ended', () => {
720
- this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
721
- });
722
- return video;
740
+ initMaxMeasureTimer() {
741
+ // 최대 측정 시간 후 자동 종료
742
+ this.maxVisibilityTimer = setTimeout(() => {
743
+ this.destroy();
744
+ }, this.config.maxMeasureTime);
723
745
  }
724
- }
725
-
726
- var _a;
727
- /**
728
- * 광고 렌더러 팩토리
729
- * - 광고 타입에 따라 적절한 렌더러 인스턴스를 반환
730
- */
731
- class AdRendererFactory {
732
- /**
733
- * 광고 타입에 맞는 렌더러 생성
734
- */
735
- static createRenderer(adType, trackEvent) {
736
- const RendererClass = this.renderers.get(adType);
737
- if (!RendererClass) {
738
- console.warn(`No renderer found for ad type: ${adType}, falling back to Banner renderer`);
739
- return new BannerAdRenderer(trackEvent);
746
+ onViewabilityAchieved() {
747
+ if (this.isViewableAchieved)
748
+ return;
749
+ this.isViewableAchieved = true;
750
+ const metrics = this.calculateMetrics();
751
+ if (this.onViewableCallback) {
752
+ this.onViewableCallback(metrics);
740
753
  }
741
- return new RendererClass(trackEvent);
742
754
  }
743
- /**
744
- * 광고 렌더링 (편의 메서드)
745
- */
746
- static render(ad, slot, trackEvent) {
747
- const renderer = this.createRenderer(slot.adType, trackEvent);
748
- return renderer.render(ad, slot);
755
+ calculateMetrics() {
756
+ const currentTime = performance.now();
757
+ const exposureTime = this.firstViewableTime
758
+ ? currentTime - this.firstViewableTime
759
+ : 0;
760
+ return {
761
+ isViewable: this.isViewableAchieved,
762
+ exposureTime,
763
+ maxVisibilityRatio: this.maxVisibilityRatio,
764
+ firstViewableTime: this.firstViewableTime,
765
+ measureStartTime: this.startTime,
766
+ };
749
767
  }
750
- /**
751
- * 사용 가능한 렌더러 타입 목록
752
- */
753
- static getSupportedAdTypes() {
754
- return Array.from(this.renderers.keys());
768
+ getMetrics() {
769
+ return this.calculateMetrics();
755
770
  }
756
- /**
757
- * 커스텀 렌더러 등록
758
- */
759
- static registerRenderer(adType, RendererClass) {
760
- this.renderers.set(adType, RendererClass);
771
+ destroy() {
772
+ this.stopViewabilityTimer();
773
+ if (this.maxVisibilityTimer) {
774
+ clearTimeout(this.maxVisibilityTimer);
775
+ this.maxVisibilityTimer = null;
776
+ }
777
+ if (this.observer) {
778
+ this.observer.disconnect();
779
+ this.observer = null;
780
+ }
761
781
  }
762
782
  }
763
- _a = AdRendererFactory;
764
- AdRendererFactory.renderers = new Map();
765
- (() => {
766
- // 렌더러 등록
767
- _a.renderers.set(AdType.BANNER, BannerAdRenderer);
783
+
784
+ /**
785
+ * BasicFraudDetector - 현실적 구현 버전
786
+ * 기본적인 봇 탐지 및 간단한 행동 패턴 분석
787
+ */
788
+ class BasicFraudDetector {
789
+ constructor() {
790
+ this.mouseEvents = 0;
791
+ this.keyboardEvents = 0;
792
+ this.scrollEvents = 0;
793
+ this.startTime = Date.now();
794
+ this.initBasicTracking();
795
+ }
796
+ initBasicTracking() {
797
+ // 기본적인 사용자 상호작용 추적
798
+ document.addEventListener('mousemove', () => this.mouseEvents++, { passive: true });
799
+ document.addEventListener('keydown', () => this.keyboardEvents++, { passive: true });
800
+ document.addEventListener('scroll', () => this.scrollEvents++, { passive: true });
801
+ }
802
+ calculateFraudScore() {
803
+ let score = 0;
804
+ const reasons = [];
805
+ // 1. 웹드라이버 탐지 (기본)
806
+ if (this.detectWebDriver()) {
807
+ score += 50;
808
+ reasons.push('WebDriver detected');
809
+ }
810
+ // 2. 헤드리스 브라우저 기본 탐지
811
+ if (this.detectBasicHeadless()) {
812
+ score += 40;
813
+ reasons.push('Headless browser signatures');
814
+ }
815
+ // 3. 사용자 상호작용 부족
816
+ const sessionTime = Date.now() - this.startTime;
817
+ if (sessionTime > 5000) { // 5초 이상 경과
818
+ if (this.mouseEvents === 0) {
819
+ score += 20;
820
+ reasons.push('No mouse interaction');
821
+ }
822
+ if (this.scrollEvents === 0 && sessionTime > 10000) {
823
+ score += 15;
824
+ reasons.push('No scroll activity');
825
+ }
826
+ }
827
+ // 4. 브라우저 환경 이상 징후
828
+ const browserCheck = this.checkBrowserEnvironment();
829
+ score += browserCheck.score;
830
+ reasons.push(...browserCheck.reasons);
831
+ // 5. 시간 패턴 이상 (너무 빠른 페이지 로드 후 즉시 클릭)
832
+ if (sessionTime < 1000) {
833
+ score += 25;
834
+ reasons.push('Suspiciously fast interaction');
835
+ }
836
+ const finalScore = Math.min(score, 100);
837
+ return {
838
+ score: finalScore,
839
+ riskLevel: this.getRiskLevel(finalScore),
840
+ reasons: reasons
841
+ };
842
+ }
843
+ detectWebDriver() {
844
+ // 기본적인 웹드라이버 탐지
845
+ return !!(window.webdriver ||
846
+ navigator.webdriver ||
847
+ window.__webdriver_evaluate ||
848
+ window.__selenium_evaluate ||
849
+ window.__webdriver_script_function ||
850
+ window.__webdriver_script_func ||
851
+ window.__webdriver_script_fn ||
852
+ window.__fxdriver_evaluate ||
853
+ window.__driver_unwrapped ||
854
+ window.__webdriver_unwrapped ||
855
+ window.__driver_evaluate ||
856
+ window.__selenium_unwrapped ||
857
+ window.__fxdriver_unwrapped);
858
+ }
859
+ detectBasicHeadless() {
860
+ const signatures = [];
861
+ // PhantomJS 탐지
862
+ if (window._phantom || window.phantom) {
863
+ signatures.push('PhantomJS');
864
+ }
865
+ // Chrome headless 기본 탐지
866
+ if (navigator.userAgent.includes('HeadlessChrome')) {
867
+ signatures.push('Chrome Headless');
868
+ }
869
+ // 플러그인 없음 (일반적이지 않음)
870
+ if (navigator.plugins.length === 0) {
871
+ signatures.push('No plugins');
872
+ }
873
+ return signatures.length > 0;
874
+ }
875
+ checkBrowserEnvironment() {
876
+ let score = 0;
877
+ const reasons = [];
878
+ // 언어 설정 이상
879
+ if (!navigator.language || navigator.language === 'C') {
880
+ score += 10;
881
+ reasons.push('Unusual language setting');
882
+ }
883
+ // 쿠키 비활성화
884
+ if (!navigator.cookieEnabled) {
885
+ score += 15;
886
+ reasons.push('Cookies disabled');
887
+ }
888
+ // 화면 해상도 이상
889
+ if (screen.width === 0 || screen.height === 0) {
890
+ score += 20;
891
+ reasons.push('Invalid screen resolution');
892
+ }
893
+ // 시간대 정보 없음
894
+ try {
895
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
896
+ if (!timezone || timezone === 'UTC') {
897
+ score += 5;
898
+ reasons.push('No timezone info');
899
+ }
900
+ }
901
+ catch (e) {
902
+ score += 10;
903
+ reasons.push('Timezone detection failed');
904
+ }
905
+ return { score, reasons };
906
+ }
907
+ getRiskLevel(score) {
908
+ if (score >= 70)
909
+ return 'CRITICAL';
910
+ if (score >= 50)
911
+ return 'HIGH';
912
+ if (score >= 30)
913
+ return 'MEDIUM';
914
+ return 'LOW';
915
+ }
916
+ getBrowserInfo() {
917
+ return {
918
+ userAgent: navigator.userAgent,
919
+ language: navigator.language,
920
+ platform: navigator.platform,
921
+ cookieEnabled: navigator.cookieEnabled,
922
+ doNotTrack: navigator.doNotTrack,
923
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
924
+ screenResolution: `${screen.width}x${screen.height}`,
925
+ viewportSize: `${window.innerWidth}x${window.innerHeight}`
926
+ };
927
+ }
928
+ destroy() {
929
+ // 이벤트 리스너 정리는 생략 (메모리 누수 방지를 위해 필요시 구현)
930
+ }
931
+ }
932
+
933
+ /**
934
+ * AdStage SDK 엔드포인트 상수 관리
935
+ * 모든 API URL을 중앙에서 관리
936
+ */
937
+ /**
938
+ * 환경별 API 엔드포인트 (읽기 전용)
939
+ */
940
+ const API_ENDPOINTS = {
941
+ /** 프로덕션 환경 */
942
+ production: 'https://api.adstage.io',
943
+ /** 베타 환경 (기본값) */
944
+ beta: 'https://beta-api.adstage.app'
945
+ };
946
+ /**
947
+ * API 경로 상수
948
+ */
949
+ const API_PATHS = {
950
+ /** 광고 관련 */
951
+ advertisements: {
952
+ list: '/advertisements/list',
953
+ events: '/advertisements/events'
954
+ },
955
+ /** 이벤트 관련 */
956
+ events: {
957
+ track: '/events/track',
958
+ batch: '/events/batch'
959
+ }
960
+ };
961
+ /**
962
+ * 완전한 API URL 생성 헬퍼
963
+ */
964
+ class EndpointBuilder {
965
+ constructor(baseUrl) {
966
+ /**
967
+ * 광고 엔드포인트
968
+ */
969
+ this.advertisements = {
970
+ list: () => `${this.baseUrl}${API_PATHS.advertisements.list}`,
971
+ events: (adId, eventType) => `${this.baseUrl}${API_PATHS.advertisements.events}/${adId}/${eventType}`
972
+ };
973
+ /**
974
+ * 이벤트 엔드포인트
975
+ */
976
+ this.events = {
977
+ track: () => `${this.baseUrl}${API_PATHS.events.track}`,
978
+ batch: () => `${this.baseUrl}${API_PATHS.events.batch}`
979
+ };
980
+ // 기본값은 베타 환경 사용
981
+ this.baseUrl = baseUrl || API_ENDPOINTS.beta;
982
+ }
983
+ /**
984
+ * 기본 URL 변경
985
+ */
986
+ setBaseUrl(url) {
987
+ this.baseUrl = url;
988
+ console.log('🔄 API endpoint changed:', url);
989
+ }
990
+ /**
991
+ * 기본 URL 반환
992
+ */
993
+ getBaseUrl() {
994
+ return this.baseUrl;
995
+ }
996
+ /**
997
+ * 커스텀 경로 생성
998
+ */
999
+ custom(path) {
1000
+ return `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
1001
+ }
1002
+ }
1003
+ /**
1004
+ * 전역 엔드포인트 빌더 인스턴스 (기본: 베타 환경)
1005
+ */
1006
+ const endpoints = new EndpointBuilder();
1007
+
1008
+ /**
1009
+ * 기본 광고 렌더러 추상 클래스
1010
+ */
1011
+ class BaseAdRenderer {
1012
+ constructor(trackEvent) {
1013
+ this.trackEvent = trackEvent;
1014
+ }
1015
+ /**
1016
+ * 공통 클릭 이벤트 핸들러 (SSR 안전)
1017
+ */
1018
+ addClickHandler(element, ad, slot) {
1019
+ DOMUtils.safeAddEventListener(element, 'click', () => {
1020
+ this.trackEvent?.(ad._id, slot.id, 'CLICK');
1021
+ if (ad.linkUrl) {
1022
+ DOMUtils.safeWindowOpen(ad.linkUrl, '_blank');
1023
+ }
1024
+ });
1025
+ }
1026
+ /**
1027
+ * 공통 스타일 적용 유틸리티 (SSR 안전)
1028
+ */
1029
+ applyStyles(element, styles) {
1030
+ DOMUtils.safeApplyStyles(element, styles);
1031
+ }
1032
+ /**
1033
+ * 크기 값 파싱 유틸리티 (px, %, number 지원)
1034
+ */
1035
+ parseSizeValue(value) {
1036
+ if (!value)
1037
+ return undefined;
1038
+ if (typeof value === 'number') {
1039
+ return value > 0 ? `${value}px` : undefined;
1040
+ }
1041
+ if (typeof value === 'string') {
1042
+ const trimmed = value.trim();
1043
+ if (!trimmed)
1044
+ return undefined;
1045
+ // 퍼센트 값 처리
1046
+ if (trimmed.endsWith('%')) {
1047
+ const percent = parseFloat(trimmed);
1048
+ return !isNaN(percent) && percent > 0 ? trimmed : undefined;
1049
+ }
1050
+ // px 값 처리 (px 단위 포함/미포함 모두 지원)
1051
+ const numValue = trimmed.endsWith('px')
1052
+ ? parseFloat(trimmed.slice(0, -2))
1053
+ : parseFloat(trimmed);
1054
+ return !isNaN(numValue) && numValue > 0 ? `${numValue}px` : undefined;
1055
+ }
1056
+ return undefined;
1057
+ }
1058
+ /**
1059
+ * 기본 컨테이너 스타일 (사용자 지정 크기만 적용)
1060
+ */
1061
+ getBaseContainerStyles(slot) {
1062
+ const styles = {
1063
+ cursor: 'pointer',
1064
+ position: 'relative',
1065
+ overflow: 'hidden',
1066
+ };
1067
+ // 사용자가 지정한 크기가 있을 때만 적용
1068
+ const parsedWidth = this.parseSizeValue(slot.width);
1069
+ const parsedHeight = this.parseSizeValue(slot.height);
1070
+ if (parsedWidth) {
1071
+ styles.width = parsedWidth;
1072
+ }
1073
+ if (parsedHeight) {
1074
+ styles.height = parsedHeight;
1075
+ }
1076
+ return styles;
1077
+ }
1078
+ /**
1079
+ * 이미지 스타일 (고유 사이즈 유지, 사용자 지정 크기 우선)
1080
+ */
1081
+ getImageStyles(slot) {
1082
+ const styles = {
1083
+ display: 'block',
1084
+ 'max-width': '100%',
1085
+ height: 'auto',
1086
+ };
1087
+ // 사용자가 컨테이너 크기를 지정한 경우에만 크기 제한
1088
+ const parsedWidth = this.parseSizeValue(slot?.width);
1089
+ const parsedHeight = this.parseSizeValue(slot?.height);
1090
+ if (parsedWidth && parsedHeight) {
1091
+ styles.width = '100%';
1092
+ styles.height = '100%';
1093
+ styles['object-fit'] = 'cover';
1094
+ }
1095
+ return styles;
1096
+ }
1097
+ /**
1098
+ * 기본 폰트 스타일
1099
+ */
1100
+ getBaseFontStyles() {
1101
+ return {
1102
+ 'font-family': 'Arial, sans-serif',
1103
+ 'line-height': '1.4',
1104
+ 'word-break': 'keep-all',
1105
+ };
1106
+ }
1107
+ /**
1108
+ * 이미지 요소 생성 (SSR 안전)
1109
+ */
1110
+ createImageElement(imageUrl, alt = '', slot) {
1111
+ const img = DOMUtils.safeCreateElement('img');
1112
+ if (!img)
1113
+ return null;
1114
+ img.src = imageUrl;
1115
+ img.alt = alt;
1116
+ this.applyStyles(img, this.getImageStyles(slot));
1117
+ return img;
1118
+ }
1119
+ /**
1120
+ * 텍스트 요소 생성 (SSR 안전)
1121
+ */
1122
+ createTextElement(text, tag = 'div', additionalStyles = {}) {
1123
+ const element = DOMUtils.safeCreateElement(tag);
1124
+ if (!element)
1125
+ return null;
1126
+ DOMUtils.safeSetTextContent(element, text);
1127
+ this.applyStyles(element, {
1128
+ ...this.getBaseFontStyles(),
1129
+ ...additionalStyles,
1130
+ });
1131
+ return element;
1132
+ }
1133
+ /**
1134
+ * 플레이스홀더 요소 생성
1135
+ */
1136
+ createPlaceholder(slot, text = '광고') {
1137
+ let placeholder = DOMUtils.safeCreateElement('div');
1138
+ // SSR 환경에서 DOM을 사용할 수 없는 경우, 런타임에 생성되도록 함
1139
+ if (!placeholder) {
1140
+ // SSR에서는 빈 div를 반환하되, 브라우저에서는 제대로 작동하도록 함
1141
+ if (typeof document !== 'undefined') {
1142
+ placeholder = document.createElement('div');
1143
+ }
1144
+ else {
1145
+ // SSR 환경에서는 더미 객체 반환 (타입 단언 사용)
1146
+ placeholder = {};
1147
+ }
1148
+ }
1149
+ // DOM이 사용 가능한 경우에만 스타일 적용
1150
+ if (DOMUtils.canUseDOM() && placeholder) {
1151
+ this.applyStyles(placeholder, {
1152
+ ...this.getBaseContainerStyles(slot),
1153
+ background: '#f8f9fa',
1154
+ display: 'flex',
1155
+ 'align-items': 'center',
1156
+ 'justify-content': 'center',
1157
+ color: '#6c757d',
1158
+ ...this.getBaseFontStyles(),
1159
+ // 플레이스홀더는 최소 크기 보장
1160
+ 'min-width': '100px',
1161
+ 'min-height': '100px',
1162
+ });
1163
+ DOMUtils.safeSetTextContent(placeholder, text);
1164
+ }
1165
+ return placeholder;
1166
+ }
1167
+ }
1168
+
1169
+ /**
1170
+ * 배너 광고 렌더러 - 이미지만 표시
1171
+ */
1172
+ class BannerAdRenderer extends BaseAdRenderer {
1173
+ render(ad, slot) {
1174
+ const adElement = DOMUtils.safeCreateElement('div');
1175
+ if (!adElement) {
1176
+ // SSR 환경에서는 기본 div 반환
1177
+ return document.createElement('div');
1178
+ }
1179
+ // 기본 컨테이너 스타일 적용 (불필요한 스타일 제거)
1180
+ this.applyStyles(adElement, this.getBaseContainerStyles(slot));
1181
+ // 배너 광고는 이미지만 표시
1182
+ if (!ad.imageUrl) {
1183
+ // 이미지가 없는 경우 플레이스홀더 반환
1184
+ const placeholder = this.createPlaceholder(slot, '배너 광고');
1185
+ return placeholder || adElement;
1186
+ }
1187
+ const img = this.createImageElement(ad.imageUrl, '', slot);
1188
+ if (img) {
1189
+ DOMUtils.safeAppendChild(adElement, img);
1190
+ // 클릭 이벤트 추가
1191
+ this.addClickHandler(adElement, ad, slot);
1192
+ }
1193
+ return adElement;
1194
+ }
1195
+ }
1196
+
1197
+ /**
1198
+ * 텍스트 광고 렌더러 - textContent만 표시
1199
+ */
1200
+ class TextAdRenderer extends BaseAdRenderer {
1201
+ render(ad, slot) {
1202
+ let adElement = DOMUtils.safeCreateElement('div');
1203
+ if (!adElement) {
1204
+ return this.createPlaceholder(slot, '텍스트 광고');
1205
+ }
1206
+ // 기본 컨테이너 스타일
1207
+ const containerStyles = {
1208
+ ...this.getBaseContainerStyles(slot),
1209
+ padding: '20px',
1210
+ background: 'transparent',
1211
+ display: 'flex',
1212
+ 'align-items': 'center',
1213
+ 'justify-content': 'center',
1214
+ // text-align은 사용자가 설정할 수 있도록 기본값에서 제외
1215
+ ...this.getBaseFontStyles(),
1216
+ };
1217
+ // 사용자가 크기를 지정하지 않은 경우 컨텐츠에 맞춤
1218
+ if (!slot.width || slot.width === 0) {
1219
+ containerStyles.display = 'inline-flex';
1220
+ containerStyles['white-space'] = 'nowrap';
1221
+ containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
1222
+ }
1223
+ // height만 자동인 경우 줄바꿈 허용
1224
+ if ((slot.width && slot.width !== 0) && (!slot.height || slot.height === 0)) {
1225
+ containerStyles['white-space'] = 'normal';
1226
+ containerStyles['min-height'] = 'auto';
1227
+ containerStyles['justify-content'] = 'flex-start'; // 좌측 정렬로 변경
1228
+ }
1229
+ this.applyStyles(adElement, containerStyles);
1230
+ // 텍스트 광고는 textContent만 표시
1231
+ if (!ad.textContent) {
1232
+ // 텍스트가 없는 경우 플레이스홀더 반환
1233
+ return this.createPlaceholder(slot, '텍스트 광고');
1234
+ }
1235
+ // 텍스트 콘텐츠 생성
1236
+ const textContent = this.createTextElement(ad.textContent, 'div', {
1237
+ 'font-size': '16px',
1238
+ 'font-weight': '500',
1239
+ color: '#212529',
1240
+ width: '100%', // 전체 너비 사용하여 텍스트 정렬이 적용되도록 함
1241
+ });
1242
+ if (textContent) {
1243
+ adElement.appendChild(textContent);
1244
+ }
1245
+ // 사용자가 text-align을 지정했는지 확인하고 레이아웃 조정
1246
+ setTimeout(() => {
1247
+ if (!adElement || typeof window === 'undefined')
1248
+ return;
1249
+ const computedStyle = window.getComputedStyle(adElement);
1250
+ const textAlign = computedStyle.textAlign;
1251
+ // 사용자가 text-align을 설정했고, width가 없는 경우
1252
+ if (textAlign && textAlign !== 'start' && textAlign !== 'left' && (!slot.width || slot.width === 0)) {
1253
+ // 블록 레벨로 변경하여 text-align이 제대로 작동하도록 함
1254
+ adElement.style.display = 'block';
1255
+ adElement.style.whiteSpace = 'normal';
1256
+ // 최소 너비 설정 (텍스트가 한 줄일 때를 위해)
1257
+ if (textContent) {
1258
+ const textRect = textContent.getBoundingClientRect();
1259
+ if (textRect.width > 0) {
1260
+ adElement.style.minWidth = `${textRect.width}px`;
1261
+ }
1262
+ }
1263
+ }
1264
+ }, 0);
1265
+ // 클릭 이벤트 추가
1266
+ this.addClickHandler(adElement, ad, slot);
1267
+ return adElement;
1268
+ }
1269
+ }
1270
+
1271
+ /**
1272
+ * 네이티브 광고 렌더러 - 이미지 + textContent 표시
1273
+ */
1274
+ class NativeAdRenderer extends BaseAdRenderer {
1275
+ render(ad, slot) {
1276
+ const adElement = DOMUtils.safeCreateElement('div');
1277
+ if (!adElement) {
1278
+ return document.createElement('div');
1279
+ }
1280
+ // 컨테이너 스타일 적용 (불필요한 스타일 제거)
1281
+ this.applyStyles(adElement, this.getBaseContainerStyles(slot));
1282
+ // 네이티브 광고는 이미지만 표시
1283
+ if (!ad.imageUrl) {
1284
+ // 이미지가 없는 경우 플레이스홀더 반환
1285
+ const placeholder = this.createPlaceholder(slot, '네이티브 광고');
1286
+ return placeholder || adElement;
1287
+ }
1288
+ // 이미지 생성 (고유 사이즈 또는 사용자 지정 크기)
1289
+ const img = this.createImageElement(ad.imageUrl, '', slot);
1290
+ if (img) {
1291
+ DOMUtils.safeAppendChild(adElement, img);
1292
+ // 클릭 이벤트 추가
1293
+ this.addClickHandler(adElement, ad, slot);
1294
+ }
1295
+ return adElement;
1296
+ }
1297
+ }
1298
+
1299
+ /**
1300
+ * 비디오 광고 렌더러 - 비디오 또는 이미지 표시
1301
+ */
1302
+ class VideoAdRenderer extends BaseAdRenderer {
1303
+ render(ad, slot) {
1304
+ let adElement = DOMUtils.safeCreateElement('div');
1305
+ if (!adElement) {
1306
+ return this.createPlaceholder(slot, '비디오 광고');
1307
+ }
1308
+ // 컨테이너 스타일 적용 (불필요한 스타일 제거)
1309
+ this.applyStyles(adElement, {
1310
+ ...this.getBaseContainerStyles(slot),
1311
+ background: '#000',
1312
+ });
1313
+ // 비디오 광고는 비디오만 표시
1314
+ if (!ad.videoUrl) {
1315
+ // 비디오가 없는 경우 플레이스홀더 반환
1316
+ return this.createPlaceholder(slot, '비디오 광고');
1317
+ }
1318
+ const video = this.createVideoElement(ad.videoUrl, ad, slot);
1319
+ if (video) {
1320
+ adElement.appendChild(video);
1321
+ }
1322
+ // 클릭 이벤트 추가
1323
+ this.addClickHandler(adElement, ad, slot);
1324
+ return adElement;
1325
+ }
1326
+ /**
1327
+ * 비디오 요소 생성
1328
+ */
1329
+ createVideoElement(videoUrl, ad, slot) {
1330
+ const video = DOMUtils.safeCreateElement('video');
1331
+ if (!video)
1332
+ return null;
1333
+ video.src = videoUrl;
1334
+ video.controls = true;
1335
+ // 비디오도 이미지와 같은 스타일 적용
1336
+ this.applyStyles(video, this.getImageStyles(slot));
1337
+ // 비디오 이벤트 추적
1338
+ video.addEventListener('play', () => {
1339
+ this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
1340
+ });
1341
+ video.addEventListener('ended', () => {
1342
+ this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
1343
+ });
1344
+ return video;
1345
+ }
1346
+ }
1347
+
1348
+ /**
1349
+ * 전면/팝업 광고 렌더러 - 핵심 콘텐츠만 표시
1350
+ */
1351
+ class InterstitialAdRenderer extends BaseAdRenderer {
1352
+ render(ad, slot) {
1353
+ let adElement = DOMUtils.safeCreateElement('div');
1354
+ if (!adElement) {
1355
+ return this.createPlaceholder(slot, '전면 광고');
1356
+ }
1357
+ // 컨테이너 스타일 적용 (불필요한 스타일 제거)
1358
+ this.applyStyles(adElement, {
1359
+ ...this.getBaseContainerStyles(slot),
1360
+ display: 'flex',
1361
+ 'flex-direction': 'column',
1362
+ });
1363
+ // 우선순위: 1. 이미지, 2. 비디오, 3. 텍스트
1364
+ if (ad.imageUrl) {
1365
+ const img = this.createImageElement(ad.imageUrl, '', slot);
1366
+ if (img) {
1367
+ adElement.appendChild(img);
1368
+ }
1369
+ }
1370
+ else if (ad.videoUrl) {
1371
+ // 이미지가 없고 비디오가 있는 경우
1372
+ const video = this.createVideoElement(ad.videoUrl, ad, slot);
1373
+ if (video) {
1374
+ adElement.appendChild(video);
1375
+ }
1376
+ }
1377
+ else {
1378
+ // 모든 콘텐츠가 없는 경우
1379
+ return this.createPlaceholder(slot, '전면 광고');
1380
+ }
1381
+ // 클릭 이벤트 추가
1382
+ this.addClickHandler(adElement, ad, slot);
1383
+ return adElement;
1384
+ }
1385
+ /**
1386
+ * 비디오 요소 생성
1387
+ */
1388
+ createVideoElement(videoUrl, ad, slot) {
1389
+ const video = DOMUtils.safeCreateElement('video');
1390
+ if (!video)
1391
+ return null;
1392
+ video.src = videoUrl;
1393
+ video.controls = true;
1394
+ // 비디오도 이미지와 같은 스타일 적용
1395
+ this.applyStyles(video, this.getImageStyles(slot));
1396
+ // 비디오 이벤트 추적
1397
+ video.addEventListener('play', () => {
1398
+ this.trackEvent?.(ad._id, slot.id, 'VIDEO_START');
1399
+ });
1400
+ video.addEventListener('ended', () => {
1401
+ this.trackEvent?.(ad._id, slot.id, 'VIDEO_COMPLETE');
1402
+ });
1403
+ return video;
1404
+ }
1405
+ }
1406
+
1407
+ var _a;
1408
+ /**
1409
+ * 광고 렌더러 팩토리
1410
+ * - 광고 타입에 따라 적절한 렌더러 인스턴스를 반환
1411
+ */
1412
+ class AdRendererFactory {
1413
+ /**
1414
+ * 광고 타입에 맞는 렌더러 생성
1415
+ */
1416
+ static createRenderer(adType, trackEvent) {
1417
+ const RendererClass = this.renderers.get(adType);
1418
+ if (!RendererClass) {
1419
+ console.warn(`No renderer found for ad type: ${adType}, falling back to Banner renderer`);
1420
+ return new BannerAdRenderer(trackEvent);
1421
+ }
1422
+ return new RendererClass(trackEvent);
1423
+ }
1424
+ /**
1425
+ * 광고 렌더링 (편의 메서드)
1426
+ */
1427
+ static render(ad, slot, trackEvent) {
1428
+ const renderer = this.createRenderer(slot.adType, trackEvent);
1429
+ return renderer.render(ad, slot);
1430
+ }
1431
+ /**
1432
+ * 사용 가능한 렌더러 타입 목록
1433
+ */
1434
+ static getSupportedAdTypes() {
1435
+ return Array.from(this.renderers.keys());
1436
+ }
1437
+ /**
1438
+ * 커스텀 렌더러 등록
1439
+ */
1440
+ static registerRenderer(adType, RendererClass) {
1441
+ this.renderers.set(adType, RendererClass);
1442
+ }
1443
+ }
1444
+ _a = AdRendererFactory;
1445
+ AdRendererFactory.renderers = new Map();
1446
+ (() => {
1447
+ // 렌더러 등록
1448
+ _a.renderers.set(AdType.BANNER, BannerAdRenderer);
768
1449
  _a.renderers.set(AdType.TEXT, TextAdRenderer);
769
1450
  _a.renderers.set(AdType.NATIVE, NativeAdRenderer);
770
1451
  _a.renderers.set(AdType.VIDEO, VideoAdRenderer);
@@ -803,12 +1484,11 @@ class CarouselSliderManager {
803
1484
  width = `${slot.width}px`;
804
1485
  }
805
1486
  containerStyles.width = width;
806
- containerStyles.display = 'block'; // 하단 공백 제거를 위해 block 사용
1487
+ containerStyles.display = 'inline-block'; // 지정된 크기에 맞춤 (좌측 정렬)
807
1488
  }
808
1489
  else {
809
- // 컨텐츠 크기에 맞춤 - fit-content로 컨텐츠에 맞는 크기 설정
810
- containerStyles.display = 'block';
811
- containerStyles.width = 'fit-content'; // 컨텐츠 크기에 맞춤
1490
+ // 컨텐츠 크기에 맞춤
1491
+ containerStyles.display = 'inline-block';
812
1492
  }
813
1493
  if (slot.height && slot.height !== 0) {
814
1494
  const height = typeof slot.height === 'string' ? slot.height : `${slot.height}px`;
@@ -917,7 +1597,7 @@ class CarouselSliderManager {
917
1597
  let currentSlide = 0;
918
1598
  const totalSlides = advertisements.length;
919
1599
  const autoSlideInterval = (options?.autoSlideInterval || 3) * 1000; // 기본 3초
920
- // 슬라이드 이동 함수 (무한 루프 지원 + 동적 높이 조정)
1600
+ // 슬라이드 이동 함수 (무한 루프 지원)
921
1601
  const moveToSlide = (index, instant = false) => {
922
1602
  currentSlide = index;
923
1603
  // 애니메이션 임시 비활성화 (무한 루프용)
@@ -929,33 +1609,6 @@ class CarouselSliderManager {
929
1609
  }
930
1610
  // 항상 퍼센트 기반으로 이동
931
1611
  slideContainer.style.transform = `translateX(-${(100 / extendedAds.length) * currentSlide}%)`;
932
- // 🆕 동적 높이 조정: 현재 슬라이드의 이미지 높이에 맞춰 컨테이너 높이 조정
933
- if (!instant && !slot.height && !slot.width) { // 사용자가 크기를 지정하지 않은 경우에만
934
- const currentSlideElement = slideContainer.children[currentSlide];
935
- if (currentSlideElement) {
936
- const currentAdElement = currentSlideElement.children[0];
937
- if (currentAdElement) {
938
- // 이미지 요소 찾기
939
- const imgElement = currentAdElement.querySelector('img');
940
- if (imgElement) {
941
- // 이미지 로드 완료 후 높이 조정
942
- const adjustHeight = () => {
943
- const imgHeight = imgElement.getBoundingClientRect().height;
944
- if (imgHeight > 0) {
945
- sliderWrapper.style.height = `${imgHeight}px`;
946
- sliderWrapper.style.transition = instant ? 'none' : 'height 0.4s ease-out';
947
- }
948
- };
949
- if (imgElement.complete && imgElement.naturalHeight > 0) {
950
- adjustHeight();
951
- }
952
- else {
953
- imgElement.addEventListener('load', adjustHeight, { once: true });
954
- }
955
- }
956
- }
957
- }
958
- }
959
1612
  // 도트 업데이트 (무채색 스타일) - 실제 광고 인덱스 기준, 텍스트 광고가 아닐 때만
960
1613
  const actualIndex = currentSlide === totalSlides ? 0 : currentSlide;
961
1614
  if (dotContainer) {
@@ -1087,252 +1740,24 @@ class CarouselSliderManager {
1087
1740
  dot.style.opacity = '0.9';
1088
1741
  }
1089
1742
  });
1090
- dot.addEventListener('mouseleave', () => {
1091
- if (!dot.classList.contains('active')) {
1092
- dot.style.borderColor = '#cccccc';
1093
- dot.style.opacity = '0.7';
1094
- }
1095
- });
1096
- dotContainer.appendChild(dot);
1097
- }
1098
- return dotContainer;
1099
- }
1100
- /**
1101
- * 터치 제스처 지원 추가
1102
- */
1103
- static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides, handleInfiniteLoop) {
1104
- let startX = 0;
1105
- let isDragging = false;
1106
- container.addEventListener('touchstart', (e) => {
1107
- startX = e.touches[0].clientX;
1108
- isDragging = true;
1109
- });
1110
- container.addEventListener('touchmove', (e) => {
1111
- if (!isDragging)
1112
- return;
1113
- e.preventDefault();
1114
- });
1115
- container.addEventListener('touchend', (e) => {
1116
- if (!isDragging)
1117
- return;
1118
- isDragging = false;
1119
- const endX = e.changedTouches[0].clientX;
1120
- const diff = startX - endX;
1121
- if (Math.abs(diff) > 50) { // 50px 이상 스와이프 시
1122
- const currentSlide = getCurrentSlide();
1123
- if (diff > 0) {
1124
- // 왼쪽으로 스와이프 (다음 슬라이드)
1125
- const nextIndex = currentSlide + 1;
1126
- moveToSlide(nextIndex);
1127
- if (handleInfiniteLoop) {
1128
- handleInfiniteLoop();
1129
- }
1130
- }
1131
- else {
1132
- // 오른쪽으로 스와이프 (이전 슬라이드)
1133
- const prevIndex = currentSlide > 0 ? currentSlide - 1 : totalSlides - 1;
1134
- moveToSlide(prevIndex);
1135
- }
1136
- }
1137
- });
1138
- }
1139
- }
1140
-
1141
- /**
1142
- * 텍스트 전환 효과 관리 클래스
1143
- * - 텍스트 광고 전용 페이드 인/아웃 + 상하 움직임 효과
1144
- * - 부드러운 전환 애니메이션 (vertical transition)
1145
- * - 무한 루프 지원
1146
- */
1147
- class TextTransitionManager {
1148
- /**
1149
- * 텍스트 전환 슬라이더 컨테이너 생성
1150
- */
1151
- static createTextTransitionContainer(slot, advertisements, options, trackEventCallback) {
1152
- const sliderWrapper = document.createElement('div');
1153
- sliderWrapper.className = 'adstage-fade-slider-wrapper';
1154
- // 래퍼 스타일 설정
1155
- const containerStyles = {
1156
- position: 'relative',
1157
- overflow: 'hidden',
1158
- display: 'block', // ✅ 하단 공백 제거를 위해 block 사용
1159
- width: 'fit-content', // 컨텐츠 크기에 맞춤
1160
- };
1161
- // 사용자가 크기를 지정한 경우
1162
- if (slot.width && slot.width !== 0) {
1163
- let width;
1164
- if (typeof slot.width === 'string') {
1165
- width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
1166
- }
1167
- else {
1168
- width = `${slot.width}px`;
1169
- }
1170
- containerStyles.width = width;
1171
- }
1172
- if (slot.height && slot.height !== 0) {
1173
- let height;
1174
- if (typeof slot.height === 'string') {
1175
- height = slot.height.includes('px') || slot.height.includes('%') ? slot.height : `${slot.height}px`;
1176
- }
1177
- else {
1178
- height = `${slot.height}px`;
1179
- }
1180
- containerStyles.height = height;
1181
- }
1182
- // 스타일 적용
1183
- Object.entries(containerStyles).forEach(([key, value]) => {
1184
- sliderWrapper.style.setProperty(key, value);
1185
- });
1186
- // 슬라이드 컨테이너
1187
- const slideContainer = document.createElement('div');
1188
- slideContainer.className = 'adstage-fade-slide-container';
1189
- slideContainer.style.cssText = `
1190
- position: relative;
1191
- width: 100%;
1192
- height: 100%;
1193
- `;
1194
- // 크기 측정을 위한 임시 컨테이너 (자동 크기 계산이 필요한 경우)
1195
- let measureContainer = null;
1196
- const needsWidthMeasurement = !slot.width || slot.width === 0;
1197
- const needsHeightMeasurement = !slot.height || slot.height === 0;
1198
- if (needsWidthMeasurement || needsHeightMeasurement) {
1199
- measureContainer = document.createElement('div');
1200
- measureContainer.style.cssText = `
1201
- position: absolute;
1202
- visibility: hidden;
1203
- white-space: nowrap;
1204
- top: -9999px;
1205
- left: -9999px;
1206
- `;
1207
- // width가 설정되어 있으면 측정 컨테이너에도 적용
1208
- if (!needsWidthMeasurement && slot.width) {
1209
- let width;
1210
- if (typeof slot.width === 'string') {
1211
- width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
1212
- }
1213
- else {
1214
- width = `${slot.width}px`;
1215
- }
1216
- measureContainer.style.width = width;
1217
- measureContainer.style.whiteSpace = 'normal'; // width가 있으면 줄바꿈 허용
1218
- }
1219
- document.body.appendChild(measureContainer);
1220
- let maxWidth = 0;
1221
- let maxHeight = 0;
1222
- // 모든 광고의 크기를 측정하여 최대 크기 찾기
1223
- advertisements.forEach(ad => {
1224
- const measureAdElement = AdRendererFactory.render(ad, slot, trackEventCallback);
1225
- measureContainer.appendChild(measureAdElement);
1226
- const rect = measureAdElement.getBoundingClientRect();
1227
- if (rect.width > maxWidth)
1228
- maxWidth = rect.width;
1229
- if (rect.height > maxHeight)
1230
- maxHeight = rect.height;
1231
- // 측정 후 요소 제거
1232
- measureContainer.removeChild(measureAdElement);
1233
- });
1234
- // 측정된 최대 크기로 래퍼 크기 설정
1235
- if (needsWidthMeasurement && maxWidth > 0) {
1236
- sliderWrapper.style.width = `${maxWidth}px`;
1237
- }
1238
- if (needsHeightMeasurement && maxHeight > 0) {
1239
- sliderWrapper.style.height = `${maxHeight}px`;
1240
- }
1241
- // 측정 컨테이너 제거
1242
- document.body.removeChild(measureContainer);
1243
- }
1244
- // 각 광고를 슬라이드로 생성
1245
- const slideElements = [];
1246
- advertisements.forEach((ad, index) => {
1247
- const slideElement = document.createElement('div');
1248
- slideElement.className = 'adstage-fade-slide';
1249
- slideElement.style.cssText = `
1250
- position: absolute;
1251
- top: 0;
1252
- left: 0;
1253
- width: 100%;
1254
- height: 100%;
1255
- display: flex;
1256
- align-items: center;
1257
- justify-content: center;
1258
- opacity: ${index === 0 ? '1' : '0'};
1259
- transform: translateY(${index === 0 ? '0' : '20px'});
1260
- transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
1261
- z-index: ${index === 0 ? '2' : '1'};
1262
- `;
1263
- // 광고 렌더링
1264
- const adElement = AdRendererFactory.render(ad, slot, trackEventCallback);
1265
- slideElement.appendChild(adElement);
1266
- slideContainer.appendChild(slideElement);
1267
- slideElements.push(slideElement);
1268
- });
1269
- // 슬라이더 상태 관리
1270
- let currentSlide = 0;
1271
- const totalSlides = advertisements.length;
1272
- const autoSlideInterval = (options?.autoSlideInterval || 4) * 1000; // 기본 4초 (페이드는 조금 더 길게)
1273
- // 슬라이드 이동 함수 (페이드 효과)
1274
- const moveToSlide = (index) => {
1275
- if (index >= totalSlides) {
1276
- index = 0; // 무한 루프
1277
- }
1278
- else if (index < 0) {
1279
- index = totalSlides - 1;
1280
- }
1281
- const previousSlide = slideElements[currentSlide];
1282
- const nextSlide = slideElements[index];
1283
- // 이전 슬라이드 페이드 아웃 (아래로)
1284
- previousSlide.style.opacity = '0';
1285
- previousSlide.style.transform = 'translateY(-20px)';
1286
- previousSlide.style.zIndex = '1';
1287
- // 다음 슬라이드 페이드 인 (위에서)
1288
- nextSlide.style.opacity = '1';
1289
- nextSlide.style.transform = 'translateY(0)';
1290
- nextSlide.style.zIndex = '2';
1291
- // 다른 슬라이드들은 숨김
1292
- slideElements.forEach((slide, i) => {
1293
- if (i !== index && i !== currentSlide) {
1294
- slide.style.opacity = '0';
1295
- slide.style.transform = 'translateY(20px)';
1296
- slide.style.zIndex = '1';
1297
- }
1298
- });
1299
- currentSlide = index;
1300
- // 현재 슬라이드의 광고에 대해 노출 이벤트 추적
1301
- if (currentSlide > 0) { // 첫 번째는 이미 loadSlot에서 추적됨
1302
- trackEventCallback(advertisements[currentSlide]._id, slot.id, AdEventType.VIEWABLE);
1303
- }
1304
- };
1305
- // 자동 슬라이드
1306
- let autoSlideTimer = setInterval(() => {
1307
- const nextIndex = currentSlide + 1;
1308
- moveToSlide(nextIndex);
1309
- }, autoSlideInterval);
1310
- // 마우스 호버 시 자동 슬라이드 일시정지
1311
- sliderWrapper.addEventListener('mouseenter', () => {
1312
- clearInterval(autoSlideTimer);
1313
- });
1314
- sliderWrapper.addEventListener('mouseleave', () => {
1315
- autoSlideTimer = setInterval(() => {
1316
- const nextIndex = currentSlide + 1;
1317
- moveToSlide(nextIndex);
1318
- }, autoSlideInterval);
1319
- });
1320
- // 터치 제스처 지원
1321
- TextTransitionManager.addTouchSupport(sliderWrapper, moveToSlide, () => currentSlide, totalSlides);
1322
- // 요소들 조립
1323
- sliderWrapper.appendChild(slideContainer);
1324
- return sliderWrapper;
1743
+ dot.addEventListener('mouseleave', () => {
1744
+ if (!dot.classList.contains('active')) {
1745
+ dot.style.borderColor = '#cccccc';
1746
+ dot.style.opacity = '0.7';
1747
+ }
1748
+ });
1749
+ dotContainer.appendChild(dot);
1750
+ }
1751
+ return dotContainer;
1325
1752
  }
1326
1753
  /**
1327
1754
  * 터치 제스처 지원 추가
1328
1755
  */
1329
- static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides) {
1756
+ static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides, handleInfiniteLoop) {
1330
1757
  let startX = 0;
1331
- let startY = 0;
1332
1758
  let isDragging = false;
1333
1759
  container.addEventListener('touchstart', (e) => {
1334
1760
  startX = e.touches[0].clientX;
1335
- startY = e.touches[0].clientY;
1336
1761
  isDragging = true;
1337
1762
  });
1338
1763
  container.addEventListener('touchmove', (e) => {
@@ -1345,19 +1770,21 @@ class TextTransitionManager {
1345
1770
  return;
1346
1771
  isDragging = false;
1347
1772
  const endX = e.changedTouches[0].clientX;
1348
- const endY = e.changedTouches[0].clientY;
1349
- const diffX = startX - endX;
1350
- const diffY = startY - endY;
1351
- // 가로 스와이프가 세로 스와이프보다 클 때만 처리
1352
- if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
1773
+ const diff = startX - endX;
1774
+ if (Math.abs(diff) > 50) { // 50px 이상 스와이프 시
1353
1775
  const currentSlide = getCurrentSlide();
1354
- if (diffX > 0) {
1776
+ if (diff > 0) {
1355
1777
  // 왼쪽으로 스와이프 (다음 슬라이드)
1356
- moveToSlide(currentSlide + 1);
1778
+ const nextIndex = currentSlide + 1;
1779
+ moveToSlide(nextIndex);
1780
+ if (handleInfiniteLoop) {
1781
+ handleInfiniteLoop();
1782
+ }
1357
1783
  }
1358
1784
  else {
1359
1785
  // 오른쪽으로 스와이프 (이전 슬라이드)
1360
- moveToSlide(currentSlide - 1);
1786
+ const prevIndex = currentSlide > 0 ? currentSlide - 1 : totalSlides - 1;
1787
+ moveToSlide(prevIndex);
1361
1788
  }
1362
1789
  }
1363
1790
  });
@@ -1365,698 +1792,844 @@ class TextTransitionManager {
1365
1792
  }
1366
1793
 
1367
1794
  /**
1368
- * VIEWABLE 이벤트 추적 및 중복 방지 관리 클래스
1369
- * - 메모리 기반 중복 확인
1370
- * - 세션 스토리지 기반 영구 추적
1371
- * - 자동 정리 기능
1372
- * - ViewabilityTracker와 함께 사용하여 중복 viewable 이벤트 방지
1795
+ * 텍스트 전환 효과 관리 클래스
1796
+ * - 텍스트 광고 전용 페이드 인/아웃 + 상하 움직임 효과
1797
+ * - 부드러운 전환 애니메이션 (vertical transition)
1798
+ * - 무한 루프 지원
1373
1799
  */
1374
- class ViewableEventTracker {
1800
+ class TextTransitionManager {
1375
1801
  /**
1376
- * 중복 viewable 이벤트 여부 확인
1802
+ * 텍스트 전환 슬라이더 컨테이너 생성
1377
1803
  */
1378
- static isDuplicateViewable(adId, slotId, debug = false) {
1379
- const key = `${adId}_${slotId}`;
1380
- const now = Date.now();
1381
- // 메모리 기반 중복 확인 (새로고침 시 초기화됨)
1382
- const lastViewable = ViewableEventTracker.viewableTracker.get(key);
1383
- if (lastViewable && (now - lastViewable) < ViewableEventTracker.VIEWABLE_COOLDOWN) {
1384
- if (debug) {
1385
- console.log(`Duplicate viewable blocked for ad ${adId} in slot ${slotId}. Cooldown: ${Math.round((ViewableEventTracker.VIEWABLE_COOLDOWN - (now - lastViewable)) / 1000)}s remaining`);
1804
+ static createTextTransitionContainer(slot, advertisements, options, trackEventCallback) {
1805
+ const sliderWrapper = document.createElement('div');
1806
+ sliderWrapper.className = 'adstage-fade-slider-wrapper';
1807
+ // 래퍼 스타일 설정
1808
+ const containerStyles = {
1809
+ position: 'relative',
1810
+ overflow: 'hidden',
1811
+ display: 'inline-block',
1812
+ };
1813
+ // 사용자가 크기를 지정한 경우
1814
+ if (slot.width && slot.width !== 0) {
1815
+ let width;
1816
+ if (typeof slot.width === 'string') {
1817
+ width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
1386
1818
  }
1387
- return true;
1388
- }
1389
- // 세션 스토리지 기반 중복 확인 (새로고침 시에도 유지)
1390
- const sessionKey = `adstage_viewable_${key}`;
1391
- const sessionViewable = sessionStorage.getItem(sessionKey);
1392
- if (sessionViewable) {
1393
- const sessionTime = parseInt(sessionViewable, 10);
1394
- if (!isNaN(sessionTime) && (now - sessionTime) < ViewableEventTracker.VIEWABLE_COOLDOWN) {
1395
- if (debug) {
1396
- console.log(`Session-based duplicate viewable blocked for ad ${adId} in slot ${slotId}. Cooldown: ${Math.round((ViewableEventTracker.VIEWABLE_COOLDOWN - (now - sessionTime)) / 1000)}s remaining`);
1397
- }
1398
- // 메모리에도 기록하여 이후 요청 최적화
1399
- ViewableEventTracker.viewableTracker.set(key, sessionTime);
1400
- return true;
1819
+ else {
1820
+ width = `${slot.width}px`;
1401
1821
  }
1822
+ containerStyles.width = width;
1402
1823
  }
1403
- // viewable 이벤트 시점 기록 (메모리 + 세션 스토리지)
1404
- ViewableEventTracker.viewableTracker.set(key, now);
1405
- sessionStorage.setItem(sessionKey, now.toString());
1406
- if (debug) {
1407
- console.log(`🎯 New viewable event allowed for ad ${adId} in slot ${slotId}`);
1408
- }
1409
- // 오래된 세션 스토리지 데이터 정리 (선택적)
1410
- ViewableEventTracker.cleanupOldViewables();
1411
- return false;
1412
- }
1413
- /**
1414
- * 오래된 viewable 추적 데이터 정리
1415
- */
1416
- static cleanupOldViewables() {
1417
- const now = Date.now();
1418
- const cleanupThreshold = ViewableEventTracker.VIEWABLE_COOLDOWN * 2; // 쿨다운의 2배 시간이 지난 데이터 정리
1419
- // 세션 스토리지 정리
1420
- for (let i = 0; i < sessionStorage.length; i++) {
1421
- const key = sessionStorage.key(i);
1422
- if (key && key.startsWith('adstage_viewable_')) {
1423
- const timestamp = sessionStorage.getItem(key);
1424
- if (timestamp) {
1425
- const time = parseInt(timestamp, 10);
1426
- if (!isNaN(time) && (now - time) > cleanupThreshold) {
1427
- sessionStorage.removeItem(key);
1428
- i--; // 인덱스 조정
1429
- }
1430
- }
1824
+ if (slot.height && slot.height !== 0) {
1825
+ let height;
1826
+ if (typeof slot.height === 'string') {
1827
+ height = slot.height.includes('px') || slot.height.includes('%') ? slot.height : `${slot.height}px`;
1431
1828
  }
1432
- }
1433
- // 메모리 정리
1434
- for (const [key, timestamp] of ViewableEventTracker.viewableTracker.entries()) {
1435
- if ((now - timestamp) > cleanupThreshold) {
1436
- ViewableEventTracker.viewableTracker.delete(key);
1829
+ else {
1830
+ height = `${slot.height}px`;
1437
1831
  }
1832
+ containerStyles.height = height;
1438
1833
  }
1439
- }
1440
- /**
1441
- * 모든 추적 데이터 정리
1442
- */
1443
- static clear() {
1444
- ViewableEventTracker.viewableTracker.clear();
1445
- }
1446
- }
1447
- ViewableEventTracker.viewableTracker = new Map();
1448
- ViewableEventTracker.VIEWABLE_COOLDOWN = 30000; // 30초 쿨다운 (테스트용으로 단축)
1449
-
1450
- /**
1451
- * 디바이스 정보 수집 클래스
1452
- * - 브라우저 환경 정보 수집
1453
- * - 디바이스 ID 생성 관리
1454
- * - 세션 ID 생성 관리
1455
- */
1456
- class DeviceInfoCollector {
1457
- /**
1458
- * 디바이스 ID 생성 및 반환 (SSR 안전)
1459
- */
1460
- static generateDeviceId() {
1461
- if (!DOMUtils.isBrowser())
1462
- return 'ssr_device_' + Date.now();
1463
- const stored = localStorage.getItem('adstage_device_id');
1464
- if (stored)
1465
- return stored;
1466
- const deviceId = 'device_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
1467
- localStorage.setItem('adstage_device_id', deviceId);
1468
- return deviceId;
1469
- }
1470
- /**
1471
- * 세션 ID 생성 및 반환 (SSR 안전)
1472
- */
1473
- static generateSessionId() {
1474
- if (!DOMUtils.isBrowser())
1475
- return 'ssr_session_' + Date.now();
1476
- const stored = sessionStorage.getItem('adstage_session_id');
1477
- if (stored)
1478
- return stored;
1479
- const sessionId = 'session_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
1480
- sessionStorage.setItem('adstage_session_id', sessionId);
1481
- return sessionId;
1482
- }
1483
- /**
1484
- * 모바일 디바이스 여부 확인
1485
- */
1486
- static isMobile() {
1487
- return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
1488
- }
1489
- /**
1490
- * 플랫폼 타입 반환 (서버 enum에 맞춤)
1491
- */
1492
- static getPlatform() {
1493
- const userAgent = navigator.userAgent.toLowerCase();
1494
- if (/iphone|ipad|ipod/.test(userAgent)) {
1495
- return 'ios';
1496
- }
1497
- if (/android/.test(userAgent)) {
1498
- return 'android';
1499
- }
1500
- if (DeviceInfoCollector.isMobile()) {
1501
- return 'web'; // 모바일
1502
- }
1503
- return 'desktop'; // 데스크톱 웹
1504
- }
1505
- /**
1506
- * 완전한 디바이스 정보 수집
1507
- */
1508
- static collectDeviceInfo() {
1509
- const viewportInfo = DOMUtils.getViewportInfo();
1510
- return {
1511
- deviceId: DeviceInfoCollector.generateDeviceId(),
1512
- sessionId: DeviceInfoCollector.generateSessionId(),
1513
- osVersion: DOMUtils.isBrowser() ? navigator.platform : 'SSR',
1514
- deviceModel: DOMUtils.isBrowser() ? navigator.platform : 'SSR',
1515
- appVersion: '1.0.0',
1516
- sdkVersion: '1.0.0',
1517
- language: DOMUtils.isBrowser() ? (navigator.language || 'ko') : 'ko',
1518
- country: 'KR', // 기본값
1519
- ipAddress: '', // 서버에서 자동으로 설정됨
1520
- userAgent: DOMUtils.isBrowser() ? navigator.userAgent : 'SSR',
1521
- timezone: DOMUtils.isBrowser() ? Intl.DateTimeFormat().resolvedOptions().timeZone : 'UTC',
1522
- viewportWidth: viewportInfo.width,
1523
- viewportHeight: viewportInfo.height,
1524
- screenWidth: DOMUtils.isBrowser() ? screen.width : 0,
1525
- screenHeight: DOMUtils.isBrowser() ? screen.height : 0,
1526
- colorDepth: DOMUtils.isBrowser() ? screen.colorDepth : 24,
1527
- pixelRatio: viewportInfo.pixelRatio,
1528
- connectionType: DOMUtils.isBrowser() ? (navigator.connection?.effectiveType || 'unknown') : 'unknown',
1529
- platform: DeviceInfoCollector.getPlatform(),
1834
+ // 스타일 적용
1835
+ Object.entries(containerStyles).forEach(([key, value]) => {
1836
+ sliderWrapper.style.setProperty(key, value);
1837
+ });
1838
+ // 슬라이드 컨테이너
1839
+ const slideContainer = document.createElement('div');
1840
+ slideContainer.className = 'adstage-fade-slide-container';
1841
+ slideContainer.style.cssText = `
1842
+ position: relative;
1843
+ width: 100%;
1844
+ height: 100%;
1845
+ `;
1846
+ // 크기 측정을 위한 임시 컨테이너 (자동 크기 계산이 필요한 경우)
1847
+ let measureContainer = null;
1848
+ const needsWidthMeasurement = !slot.width || slot.width === 0;
1849
+ const needsHeightMeasurement = !slot.height || slot.height === 0;
1850
+ if (needsWidthMeasurement || needsHeightMeasurement) {
1851
+ measureContainer = document.createElement('div');
1852
+ measureContainer.style.cssText = `
1853
+ position: absolute;
1854
+ visibility: hidden;
1855
+ white-space: nowrap;
1856
+ top: -9999px;
1857
+ left: -9999px;
1858
+ `;
1859
+ // width가 설정되어 있으면 측정 컨테이너에도 적용
1860
+ if (!needsWidthMeasurement && slot.width) {
1861
+ let width;
1862
+ if (typeof slot.width === 'string') {
1863
+ width = slot.width.includes('px') || slot.width.includes('%') ? slot.width : `${slot.width}px`;
1864
+ }
1865
+ else {
1866
+ width = `${slot.width}px`;
1867
+ }
1868
+ measureContainer.style.width = width;
1869
+ measureContainer.style.whiteSpace = 'normal'; // width가 있으면 줄바꿈 허용
1870
+ }
1871
+ document.body.appendChild(measureContainer);
1872
+ let maxWidth = 0;
1873
+ let maxHeight = 0;
1874
+ // 모든 광고의 크기를 측정하여 최대 크기 찾기
1875
+ advertisements.forEach(ad => {
1876
+ const measureAdElement = AdRendererFactory.render(ad, slot, trackEventCallback);
1877
+ measureContainer.appendChild(measureAdElement);
1878
+ const rect = measureAdElement.getBoundingClientRect();
1879
+ if (rect.width > maxWidth)
1880
+ maxWidth = rect.width;
1881
+ if (rect.height > maxHeight)
1882
+ maxHeight = rect.height;
1883
+ // 측정 후 요소 제거
1884
+ measureContainer.removeChild(measureAdElement);
1885
+ });
1886
+ // 측정된 최대 크기로 래퍼 크기 설정
1887
+ if (needsWidthMeasurement && maxWidth > 0) {
1888
+ sliderWrapper.style.width = `${maxWidth}px`;
1889
+ }
1890
+ if (needsHeightMeasurement && maxHeight > 0) {
1891
+ sliderWrapper.style.height = `${maxHeight}px`;
1892
+ }
1893
+ // 측정 컨테이너 제거
1894
+ document.body.removeChild(measureContainer);
1895
+ }
1896
+ // 광고를 슬라이드로 생성
1897
+ const slideElements = [];
1898
+ advertisements.forEach((ad, index) => {
1899
+ const slideElement = document.createElement('div');
1900
+ slideElement.className = 'adstage-fade-slide';
1901
+ slideElement.style.cssText = `
1902
+ position: absolute;
1903
+ top: 0;
1904
+ left: 0;
1905
+ width: 100%;
1906
+ height: 100%;
1907
+ display: flex;
1908
+ align-items: center;
1909
+ justify-content: center;
1910
+ opacity: ${index === 0 ? '1' : '0'};
1911
+ transform: translateY(${index === 0 ? '0' : '20px'});
1912
+ transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
1913
+ z-index: ${index === 0 ? '2' : '1'};
1914
+ `;
1915
+ // 광고 렌더링
1916
+ const adElement = AdRendererFactory.render(ad, slot, trackEventCallback);
1917
+ slideElement.appendChild(adElement);
1918
+ slideContainer.appendChild(slideElement);
1919
+ slideElements.push(slideElement);
1920
+ });
1921
+ // 슬라이더 상태 관리
1922
+ let currentSlide = 0;
1923
+ const totalSlides = advertisements.length;
1924
+ const autoSlideInterval = (options?.autoSlideInterval || 4) * 1000; // 기본 4초 (페이드는 조금 더 길게)
1925
+ // 슬라이드 이동 함수 (페이드 효과)
1926
+ const moveToSlide = (index) => {
1927
+ if (index >= totalSlides) {
1928
+ index = 0; // 무한 루프
1929
+ }
1930
+ else if (index < 0) {
1931
+ index = totalSlides - 1;
1932
+ }
1933
+ const previousSlide = slideElements[currentSlide];
1934
+ const nextSlide = slideElements[index];
1935
+ // 이전 슬라이드 페이드 아웃 (아래로)
1936
+ previousSlide.style.opacity = '0';
1937
+ previousSlide.style.transform = 'translateY(-20px)';
1938
+ previousSlide.style.zIndex = '1';
1939
+ // 다음 슬라이드 페이드 인 (위에서)
1940
+ nextSlide.style.opacity = '1';
1941
+ nextSlide.style.transform = 'translateY(0)';
1942
+ nextSlide.style.zIndex = '2';
1943
+ // 다른 슬라이드들은 숨김
1944
+ slideElements.forEach((slide, i) => {
1945
+ if (i !== index && i !== currentSlide) {
1946
+ slide.style.opacity = '0';
1947
+ slide.style.transform = 'translateY(20px)';
1948
+ slide.style.zIndex = '1';
1949
+ }
1950
+ });
1951
+ currentSlide = index;
1952
+ // 현재 슬라이드의 광고에 대해 노출 이벤트 추적
1953
+ if (currentSlide > 0) { // 첫 번째는 이미 loadSlot에서 추적됨
1954
+ trackEventCallback(advertisements[currentSlide]._id, slot.id, AdEventType.VIEWABLE);
1955
+ }
1530
1956
  };
1957
+ // 자동 슬라이드
1958
+ let autoSlideTimer = setInterval(() => {
1959
+ const nextIndex = currentSlide + 1;
1960
+ moveToSlide(nextIndex);
1961
+ }, autoSlideInterval);
1962
+ // 마우스 호버 시 자동 슬라이드 일시정지
1963
+ sliderWrapper.addEventListener('mouseenter', () => {
1964
+ clearInterval(autoSlideTimer);
1965
+ });
1966
+ sliderWrapper.addEventListener('mouseleave', () => {
1967
+ autoSlideTimer = setInterval(() => {
1968
+ const nextIndex = currentSlide + 1;
1969
+ moveToSlide(nextIndex);
1970
+ }, autoSlideInterval);
1971
+ });
1972
+ // 터치 제스처 지원
1973
+ TextTransitionManager.addTouchSupport(sliderWrapper, moveToSlide, () => currentSlide, totalSlides);
1974
+ // 요소들 조립
1975
+ sliderWrapper.appendChild(slideContainer);
1976
+ return sliderWrapper;
1531
1977
  }
1532
1978
  /**
1533
- * 슬롯 위치 정보 가져오기 (SSR 안전)
1979
+ * 터치 제스처 지원 추가
1534
1980
  */
1535
- static getSlotPosition(containerId) {
1536
- const element = DOMUtils.safeGetElementById(containerId);
1537
- if (!element)
1538
- return 'unknown';
1539
- const rect = element.getBoundingClientRect();
1540
- const scrollInfo = DOMUtils.getScrollInfo();
1541
- return `x:${Math.round(rect.left)},y:${Math.round(rect.top + scrollInfo.scrollTop)}`;
1981
+ static addTouchSupport(container, moveToSlide, getCurrentSlide, totalSlides) {
1982
+ let startX = 0;
1983
+ let startY = 0;
1984
+ let isDragging = false;
1985
+ container.addEventListener('touchstart', (e) => {
1986
+ startX = e.touches[0].clientX;
1987
+ startY = e.touches[0].clientY;
1988
+ isDragging = true;
1989
+ });
1990
+ container.addEventListener('touchmove', (e) => {
1991
+ if (!isDragging)
1992
+ return;
1993
+ e.preventDefault();
1994
+ });
1995
+ container.addEventListener('touchend', (e) => {
1996
+ if (!isDragging)
1997
+ return;
1998
+ isDragging = false;
1999
+ const endX = e.changedTouches[0].clientX;
2000
+ const endY = e.changedTouches[0].clientY;
2001
+ const diffX = startX - endX;
2002
+ const diffY = startY - endY;
2003
+ // 가로 스와이프가 세로 스와이프보다 클 때만 처리
2004
+ if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
2005
+ const currentSlide = getCurrentSlide();
2006
+ if (diffX > 0) {
2007
+ // 왼쪽으로 스와이프 (다음 슬라이드)
2008
+ moveToSlide(currentSlide + 1);
2009
+ }
2010
+ else {
2011
+ // 오른쪽으로 스와이프 (이전 슬라이드)
2012
+ moveToSlide(currentSlide - 1);
2013
+ }
2014
+ }
2015
+ });
1542
2016
  }
1543
2017
  }
1544
2018
 
1545
2019
  /**
1546
- * AdStage SDK - API 헤더 유틸리티
1547
- * 공통 헤더 생성 로직
2020
+ * AdRenderer - 광고 렌더링 전용 클래스
2021
+ * AdsModule에서 렌더링 관련 기능을 분리
1548
2022
  */
1549
- class ApiHeaders {
1550
- /**
1551
- * 표준 API 헤더 생성
1552
- */
1553
- static create(apiKey, options) {
1554
- if (!apiKey) {
1555
- throw new Error('API key is required');
1556
- }
1557
- const headers = {
1558
- 'x-api-key': apiKey,
1559
- 'Content-Type': options?.contentType || 'application/json'
1560
- };
1561
- // User-Agent는 이벤트 추적에서 실제로 사용됨
1562
- if (typeof navigator !== 'undefined') {
1563
- headers['User-Agent'] = options?.userAgent || navigator.userAgent;
1564
- }
1565
- // X-Current-URL은 현재 서버에서 사용하지 않으므로 제거
1566
- // 필요시 이벤트 데이터 body에 포함
1567
- return headers;
2023
+ class AdRenderer {
2024
+ constructor(debug = false, advertisementEventTracker) {
2025
+ this.debug = debug;
2026
+ this.advertisementEventTracker = advertisementEventTracker || null;
1568
2027
  }
1569
2028
  /**
1570
- * 이벤트 추적용 헤더 생성
1571
- * User-Agent는 서버에서 실제로 사용됨
2029
+ * Placeholder(슬롯 컨테이너) 생성
1572
2030
  */
1573
- static createForEvents(apiKey, eventData) {
1574
- const baseHeaders = ApiHeaders.create(apiKey);
1575
- // User-Agent 오버라이드 (서버에서 실제 사용)
1576
- if (eventData?.userAgent) {
1577
- baseHeaders['User-Agent'] = eventData.userAgent;
2031
+ createPlaceholder(container, slotId, type, options, _config) {
2032
+ const adElement = document.createElement('div');
2033
+ adElement.id = slotId;
2034
+ adElement.className = `adstage-slot adstage-${String(type).toLowerCase()}`;
2035
+ adElement.setAttribute('data-adstage-container', 'true');
2036
+ adElement.setAttribute('data-adstage-type', String(type));
2037
+ adElement.setAttribute('data-adstage-slot', slotId);
2038
+ const { width, height } = this.calculateAdSize(container, type, options, _config) || {
2039
+ width: '100%',
2040
+ height: '250px'
2041
+ };
2042
+ adElement.style.width = width;
2043
+ adElement.style.height = height;
2044
+ adElement.style.border = '1px dashed #ccc';
2045
+ adElement.style.display = 'flex';
2046
+ adElement.style.alignItems = 'center';
2047
+ adElement.style.justifyContent = 'center';
2048
+ adElement.style.backgroundColor = '#f9f9f9';
2049
+ adElement.style.color = '#666';
2050
+ adElement.innerHTML = `<span>Loading ${type} ad...</span>`;
2051
+ container.appendChild(adElement);
2052
+ if (this.debug) {
2053
+ console.log(`📦 Placeholder created for slot: ${slotId} (${width} x ${height})`);
1578
2054
  }
1579
- // 다른 정보들은 HTTP 헤더가 아닌 이벤트 데이터 body에 포함하는 것이 적절
1580
- // (currentUrl, referrer 등은 POST body로 전송)
1581
- return baseHeaders;
1582
- }
1583
- }
1584
-
1585
- /**
1586
- * 광고 이벤트 추적 관리 클래스
1587
- * - 광고 전용 이벤트 추적 및 전송
1588
- * - Viewable 이벤트 중복 방지 통합
1589
- * - 광고 서버 API 통신
1590
- */
1591
- class AdvertisementEventTracker {
1592
- constructor(baseUrl, apiKey, debug, slots) {
1593
- this.baseUrl = baseUrl;
1594
- this.apiKey = apiKey;
1595
- this.debug = debug;
1596
- this.slots = slots;
1597
2055
  }
1598
2056
  /**
1599
- * 광고 이벤트 추적 - viewability 데이터 지원
2057
+ * 여러 광고의 최적 컨테이너 크기 계산 (동적 크기 조정)
1600
2058
  */
1601
- async trackAdvertisementEvent(adId, slotId, eventType, additionalData) {
1602
- try {
1603
- // 중복 확인은 AdsModule에서 이미 수행됨 - 여기서는 제거
1604
- // 현재 슬롯 정보 가져오기
1605
- const slot = this.slots.get(slotId);
1606
- // 디바이스 정보 수집
1607
- const deviceInfo = DeviceInfoCollector.collectDeviceInfo();
1608
- // 광고 이벤트 데이터 구성 (DTO 구조에 맞춤)
1609
- const eventData = {
1610
- // 서버에서 자동 설정: orgId, advertisementId, action
1611
- // 하지만 DTO 검증을 위해 임시값 제공
1612
- orgId: 'temp', // 서버에서 API 키로부터 덮어씀
1613
- advertisementId: adId, // 서버에서 URL 파라미터로부터 덮어씀
1614
- action: eventType, // 서버에서 URL 파라미터로부터 덮어씀
1615
- // 필수 필드들
1616
- adType: slot?.adType || 'BANNER',
1617
- platform: deviceInfo.platform,
1618
- // 디바이스 정보 - 스키마에 맞게 최상위 레벨로 추출
1619
- deviceId: deviceInfo.deviceId,
1620
- osVersion: deviceInfo.osVersion,
1621
- deviceModel: deviceInfo.deviceModel,
1622
- appVersion: deviceInfo.appVersion,
1623
- sdkVersion: deviceInfo.sdkVersion,
1624
- language: deviceInfo.language,
1625
- country: deviceInfo.country,
1626
- timezone: deviceInfo.timezone,
1627
- viewportWidth: deviceInfo.viewportWidth,
1628
- viewportHeight: deviceInfo.viewportHeight,
1629
- screenWidth: deviceInfo.screenWidth,
1630
- screenHeight: deviceInfo.screenHeight,
1631
- connectionType: deviceInfo.connectionType,
1632
- // 페이지 및 슬롯 정보
1633
- pageUrl: DOMUtils.getPageInfo().url,
1634
- pageTitle: DOMUtils.getPageInfo().title,
1635
- referrer: DOMUtils.getPageInfo().referrer,
1636
- slotId,
1637
- slotPosition: DeviceInfoCollector.getSlotPosition(slot?.containerId || ''),
1638
- slotWidth: AdvertisementEventTracker.parseNumericValue(slot?.width),
1639
- slotHeight: AdvertisementEventTracker.parseNumericValue(slot?.height),
1640
- sessionId: deviceInfo.sessionId,
1641
- // 성능 메트릭
1642
- pageLoadTime: performance.now(),
1643
- // 추가 메타데이터
1644
- metadata: {
1645
- eventType,
1646
- sdkVersion: '1.0.0',
1647
- timestamp: Date.now(),
1648
- },
1649
- // viewable 관련 추가 데이터 (DTO 필드명과 매칭)
1650
- ...(additionalData?.viewabilityMetrics && {
1651
- isViewable: additionalData.viewabilityMetrics.isViewable,
1652
- exposureTime: additionalData.viewabilityMetrics.exposureTime,
1653
- maxVisibilityRatio: additionalData.viewabilityMetrics.maxVisibilityRatio,
1654
- firstViewableTime: additionalData.viewabilityMetrics.firstViewableTime,
1655
- // IAB 표준 준수 여부
1656
- iabCompliant: additionalData.viewabilityMetrics.isViewable,
1657
- }),
1658
- // fraud 관련 데이터 (DTO 필드명과 매칭)
1659
- ...(additionalData?.fraudScore !== undefined && {
1660
- fraudScore: additionalData.fraudScore,
1661
- fraudReasons: additionalData.fraudReasons,
1662
- riskLevel: additionalData.riskLevel,
1663
- }),
2059
+ async calculateOptimalContainerSize(advertisements, containerWidth, adType) {
2060
+ if (!advertisements.length || adType !== AdType.BANNER) {
2061
+ return {
2062
+ width: '100%',
2063
+ height: this.getDefaultHeightForAdType(adType) || '250px',
2064
+ aspectRatio: 16 / 9
1664
2065
  };
1665
- await fetch(`${this.baseUrl}/advertisements/events/${adId}/${eventType}`, {
1666
- method: 'POST',
1667
- headers: ApiHeaders.createForEvents(this.apiKey, eventData),
1668
- body: JSON.stringify(eventData),
1669
- });
2066
+ }
2067
+ try {
2068
+ const imageDimensions = await Promise.allSettled(advertisements
2069
+ .filter(ad => ad.imageUrl)
2070
+ .map(ad => this.loadImageDimensions(ad.imageUrl)));
2071
+ const validDimensions = imageDimensions
2072
+ .filter((result) => result.status === 'fulfilled')
2073
+ .map(result => result.value);
2074
+ if (validDimensions.length === 0) {
2075
+ return {
2076
+ width: '100%',
2077
+ height: this.getDefaultHeightForAdType(adType) || '250px',
2078
+ aspectRatio: 16 / 9
2079
+ };
2080
+ }
2081
+ const strategy = this.selectOptimalSizeStrategy(validDimensions);
2082
+ const optimalHeight = this.calculateOptimalHeight(validDimensions, containerWidth, strategy);
1670
2083
  if (this.debug) {
1671
- console.log(`Tracked advertisement event: ${eventType} for ad ${adId}`, eventData);
2084
+ console.log(`📐 Optimal container calculated: ${containerWidth}x${optimalHeight} (strategy: ${strategy})`);
1672
2085
  }
2086
+ return {
2087
+ width: '100%',
2088
+ height: `${optimalHeight}px`,
2089
+ aspectRatio: containerWidth / optimalHeight
2090
+ };
1673
2091
  }
1674
2092
  catch (error) {
1675
- console.error('Failed to track advertisement event:', error);
2093
+ console.warn('Failed to calculate optimal size, using defaults:', error);
2094
+ return {
2095
+ width: '100%',
2096
+ height: this.getDefaultHeightForAdType(adType) || '250px',
2097
+ aspectRatio: 16 / 9
2098
+ };
1676
2099
  }
1677
2100
  }
1678
2101
  /**
1679
- * 크기 값을 숫자로 변환 (서버 API용)
2102
+ * 최적 크기 조정 전략 선택
1680
2103
  */
1681
- static parseNumericValue(value) {
1682
- if (typeof value === 'number') {
1683
- return value;
1684
- }
1685
- if (typeof value === 'string') {
1686
- // px 단위 제거하고 숫자만 추출
1687
- const numericValue = parseFloat(value.replace(/px$/, ''));
1688
- return isNaN(numericValue) ? 0 : numericValue;
2104
+ selectOptimalSizeStrategy(dimensions) {
2105
+ const aspectRatios = dimensions.map(d => d.width / d.height);
2106
+ const ratioGroups = new Map();
2107
+ aspectRatios.forEach(ratio => {
2108
+ const roundedRatio = Math.round(ratio * 10) / 10;
2109
+ const key = roundedRatio.toString();
2110
+ ratioGroups.set(key, (ratioGroups.get(key) || 0) + 1);
2111
+ });
2112
+ const maxGroup = Math.max(...ratioGroups.values());
2113
+ const totalImages = dimensions.length;
2114
+ if (maxGroup / totalImages >= 0.7) {
2115
+ return 'dominant';
1689
2116
  }
1690
- return 0; // 기본값
1691
- }
1692
- }
1693
-
1694
- /**
1695
- * IAB 표준 준수 viewable impression 측정
1696
- */
1697
- // 광고 타입별 IAB 표준 설정
1698
- const VIEWABILITY_STANDARDS = {
1699
- BANNER: {
1700
- threshold: 0.5,
1701
- minDuration: 1000,
1702
- maxMeasureTime: 30000
1703
- },
1704
- VIDEO: {
1705
- threshold: 0.5,
1706
- minDuration: 2000,
1707
- maxMeasureTime: 60000
1708
- },
1709
- NATIVE: {
1710
- threshold: 0.5,
1711
- minDuration: 1000,
1712
- maxMeasureTime: 30000
1713
- },
1714
- INTERSTITIAL: {
1715
- threshold: 0.5,
1716
- minDuration: 1000,
1717
- maxMeasureTime: 10000
1718
- },
1719
- TEXT: {
1720
- threshold: 0.5,
1721
- minDuration: 1000,
1722
- maxMeasureTime: 30000
1723
- },
1724
- POPUP: {
1725
- threshold: 0.5,
1726
- minDuration: 1000,
1727
- maxMeasureTime: 10000
1728
- }
1729
- };
1730
- class ViewabilityTracker {
1731
- constructor(element, adType, onViewable) {
1732
- this.observer = null;
1733
- this.viewabilityTimer = null;
1734
- this.maxVisibilityTimer = null;
1735
- this.startTime = 0;
1736
- this.maxVisibilityRatio = 0;
1737
- this.firstViewableTime = null;
1738
- this.isViewableAchieved = false;
1739
- this.element = element;
1740
- this.config = VIEWABILITY_STANDARDS[adType] || VIEWABILITY_STANDARDS.BANNER;
1741
- this.onViewableCallback = onViewable;
1742
- this.startTime = performance.now();
1743
- this.initIntersectionObserver();
1744
- this.initMaxMeasureTimer();
1745
- }
1746
- initIntersectionObserver() {
1747
- // IntersectionObserver 지원 확인
1748
- if (!('IntersectionObserver' in window)) {
1749
- console.warn('IntersectionObserver not supported, viewability tracking disabled');
1750
- return;
2117
+ const standardRatios = [16 / 9, 4 / 3, 1 / 1, 3 / 2];
2118
+ const standardCount = aspectRatios.filter(ratio => standardRatios.some(standard => Math.abs(ratio - standard) < 0.1)).length;
2119
+ if (standardCount / totalImages >= 0.5) {
2120
+ return 'common';
1751
2121
  }
1752
- this.observer = new IntersectionObserver((entries) => this.handleIntersection(entries), {
1753
- threshold: [0, 0.1, 0.25, 0.5, 0.75, 1.0],
1754
- rootMargin: '0px'
1755
- });
1756
- this.observer.observe(this.element);
2122
+ return 'average';
1757
2123
  }
1758
- handleIntersection(entries) {
1759
- entries.forEach(entry => {
1760
- const visibilityRatio = entry.intersectionRatio;
1761
- const isVisible = this.isDocumentVisible();
1762
- // 최대 가시성 비율 추적
1763
- this.maxVisibilityRatio = Math.max(this.maxVisibilityRatio, visibilityRatio);
1764
- // Viewable 조건 확인 (50% 이상 + 문서 가시성)
1765
- if (visibilityRatio >= this.config.threshold && isVisible) {
1766
- this.startViewabilityTimer();
2124
+ /**
2125
+ * 전략에 따른 최적 높이 계산
2126
+ */
2127
+ calculateOptimalHeight(dimensions, containerWidth, strategy) {
2128
+ const aspectRatios = dimensions.map(d => d.width / d.height);
2129
+ switch (strategy) {
2130
+ case 'dominant': {
2131
+ const ratioGroups = new Map();
2132
+ aspectRatios.forEach(ratio => {
2133
+ const roundedRatio = Math.round(ratio * 10) / 10;
2134
+ const key = roundedRatio.toString();
2135
+ const existing = ratioGroups.get(key);
2136
+ if (existing) {
2137
+ existing.count++;
2138
+ }
2139
+ else {
2140
+ ratioGroups.set(key, { ratio: roundedRatio, count: 1 });
2141
+ }
2142
+ });
2143
+ const dominantGroup = Array.from(ratioGroups.values()).reduce((max, current) => current.count > max.count ? current : max);
2144
+ return Math.round(containerWidth / dominantGroup.ratio);
1767
2145
  }
1768
- else {
1769
- this.stopViewabilityTimer();
2146
+ case 'common': {
2147
+ const standardRatios = [
2148
+ { ratio: 16 / 9, name: '16:9' },
2149
+ { ratio: 4 / 3, name: '4:3' },
2150
+ { ratio: 1 / 1, name: '1:1' },
2151
+ { ratio: 3 / 2, name: '3:2' }
2152
+ ];
2153
+ const avgRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
2154
+ const bestStandard = standardRatios.reduce((best, current) => Math.abs(current.ratio - avgRatio) < Math.abs(best.ratio - avgRatio) ? current : best);
2155
+ if (this.debug) {
2156
+ console.log(`📊 Using standard ratio: ${bestStandard.name} (avg: ${avgRatio.toFixed(2)})`);
2157
+ }
2158
+ return Math.round(containerWidth / bestStandard.ratio);
2159
+ }
2160
+ case 'average':
2161
+ default: {
2162
+ const averageRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
2163
+ return Math.round(containerWidth / averageRatio);
1770
2164
  }
1771
- });
1772
- }
1773
- isDocumentVisible() {
1774
- // 단순한 문서 가시성 확인
1775
- return !document.hidden && document.visibilityState === 'visible';
1776
- }
1777
- startViewabilityTimer() {
1778
- if (this.viewabilityTimer || this.isViewableAchieved)
1779
- return;
1780
- if (this.firstViewableTime === null) {
1781
- this.firstViewableTime = performance.now();
1782
2165
  }
1783
- this.viewabilityTimer = setTimeout(() => {
1784
- this.onViewabilityAchieved();
1785
- }, this.config.minDuration);
1786
2166
  }
1787
- stopViewabilityTimer() {
1788
- if (this.viewabilityTimer) {
1789
- clearTimeout(this.viewabilityTimer);
1790
- this.viewabilityTimer = null;
2167
+ /**
2168
+ * 배너 광고를 위한 컨테이너 최적화
2169
+ */
2170
+ async optimizeContainerForBannerAds(slot, advertisements) {
2171
+ try {
2172
+ const container = document.getElementById(slot.containerId);
2173
+ const adElement = document.getElementById(slot.id);
2174
+ if (!container || !adElement)
2175
+ return;
2176
+ const containerWidth = container.getBoundingClientRect().width || 300;
2177
+ const optimalSize = await this.calculateOptimalContainerSize(advertisements, containerWidth, slot.adType);
2178
+ adElement.style.height = optimalSize.height;
2179
+ slot.optimizedHeight = optimalSize.height;
2180
+ slot.aspectRatio = optimalSize.aspectRatio;
2181
+ if (this.debug) {
2182
+ console.log(`🔧 Container optimized for ${advertisements.length} banner ads: ${optimalSize.height}`);
2183
+ }
1791
2184
  }
1792
- }
1793
- initMaxMeasureTimer() {
1794
- // 최대 측정 시간 후 자동 종료
1795
- this.maxVisibilityTimer = setTimeout(() => {
1796
- this.destroy();
1797
- }, this.config.maxMeasureTime);
1798
- }
1799
- onViewabilityAchieved() {
1800
- if (this.isViewableAchieved)
1801
- return;
1802
- this.isViewableAchieved = true;
1803
- const metrics = this.calculateMetrics();
1804
- if (this.onViewableCallback) {
1805
- this.onViewableCallback(metrics);
2185
+ catch (error) {
2186
+ console.warn('Container optimization failed, using default size:', error);
1806
2187
  }
1807
2188
  }
1808
- calculateMetrics() {
1809
- const currentTime = performance.now();
1810
- const exposureTime = this.firstViewableTime
1811
- ? currentTime - this.firstViewableTime
1812
- : 0;
1813
- return {
1814
- isViewable: this.isViewableAchieved,
1815
- exposureTime,
1816
- maxVisibilityRatio: this.maxVisibilityRatio,
1817
- firstViewableTime: this.firstViewableTime,
1818
- measureStartTime: this.startTime,
2189
+ /**
2190
+ * 광고 슬라이더 렌더링 (여러 광고 또는 autoSlide 옵션)
2191
+ */
2192
+ async renderAdSlider(slot, advertisements) {
2193
+ const container = document.getElementById(slot.containerId);
2194
+ if (!container) {
2195
+ throw new Error(`Container not found: ${slot.containerId}`);
2196
+ }
2197
+ const trackEventCallback = async (adId, slotId, eventType) => {
2198
+ if (eventType === AdEventType.VIEWABLE) {
2199
+ if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this.debug)) {
2200
+ if (this.debug) {
2201
+ console.log(`🚫 Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
2202
+ }
2203
+ return;
2204
+ }
2205
+ if (this.debug) {
2206
+ console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
2207
+ }
2208
+ }
2209
+ if (this.advertisementEventTracker) {
2210
+ try {
2211
+ await this.advertisementEventTracker.trackAdvertisementEvent(adId, slotId, eventType, {});
2212
+ if (this.debug) {
2213
+ console.log(`📊 Advertisement event tracked: ${eventType} for ad ${adId} in slot ${slotId}`);
2214
+ }
2215
+ }
2216
+ catch (error) {
2217
+ if (this.debug) {
2218
+ console.error(`❌ Failed to track ${eventType} event for ad ${adId}:`, error);
2219
+ }
2220
+ }
2221
+ }
1819
2222
  };
1820
- }
1821
- getMetrics() {
1822
- return this.calculateMetrics();
1823
- }
1824
- destroy() {
1825
- this.stopViewabilityTimer();
1826
- if (this.maxVisibilityTimer) {
1827
- clearTimeout(this.maxVisibilityTimer);
1828
- this.maxVisibilityTimer = null;
2223
+ let sliderElement;
2224
+ const optimizedSliderOptions = {
2225
+ autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
2226
+ ...slot.config,
2227
+ optimizedHeight: slot.optimizedHeight,
2228
+ aspectRatio: slot.aspectRatio
2229
+ };
2230
+ if (slot.adType === AdType.TEXT) {
2231
+ sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
2232
+ if (this.debug) {
2233
+ console.log(`✨ Text transition created for TEXT slot: ${slot.id} with ${advertisements.length} ads`);
2234
+ }
1829
2235
  }
1830
- if (this.observer) {
1831
- this.observer.disconnect();
1832
- this.observer = null;
2236
+ else {
2237
+ sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
2238
+ if (this.debug) {
2239
+ console.log(`🎠 Carousel slider created for ${slot.adType} slot: ${slot.id} with ${advertisements.length} ads (optimized: ${slot.optimizedHeight || 'default'})`);
2240
+ }
2241
+ }
2242
+ container.innerHTML = '';
2243
+ container.appendChild(sliderElement);
2244
+ if (this.debug) {
2245
+ console.log(`� Slider uses manual VIEWABLE event tracking for ${advertisements.length} ads`);
1833
2246
  }
1834
2247
  }
1835
- }
1836
-
1837
- /**
1838
- * BasicFraudDetector - 현실적 구현 버전
1839
- * 기본적인 봇 탐지 및 간단한 행동 패턴 분석
1840
- */
1841
- class BasicFraudDetector {
1842
- constructor() {
1843
- this.mouseEvents = 0;
1844
- this.keyboardEvents = 0;
1845
- this.scrollEvents = 0;
1846
- this.startTime = Date.now();
1847
- this.initBasicTracking();
1848
- }
1849
- initBasicTracking() {
1850
- // 기본적인 사용자 상호작용 추적
1851
- document.addEventListener('mousemove', () => this.mouseEvents++, { passive: true });
1852
- document.addEventListener('keydown', () => this.keyboardEvents++, { passive: true });
1853
- document.addEventListener('scroll', () => this.scrollEvents++, { passive: true });
2248
+ /**
2249
+ * 광고 렌더링 (단일 광고용)
2250
+ */
2251
+ async renderAd(slot) {
2252
+ if (!slot.advertisement) {
2253
+ throw new Error('No advertisement to render');
2254
+ }
2255
+ await this.renderAdElement(slot, slot.advertisement);
2256
+ slot.isLoaded = true;
1854
2257
  }
1855
- calculateFraudScore() {
1856
- let score = 0;
1857
- const reasons = [];
1858
- // 1. 웹드라이버 탐지 (기본)
1859
- if (this.detectWebDriver()) {
1860
- score += 50;
1861
- reasons.push('WebDriver detected');
2258
+ /**
2259
+ * 광고 요소 렌더링 (기본 구현)
2260
+ */
2261
+ async renderAdElement(slot, ad) {
2262
+ const container = document.getElementById(slot.containerId);
2263
+ if (!container)
2264
+ return;
2265
+ const adElement = document.createElement('div');
2266
+ adElement.className = 'adstage-ad';
2267
+ const optimizedHeight = slot.optimizedHeight;
2268
+ const containerElement = container.parentElement || container;
2269
+ if (optimizedHeight) {
2270
+ adElement.style.width = '100%';
2271
+ adElement.style.height = String(optimizedHeight);
1862
2272
  }
1863
- // 2. 헤드리스 브라우저 기본 탐지
1864
- if (this.detectBasicHeadless()) {
1865
- score += 40;
1866
- reasons.push('Headless browser signatures');
2273
+ else {
2274
+ const { width, height } = this.calculateAdSize(containerElement, slot.adType, slot.config || {}, { debug: this.debug }) ||
2275
+ { width: '100%', height: '250px' };
2276
+ adElement.style.width = width;
2277
+ adElement.style.height = height;
1867
2278
  }
1868
- // 3. 사용자 상호작용 부족
1869
- const sessionTime = Date.now() - this.startTime;
1870
- if (sessionTime > 5000) { // 5초 이상 경과
1871
- if (this.mouseEvents === 0) {
1872
- score += 20;
1873
- reasons.push('No mouse interaction');
1874
- }
1875
- if (this.scrollEvents === 0 && sessionTime > 10000) {
1876
- score += 15;
1877
- reasons.push('No scroll activity');
2279
+ switch (slot.adType) {
2280
+ case AdType.BANNER:
2281
+ if (ad.imageUrl) {
2282
+ await this.renderOptimizedBannerImage(adElement, ad, slot);
2283
+ }
2284
+ break;
2285
+ case AdType.TEXT: {
2286
+ const textDiv = document.createElement('div');
2287
+ textDiv.innerHTML = `
2288
+ <h3>${ad.title}</h3>
2289
+ ${ad.description ? `<p>${ad.description}</p>` : ''}
2290
+ ${ad.textContent ? `<div>${ad.textContent}</div>` : ''}
2291
+ `;
2292
+ adElement.appendChild(textDiv);
2293
+ break;
1878
2294
  }
2295
+ case AdType.VIDEO:
2296
+ if (ad.videoUrl) {
2297
+ const video = document.createElement('video');
2298
+ video.src = ad.videoUrl;
2299
+ video.controls = true;
2300
+ video.style.width = '100%';
2301
+ video.style.height = '100%';
2302
+ adElement.appendChild(video);
2303
+ }
2304
+ break;
2305
+ default:
2306
+ adElement.innerHTML = `<div>${ad.title}</div>`;
1879
2307
  }
1880
- // 4. 브라우저 환경 이상 징후
1881
- const browserCheck = this.checkBrowserEnvironment();
1882
- score += browserCheck.score;
1883
- reasons.push(...browserCheck.reasons);
1884
- // 5. 시간 패턴 이상 (너무 빠른 페이지 로드 후 즉시 클릭)
1885
- if (sessionTime < 1000) {
1886
- score += 25;
1887
- reasons.push('Suspiciously fast interaction');
2308
+ if (ad.linkUrl) {
2309
+ adElement.style.cursor = 'pointer';
2310
+ adElement.addEventListener('click', () => {
2311
+ window.open(ad.linkUrl, '_blank');
2312
+ });
1888
2313
  }
1889
- const finalScore = Math.min(score, 100);
1890
- return {
1891
- score: finalScore,
1892
- riskLevel: this.getRiskLevel(finalScore),
1893
- reasons: reasons
1894
- };
1895
- }
1896
- detectWebDriver() {
1897
- // 기본적인 웹드라이버 탐지
1898
- return !!(window.webdriver ||
1899
- navigator.webdriver ||
1900
- window.__webdriver_evaluate ||
1901
- window.__selenium_evaluate ||
1902
- window.__webdriver_script_function ||
1903
- window.__webdriver_script_func ||
1904
- window.__webdriver_script_fn ||
1905
- window.__fxdriver_evaluate ||
1906
- window.__driver_unwrapped ||
1907
- window.__webdriver_unwrapped ||
1908
- window.__driver_evaluate ||
1909
- window.__selenium_unwrapped ||
1910
- window.__fxdriver_unwrapped);
2314
+ container.innerHTML = '';
2315
+ container.appendChild(adElement);
1911
2316
  }
1912
- detectBasicHeadless() {
1913
- const signatures = [];
1914
- // PhantomJS 탐지
1915
- if (window._phantom || window.phantom) {
1916
- signatures.push('PhantomJS');
2317
+ /**
2318
+ * Fallback 광고 렌더링 - 컨테이너 접기/생성
2319
+ */
2320
+ renderFallback(slot) {
2321
+ const element = document.getElementById(slot.id);
2322
+ if (element) {
2323
+ const adstageContainers = [
2324
+ element.querySelector('[data-adstage-container="true"]'),
2325
+ element.closest('[data-adstage-container="true"]'),
2326
+ element
2327
+ ].filter(el => el && el.hasAttribute('data-adstage-container'));
2328
+ const classBasedContainers = [
2329
+ element.closest('.adstage-slot'),
2330
+ element.closest('.adstage-banner'),
2331
+ element.closest('.adstage-text'),
2332
+ element.closest('.adstage-video'),
2333
+ element.closest('.adstage-native'),
2334
+ element.closest('.adstage-interstitial')
2335
+ ].filter(Boolean);
2336
+ const generalContainers = [
2337
+ element.closest('[class*="ad"]'),
2338
+ element.closest('[class*="banner"]'),
2339
+ element.closest('[class*="container"]'),
2340
+ element.closest('div[style*="height"]'),
2341
+ element.closest('div[style*="min-height"]'),
2342
+ element.parentElement
2343
+ ].filter(Boolean);
2344
+ const possibleContainers = [...adstageContainers, ...classBasedContainers, ...generalContainers];
2345
+ const targetContainer = possibleContainers[0];
2346
+ if (targetContainer) {
2347
+ let containerType = 'unknown';
2348
+ if (targetContainer.hasAttribute('data-adstage-container')) {
2349
+ containerType = 'adstage-official';
2350
+ }
2351
+ else if (targetContainer.classList.contains('adstage-slot')) {
2352
+ containerType = 'adstage-class';
2353
+ }
2354
+ else {
2355
+ containerType = 'generic';
2356
+ }
2357
+ targetContainer.style.cssText += `
2358
+ height: 0px !important;
2359
+ min-height: 0px !important;
2360
+ padding: 0px !important;
2361
+ margin: 0px !important;
2362
+ border: none !important;
2363
+ overflow: hidden !important;
2364
+ display: block !important;
2365
+ `;
2366
+ targetContainer.innerHTML = '';
2367
+ targetContainer.setAttribute('data-adstage-empty', 'true');
2368
+ if (this.debug) {
2369
+ console.warn(`⚠️ Ad container collapsed (${containerType}): ${slot.id}`, targetContainer);
2370
+ }
2371
+ }
2372
+ else {
2373
+ this.createEmptyContainer(slot);
2374
+ }
1917
2375
  }
1918
- // Chrome headless 기본 탐지
1919
- if (navigator.userAgent.includes('HeadlessChrome')) {
1920
- signatures.push('Chrome Headless');
2376
+ slot.advertisement = undefined;
2377
+ slot.isEmpty = true;
2378
+ }
2379
+ /**
2380
+ * 빈 컨테이너 생성 (컨테이너를 찾지 못한 경우)
2381
+ */
2382
+ createEmptyContainer(slot) {
2383
+ const originalContainer = document.getElementById(slot.containerId);
2384
+ if (originalContainer) {
2385
+ originalContainer.innerHTML = '';
2386
+ const emptyElement = document.createElement('div');
2387
+ emptyElement.id = slot.id;
2388
+ emptyElement.className = 'adstage-slot adstage-empty';
2389
+ emptyElement.setAttribute('data-adstage-container', 'true');
2390
+ emptyElement.setAttribute('data-adstage-empty', 'true');
2391
+ emptyElement.setAttribute('data-adstage-slot', slot.id);
2392
+ emptyElement.style.cssText = `
2393
+ height: 0px !important;
2394
+ min-height: 0px !important;
2395
+ padding: 0px !important;
2396
+ margin: 0px !important;
2397
+ border: none !important;
2398
+ overflow: hidden !important;
2399
+ display: block !important;
2400
+ `;
2401
+ originalContainer.appendChild(emptyElement);
2402
+ if (this.debug) {
2403
+ console.warn(`⚠️ Created empty AdStage container: ${slot.id}`);
2404
+ }
1921
2405
  }
1922
- // 플러그인 없음 (일반적이지 않음)
1923
- if (navigator.plugins.length === 0) {
1924
- signatures.push('No plugins');
2406
+ }
2407
+ /**
2408
+ * 광고 타입별 기본 높이 반환
2409
+ */
2410
+ getDefaultHeightForAdType(type) {
2411
+ switch (type) {
2412
+ case AdType.BANNER:
2413
+ return '250px'; // 일반 배너
2414
+ case AdType.TEXT:
2415
+ return '120px'; // 텍스트는 좀 더 작게
2416
+ case AdType.VIDEO:
2417
+ return '360px'; // 비디오는 16:9 비율 고려
2418
+ case AdType.NATIVE:
2419
+ return '200px'; // 네이티브는 중간 크기
2420
+ case AdType.INTERSTITIAL:
2421
+ return '400px'; // 전면광고는 크게
2422
+ default:
2423
+ return '250px';
1925
2424
  }
1926
- return signatures.length > 0;
1927
2425
  }
1928
- checkBrowserEnvironment() {
1929
- let score = 0;
1930
- const reasons = [];
1931
- // 언어 설정 이상
1932
- if (!navigator.language || navigator.language === 'C') {
1933
- score += 10;
1934
- reasons.push('Unusual language setting');
2426
+ /**
2427
+ * 컨테이너와 광고 타입에 따른 스마트한 크기 계산
2428
+ */
2429
+ calculateAdSize(container, type, options, config) {
2430
+ // 사용자가 명시적으로 크기를 지정한 경우
2431
+ const explicitWidth = options.width;
2432
+ const explicitHeight = options.height;
2433
+ // 너비 처리
2434
+ let width;
2435
+ if (typeof explicitWidth === 'number') {
2436
+ width = `${explicitWidth}px`;
1935
2437
  }
1936
- // 쿠키 비활성화
1937
- if (!navigator.cookieEnabled) {
1938
- score += 15;
1939
- reasons.push('Cookies disabled');
2438
+ else if (typeof explicitWidth === 'string') {
2439
+ width = explicitWidth;
1940
2440
  }
1941
- // 화면 해상도 이상
1942
- if (screen.width === 0 || screen.height === 0) {
1943
- score += 20;
1944
- reasons.push('Invalid screen resolution');
2441
+ else {
2442
+ width = '100%'; // 기본값은 100%
1945
2443
  }
1946
- // 시간대 정보 없음
1947
- try {
1948
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1949
- if (!timezone || timezone === 'UTC') {
1950
- score += 5;
1951
- reasons.push('No timezone info');
1952
- }
2444
+ // 높이 처리 - 핵심 로직
2445
+ let height;
2446
+ if (typeof explicitHeight === 'number') {
2447
+ height = `${explicitHeight}px`;
1953
2448
  }
1954
- catch (e) {
1955
- score += 10;
1956
- reasons.push('Timezone detection failed');
2449
+ else if (typeof explicitHeight === 'string' && explicitHeight !== '100%' && explicitHeight !== 'auto') {
2450
+ // 명시적인 크기 문자열 (예: '200px', '50vh' 등)
2451
+ height = explicitHeight;
1957
2452
  }
1958
- return { score, reasons };
1959
- }
1960
- getRiskLevel(score) {
1961
- if (score >= 70)
1962
- return 'CRITICAL';
1963
- if (score >= 50)
1964
- return 'HIGH';
1965
- if (score >= 30)
1966
- return 'MEDIUM';
1967
- return 'LOW';
1968
- }
1969
- getBrowserInfo() {
1970
- return {
1971
- userAgent: navigator.userAgent,
1972
- language: navigator.language,
1973
- platform: navigator.platform,
1974
- cookieEnabled: navigator.cookieEnabled,
1975
- doNotTrack: navigator.doNotTrack,
1976
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1977
- screenResolution: `${screen.width}x${screen.height}`,
1978
- viewportSize: `${window.innerWidth}x${window.innerHeight}`
1979
- };
1980
- }
1981
- destroy() {
1982
- // 이벤트 리스너 정리는 생략 (메모리 누수 방지를 위해 필요시 구현)
2453
+ else {
2454
+ // 100%, auto이거나 높이가 지정되지 않은 경우 스마트 계산
2455
+ const containerHeight = this.getContainerHeight(container);
2456
+ if (containerHeight > 0) {
2457
+ // 컨테이너에 높이가 있으면 100% 사용
2458
+ height = '100%';
2459
+ if (config?.debug) {
2460
+ console.log(`📏 Using 100% height (container: ${containerHeight}px)`);
2461
+ }
2462
+ }
2463
+ else {
2464
+ // 컨테이너에 높이가 없으면 타입별 기본값 사용 (나중에 동적 조정됨)
2465
+ height = this.getDefaultHeightForAdType(type);
2466
+ if (config?.debug) {
2467
+ console.log(`📏 Using default height ${height} (will be optimized for ${type})`);
2468
+ }
2469
+ }
2470
+ }
2471
+ return { width, height };
1983
2472
  }
1984
- }
1985
-
1986
- /**
1987
- * AdStage SDK 엔드포인트 상수 관리
1988
- * 모든 API URL을 중앙에서 관리
1989
- */
1990
- /**
1991
- * 환경별 API 엔드포인트 (읽기 전용)
1992
- */
1993
- const API_ENDPOINTS = {
1994
- /** 프로덕션 환경 */
1995
- production: 'https://api.adstage.io',
1996
- /** 베타 환경 (기본값) */
1997
- beta: 'https://beta-api.adstage.app'
1998
- };
1999
- /**
2000
- * API 경로 상수
2001
- */
2002
- const API_PATHS = {
2003
- /** 광고 관련 */
2004
- advertisements: {
2005
- list: '/advertisements/list',
2006
- events: '/advertisements/events'
2007
- },
2008
- /** 이벤트 관련 */
2009
- events: {
2010
- track: '/events/track',
2011
- batch: '/events/batch'
2473
+ /**
2474
+ * 컨테이너의 실제 높이 계산
2475
+ */
2476
+ getContainerHeight(container) {
2477
+ // 현재 계산된 스타일에서 높이 확인
2478
+ const computedStyle = window.getComputedStyle(container);
2479
+ const height = parseFloat(computedStyle.height);
2480
+ // height가 auto이거나 0이면 다른 방법들 시도
2481
+ if (!height || height === 0) {
2482
+ // min-height 확인
2483
+ const minHeight = parseFloat(computedStyle.minHeight);
2484
+ if (minHeight > 0)
2485
+ return minHeight;
2486
+ // CSS로 설정된 고정 높이 확인
2487
+ if (container.style.height && container.style.height !== 'auto') {
2488
+ const styleHeight = parseFloat(container.style.height);
2489
+ if (styleHeight > 0)
2490
+ return styleHeight;
2491
+ }
2492
+ // 속성으로 설정된 높이 확인
2493
+ const heightAttr = container.getAttribute('height');
2494
+ if (heightAttr) {
2495
+ const attrHeight = parseFloat(heightAttr);
2496
+ if (attrHeight > 0)
2497
+ return attrHeight;
2498
+ }
2499
+ }
2500
+ return height || 0;
2012
2501
  }
2013
- };
2014
- /**
2015
- * 완전한 API URL 생성 헬퍼
2016
- */
2017
- class EndpointBuilder {
2018
- constructor(baseUrl) {
2019
- /**
2020
- * 광고 엔드포인트
2021
- */
2022
- this.advertisements = {
2023
- list: () => `${this.baseUrl}${API_PATHS.advertisements.list}`,
2024
- events: (adId, eventType) => `${this.baseUrl}${API_PATHS.advertisements.events}/${adId}/${eventType}`
2025
- };
2026
- /**
2027
- * 이벤트 엔드포인트
2028
- */
2029
- this.events = {
2030
- track: () => `${this.baseUrl}${API_PATHS.events.track}`,
2031
- batch: () => `${this.baseUrl}${API_PATHS.events.batch}`
2032
- };
2033
- // 기본값은 베타 환경 사용
2034
- this.baseUrl = baseUrl || API_ENDPOINTS.beta;
2502
+ /**
2503
+ * 이미지 로드 및 실제 크기 획득 (Promise 기반)
2504
+ */
2505
+ loadImageDimensions(imageUrl) {
2506
+ return new Promise((resolve, reject) => {
2507
+ const img = new Image();
2508
+ img.onload = () => {
2509
+ resolve({ width: img.naturalWidth, height: img.naturalHeight });
2510
+ };
2511
+ img.onerror = () => {
2512
+ reject(new Error(`Failed to load image: ${imageUrl}`));
2513
+ };
2514
+ img.src = imageUrl;
2515
+ });
2035
2516
  }
2036
2517
  /**
2037
- * 기본 URL 변경
2518
+ * 이미지와 컨테이너 비율을 고려한 최적화 스타일 적용
2038
2519
  */
2039
- setBaseUrl(url) {
2040
- this.baseUrl = url;
2041
- console.log('🔄 API endpoint changed:', url);
2520
+ applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio) {
2521
+ const ratio = imageAspectRatio / containerAspectRatio;
2522
+ if (Math.abs(ratio - 1) < 0.1) {
2523
+ // 비율이 거의 같으면 cover 사용
2524
+ img.style.objectFit = 'cover';
2525
+ img.style.objectPosition = 'center';
2526
+ }
2527
+ else if (ratio > 1.3) {
2528
+ // 이미지가 훨씬 가로형이면 contain으로 전체 보이기
2529
+ img.style.objectFit = 'contain';
2530
+ img.style.objectPosition = 'center';
2531
+ img.style.backgroundColor = '#f0f0f0'; // 빈 공간 배경색
2532
+ }
2533
+ else if (ratio < 0.7) {
2534
+ // 이미지가 훨씬 세로형이면 cover로 채우기
2535
+ img.style.objectFit = 'cover';
2536
+ img.style.objectPosition = 'center';
2537
+ }
2538
+ else {
2539
+ // 적당한 차이면 스마트 cover
2540
+ img.style.objectFit = 'cover';
2541
+ img.style.objectPosition = 'center';
2542
+ }
2543
+ if (this.debug) {
2544
+ console.log(`🎨 Image style applied: objectFit=${img.style.objectFit}, ratio=${ratio.toFixed(2)}`);
2545
+ }
2042
2546
  }
2043
2547
  /**
2044
- * 기본 URL 반환
2548
+ * 배너 이미지 최적화 렌더링
2549
+ * 이미지 실제 크기를 로드한 후 컨테이너와 비율을 맞춤
2045
2550
  */
2046
- getBaseUrl() {
2047
- return this.baseUrl;
2551
+ async renderOptimizedBannerImage(container, advertisement, slot) {
2552
+ const img = document.createElement('img');
2553
+ // 기본 스타일 설정
2554
+ img.style.width = '100%';
2555
+ img.style.height = '100%';
2556
+ img.style.display = 'block';
2557
+ img.style.borderRadius = '8px';
2558
+ img.alt = advertisement.title || 'Advertisement';
2559
+ // 이미지 로딩 상태 표시
2560
+ container.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;">Loading...</div>';
2561
+ try {
2562
+ // 이미지 URL 체크
2563
+ if (!advertisement.imageUrl) {
2564
+ throw new Error('Image URL is not provided');
2565
+ }
2566
+ // 🆕 이미지 실제 크기 로드
2567
+ const imageDimensions = await this.loadImageDimensions(advertisement.imageUrl);
2568
+ // 컨테이너 크기 정보
2569
+ const containerRect = container.getBoundingClientRect();
2570
+ const containerWidth = containerRect.width;
2571
+ const containerHeight = containerRect.height;
2572
+ if (this.debug) {
2573
+ console.log(`📸 Image dimensions: ${imageDimensions.width}x${imageDimensions.height}`);
2574
+ console.log(`📦 Container dimensions: ${containerWidth}x${containerHeight}`);
2575
+ }
2576
+ // 비율 계산
2577
+ const imageAspectRatio = imageDimensions.width / imageDimensions.height;
2578
+ const containerAspectRatio = containerWidth / containerHeight;
2579
+ // 🆕 스마트 스타일 적용
2580
+ this.applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio);
2581
+ // 이미지 설정 및 추가
2582
+ img.src = advertisement.imageUrl;
2583
+ // 컨테이너 클리어 후 이미지 추가
2584
+ container.innerHTML = '';
2585
+ container.appendChild(img);
2586
+ // 클릭 이벤트 등록
2587
+ if (advertisement.linkUrl) {
2588
+ img.style.cursor = 'pointer';
2589
+ img.addEventListener('click', () => {
2590
+ if (this.advertisementEventTracker) {
2591
+ // AdvertisementEventTracker의 실제 메소드명을 확인해야 함
2592
+ console.log(`Click tracked for ad: ${advertisement._id}`);
2593
+ }
2594
+ window.open(advertisement.linkUrl, '_blank');
2595
+ });
2596
+ }
2597
+ if (this.debug) {
2598
+ console.log(`✅ Optimized banner image rendered for ad: ${advertisement._id}`);
2599
+ }
2600
+ return img;
2601
+ }
2602
+ catch (error) {
2603
+ console.error('❌ Failed to load optimized banner image:', error);
2604
+ // 폴백: 일반 이미지 렌더링
2605
+ if (advertisement.imageUrl) {
2606
+ img.src = advertisement.imageUrl;
2607
+ img.style.objectFit = 'cover';
2608
+ img.style.objectPosition = 'center';
2609
+ container.innerHTML = '';
2610
+ container.appendChild(img);
2611
+ if (advertisement.linkUrl) {
2612
+ img.style.cursor = 'pointer';
2613
+ img.addEventListener('click', () => {
2614
+ if (this.advertisementEventTracker) {
2615
+ console.log(`Click tracked for ad: ${advertisement._id}`);
2616
+ }
2617
+ window.open(advertisement.linkUrl, '_blank');
2618
+ });
2619
+ }
2620
+ }
2621
+ return img;
2622
+ }
2048
2623
  }
2049
2624
  /**
2050
- * 커스텀 경로 생성
2625
+ * 디버그 로그 출력
2051
2626
  */
2052
- custom(path) {
2053
- return `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
2627
+ log(message, ...args) {
2628
+ if (this.debug) {
2629
+ console.log(message, ...args);
2630
+ }
2054
2631
  }
2055
- }
2056
- /**
2057
- * 전역 엔드포인트 빌더 인스턴스 (기본: 베타 환경)
2058
- */
2059
- const endpoints = new EndpointBuilder();
2632
+ }
2060
2633
 
2061
2634
  /**
2062
2635
  * AdStage SDK - Ads 모듈
@@ -2069,6 +2642,8 @@ class AdsModule {
2069
2642
  this.slots = new Map();
2070
2643
  // Advertisement 이벤트 추적 관련
2071
2644
  this.advertisementEventTracker = null;
2645
+ // 렌더링 관련
2646
+ this.adRenderer = null;
2072
2647
  }
2073
2648
  /**
2074
2649
  * Ads 모듈 초기화 (동기)
@@ -2077,6 +2652,8 @@ class AdsModule {
2077
2652
  this._config = config;
2078
2653
  // AdvertisementEventTracker 초기화 (환경 자동 감지된 엔드포인트 사용)
2079
2654
  this.advertisementEventTracker = new AdvertisementEventTracker(endpoints.getBaseUrl(), config.apiKey, config.debug || false, this.slots);
2655
+ // AdRenderer 초기화
2656
+ this.adRenderer = new AdRenderer(config.debug || false, this.advertisementEventTracker);
2080
2657
  this._isReady = true;
2081
2658
  if (config.debug) {
2082
2659
  console.log('🎯 Ads module initialized (sync mode)');
@@ -2226,8 +2803,8 @@ class AdsModule {
2226
2803
  }
2227
2804
  // 고유한 슬롯 ID 생성
2228
2805
  const slotId = `adstage-${type}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2229
- // 즉시 placeholder 생성
2230
- this.createAdSlot(container, slotId, type, options);
2806
+ // 즉시 placeholder 생성 (AdRenderer 위임)
2807
+ this.adRenderer?.createPlaceholder(container, slotId, type, options, this._config);
2231
2808
  // 광고 슬롯 정보 저장
2232
2809
  const slot = {
2233
2810
  id: slotId,
@@ -2243,7 +2820,7 @@ class AdsModule {
2243
2820
  advertisement: undefined, // 나중에 로드
2244
2821
  config: { type, ...options },
2245
2822
  load: async () => this.fetchAdData(type, options).then(ads => ads[0] || null),
2246
- render: (ad) => this.renderAdElement(slot, ad),
2823
+ render: (ad) => this.adRenderer?.renderAdElement(slot, ad),
2247
2824
  refresh: async () => this.refreshAdSlot(slot),
2248
2825
  destroy: () => this.destroy(slotId)
2249
2826
  };
@@ -2257,293 +2834,19 @@ class AdsModule {
2257
2834
  }
2258
2835
  return slotId;
2259
2836
  }
2260
- /**
2261
- * 즉시 광고 슬롯 생성 (placeholder)
2262
- */
2263
- createAdSlot(container, slotId, type, options) {
2264
- const adElement = document.createElement('div');
2265
- adElement.id = slotId;
2266
- adElement.className = `adstage-slot adstage-${type.toLowerCase()}`;
2267
- // 확실한 컨테이너 식별을 위한 데이터 속성 추가
2268
- adElement.setAttribute('data-adstage-container', 'true');
2269
- adElement.setAttribute('data-adstage-type', type);
2270
- adElement.setAttribute('data-adstage-slot', slotId);
2271
- // 스마트한 크기 설정
2272
- const { width, height } = this.calculateAdSize(container, type, options);
2273
- adElement.style.width = width;
2274
- adElement.style.height = height;
2275
- adElement.style.border = '1px dashed #ccc';
2276
- adElement.style.display = 'flex';
2277
- adElement.style.alignItems = 'center';
2278
- adElement.style.justifyContent = 'center';
2279
- adElement.style.backgroundColor = '#f9f9f9';
2280
- adElement.style.color = '#666';
2281
- adElement.innerHTML = `<span>Loading ${type} ad...</span>`;
2282
- container.appendChild(adElement);
2283
- if (this._config?.debug) {
2284
- console.log(`📦 Placeholder created for slot: ${slotId} (${width} x ${height})`);
2285
- }
2286
- }
2287
- /**
2288
- * 컨테이너와 광고 타입에 따른 스마트한 크기 계산
2289
- */
2290
- calculateAdSize(container, type, options) {
2291
- // 사용자가 명시적으로 크기를 지정한 경우
2292
- const explicitWidth = options.width;
2293
- const explicitHeight = options.height;
2294
- // 너비 처리
2295
- let width;
2296
- if (typeof explicitWidth === 'number') {
2297
- width = `${explicitWidth}px`;
2298
- }
2299
- else if (typeof explicitWidth === 'string') {
2300
- width = explicitWidth;
2301
- }
2302
- else {
2303
- width = '100%'; // 기본값은 100%
2304
- }
2305
- // 높이 처리 - 핵심 로직
2306
- let height;
2307
- if (typeof explicitHeight === 'number') {
2308
- height = `${explicitHeight}px`;
2309
- }
2310
- else if (typeof explicitHeight === 'string' && explicitHeight !== '100%' && explicitHeight !== 'auto') {
2311
- // 명시적인 크기 문자열 (예: '200px', '50vh' 등)
2312
- height = explicitHeight;
2313
- }
2314
- else {
2315
- // 100%, auto이거나 높이가 지정되지 않은 경우 스마트 계산
2316
- const containerHeight = this.getContainerHeight(container);
2317
- if (containerHeight > 0) {
2318
- // 컨테이너에 높이가 있으면 100% 사용
2319
- height = '100%';
2320
- if (this._config?.debug) {
2321
- console.log(`📏 Using 100% height (container: ${containerHeight}px)`);
2322
- }
2323
- }
2324
- else {
2325
- // 컨테이너에 높이가 없으면 타입별 기본값 사용 (나중에 동적 조정됨)
2326
- height = this.getDefaultHeightForAdType(type);
2327
- if (this._config?.debug) {
2328
- console.log(`📏 Using default height ${height} (will be optimized for ${type})`);
2329
- }
2330
- }
2331
- }
2332
- return { width, height };
2333
- }
2334
- /**
2335
- * 컨테이너의 실제 높이 계산
2336
- */
2337
- getContainerHeight(container) {
2338
- // 현재 계산된 스타일에서 높이 확인
2339
- const computedStyle = window.getComputedStyle(container);
2340
- const height = parseFloat(computedStyle.height);
2341
- // height가 auto이거나 0이면 다른 방법들 시도
2342
- if (!height || height === 0) {
2343
- // min-height 확인
2344
- const minHeight = parseFloat(computedStyle.minHeight);
2345
- if (minHeight > 0)
2346
- return minHeight;
2347
- // CSS로 설정된 고정 높이 확인
2348
- if (container.style.height && container.style.height !== 'auto') {
2349
- const styleHeight = parseFloat(container.style.height);
2350
- if (styleHeight > 0)
2351
- return styleHeight;
2352
- }
2353
- // 속성으로 설정된 높이 확인
2354
- const heightAttr = container.getAttribute('height');
2355
- if (heightAttr) {
2356
- const attrHeight = parseFloat(heightAttr);
2357
- if (attrHeight > 0)
2358
- return attrHeight;
2359
- }
2360
- }
2361
- return height || 0;
2362
- }
2363
- /**
2364
- * 광고 타입별 기본 높이 반환
2365
- */
2366
- getDefaultHeightForAdType(type) {
2367
- switch (type) {
2368
- case AdType.BANNER:
2369
- return '250px'; // 일반 배너
2370
- case AdType.TEXT:
2371
- return '120px'; // 텍스트는 좀 더 작게
2372
- case AdType.VIDEO:
2373
- return '360px'; // 비디오는 16:9 비율 고려
2374
- case AdType.NATIVE:
2375
- return '200px'; // 네이티브는 중간 크기
2376
- case AdType.INTERSTITIAL:
2377
- return '400px'; // 전면광고는 크게
2378
- default:
2379
- return '250px';
2380
- }
2381
- }
2382
- /**
2383
- * 이미지 크기 정보 로드 (프리로딩)
2384
- */
2385
- async loadImageDimensions(imageUrl) {
2386
- return new Promise((resolve, reject) => {
2387
- const img = new Image();
2388
- img.onload = () => {
2389
- resolve({ width: img.naturalWidth, height: img.naturalHeight });
2390
- };
2391
- img.onerror = () => {
2392
- reject(new Error(`Failed to load image: ${imageUrl}`));
2393
- };
2394
- img.src = imageUrl;
2395
- });
2396
- }
2837
+ // createAdSlot 제거: AdRenderer.createPlaceholder 사용
2397
2838
  /**
2398
2839
  * 여러 광고의 최적 컨테이너 크기 계산 (동적 크기 조정)
2399
2840
  */
2400
- async calculateOptimalContainerSize(advertisements, containerWidth, adType) {
2401
- if (!advertisements.length || adType !== AdType.BANNER) {
2402
- // 배너가 아니거나 광고가 없으면 기본값
2403
- return {
2404
- width: '100%',
2405
- height: this.getDefaultHeightForAdType(adType),
2406
- aspectRatio: 16 / 9
2407
- };
2408
- }
2409
- try {
2410
- // 모든 배너 이미지의 크기 정보 로드
2411
- const imageDimensions = await Promise.allSettled(advertisements
2412
- .filter(ad => ad.imageUrl)
2413
- .map(ad => this.loadImageDimensions(ad.imageUrl)));
2414
- const validDimensions = imageDimensions
2415
- .filter((result) => result.status === 'fulfilled')
2416
- .map(result => result.value);
2417
- if (validDimensions.length === 0) {
2418
- // 이미지 로드 실패시 기본값
2419
- return {
2420
- width: '100%',
2421
- height: this.getDefaultHeightForAdType(adType),
2422
- aspectRatio: 16 / 9
2423
- };
2424
- }
2425
- // 최적 전략 선택
2426
- const strategy = this.selectOptimalSizeStrategy(validDimensions);
2427
- const optimalHeight = this.calculateOptimalHeight(validDimensions, containerWidth, strategy);
2428
- if (this._config?.debug) {
2429
- console.log(`📐 Optimal container calculated: ${containerWidth}x${optimalHeight} (strategy: ${strategy})`);
2430
- }
2431
- return {
2432
- width: '100%',
2433
- height: `${optimalHeight}px`,
2434
- aspectRatio: containerWidth / optimalHeight
2435
- };
2436
- }
2437
- catch (error) {
2438
- console.warn('Failed to calculate optimal size, using defaults:', error);
2439
- return {
2440
- width: '100%',
2441
- height: this.getDefaultHeightForAdType(adType),
2442
- aspectRatio: 16 / 9
2443
- };
2444
- }
2445
- }
2446
- /**
2447
- * 최적 크기 조정 전략 선택
2448
- */
2449
- selectOptimalSizeStrategy(dimensions) {
2450
- const aspectRatios = dimensions.map(d => d.width / d.height);
2451
- // 1. 공통 비율이 있는지 확인 (±0.1 허용)
2452
- const ratioGroups = new Map();
2453
- aspectRatios.forEach(ratio => {
2454
- const roundedRatio = Math.round(ratio * 10) / 10;
2455
- const key = roundedRatio.toString();
2456
- ratioGroups.set(key, (ratioGroups.get(key) || 0) + 1);
2457
- });
2458
- const maxGroup = Math.max(...ratioGroups.values());
2459
- const totalImages = dimensions.length;
2460
- // 70% 이상이 비슷한 비율이면 dominant 전략
2461
- if (maxGroup / totalImages >= 0.7) {
2462
- return 'dominant';
2463
- }
2464
- // 표준 비율들이 많으면 common 전략
2465
- const standardRatios = [16 / 9, 4 / 3, 1 / 1, 3 / 2];
2466
- const standardCount = aspectRatios.filter(ratio => standardRatios.some(standard => Math.abs(ratio - standard) < 0.1)).length;
2467
- if (standardCount / totalImages >= 0.5) {
2468
- return 'common';
2469
- }
2470
- // 기본은 평균 전략
2471
- return 'average';
2472
- }
2473
- /**
2474
- * 전략에 따른 최적 높이 계산
2475
- */
2476
- calculateOptimalHeight(dimensions, containerWidth, strategy) {
2477
- const aspectRatios = dimensions.map(d => d.width / d.height);
2478
- switch (strategy) {
2479
- case 'dominant':
2480
- // 가장 많은 비율을 기준으로
2481
- const ratioGroups = new Map();
2482
- aspectRatios.forEach(ratio => {
2483
- const roundedRatio = Math.round(ratio * 10) / 10;
2484
- const key = roundedRatio.toString();
2485
- const existing = ratioGroups.get(key);
2486
- if (existing) {
2487
- existing.count++;
2488
- }
2489
- else {
2490
- ratioGroups.set(key, { ratio: roundedRatio, count: 1 });
2491
- }
2492
- });
2493
- const dominantGroup = Array.from(ratioGroups.values())
2494
- .reduce((max, current) => current.count > max.count ? current : max);
2495
- return Math.round(containerWidth / dominantGroup.ratio);
2496
- case 'common':
2497
- // 표준 비율 중 가장 적합한 것 선택
2498
- const standardRatios = [
2499
- { ratio: 16 / 9, name: '16:9' },
2500
- { ratio: 4 / 3, name: '4:3' },
2501
- { ratio: 1 / 1, name: '1:1' },
2502
- { ratio: 3 / 2, name: '3:2' }
2503
- ];
2504
- const avgRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
2505
- const bestStandard = standardRatios.reduce((best, current) => Math.abs(current.ratio - avgRatio) < Math.abs(best.ratio - avgRatio) ? current : best);
2506
- if (this._config?.debug) {
2507
- console.log(`📊 Using standard ratio: ${bestStandard.name} (avg: ${avgRatio.toFixed(2)})`);
2508
- }
2509
- return Math.round(containerWidth / bestStandard.ratio);
2510
- case 'average':
2511
- default:
2512
- // 평균 비율 사용
2513
- const averageRatio = aspectRatios.reduce((sum, ratio) => sum + ratio, 0) / aspectRatios.length;
2514
- return Math.round(containerWidth / averageRatio);
2515
- }
2516
- }
2517
- /**
2518
- * 개별 이미지에 최적화된 렌더링 스타일 적용
2519
- */
2520
- applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio) {
2521
- const ratio = imageAspectRatio / containerAspectRatio;
2522
- if (Math.abs(ratio - 1) < 0.1) {
2523
- // 비율이 거의 같으면 cover 사용
2524
- img.style.objectFit = 'cover';
2525
- img.style.objectPosition = 'center';
2526
- }
2527
- else if (ratio > 1.3) {
2528
- // 이미지가 훨씬 가로형이면 contain으로 전체 보이기
2529
- img.style.objectFit = 'contain';
2530
- img.style.objectPosition = 'center';
2531
- img.style.backgroundColor = '#f0f0f0'; // 빈 공간 배경색
2532
- }
2533
- else if (ratio < 0.7) {
2534
- // 이미지가 훨씬 세로형이면 cover로 채우기
2535
- img.style.objectFit = 'cover';
2536
- img.style.objectPosition = 'center';
2537
- }
2538
- else {
2539
- // 적당한 차이면 스마트 cover
2540
- img.style.objectFit = 'cover';
2541
- img.style.objectPosition = 'center';
2542
- }
2543
- if (this._config?.debug) {
2544
- console.log(`🎨 Image style applied: objectFit=${img.style.objectFit}, ratio=${ratio.toFixed(2)}`);
2545
- }
2546
- }
2841
+ // calculateOptimalContainerSize 제거: AdRenderer.calculateOptimalContainerSize 사용
2842
+ /**
2843
+ * 최적 크기 조정 전략 선택
2844
+ */
2845
+ // selectOptimalSizeStrategy 제거: AdRenderer 내부 구현 사용
2846
+ /**
2847
+ * 전략에 따른 최적 높이 계산
2848
+ */
2849
+ // calculateOptimalHeight 제거: AdRenderer 내부 구현 사용
2547
2850
  /**
2548
2851
  * 백그라운드에서 광고 콘텐츠 로드
2549
2852
  */
@@ -2552,21 +2855,21 @@ class AdsModule {
2552
2855
  // 광고 데이터 가져오기 - 여러 개 로드
2553
2856
  const adstageData = await this.fetchAdData(slot.adType, slot.config);
2554
2857
  if (!adstageData || adstageData.length === 0) {
2555
- this.renderFallback(slot);
2858
+ this.adRenderer?.renderFallback(slot);
2556
2859
  return;
2557
2860
  }
2558
2861
  // 🆕 동적 크기 조정: 배너 광고의 경우 이미지 크기 기반으로 컨테이너 최적화
2559
2862
  if (slot.adType === AdType.BANNER && adstageData.length > 0) {
2560
- await this.optimizeContainerForBannerAds(slot, adstageData);
2863
+ await this.adRenderer?.optimizeContainerForBannerAds(slot, adstageData);
2561
2864
  }
2562
2865
  // 광고가 여러 개이거나 autoSlide 옵션이 있으면 슬라이더로 렌더링
2563
2866
  if (adstageData.length > 1 || slot.config?.autoSlide) {
2564
- await this.renderAdSlider(slot, adstageData);
2867
+ await this.adRenderer?.renderAdSlider(slot, adstageData);
2565
2868
  }
2566
2869
  else {
2567
2870
  // 광고가 1개면 일반 렌더링
2568
2871
  slot.advertisement = adstageData[0];
2569
- await this.renderAdElement(slot, adstageData[0]);
2872
+ await this.adRenderer?.renderAdElement(slot, adstageData[0]);
2570
2873
  // ✅ 신규: Viewable impression 추적 시작 (기존 즉시 추적 대신)
2571
2874
  this.startBasicViewabilityTracking(slot, adstageData[0]);
2572
2875
  }
@@ -2577,35 +2880,13 @@ class AdsModule {
2577
2880
  }
2578
2881
  catch (error) {
2579
2882
  console.error(`❌ Failed to load ad for slot: ${slot.id}`, error);
2580
- this.renderFallback(slot);
2883
+ this.adRenderer?.renderFallback(slot);
2581
2884
  }
2582
2885
  }
2583
2886
  /**
2584
2887
  * 배너 광고를 위한 컨테이너 최적화
2585
2888
  */
2586
- async optimizeContainerForBannerAds(slot, advertisements) {
2587
- try {
2588
- const container = document.getElementById(slot.containerId);
2589
- const adElement = document.getElementById(slot.id);
2590
- if (!container || !adElement)
2591
- return;
2592
- // 현재 컨테이너 너비 확인
2593
- const containerWidth = container.getBoundingClientRect().width || 300;
2594
- // 최적 크기 계산
2595
- const optimalSize = await this.calculateOptimalContainerSize(advertisements, containerWidth, slot.adType);
2596
- // 컨테이너 크기 동적 조정
2597
- adElement.style.height = optimalSize.height;
2598
- // 슬롯 정보 업데이트
2599
- slot.optimizedHeight = optimalSize.height;
2600
- slot.aspectRatio = optimalSize.aspectRatio;
2601
- if (this._config?.debug) {
2602
- console.log(`🔧 Container optimized for ${advertisements.length} banner ads: ${optimalSize.height}`);
2603
- }
2604
- }
2605
- catch (error) {
2606
- console.warn('Container optimization failed, using default size:', error);
2607
- }
2608
- }
2889
+ // optimizeContainerForBannerAds 제거: AdRenderer.optimizeContainerForBannerAds 사용
2609
2890
  /**
2610
2891
  * 기본 viewability 추적 시작
2611
2892
  */
@@ -2659,109 +2940,11 @@ class AdsModule {
2659
2940
  /**
2660
2941
  * Fallback 광고 렌더링 - AdStage 확실한 컨테이너 우선 탐지
2661
2942
  */
2662
- renderFallback(slot) {
2663
- const element = document.getElementById(slot.id);
2664
- if (element) {
2665
- // 1순위: AdStage가 생성한 확실한 컨테이너들 (데이터 속성 기반)
2666
- const adstageContainers = [
2667
- element.querySelector('[data-adstage-container="true"]'), // 내부 AdStage 컨테이너
2668
- element.closest('[data-adstage-container="true"]'), // 상위 AdStage 컨테이너
2669
- element, // 자기 자신이 AdStage 컨테이너인 경우
2670
- ].filter(el => el && el.hasAttribute('data-adstage-container'));
2671
- // 2순위: AdStage 클래스 기반 컨테이너들
2672
- const classBasedContainers = [
2673
- element.closest('.adstage-slot'),
2674
- element.closest('.adstage-banner'),
2675
- element.closest('.adstage-text'),
2676
- element.closest('.adstage-video'),
2677
- element.closest('.adstage-native'),
2678
- element.closest('.adstage-interstitial'),
2679
- ].filter(Boolean);
2680
- // 3순위: 일반적인 광고 컨테이너 패턴들 (fallback)
2681
- const generalContainers = [
2682
- element.closest('[class*="ad"]'),
2683
- element.closest('[class*="banner"]'),
2684
- element.closest('[class*="container"]'),
2685
- element.closest('div[style*="height"]'),
2686
- element.closest('div[style*="min-height"]'),
2687
- element.parentElement
2688
- ].filter(Boolean);
2689
- // 우선순위에 따라 컨테이너 선택
2690
- const possibleContainers = [
2691
- ...adstageContainers,
2692
- ...classBasedContainers,
2693
- ...generalContainers
2694
- ];
2695
- // 가장 적절한 컨테이너 선택
2696
- const targetContainer = possibleContainers[0];
2697
- if (targetContainer) {
2698
- // 컨테이너 타입 로깅
2699
- let containerType = 'unknown';
2700
- if (targetContainer.hasAttribute('data-adstage-container')) {
2701
- containerType = 'adstage-official';
2702
- }
2703
- else if (targetContainer.classList.contains('adstage-slot')) {
2704
- containerType = 'adstage-class';
2705
- }
2706
- else {
2707
- containerType = 'generic';
2708
- }
2709
- targetContainer.style.cssText += `
2710
- height: 0px !important;
2711
- min-height: 0px !important;
2712
- padding: 0px !important;
2713
- margin: 0px !important;
2714
- border: none !important;
2715
- overflow: hidden !important;
2716
- display: block !important;
2717
- `;
2718
- // 내부 모든 요소 제거
2719
- targetContainer.innerHTML = '';
2720
- // 빈 상태임을 표시하는 속성 추가
2721
- targetContainer.setAttribute('data-adstage-empty', 'true');
2722
- if (this._config?.debug) {
2723
- console.warn(`⚠️ Ad container collapsed (${containerType}): ${slot.id}`, targetContainer);
2724
- }
2725
- }
2726
- else {
2727
- // 컨테이너를 찾지 못한 경우 새로운 빈 컨테이너 생성
2728
- this.createEmptyContainer(slot);
2729
- }
2730
- }
2731
- // 슬롯 상태 업데이트 (제거하지 않고 빈 상태로 마킹)
2732
- slot.advertisement = undefined;
2733
- slot.isEmpty = true;
2734
- }
2943
+ // renderFallback 제거: AdRenderer.renderFallback 사용
2735
2944
  /**
2736
2945
  * 빈 컨테이너 생성 (컨테이너를 찾지 못한 경우)
2737
2946
  */
2738
- createEmptyContainer(slot) {
2739
- const originalContainer = document.getElementById(slot.containerId);
2740
- if (originalContainer) {
2741
- // 기존 내용 제거
2742
- originalContainer.innerHTML = '';
2743
- // 빈 AdStage 컨테이너 생성
2744
- const emptyElement = document.createElement('div');
2745
- emptyElement.id = slot.id;
2746
- emptyElement.className = 'adstage-slot adstage-empty';
2747
- emptyElement.setAttribute('data-adstage-container', 'true');
2748
- emptyElement.setAttribute('data-adstage-empty', 'true');
2749
- emptyElement.setAttribute('data-adstage-slot', slot.id);
2750
- emptyElement.style.cssText = `
2751
- height: 0px !important;
2752
- min-height: 0px !important;
2753
- padding: 0px !important;
2754
- margin: 0px !important;
2755
- border: none !important;
2756
- overflow: hidden !important;
2757
- display: block !important;
2758
- `;
2759
- originalContainer.appendChild(emptyElement);
2760
- if (this._config?.debug) {
2761
- console.warn(`⚠️ Created empty AdStage container: ${slot.id}`);
2762
- }
2763
- }
2764
- }
2947
+ // createEmptyContainer 제거: AdRenderer 내부 구현 사용
2765
2948
  /**
2766
2949
  * 광고 데이터 가져오기
2767
2950
  */
@@ -2804,228 +2987,15 @@ class AdsModule {
2804
2987
  /**
2805
2988
  * 광고 슬라이더 렌더링 (여러 광고 또는 autoSlide 옵션)
2806
2989
  */
2807
- async renderAdSlider(slot, advertisements) {
2808
- const container = document.getElementById(slot.containerId);
2809
- if (!container) {
2810
- throw new Error(`Container not found: ${slot.containerId}`);
2811
- }
2812
- // 이벤트 추적 콜백 함수 (중복 노출 방지 포함)
2813
- const trackEventCallback = async (adId, slotId, eventType) => {
2814
- // 노출 이벤트인 경우 중복 확인
2815
- if (eventType === AdEventType.VIEWABLE) {
2816
- if (ViewableEventTracker.isDuplicateViewable(adId, slotId, this._config?.debug)) {
2817
- if (this._config?.debug) {
2818
- console.log(`🚫 Duplicate viewable blocked for ad ${adId} in slot ${slotId}`);
2819
- }
2820
- return; // 중복 노출이면 추적하지 않음
2821
- }
2822
- if (this._config?.debug) {
2823
- console.log(`✅ New viewable recorded for ad ${adId} in slot ${slotId}`);
2824
- }
2825
- }
2826
- // 실제 API 호출로 이벤트 전송
2827
- if (this.advertisementEventTracker) {
2828
- try {
2829
- await this.advertisementEventTracker.trackAdvertisementEvent(adId, slotId, eventType, {} // 기본 메타데이터
2830
- );
2831
- if (this._config?.debug) {
2832
- console.log(`📊 Advertisement event tracked: ${eventType} for ad ${adId} in slot ${slotId}`);
2833
- }
2834
- }
2835
- catch (error) {
2836
- if (this._config?.debug) {
2837
- console.error(`❌ Failed to track ${eventType} event for ad ${adId}:`, error);
2838
- }
2839
- }
2840
- }
2841
- // 🆕 슬라이더에서 VIEWABLE 이벤트 발생 시 해당 광고로 ViewabilityTracker 교체
2842
- if (eventType === AdEventType.VIEWABLE && advertisements.length > 1) {
2843
- const currentAd = advertisements.find(ad => ad._id === adId);
2844
- if (currentAd) {
2845
- // 기존 ViewabilityTracker 정리
2846
- if (slot.viewabilityTracker) {
2847
- slot.viewabilityTracker.destroy();
2848
- slot.viewabilityTracker = null;
2849
- }
2850
- // 현재 광고에 대해 새로운 ViewabilityTracker 시작
2851
- this.startBasicViewabilityTracking(slot, currentAd);
2852
- if (this._config?.debug) {
2853
- console.log(`🔄 ViewabilityTracker switched to ad ${adId} in slider: ${slot.id}`);
2854
- }
2855
- }
2856
- }
2857
- };
2858
- let sliderElement;
2859
- // 최적화된 슬라이더 옵션 준비
2860
- const optimizedSliderOptions = {
2861
- autoSlideInterval: (slot.config?.slideInterval || 5000) / 1000,
2862
- ...slot.config,
2863
- // 🆕 동적 크기 정보 전달
2864
- optimizedHeight: slot.optimizedHeight,
2865
- aspectRatio: slot.aspectRatio
2866
- };
2867
- // 텍스트 광고는 TextTransitionManager 사용, 그 외는 CarouselSliderManager 사용
2868
- if (slot.adType === AdType.TEXT) {
2869
- sliderElement = TextTransitionManager.createTextTransitionContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
2870
- if (this._config?.debug) {
2871
- console.log(`✨ Text transition created for TEXT slot: ${slot.id} with ${advertisements.length} ads`);
2872
- }
2873
- }
2874
- else {
2875
- sliderElement = CarouselSliderManager.createSliderContainer(slot, advertisements, optimizedSliderOptions, trackEventCallback);
2876
- if (this._config?.debug) {
2877
- console.log(`🎠 Carousel slider created for ${slot.adType} slot: ${slot.id} with ${advertisements.length} ads (optimized: ${slot.optimizedHeight || 'default'})`);
2878
- }
2879
- }
2880
- // 기존 내용 제거하고 슬라이더 추가
2881
- container.innerHTML = '';
2882
- container.appendChild(sliderElement);
2883
- // ✅ 신규: 슬라이더에서도 첫 번째 광고에 대해 ViewabilityTracker 시작
2884
- if (advertisements.length > 0) {
2885
- this.startBasicViewabilityTracking(slot, advertisements[0]);
2886
- if (this._config?.debug) {
2887
- console.log(`🎯 Viewability tracking started for first ad in slider: ${slot.id}`);
2888
- }
2889
- }
2890
- }
2990
+ // renderAdSlider 제거: AdRenderer.renderAdSlider 사용
2891
2991
  /**
2892
2992
  * 광고 렌더링 (단일 광고용)
2893
2993
  */
2894
- async renderAd(slot) {
2895
- if (!slot.advertisement) {
2896
- throw new Error('No advertisement to render');
2897
- }
2898
- await this.renderAdElement(slot, slot.advertisement);
2899
- slot.isLoaded = true;
2900
- }
2994
+ // renderAd 제거: AdRenderer.renderAd 사용
2901
2995
  /**
2902
2996
  * 광고 요소 렌더링 (기본 구현)
2903
2997
  */
2904
- async renderAdElement(slot, ad) {
2905
- const container = document.getElementById(slot.containerId);
2906
- if (!container)
2907
- return;
2908
- // 기본 HTML 구조 생성
2909
- const adElement = document.createElement('div');
2910
- adElement.className = 'adstage-ad';
2911
- // 스마트한 크기 설정 - 최적화된 크기가 있으면 사용
2912
- const optimizedHeight = slot.optimizedHeight;
2913
- const containerElement = container.parentElement || container;
2914
- if (optimizedHeight) {
2915
- adElement.style.width = '100%';
2916
- adElement.style.height = optimizedHeight;
2917
- }
2918
- else {
2919
- const { width, height } = this.calculateAdSize(containerElement, slot.adType, slot.config || {});
2920
- adElement.style.width = width;
2921
- adElement.style.height = height;
2922
- }
2923
- // 광고 타입별 렌더링
2924
- switch (slot.adType) {
2925
- case AdType.BANNER:
2926
- if (ad.imageUrl) {
2927
- await this.renderOptimizedBannerImage(adElement, ad, slot);
2928
- }
2929
- break;
2930
- case AdType.TEXT:
2931
- const textDiv = document.createElement('div');
2932
- textDiv.innerHTML = `
2933
- <h3>${ad.title}</h3>
2934
- ${ad.description ? `<p>${ad.description}</p>` : ''}
2935
- ${ad.textContent ? `<div>${ad.textContent}</div>` : ''}
2936
- `;
2937
- adElement.appendChild(textDiv);
2938
- break;
2939
- case AdType.VIDEO:
2940
- if (ad.videoUrl) {
2941
- const video = document.createElement('video');
2942
- video.src = ad.videoUrl;
2943
- video.controls = true;
2944
- video.style.width = '100%';
2945
- video.style.height = '100%';
2946
- adElement.appendChild(video);
2947
- }
2948
- break;
2949
- default:
2950
- adElement.innerHTML = `<div>${ad.title}</div>`;
2951
- }
2952
- // 클릭 이벤트 추가
2953
- if (ad.linkUrl) {
2954
- adElement.style.cursor = 'pointer';
2955
- adElement.addEventListener('click', () => {
2956
- window.open(ad.linkUrl, '_blank');
2957
- });
2958
- }
2959
- container.innerHTML = '';
2960
- container.appendChild(adElement);
2961
- }
2962
- /**
2963
- * 최적화된 배너 이미지 렌더링
2964
- */
2965
- async renderOptimizedBannerImage(adElement, ad, slot) {
2966
- try {
2967
- // 사용자가 크기를 지정했는지 확인
2968
- const configWidth = slot.config?.width;
2969
- const configHeight = slot.config?.height;
2970
- const hasUserDefinedWidth = configWidth &&
2971
- (typeof configWidth === 'number' || (typeof configWidth === 'string' && configWidth !== '100%'));
2972
- const hasUserDefinedHeight = configHeight &&
2973
- (typeof configHeight === 'number' || (typeof configHeight === 'string' && configHeight !== 'auto'));
2974
- const hasUserDefinedSize = hasUserDefinedWidth || hasUserDefinedHeight;
2975
- // 이미지 요소 생성
2976
- const img = document.createElement('img');
2977
- img.src = ad.imageUrl;
2978
- img.alt = ad.title;
2979
- if (hasUserDefinedSize) {
2980
- // 🎯 사용자가 크기를 지정한 경우: 컨테이너에 꽉 차도록 설정
2981
- img.style.width = '100%';
2982
- img.style.height = '100%';
2983
- img.style.objectFit = 'cover'; // 컨테이너에 꽉 찬 상태로 비율 유지
2984
- img.style.objectPosition = 'center';
2985
- if (this._config?.debug) {
2986
- console.log(`🎯 User-defined size detected: filling container completely`);
2987
- }
2988
- }
2989
- else {
2990
- // 사용자가 크기를 지정하지 않은 경우: 동적 최적화 적용
2991
- const imageDimensions = await this.loadImageDimensions(ad.imageUrl);
2992
- const imageAspectRatio = imageDimensions.width / imageDimensions.height;
2993
- const containerAspectRatio = slot.aspectRatio || 16 / 9;
2994
- img.style.width = '100%';
2995
- img.style.height = '100%';
2996
- // 🎨 최적화된 스타일 적용
2997
- this.applyOptimizedImageStyle(img, imageAspectRatio, containerAspectRatio);
2998
- if (this._config?.debug) {
2999
- console.log(`🖼️ Optimized banner image loaded: ${imageDimensions.width}x${imageDimensions.height} (ratio: ${imageAspectRatio.toFixed(2)})`);
3000
- }
3001
- }
3002
- // 이미지 로드 완료 처리
3003
- img.onload = () => {
3004
- if (this._config?.debug) {
3005
- console.log(`✅ Banner image loaded successfully`);
3006
- }
3007
- };
3008
- // 에러 처리
3009
- img.onerror = () => {
3010
- console.warn(`Failed to load banner image: ${ad.imageUrl}`);
3011
- // 폴백 텍스트 표시
3012
- adElement.innerHTML = `<div style="display: flex; align-items: center; justify-content: center; background: #f0f0f0; color: #666;">${ad.title}</div>`;
3013
- };
3014
- adElement.appendChild(img);
3015
- }
3016
- catch (error) {
3017
- console.warn('Failed to optimize banner image, using fallback:', error);
3018
- // 기본 이미지 렌더링 (폴백)
3019
- const img = document.createElement('img');
3020
- img.src = ad.imageUrl;
3021
- img.alt = ad.title;
3022
- img.style.width = '100%';
3023
- img.style.height = '100%';
3024
- img.style.objectFit = 'cover';
3025
- img.style.objectPosition = 'center'; // 🎯 폴백 이미지도 중앙 정렬
3026
- adElement.appendChild(img);
3027
- }
3028
- }
2998
+ // renderAdElement 제거: AdRenderer.renderAdElement 사용
3029
2999
  /**
3030
3000
  * 광고 슬롯 새로고침
3031
3001
  */
@@ -3035,7 +3005,7 @@ class AdsModule {
3035
3005
  const newAdData = await this.fetchAdData(slot.adType, slot.config || {});
3036
3006
  if (newAdData && newAdData.length > 0) {
3037
3007
  slot.advertisement = newAdData[0]; // 첫 번째 광고로 업데이트
3038
- await this.renderAd(slot);
3008
+ await this.adRenderer?.renderAd(slot);
3039
3009
  // 새로운 노출 추적
3040
3010
  if (this.advertisementEventTracker) {
3041
3011
  console.log('New advertisement viewable tracked for slot:', slot.id);
@@ -3282,13 +3252,6 @@ class AdStage {
3282
3252
  productionMode: false,
3283
3253
  ...config
3284
3254
  };
3285
- // baseUrl이 설정되었으면 endpoints에 적용
3286
- if (config.baseUrl) {
3287
- endpoints.setBaseUrl(config.baseUrl);
3288
- if (config.debug) {
3289
- console.log('🔄 API base URL set to:', config.baseUrl);
3290
- }
3291
- }
3292
3255
  // 모듈 동기 초기화
3293
3256
  const enabledModules = instance._config.modules || ['ads', 'events', 'config'];
3294
3257
  for (const moduleName of enabledModules) {
@@ -3351,82 +3314,6 @@ class AdStage {
3351
3314
  }
3352
3315
  }
3353
3316
 
3354
- const AdStageContext = createContext(null);
3355
- function AdStageProvider({ children, config }) {
3356
- const [isInitialized, setIsInitialized] = useState(false);
3357
- const [currentConfig, setCurrentConfig] = useState(null);
3358
- const [error, setError] = useState(null);
3359
- const initialize = (newConfig) => {
3360
- try {
3361
- setError(null);
3362
- // 기존 인스턴스가 있으면 리셋
3363
- if (isInitialized) {
3364
- AdStage.reset();
3365
- }
3366
- AdStage.init(newConfig);
3367
- setCurrentConfig(newConfig);
3368
- setIsInitialized(true);
3369
- if (newConfig.debug) {
3370
- console.log('✅ AdStage SDK initialized successfully via React Provider');
3371
- }
3372
- }
3373
- catch (err) {
3374
- const errorMessage = err instanceof Error ? err.message : 'Unknown error';
3375
- setError(errorMessage);
3376
- console.error('❌ AdStage SDK initialization failed:', err);
3377
- setIsInitialized(false);
3378
- setCurrentConfig(null);
3379
- }
3380
- };
3381
- const reset = () => {
3382
- try {
3383
- AdStage.reset();
3384
- setIsInitialized(false);
3385
- setCurrentConfig(null);
3386
- setError(null);
3387
- }
3388
- catch (err) {
3389
- console.error('❌ AdStage SDK reset failed:', err);
3390
- }
3391
- };
3392
- // 자동 초기화
3393
- useEffect(() => {
3394
- if (config && !isInitialized) {
3395
- initialize(config);
3396
- }
3397
- }, [config, isInitialized]);
3398
- const contextValue = {
3399
- isInitialized,
3400
- config: currentConfig,
3401
- initialize,
3402
- reset,
3403
- error
3404
- };
3405
- return (jsx(AdStageContext.Provider, { value: contextValue, children: children }));
3406
- }
3407
- /**
3408
- * AdStage Context Hook
3409
- * AdStageProvider 내에서 SDK 상태에 접근할 수 있습니다.
3410
- */
3411
- function useAdStage() {
3412
- const context = useContext(AdStageContext);
3413
- if (!context) {
3414
- throw new Error('useAdStage must be used within an AdStageProvider');
3415
- }
3416
- return context;
3417
- }
3418
- /**
3419
- * AdStage SDK Hook
3420
- * 초기화된 AdStage 인스턴스에 직접 접근할 수 있습니다.
3421
- */
3422
- function useAdStageSDK() {
3423
- const { isInitialized } = useAdStage();
3424
- if (!isInitialized) {
3425
- throw new Error('AdStage SDK is not initialized. Please call initialize() first or provide config to AdStageProvider.');
3426
- }
3427
- return AdStage;
3428
- }
3429
-
3430
3317
  /**
3431
3318
  * AdStage Web SDK
3432
3319
  * 네임스페이스 아키텍처 기반 SDK
@@ -3436,4 +3323,4 @@ function useAdStageSDK() {
3436
3323
  const SDK_VERSION = '2.0.0';
3437
3324
  const SUPPORTED_MODULES = ['ads', 'events', 'config'];
3438
3325
 
3439
- export { AdStage, AdStageProvider, SDK_VERSION, SUPPORTED_MODULES, useAdStage, useAdStageSDK };
3326
+ export { AdStage, SDK_VERSION, SUPPORTED_MODULES };