@adstage/web-sdk
Version:
AdStage Web SDK - Production-ready marketing platform SDK with React Provider support for seamless integration
634 lines (617 loc) • 15.5 kB
TypeScript
import * as react_jsx_runtime from 'react/jsx-runtime';
import { ReactNode } from 'react';
/**
* AdStage SDK 모듈 타입
*/
type ModuleName = 'ads' | 'events' | 'config';
/**
* AdStage SDK 초기화 설정
*/
interface AdStageConfig {
/** API 키 (조직 정보 자동 추출) */
apiKey: string;
/** 디버그 모드 활성화 */
debug?: boolean;
/** API 기본 URL (선택사항, 기본값: 환경 자동 감지) */
baseUrl?: string;
/** 로드할 모듈 선택 (기본값: 모든 모듈) */
modules?: ModuleName[];
/** 요청 타임아웃 (ms) */
timeout?: number;
/** 플레이스홀더 스타일 모드 (기본값: 'subtle') */
placeholderMode?: 'invisible' | 'transparent' | 'subtle' | 'minimal' | 'debug' | 'legacy';
}
/**
* 모듈 기본 인터페이스
*/
interface BaseModule {
/** 모듈 초기화 (동기) */
init(config: AdStageConfig): void;
/** 모듈 준비 상태 확인 */
isReady(): boolean;
/** 모듈 설정 반환 */
getConfig(): any;
}
/**
* API 응답 기본 타입
*/
interface ApiResponse<T = any> {
success: boolean;
data?: T;
error?: string;
message?: string;
}
/**
* 조직 정보
*/
interface OrganizationInfo {
id: string;
name: string;
slug: string;
settings: Record<string, any>;
}
declare enum AdType {
BANNER = "BANNER",
POPUP = "POPUP",
INTERSTITIAL = "INTERSTITIAL",
NATIVE = "NATIVE",
VIDEO = "VIDEO",
TEXT = "TEXT"
}
declare enum Platform {
WEB = "WEB",
MOBILE = "MOBILE"
}
declare enum AdEventType {
VIEWABLE = "VIEWABLE",
CLICK = "CLICK"
}
declare enum DeviceType {
DESKTOP = "DESKTOP",
MOBILE = "MOBILE",
TABLET = "TABLET"
}
interface Advertisement {
_id: string;
title: string;
description?: string;
adType: AdType;
orgId: string;
textContent?: string;
imageUrl?: string;
videoUrl?: string;
linkUrl: string;
startDate: Date | string;
endDate: Date | string;
status: 'ACTIVE' | 'INACTIVE' | 'PENDING';
order: number;
language: string;
countries: string[];
deviceType: DeviceType;
createdAt: Date | string;
updatedAt: Date | string;
}
interface AdSlotConfig {
type: AdType;
placement?: string;
width?: number;
height?: number;
autoRefresh?: number;
fallback?: string;
targeting?: Record<string, any>;
lazyLoad?: boolean;
responsive?: boolean;
className?: string;
style?: Partial<CSSStyleDeclaration>;
}
/**
* 가시성 메트릭스
*/
interface ViewabilityMetrics {
isViewable: boolean;
visibilityRatio: number;
duration: number;
viewables: number;
attentionTime: number;
scrollDepth: number;
completionRate: number;
firstView: number;
timestamps: {
firstView: number;
lastView: number;
totalViewTime: number;
};
}
interface DeviceInfo {
deviceId: string;
platform: Platform;
osVersion?: string;
deviceModel?: string;
appVersion?: string;
sdkVersion: string;
viewport: {
width: number;
height: number;
};
screen: {
width: number;
height: number;
};
userAgent: string;
language: string;
timezone: string;
connectionType?: string;
}
interface AdEvent {
id: string;
type: AdEventType;
adId: string;
slotId: string;
timestamp: number;
deviceInfo: DeviceInfo;
contextInfo: {
pageUrl: string;
pageTitle: string;
referrer: string;
sessionId: string;
userId?: string;
};
adInfo: {
type: AdType;
placement: string;
creative: string;
campaign?: string;
targeting?: Record<string, any>;
};
viewabilityMetrics?: ViewabilityMetrics;
performanceMetrics?: {
pageLoadTime?: number;
adLoadTime?: number;
renderTime?: number;
};
abTestVariant?: string;
metadata?: Record<string, any>;
}
interface AdSlot {
id: string;
containerId: string;
adType: AdType;
width: number | string;
height: number | string;
isLoaded: boolean;
isVisible: boolean;
refreshRate: number;
lazyLoad: boolean;
targeting: Record<string, any>;
element?: HTMLElement;
config?: AdSlotConfig;
advertisement?: Advertisement;
isViewable?: boolean;
viewableSent?: boolean;
loadTime?: number;
renderTime?: number;
events?: AdEvent[];
load(): Promise<Advertisement | null>;
render(ad: Advertisement): void;
refresh(): Promise<void>;
destroy(): void;
}
/**
* AdStage SDK - Ads 모듈
* 광고 관리 및 렌더링 기능
*/
interface AdOptions {
width?: string | number;
height?: number;
autoSlide?: boolean;
slideInterval?: number;
maxLines?: number;
style?: string;
autoplay?: boolean;
muted?: boolean;
loop?: boolean;
playsinline?: boolean;
controls?: boolean;
hideControls?: boolean;
customControls?: {
hidePlayButton?: boolean;
hideProgressBar?: boolean;
hideCurrentTime?: boolean;
hideRemainingTime?: boolean;
hideVolumeSlider?: boolean;
hideMuteButton?: boolean;
hideFullscreenButton?: boolean;
};
onClick?: (adData: any) => void;
adId?: string;
language?: 'ko' | 'en' | 'ja' | 'zh';
deviceType?: 'MOBILE' | 'DESKTOP';
country?: 'KR' | 'US' | 'JP' | 'CN' | 'DE';
}
declare class AdsModule implements BaseModule {
private _isReady;
private _config;
private slots;
private advertisementEventTracker;
private adRenderer;
private mutationObserver;
/**
* Ads 모듈 초기화 (동기)
*/
init(config: AdStageConfig): void;
/**
* 모듈 준비 상태 확인
*/
isReady(): boolean;
/**
* 모듈 설정 반환
*/
getConfig(): AdStageConfig | null;
/**
* 배너 광고 생성 (동기)
*/
banner(containerId: string | HTMLElement, options?: AdOptions): string;
/**
* 텍스트 광고 생성 (동기)
*/
text(containerId: string | HTMLElement, options?: AdOptions): string;
/**
* 비디오 광고 생성 (동기) - 단일 비디오만 지원
*/
video(containerId: string | HTMLElement, options?: AdOptions): string;
/**
* 네이티브 광고 생성 (동기)
*/
native(containerId: string, options?: AdOptions): string;
/**
* 전면 광고 생성 (동기)
*/
interstitial(containerId: string, options?: AdOptions): string;
/**
* 광고 새로고침
*/
refresh(slotId: string): void;
/**
* 광고 제거
*/
destroy(slotId: string): void;
/**
* 모든 광고 슬롯 반환
*/
getAllSlots(): AdSlot[];
/**
* 특정 광고 슬롯 반환
*/
getSlotById(slotId: string): AdSlot | null;
/**
* 광고 생성 내부 메소드 (동기 + Lazy 로딩)
*/
private createAd;
private createAdWithRetry;
private createAdInternal;
/**
* 백그라운드에서 광고 콘텐츠 로드
*/
private loadAdContentInBackground;
/**
* 배너 광고를 위한 컨테이너 최적화
*/
/**
* 단순한 노출 추적 시작 (재시도 로직 포함)
*/
private startSimpleViewabilityTracking;
/**
* Viewable 이벤트 처리 (단순화됨)
*/
private handleViewableEvent;
/**
* 광고 데이터 가져오기
*/
private fetchAdData;
/**
* 광고 슬롯 새로고침
*/
private refreshAdSlot;
/**
* 모듈 준비 상태 확인
*/
private ensureReady;
/**
* DOM 변화 감지를 통한 자동 정리 설정
*/
private setupAutoCleanup;
/**
* 제거된 요소에서 광고 슬롯 정리
*/
private handleRemovedElement;
/**
* 자동 정리 (로그 없이 조용히 정리)
*/
private autoDestroy;
/**
* 모듈 종료 시 정리
*/
destroyModule(): void;
}
/**
* AdStage SDK - Config 모듈
* 설정 관리 및 API 키 검증
*/
declare class ConfigModule implements BaseModule {
private _isReady;
private _config;
private _organizationInfo;
/**
* Config 모듈 초기화 (동기)
*/
init(config: AdStageConfig): void;
/**
* 모듈 준비 상태 확인
*/
isReady(): boolean;
/**
* 현재 설정 반환
*/
getConfig(): AdStageConfig | null;
/**
* 조직 정보 반환
*/
getOrganizationInfo(): OrganizationInfo | null;
/**
* API 엔드포인트 반환
*/
getApiEndpoint(): string;
/**
* 디버그 모드 여부 확인
*/
isDebugMode(): boolean;
/**
* 활성화된 모듈 목록 반환
*/
getEnabledModules(): string[];
/**
* 특정 모듈이 활성화되어 있는지 확인
*/
isModuleEnabled(moduleName: string): boolean;
/**
* 설정 업데이트 (런타임)
*/
updateConfig(updates: Partial<AdStageConfig>): void;
/**
* API 헤더 생성 (공통 유틸리티 사용)
*/
getApiHeaders(): Record<string, string>;
}
/**
* 사용자 속성 타입
* API의 UserAttributesInput과 동일한 구조
*/
interface UserProperties {
/** 성별 */
gender?: 'male' | 'female' | 'other' | 'unknown';
/** 국가 코드 (ISO 3166-1 alpha-2) */
country?: string;
/** 도시명 */
city?: string;
/** 나이 (문자열) */
age?: string;
/** 언어 코드 (ISO 639-1) */
language?: string;
}
/**
* 이벤트 속성 타입
*/
interface EventProperties {
/** 이벤트 매개변수 */
[key: string]: any;
}
/**
* AdStage SDK - Events 모듈
* 이벤트 추적 시스템
*/
declare class EventsModule implements BaseModule {
private _isReady;
private _config;
/**
* Events 모듈 초기화 (동기)
*/
init(config: AdStageConfig): void;
/**
* 모듈 준비 상태 확인
*/
isReady(): boolean;
/**
* 모듈 설정 반환
*/
getConfig(): AdStageConfig | null;
/**
* 사용자 ID 설정
*/
setUserId(userId: string): void;
/**
* 현재 사용자 ID 반환
*/
getUserId(): string | undefined;
/**
* 사용자 속성 설정
*/
setUserProperties(properties: UserProperties): void;
/**
* 현재 사용자 속성 반환
*/
getUserProperties(): any;
/**
* 디바이스 정보 설정
*/
setDeviceInfo(deviceInfo: Partial<{
category: 'mobile' | 'desktop' | 'tablet' | 'other';
platform: string;
model: string;
appVersion: string;
osVersion: string;
}>): void;
/**
* 개별 디바이스 속성 설정
*/
setDeviceProperty(key: 'category' | 'platform' | 'model' | 'appVersion' | 'osVersion', value: string): void;
/**
* 사용자 제공 디바이스 정보 초기화
*/
clearDeviceInfo(): void;
/**
* 현재 사용자가 설정한 디바이스 정보 반환
*/
getUserDeviceInfo(): any;
/**
* 현재 디바이스 정보 반환
*/
getDeviceInfo(): any;
/**
* 현재 사용자 정보 반환
*/
getUserInfo(): any;
/**
* 현재 사용자 속성 반환 (별칭)
*/
getCurrentUserProperties(): any;
/**
* 이벤트 추적
* @param eventName 이벤트 이름
* @param properties 이벤트 속성
*/
track(eventName: string, properties?: EventProperties): Promise<void>;
/**
* 서버에 이벤트 전송
*/
private sendEventToServer;
}
/**
* AdStage SDK - 메인 네임스페이스 클래스
* v2.0.0 - 확장 가능한 모듈 아키텍처
*/
declare class AdStage {
private static instance;
private _isInitialized;
private _config;
readonly ads: AdsModule;
readonly config: ConfigModule;
readonly events: EventsModule;
private constructor();
/**
* AdStage SDK 초기화 (동기)
*/
static init(config: AdStageConfig): void;
/**
* SDK 초기화 상태 확인
*/
static isReady(): boolean;
/**
* 현재 설정 반환
*/
static getConfig(): AdStageConfig | null;
/**
* SDK 인스턴스 반환 (공개 메소드로 변경)
*/
static getInstance(): AdStage;
/**
* 편의성을 위한 정적 모듈 접근자들 (안전장치 포함)
*/
static get ads(): AdsModule;
static get events(): EventsModule;
static get config(): ConfigModule;
/**
* SDK 리셋 (테스트용)
*/
static reset(): void;
/**
* 디버그용 메서드들
*/
static debug: {
/**
* 모든 viewable 추적 데이터 초기화
*/
clearAllViewable: () => void;
/**
* 특정 광고의 viewable 추적 초기화
*/
clearAdViewable: (adId: string, slotId: string) => void;
/**
* 현재 추적 중인 viewable 상태 확인
*/
getViewableStatus: () => void;
};
}
/**
* 이벤트 추적 (메인 함수)
* @param eventName 이벤트 이름
* @param properties 이벤트 속성
*
* @example
* track('purchase', {
* transaction_id: 'T123',
* value: 99.99,
* currency: 'USD'
* });
*/
declare function track(eventName: string, properties?: EventProperties): Promise<void>;
/**
* 사용자 ID 설정
* @param userId 사용자 ID
*
* @example
* setUserId('user123');
*/
declare function setUserId(userId: string): void;
/**
* 현재 사용자 ID 반환
*/
declare function getUserId(): string | undefined;
/**
* 사용자 속성 설정
* @param properties 사용자 속성 객체
*
* @example
* setUserProperties({
* gender: 'male',
* country: 'KR',
* age: '25'
* });
*/
declare function setUserProperties(properties: UserProperties): void;
/**
* 현재 사용자 속성 반환
*/
declare function getUserProperties(): any;
interface AdStageContextType {
isInitialized: boolean;
config: AdStageConfig | null;
initialize: (config: AdStageConfig) => void;
reset: () => void;
error: string | null;
}
interface AdStageProviderProps {
children: ReactNode;
/**
* 자동 초기화를 위한 설정 (선택사항)
* 제공되면 Provider 마운트 시 자동으로 초기화됩니다.
*/
config?: AdStageConfig;
}
declare function AdStageProvider({ children, config }: AdStageProviderProps): react_jsx_runtime.JSX.Element;
/**
* AdStage Context Hook
* AdStageProvider 내에서 SDK 상태에 접근할 수 있습니다.
*/
declare function useAdStageContext(): AdStageContextType;
/**
* AdStage Instance Hook
* 초기화된 AdStage 인스턴스에 직접 접근할 수 있습니다.
*/
declare function useAdStageInstance(): typeof AdStage | null;
/**
* AdStage Web SDK
* 네임스페이스 아키텍처 기반 SDK
*/
declare const SDK_VERSION = "2.0.0";
declare const SUPPORTED_MODULES: readonly ["ads", "events", "config"];
export { AdEventType, AdOptions, AdSlot, AdStage, AdStageConfig, AdStageProvider, AdType, Advertisement, ApiResponse, BaseModule, EventProperties, ModuleName, OrganizationInfo, SDK_VERSION, SUPPORTED_MODULES, UserProperties, getUserId, getUserProperties, setUserId, setUserProperties, track, useAdStageContext, useAdStageInstance };