npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

universal-ad-loader

v0.5.0

Published

Loader pubblicitario universale: un tag per sito, configurazione centralizzata, waterfall tra provider e consenso TCF. Componenti per React, Next.js, Vue e Astro.

Readme

UAL — Universal Ad Loader NPM version Downloads Node version Bundle size License

One tag per site. It handles slots, centralized configuration, TCF consent, lazy loading, waterfalls across providers (adapters), sandboxed rendering, viewability and events. ~10 KB gzip.

Installing on a site

<script async src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ual.min.js"
        data-config="https://adcdn.yourdomain.net/config/site_123.json"></script>

<div data-ad-slot="top"></div>
<div data-ad-slot="sidebar" data-ad-params='{"zone":7}'></div>
  • data-ad-slot is the slot name in the configuration. The same name can appear more than once (e.g. in-feed).
  • data-ad-params (optional) overrides the provider's params for that instance.
  • Divs added later (SPA, infinite scroll) are detected automatically. On a route change, call ual.pageView().

Inline configuration (no JSON file). Instead of data-config, the configuration can be passed as an object in the page. The cmd.push block can go before or after the loader tag:

<script>
  window.ual = window.ual || { cmd: [] };
  ual.cmd.push(function (u) {
    u.init({
      site: 'site_123',
      providers: { main: { adapter: 'json', endpoint: 'https://ads.yourdomain.net/v1/decide' } },
      slots: { top: { sizes: [[728, 90]], providers: ['main'] } }
    });
  });
</script>
<script async src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ual.min.js"></script>

<div data-ad-slot="top"></div>
  • Use either data-config or init(...), not both: a second init is ignored with a warning.
  • The configuration lives in the page HTML, so changing it means redeploying the page (with a JSON on the CDN you just replace the file). u.init('https://.../site_123.json') also works if you want to choose the URL at runtime.
  • An inline script needs 'unsafe-inline' or a nonce in the page's CSP; with a strict CSP prefer the external JSON.
  • Components (React, Next.js, Vue, Astro): the same applies, and inline is already the default. The config prop takes an object (inline) or the URL of a JSON; Astro's UalBundled writes the object into an application/json block, which works even with a strict CSP. See docs/libreria.md.

Where the files live: the loader is served for free by jsDelivr straight from the npm package (nothing to upload; pin the version in the URL, as above). Only the configuration JSON, one per site, goes on your own CDN with the right headers: see docs/cdn.md.

Configuration (JSON served from the CDN)

See examples/site_demo.json. Main fields:

| Field | Description | |---|---| | site | Site ID, sent to the adapters | | consent | { mode:'tcf'\|'none', timeoutMs, requiredPurposes:[1], vendorId } | | lazy | { enabled, fetchMargin:'200px' }. The slot is requested when it comes within that distance of the viewport | | viewability | { threshold:0.5, durationMs:1000 } (MRC standard) | | collapseEmpty | hides the slot if no provider fills it. A slot already on screen is hidden when it leaves the screen, not at once (no layout jump) | | providerTimeoutMs | default timeout per provider | | maxConcurrentLoads | creatives loading at the same time (default 4, 0 = no limit); the others wait, the ones closest to the viewport first. Does not apply to adapters that render by themselves (gpt, adsense, revive-async) | | renderTimeoutMs | how long a creative may take to load (default 10000). Until it is loaded the iframe is hidden and no impression is counted; after the timeout the slot is empty | | frameUrl | URL of dist/frame.html on a dedicated domain, for strict CSP (see below) | | targeting | page-level key-values sent to all adapters | | providers | { id: { adapter:'json'\|'iframe'\|'revive'\|'revive-async'\|'gpt'\|'adsense'\|'house', consent:'optional'\|'required'\|'contextual', timeoutMs, ...adapter options } } | | slots | { name: { sizes \| sizeMapping, providers:[...waterfall], label, minHeight, lazy, collapseEmpty, refreshSec, maxRefresh, enabled } } | | pageRules | [{ match:'^/on-air', disable:[...], enable:[...], targeting:{}, slots:{ override } }] |

Waterfall: a slot's providers is an ordered list ("house" or { "id":"main", "params":{...} }). If the first one does not fill the slot, the next one is tried. At each level, the slots that become ready together are grouped into a single request per provider.

Consent per provider (providers.X.consent):

| Value | Behavior | |---|---| | optional (default) | Waits for the CMP response (up to consent.timeoutMs) and receives the consent as it is | | required | Like optional, but if consent is missing the provider is skipped and the next level is tried (e.g. a contextual house fallback) | | contextual | Does not wait for the CMP: starts immediately and receives the consent known at that moment (often granted:false). For contextual requests with no cookies or IDs |

