3 Commits

Author SHA1 Message Date
7201bf9845 playworks converter 2026-05-28 14:30:38 +08:00
2921d4d384 playworks converter 2026-05-28 14:23:48 +08:00
cce30c0729 update playworks checker 2026-05-28 14:17:26 +08:00
22 changed files with 612 additions and 53 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

53
package-lock.json generated
View File

@@ -1,15 +1,17 @@
{
"name": "hpl-toolbox",
"version": "0.1.0",
"version": "0.1.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "hpl-toolbox",
"version": "0.1.0",
"version": "0.1.6",
"license": "UNLICENSED",
"devDependencies": {
"@types/node": "^20.0.0",
"@types/vscode": "^1.85.0",
"playwright": "^1.60.0",
"typescript": "^5.4.0"
},
"engines": {
@@ -33,6 +35,53 @@
"dev": true,
"license": "MIT"
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/playwright": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz",
"integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.60.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz",
"integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",

View File

@@ -131,6 +131,7 @@
"devDependencies": {
"@types/node": "^20.0.0",
"@types/vscode": "^1.85.0",
"playwright": "^1.60.0",
"typescript": "^5.4.0"
}
}

View File

@@ -0,0 +1,177 @@
import { chromium } from 'playwright';
import { createServer } from 'node:http';
import { execFileSync } from 'node:child_process';
import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
const root = process.cwd();
const dogCatRoot = process.env.DOGCAT_ROOT || path.join(root, 'aiAssets', 'DogCat3');
const waitMs = Number(process.env.RUNTIME_WAIT_MS || 9000);
const mraidStub = `
window.mraid = window.mraid || {
getState: function(){ return 'default'; },
isViewable: function(){ return true; },
addEventListener: function(name, cb){ if (name === 'ready') setTimeout(cb, 0); },
removeEventListener: function(){},
open: function(url){ console.log('[stub mraid.open]', url); },
close: function(){ console.log('[stub mraid.close]'); },
supports: function(){ return false; }
};
`;
const exitApiStub = `
window.ExitApi = window.ExitApi || {
exit: function(){ console.log('[stub ExitApi.exit]'); }
};
`;
async function collectCases(tempDir) {
const cases = [];
const networkFolders = [
'Applovin',
'Facebook',
'Ironsource',
'Moloco',
'Unity',
'GoogleAds',
'Mintegral',
'Vungle',
];
for (const name of networkFolders) {
const dir = path.join(dogCatRoot, name);
if (!existsSync(dir)) continue;
const entries = await readdir(dir);
const htmlName = entries.find((entry) => /\.html?$/i.test(entry));
if (htmlName) {
cases.push([name, await readFile(path.join(dir, htmlName))]);
continue;
}
const zipName = entries.find((entry) => /\.zip$/i.test(entry));
if (!zipName) continue;
const zip = path.join(dir, zipName);
const out = path.join(tempDir, name);
execFileSync('powershell', [
'-NoProfile',
'-Command',
`Expand-Archive -LiteralPath '${zip.replaceAll("'", "''")}' -DestinationPath '${out.replaceAll("'", "''")}' -Force`,
], { stdio: 'ignore' });
const expanded = await readdir(out);
const indexName = expanded.find((entry) => entry.toLowerCase() === 'index.html');
if (indexName) cases.push([name, await readFile(path.join(out, indexName))]);
}
return cases;
}
async function startServer(cases) {
const html = new Map(cases.map(([name, body]) => [`/${name}/index.html`, body]));
const server = createServer((req, res) => {
const url = new URL(req.url || '/', 'http://127.0.0.1');
if (url.pathname.endsWith('/mraid.js')) {
res.writeHead(200, { 'content-type': 'application/javascript' });
res.end(mraidStub);
return;
}
if (url.pathname.endsWith('/exitapi.js')) {
res.writeHead(200, { 'content-type': 'application/javascript' });
res.end(exitApiStub);
return;
}
const body = html.get(url.pathname);
if (body) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(body);
return;
}
res.writeHead(404, { 'content-type': 'text/plain' });
res.end('not found');
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
return {
baseUrl: `http://127.0.0.1:${server.address().port}`,
close: () => new Promise((resolve) => server.close(resolve)),
};
}
function simplifyUrl(url) {
return url.replace(/^https?:\/\/127\.0\.0\.1:\d+\//, '/');
}
async function runCase(browser, baseUrl, name) {
const page = await browser.newPage({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true });
const issues = [];
page.on('pageerror', (error) => {
issues.push({ type: 'pageerror', text: error.stack || error.message });
});
page.on('console', (message) => {
if (['error', 'assert'].includes(message.type())) {
const location = message.location();
const suffix = location.url ? ` @ ${simplifyUrl(location.url)}:${location.lineNumber}:${location.columnNumber}` : '';
issues.push({ type: `console.${message.type()}`, text: `${message.text()}${suffix}` });
}
});
page.on('requestfailed', (request) => {
issues.push({
type: 'requestfailed',
text: `${simplifyUrl(request.url())} :: ${request.failure()?.errorText || 'failed'}`,
});
});
page.on('response', (response) => {
if (response.status() >= 400) {
issues.push({
type: `http.${response.status()}`,
text: simplifyUrl(response.url()),
});
}
});
await page.goto(`${baseUrl}/${name}/index.html`, { waitUntil: 'domcontentloaded', timeout: 20000 });
await page.waitForTimeout(waitMs);
const bodyText = await page.locator('body').evaluate((body) => body.innerText.slice(0, 2000)).catch(() => '');
const canvasCount = await page.locator('canvas').count().catch(() => 0);
const title = await page.title().catch(() => '');
await page.close();
return { issues, canvasCount, title, bodyText };
}
async function main() {
const tempDir = await mkdtemp(path.join(tmpdir(), 'dogcat3-playwright-'));
let server;
let browser;
try {
const cases = await collectCases(tempDir);
server = await startServer(cases);
browser = await chromium.launch({ channel: 'msedge', headless: true });
for (const [name] of cases) {
const result = await runCase(browser, server.baseUrl, name);
console.log(`\n## ${name}`);
console.log(`canvas=${result.canvasCount}`);
if (result.title) console.log(`title=${result.title}`);
if (!result.issues.length) {
console.log('No page errors, console errors, failed requests, or HTTP 4xx/5xx responses captured.');
} else {
for (const issue of result.issues) {
console.log(`- ${issue.type}: ${issue.text.replace(/\s+/g, ' ').slice(0, 700)}`);
}
}
if (result.bodyText && /error|exception|cannot|failed/i.test(result.bodyText)) {
console.log(`body_error_text=${result.bodyText.replace(/\s+/g, ' ').slice(0, 700)}`);
}
}
} finally {
if (browser) await browser.close();
if (server) await server.close();
await rm(tempDir, { recursive: true, force: true });
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -95,8 +95,8 @@ export function openPlayworksConverter(_context: vscode.ExtensionContext) {
}
const ZIPPED_NETWORKS = new Set(['gg', 'vu', 'mtg']);
const SUPPORTED_NETWORKS = new Set(['al', 'is', 'fb', 'gg', 'mo', 'vu', 'mtg', 'tt']);
const MRAID_NETWORKS = new Set(['al', 'is']);
const SUPPORTED_NETWORKS = new Set(['al', 'is', 'fb', 'gg', 'mo', 'vu', 'mtg', 'un', 'tt']);
const MRAID_NETWORKS = new Set(['al', 'is', 'un']);
const NETWORK_OUTPUT_FOLDERS: Record<string, string> = {
al: 'Applovin',
is: 'Ironsource',
@@ -105,6 +105,7 @@ const NETWORK_OUTPUT_FOLDERS: Record<string, string> = {
mo: 'Moloco',
vu: 'Vungle',
mtg: 'Mintegral',
un: 'Unity',
tt: 'TikTok',
};
@@ -149,15 +150,15 @@ async function convertNetwork(html: string, opts: ConvertOptions, network: strin
}
function transformHtml(html: string, network: string): string {
let result = html;
let result = sanitizePlayworksHtml(html);
// Inject into </head>: lifecycle stubs only (must register luna:build listener
// BEFORE the Playworks bundle so our handler fires first), then any network SDK script.
// Console restore stays at end-of-body — it must run AFTER the bundle overrides console.
result = removeNetworkSdkScripts(result, network);
result = removeNetworkSdkScripts(result);
let headInject = buildLifecycleScript();
if (MRAID_NETWORKS.has(network)) {
headInject += '<script src="mraid.js"></script>';
headInject += '<script src="mraid.js"></script>' + buildMraidComplianceScript();
} else if (network === 'gg') {
headInject += '<script src="exitapi.js"></script>';
}
@@ -175,16 +176,60 @@ function transformHtml(html: string, network: string): string {
// Replace the CTA script
result = replaceCTAScript(result, network);
return finalizeNetworkHtml(result, network);
}
function sanitizePlayworksHtml(html: string): string {
let result = cleanupPlayworksHtml(html);
return removeNetworkSdkScripts(result);
}
function cleanupPlayworksHtml(html: string): string {
let result = html;
result = trimAfterFirstHtmlClose(result);
result = result.replace(/<script\b[^>]*>[\s\S]*?insertYourRemoteDebuggingTokenHere[\s\S]*?<\/script>\s*/gi, '');
result = result.replace(/https:\/\/mrdoob\.github\.io\/stats\.js\/build\/stats\.min\.js/gi, 'data:text/javascript,');
result = result.replace(/\s+crossorigin(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?/gi, '');
result = result.replace(/\s+type\s*=\s*["']module["']/gi, '');
result = result.replace(/\bconsole\.error\s*\(/g, 'console.warn(');
return result;
}
function removeNetworkSdkScripts(html: string, network: string): string {
function trimAfterFirstHtmlClose(html: string): string {
const idx = html.search(/<\/html\s*>/i);
if (idx === -1) return html;
const close = html.match(/<\/html\s*>/i);
return close ? html.slice(0, idx + close[0].length) : html;
}
function finalizeNetworkHtml(html: string, network: string): string {
let result = cleanupPlayworksHtml(html);
result = dedupeScriptSrc(result, 'mraid.js', MRAID_NETWORKS.has(network));
result = dedupeScriptSrc(result, 'exitapi.js', network === 'gg');
return result;
}
function removeNetworkSdkScripts(html: string): string {
let result = html;
if (MRAID_NETWORKS.has(network)) {
result = result.replace(/<script\b[^>]*\bsrc\s*=\s*["']mraid\.js["'][^>]*>\s*<\/script>\s*/gi, '');
for (const src of ['mraid.js', 'exitapi.js']) {
const escaped = src.replace('.', '\\.');
result = result.replace(new RegExp(`<script\\b[^>]*\\bsrc\\s*=\\s*["']${escaped}["'][^>]*>\\s*<\\/script>\\s*`, 'gi'), '');
}
if (network === 'gg') {
result = result.replace(/<script\b[^>]*\bsrc\s*=\s*["']exitapi\.js["'][^>]*>\s*<\/script>\s*/gi, '');
return result;
}
function dedupeScriptSrc(html: string, src: string, shouldExist: boolean): string {
const escaped = src.replace('.', '\\.');
let seen = false;
let result = html.replace(new RegExp(`<script\\b[^>]*\\bsrc\\s*=\\s*["']${escaped}["'][^>]*>\\s*<\\/script>\\s*`, 'gi'), (match) => {
if (shouldExist && !seen) {
seen = true;
return `<script src="${src}"></script>`;
}
return '';
});
if (shouldExist && !seen) {
result = injectBeforeHeadClose(result, `<script src="${src}"></script>`);
}
return result;
}
@@ -273,6 +318,28 @@ function buildLifecycleScript(): string {
].join('');
}
function buildMraidComplianceScript(): string {
return [
'<script>(function(){',
'var m=null,scene=null,viewable=true,exposed=true,volume=null;',
'function get(){return window.mraid||m;}',
'function emit(name,detail){try{window.dispatchEvent(new CustomEvent(name,{detail:detail}));}catch(e){}}',
'function apply(){emit("hpl:mraid:visibility",{viewable:viewable,exposed:exposed,hidden:!viewable||!exposed});if(scene&&scene.sound&&typeof scene.sound.setMute==="function")scene.sound.setMute(!viewable||!exposed);}',
'function onViewable(v){viewable=!!v;apply();}',
'function onExposure(p){if(typeof p==="number")exposed=p>0;apply();}',
'function onVolume(v){if(typeof v==="number"){volume=v/100;emit("hpl:mraid:volume",volume);if(scene&&scene.sound&&typeof scene.sound.setVolume==="function")scene.sound.setVolume(volume);}}',
'function add(name,fn){var x=get();try{if(x&&typeof x.addEventListener==="function")x.addEventListener(name,fn);}catch(e){}}',
'function unload(){try{if(typeof mraid!=="undefined"&&typeof mraid.unload==="function")mraid.unload();}catch(e){}}',
'window.__hplMraidUnload=unload;',
'function setup(){var x=get();if(!x||setup.done)return;setup.done=true;m=x;try{if(typeof mraid!=="undefined"&&typeof mraid.isViewable==="function")viewable=!!mraid.isViewable();else if(typeof x.isViewable==="function")viewable=!!x.isViewable();}catch(e){}try{if(typeof mraid!=="undefined"&&typeof mraid.addEventListener==="function"){mraid.addEventListener("error",function(message,action){console.warn("[MRAID error]",{message:message,action:action});});mraid.addEventListener("stateChange",function(state){console.log("[MRAID stateChange]",state);});mraid.addEventListener("exposureChange",onExposure);mraid.addEventListener("viewableChange",onViewable);mraid.addEventListener("audioVolumeChange",onVolume);apply();return;}}catch(e){}add("error",function(message,action){console.warn("[MRAID error]",{message:message,action:action});});add("stateChange",function(state){console.log("[MRAID stateChange]",state);});add("exposureChange",onExposure);add("viewableChange",onViewable);add("audioVolumeChange",onVolume);apply();}',
'function ready(){var x=get();if(!x)return false;try{if(typeof mraid!=="undefined"&&typeof mraid.getState==="function"&&mraid.getState()==="loading"){mraid.addEventListener("ready",setup);return true;}if(typeof x.getState==="function"&&x.getState()==="loading"){add("ready",setup);return true;}}catch(e){}setup();return true;}',
'window.__hplMraidBindScene=function(s){scene=s;apply();if(typeof volume==="number"&&scene&&scene.sound&&typeof scene.sound.setVolume==="function")scene.sound.setVolume(volume);};',
'if(!ready()){var end=Date.now()+500;(function poll(){if(ready()||Date.now()>end)return;setTimeout(poll,50);})();}',
'setTimeout(setup,2000);',
'})();</script>',
].join('');
}
function buildCTAScript(network: string): string {
const urlSetup = `n=n||window.$environment.packageConfig.iosLink,i=i||window.$environment.packageConfig.androidLink;var o=/iphone|ipad|ipod|macintosh/i.test(window.navigator.userAgent.toLowerCase())?n:i;`;
// gameClose must fire before every redirect
@@ -282,6 +349,7 @@ function buildCTAScript(network: string): string {
switch (network) {
case 'al':
case 'is':
case 'un':
// MRAID — mraid.js injected in <head>
ctaLogic = `${closeCall}if(typeof mraid!=="undefined"&&typeof mraid.open==="function"){var s=typeof mraid.getState==="function"?mraid.getState():"default";if(s!=="loading"){mraid.open(o);return;}}window.open(o,"_blank");`;
break;
@@ -353,6 +421,7 @@ function getHtml(): string {
{ tag: 'mo', label: 'Moloco', note: 'HTML + FbPlayableAd CTA' },
{ tag: 'vu', label: 'Vungle', note: 'ZIP + __VUNGLE__ flag' },
{ tag: 'mtg', label: 'Mintegral', note: 'ZIP + onload="gameReady()"' },
{ tag: 'un', label: 'Unity', note: 'HTML + mraid.js in head' },
{ tag: 'tt', label: 'TikTok', note: 'HTML + __TIKTOK__ flag' },
];

View File

@@ -0,0 +1,93 @@
package main
import (
"archive/zip"
"io"
"os"
"path/filepath"
"strings"
"testing"
)
func TestDogCat3MraidChecker(t *testing.T) {
root := filepath.Join("..", "aiAssets", "DogCat3")
files, err := collectDogCat3MraidTargets(root)
if err != nil {
t.Fatalf("collect targets: %v", err)
}
if len(files) == 0 {
t.Fatalf("no DogCat3 MRAID targets found")
}
for _, file := range files {
t.Run(filepath.Base(file), func(t *testing.T) {
html, displayPath, err := readDogCat3HTML(file)
if err != nil {
t.Fatalf("read target: %v", err)
}
issues := checkMraid(html, displayPath)
if len(issues) == 0 {
return
}
var parts []string
for _, issue := range issues {
parts = append(parts, issue.ID+": "+issue.Title+" ("+issue.Severity+")")
}
t.Fatalf("MRAID checker issues:\n%s", strings.Join(parts, "\n"))
})
}
}
func collectDogCat3MraidTargets(root string) ([]string, error) {
var out []string
for _, folder := range []string{"Applovin", "Ironsource", "Unity"} {
dir := filepath.Join(root, folder)
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := strings.ToLower(entry.Name())
if strings.HasSuffix(name, ".html") || strings.HasSuffix(name, ".htm") || strings.HasSuffix(name, ".zip") {
out = append(out, filepath.Join(dir, entry.Name()))
}
}
}
return out, nil
}
func readDogCat3HTML(file string) (html string, displayPath string, err error) {
if strings.HasSuffix(strings.ToLower(file), ".zip") {
zr, err := zip.OpenReader(file)
if err != nil {
return "", "", err
}
defer zr.Close()
for _, entry := range zr.File {
if strings.EqualFold(entry.Name, "index.html") {
rc, err := entry.Open()
if err != nil {
return "", "", err
}
defer rc.Close()
data, err := io.ReadAll(rc)
if err != nil {
return "", "", err
}
return string(data), file + "#index.html", nil
}
}
return "", "", os.ErrNotExist
}
data, err := os.ReadFile(file)
if err != nil {
return "", "", err
}
return string(data), file, nil
}

View File

@@ -82,6 +82,7 @@ func PlayworksPage(w http.ResponseWriter, r *http.Request) {
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="mo" checked /><span class="net-label">Moloco <span class="net-tag">mo</span></span><span class="net-note">HTML + FbPlayableAd CTA</span></label>
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="vu" checked /><span class="net-label">Vungle <span class="net-tag">vu</span></span><span class="net-note">ZIP + __VUNGLE__ flag</span></label>
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="mtg" checked /><span class="net-label">Mintegral <span class="net-tag">mtg</span></span><span class="net-note">ZIP + onload gameReady</span></label>
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="un" checked /><span class="net-label">Unity <span class="net-tag">un</span></span><span class="net-note">HTML + mraid.js in head</span></label>
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="tt" /><span class="net-label">TikTok <span class="net-tag">tt</span></span><span class="net-note">HTML + __TIKTOK__ flag</span></label>
</div>
</div>
@@ -234,6 +235,12 @@ var playworksExitapiScriptRx = regexp.MustCompile(`(?i)<script\b[^>]*\bsrc\s*=\s
var playworksHeadCloseRx = regexp.MustCompile(`(?i)</head>`)
var playworksBodyOpenRx = regexp.MustCompile(`(?i)<body\b[^>]*>`)
var playworksBodyTagRx = regexp.MustCompile(`(?i)<body\b([^>]*)>`)
var playworksHtmlCloseRx = regexp.MustCompile(`(?i)</html\s*>`)
var playworksRemoteDebugScriptRx = regexp.MustCompile(`(?is)<script\b[^>]*>.*?insertYourRemoteDebuggingTokenHere.*?</script>\s*`)
var playworksStatsURLRx = regexp.MustCompile(`(?i)https://mrdoob\.github\.io/stats\.js/build/stats\.min\.js`)
var playworksCrossoriginRx = regexp.MustCompile(`(?i)\s+crossorigin(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?`)
var playworksTypeModuleRx = regexp.MustCompile(`(?i)\s+type\s*=\s*["']module["']`)
var playworksConsoleErrorRx = regexp.MustCompile(`\bconsole\.error\s*\(`)
func playworksSourceBaseName(sourcePath string) string {
base := strings.TrimSuffix(filepath.Base(sourcePath), filepath.Ext(sourcePath))
@@ -305,6 +312,8 @@ func playworksNetworkOutputFolder(network string) string {
return "Vungle"
case "mtg":
return "Mintegral"
case "un":
return "Unity"
case "tt":
return "TikTok"
default:
@@ -317,12 +326,12 @@ func playworksNeedsZip(network string) bool {
}
func playworksIsMraidNetwork(network string) bool {
return network == "al" || network == "is"
return network == "al" || network == "is" || network == "un"
}
func playworksIsSupportedNetwork(network string) bool {
switch network {
case "al", "is", "fb", "gg", "mo", "vu", "mtg", "tt":
case "al", "is", "fb", "gg", "mo", "vu", "mtg", "un", "tt":
return true
default:
return false
@@ -330,11 +339,10 @@ func playworksIsSupportedNetwork(network string) bool {
}
func transformPlayworksHTML(htmlSrc, network string) string {
result := htmlSrc
result = removePlayworksNetworkScripts(result, network)
result := sanitizePlayworksHTML(htmlSrc)
headInject := buildPlayworksLifecycleScript()
if playworksIsMraidNetwork(network) {
headInject += `<script src="mraid.js"></script>`
headInject += `<script src="mraid.js"></script>` + buildPlayworksMraidComplianceScript()
} else if network == "gg" {
headInject += `<script src="exitapi.js"></script>`
}
@@ -349,23 +357,64 @@ func transformPlayworksHTML(htmlSrc, network string) string {
}
result = replacePlayworksCTAScript(result, network)
return finalizePlayworksNetworkHTML(result, network)
}
func sanitizePlayworksHTML(htmlSrc string) string {
return removePlayworksNetworkScripts(cleanupPlayworksHTML(htmlSrc))
}
func cleanupPlayworksHTML(htmlSrc string) string {
result := trimPlayworksAfterFirstHTMLClose(htmlSrc)
result = playworksRemoteDebugScriptRx.ReplaceAllString(result, "")
result = playworksStatsURLRx.ReplaceAllString(result, "data:text/javascript,")
result = playworksCrossoriginRx.ReplaceAllString(result, "")
result = playworksTypeModuleRx.ReplaceAllString(result, "")
result = playworksConsoleErrorRx.ReplaceAllString(result, "console.warn(")
return result
}
func removePlayworksNetworkScripts(htmlSrc, network string) string {
result := htmlSrc
if playworksIsMraidNetwork(network) {
result = playworksMraidScriptRx.ReplaceAllString(result, "")
func trimPlayworksAfterFirstHTMLClose(htmlSrc string) string {
loc := playworksHtmlCloseRx.FindStringIndex(htmlSrc)
if loc == nil {
return htmlSrc
}
if network == "gg" {
result = playworksExitapiScriptRx.ReplaceAllString(result, "")
return htmlSrc[:loc[1]]
}
func finalizePlayworksNetworkHTML(htmlSrc, network string) string {
result := cleanupPlayworksHTML(htmlSrc)
result = dedupePlayworksScriptSrc(result, "mraid.js", playworksIsMraidNetwork(network))
result = dedupePlayworksScriptSrc(result, "exitapi.js", network == "gg")
return result
}
func removePlayworksNetworkScripts(htmlSrc string) string {
result := playworksMraidScriptRx.ReplaceAllString(htmlSrc, "")
result = playworksExitapiScriptRx.ReplaceAllString(result, "")
return result
}
func dedupePlayworksScriptSrc(htmlSrc, src string, shouldExist bool) string {
rx := regexp.MustCompile(`(?i)<script\b[^>]*\bsrc\s*=\s*["']` + regexp.QuoteMeta(src) + `["'][^>]*>\s*</script>\s*`)
seen := false
result := rx.ReplaceAllStringFunc(htmlSrc, func(match string) string {
if shouldExist && !seen {
seen = true
return `<script src="` + src + `"></script>`
}
return ""
})
if shouldExist && !seen {
result = injectPlayworksBeforeHeadClose(result, `<script src="`+src+`"></script>`)
}
return result
}
func injectPlayworksBeforeHeadClose(htmlSrc, injection string) string {
if playworksHeadCloseRx.MatchString(htmlSrc) {
return playworksHeadCloseRx.ReplaceAllString(htmlSrc, injection+"\n</head>")
loc := playworksHeadCloseRx.FindStringIndex(htmlSrc)
if loc != nil {
return htmlSrc[:loc[0]] + injection + "\n" + htmlSrc[loc[0]:]
}
return injection + "\n" + htmlSrc
}
@@ -489,12 +538,34 @@ func buildPlayworksLifecycleScript() string {
}, "")
}
func buildPlayworksMraidComplianceScript() string {
return strings.Join([]string{
`<script>(function(){`,
`var m=null,scene=null,viewable=true,exposed=true,volume=null;`,
`function get(){return window.mraid||m;}`,
`function emit(name,detail){try{window.dispatchEvent(new CustomEvent(name,{detail:detail}));}catch(e){}}`,
`function apply(){emit("hpl:mraid:visibility",{viewable:viewable,exposed:exposed,hidden:!viewable||!exposed});if(scene&&scene.sound&&typeof scene.sound.setMute==="function")scene.sound.setMute(!viewable||!exposed);}`,
`function onViewable(v){viewable=!!v;apply();}`,
`function onExposure(p){if(typeof p==="number")exposed=p>0;apply();}`,
`function onVolume(v){if(typeof v==="number"){volume=v/100;emit("hpl:mraid:volume",volume);if(scene&&scene.sound&&typeof scene.sound.setVolume==="function")scene.sound.setVolume(volume);}}`,
`function add(name,fn){var x=get();try{if(x&&typeof x.addEventListener==="function")x.addEventListener(name,fn);}catch(e){}}`,
`function unload(){try{if(typeof mraid!=="undefined"&&typeof mraid.unload==="function")mraid.unload();}catch(e){}}`,
`window.__hplMraidUnload=unload;`,
`function setup(){var x=get();if(!x||setup.done)return;setup.done=true;m=x;try{if(typeof mraid!=="undefined"&&typeof mraid.isViewable==="function")viewable=!!mraid.isViewable();else if(typeof x.isViewable==="function")viewable=!!x.isViewable();}catch(e){}try{if(typeof mraid!=="undefined"&&typeof mraid.addEventListener==="function"){mraid.addEventListener("error",function(message,action){console.warn("[MRAID error]",{message:message,action:action});});mraid.addEventListener("stateChange",function(state){console.log("[MRAID stateChange]",state);});mraid.addEventListener("exposureChange",onExposure);mraid.addEventListener("viewableChange",onViewable);mraid.addEventListener("audioVolumeChange",onVolume);apply();return;}}catch(e){}add("error",function(message,action){console.warn("[MRAID error]",{message:message,action:action});});add("stateChange",function(state){console.log("[MRAID stateChange]",state);});add("exposureChange",onExposure);add("viewableChange",onViewable);add("audioVolumeChange",onVolume);apply();}`,
`function ready(){var x=get();if(!x)return false;try{if(typeof mraid!=="undefined"&&typeof mraid.getState==="function"&&mraid.getState()==="loading"){mraid.addEventListener("ready",setup);return true;}if(typeof x.getState==="function"&&x.getState()==="loading"){add("ready",setup);return true;}}catch(e){}setup();return true;}`,
`window.__hplMraidBindScene=function(s){scene=s;apply();if(typeof volume==="number"&&scene&&scene.sound&&typeof scene.sound.setVolume==="function")scene.sound.setVolume(volume);};`,
`if(!ready()){var end=Date.now()+500;(function poll(){if(ready()||Date.now()>end)return;setTimeout(poll,50);})();}`,
`setTimeout(setup,2000);`,
`})();</script>`,
}, "")
}
func buildPlayworksCTAScript(network string) string {
urlSetup := `n=n||window.$environment.packageConfig.iosLink,i=i||window.$environment.packageConfig.androidLink;var o=/iphone|ipad|ipod|macintosh/i.test(window.navigator.userAgent.toLowerCase())?n:i;`
closeCall := `try{window.gameClose();}catch(e){}`
ctaLogic := closeCall + `window.open(o,"_blank");`
switch network {
case "al", "is":
case "al", "is", "un":
ctaLogic = closeCall + `if(typeof mraid!=="undefined"&&typeof mraid.open==="function"){var s=typeof mraid.getState==="function"?mraid.getState():"default";if(s!=="loading"){mraid.open(o);return;}}window.open(o,"_blank");`
case "fb":
ctaLogic = closeCall + `if(typeof FbPlayableAd!=="undefined"&&typeof FbPlayableAd.onCTAClick==="function"){FbPlayableAd.onCTAClick();return;}window.open(o,"_blank");`

View File

@@ -0,0 +1,32 @@
package main
import (
"os"
"path/filepath"
"testing"
)
func TestExportPlayworksNetworksForRuntimeCheck(t *testing.T) {
outDir := os.Getenv("PLAYWORKS_EXPORT_DIR")
if outDir == "" {
t.Skip("PLAYWORKS_EXPORT_DIR not set")
}
sourcePath := filepath.Join("..", "aiAssets", "Playworks_UnityNetwork.html")
data, err := os.ReadFile(sourcePath)
if err != nil {
t.Fatalf("read source: %v", err)
}
opts := playworksConvertOptions{
SourcePath: sourcePath,
OutputDir: outDir,
BaseName: "wat_mip_grhpl_dogcat3_05_real_na_noseason_en_full_na",
}
for _, network := range []string{"al", "fb", "gg", "is", "mo", "mtg", "un", "vu"} {
if _, err := convertPlayworksNetwork(string(data), opts, network); err != nil {
t.Fatalf("convert %s: %v", network, err)
}
}
}

View File

@@ -0,0 +1,75 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestTransformPlayworksHTMLNetworkRequirements(t *testing.T) {
sourcePath := filepath.Join("..", "aiAssets", "Playworks_UnityNetwork.html")
data, err := os.ReadFile(sourcePath)
if err != nil {
t.Fatalf("read source: %v", err)
}
tests := []struct {
network string
wantMraid int
wantExitapi int
}{
{network: "al", wantMraid: 1},
{network: "is", wantMraid: 1},
{network: "un", wantMraid: 1},
{network: "gg", wantExitapi: 1},
{network: "fb"},
{network: "mo"},
{network: "vu"},
{network: "mtg"},
}
for _, tt := range tests {
t.Run(tt.network, func(t *testing.T) {
html := transformPlayworksHTML(string(data), tt.network)
assertCount(t, html, `src="mraid.js"`, tt.wantMraid)
assertCount(t, html, `src="exitapi.js"`, tt.wantExitapi)
assertCount(t, strings.ToLower(html), "</html>", 1)
assertCount(t, strings.ToLower(html), "</head>", 1)
for _, forbidden := range []string{
`type="module"`,
`crossorigin`,
`console.error(`,
`stats.min.js`,
`insertYourRemoteDebuggingTokenHere`,
`console.re/connector.js`,
} {
if strings.Contains(html, forbidden) {
t.Fatalf("forbidden content remains: %s", forbidden)
}
}
for _, required := range []string{"gameReady", "gameStart", "gameEnd", "gameClose"} {
if !strings.Contains(html, required) {
t.Fatalf("missing lifecycle symbol: %s", required)
}
}
if tt.wantMraid == 1 {
for _, required := range []string{"exposureChange", "viewableChange", "audioVolumeChange", "[MRAID error]", "stateChange"} {
if !strings.Contains(html, required) {
t.Fatalf("missing MRAID requirement marker: %s", required)
}
}
}
})
}
}
func assertCount(t *testing.T, haystack, needle string, want int) {
t.Helper()
if got := strings.Count(haystack, needle); got != want {
t.Fatalf("%q count = %d, want %d", needle, got, want)
}
}