-
Notifications
You must be signed in to change notification settings - Fork 8
GPT integration #282
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
GPT integration #282
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8ce5be3
gpt integration
ChristianPavilonis d22824a
script guard to catch and proxy pubads_impl.js
ChristianPavilonis 8173655
doc/js format
ChristianPavilonis e1ab3d0
just one gpt domain for now
ChristianPavilonis 95bf9a1
revert
ChristianPavilonis 4bae967
update docs and removed legacy rewrites
ChristianPavilonis 6d64721
clean up comment and documentation inaccuracies
ChristianPavilonis 28db620
address some pr comments
ChristianPavilonis 22f512a
javascript format
ChristianPavilonis 20cbfca
Check if integration is enabled before script init
ChristianPavilonis c4cc2a1
format and lint
ChristianPavilonis 45a5ba1
address pr comments
ChristianPavilonis 7fde816
fix: resolve GPT shim auto-init race by using explicit activation
ChristianPavilonis 3107e16
disable gpt integration by default in trusted-server.toml
ChristianPavilonis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| import { log } from '../../core/log'; | ||
|
|
||
| import { installGptGuard } from './script_guard'; | ||
|
|
||
| /** | ||
| * Google Publisher Tags (GPT) Integration Shim | ||
| * | ||
| * Hooks into the googletag.cmd command queue so the Trusted Server can | ||
| * observe and augment ad-slot definitions before GPT processes them. | ||
| * The shim ensures the googletag stub exists early (matching GPT's own | ||
| * bootstrap pattern) and patches `cmd.push` to wrap queued callbacks. | ||
| * | ||
| * Current capabilities: | ||
| * - Installs a script guard that rewrites dynamically inserted GPT | ||
| * `<script>` elements to the first-party proxy endpoint. | ||
| * - Takes over the `googletag.cmd` array so that every callback runs | ||
| * through a wrapper that can inject targeting, logging, or consent | ||
| * signals before the real GPT processes the command. | ||
| * | ||
| * Future enhancements (driven by config or tsjs API): | ||
| * - Inject synthetic ID as page-level key-value targeting. | ||
| * - Gate ad requests on consent status. | ||
| * - Rewrite ad-unit paths for A/B testing. | ||
| */ | ||
|
|
||
| // ------------------------------------------------------------------ | ||
| // googletag type stubs (minimal surface needed by the shim) | ||
| // ------------------------------------------------------------------ | ||
|
|
||
| interface GoogleTagSlot { | ||
| getAdUnitPath(): string; | ||
| getSlotElementId(): string; | ||
| setTargeting(key: string, value: string | string[]): GoogleTagSlot; | ||
| } | ||
|
|
||
| interface GoogleTagPubAdsService { | ||
| setTargeting(key: string, value: string | string[]): GoogleTagPubAdsService; | ||
| getTargeting(key: string): string[]; | ||
| enableSingleRequest(): void; | ||
| } | ||
|
|
||
| interface GoogleTag { | ||
| cmd: Array<() => void>; | ||
| pubads(): GoogleTagPubAdsService; | ||
| defineSlot( | ||
| adUnitPath: string, | ||
| size: Array<number | number[]>, | ||
| elementId: string | ||
| ): GoogleTagSlot | null; | ||
| enableServices(): void; | ||
| display(elementId: string): void; | ||
| _loaded_?: boolean; | ||
| } | ||
|
|
||
| type GptWindow = Window & { | ||
| googletag?: Partial<GoogleTag>; | ||
| }; | ||
|
|
||
| // ------------------------------------------------------------------ | ||
| // Shim implementation | ||
| // ------------------------------------------------------------------ | ||
|
|
||
| /** | ||
| * Ensure the `googletag` stub exists on `window`. | ||
| * | ||
| * This mirrors the official GPT bootstrap snippet: | ||
| * ```js | ||
| * window.googletag = window.googletag || {}; | ||
| * googletag.cmd = googletag.cmd || []; | ||
| * ``` | ||
| * By running before the publisher's own snippet we can patch `cmd` early. | ||
| */ | ||
| function ensureGoogleTagStub(win: GptWindow): Partial<GoogleTag> { | ||
| const tag = (win.googletag = win.googletag ?? {}); | ||
| tag.cmd = tag.cmd ?? []; | ||
| return tag; | ||
| } | ||
|
|
||
| /** | ||
| * Wrap a queued GPT callback to add instrumentation and future hook points. | ||
| * | ||
| * Today the wrapper only logs; as the integration matures it will inject | ||
| * synthetic ID targeting and consent gates. | ||
| */ | ||
| function wrapCommand(fn: () => void): () => void { | ||
| return () => { | ||
| try { | ||
| fn(); | ||
| } catch (err) { | ||
| log.error('GPT shim: queued command threw', err); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Patch `googletag.cmd` so every pushed callback runs through [`wrapCommand`]. | ||
| * | ||
| * Preserves the existing `tag.cmd` array identity so that GPT's own custom | ||
| * `cmd.push` behaviour (immediate execution when the library is already | ||
| * loaded) is not lost. The original `push` is saved and delegated to after | ||
| * wrapping each callback. | ||
| * | ||
| * Already-queued callbacks are re-wrapped in place so GPT processes them | ||
| * through our wrapper when it drains the queue. | ||
| */ | ||
| function patchCommandQueue(tag: Partial<GoogleTag>): void { | ||
| // Ensure the queue exists. | ||
| if (!Array.isArray(tag.cmd)) { | ||
| tag.cmd = []; | ||
| } | ||
|
|
||
| const queue = tag.cmd; | ||
|
|
||
| // Guard against double-patching (idempotent install). | ||
| if ((queue as { __tsPushed?: boolean }).__tsPushed) { | ||
| log.debug('GPT shim: command queue already patched, skipping'); | ||
| return; | ||
| } | ||
|
|
||
| const originalPush = queue.push.bind(queue); | ||
|
|
||
| // Override push on the *existing* array — preserves object identity so | ||
| // GPT (if already loaded) keeps its reference. | ||
| queue.push = function (...callbacks: Array<() => void>): number { | ||
| const wrapped = callbacks.map(wrapCommand); | ||
| return originalPush(...wrapped); | ||
| }; | ||
|
|
||
| // Mark as patched to prevent double-wrapping. | ||
| (queue as { __tsPushed?: boolean }).__tsPushed = true; | ||
|
|
||
| // Re-wrap any callbacks that were queued before we patched. | ||
| for (let i = 0; i < queue.length; i++) { | ||
| queue[i] = wrapCommand(queue[i]); | ||
| } | ||
|
|
||
| log.debug('GPT shim: command queue patched', { pendingCommands: queue.length }); | ||
| } | ||
|
|
||
| /** | ||
| * Install the GPT integration shim. | ||
| * | ||
| * Sets up the script guard for dynamic script interception and patches the | ||
| * `googletag.cmd` command queue. | ||
| */ | ||
| export function installGptShim(): boolean { | ||
| if (typeof window === 'undefined') { | ||
| return false; | ||
| } | ||
|
|
||
| const win = window as GptWindow; | ||
|
|
||
| // Install DOM interception guard first so any dynamic GPT script insertions | ||
| // are rewritten before the browser fetches them. | ||
| installGptGuard(); | ||
|
|
||
| const tag = ensureGoogleTagStub(win); | ||
| patchCommandQueue(tag); | ||
|
|
||
| log.info('GPT shim installed'); | ||
| return true; | ||
| } | ||
|
|
||
| // Register the activation function on `window` so the server-injected inline | ||
| // script can call it explicitly. The server emits: | ||
| // <script>window.__tsjs_gpt_enabled=true; | ||
| // window.__tsjs_installGptShim&&window.__tsjs_installGptShim();</script> | ||
| // Because that inline <script> runs *after* the unified bundle has evaluated, | ||
| // the function is guaranteed to be available by the time the inline script | ||
| // executes. This avoids a race where the module-scope auto-init would check | ||
| // `__tsjs_gpt_enabled` before the flag is set. | ||
| if (typeof window !== 'undefined') { | ||
| (window as Record<string, unknown>).__tsjs_installGptShim = installGptShim; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.