UNPKG

@openrtb/macro-replacer

Version:

TypeScript macro replacer library compliant with OpenRTB 2.6/3.0

2 lines (1 loc) 1.9 kB
var a=class{macroMap;context;version="both";constructor(e={},o="both"){this.context=e,this.version=o,this.macroMap=this.initializeMacroMap()}initializeMacroMap(){let e=new Map,o=t=>t?.toString()??"",n={"${OPENRTB_ID}":t=>o(t.id),"${OPENRTB_BID_ID}":t=>o(t.bidId),"${OPENRTB_ITEM_ID}":t=>o(t.itemId),"${OPENRTB_SEAT_ID}":t=>o(t.seatId),"${OPENRTB_PRICE}":t=>o(t.price),"${OPENRTB_CURRENCY}":t=>o(t.currency),"${OPENRTB_MBR}":t=>o(t.mbr),"${OPENRTB_LOSS}":t=>o(t.loss),"${OPENRTB_MIN_TO_WIN}":t=>o(t.minToWin),"${AUCTION_ID}":t=>o(t.id),"${AUCTION_BID_ID}":t=>o(t.bidId),"${AUCTION_IMP_ID}":t=>o(t.itemId),"${AUCTION_SEAT_ID}":t=>o(t.seatId),"${AUCTION_PRICE}":t=>o(t.price),"${AUCTION_CURRENCY}":t=>o(t.currency),"${AUCTION_MBR}":t=>o(t.mbr),"${AUCTION_LOSS}":t=>o(t.loss),"${AUCTION_MIN_TO_WIN}":t=>o(t.minToWin)},i={openrtb:{"${OPENRTB_MEDIA_ID}":t=>o(t.mediaId),"${OPENRTB_ITEM_QTY}":t=>o(t.itemQty)},auction:{"${AUCTION_AD_ID}":t=>o(t.adId),"${AUCTION_MULTIPLIER}":t=>o(t.multiplier),"${AUCTION_IMP_TS}":t=>o(t.impTs)}};return(this.version==="both"||this.version==="3")&&Object.entries(n).forEach(([t,r])=>{t.startsWith("${OPENRTB_")&&e.set(t,r)}),(this.version==="both"||this.version==="2")&&Object.entries(n).forEach(([t,r])=>{t.startsWith("${AUCTION_")&&e.set(t,r)}),(this.version==="both"||this.version==="3")&&Object.entries(i.openrtb).forEach(([t,r])=>e.set(t,r)),(this.version==="both"||this.version==="2")&&Object.entries(i.auction).forEach(([t,r])=>e.set(t,r)),e}updateContext(e){this.context={...this.context,...e}}replace(e,o){let n=e;for(let[i,t]of this.macroMap)try{let r=t({...this.context,...o});n=n.replace(new RegExp(i.replace(/\$/g,"\\$"),"g"),r)}catch(r){if(r instanceof Error)throw new Error(`Error replacing macro ${i}: ${r.message}`)}return n}getSupportedMacros(){return Array.from(this.macroMap.keys())}getContext(){return{...this.context}}};export{a as MacroReplacer};