Consent is followed for the whole life of the page: if the CMP shows up late (up to consent.lateWatchMs, default 30 s) or the user changes their choice, UAL emits the consent event and, when it switches to granted:true, reloads the slots that had skipped a required provider.

Included adapters

| Adapter | Use | Detects empty? | |---|---|---| | json | Your ad server: batch POST to endpoint (contract below) | Yes | | iframe | Any URL that returns the banner (work.php?n=..&size=..) with {params.x}, {width}, {cb}… templates | No (treated as filled) | | revive | Revive Adserver via afr.php (iframe) | No | | revive-async | Revive via asyncjs.php + <ins> | Yes (observes the DOM) | | gpt | Google Ad Manager, SRA with disableInitialLoad + refresh | Yes (slotRenderEnded) | | adsense | AdSense as backfill | Yes (data-ad-status) | | house | Creatives in the config, weighted pick by slot/device/date | Yes |

The json adapter contract

Request POST {endpoint}:

{
  "site": "site_123",
  "page": { "url": "...", "path": "/", "ref": "...", "title": "..." },
  "device": "desktop", "viewport": { "w": 1280, "h": 900 },
  "targeting": { "section": "onair" },
  "consent": { "gdprApplies": true, "tcString": "...", "granted": true },
  "slots": [ { "id": "top#1", "name": "top", "sizes": [[728,90]], "params": { "zone": 1 } } ]
}

Response (200, or 204 if empty):

{ "ads": [ {
  "slotId": "top#1", "type": "image", "src": "https://cdn/.../b.webp",
  "width": 728, "height": 90, "clickUrl": "https://ads/c?t=SIGNED",
  "trackers": { "impression": ["https://ads/i?t=..."], "viewable": ["https://ads/v?t=..."], "click": [] }
} ] }

type: image (src + clickUrl), html (markup, clickTag available), url (external iframe). Slots with no entry fall through to the next provider.

Rendering and creative API

image/html creatives run in a srcdoc iframe with a sandbox without allow-same-origin (opaque origin): they cannot read the page, its cookies or its DOM. Inside the iframe the following are available:

clickTag                   // = clickUrl
UALExt.click()             // tracks the click and opens clickTag
UALExt.expand(728, 300)    // resizes (max 2000px)
UALExt.collapse()          // back to the original size
UALExt.close()             // closes and hides the slot
UALExt.state()             // { inViewport, pageHidden }: is the ad on screen, is the tab hidden
UALExt.onState(fn)         // called on every change (pause animations or video when not visible)
UALExt.onResizeDenied(fn)  // called with { reason } when a resize was refused

UALExt.resize is limited like AMP's embed-size: one request every 500 ms, and an ad that would grow while on screen is refused (it would push the content the reader is looking at). UALExt.expand (a user gesture), shrinking, ads below the fold and ads inside a fixed container (sticky) are always allowed.

The impression tracker and the slotRendered event fire when the creative has loaded, not when it is inserted in the page. The iframe stays hidden until then; if it does not load within renderTimeoutMs no impression is counted. Messages are accepted only from the slot's own iframe (checked on event.source).

Creative validation. Every ad received from an adapter goes through a check before rendering; if it is not valid it is discarded (log + error event) and the next provider is tried:

  • width and height are required, integers between 1 and 2000.
  • src (image), url (url), clickUrl and all trackers: only http:/https: (and data:image/ for src). No javascript:.
  • Sandbox: never allow-same-origin for image/html; never allow-top-navigation (a creative cannot redirect the page; target=_blank links open a popup). For type:'url', allow-same-origin is kept (legacy servers need it) only if the URL has a different origin from the page; if it is the same origin it is removed. A creative's sandbox override is filtered with the same rules.

Native, video and sticky

Besides image, html and url, an ad can be native or video.

{ "slotId": "feed#1", "type": "native", "clickUrl": "https://ads/c?t=SIGNED",
  "native": { "title": "A headline", "body": "Two lines of text", "sponsoredBy": "ACME",
              "cta": "Learn more", "image": { "src": "https://cdn/.../main.jpg", "width": 1200, "height": 628 },
              "icon": "https://cdn/.../icon.png", "layout": "card" },
  "trackers": { "impression": ["https://ads/i?t=..."], "viewable": ["https://ads/v?t=..."] } }

The assets are plain data (never HTML). UAL draws them in the page inside a Shadow DOM, so the card inherits the site's font and colour; a "Sponsored" label is always shown. Style it with CSS variables on the slot: --ual-native-bg, --ual-native-border, --ual-native-radius, --ual-native-accent, --ual-native-accent-text. Title is limited to 150 characters, body to 300 (longer text is cut).

