Source Code Preview - This is the actual code running on the server.
The code is loaded and syntax-highlighted at server startup.
// Format pages - dynamic routing
app.get('/formats/:format', async (req, res) => {
const formatSlug = req.params.format;
// Find format configurationconst formatConfig = FORMATS.find(f => f.slug === formatSlug);
if (!formatConfig) {
return res.status(404).render('404', { requestedFormat: formatSlug });
}
// Determine rendering mode from query paramconst mode = ['backend', 'frontend'].includes(req.query.mode)
? req.query.mode
: 'backend'; // Default to backend (SSR)let adData = null;
// Only fetch bid server-side for backend modeif (mode === 'backend') {
try {
const bidResult = await bidder.fetchBid({
site: 'demo_page',
tagId: formatConfig.tagId,
containerId: formatConfig.containerId,
networkId: formatConfig.networkId, // Use format-specific network IDkeyvalues: {
manufacturer_id: '12345678',
npa: 0// 0 - user has all required consent, 1 - user has not given consent
}
});
adData = bidResult?.hasAd ? bidResult.adData : null;
// For branded-products: use mock product service// This simulates how a real shop would fetch product details from their catalogif (formatSlug === 'branded-products' && adData) {
console.log('[Server] Using mock product service for branded-products...');
const mockProducts = productService.getProductsByIds(
IdealoClient.getDemoProductIds().slice(0, 5)
);
const mockOffers = productService.toOfferFormat(mockProducts);
// Merge mock product data with original offer_url from ad server (for tracking)// - product_url: URL produktu z mock danych (dla href)// - offer_url: tracking URL z ad servera (dla onclick)const originalOffers = adData.offers || [];
adData.offers = mockOffers.map((mockOffer, index) => ({
...mockOffer,
// Product URL from mock data (destination link)product_url: mockOffer.offer_url,
// Tracking URL from ad server (click tracking)offer_url: originalOffers[index]?.offer_url || ''
}));
adData.mockProductsUsed = true;
console.log('[Server] Mock products integrated:', mockProducts.length);
}
} catch (error) {
console.error(`[Server] Error fetching bid for ${formatSlug}:`, error.message);
adData = null;
}
}
console.log(`[Server] Rendering ${formatSlug} in ${mode.toUpperCase()} mode`);
res.render(`formats/${formatSlug}`, {
adData,
mode,
format: formatConfig,
formats: FORMATS,
sourceCode: SOURCE_CODE_BY_FORMAT[formatSlug] || SOURCE_CODE_BY_FORMAT['brand-store']
});
});
/**
* CSR Bidder Client
* ═══════════════════════════════════════════════════════════════════════════════
* Fetches ads from Ring DAS CSR bidder for server-side rendering (SSR).
*
* SUPPORTED FORMATS:
* ─────────────────────────────────────────────────────────────────────────────
* 1. Brand Store (brand_store)
* - Ad server provides: click tracking URL
* - Shop provides: ALL product data (logo, price, URL)
*
* 2. Branded Products (branded_products)
* - Ad server provides: bannerImage (logo) + offers[].product_id
* - Shop provides: product details fetched using product_id
*
* ═══════════════════════════════════════════════════════════════════════════════
*
* Usage:
* const { BidderClient } = require('./lib/bidder-client');
* const bidder = new BidderClient({ networkId: '1746213' });
* const result = await bidder.fetchBid({
* site: 'demo_page',
* tagId: 'branded_products',
* containerId: 'ad-container'
* });
*/// ═══════════════════════════════════════════════════════════════════════════════// HELPER FUNCTIONS// ═══════════════════════════════════════════════════════════════════════════════/**
* Returns hardcoded shop display data for Brand Store format.
* In real implementation, shop would provide this data.
*/functiongetBrandStoreShopData() {
return {
shopName: 'AD Partner Shop',
price: '€899.00',
label: 'Ad'
};
}
/**
* Generates unique request ID for bid requests
*/functiongenerateRequestId() {
returnMath.random().toString(16).substring(2, 15) +
Math.random().toString(16).substring(2, 15);
}
// ═══════════════════════════════════════════════════════════════════════════════// BIDDER CLIENT CLASS// ═══════════════════════════════════════════════════════════════════════════════classBidderClient {
/**
* Create a new BidderClient instance
* @param {Object} options
* @param {string} [options.networkId='1746213'] - Default network ID
*/constructor(options = {}) {
this.networkId = options.networkId || '1746213';
this.baseUrl = `https://csr.onet.pl/${this.networkId}/bid`;
}
// ─────────────────────────────────────────────────────────────────────────// REQUEST BUILDING// ─────────────────────────────────────────────────────────────────────────/**
* Build OpenRTB-compatible bid request body
*
* @param {Object} params
* @param {string} params.site - Site identifier (e.g., 'demo_page')
* @param {string} params.tagId - Slot tag ID ('brand_store' or 'branded_products')
* @param {string} params.networkId - Network ID for this request
* @param {Object} [params.keyvalues={}] - Additional targeting key-values
* @returns {Object} OpenRTB bid request body
*/buildRequestBody({ site, tagId, networkId, keyvalues = {} }) {
return {
id: generateRequestId(),
imp: [{
id: 'imp-1',
tagid: tagId,
secure: 1,
native: { request: "{}" },
ext: {
offers_limit: 10
}
}],
site: {
id: site
},
user: {
ext: {
npa: false// false = consent given, true = no consent
}
},
ext: {
network: networkId,
keyvalues: {
kvIV: generateRequestId(),
kvIP: generateRequestId(),
...keyvalues
},
is_non_prebid_request: true
},
at: 1,
tmax: 1000,
regs: {
gdpr: 1,
gpp: '',
ext: {
dsa: 1// Request DSA transparency info
}
}
};
}
// ─────────────────────────────────────────────────────────────────────────// RESPONSE PARSING// ─────────────────────────────────────────────────────────────────────────/**
* Parse bid response and extract ad data
*
* DATA SOURCES:
* ─────────────────────────────────────────────────────────────────────────
* FROM AD SERVER (returned in response):
* - bannerImage: Brand logo URL
* - offers[]: Array with product_id for each product
* - dsaInfo: DSA transparency information
* - clickUrl: Click tracking URL
* - rawResponse: Full response for viewability tracking
*
* FROM SHOP (must be fetched separately using product_id):
* - Product image, name, price, URL
*
* For demo purposes, offers contain full product data (simulating shop lookup).
* ─────────────────────────────────────────────────────────────────────────
*
* @param {Object} response - Raw bid response from ad server
* @param {string} containerId - Container element ID for viewability
* @returns {Object|null} Parsed ad data or null if no bid
*/parseResponse(response, containerId) {
try {
const bid = response?.seatbid?.[0]?.bid?.[0];
if (!bid) {
console.log('[BidderClient] No bid in response');
returnnull;
}
// Parse adm (it's a JSON string containing ad creative data)const adm = JSON.parse(bid.adm);
// ─────────────────────────────────────────────────────────────────// EXTRACT DATA FROM AD SERVER// ─────────────────────────────────────────────────────────────────// DSA (Digital Services Act) transparency infoconst dsaData = bid?.ext?.dsa || null;
const dsaInfo = dsaData ? {
advertiser: dsaData.behalf || null,
payer: dsaData.paid || null,
adrender: dsaData.adrender || 0
} : null;
// Click tracking URL (for Brand Store)const metaAdclick = adm?.meta?.adclick;
const fieldsClick = adm?.fields?.click;
const clickUrl = (metaAdclick && fieldsClick)
? metaAdclick + encodeURIComponent(fieldsClick)
: null;
// Branded Products data from ad serverconst bannerImage = adm?.fields?.bannerImage || null; // Brand logoconst offers = adm?.fields?.feed?.offers || []; // Product IDs (+ demo data)// Impression tracking URLconst impressionUrl = bid?.ext?.ems_link;
// ─────────────────────────────────────────────────────────────────// BUILD RESPONSE OBJECT// ─────────────────────────────────────────────────────────────────return {
hasAd: true,
adData: {
// Container for viewability tracking
containerId,
// Full response for dlApi.registerBidResponse()rawResponse: response,
// ─────────────────────────────────────────────────────────// FROM AD SERVER:// ─────────────────────────────────────────────────────────// Brand logo URL (render directly)
bannerImage,
// Product IDs from ad server// In real implementation: use product_id to fetch from shop's DB// For demo: contains full product data (simulating shop lookup)
offers,
// DSA transparency info
dsaInfo,
// Click tracking
clickUrl,
metaAdclick, // Base URL for constructing tracking URLs
impressionUrl,
// MetadataadId: adm?.meta?.adid,
templateCode: adm?.tplCode,
// ─────────────────────────────────────────────────────────// FROM SHOP (Brand Store only):// ─────────────────────────────────────────────────────────
...getBrandStoreShopData()
}
};
} catch (error) {
console.error('[BidderClient] Error parsing response:', error.message);
returnnull;
}
}
// ─────────────────────────────────────────────────────────────────────────// MAIN FETCH METHOD// ─────────────────────────────────────────────────────────────────────────/**
* Fetch bid from Ring DAS CSR bidder
*
* @param {Object} params
* @param {string} params.site - Site identifier (e.g., 'demo_page')
* @param {string} params.tagId - Slot tag ID ('brand_store' or 'branded_products')
* @param {string} params.containerId - Container element ID for viewability
* @param {string} [params.networkId] - Network ID (overrides default)
* @param {Object} [params.keyvalues={}] - Additional targeting parameters
* @returns {Promise<Object|null>} Bid result or null if no ad
*/asyncfetchBid({ site, tagId, containerId, networkId, keyvalues = {} }) {
const effectiveNetworkId = networkId || this.networkId;
const bidUrl = `https://csr.onet.pl/${effectiveNetworkId}/bid`;
const requestBody = this.buildRequestBody({
site,
tagId,
networkId: effectiveNetworkId,
keyvalues
});
console.log('[BidderClient] ─────────────────────────────────────────');
console.log('[BidderClient] Fetching bid from:', bidUrl);
console.log('[BidderClient] Tag ID:', tagId);
console.log('[BidderClient] Request:', JSON.stringify(requestBody, null, 2));
try {
// Send as GET request with body in data= parameter (as per documentation)const encodedData = encodeURIComponent(JSON.stringify(requestBody));
const response = awaitfetch(`${bidUrl}?data=${encodedData}`);
console.log('[BidderClient] Response status:', response.status);
if (!response.ok) {
console.error('[BidderClient] HTTP error:', response.status, response.statusText);
returnnull;
}
const data = await response.json();
console.log('[BidderClient] Response received');
const result = this.parseResponse(data, containerId);
if (result) {
console.log('[BidderClient] ✓ Ad found');
console.log('[BidderClient] - Banner image:', result.adData.bannerImage ? 'Yes' : 'No');
console.log('[BidderClient] - Products:', result.adData.offers?.length || 0);
console.log('[BidderClient] - DSA info:', result.adData.dsaInfo ? 'Yes' : 'No');
} else {
console.log('[BidderClient] ✗ No ad available');
}
console.log('[BidderClient] ─────────────────────────────────────────');
return result;
} catch (error) {
console.error('[BidderClient] Fetch error:', error.message);
returnnull;
}
}
}
module.exports = {
BidderClient
};
<% if (adData) { %>
<!-- AD Button - dynamically loaded from bidder --><!-- TODO - check if ad for this manufacturer is valid:
* manufacturer S has a brandShop S
* offerList contains offers from S -->
<%
/**
* Mock shop/retailer data.
* In production, this data is provided by the shop/retailer system,
* NOT from the ad server. The ad server only provides tracking (adClick).
*/
const shopData = {
productUrl: 'https://www.apple.com/de/shop/buy-iphone/iphone-17',
shopName: 'Apple',
shopLogo: 'https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg',
price: '€899.00',
currency: 'EUR'
};
%>
<divid="<%= adData.containerId %>"class="offer-button-wrapper offer-button-ad"data-ad-slot="oop-button-ad"><divclass="ad-header"><spanclass="ad-label"><%= adData.label %></span>
<% if (adData.dsaInfo) { %>
<divclass="dsa-info-wrapper"><spanclass="dsa-info-icon"title="Ad transparency info">i</span><divclass="dsa-info-tooltip"><divclass="dsa-info-row"><spanclass="dsa-info-label">Advertiser:</span><spanclass="dsa-info-value"><%= adData.dsaInfo.advertiser || 'N/A' %></span></div><divclass="dsa-info-row"><spanclass="dsa-info-label">Paid by:</span><spanclass="dsa-info-value"><%= adData.dsaInfo.payer || 'N/A' %></span></div></div></div>
<% } %>
</div><!--
Shop data (productUrl, shopLogo, shopName, price) - provided by retailer/shop system
Ad tracking (clickUrl) - provided by ad server (this is the ONLY data from ad server)
--><ahref="<%= shopData.productUrl %>"class="brand-shop-button"target="_blank"rel="noopener nofollow sponsored"data-offer-type="ad"data-ad-id="<%= adData.adId || 'unknown' %>"onclick="dlApi.cmd.push(function() { var url = '<%= adData.clickUrl %>'; console.log('[dlApi] Adclick:', url); new Image().src = url; });">
At <imgsrc="<%= shopData.shopLogo %>"alt="<%= shopData.shopName %>"class="shop-logo"style="height: 16px; vertical-align: middle;">
for <spanclass="button-price"><%= shopData.price %></span></a></div><script>
dlApi.cmd.push(function () {
dlApi.registerBidResponse(
<%- JSON.stringify(adData.rawResponse) %>,
'<%= adData.containerId %>'
);
});
</script>
<% } %>
<!-- AD Button - loaded client-side via dlApi --><divid="oop-ad-button"class="offer-button-wrapper offer-button-ad"><divclass="ad-header"><spanclass="ad-label">Ad</span></div><divclass="ad-slot-loading">Loading ad...</div></div><script>// Frontend approach:const divId = 'oop-ad-button';
/**
* Mock function simulating shop/retailer data response.
* In production, this data is provided by the shop/retailer system,
* NOT from the ad server. The ad server only provides tracking (adClick).
*/functiongetMockShopData() {
return {
productUrl: 'https://www.apple.com/de/shop/buy-iphone/iphone-17',
shopName: 'Apple',
shopLogo: 'https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg',
price: '€899.00',
currency: 'EUR'
};
}
/**
* Generate DSA info icon HTML
* @param {Object} dsa - DSA object from ad.dsa with fields: behalf, paid, adrender
*/functiongetDsaInfoHtml(dsa) {
if (!dsa) return'';
return'<div class="dsa-info-wrapper">' +
'<span class="dsa-info-icon" title="Ad transparency info">i</span>' +
'<div class="dsa-info-tooltip">' +
'<div class="dsa-info-row">' +
'<span class="dsa-info-label">Advertiser:</span> ' +
'<span class="dsa-info-value">' + (dsa.behalf || 'N/A') + '</span>' +
'</div>' +
'<div class="dsa-info-row">' +
'<span class="dsa-info-label">Paid by:</span> ' +
'<span class="dsa-info-value">' + (dsa.paid || 'N/A') + '</span>' +
'</div>' +
'</div>' +
'</div>';
}
// Step 1: Wait for SDK to be ready (all dlApi calls must be inside cmd.push)
dlApi.cmd.push(function (dlApi) {
// Step 2: Set targeting key-values (sent to ad server for campaign matching)
dlApi.addKeyValue('manufacturer_id', '12345678'); // Product manufacturer ID// 3. Register template - defines HOW ad is rendered
dlApi.fetchNativeAd({
slot: 'brand_store', // constant value for Sponsored Productdiv: divId,
tplCode: '1746213/Banner-Standard', // constant value for Sponsored ProductasyncRender: true// manually count ad impressions if you want to show only active offers
}).then(ad => {
if (!ad) {
console.info('[Frontend Mode] Ad not found!');
return;
}
/** TODO - check if ad for this manufacturer is valid:
* manufacturer S has a brandShop S
* offerList contains offers from S
**/console.log('[Frontend Mode] renderAd called:', ad);
// Use parent document (not iframe's win.document)var container = document.getElementById(divId);
if (!container) {
console.error('[Frontend Mode] Container not found!');
return;
}
// Shop data - provided by retailer/shop system (mocked for demo)var shopData = getMockShopData();
// DSA info from ad response (ad.dsa contains: behalf, paid, adrender)var dsaInfo = ad.dsa;
// Count impressions manually
ad.render();
// Ad tracking URL - provided by ad server (this is the ONLY data from ad server)var clickUrl = ad.meta.adclick + encodeURIComponent(ad.fields.click || '');
// Replace entire container content with proper structure// Note: All product data (URL, logo, price) comes from shop, only adClick tracking comes from ad
container.innerHTML =
'<div class="ad-header">' +
'<span class="ad-label">Ad</span>' +
getDsaInfoHtml(dsaInfo) +
'</div>' +
'<a href="' + shopData.productUrl + '" ' +
'class="brand-shop-button" ' +
'target="_blank" ' +
'rel="noopener nofollow sponsored" ' +
'data-offer-type="ad" ' +
'data-ad-id="' + (ad.meta.adid || 'unknown') + '" ' +
'onclick="(function(){ console.log(\'[dlApi] Adclick:\', \'' + clickUrl + '\'); new Image().src = \'' + clickUrl + '\'; })();">' +
'At <img src="' + shopData.shopLogo + '" ' +
'alt="' + shopData.shopName + '" class="shop-logo" style="height: 16px; vertical-align: middle;"> ' +
'for <span class="button-price">' + shopData.price + '</span>' +
'</a>';
console.log('[Frontend Mode] Button rendered successfully');
}
).catch(err => {
console.error('Ad for rmn-sponsored-product could not be loaded:', err);
});
// 4: Trigger ad request (sends all slots to ad server)
dlApi.fetch();
//// // 3. SECOND WAY//// // Step 3: Define ad slot ('branded_products' = slot name, containerId = container element)// const slot = dlApi.defineSlot('brand_store', divId, { pos: 1 });//// // Step 4: Register custom template to control how ad is rendered// slot.registerTemplate({// tplCode: '1746213/Banner-Standard',// asyncRender: true,// renderAd: function (ad) {// if (!ad) {// console.info('[Frontend Mode] Ad not found!');// return;// }//// /** TODO - check if ad for this manufacturer is valid:// * manufacturer S has a brandShop S// * offerList contains offers from S// **/////// console.log('[Frontend Mode] renderAd called:', ad);// // Use parent document (not iframe's win.document)// var container = document.getElementById(divId);// if (!container) {// console.error('[Frontend Mode] Container not found!');// return;// }//// // Shop data - provided by retailer/shop system (mocked for demo)// var shopData = getMockShopData();//// // DSA info from ad response (ad.dsa contains: behalf, paid, adrender)// var dsaInfo = ad.dsa;//// // Count impressions manually// ad.render();//// // Ad tracking URL - provided by ad server (this is the ONLY data from ad server)// var clickUrl = ad.meta.adclick + encodeURIComponent(ad.fields.click || '');//// // Replace entire container content with proper structure// // Note: All product data (URL, logo, price) comes from shop, only adClick tracking comes from ad// container.innerHTML =// '<div class="ad-header">' +// '<span class="ad-label">Ad</span>' +// getDsaInfoHtml(dsaInfo) +// '</div>' +// '<a href="' + shopData.productUrl + '" ' +// 'class="brand-shop-button" ' +// 'target="_blank" ' +// 'rel="noopener nofollow sponsored" ' +// 'data-offer-type="ad" ' +// 'data-ad-id="' + (ad.meta.adid || 'unknown') + '" ' +// 'onclick="(function(){ console.log(\'[dlApi] Adclick:\', \'' + clickUrl + '\'); new Image().src = \'' + clickUrl + '\'; })();">' +// 'At <img src="' + shopData.shopLogo + '" ' +// 'alt="' + shopData.shopName + '" class="shop-logo" style="height: 16px; vertical-align: middle;"> ' +// 'for <span class="button-price">' + shopData.price + '</span>' +// '</a>';//// console.log('[Frontend Mode] Button rendered successfully');// }// });//// // Step 5: Handle "empty" event (no ad available for this slot)// slot.on('empty', function () {// console.log('[Brand Store] Slot empty - no ad available');// });//// // Step 6: Trigger ad request (sends all slots to ad server)// dlApi.fetch();
});
</script>