From 4b554c9e472aca2bbb387f1b0795b41c5ab6d2d0 Mon Sep 17 00:00:00 2001 From: LinuxCTRL Date: Sun, 15 Nov 2026 16:33:59 +0000 Subject: [PATCH 1/4] fix: resolve Phase 1 blockers (quickstart consent, RSC imports, ad lifecycle, spacing rules, feed cache) --- package.json | 2 +- src/client/AdSenseSlot.tsx | 32 +++++++-- src/client/ConsentProvider.tsx | 30 ++++++-- src/client/InArticleAds.tsx | 9 ++- src/rules/rule-evaluator.ts | 19 +++++ src/transformers/feed-inserter.ts | 99 +++++++++++++++++++++++++-- src/transformers/html-inserter.ts | 32 +++++++-- src/transformers/markdown-inserter.ts | 31 ++++++++- tests/consent-and-adapters.test.tsx | 10 +++ tests/html-markdown-portable.test.ts | 61 +++++++++++++++++ tests/idempotency-and-density.test.ts | 30 ++++++++ tsup.config.ts | 5 +- 12 files changed, 326 insertions(+), 34 deletions(-) diff --git a/package.json b/package.json index 26b5918..1d60693 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ "url": "https://github.com/LinuxCTRL/adinject-react/issues" }, "scripts": { - "build": "tsup && node -e 'const fs = require(\"fs\"); [\"dist/index.js\", \"dist/index.mjs\", \"dist/client/index.js\", \"dist/client/index.mjs\"].forEach(f => { if (fs.existsSync(f)) { const c = fs.readFileSync(f, \"utf8\"); if (!c.startsWith(\"\\\"use client\\\"\")) fs.writeFileSync(f, \"\\\"use client\\\";\\n\" + c); } });'", + "build": "tsup && node -e 'const fs = require(\"fs\"); [\"dist/client/index.js\", \"dist/client/index.mjs\"].forEach(f => { if (fs.existsSync(f)) { const c = fs.readFileSync(f, \"utf8\"); if (!c.startsWith(\"\\\"use client\\\"\")) fs.writeFileSync(f, \"\\\"use client\\\";\\n\" + c); } });'", "dev": "tsup --watch", "test": "bun test", "typecheck": "tsc --noEmit", diff --git a/src/client/AdSenseSlot.tsx b/src/client/AdSenseSlot.tsx index d5f1104..e3999a6 100644 --- a/src/client/AdSenseSlot.tsx +++ b/src/client/AdSenseSlot.tsx @@ -156,9 +156,26 @@ export function AdSenseSlot({ return () => clearTimeout(pushTimer); }, [isVisible, effectiveTestMode, updateStatus, isConsentGranted]); - // 3. Fallback unfill detection check + // 3. Fallback unfill detection check (MutationObserver + safety timeout) useEffect(() => { - if (effectiveTestMode || !isPushedRef.current) return; + if (effectiveTestMode || status !== "rendered") return; + + const insEl = containerRef.current?.querySelector(".adsbygoogle"); + let observer: MutationObserver | null = null; + + if (insEl && typeof MutationObserver !== "undefined") { + observer = new MutationObserver(() => { + const adStatus = insEl.getAttribute("data-ad-status"); + if (adStatus === "unfilled") { + updateStatus("unfilled"); + observer?.disconnect(); + } + }); + observer.observe(insEl, { + attributes: true, + attributeFilter: ["data-ad-status"], + }); + } const checkTimer = setTimeout(() => { const el = containerRef.current?.querySelector(".adsbygoogle"); @@ -170,15 +187,18 @@ export function AdSenseSlot({ } }, 2500); - return () => clearTimeout(checkTimer); - }, [effectiveTestMode, updateStatus]); + return () => { + if (observer) observer.disconnect(); + clearTimeout(checkTimer); + }; + }, [status, effectiveTestMode, updateStatus]); // 4. Dev-Mode CLS Regression Guard useEffect(() => { if ( process.env.NODE_ENV === "production" || effectiveTestMode || - !isPushedRef.current + status !== "rendered" ) return; @@ -199,7 +219,7 @@ export function AdSenseSlot({ }, 3500); return () => clearTimeout(clsCheckTimer); - }, [effectiveTestMode, slot, effectiveDimensions.minHeight]); + }, [status, effectiveTestMode, slot, effectiveDimensions.minHeight]); const containerStyle: React.CSSProperties = { width: "100%", diff --git a/src/client/ConsentProvider.tsx b/src/client/ConsentProvider.tsx index c7ffa40..4f8ca9b 100644 --- a/src/client/ConsentProvider.tsx +++ b/src/client/ConsentProvider.tsx @@ -40,24 +40,26 @@ const ConsentContext = createContext({ }); /** - * Updates Google Consent Mode v2 via gtag('consent', 'update', ...) + * Updates Google Consent Mode v2 via gtag('consent', 'default' | 'update', ...) */ -function syncGoogleConsentMode(status: ConsentStatus) { +function syncGoogleConsentMode(status: ConsentStatus, isDefault = false) { if (typeof window === "undefined") return; const consentValue = status === "granted" ? "granted" : "denied"; + const command = isDefault ? "default" : "update"; + window.dataLayer = window.dataLayer || []; if (typeof window.gtag === "function") { - window.gtag("consent", "update", { + window.gtag("consent", command, { ad_storage: consentValue, ad_user_data: consentValue, ad_personalization: consentValue, analytics_storage: consentValue, }); - } else if (Array.isArray(window.dataLayer)) { + } else { window.dataLayer.push([ "consent", - "update", + command, { ad_storage: consentValue, ad_user_data: consentValue, @@ -75,10 +77,24 @@ export function ConsentProvider({ mode = "google-consent-v2", getConsent, listenEvent, - initialStatus = "unknown", + initialStatus, children, }: ConsentProviderProps) { - const [status, setStatus] = useState(initialStatus); + // If a custom CMP check (getConsent) or event listener is supplied without an explicit initialStatus, + // wait in "unknown" until resolved; otherwise default to "granted" so quickstart renders ads. + const resolvedInitialStatus: ConsentStatus = + initialStatus ?? + (getConsent || listenEvent || mode === "tcf" || mode === "gpp" + ? "unknown" + : "granted"); + const [status, setStatus] = useState(resolvedInitialStatus); + + // On mount, establish initial consent signals for Google Consent Mode v2 + useEffect(() => { + if (mode === "google-consent-v2") { + syncGoogleConsentMode(resolvedInitialStatus, true); + } + }, [mode, resolvedInitialStatus]); const grant = useCallback(() => { setStatus("granted"); diff --git a/src/client/InArticleAds.tsx b/src/client/InArticleAds.tsx index 42ff36c..feb2fa0 100644 --- a/src/client/InArticleAds.tsx +++ b/src/client/InArticleAds.tsx @@ -22,6 +22,8 @@ export interface InArticleAdsProps { interval?: number; /** Minimum paragraphs before the first ad (default: 1) */ startOffset?: number; + /** Minimum total paragraphs required in the article before any ad is injected (default: 0) */ + minParagraphsTotal?: number; /** Maximum total ads injected in the article (default: 4) */ maxAds?: number; /** AdSense slot ID (inherits client from AdInjectProvider) */ @@ -52,6 +54,7 @@ export function InArticleAds({ markdown, interval = 3, startOffset = 1, + minParagraphsTotal = 0, maxAds = 4, slot, adUnit, @@ -95,8 +98,9 @@ export function InArticleAds({ enabled: true, deviceFilter: "all" as const, paragraphInterval: interval, - minWordsBeforeFirstAd: startOffset * 10, - minParagraphsTotal: startOffset + 1, + startOffset, + minWordsBeforeFirstAd: 0, + minParagraphsTotal, maxAdsPerArticle: maxAds, adUnitId: targetAdUnit.id, }; @@ -127,6 +131,7 @@ export function InArticleAds({ markdown, interval, startOffset, + minParagraphsTotal, maxAds, adUnit, effectiveSlot, diff --git a/src/rules/rule-evaluator.ts b/src/rules/rule-evaluator.ts index 2d8da67..2840ae5 100644 --- a/src/rules/rule-evaluator.ts +++ b/src/rules/rule-evaluator.ts @@ -26,6 +26,25 @@ export function matchesPathPattern( return pathname === pattern; } +/** + * Returns true when a paragraph (1-based) should receive an ad slot. + * + * `startOffset` is the paragraph number after which the first ad is placed + * (default: 1), and `interval` is the number of paragraphs between ads. + * + * Example: startOffset=1, interval=3 -> ads after paragraphs 1, 4, 7, ... + */ +export function isParagraphAdPosition( + paragraphNumber: number, + startOffset = 1, + interval = 1, +): boolean { + const offset = Math.max(1, Math.floor(startOffset || 1)); + const step = Math.max(1, Math.floor(interval || 1)); + if (paragraphNumber < offset) return false; + return (paragraphNumber - offset) % step === 0; +} + /** * Evaluates device filters */ diff --git a/src/transformers/feed-inserter.ts b/src/transformers/feed-inserter.ts index 1685aa6..a01820c 100644 --- a/src/transformers/feed-inserter.ts +++ b/src/transformers/feed-inserter.ts @@ -9,8 +9,91 @@ export interface InjectFeedAdsOptions { idempotencyKey?: string; } -// Module-level idempotency cache for string keys -const keyCache = new Map[]>(); +interface CacheEntry { + itemsRef: T[]; + itemsLength: number; + ruleEnabled: boolean; + ruleId?: string; + interval?: number; + startOffset?: number; + maxAds?: number; + adUnitId?: string; + result: FeedItem[]; +} + +const MAX_CACHE_ENTRIES = 200; +const keyCache = new Map>(); + +/** + * Resets the module-level feed cache (mainly for testing) + */ +export function clearFeedCache(): void { + keyCache.clear(); +} + +function getCachedResult( + key: string, + items: T[], + rule?: PlacementRule, + adUnit?: AdUnit, +): FeedItem[] | null { + const entry = keyCache.get(key) as CacheEntry | undefined; + if (!entry) return null; + + // Invalidate if items reference changed and contents/length changed + if (entry.itemsRef !== items && entry.itemsLength !== items.length) { + return null; + } + + // Invalidate if rule enabled state changed + const ruleEnabled = rule ? rule.enabled : true; + if (entry.ruleEnabled !== ruleEnabled) { + return null; + } + + // Invalidate if spacing parameters changed + if ( + entry.interval !== (rule?.itemInterval ?? 4) || + entry.startOffset !== (rule?.startOffset ?? 2) || + entry.maxAds !== (rule?.maxAdsPerFeed ?? 4) || + entry.adUnitId !== (adUnit?.id ?? rule?.adUnitId) + ) { + return null; + } + + // Refresh position in Map for LRU + keyCache.delete(key); + keyCache.set(key, entry as CacheEntry); + + return entry.result; +} + +function setCachedResult( + key: string, + items: T[], + rule: PlacementRule | undefined, + adUnit: AdUnit | undefined, + result: FeedItem[], +) { + if (keyCache.size >= MAX_CACHE_ENTRIES) { + const oldestKey = keyCache.keys().next().value; + if (oldestKey !== undefined) { + keyCache.delete(oldestKey); + } + } + + keyCache.set(key, { + itemsRef: items, + itemsLength: items.length, + ruleEnabled: rule ? rule.enabled : true, + ruleId: rule?.id, + interval: rule?.itemInterval ?? 4, + startOffset: rule?.startOffset ?? 2, + maxAds: rule?.maxAdsPerFeed ?? 4, + adUnitId: adUnit?.id ?? rule?.adUnitId, + result, + }); +} /** * Injects Google AdSense / affiliate ad placeholders between items in an array @@ -34,8 +117,9 @@ export function injectFeedAds({ }: InjectFeedAdsOptions): FeedItem[] { if (!items || items.length === 0) return []; - if (idempotencyKey && keyCache.has(idempotencyKey)) { - return keyCache.get(idempotencyKey) as FeedItem[]; + if (idempotencyKey) { + const cached = getCachedResult(idempotencyKey, items, rule, adUnit); + if (cached) return cached; } // Default ad unit if not provided @@ -78,8 +162,9 @@ export function injectFeedAds({ type: "item", data, })); - if (idempotencyKey) - keyCache.set(idempotencyKey, rawItems as FeedItem[]); + if (idempotencyKey) { + setCachedResult(idempotencyKey, items, rule, adUnit, rawItems); + } return rawItems; } @@ -122,7 +207,7 @@ export function injectFeedAds({ } if (idempotencyKey) { - keyCache.set(idempotencyKey, result as FeedItem[]); + setCachedResult(idempotencyKey, items, rule, adUnit, result); } return result; diff --git a/src/transformers/html-inserter.ts b/src/transformers/html-inserter.ts index 6731993..13ca355 100644 --- a/src/transformers/html-inserter.ts +++ b/src/transformers/html-inserter.ts @@ -1,3 +1,4 @@ +import { isParagraphAdPosition } from "../rules/rule-evaluator"; import type { AdInjectionResult, AdUnit, @@ -63,6 +64,16 @@ export function injectHtmlAds({ }; } + const totalParagraphsInDocument = (html.match(/<\/p>/gi) || []).length; + if (totalParagraphsInDocument < Math.max(0, rule.minParagraphsTotal ?? 0)) { + return { + content: html, + insertedAds: [], + totalWords: countWordsInHtml(html), + totalParagraphs: totalParagraphsInDocument, + }; + } + const defaultTemplate = (slot: InjectedAdSlot) => `
@@ -101,8 +112,12 @@ export function injectHtmlAds({ const canInject = adsInsertedCount < rule.maxAdsPerArticle && - wordCountAccumulator >= rule.minWordsBeforeFirstAd && - totalParagraphCount % rule.paragraphInterval === 0 && + wordCountAccumulator >= (rule.minWordsBeforeFirstAd ?? 0) && + isParagraphAdPosition( + totalParagraphCount, + rule.startOffset ?? 1, + rule.paragraphInterval, + ) && !isExcludedParagraph(precedingParagraph, rule.excludedSelectors); if (canInject) { @@ -148,6 +163,11 @@ export function splitHtmlForAds({ return [{ type: "html", content: html }]; } + const totalParagraphsInDocument = (html.match(/<\/p>/gi) || []).length; + if (totalParagraphsInDocument < Math.max(0, rule.minParagraphsTotal ?? 0)) { + return [{ type: "html", content: html }]; + } + const parts = html.split(/(<\/p>)/i); const chunks: HtmlChunk[] = []; let currentHtmlBuffer = ""; @@ -168,8 +188,12 @@ export function splitHtmlForAds({ const canInject = adsInsertedCount < rule.maxAdsPerArticle && - wordCountAccumulator >= rule.minWordsBeforeFirstAd && - totalParagraphCount % rule.paragraphInterval === 0 && + wordCountAccumulator >= (rule.minWordsBeforeFirstAd ?? 0) && + isParagraphAdPosition( + totalParagraphCount, + rule.startOffset ?? 1, + rule.paragraphInterval, + ) && !isExcludedParagraph(precedingParagraph, rule.excludedSelectors); if (canInject) { diff --git a/src/transformers/markdown-inserter.ts b/src/transformers/markdown-inserter.ts index fc4f5cd..6283031 100644 --- a/src/transformers/markdown-inserter.ts +++ b/src/transformers/markdown-inserter.ts @@ -1,3 +1,4 @@ +import { isParagraphAdPosition } from "../rules/rule-evaluator"; import type { AdInjectionResult, AdUnit, @@ -39,12 +40,32 @@ export function injectMarkdownAds({ }; } + const rawBlocks = markdown.split(/\n\s*\n/); + const totalParagraphCount = rawBlocks.filter( + (block) => + block && + block.trim().length > 0 && + !block.startsWith("#") && + !block.startsWith("```") && + !block.startsWith(">") && + !block.startsWith("- ") && + !block.startsWith("1. "), + ).length; + + if (totalParagraphCount < Math.max(0, rule.minParagraphsTotal ?? 0)) { + return { + content: markdown, + insertedAds: [], + totalWords: countWordsInMarkdown(markdown), + totalParagraphs: totalParagraphCount, + }; + } + const defaultMarker = (slot: InjectedAdSlot) => `\n\n\n\n`; const renderMarker = customAdMarker || defaultMarker; - const rawBlocks = markdown.split(/\n\s*\n/); const transformedBlocks: string[] = []; const insertedAds: InjectedAdSlot[] = []; @@ -71,8 +92,12 @@ export function injectMarkdownAds({ const shouldInject = adsInserted < rule.maxAdsPerArticle && - wordCountAccumulator >= rule.minWordsBeforeFirstAd && - paragraphIndex % rule.paragraphInterval === 0 && + wordCountAccumulator >= (rule.minWordsBeforeFirstAd ?? 0) && + isParagraphAdPosition( + paragraphIndex, + rule.startOffset ?? 1, + rule.paragraphInterval, + ) && i < rawBlocks.length - 1; if (shouldInject) { diff --git a/tests/consent-and-adapters.test.tsx b/tests/consent-and-adapters.test.tsx index 9948ec5..9f6db1f 100644 --- a/tests/consent-and-adapters.test.tsx +++ b/tests/consent-and-adapters.test.tsx @@ -45,6 +45,16 @@ describe("Consent Provider & Ad Adapters", () => { expect(html).toContain("Google AdSense Test Slot"); }); + it("should render live ad ins tag by default in quickstart without explicit initialStatus", () => { + const html = renderToString( + + + , + ); + expect(html).toContain('class="adsbygoogle"'); + expect(html).not.toContain("Consent Required for Personalized Ads"); + }); + it("should render affiliate fallback when consent is denied", () => { const html = renderToString( diff --git a/tests/html-markdown-portable.test.ts b/tests/html-markdown-portable.test.ts index 3333ec0..522d23a 100644 --- a/tests/html-markdown-portable.test.ts +++ b/tests/html-markdown-portable.test.ts @@ -47,6 +47,36 @@ describe("Content Transformers", () => { const result = injectHtmlAds({ html: shortHtml, rule, adUnit }); expect(result.insertedAds.length).toBe(0); }); + + it("should respect minParagraphsTotal threshold", () => { + const html = ` +

Paragraph 1 with plenty of words to easily exceed word limits.

+

Paragraph 2 with plenty of words to easily exceed word limits.

+ `; + const result = injectHtmlAds({ + html, + rule: { ...rule, minParagraphsTotal: 4 }, + adUnit, + }); + expect(result.insertedAds.length).toBe(0); + }); + + it("should place first ad after startOffset paragraph", () => { + const html = ` +

Paragraph 1 with plenty of words to easily exceed word limits.

+

Paragraph 2 with plenty of words to easily exceed word limits.

+

Paragraph 3 with plenty of words to easily exceed word limits.

+

Paragraph 4 with plenty of words to easily exceed word limits.

+ `; + const result = injectHtmlAds({ + html, + rule: { ...rule, startOffset: 2, paragraphInterval: 2, minParagraphsTotal: 2 }, + adUnit, + }); + expect(result.insertedAds.length).toBe(2); + expect(result.insertedAds[0]?.insertedAfterParagraph).toBe(2); + expect(result.insertedAds[1]?.insertedAfterParagraph).toBe(4); + }); }); describe("injectMarkdownAds", () => { @@ -64,6 +94,37 @@ Paragraph 4 summarizes the recipe and nutritional info. const result = injectMarkdownAds({ markdown, rule, adUnit }); expect(result.insertedAds.length).toBeGreaterThan(0); }); + + it("should respect minParagraphsTotal and startOffset in Markdown", () => { + const markdown = ` +Paragraph 1 with plenty of words to easily exceed word limits. + +Paragraph 2 with plenty of words to easily exceed word limits. + `; + const resultTooShort = injectMarkdownAds({ + markdown, + rule: { ...rule, minParagraphsTotal: 4 }, + adUnit, + }); + expect(resultTooShort.insertedAds.length).toBe(0); + + const markdownFour = ` +Paragraph 1 with plenty of words. + +Paragraph 2 with plenty of words. + +Paragraph 3 with plenty of words. + +Paragraph 4 with plenty of words. + `; + const resultOffset = injectMarkdownAds({ + markdown: markdownFour, + rule: { ...rule, startOffset: 2, paragraphInterval: 2, minParagraphsTotal: 2 }, + adUnit, + }); + expect(resultOffset.insertedAds.length).toBe(1); // after para 2 (para 4 is the last block, skipped by i < rawBlocks.length - 1) + expect(resultOffset.insertedAds[0]?.insertedAfterParagraph).toBe(2); + }); }); describe("injectPortableTextAds & injectPortableTextAffiliate", () => { diff --git a/tests/idempotency-and-density.test.ts b/tests/idempotency-and-density.test.ts index 141375e..718946e 100644 --- a/tests/idempotency-and-density.test.ts +++ b/tests/idempotency-and-density.test.ts @@ -149,6 +149,36 @@ describe("Idempotency & Density Guards", () => { expect(run1).toBe(run2); // exact cached reference }); + it("should invalidate feed cache when items length changes or rule enables", () => { + const initialItems = ["Item 1", "Item 2", "Item 3"]; + const runDisabled = injectFeedAds({ + items: initialItems, + rule: { ...sampleRule, enabled: false }, + adUnit: sampleAdUnit, + idempotencyKey: "dynamic-feed-test", + }); + expect(runDisabled.filter((i) => i.type === "ad").length).toBe(0); + + // Rule enabled with same key should NOT return poisoned disabled cache + const runEnabled = injectFeedAds({ + items: initialItems, + rule: { ...sampleRule, enabled: true }, + adUnit: sampleAdUnit, + idempotencyKey: "dynamic-feed-test", + }); + expect(runEnabled.filter((i) => i.type === "ad").length).toBeGreaterThan(0); + + // More items appended should invalidate stale cache + const expandedItems = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"]; + const runExpanded = injectFeedAds({ + items: expandedItems, + rule: sampleRule, + adUnit: sampleAdUnit, + idempotencyKey: "dynamic-feed-test", + }); + expect(runExpanded.length).toBeGreaterThan(runEnabled.length); + }); + it("should stamp data-adinject-affiliate attribute on autolinked anchors", () => { const html = "

Get your air fryer ready for dinner.

"; const result = injectHtmlAffiliateKeywords(html, { diff --git a/tsup.config.ts b/tsup.config.ts index ef08d4b..1721cc6 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -11,13 +11,10 @@ export default defineConfig({ format: ["cjs", "esm"], dts: true, clean: true, - splitting: false, + splitting: true, treeshake: true, sourcemap: true, minify: false, - banner: { - js: '"use client";', - }, external: ["react", "react-dom", "next", "next/script", "next/navigation"], }); From 2c8b3b68d8483e12029360ae24aeb2828f608c7e Mon Sep 17 00:00:00 2001 From: LinuxCTRL Date: Sun, 15 Nov 2026 16:38:47 +0000 Subject: [PATCH 2/4] fix: resolve Phase 2 correctness issues (TCF/GPP signals, GAM/Ezoic adapters, deterministic PortableText keys, timer leaks, feed context) --- package.json | 7 +- src/adapters/index.tsx | 121 +++++++++++++++++---- src/client/AdInjectFeed.tsx | 26 ++++- src/client/AdSenseScript.tsx | 56 ++++++++-- src/client/AdSenseSlot.tsx | 58 +++++++++- src/client/AdSlotFrame.tsx | 8 ++ src/client/ConsentProvider.tsx | 57 ++++++++-- src/client/InFeedAdCard.tsx | 4 +- src/client/useAdMetrics.ts | 31 +++--- src/transformers/feed-inserter.ts | 5 +- src/transformers/portable-text-adapter.tsx | 6 +- tests/html-markdown-portable.test.ts | 18 ++- 12 files changed, 331 insertions(+), 66 deletions(-) diff --git a/package.json b/package.json index 1d60693..366ce4a 100644 --- a/package.json +++ b/package.json @@ -83,12 +83,15 @@ } }, "devDependencies": { - "@types/node": "^26.3.0", + "@types/node": "^26.6.6", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", "tsup": "^8.3.6", "typescript": "^5.7.3" + }, + "allowScripts": { + "esbuild": true } -} \ No newline at end of file +} diff --git a/src/adapters/index.tsx b/src/adapters/index.tsx index a384833..c7ad57a 100644 --- a/src/adapters/index.tsx +++ b/src/adapters/index.tsx @@ -1,7 +1,31 @@ -import type React from "react"; +import React, { useEffect } from "react"; import { AdSenseSlot } from "../client/AdSenseSlot"; import type { AdDimensions, AdFormat, FallbackBanner } from "../types"; +declare global { + interface Window { + googletag?: { + cmd: Array<() => void>; + defineSlot?: ( + adUnitPath: string, + size: unknown, + divId: string, + ) => { + addService: (service: unknown) => unknown; + }; + pubads?: () => unknown; + enableServices?: () => void; + display?: (divId: string) => void; + }; + ezstandalone?: { + cmd?: Array<() => void>; + define?: (...slots: number[]) => void; + enable?: () => void; + display?: () => void; + }; + } +} + export interface AdAdapterSlotProps { slot: string; client?: string; @@ -97,6 +121,77 @@ export function adsenseAdapter(opts: { }); } +function GamSlotContainer({ + divId, + adUnitPath, + props, +}: { + divId: string; + adUnitPath: string; + props: AdAdapterSlotProps; +}) { + useEffect(() => { + if (typeof window === "undefined") return; + window.googletag = window.googletag || { cmd: [] }; + window.googletag.cmd = window.googletag.cmd || []; + window.googletag.cmd.push(() => { + if (window.googletag?.defineSlot && window.googletag?.pubads) { + window.googletag + .defineSlot(adUnitPath, "fluid", divId) + ?.addService(window.googletag.pubads()); + window.googletag.enableServices?.(); + } + window.googletag?.display?.(divId); + }); + }, [divId, adUnitPath]); + + return ( +