{ "slotId": "article#1", "type": "video", "src": "https://cdn/.../ad.mp4", "mime": "video/mp4", "poster": "https://cdn/.../p.jpg",
  "width": 640, "height": 360, "clickUrl": "https://ads/c?t=SIGNED",
  "trackers": { "impression": ["..."], "viewable": ["..."], "start": ["..."],
                "quartile": { "firstQuartile": ["..."], "midpoint": ["..."], "thirdQuartile": ["..."], "complete": ["..."] } } }

The video starts muted when at least half of it is visible and pauses when it is not; the visitor can turn the sound on. Each tracker fires once. The videoEvent event reports start, firstQuartile, midpoint, thirdQuartile and complete. Video is counted as viewable after 2 s in view (set viewability.durationMs on the slot to change it).

UALExt.track(name) lets an HTML creative fire a named tracker declared in trackers.custom ({ "engaged": ["https://ads/e?t=..."] }); names that were not declared are ignored.

slots.X.sticky (true, "top", "bottom" or { "position": "bottom", "maxHeightPct": 25 }) anchors a small banner to the screen edge with a 50x50 close button. It only applies if the ad is at most 25% of the screen height (IAB); set maxHeightPct up to 30 for the Better Ads limit. Larger ads stay in the page. An ad wider than the screen is scaled down to fit edge to edge.

Flexible sizes (IAB)

slots.X.ratio ("8:1", "6:1", "1:1", "9:16"…) and slots.X.maxWidth (px) reserve the space before the ad arrives (no layout jump). The ad server can add flex to the response:

{ "type": "html", "html": "…", "width": 600, "height": 75,
  "flex": { "ratio": "8:1", "minWidth": 600, "maxWidth": 1200, "fit": "scale" } }

fit: scale (default) scales the creative to the container width, fill lets the creative fill the container by itself, native keeps the natural size, centred and never enlarged. The ad follows resizes and rotation. Without ratio and flex nothing changes.

JavaScript API

window.ual = window.ual || { cmd: [] };
ual.cmd.push(function (u) {
  u.on('slotRendered', (e) => console.log(e.slot, e.provider, e.width, e.height));
  u.on('slotEmpty', (e) => {});
  u.on('slotViewable', (e) => {});
  u.on('slotClick', (e) => {});
  u.on('error', (e) => {});
  u.setTargeting({ author: 'mario' });
});
// Without data-config: ual.cmd.push(u => u.init({ ...config }))  or  u.init('https://.../site.json')
ual.refresh(['top']);   // reloads slots (all of them if called without arguments)
ual.pageView();         // SPA: new page
ual.getSlots(); ual.getConsent();
ual.isInitialized();    // true if init has already been started (even if not finished yet)
ual.whenReady();        // the init promise, or null if never started

setTargeting also works before init (inside ual.cmd.push), stays valid after pageView(), and a null value removes the key. The pageRules targeting is recomputed on every page. The gpt adapter reapplies it on every request and removes keys that are no longer present.

The script attribute can be named data-config or data-ual-config (equivalent; the second is also read when the script was inserted dynamically by a framework).

Debug: ?ual_debug=1 in the URL, or localStorage.ual_debug = '1'.

With Astro, Next.js, React, Vue and Node

UAL is a browser script (it does not run in Node). For sites with a build step there is also the package: server-safe import, components for React, Next.js, Vue and Astro, TypeScript types (defineConfig). See docs/libreria.md. The universal-ad-loader package is published on npm (npm i universal-ad-loader).

import { UalProvider, AdSlot } from 'universal-ad-loader/next';   // or /react, /vue; for Astro use the files in astro/

<UalProvider config={config}>   {/* starts after hydration, handles page changes */}
  <AdSlot name="top" minHeight={90} />
</UalProvider>

If you use the tag with a framework instead, things verified with a server-rendered React app:

  • Load the loader after hydration (next/script with strategy="afterInteractive", or a useEffect). If it starts earlier, UAL inserts the banner into the div before React attaches: Hydration failed error (even with suppressHydrationWarning) and the banner is requested twice. The components avoid this on their own.
  • Client-side page change: new slots register themselves, but pageRules and targeting are only recomputed with ual.pageView().
  • Do not import dist/ual.js in server code: it uses window at load time (ReferenceError in Node). The package core (dist/index.*) is safe, though.
  • Strict CSP: creatives inherit the page's CSP (unless you use frameUrl, below). Tested: without 'unsafe-inline' for scripts and styles the banner shows up but UALExt and the tracked click do not work; the same goes for nonces with 'strict-dynamic'.

Dedicated frame (strict CSP). Copy dist/frame.html to a domain of yours (for example next to the config on your CDN) and set frameUrl: "https://cdn.example.com/ual/frame.html". html and image creatives are then written into that page (through postMessage, still in a sandbox without allow-same-origin), so they do not inherit the CSP of the publisher's page: UALExt and the tracked click work. The publisher's CSP must allow that domain in frame-src, and the frame page itself must be served without a restrictive CSP. Do not use jsDelivr for this file: it does not serve HTML as a page.

Sandbox. An ad server response cannot remove the sandbox: sandbox: "none" on a cross-origin url ad is ignored unless the json provider has allowUnsandboxed: true.

Guide with examples and a CSP table: configurator, /docs/ page.

Other documents

  • docs/esempio.md: complete client site (config, flow, minimal decide endpoint).
  • docs/cdn.md: which files to put on the CDN (loader and configuration), headers, structure, what is not needed and how to update.
  • docs/libreria.md: UAL as a package (React/Next/Vue/Astro components, types, server-safe core, how it is verified).
  • docs/ad-server-esistenti.md: how to connect AdManager, Banner Exchange Pro, Banner Exchange and the legacy PHP systems with the iframe adapter, with limits and checks.
  • schema/ual-config.schema.json: JSON Schema of the configuration.
  • The web configurator (../ual-configurator) has an HTML guide with examples that open in the editor.

Custom adapters

ual.cmd.push(u => u.registerAdapter('myserver', {
  init(providerCfg, ctx) {},                       // optional, once per provider
  // A) the adapter returns the ads and UAL renders them in the sandbox:
  async request(slots, providerCfg, ctx) {         // slots: [{id,name,sizes,params,el}]
    return { [slots[0].id]: { type:'image', src:'...', width:300, height:250, clickUrl:'...' } };
  },
  // B) or the adapter renders by itself inside slot.el:
  // async fill(slots, providerCfg, ctx) { return { [id]: { filled:true, width, height } } },
  destroy(slot, providerCfg) {},                   // optional
}));

ctx contains site, page, device, viewport, targeting, consent. To register a custom adapter before the automatic init, put ual.cmd.push(...) before the loader tag.

Build and tests

npm ci                          # base dependencies (~120 MB)
npm ci --prefix test/heavy      # only for the framework tests: Next.js and Astro (~620 MB)
npx playwright install chromium # once, for the browser tests
npm test                        # build + all suites, about 2 minutes

To work on one part at a time (this is what CI does, in parallel jobs):

| Command | What it runs | Needs | |---|---|---| | npm run lint | oxlint on the sources | base dependencies only | | npm run test:node | test/runtime.mjs | 0.5: load queue and priority, impression at load, resize limits, collapse without layout jump, state sent to the creative, dedicated frame under a strict CSP, sandbox: "none" | | test/package.mjs | base dependencies only (no browser) | | npm run test:browser | test/run.mjs, test/regression.mjs and test/formats.mjs | + Chromium | | npm run test:frameworks | test/wrappers.mjs | + test/heavy and Chromium |

Every suite also writes a JUnit report to test-results/ (CI shows it in the Tests tab).

| Suite | What it verifies | |---|---| | test/run.mjs | loader e2e with a fake ad server and a fake CMP: batching per provider, waterfall to house, lazy load, sizeMapping, consent, pageRules, trackers, expand, sandbox | | test/regression.mjs | render security, setTargeting, late CMP, contextual providers, slots moved/closed in the DOM, refresh, pageView, the gpt adapter (with a googletag stub), the iframe adapter with the existing systems | | test/formats.mjs | native, video (muted autoplay when visible, pause, quartiles once each, sound button), UALExt.track and sticky, in Chromium with a real video file; plus the validation rules | | test/package.mjs | the package: import in Node (ESM and CJS) without window, server rendering of React and Vue, exports map, tarball contents (npm pack), types (correct usages compile, wrong ones fail) | | test/wrappers.mjs | the components in a real browser, with server rendering and delayed hydration: React (in the bundle, from CDN, Next version), Vue, Next.js 16 (App Router, production build) and Astro 7 (View Transitions); plus a check that demonstrates the problem the components avoid |

The adsense and revive-async adapters are written against the public APIs but are not tested: they need to be tried on your own accounts and servers. gpt too must be tried with a real Google Ad Manager: the stub verifies UAL's logic, not GPT's behavior. Nuxt, Remix and React Router have not been run.

Notes

  • Consent: on client sites your ad server is a third-party vendor. Without consent, send only contextual requests (no cookies or IDs). vendorId is needed if your server is registered in the IAB GVL. Have the privacy setup reviewed by a lawyer.
  • Automatic refresh (refreshSec): only if the slot is on screen and the tab is visible. GPT and AdSense have their own refresh policies.
  • CLS: use minHeight on above-the-fold slots.