Compare commits
46 Commits
859c7d9e7c
...
v0.2.3
| Author | SHA1 | Date | |
|---|---|---|---|
| 5fa1ce949c | |||
| e50b4c2133 | |||
| cebb65fb35 | |||
| 7094e6c3b0 | |||
| 6c09beea43 | |||
| ad6403f3e4 | |||
| 700bb135ad | |||
| 986993a027 | |||
| 9e24342142 | |||
| b71e730482 | |||
| e3f454c5f2 | |||
| 88981d209b | |||
| 2524bacb5d | |||
| 9e919756fd | |||
| 1c445e2771 | |||
| a2d80d2660 | |||
| 1ee22b7155 | |||
| 2ca858cfa4 | |||
| 80f155dfe8 | |||
| 5625d94106 | |||
| a1d3fde774 | |||
| 7201bf9845 | |||
| 2921d4d384 | |||
| cce30c0729 | |||
| 4f17523f26 | |||
| 274bafe1cb | |||
| afbf504957 | |||
| 16847a78ca | |||
| ca9cc62b8c | |||
| 8e8d3d6da0 | |||
| 3f86aeaf0c | |||
| 92de00b52e | |||
| 78578cec16 | |||
| 75a506a505 | |||
| 698223234d | |||
| 9e82656eeb | |||
| c7ad1e14ca | |||
| d384c1be3a | |||
| 6be55255b2 | |||
| 9d6ed4b0a5 | |||
| 1336695068 | |||
| 40f13989c2 | |||
| 716dac31ef | |||
| f367b66b60 | |||
| 1cfdcb03ab | |||
| f123cbfc4a |
7
.claude/settings.local.json
Normal file
7
.claude/settings.local.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(go build *)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -93,7 +93,6 @@ out
|
|||||||
|
|
||||||
# Nuxt.js build / generate output
|
# Nuxt.js build / generate output
|
||||||
.nuxt
|
.nuxt
|
||||||
dist
|
|
||||||
|
|
||||||
# Gatsby files
|
# Gatsby files
|
||||||
.cache/
|
.cache/
|
||||||
|
|||||||
11
.vscodeignore
Normal file
11
.vscodeignore
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
.git/**
|
||||||
|
.vscode/**
|
||||||
|
.gitignore
|
||||||
|
standalone/**
|
||||||
|
dist/**
|
||||||
|
src/**
|
||||||
|
out/**/*.map
|
||||||
|
build.ps1
|
||||||
|
tsconfig.json
|
||||||
|
**/*.vsix
|
||||||
|
node_modules/.cache/**
|
||||||
4
LICENSE
Normal file
4
LICENSE
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
Copyright (c) 2026 HPL
|
||||||
|
|
||||||
|
All rights reserved. This software is proprietary and confidential.
|
||||||
|
Unauthorized copying, distribution, or use is prohibited.
|
||||||
119
README.md
Normal file
119
README.md
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
# HPL Toolbox
|
||||||
|
|
||||||
|
Bundled VS Code extension and standalone tools for playable ad workflows.
|
||||||
|
|
||||||
|
# Tools
|
||||||
|
|
||||||
|
- **PLEC Upload** - Upload selected HTML files to the internal PLEC server.
|
||||||
|
- **AppLovin Playable Preview** - Upload HTML files to p.applov.in and generate QR preview links.
|
||||||
|
- **Base64 Scanner** - Scan HTML files for external or non-base64 asset references.
|
||||||
|
- **Send To Mobile** - Share selected HTML files to a phone over LAN with a QR code.
|
||||||
|
- **MRAID Checker** - Check HTML files against MRAID requirements and best practices.
|
||||||
|
- **Mintegral Checker** - Validate Mintegral playable ZIPs against PlayTurbo requirements.
|
||||||
|
- **Playworks Converter** - Convert Playworks HTML into per-network variants. Beta.
|
||||||
|
|
||||||
|
# Changelog
|
||||||
|
|
||||||
|
**v0.1.2**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added local hosting for HTML files.
|
||||||
|
- Added the standalone app.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.1.3**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added QR regeneration for AppLovin previews that fail to render.
|
||||||
|
- Added Save QR and Save All QRs actions.
|
||||||
|
|
||||||
|
Changed
|
||||||
|
- Updated AppLovin Demo Upload.
|
||||||
|
- Improved the file selection workflow.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.1.5**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added multi-file selection for PLEC Upload.
|
||||||
|
- Added automatic iteration name detection.
|
||||||
|
|
||||||
|
Changed
|
||||||
|
- Improved PLEC Upload file selection.
|
||||||
|
- Moved standalone temporary files into the user temp folder.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.1.6**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added beta tools for further testing:
|
||||||
|
- Playworks Converter for converting Playworks UnityAds HTML into other network variants.
|
||||||
|
- MRAID Checker for scanning HTML files against MRAID requirements and best practices.
|
||||||
|
|
||||||
|
Changed
|
||||||
|
- Simplified the UI.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.1.7**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added standalone drag-and-drop file/folder selection for HTML inputs across supported tools.
|
||||||
|
- Added status throbber/progress updates for batch scans, uploads, sharing, and conversions.
|
||||||
|
- Added streamed standalone progress updates so long-running actions update the status bar before completion.
|
||||||
|
|
||||||
|
Changed
|
||||||
|
- MRAID Checker is no longer marked as beta in extension or standalone.
|
||||||
|
- Playworks Converter source selection now matches the other file-selection UIs more closely.
|
||||||
|
- Playworks Converter default output folder now resolves to the input file location's Output folder.
|
||||||
|
- Progress text now follows the format: [throbber] Verb count file.
|
||||||
|
|
||||||
|
Fixed
|
||||||
|
- Fixed standalone drag-and-drop handling for multiple files and multiple folders.
|
||||||
|
- Fixed cleanup behavior for temporary dropped files when clearing or removing rows.
|
||||||
|
- Fixed standalone PLEC Upload Open button using an incorrect/mangled URL by switching to the Windows URL protocol handler.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.2.0**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added Mintegral Checker to the VS Code extension.
|
||||||
|
- Added Mintegral Checker to the standalone app.
|
||||||
|
- Added PlayTurbo-compatible runtime validation for Mintegral playables using the injected preview utility script.
|
||||||
|
|
||||||
|
Changed
|
||||||
|
- Mintegral Checker is available as a regular tool, not a beta tool.
|
||||||
|
- Standalone navigation now uses a collapsible sidebar with compact tool initials.
|
||||||
|
- Mintegral Checker UI now embeds the playable preview, checklist, runtime events, mute, and reload controls in one view.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.2.1**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added Device Simulator to the VS Code extension and standalone app.
|
||||||
|
- Added editable Device Simulator device lists with add, delete, restore defaults, import, and export.
|
||||||
|
- Added drag-and-drop reordering for Device Simulator devices.
|
||||||
|
- Added iPhone 17, iPhone Air, iPhone 17 Pro, and iPhone 17 Pro Max defaults.
|
||||||
|
- Added drag-and-drop tool reordering with persisted order in the VS Code launcher and standalone Home/sidebar.
|
||||||
|
|
||||||
|
Changed
|
||||||
|
- Device Simulator settings now use a modal list manager with multi-select, add/delete, and move up/down controls.
|
||||||
|
- Standalone Device Simulator sidebar abbreviation is now DS.
|
||||||
|
- Send To Mobile browser preview now opens playables in a delayed full-screen preview wrapper while Download still serves the original HTML.
|
||||||
|
|
||||||
|
Fixed
|
||||||
|
- Fixed Device Simulator mute for HTML media and WebAudio playables.
|
||||||
|
- Fixed Device Simulator Add Device and Remove Device interactions inside embedded webviews.
|
||||||
|
- Fixed Send To Mobile browser preview spending the View button's initial tap as a premature playable click-through while preserving real user-initiated redirects.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.2.2**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added automatic update checking to the VS Code extension and standalone app.
|
||||||
|
```
|
||||||
|
|
||||||
|
**v0.2.3**
|
||||||
|
```
|
||||||
|
Added
|
||||||
|
- Added Localization dropdown in Device Simulator.
|
||||||
|
```
|
||||||
155
TODO.md
Normal file
155
TODO.md
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
# Mintegral Checker — TODO
|
||||||
|
|
||||||
|
## Task Overview
|
||||||
|
|
||||||
|
Build a local VS Code webview equivalent of the Mintegral PlayTurbo checker
|
||||||
|
(`https://www.playturbo.com/review`). Validates a Mintegral playable ad ZIP against
|
||||||
|
PlayTurbo requirements. Two check categories:
|
||||||
|
|
||||||
|
- **Static** — parse `index.html` + ZIP structure without running the ad.
|
||||||
|
- **Runtime** — load the ad in a sandboxed `srcdoc` iframe, inject a monitoring stub,
|
||||||
|
and detect whether lifecycle callbacks (`gameReady`, `gameEnd`, `gameStart`,
|
||||||
|
`gameClose`, `install`) actually fire.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Finished
|
||||||
|
|
||||||
|
- [x] Pure-Node ZIP parser (EOCD → Central Directory → Local File Headers, zlib DEFLATE)
|
||||||
|
- [x] All 9 static checks:
|
||||||
|
- HTML Requirements (charset, viewport, single-file)
|
||||||
|
- CTA Method (`window.install` reference in scripts)
|
||||||
|
- Game End / Game Ready / Game Start / Game Close (regex on scripts)
|
||||||
|
- File Handling (no external URLs, base64 assets)
|
||||||
|
- File Spec (ZIP ≤ 5 MB, single `index.html`)
|
||||||
|
- Storage (no `localStorage.setItem` / `sessionStorage.setItem`)
|
||||||
|
- [x] Device-frame simulator (phone mockup around `srcdoc` iframe)
|
||||||
|
- [x] Event log panel showing runtime events as they fire
|
||||||
|
- [x] Runtime timer with 60s timeout and per-check waiting badges
|
||||||
|
- [x] `__ping__` handshake → "Simulator connected" in event log (confirms stub runs)
|
||||||
|
- [x] Dual notification channels: polling `__hplMtgEvents` + `parent.__hplMtgNotify`
|
||||||
|
- [x] `MW_INIT` interceptor (wraps `emitCheckData`, forces `_hasReview`/`_isPreview`)
|
||||||
|
- [x] `window.postMessage` override (catches `previewer:gameReady` self-posts)
|
||||||
|
- [x] `mkAccess` — `Object.defineProperty` accessor with undefined getter so AD's
|
||||||
|
`typeof window.gameReady === 'undefined'` guard passes, setter wraps assignment
|
||||||
|
- [x] Capture-phase `load` safety net — wraps any SDK function declarations that
|
||||||
|
overwrote accessors, fires before `body.onload`
|
||||||
|
- [x] Mute button UI (shows on ZIP load, hidden on reset, toggles Mute/Unmute label)
|
||||||
|
- [x] Diagnostic lifecycle logging (`post-parse`, `DOMContentLoaded`, `load`,
|
||||||
|
`load+500ms`, callback assignment/call traces)
|
||||||
|
- [x] AudioContext construction proxy for mute/unmute of closure-owned engine audio
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Bugs
|
||||||
|
|
||||||
|
### 1. Callbacks never fire (critical, diagnostics added)
|
||||||
|
|
||||||
|
**Symptom:** Event log shows "Simulator connected" (`__ping__` fires) but no lifecycle
|
||||||
|
events appear. The same ZIP passes all checks on the real PlayTurbo site.
|
||||||
|
|
||||||
|
**Root cause candidates (narrowed down but not confirmed):**
|
||||||
|
|
||||||
|
A. **`body.onload` vs capture `load` ordering on `window`** — When the event target is
|
||||||
|
`window` itself, capture and bubble listeners both run at the "at target" phase in
|
||||||
|
registration order. Our stub is in `<head>` and registers first, so it should fire
|
||||||
|
before the body's `onload`. But this assumes no edge-case behaviour in VS Code's
|
||||||
|
Chromium sandbox / srcdoc context.
|
||||||
|
|
||||||
|
B. **SDK function declaration closes over a local reference** — If the ad does:
|
||||||
|
```js
|
||||||
|
var gameReady = function() { ... };
|
||||||
|
window.gameReady = gameReady;
|
||||||
|
```
|
||||||
|
and `body.onload="gameReady()"` resolves to the local var (via closure), then
|
||||||
|
reassigning `window.gameReady` in our load-time wrapper has no effect.
|
||||||
|
|
||||||
|
C. **CSP in VS Code webview blocks stub execution silently** — The webview panel has
|
||||||
|
an implicit CSP. The stub is injected into `srcdoc`; it might run in a restricted
|
||||||
|
context that prevents property interception or `parent` access for later events (even
|
||||||
|
though `__ping__` works because it runs synchronously at parse time).
|
||||||
|
|
||||||
|
D. **Ad calls `gameReady()` before load** — If the ad boots via DOMContentLoaded and
|
||||||
|
calls `gameReady()` there (rather than body.onload), our load-event safety net fires
|
||||||
|
too late. The `mkAccess` accessor should still catch it, but only if the ad assigns
|
||||||
|
`window.gameReady` first.
|
||||||
|
|
||||||
|
**What's been added:**
|
||||||
|
- Injected diagnostic logging for lifecycle function `typeof` at post-parse,
|
||||||
|
DOMContentLoaded, load capture before/after wrapping, and 500 ms after load.
|
||||||
|
- Logs callback assignment/wrapping and wrapper call paths to the event log.
|
||||||
|
- Logs dynamic `document.createElement('script')` calls to help trace script injection.
|
||||||
|
|
||||||
|
**What's still needed if callbacks still do not fire:**
|
||||||
|
- Check if the ad bundles `preview-util.js` inside `index.html` or references it
|
||||||
|
externally (would fail file-handling check anyway).
|
||||||
|
- Compare the diagnostic timeline against the real PlayTurbo execution path.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. Mute button does nothing (fixed in monitor stub)
|
||||||
|
|
||||||
|
**Symptom:** Clicking Mute/Unmute changes the label but has no audible effect.
|
||||||
|
|
||||||
|
**Root cause:** The current approach searches `Object.keys(cw)` for an `AudioContext`
|
||||||
|
instance. AudioContexts are almost always created in closures (inside Phaser or the ad
|
||||||
|
IIFE) and are never assigned as window properties — `Object.keys` will never find them.
|
||||||
|
`cw.Phaser.game.sound` also likely fails because Phaser stores the game instance
|
||||||
|
internally, not at `window.Phaser.game`.
|
||||||
|
|
||||||
|
**Fix applied:**
|
||||||
|
Intercepts `AudioContext`/`webkitAudioContext` construction in the monitoring stub,
|
||||||
|
stores captured contexts/gain nodes on `window.__hplAudioContexts` and
|
||||||
|
`window.__hplMasterGains`, and routes `ctx.destination` through a master gain when
|
||||||
|
possible. The mute button now sets captured master gain values first, then falls back
|
||||||
|
to suspending/resuming captured contexts and exposed Phaser/global game sound objects.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Improvements / Nice-to-Have
|
||||||
|
|
||||||
|
- [ ] **Inject SDK alongside ad** — The real PlayTurbo checker loads `preview-util.js`
|
||||||
|
next to the ad. Bundling (or downloading once) the 265 KB SDK and injecting it into
|
||||||
|
the srcdoc would let `MW_INIT`/`emitCheckData` fire natively, which is the most
|
||||||
|
reliable callback path and matches what the real checker does.
|
||||||
|
|
||||||
|
- [ ] **Diagnostic mode** — A "Debug" toggle that logs `typeof` of each lifecycle
|
||||||
|
function at key moments (post-parse, DCL, load, 500ms after load) to the event log,
|
||||||
|
making root-cause analysis faster.
|
||||||
|
|
||||||
|
- [ ] **Replay button** — Reload only the iframe (not the full ZIP re-parse) to retest
|
||||||
|
without re-picking the file.
|
||||||
|
|
||||||
|
- [ ] **Portrait / landscape toggle** — Flip the device frame aspect ratio.
|
||||||
|
|
||||||
|
- [ ] **Multiple HTML entry points** — Some ZIPs have `playable.html` instead of
|
||||||
|
`index.html`; add a fallback search.
|
||||||
|
|
||||||
|
- [ ] **Orientation lock detection** — Check for `screen.orientation.lock()` calls
|
||||||
|
(Mintegral requires the ad to handle both orientations).
|
||||||
|
|
||||||
|
- [ ] **Version bump and changelog entry** — Once callbacks are working, bump to 0.1.8
|
||||||
|
and add a changelog entry for the Mintegral Checker tool.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Known Issues / Constraints
|
||||||
|
|
||||||
|
- VS Code `WebviewPanel` runs in a sandboxed Chromium process. `srcdoc` iframes are
|
||||||
|
same-origin with the webview, so `parent` access works — but the webview's implicit
|
||||||
|
CSP may still block certain APIs inside nested iframes.
|
||||||
|
|
||||||
|
- The `Object.defineProperty` accessor approach (`mkAccess`) is the only way to let the
|
||||||
|
AD's `typeof window.X === 'undefined'` guard pass while still intercepting the
|
||||||
|
assignment. Any early concrete assignment (even `undefined`) breaks the guard in some
|
||||||
|
runtimes.
|
||||||
|
|
||||||
|
- SDK `function` declarations at brace-depth 0 are `[[DefineOwnProperty]]` calls at
|
||||||
|
parse time; they overwrite our configurable accessors unconditionally. The load-time
|
||||||
|
safety net is the only recovery path for that scenario.
|
||||||
|
|
||||||
|
- The `applyStaticResults` function sets `runtimeStatus = null` for lifecycle checks
|
||||||
|
that already failed statically. `handleRuntimeEvent` only transitions
|
||||||
|
`runtimeStatus === 'waiting'` → `'pass'`; it silently ignores `null`. This means a
|
||||||
|
static-fail check can't be runtime-rescued via the direct lifecycle path (though the
|
||||||
|
`handleSdkCheck` path does handle `null`). Intentional, but worth documenting.
|
||||||
321
aiAssets/GUIDE.md
Normal file
321
aiAssets/GUIDE.md
Normal file
@@ -0,0 +1,321 @@
|
|||||||
|
# AGENTS.md — Playable Ads
|
||||||
|
|
||||||
|
## Stack
|
||||||
|
Phaser 3.90 · TypeScript · Vite + vite-plugin-singlefile · WebP · MP3 96kbps
|
||||||
|
Networks: Applovin (al) · GoogleAds (gg) · Ironsource (is) · Mintegral (mtg) · Facebook (fb) · Unity (un) · Vungle (vu) · Moloco (mo) · TikTok (tt)
|
||||||
|
|
||||||
|
## Porting to a new project
|
||||||
|
1. Update naming fields (3LC, vendor, concept name) in [scripts/build-all.mjs](scripts/build-all.mjs) — drives the output filename
|
||||||
|
2. Update store URLs in [constants.ts](src/constants.ts) (iOS + Android)
|
||||||
|
3. Adjust the Depth Map below to match the project's layer needs
|
||||||
|
4. Update [iteration.ts](src/iteration.ts) A/B config shape for this project's variants
|
||||||
|
5. Replace `Assets/` with project assets; update asset manifests in [BootScene.ts](src/scenes/BootScene.ts)
|
||||||
|
6. Rewrite `game/` modules for the new mechanic(s) — keep the single-responsibility split
|
||||||
|
7. Update this AGENTS.md's Depth Map and any project-specific pitfalls
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
main.ts # Bootstrap, resize, MRAID gating, lifecycle stubs on window
|
||||||
|
constants.ts # Design coords (1080×1920), store URLs
|
||||||
|
networks.ts # triggerCTA(), initMraid(), bindLifecycle(), notifyGameX()
|
||||||
|
analytics.ts # trackEvent() → SDK
|
||||||
|
iteration.ts # A/B iteration config
|
||||||
|
utils/
|
||||||
|
responsive.ts # sx(), sy(), sd() — coordinate helpers
|
||||||
|
scenes/
|
||||||
|
BootScene.ts # Critical preload + deferred asset manifest
|
||||||
|
GameScene.ts # Orchestrator only — wires game/ modules, handles lifecycle
|
||||||
|
cta.ts # End-card layout + redirectToStore() → notifyGameClose() + triggerCTA()
|
||||||
|
game/ # Single-responsibility modules (no direct ad-SDK calls)
|
||||||
|
# …one file per distinct mechanic or UI widget
|
||||||
|
Assets/
|
||||||
|
scripts/build-all.mjs # Single build → per-network HTML variants
|
||||||
|
```
|
||||||
|
|
||||||
|
### Responsibility split
|
||||||
|
- **`game/`** modules each own a single concern (one mechanic, one widget, one system).
|
||||||
|
They receive the Phaser scene as a constructor arg and own their own game objects.
|
||||||
|
They never call ad-SDK functions (`triggerCTA`, `notifyGameX`, `trackEvent`).
|
||||||
|
- **`GameScene.ts`** is the wiring layer: creates modules, passes data between them,
|
||||||
|
and calls SDK helpers at the correct lifecycle moments.
|
||||||
|
- **`scenes/cta.ts`** owns end-card presentation and the store-redirect sequence.
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
- 60 FPS target; never below 30 on mid-range Android
|
||||||
|
- `dist/index.html` < 5 MB; WebP images, short audio
|
||||||
|
- No hardcoded px — `sx()`, `sy()`, `sd()` only
|
||||||
|
- No audio autoplay — unmute on first `pointerdown`
|
||||||
|
- `for` loops in game logic; pool objects; no GC
|
||||||
|
- `setDisplaySize(sd())` on images — never `setScale`
|
||||||
|
- Never dim via `body`/page background
|
||||||
|
|
||||||
|
## Phaser Config
|
||||||
|
```ts
|
||||||
|
{ type: Phaser.AUTO, transparent: true,
|
||||||
|
scale: { mode: Phaser.Scale.NONE, width: 1080, height: 1920 },
|
||||||
|
render: { antialias: true, pixelArt: false } }
|
||||||
|
```
|
||||||
|
`Scale.NONE` — manual sizing; CSS = viewport px; internal = viewport × DPR.
|
||||||
|
`antialias: true` — required to avoid jagged edges on scaled WebP assets (end-card logo, CTA, score pill). Never set to `false`.
|
||||||
|
|
||||||
|
## Responsive (1080×1920 ref)
|
||||||
|
```ts
|
||||||
|
const s = Math.min(viewW / 1080, viewH / 1920)
|
||||||
|
const offX = (viewW - 1080 * s) / 2
|
||||||
|
const offY = (viewH - 1920 * s) / 2
|
||||||
|
// sx/sy/sd apply offX, offY, s
|
||||||
|
```
|
||||||
|
- `update()` polls `visualViewport` per-frame for rotation
|
||||||
|
- On change: `game.scale.resize(vw*dpr, vh*dpr)` → `relayout()`
|
||||||
|
- `bindResponsiveResize()`: rAF debounce + 100/300/600ms retries
|
||||||
|
|
||||||
|
## CTA — SDK Priority (triggerCTA fallback chain)
|
||||||
|
```
|
||||||
|
1. ExitApi.exit() → GoogleAds (gg)
|
||||||
|
2. FbPlayableAd.onCTAClick() → Facebook (fb) · Moloco (mo)
|
||||||
|
3. Luna.Unity.Playable → Unity (un)
|
||||||
|
4. playableSDK.openAppStore() → (runtime fallback if SDK present)
|
||||||
|
5. window.install() → Mintegral (mtg)
|
||||||
|
6. window.openAppStore() → (runtime fallback)
|
||||||
|
7. window.clickTag → Moloco (mo) fallback
|
||||||
|
8. window.__VUNGLE__ → Vungle (vu) via parent.postMessage
|
||||||
|
9. window.__TIKTOK__ → TikTok (tt) → openAppStore() or window.open fallback
|
||||||
|
10. mraid.open(url) → Applovin (al) / Ironsource (is) / Unity (un fallback after Luna)
|
||||||
|
11. window.open(storeUrl) → Fallback (all others)
|
||||||
|
```
|
||||||
|
`notifyGameClose()` fires before every CTA redirect (all networks, no-op when SDK absent).
|
||||||
|
MRAID CTA calls must be guarded: require `typeof mraid.open === 'function'`; treat missing `mraid.getState()` as `ready`; if state is still `loading`, fall through to `window.open(storeUrl)`.
|
||||||
|
|
||||||
|
## Analytics — SDK Priority
|
||||||
|
```
|
||||||
|
ALPlayableAnalytics.trackEvent(e) → Applovin (al)
|
||||||
|
playableSDK.reportEvent(e) → (runtime fallback if SDK present)
|
||||||
|
console.log('[Analytics]', e) → All other networks
|
||||||
|
```
|
||||||
|
Events: `DISPLAYED` · `CTA_CLICKED` · `ENDCARD_SHOWN` · `CHALLENGE_STARTED` · `CHALLENGE_SOLVED`
|
||||||
|
|
||||||
|
## Game Lifecycle (all networks)
|
||||||
|
`main.ts` exposes stubs on `window` so every network's preview tool detects them.
|
||||||
|
Stubs only set if the SDK hasn't already provided its own (`typeof` guard).
|
||||||
|
```
|
||||||
|
gameReady() → stub in main.ts; Mintegral also gets onload body attr from build
|
||||||
|
gameStart() → notifyGameStart() in GameScene.startPlaying()
|
||||||
|
gameEnd() → notifyGameEnd() in GameScene.triggerFail() / triggerWin()
|
||||||
|
gameClose() → notifyGameClose() in cta.ts redirectToStore(), before triggerCTA()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pause / Resume / Mute (bindLifecycle in networks.ts)
|
||||||
|
| Network | Mechanism |
|
||||||
|
|---|---|
|
||||||
|
| Unity | `luna:mute` / `luna:unmute` / `luna:pause` / `luna:resume` events; also shared MRAID exposure/viewability when `mraid.js` is present |
|
||||||
|
| Mintegral | `window.message` → `onPause` / `onResume` |
|
||||||
|
| Vungle | `ad-event-pause` / `ad-event-resume` events |
|
||||||
|
| Applovin / Ironsource / Unity | MRAID 3.0 `exposureChange`, MRAID 2.0 fallback `viewableChange` / `isViewable`, and `audioVolumeChange` (gated in `initMraid`) |
|
||||||
|
| GoogleAds / Facebook / Moloco | No SDK pause — browser handles visibility |
|
||||||
|
|
||||||
|
### MRAID 3.0 Requirements & Best Practices
|
||||||
|
MRAID networks are **Applovin (`al`)**, **Ironsource (`is`)**, and **Unity (`un`)**. All three must request `<script src="mraid.js"></script>` early in the generated HTML. Unity still uses Luna first for CTA/lifecycle where available, but MRAID must exist as the standards fallback.
|
||||||
|
|
||||||
|
Creative requirements from the MRAID 3.0 spec and Best Practices Guide:
|
||||||
|
- Request `mraid.js` as early as possible, exactly once, either with `<script src="mraid.js"></script>` or DOM insertion. Do not rely on the container to inject it automatically.
|
||||||
|
- Wait for both DOM readiness and MRAID readiness before starting rich media behavior. Use `document.readyState` / `DOMContentLoaded` or `load` for the DOM side.
|
||||||
|
- Use `mraid.getState()` together with `mraid.addEventListener('ready', ...)` so the creative still starts when the container fires `ready` before the listener attaches.
|
||||||
|
- Guard access to `mraid` and MRAID methods with `typeof` checks. Treat missing optional methods as unsupported and fall back gracefully.
|
||||||
|
- Use `mraid.open(url)` for MRAID clickthroughs. Avoid `<a href>`, `location.href` / `assign` / `replace`, and unguarded `window.open`.
|
||||||
|
- Include `<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">` or an equivalent mobile viewport tag.
|
||||||
|
- Do not assume nested iframes can access native MRAID. If nested iframe access is required, the outer frame must provide its own bridge.
|
||||||
|
- Use `exposureChange` as the MRAID 3.0 viewability signal, then degrade to `viewableChange` / `isViewable()` for MRAID 2.0 compatibility.
|
||||||
|
- Listen for `audioVolumeChange`; `null` is valid and must be ignored. Only apply volume math when the value is numeric.
|
||||||
|
- Listen for `error`; if the ad cannot run or assets fail, gracefully degrade or call `mraid.unload()` instead of showing a broken/blank ad.
|
||||||
|
- Call `setResizeProperties()` before `resize()`. Do not use `resize()` for full-screen takeovers; use `expand()` for that case.
|
||||||
|
- Avoid resizing or expanding interstitials. Check placement with `getPlacementType()` when one creative can serve inline and interstitial placements.
|
||||||
|
- Avoid `useCustomClose()` and custom close indicators in MRAID 3.0. The host provides the close control.
|
||||||
|
- Avoid two-part expandable ads (`expand(url)`); use self-contained one-part expandables.
|
||||||
|
- Call `supports()` before optional/native features such as `storePicture`, `createCalendarEvent`, `getLocation`, VPAID, SMS/tel, or inline video behavior.
|
||||||
|
- Use `playVideo()` for native video playback cases instead of `mraid.open(videoUrl)`. Use HTML5 `<video>` for inline playback when supported.
|
||||||
|
|
||||||
|
Implementation requirements for `networks.ts` / `networks.js`:
|
||||||
|
- Export `initMraid(timeoutMs = 2000, detectTimeoutMs = 500)` and call it at module load.
|
||||||
|
- If `window.mraid` is missing at module load, poll briefly (`detectTimeoutMs`, default 500 ms) for late container injection before resolving as no-MRAID.
|
||||||
|
- If MRAID exists and `mraid.getState() === 'loading'`, wait for `mraid.addEventListener('ready', ...)`; self-resolve after `timeoutMs` (default 2000 ms) so startup never hangs.
|
||||||
|
- `main` / boot must `await initMraid()` before constructing `new Phaser.Game(...)`.
|
||||||
|
- On setup, seed cached visibility from `mraid.isViewable()` when available.
|
||||||
|
- Register MRAID callbacks once, before any Phaser scene is ready:
|
||||||
|
- `mraid.addEventListener('error', (message, action) => ...)` — log or gracefully handle failed/unsupported MRAID calls.
|
||||||
|
- `mraid.addEventListener('stateChange', state => ...)` — required when using state-changing MRAID behavior such as `close`, `expand`, or `resize`.
|
||||||
|
- `mraid.addEventListener('exposureChange', exposedPercentage => ...)` — MRAID 3.0 primary viewability. Pause when `exposedPercentage <= 0`; resume when positive.
|
||||||
|
- `mraid.addEventListener('viewableChange', viewable => ...)` — MRAID 2.0 compatibility fallback.
|
||||||
|
- `mraid.addEventListener('audioVolumeChange', pct => ...)` — only apply `pct / 100` when `typeof pct === 'number'`.
|
||||||
|
- In `bindLifecycle(scene)`, apply cached hidden/non-exposed MRAID state immediately once a scene exists.
|
||||||
|
- If the creative renders its own close control, wire that control to a guarded `mraid.close()` helper and call `notifyGameClose()` before closing.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
Vite outputs IIFE format (`format: 'iife'`, `modulePreload: false`).
|
||||||
|
Build script strips `type="module"` and `crossorigin` — ad networks reject ES modules.
|
||||||
|
MRAID networks (`al`, `is`, `un`) inject exactly one `<script src="mraid.js"></script>` request.
|
||||||
|
If built output contains `console.error` from Phaser or bundled node modules, prefer dropping it at bundle time instead of editing library source. Add this option to the shared Vite config, usually `vite.shared.js`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export default {
|
||||||
|
esbuild: {
|
||||||
|
pure: ['console.error'],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep project-authored error handling meaningful: use visible fallback UI, `console.warn`, or guarded debug logging where needed.
|
||||||
|
|
||||||
|
| Network | Tag | Injected | Zipped | Included |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Applovin | al | `mraid.js` | — | ✓ |
|
||||||
|
| Google | gg | `exitapi.js` | ✓ | ✓ |
|
||||||
|
| Ironsource | is | `mraid.js` | — | ✓ |
|
||||||
|
| Mintegral | mtg | `onload="gameReady()"` | ✓ | ✓ |
|
||||||
|
| Facebook | fb | — | — | ✓ |
|
||||||
|
| Unity | un | `mraid.js` | — | ✓ |
|
||||||
|
| Vungle | vu | `window.__VUNGLE__=true` | ✓ | ✓ |
|
||||||
|
| Moloco | mo | — | — | ✓ |
|
||||||
|
| TikTok | tt | `window.__TIKTOK__=true` | — | — |
|
||||||
|
|
||||||
|
|
||||||
|
Networks marked **Zipped** ingest zipped creatives — [scripts/build-all.mjs](scripts/build-all.mjs) writes a `.zip` containing the HTML (one zip per variant, containing just that HTML at the root named index.html). Toggled per-network via `zip: true` in the `NETWORKS` array.
|
||||||
|
|
||||||
|
Networks marked **Included** are built by default. Networks not marked are prepared for but not built. Toggle per-network via `included: true` in the `NETWORKS` array.
|
||||||
|
|
||||||
|
Output is grouped by **iteration length** (e.g. `2words/`, `4words/`, `full/`) then by **network** (e.g. `Applovin/`, `Google/`, `Mintegral/`), with all per-network HTML or ZIP variants for that iteration sitting together inside the folder:
|
||||||
|
|
||||||
|
`dist/<length>/<3lc>_<creative-type>_<vendor>_<concept-name>_<concept-num>_<gameplay>_<ugc>_<seasonal>_<lang>_<length>_<size>_<network>`
|
||||||
|
|
||||||
|
Example layout:
|
||||||
|
```
|
||||||
|
dist/
|
||||||
|
2words/
|
||||||
|
Applovin/
|
||||||
|
ws_mip_grhpl_wbinspiredvar1_01_real_na_noseason_en_2words_na_al.html
|
||||||
|
Google/
|
||||||
|
ws_mip_grhpl_wbinspiredvar1_01_real_na_noseason_en_2words_na_gg.zip
|
||||||
|
Ironsource/
|
||||||
|
ws_mip_grhpl_wbinspiredvar1_01_real_na_noseason_en_2words_na_is.html
|
||||||
|
…one HTML or ZIP per network…
|
||||||
|
4words/
|
||||||
|
full/
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Description | Example |
|
||||||
|
|---|---|---|
|
||||||
|
| 3LC | 3-letter project code | `ws` (Wordscapes), `pp` (PeoplePuzzle) |
|
||||||
|
| Creative Type | Format identifier | `mip` |
|
||||||
|
| Vendor | Studio / vendor code | `grhpl` |
|
||||||
|
| Concept Name | Creative concept (append `var1`, `var2`… for variants) | `wbinspiredvar1`, `wbinspiredvar2`, `burglar` |
|
||||||
|
| Concept # | Iteration number, zero-padded | `01`, `02`, `03` |
|
||||||
|
| Gameplay | Gameplay style | `real`, `cartoon` |
|
||||||
|
| UGC | UGC presence | `na`, `ugc`, `nougc` |
|
||||||
|
| Seasonal | Seasonal tie-in | `noseason`, `xmas` |
|
||||||
|
| Language | Locale code | `en` |
|
||||||
|
| Length | Run length | `2words`, `4words`, `7words`, `full` (Wordscapes); `2clk`, `10clk`, `120sec` (other projects) |
|
||||||
|
| Size | Region / size code | `na` |
|
||||||
|
| Network | Network tag (last segment) | `al`, `gg`, `is`, `mtg`, `fb`, `un`, `vu`, `mo`, `tt` |
|
||||||
|
|
||||||
|
Examples (this project):
|
||||||
|
- `ws_mip_grhpl_wbinspiredvar1_01_real_na_noseason_en_2words_na_al.html` (cta2, default theme)
|
||||||
|
- `ws_mip_grhpl_wbinspiredvar1_04_real_na_noseason_en_full_na_fb.html` (full, default theme)
|
||||||
|
- `ws_mip_grhpl_wbinspiredvar2_01_real_na_noseason_en_2words_na_gg.html` (cta2, v1 theme)
|
||||||
|
|
||||||
|
Naming fields are defined in [scripts/build-all.mjs](scripts/build-all.mjs) — update them when porting.
|
||||||
|
|
||||||
|
## Asset Loading
|
||||||
|
- **Critical** (BootScene): first-frame assets, target < 200 KB
|
||||||
|
- **Deferred**: audio, overlays, secondary UI — loads during intro
|
||||||
|
- Gameplay start waits on a deferred-ready flag set when the secondary manifest finishes loading
|
||||||
|
|
||||||
|
## Depth Map (adjust per project)
|
||||||
|
Define depths as named constants in [constants.ts](src/constants.ts) — never use magic numbers in scene code.
|
||||||
|
|
||||||
|
| Layer | Depth |
|
||||||
|
|---|---|
|
||||||
|
| Background | 0 |
|
||||||
|
| Game objects | 1–10 |
|
||||||
|
| Logo | 17 |
|
||||||
|
| Dim overlay | 20 |
|
||||||
|
| Fail/win UI | 21 |
|
||||||
|
| EndCard input | 25 |
|
||||||
|
|
||||||
|
## Ship Checklist
|
||||||
|
- [ ] < 5 MB, all WebP
|
||||||
|
- [ ] FPS ≥ 55 under CPU throttle
|
||||||
|
- [ ] Portrait + landscape pass
|
||||||
|
- [ ] MRAID ready before gameplay
|
||||||
|
- [ ] Audio muted by default
|
||||||
|
- [ ] CTA fires in fallback
|
||||||
|
- [ ] No `console.error`
|
||||||
|
- [ ] No `type="module"` or `crossorigin` on `<script>` in output HTML
|
||||||
|
- [ ] Lifecycle: gameReady / gameStart / gameEnd / gameClose detected by all network preview tools
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
| Issue | Fix |
|
||||||
|
|---|---|
|
||||||
|
| Rotation stuck | `Scale.NONE` + per-frame poll |
|
||||||
|
| Mobile aliasing | Canvas = viewport × DPR |
|
||||||
|
| FPS drop on resize | rAF debounce |
|
||||||
|
| MRAID crash | `typeof mraid !== 'undefined'` guard |
|
||||||
|
| Assets not inlined | `assetsInlineLimit: 100_000_000` |
|
||||||
|
| Bundle > 5 MB | WebP q75, shorter audio |
|
||||||
|
| Built output contains library `console.error` | If `console.error` comes from Phaser or bundled node modules, add `esbuild: { pure: ['console.error'] }` in `vite.shared.js` so it is dropped at bundle time. Do not edit library source. |
|
||||||
|
| Audio blocked | Gate on `pointerdown` |
|
||||||
|
| Letterbox | Avoid `Scale.FIT/EXPAND/CENTER_BOTH` |
|
||||||
|
| CORS / module error | `format: 'iife'` + strip `type="module"` and `crossorigin` |
|
||||||
|
| Network preview checklist fail | Expose lifecycle stubs on `window` + call `notifyX()` with `typeof` guards |
|
||||||
|
| `playableSDK.reportEvent is not a function` | Applovin preview injects `playableSDK` without `reportEvent` — guard with `typeof playableSDK.reportEvent === 'function'`, not just `typeof playableSDK !== 'undefined'` |
|
||||||
|
| iPhone black screen (Android works) | **Only one `Phaser.Game` per page, ever.** iOS WKWebView — used by Applovin/Ironsource preview apps and most in-app ad containers — caps or outright rejects the 2nd WebGL context. If a background scene is spun up as a separate `new Phaser.Game()` synchronously at module load, it can throw before `await initMraid()` and before the font promise resolves, so the rest of `main.ts` never runs → black screen with no visible error. Render the background as a CSS `background-image` on `#bg-container` (cover-sized) instead — zero WebGL contexts for the background, and nothing to throw at module-load time. iOS-debug path: enable Safari → Advanced → Web Inspector on the iPhone, connect to a Mac, open Develop → iPhone → preview WebView, read the Console. Without a Mac, temporarily install top-of-`main.ts` `window.addEventListener('error',…)` and `unhandledrejection` handlers that write the error into `document.body.innerHTML` so the failure is visible on-screen. |
|
||||||
|
| iOS hangs on font load | `document.fonts.load()` silently stalls in WKWebView when `@font-face` uses base64 `data:` URLs. Race against a 1.5 s timeout: `Promise.race([Promise.all([…fonts]), new Promise(r=>setTimeout(r,1500))]).then(startGame)` |
|
||||||
|
| iOS hangs on MRAID ready | `mraid.addEventListener('ready', …)` can miss the event if the container fires it before the listener attaches. `initMraid()` must self-resolve after ~2 s so `startGame()` always runs; also check `mraid.getState() !== 'loading'` first. |
|
||||||
|
| External `src=` survives build | `vite-plugin-singlefile` only inlines assets *imported from JS*. A raw `<img src="src/assets/…">` in `index.html` ships as a literal relative path and fails in ad sandboxes, producing inconsistent per-device load failures. Leave DOM `<img>` elements with no `src`; assign via JS from `assets.ts` at boot (`setEndcardHtmlAssets()`). |
|
||||||
|
| Audio keeps playing when ad hides | Add `visibilitychange` listener in the sound module — mute Phaser's sound system and `suspend()` the `AudioContext` when `document.hidden`, resume on return. Spec requires audio stop on hide/close. |
|
||||||
|
| `mraid.open()` silently no-ops | Guard with `mraid.getState() !== 'loading'` before calling; fall through to `window.open()` if still loading. |
|
||||||
|
| Previewer black screen with `Cannot read properties of null (reading 'appendChild')` in Phaser boot | Two compounding causes: (1) `vite-plugin-singlefile` hoists the bundled script into `<head>`, and the build strips `type="module"`, so the script runs **synchronously before `<body>` is parsed** — `document.body` is null. Wrap main.ts in a `DOMContentLoaded` gate (`if (document.readyState === 'loading') addEventListener('DOMContentLoaded', boot) else boot()`). (2) `parent: 'game'` (string selector) fails when the previewer sandbox strips custom DOM; create `<div id="game">` at runtime inside `boot()` and pass the **element reference** (not the string) to `Phaser.Game({ parent })`. The cascading `ScaleManager.resize → Cannot set properties of undefined (setting 'width')` errors all trace back to `game.canvas` never being created when either of these fail. |
|
||||||
|
| NineSlice won't shrink in landscape | Phaser's `NineSlice` silently clamps its minimum dimensions to `(leftWidth + rightWidth) × (topHeight + bottomHeight)` **in source pixels**. Symptom: one UI chrome element stays huge in landscape while every other `sd()`-driven element rescales correctly — because the requested `sd(H)` is below the inset total. Shrinking the insets fixes the scale clamp but stretches the art's rounded corners. The right fix: **operate the NineSlice in source-pixel space and scale it uniformly with `setScale(sd(1))`**. Keep `setSize(wSrc, hSrc)` in source px so the center stretches horizontally with text growth while corners stay intact; the `sd(1)` scale is what makes the whole object shrink in landscape, bypassing the min-dim clamp entirely. When reading `this.preview.width` (which is in scaled px) to decide `wSrc`, divide by `sd(1)` to convert back to source space. Tween callers that reset `setScale(1)` also need updating — the bg's base scale is now `sd(1)`, not 1. See [SelectionLine.ts](src/game/SelectionLine.ts) for the pattern. |
|
||||||
|
| Unity (un) submission: "not allowed to use window.top" | Luna's static scan flags the literal `window.top`, which Phaser 3 ships internally. In `build-all.mjs`, rewrite `window.top` → `window.self` for the `un` HTML only (other networks keep the original). Safe inside the playable's own frame because the iframe-vs-top check collapses to always-top. |
|
||||||
|
| MRAID network missing `mraid.js` | MRAID 3.0 creatives must request `mraid.js` early. Inject `<script src="mraid.js"></script>` exactly once for Applovin (`al`), Ironsource (`is`), and Unity (`un`), even if the container may also expose runtime MRAID objects. |
|
||||||
|
| MRAID listener wired too late | Previewers can probe MRAID before any Phaser scene is ready — if listeners are wired only inside `bindLifecycle` / scene `create()`, the creative can miss `ready`, `exposureChange`, or `viewableChange`. Fix: call `initMraid()` at `networks.ts` module-load time, guarded by `getState() === 'loading'` → `addEventListener('ready', setupMraid)` vs immediate call. Cache `_mraidViewable` / `_mraidExposed`; in `bindLifecycle` apply cached hidden/non-exposed state immediately. |
|
||||||
|
| MRAID 3.0 `exposureChange` not handled | MRAID 3.0 containers dispatch `exposureChange` with `exposedPercentage` directly instead of — or in addition to — `viewableChange`. If only listening to `viewableChange`, the ad may never receive pause signals on newer AL/IS/Unity builds. Register both: `mraid.addEventListener('exposureChange', exposedPercentage => onExposure(exposedPercentage > 0))` and `mraid.addEventListener('viewableChange', onViewable)` inside `initMraid()`. Seed initial state from `mraid.isViewable()` on ready. |
|
||||||
|
| MRAID 3.0 `audioVolumeChange` not handled | MRAID 3.0 containers fire `audioVolumeChange` with a volume level (0–100) or `null` when unavailable. Without a listener, the ad ignores host-level mute/unmute signals; if `null` is divided by 100, the ad can mute accidentally. Register `mraid.addEventListener('audioVolumeChange', v => { if (typeof v === 'number') scene.sound.setVolume(v / 100) })` in `initMraid()`. |
|
||||||
|
| MRAID `error` listener missing | Validators expect failed or unsupported MRAID calls to be observable. Register `mraid.addEventListener('error', (message, action) => console.warn('[MRAID error]', { message, action }))` during early MRAID setup. |
|
||||||
|
| MRAID `stateChange` listener missing | If the creative uses state-changing container behavior such as `mraid.close()`, `expand`, or `resize`, validators expect a `stateChange` listener. Register `mraid.addEventListener('stateChange', state => console.log('[MRAID stateChange]', state))` with the other early MRAID callbacks. |
|
||||||
|
| Custom close control not wired to MRAID | If the creative renders its own close button, the button must call a guarded close helper: `notifyGameClose()` then `mraid.close()` when `typeof mraid.close === 'function'` and `mraid.getState() !== 'loading'`. Do not use CTA/install buttons as close controls. |
|
||||||
|
| MRAID init not awaited before Phaser boot | If `new Phaser.Game()` is created before `initMraid()` resolves, the scene may fire `create()` before MRAID state is known — `bindLifecycle` then cannot apply a cached hidden/paused state. Make `boot()` async and `await initMraid()` before constructing the Phaser game. `initMraid()` must self-resolve after a timeout (~2 s) so a missing or non-firing MRAID container never blocks startup. |
|
||||||
|
| Late MRAID injection not handled | Some containers inject `window.mraid` after the script executes — a synchronous `typeof window.mraid !== 'undefined'` check at module load returns false even though MRAID will be present. After the immediate check fails, poll briefly (~500 ms) before concluding no-MRAID, then proceed. |
|
||||||
|
| Unsafe optional MRAID API calls | `useCustomClose()` was removed in MRAID 3.0, and APIs such as `expand`, `resize`, `storePicture`, and `createCalendarEvent` are optional/capability-dependent. Do not call them unless the project intentionally supports the feature and guards every call with `typeof mraid.method === 'function'` / `mraid.supports(...)` where relevant. |
|
||||||
|
|
||||||
|
## Ironsource — Runtime Analysis
|
||||||
|
Ironsource requires every `_is.html` build to pass **LevelPlay → Creative Management → Playable Workshop** (Runtime Analysis / Playable Validator) before launch. Skipping this can get the ad disabled. The validator runs in an iOS-like WKWebView sandbox and exposes console errors — use it as a free diagnostic channel for iPhone-only failures when a Mac + Safari remote-debug isn't available.
|
||||||
|
|
||||||
|
## Moloco — Upload Checklist & CTA Implementation
|
||||||
|
Creative specs: HTML5 (`.html` / `.htm`), < 5 MB, portrait + landscape.
|
||||||
|
|
||||||
|
Before uploading to Moloco Ads, confirm all three:
|
||||||
|
- [ ] No `XMLHttpRequest` anywhere in the ad (Moloco rejects it outright)
|
||||||
|
- [ ] CTA calls `FbPlayableAd.onCTAClick()` with no parameters — Moloco uses this for store redirect (not `window.clickTag`)
|
||||||
|
- [ ] No JavaScript redirects in ad file assets
|
||||||
|
|
||||||
|
### CTA implementation options
|
||||||
|
|
||||||
|
**Option 1 — event listener**
|
||||||
|
```html
|
||||||
|
<button id="ctaButton">Install</button>
|
||||||
|
<script>
|
||||||
|
document.getElementById('ctaButton').addEventListener('click', function() {
|
||||||
|
FbPlayableAd.onCTAClick();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Option 2 — inline onClick**
|
||||||
|
```html
|
||||||
|
<button onclick="FbPlayableAd.onCTAClick()">Install</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Moloco's validator requires `FbPlayableAd.onCTAClick()` — this is why it shares priority #2 in the CTA chain with Facebook. `window.clickTag` is kept as a fallback at priority #7.
|
||||||
|
|
||||||
|
***EOF***
|
||||||
|
[05/28/2026]
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
138
build.ps1
Normal file
138
build.ps1
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Builds both the VSCode extension (.vsix) and the standalone Windows exe.
|
||||||
|
Both artifacts land in dist/.
|
||||||
|
|
||||||
|
.EXAMPLE
|
||||||
|
.\build.ps1
|
||||||
|
.\build.ps1 -Standalone # Skip the extension; build only the exe
|
||||||
|
.\build.ps1 -Extension # Skip the standalone; build only the .vsix
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[switch]$Extension,
|
||||||
|
[switch]$Standalone
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$repoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
Set-Location $repoRoot
|
||||||
|
|
||||||
|
# If neither was specified, build both.
|
||||||
|
if (-not $Extension -and -not $Standalone) {
|
||||||
|
$Extension = $true
|
||||||
|
$Standalone = $true
|
||||||
|
}
|
||||||
|
|
||||||
|
$distDir = Join-Path $repoRoot "dist"
|
||||||
|
if (Test-Path $distDir) {
|
||||||
|
Remove-Item -Path (Join-Path $distDir "*") -Recurse -Force
|
||||||
|
}
|
||||||
|
New-Item -ItemType Directory -Path $distDir -Force | Out-Null
|
||||||
|
|
||||||
|
$pkg = Get-Content (Join-Path $repoRoot "package.json") -Raw | ConvertFrom-Json
|
||||||
|
$version = $pkg.version
|
||||||
|
|
||||||
|
function Write-Step($msg) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-FileSize($path) {
|
||||||
|
if (-not (Test-Path $path)) { return $null }
|
||||||
|
$bytes = (Get-Item $path).Length
|
||||||
|
if ($bytes -ge 1MB) { return "{0:N2} MB" -f ($bytes / 1MB) }
|
||||||
|
if ($bytes -ge 1KB) { return "{0:N1} KB" -f ($bytes / 1KB) }
|
||||||
|
return "$bytes B"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Ensure Go is on PATH (winget install doesn't update current session)
|
||||||
|
if (-not (Get-Command go -ErrorAction SilentlyContinue)) {
|
||||||
|
$goBin = "C:\Program Files\Go\bin"
|
||||||
|
if (Test-Path "$goBin\go.exe") {
|
||||||
|
$env:Path = "$goBin;$env:Path"
|
||||||
|
} else {
|
||||||
|
Write-Error "go not found on PATH. Install Go from https://go.dev/dl/"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$summary = @()
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# VSCode extension -> .vsix
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
if ($Extension) {
|
||||||
|
Write-Step "Building VSCode extension"
|
||||||
|
if (-not (Test-Path "node_modules")) {
|
||||||
|
Write-Host " node_modules missing - running npm install" -ForegroundColor Yellow
|
||||||
|
npm install
|
||||||
|
if ($LASTEXITCODE -ne 0) { Write-Error "npm install failed"; exit 1 }
|
||||||
|
}
|
||||||
|
npm run compile
|
||||||
|
if ($LASTEXITCODE -ne 0) { Write-Error "tsc compile failed"; exit 1 }
|
||||||
|
|
||||||
|
Write-Step "Packaging .vsix -> dist/"
|
||||||
|
$vsixTargetDir = $distDir
|
||||||
|
if (Get-Command vsce -ErrorAction SilentlyContinue) {
|
||||||
|
vsce package --out $vsixTargetDir
|
||||||
|
} else {
|
||||||
|
Write-Host " vsce not found - using npx @vscode/vsce" -ForegroundColor Yellow
|
||||||
|
npx --yes @vscode/vsce package --out $vsixTargetDir
|
||||||
|
}
|
||||||
|
if ($LASTEXITCODE -ne 0) { Write-Error "vsce package failed"; exit 1 }
|
||||||
|
|
||||||
|
$vsix = Get-ChildItem -Path $distDir -Filter "*.vsix" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
|
||||||
|
if ($vsix) {
|
||||||
|
$summary += [pscustomobject]@{
|
||||||
|
Artifact = $vsix.Name
|
||||||
|
Path = "dist\$($vsix.Name)"
|
||||||
|
Size = Get-FileSize $vsix.FullName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Standalone Windows exe -> dist/hpl-toolbox.exe
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
if ($Standalone) {
|
||||||
|
Write-Step "Building standalone exe -> dist/"
|
||||||
|
Push-Location (Join-Path $repoRoot "standalone")
|
||||||
|
try {
|
||||||
|
# If rsrc.syso is missing (e.g. fresh clone before icon embedding), regenerate.
|
||||||
|
if (-not (Test-Path "rsrc.syso") -and (Test-Path "hpl.ico")) {
|
||||||
|
if (Get-Command rsrc -ErrorAction SilentlyContinue) {
|
||||||
|
Write-Host " Regenerating rsrc.syso" -ForegroundColor Yellow
|
||||||
|
rsrc -ico hpl.ico -o rsrc.syso
|
||||||
|
} else {
|
||||||
|
Write-Host " rsrc tool missing - exe will build without embedded icon" -ForegroundColor Yellow
|
||||||
|
Write-Host " (install with: go install github.com/akavel/rsrc@latest)" -ForegroundColor Yellow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$exeName = "hpl-toolbox-$version.exe"
|
||||||
|
$exeOut = Join-Path $distDir $exeName
|
||||||
|
$embeddedReadme = Join-Path (Get-Location) "README.md"
|
||||||
|
Copy-Item -Path (Join-Path $repoRoot "README.md") -Destination $embeddedReadme -Force
|
||||||
|
try {
|
||||||
|
go build -tags release -ldflags="-s -w -H windowsgui -X main.AppVersion=$version" -trimpath -o $exeOut .
|
||||||
|
if ($LASTEXITCODE -ne 0) { Write-Error "go build failed"; exit 1 }
|
||||||
|
} finally {
|
||||||
|
Remove-Item -Path $embeddedReadme -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
|
||||||
|
$summary += [pscustomobject]@{
|
||||||
|
Artifact = $exeName
|
||||||
|
Path = "dist\$exeName"
|
||||||
|
Size = Get-FileSize $exeOut
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
Pop-Location
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Summary
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
Write-Step "Build complete"
|
||||||
|
$summary | Format-Table -AutoSize | Out-Host
|
||||||
BIN
dist/hpl-toolbox-0.2.3.exe
vendored
Normal file
BIN
dist/hpl-toolbox-0.2.3.exe
vendored
Normal file
Binary file not shown.
BIN
dist/hpl-toolbox-0.2.3.vsix
vendored
Normal file
BIN
dist/hpl-toolbox-0.2.3.vsix
vendored
Normal file
Binary file not shown.
Binary file not shown.
1
media/mintegral/preview-util.js
Normal file
1
media/mintegral/preview-util.js
Normal file
File diff suppressed because one or more lines are too long
53
package-lock.json
generated
53
package-lock.json
generated
@@ -1,15 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "hpl-toolbox",
|
"name": "hpl-toolbox",
|
||||||
"version": "0.1.0",
|
"version": "0.1.6",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "hpl-toolbox",
|
"name": "hpl-toolbox",
|
||||||
"version": "0.1.0",
|
"version": "0.1.6",
|
||||||
|
"license": "UNLICENSED",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^20.0.0",
|
"@types/node": "^20.0.0",
|
||||||
"@types/vscode": "^1.85.0",
|
"@types/vscode": "^1.85.0",
|
||||||
|
"playwright": "^1.60.0",
|
||||||
"typescript": "^5.4.0"
|
"typescript": "^5.4.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -33,6 +35,53 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/typescript": {
|
||||||
"version": "5.9.3",
|
"version": "5.9.3",
|
||||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||||
|
|||||||
49
package.json
49
package.json
@@ -1,13 +1,20 @@
|
|||||||
{
|
{
|
||||||
"name": "hpl-toolbox",
|
"name": "hpl-toolbox",
|
||||||
"displayName": "HPL Toolbox",
|
"displayName": "HPL Toolbox",
|
||||||
"description": "Bundled tools: PLEC Upload, AppLovin Demo Upload, Base64 Asset Scanner, Daily Update. Local HTML Host.",
|
"description": "Bundled tools: PLEC Upload, AppLovin Playable Preview, Base64 Scanner, MRAID Checker. Local HTML Host.",
|
||||||
"version": "0.1.2",
|
"version": "0.2.3",
|
||||||
"publisher": "hesukastro",
|
"publisher": "hesukastro",
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://gitea.hesukastro.com/hesukastro/vsix-hpl-toolbox.git"
|
||||||
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"vscode": "^1.85.0"
|
"vscode": "^1.85.0"
|
||||||
},
|
},
|
||||||
"categories": ["Other"],
|
"categories": [
|
||||||
|
"Other"
|
||||||
|
],
|
||||||
"icon": "media/hpl.png",
|
"icon": "media/hpl.png",
|
||||||
"main": "./out/extension.js",
|
"main": "./out/extension.js",
|
||||||
"activationEvents": [],
|
"activationEvents": [],
|
||||||
@@ -19,19 +26,35 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"command": "hplToolbox.openApplovinUpload",
|
"command": "hplToolbox.openApplovinUpload",
|
||||||
"title": "HPL Toolbox: Open AppLovin Demo Upload"
|
"title": "HPL Toolbox: Open AppLovin Playable Preview"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"command": "hplToolbox.openBase64Scanner",
|
"command": "hplToolbox.openBase64Scanner",
|
||||||
"title": "HPL Toolbox: Open Base64 Scanner"
|
"title": "HPL Toolbox: Open Base64 Scanner"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"command": "hplToolbox.openDailyUpdate",
|
"command": "hplToolbox.openMraidChecker",
|
||||||
"title": "HPL Toolbox: Open Daily Update"
|
"title": "HPL Toolbox: Open MRAID Checker"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"command": "hplToolbox.openSendToMobile",
|
"command": "hplToolbox.openSendToMobile",
|
||||||
"title": "HPL Toolbox: Open Send To Mobile"
|
"title": "HPL Toolbox: Open Send To Mobile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "hplToolbox.openPlayworksConverter",
|
||||||
|
"title": "HPL Toolbox: Open Playworks Converter"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "hplToolbox.openMintegralChecker",
|
||||||
|
"title": "HPL Toolbox: Open Mintegral Checker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "hplToolbox.openDeviceSimulator",
|
||||||
|
"title": "HPL Toolbox: Open Device Simulator"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "hplToolbox.checkForUpdates",
|
||||||
|
"title": "HPL Toolbox: Check for Updates"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"viewsContainers": {
|
"viewsContainers": {
|
||||||
@@ -48,7 +71,7 @@
|
|||||||
{
|
{
|
||||||
"type": "webview",
|
"type": "webview",
|
||||||
"id": "hplToolbox.launcher",
|
"id": "hplToolbox.launcher",
|
||||||
"name": "Tools"
|
"name": ""
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -85,6 +108,17 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "",
|
"default": "",
|
||||||
"description": "Value of the __Host-APPLOVINID cookie for p.applov.in (log in at https://p.applov.in/playablePreview?create=1&qr=1 and copy the cookie from DevTools)."
|
"description": "Value of the __Host-APPLOVINID cookie for p.applov.in (log in at https://p.applov.in/playablePreview?create=1&qr=1 and copy the cookie from DevTools)."
|
||||||
|
},
|
||||||
|
"hplToolbox.applovin.delayMs": {
|
||||||
|
"type": "number",
|
||||||
|
"default": 5000,
|
||||||
|
"minimum": 0,
|
||||||
|
"description": "Delay (in milliseconds) between consecutive file uploads, to avoid AppLovin rate limiting / 403 responses."
|
||||||
|
},
|
||||||
|
"hplToolbox.applovin.randomizeUserAgent": {
|
||||||
|
"type": "boolean",
|
||||||
|
"default": true,
|
||||||
|
"description": "Randomize the User-Agent header on every request to p.applov.in to reduce bot detection."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -108,6 +142,7 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^20.0.0",
|
"@types/node": "^20.0.0",
|
||||||
"@types/vscode": "^1.85.0",
|
"@types/vscode": "^1.85.0",
|
||||||
|
"playwright": "^1.60.0",
|
||||||
"typescript": "^5.4.0"
|
"typescript": "^5.4.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
11
run-standalone.ps1
Normal file
11
run-standalone.ps1
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
$standalone = Join-Path $root 'standalone'
|
||||||
|
|
||||||
|
Push-Location $standalone
|
||||||
|
try {
|
||||||
|
go run .
|
||||||
|
} finally {
|
||||||
|
Pop-Location
|
||||||
|
}
|
||||||
177
scripts/check-dogcat3-playwright.mjs
Normal file
177
scripts/check-dogcat3-playwright.mjs
Normal 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;
|
||||||
|
});
|
||||||
222
src/changelogView.ts
Normal file
222
src/changelogView.ts
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
|
||||||
|
export function openChangelog(context: vscode.ExtensionContext) {
|
||||||
|
const panel = vscode.window.createWebviewPanel(
|
||||||
|
'hplToolbox.changelog',
|
||||||
|
'HPL Toolbox Changelog',
|
||||||
|
vscode.ViewColumn.One,
|
||||||
|
{ enableScripts: false }
|
||||||
|
);
|
||||||
|
const readmePath = path.join(context.extensionPath, 'README.md');
|
||||||
|
let markdown = '# Changelog\n\nREADME.md was not found.';
|
||||||
|
try {
|
||||||
|
markdown = fs.readFileSync(readmePath, 'utf8');
|
||||||
|
} catch {
|
||||||
|
// Keep the fallback text readable in packaged or development installs.
|
||||||
|
}
|
||||||
|
panel.webview.html = getHtml(renderMarkdown(markdown));
|
||||||
|
}
|
||||||
|
|
||||||
|
function getHtml(content: string): string {
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 18px;
|
||||||
|
font-family: var(--vscode-font-family);
|
||||||
|
font-size: var(--vscode-font-size);
|
||||||
|
background: var(--vscode-editor-background);
|
||||||
|
color: var(--vscode-foreground);
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
max-width: 840px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
margin: 0 0 14px;
|
||||||
|
font-size: 20px;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
margin: 18px 0 8px;
|
||||||
|
padding-top: 12px;
|
||||||
|
border-top: 1px solid var(--vscode-panel-border);
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
h3 {
|
||||||
|
margin: 14px 0 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
strong {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
ul {
|
||||||
|
margin: 6px 0 12px;
|
||||||
|
padding-left: 20px;
|
||||||
|
}
|
||||||
|
li {
|
||||||
|
margin: 4px 0;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
p {
|
||||||
|
margin: 8px 0;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
code {
|
||||||
|
font-family: var(--vscode-editor-font-family, monospace);
|
||||||
|
font-size: 0.95em;
|
||||||
|
background: var(--vscode-textCodeBlock-background);
|
||||||
|
padding: 1px 4px;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
.changelog-block {
|
||||||
|
margin: 8px 0 18px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--vscode-panel-border);
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--vscode-textCodeBlock-background);
|
||||||
|
}
|
||||||
|
.change-section {
|
||||||
|
margin: 8px 0 4px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.changelog-block ul {
|
||||||
|
margin: 4px 0 10px;
|
||||||
|
}
|
||||||
|
.changelog-block li.nested {
|
||||||
|
margin-left: 18px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>${content}</main>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderMarkdown(markdown: string): string {
|
||||||
|
const lines = markdown.replace(/\r\n/g, '\n').split('\n');
|
||||||
|
const html: string[] = [];
|
||||||
|
let inList = false;
|
||||||
|
let inCodeBlock = false;
|
||||||
|
let codeLines: string[] = [];
|
||||||
|
|
||||||
|
const closeList = () => {
|
||||||
|
if (inList) {
|
||||||
|
html.push('</ul>');
|
||||||
|
inList = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const rawLine of lines) {
|
||||||
|
if (rawLine.trim() === '```') {
|
||||||
|
closeList();
|
||||||
|
if (inCodeBlock) {
|
||||||
|
html.push(renderChangelogBlock(codeLines));
|
||||||
|
codeLines = [];
|
||||||
|
inCodeBlock = false;
|
||||||
|
} else {
|
||||||
|
inCodeBlock = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (inCodeBlock) {
|
||||||
|
codeLines.push(rawLine);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const line = rawLine.trim();
|
||||||
|
if (!line) {
|
||||||
|
closeList();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const heading = line.match(/^(#{1,3})\s+(.+)$/);
|
||||||
|
if (heading) {
|
||||||
|
closeList();
|
||||||
|
const level = Math.min(heading[1].length, 2);
|
||||||
|
html.push(`<h${level}>${renderInlineMarkdown(heading[2])}</h${level}>`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const boldHeading = line.match(/^\*\*(.+)\*\*$/);
|
||||||
|
if (boldHeading) {
|
||||||
|
closeList();
|
||||||
|
html.push(`<h2>${escapeHtml(boldHeading[1])}</h2>`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const listItem = line.match(/^-\s+(.+)$/);
|
||||||
|
if (listItem) {
|
||||||
|
if (!inList) {
|
||||||
|
html.push('<ul>');
|
||||||
|
inList = true;
|
||||||
|
}
|
||||||
|
html.push(`<li>${renderInlineMarkdown(listItem[1])}</li>`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
closeList();
|
||||||
|
html.push(`<p>${renderInlineMarkdown(line)}</p>`);
|
||||||
|
}
|
||||||
|
if (inCodeBlock) {
|
||||||
|
html.push(renderChangelogBlock(codeLines));
|
||||||
|
}
|
||||||
|
closeList();
|
||||||
|
return html.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderChangelogBlock(lines: string[]): string {
|
||||||
|
const html: string[] = ['<div class="changelog-block">'];
|
||||||
|
let inList = false;
|
||||||
|
|
||||||
|
const closeList = () => {
|
||||||
|
if (inList) {
|
||||||
|
html.push('</ul>');
|
||||||
|
inList = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const rawLine of lines) {
|
||||||
|
const line = rawLine.trim();
|
||||||
|
if (!line) {
|
||||||
|
closeList();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const listItem = line.match(/^-\s+(.+)$/);
|
||||||
|
if (listItem) {
|
||||||
|
if (!inList) {
|
||||||
|
html.push('<ul>');
|
||||||
|
inList = true;
|
||||||
|
}
|
||||||
|
const nested = rawLine.match(/^\s{8,}-\s+/) ? ' class="nested"' : '';
|
||||||
|
html.push(`<li${nested}>${renderInlineMarkdown(listItem[1])}</li>`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
closeList();
|
||||||
|
html.push(`<div class="change-section">${renderInlineMarkdown(line)}</div>`);
|
||||||
|
}
|
||||||
|
closeList();
|
||||||
|
html.push('</div>');
|
||||||
|
return html.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInlineMarkdown(value: string): string {
|
||||||
|
return escapeHtml(value)
|
||||||
|
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
||||||
|
.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(value: string): string {
|
||||||
|
return value.replace(/[&<>"']/g, ch => ({
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
"'": ''',
|
||||||
|
}[ch] ?? ch));
|
||||||
|
}
|
||||||
@@ -3,18 +3,30 @@ import { LauncherViewProvider } from './launcherView';
|
|||||||
import { openPlecUpload } from './tools/plecUpload';
|
import { openPlecUpload } from './tools/plecUpload';
|
||||||
import { openApplovinUpload } from './tools/applovinUpload';
|
import { openApplovinUpload } from './tools/applovinUpload';
|
||||||
import { openBase64Scanner } from './tools/base64Scanner';
|
import { openBase64Scanner } from './tools/base64Scanner';
|
||||||
import { openDailyUpdate } from './tools/dailyUpdate';
|
import { openMraidChecker } from './tools/mraidChecker';
|
||||||
import { openSendToMobile } from './tools/sendToMobile';
|
import { openSendToMobile } from './tools/sendToMobile';
|
||||||
|
import { openPlayworksConverter } from './tools/playworksConverter';
|
||||||
|
import { openMintegralChecker } from './tools/mintegralChecker';
|
||||||
|
import { openChangelog } from './changelogView';
|
||||||
|
import { openDeviceSimulator } from './tools/deviceSimulator';
|
||||||
|
import { checkForUpdates } from './updateChecker';
|
||||||
|
|
||||||
export function activate(context: vscode.ExtensionContext) {
|
export function activate(context: vscode.ExtensionContext) {
|
||||||
context.subscriptions.push(
|
context.subscriptions.push(
|
||||||
vscode.commands.registerCommand('hplToolbox.openPlecUpload', () => openPlecUpload(context)),
|
vscode.commands.registerCommand('hplToolbox.openPlecUpload', () => openPlecUpload(context)),
|
||||||
vscode.commands.registerCommand('hplToolbox.openApplovinUpload', () => openApplovinUpload(context)),
|
vscode.commands.registerCommand('hplToolbox.openApplovinUpload', () => openApplovinUpload(context)),
|
||||||
vscode.commands.registerCommand('hplToolbox.openBase64Scanner', () => openBase64Scanner(context)),
|
vscode.commands.registerCommand('hplToolbox.openBase64Scanner', () => openBase64Scanner(context)),
|
||||||
vscode.commands.registerCommand('hplToolbox.openDailyUpdate', () => openDailyUpdate(context)),
|
vscode.commands.registerCommand('hplToolbox.openMraidChecker', () => openMraidChecker(context)),
|
||||||
vscode.commands.registerCommand('hplToolbox.openSendToMobile', () => openSendToMobile(context)),
|
vscode.commands.registerCommand('hplToolbox.openSendToMobile', () => openSendToMobile(context)),
|
||||||
vscode.window.registerWebviewViewProvider('hplToolbox.launcher', new LauncherViewProvider())
|
vscode.commands.registerCommand('hplToolbox.openPlayworksConverter', () => openPlayworksConverter(context)),
|
||||||
|
vscode.commands.registerCommand('hplToolbox.openMintegralChecker', () => openMintegralChecker(context)),
|
||||||
|
vscode.commands.registerCommand('hplToolbox.openDeviceSimulator', () => openDeviceSimulator(context)),
|
||||||
|
vscode.commands.registerCommand('hplToolbox.openChangelog', () => openChangelog(context)),
|
||||||
|
vscode.commands.registerCommand('hplToolbox.checkForUpdates', () => checkForUpdates(context)),
|
||||||
|
vscode.window.registerWebviewViewProvider('hplToolbox.launcher', new LauncherViewProvider(context))
|
||||||
);
|
);
|
||||||
|
|
||||||
|
void checkForUpdates(context);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deactivate() {}
|
export function deactivate() {}
|
||||||
|
|||||||
@@ -1,69 +1,314 @@
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
const BETA_TOOLS_ENABLED_KEY = 'hplToolbox.betaTools.enabled';
|
||||||
|
const TOOL_ORDER_KEY = 'hplToolbox.toolOrder.v1';
|
||||||
|
|
||||||
|
interface ToolDefinition {
|
||||||
|
id?: string;
|
||||||
|
command: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
beta?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FALLBACK_TOOLS: ToolDefinition[] = [
|
||||||
|
{
|
||||||
|
command: 'hplToolbox.openPlecUpload',
|
||||||
|
title: 'PLEC Upload',
|
||||||
|
description: 'Upload HTML to internal PLEC server',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command: 'hplToolbox.openApplovinUpload',
|
||||||
|
title: 'AppLovin Playable Preview',
|
||||||
|
description: 'Upload to p.applov.in (QR preview)',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command: 'hplToolbox.openBase64Scanner',
|
||||||
|
title: 'Base64 Scanner',
|
||||||
|
description: 'Find non-base64 assets in HTML',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command: 'hplToolbox.openSendToMobile',
|
||||||
|
title: 'Send To Mobile',
|
||||||
|
description: 'Share HTML to a phone via LAN + QR',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command: 'hplToolbox.openMraidChecker',
|
||||||
|
title: 'MRAID Checker',
|
||||||
|
description: 'Check MRAID requirements and best practices',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command: 'hplToolbox.openPlayworksConverter',
|
||||||
|
title: 'Playworks Converter',
|
||||||
|
description: 'Convert Playworks HTML to per-network variants',
|
||||||
|
beta: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
export class LauncherViewProvider implements vscode.WebviewViewProvider {
|
export class LauncherViewProvider implements vscode.WebviewViewProvider {
|
||||||
|
constructor(private readonly context: vscode.ExtensionContext) { }
|
||||||
|
|
||||||
resolveWebviewView(view: vscode.WebviewView) {
|
resolveWebviewView(view: vscode.WebviewView) {
|
||||||
view.webview.options = { enableScripts: true };
|
view.webview.options = { enableScripts: true };
|
||||||
view.webview.html = getHtml();
|
const version = this.context.extension.packageJSON.version as string;
|
||||||
view.webview.onDidReceiveMessage((msg) => {
|
const tools = loadToolDefinitions(this.context.extensionPath);
|
||||||
|
const betaToolsEnabled = this.context.globalState.get<boolean>(BETA_TOOLS_ENABLED_KEY, false);
|
||||||
|
const toolOrder = this.context.globalState.get<string[]>(TOOL_ORDER_KEY, []);
|
||||||
|
view.webview.html = getHtml(version, betaToolsEnabled, tools, toolOrder);
|
||||||
|
view.webview.onDidReceiveMessage(async (msg) => {
|
||||||
if (msg?.type === 'open' && typeof msg.command === 'string') {
|
if (msg?.type === 'open' && typeof msg.command === 'string') {
|
||||||
vscode.commands.executeCommand(msg.command);
|
vscode.commands.executeCommand(msg.command);
|
||||||
|
} else if (msg?.type === 'openChangelog') {
|
||||||
|
vscode.commands.executeCommand('hplToolbox.openChangelog');
|
||||||
|
} else if (msg?.type === 'checkForUpdates') {
|
||||||
|
vscode.commands.executeCommand('hplToolbox.checkForUpdates');
|
||||||
|
} else if (msg?.type === 'setBetaToolsEnabled' && typeof msg.enabled === 'boolean') {
|
||||||
|
await this.context.globalState.update(BETA_TOOLS_ENABLED_KEY, msg.enabled);
|
||||||
|
view.webview.html = getHtml(version, msg.enabled, tools, this.context.globalState.get<string[]>(TOOL_ORDER_KEY, []));
|
||||||
|
} else if (msg?.type === 'setToolOrder' && Array.isArray(msg.order)) {
|
||||||
|
await this.context.globalState.update(TOOL_ORDER_KEY, msg.order.filter((id: unknown) => typeof id === 'string'));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getHtml(): string {
|
function loadToolDefinitions(extensionPath: string): ToolDefinition[] {
|
||||||
|
const toolsPath = path.join(extensionPath, 'tools.json');
|
||||||
|
try {
|
||||||
|
const raw = JSON.parse(fs.readFileSync(toolsPath, 'utf8'));
|
||||||
|
if (!Array.isArray(raw)) return FALLBACK_TOOLS;
|
||||||
|
const tools = raw
|
||||||
|
.filter((tool: any) => tool && typeof tool.command === 'string' && typeof tool.title === 'string')
|
||||||
|
.map((tool: any) => ({
|
||||||
|
id: typeof tool.id === 'string' ? tool.id : undefined,
|
||||||
|
command: tool.command,
|
||||||
|
title: tool.title,
|
||||||
|
description: typeof tool.description === 'string' ? tool.description : '',
|
||||||
|
beta: Boolean(tool.beta),
|
||||||
|
}));
|
||||||
|
return tools.length ? tools : FALLBACK_TOOLS;
|
||||||
|
} catch {
|
||||||
|
return FALLBACK_TOOLS;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getHtml(version: string, betaToolsEnabled: boolean, tools: ToolDefinition[], toolOrder: string[]): string {
|
||||||
|
const visibleTools = sortToolsForDisplay(tools.filter(tool => betaToolsEnabled || !tool.beta), toolOrder);
|
||||||
|
const toolButtons = visibleTools.map(renderToolButton).join('\n');
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<style>
|
<style>
|
||||||
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 12px 8px; }
|
* { box-sizing: border-box; }
|
||||||
h3 { margin: 0 0 12px 0; font-size: 11px; text-transform: uppercase; letter-spacing: 0.6px; opacity: 0.7; }
|
body {
|
||||||
|
min-height: 100vh;
|
||||||
|
margin: 0;
|
||||||
|
padding: 10px 8px 8px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
font-family: var(--vscode-font-family);
|
||||||
|
font-size: var(--vscode-font-size);
|
||||||
|
background: var(--vscode-sideBar-background, var(--vscode-editor-background));
|
||||||
|
color: var(--vscode-foreground);
|
||||||
|
}
|
||||||
|
.tools {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
.tool-btn {
|
.tool-btn {
|
||||||
display: block; width: 100%; text-align: left;
|
display: block;
|
||||||
padding: 8px 10px; margin-bottom: 6px;
|
width: 100%;
|
||||||
background: var(--vscode-button-secondaryBackground);
|
min-height: 52px;
|
||||||
color: var(--vscode-button-secondaryForeground);
|
padding: 8px 9px;
|
||||||
border: 1px solid var(--vscode-panel-border);
|
text-align: left;
|
||||||
border-radius: 3px; cursor: pointer; font-size: 13px;
|
background: var(--vscode-list-inactiveSelectionBackground, var(--vscode-button-secondaryBackground));
|
||||||
|
color: var(--vscode-foreground);
|
||||||
|
border: 1px solid var(--vscode-panel-border, transparent);
|
||||||
|
border-radius: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
.tool-btn.dragging {
|
||||||
|
opacity: 0.55;
|
||||||
}
|
}
|
||||||
.tool-btn:hover {
|
.tool-btn:hover {
|
||||||
background: var(--vscode-button-secondaryHoverBackground);
|
background: var(--vscode-list-hoverBackground, var(--vscode-button-secondaryHoverBackground));
|
||||||
|
border-color: var(--vscode-focusBorder, var(--vscode-panel-border));
|
||||||
|
}
|
||||||
|
.tool-btn:focus {
|
||||||
|
outline: 1px solid var(--vscode-focusBorder);
|
||||||
|
outline-offset: 1px;
|
||||||
|
}
|
||||||
|
.tool-btn:active {
|
||||||
|
background: var(--vscode-list-activeSelectionBackground, var(--vscode-button-background));
|
||||||
|
color: var(--vscode-list-activeSelectionForeground, var(--vscode-button-foreground));
|
||||||
|
}
|
||||||
|
.tool-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
.tool-desc {
|
||||||
|
display: block;
|
||||||
|
margin-top: 4px;
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
.beta-badge {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 1px 5px;
|
||||||
|
border: 1px solid var(--vscode-panel-border);
|
||||||
|
border-radius: 3px;
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: 10px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
.footer {
|
||||||
|
margin-top: auto;
|
||||||
|
padding-top: 8px;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr auto 1fr;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: 8px;
|
||||||
|
border-top: 1px solid var(--vscode-panel-border);
|
||||||
|
}
|
||||||
|
.footer-action {
|
||||||
|
padding: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
border: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 10px;
|
||||||
|
opacity: 0.72;
|
||||||
|
}
|
||||||
|
#betaToggle {
|
||||||
|
justify-self: start;
|
||||||
|
}
|
||||||
|
.footer-action:hover {
|
||||||
|
opacity: 1;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
.footer-version {
|
||||||
|
opacity: 0.75;
|
||||||
|
text-align: center;
|
||||||
|
white-space: nowrap;
|
||||||
|
justify-self: center;
|
||||||
|
}
|
||||||
|
.changelog-link {
|
||||||
|
justify-self: end;
|
||||||
|
text-align: right;
|
||||||
}
|
}
|
||||||
.tool-desc { display: block; font-size: 11px; opacity: 0.7; margin-top: 2px; }
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h3>HPL Toolbox</h3>
|
<div class="tools">
|
||||||
<button class="tool-btn" data-cmd="hplToolbox.openPlecUpload">
|
${toolButtons}
|
||||||
PLEC Upload
|
</div>
|
||||||
<span class="tool-desc">Upload HTML to internal PLEC server</span>
|
<div class="footer">
|
||||||
</button>
|
<button id="betaToggle" class="footer-action" data-enabled="${betaToolsEnabled ? 'true' : 'false'}">${betaToolsEnabled ? 'Hide beta' : 'Show beta'}</button>
|
||||||
<button class="tool-btn" data-cmd="hplToolbox.openApplovinUpload">
|
<button id="updateCheck" class="footer-action footer-version" title="Check for updates">${version} - JJGC 00784</button>
|
||||||
AppLovin Demo Upload
|
<button id="changelogLink" class="footer-action changelog-link">Changelog</button>
|
||||||
<span class="tool-desc">Upload to p.applov.in (QR preview)</span>
|
</div>
|
||||||
</button>
|
|
||||||
<button class="tool-btn" data-cmd="hplToolbox.openBase64Scanner">
|
|
||||||
Base64 Scanner
|
|
||||||
<span class="tool-desc">Find non-base64 assets in HTML</span>
|
|
||||||
</button>
|
|
||||||
<button class="tool-btn" data-cmd="hplToolbox.openDailyUpdate">
|
|
||||||
Daily Update
|
|
||||||
<span class="tool-desc">Compose & copy a daily status</span>
|
|
||||||
</button>
|
|
||||||
<button class="tool-btn" data-cmd="hplToolbox.openSendToMobile">
|
|
||||||
Send To Mobile
|
|
||||||
<span class="tool-desc">Share HTML to a phone via LAN + QR</span>
|
|
||||||
</button>
|
|
||||||
<script>
|
<script>
|
||||||
const vscode = acquireVsCodeApi();
|
const vscode = acquireVsCodeApi();
|
||||||
document.querySelectorAll('.tool-btn').forEach((btn) => {
|
document.querySelectorAll('.tool-btn').forEach((btn) => {
|
||||||
btn.addEventListener('click', () => {
|
btn.addEventListener('click', () => {
|
||||||
|
if (btn.dataset.dragging === 'true') {
|
||||||
|
btn.dataset.dragging = 'false';
|
||||||
|
return;
|
||||||
|
}
|
||||||
vscode.postMessage({ type: 'open', command: btn.dataset.cmd });
|
vscode.postMessage({ type: 'open', command: btn.dataset.cmd });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
const toolsEl = document.querySelector('.tools');
|
||||||
|
let dragged = null;
|
||||||
|
toolsEl.querySelectorAll('.tool-btn').forEach((btn) => {
|
||||||
|
btn.draggable = true;
|
||||||
|
btn.addEventListener('dragstart', (event) => {
|
||||||
|
dragged = btn;
|
||||||
|
btn.classList.add('dragging');
|
||||||
|
event.dataTransfer.effectAllowed = 'move';
|
||||||
|
event.dataTransfer.setData('text/plain', btn.dataset.id || '');
|
||||||
|
});
|
||||||
|
btn.addEventListener('dragend', () => {
|
||||||
|
btn.classList.remove('dragging');
|
||||||
|
btn.dataset.dragging = 'true';
|
||||||
|
dragged = null;
|
||||||
|
persistToolOrder();
|
||||||
|
setTimeout(() => { btn.dataset.dragging = 'false'; }, 0);
|
||||||
|
});
|
||||||
|
btn.addEventListener('dragover', (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!dragged || dragged === btn) return;
|
||||||
|
const rect = btn.getBoundingClientRect();
|
||||||
|
const after = event.clientY > rect.top + rect.height / 2;
|
||||||
|
toolsEl.insertBefore(dragged, after ? btn.nextSibling : btn);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
function persistToolOrder() {
|
||||||
|
vscode.postMessage({
|
||||||
|
type: 'setToolOrder',
|
||||||
|
order: Array.from(toolsEl.querySelectorAll('.tool-btn')).map(btn => btn.dataset.id).filter(Boolean),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
document.getElementById('betaToggle').addEventListener('click', (event) => {
|
||||||
|
const enabled = event.currentTarget.dataset.enabled === 'true';
|
||||||
|
vscode.postMessage({ type: 'setBetaToolsEnabled', enabled: !enabled });
|
||||||
|
});
|
||||||
|
document.getElementById('changelogLink').addEventListener('click', () => {
|
||||||
|
vscode.postMessage({ type: 'openChangelog' });
|
||||||
|
});
|
||||||
|
document.getElementById('updateCheck').addEventListener('click', () => {
|
||||||
|
vscode.postMessage({ type: 'checkForUpdates' });
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sortToolsForDisplay(tools: ToolDefinition[], toolOrder: string[]): ToolDefinition[] {
|
||||||
|
const order = new Map(toolOrder.map((id, index) => [id, index]));
|
||||||
|
return [...tools].sort((a, b) => {
|
||||||
|
const aId = toolId(a);
|
||||||
|
const bId = toolId(b);
|
||||||
|
const ai = order.has(aId) ? order.get(aId)! : Number.MAX_SAFE_INTEGER;
|
||||||
|
const bi = order.has(bId) ? order.get(bId)! : Number.MAX_SAFE_INTEGER;
|
||||||
|
if (ai !== bi) return ai - bi;
|
||||||
|
return Number(Boolean(a.beta)) - Number(Boolean(b.beta));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderToolButton(tool: ToolDefinition): string {
|
||||||
|
return ` <button class="tool-btn" data-id="${escapeHtml(toolId(tool))}" data-cmd="${escapeHtml(tool.command)}">
|
||||||
|
<span class="tool-title">${escapeHtml(tool.title)}${tool.beta ? ' <span class="beta-badge">Beta</span>' : ''}</span>
|
||||||
|
<span class="tool-desc">${escapeHtml(tool.description)}</span>
|
||||||
|
</button>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toolId(tool: ToolDefinition): string {
|
||||||
|
return tool.id || tool.command;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(value: string): string {
|
||||||
|
return value.replace(/[&<>"']/g, ch => ({
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
"'": ''',
|
||||||
|
}[ch] ?? ch));
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ import * as vscode from 'vscode';
|
|||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import { File } from 'node:buffer';
|
import { File } from 'node:buffer';
|
||||||
import { handleClipboardAndOpen, singletonPanel } from './shared';
|
import { getToolWebviewStyles, handleClipboardAndOpen, singletonPanel } from './shared';
|
||||||
|
|
||||||
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
||||||
|
|
||||||
export function openApplovinUpload(_context: vscode.ExtensionContext) {
|
export function openApplovinUpload(_context: vscode.ExtensionContext) {
|
||||||
const { panel, isNew } = singletonPanel(store, 'hplToolbox.applovinUpload', 'AppLovin Demo Upload');
|
const { panel, isNew } = singletonPanel(store, 'hplToolbox.applovinUpload', 'AppLovin Playable Preview');
|
||||||
if (!isNew) return;
|
if (!isNew) return;
|
||||||
|
|
||||||
panel.webview.html = getHtml();
|
panel.webview.html = getHtml();
|
||||||
@@ -15,11 +15,30 @@ export function openApplovinUpload(_context: vscode.ExtensionContext) {
|
|||||||
try {
|
try {
|
||||||
if (handleClipboardAndOpen(msg)) return;
|
if (handleClipboardAndOpen(msg)) return;
|
||||||
|
|
||||||
|
if (msg.type === 'pickFolder') {
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFolders: true,
|
||||||
|
canSelectFiles: false,
|
||||||
|
canSelectMany: false,
|
||||||
|
openLabel: 'Select Folder',
|
||||||
|
defaultUri: getPickerDefaultUri(),
|
||||||
|
});
|
||||||
|
if (picked && picked[0]) {
|
||||||
|
const files = await collectHtmlFiles(picked[0].fsPath);
|
||||||
|
panel.webview.postMessage({
|
||||||
|
type: 'filesSelected',
|
||||||
|
files: files.map(filePath => ({ path: filePath, name: path.basename(filePath) })),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (msg.type === 'pickFiles') {
|
if (msg.type === 'pickFiles') {
|
||||||
const picked = await vscode.window.showOpenDialog({
|
const picked = await vscode.window.showOpenDialog({
|
||||||
canSelectMany: true,
|
canSelectMany: true,
|
||||||
filters: { HTML: ['html', 'htm'] },
|
filters: { HTML: ['html', 'htm'] },
|
||||||
openLabel: 'Select',
|
openLabel: 'Select',
|
||||||
|
defaultUri: getPickerDefaultUri(),
|
||||||
});
|
});
|
||||||
if (picked && picked.length) {
|
if (picked && picked.length) {
|
||||||
panel.webview.postMessage({
|
panel.webview.postMessage({
|
||||||
@@ -34,15 +53,46 @@ export function openApplovinUpload(_context: vscode.ExtensionContext) {
|
|||||||
await handleUpload(panel, msg.paths);
|
await handleUpload(panel, msg.paths);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (msg.type === 'saveQr') {
|
||||||
|
await handleSaveQr(panel, msg.url, msg.name);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.type === 'saveAllQrs') {
|
||||||
|
await handleSaveAllQrs(panel, msg.items || []);
|
||||||
|
return;
|
||||||
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
panel.webview.postMessage({ type: 'error', message: err?.message || String(err) });
|
panel.webview.postMessage({ type: 'error', message: err?.message || String(err) });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const USER_AGENTS = [
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0',
|
||||||
|
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||||||
|
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15',
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0',
|
||||||
|
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||||||
|
];
|
||||||
|
|
||||||
|
function pickUserAgent(randomize: boolean): string {
|
||||||
|
if (!randomize) return USER_AGENTS[0];
|
||||||
|
return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
async function handleUpload(panel: vscode.WebviewPanel, filePaths: string[]) {
|
async function handleUpload(panel: vscode.WebviewPanel, filePaths: string[]) {
|
||||||
const cfg = vscode.workspace.getConfiguration('hplToolbox.applovin');
|
const cfg = vscode.workspace.getConfiguration('hplToolbox.applovin');
|
||||||
const cookie = (cfg.get<string>('cookie') || '').trim();
|
const cookie = (cfg.get<string>('cookie') || '').trim();
|
||||||
|
const delayMs = Math.max(0, cfg.get<number>('delayMs') ?? 1500);
|
||||||
|
const randomizeUA = cfg.get<boolean>('randomizeUserAgent') ?? true;
|
||||||
|
|
||||||
const paths = Array.isArray(filePaths) ? filePaths : [filePaths];
|
const paths = Array.isArray(filePaths) ? filePaths : [filePaths];
|
||||||
if (!paths.length) {
|
if (!paths.length) {
|
||||||
@@ -50,14 +100,17 @@ async function handleUpload(panel: vscode.WebviewPanel, filePaths: string[]) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const headers: Record<string, string> = {
|
const buildHeaders = (): Record<string, string> => {
|
||||||
'Accept': 'application/json, text/javascript, */*; q=0.01',
|
const headers: Record<string, string> = {
|
||||||
'Origin': 'https://p.applov.in',
|
'Accept': 'application/json, text/javascript, */*; q=0.01',
|
||||||
'Referer': 'https://p.applov.in/playablePreview?create=1&qr=1',
|
'Origin': 'https://p.applov.in',
|
||||||
'X-Requested-With': 'XMLHttpRequest',
|
'Referer': 'https://p.applov.in/playablePreview?create=1&qr=1',
|
||||||
'User-Agent': 'Mozilla/5.0 (HPL-Toolbox-VSCode)',
|
'X-Requested-With': 'XMLHttpRequest',
|
||||||
|
'User-Agent': pickUserAgent(randomizeUA),
|
||||||
|
};
|
||||||
|
if (cookie) headers['Cookie'] = `__Host-APPLOVINID=${cookie}`;
|
||||||
|
return headers;
|
||||||
};
|
};
|
||||||
if (cookie) headers['Cookie'] = `__Host-APPLOVINID=${cookie}`;
|
|
||||||
|
|
||||||
const buildForm = (filePath: string): FormData => {
|
const buildForm = (filePath: string): FormData => {
|
||||||
const buf = fs.readFileSync(filePath);
|
const buf = fs.readFileSync(filePath);
|
||||||
@@ -80,12 +133,17 @@ async function handleUpload(panel: vscode.WebviewPanel, filePaths: string[]) {
|
|||||||
if (!filePath || !fs.existsSync(filePath)) { reportError('File missing'); continue; }
|
if (!filePath || !fs.existsSync(filePath)) { reportError('File missing'); continue; }
|
||||||
if (!/\.html?$/i.test(filePath)) { reportError('Must be .html'); continue; }
|
if (!/\.html?$/i.test(filePath)) { reportError('Must be .html'); continue; }
|
||||||
|
|
||||||
panel.webview.postMessage({ type: 'status', message: `[${idx}/${paths.length}] Validating ${fileName}...` });
|
if (i > 0 && delayMs > 0) {
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Waiting ${idx}/${paths.length} ${fileName}` });
|
||||||
|
await sleep(delayMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Validating ${idx}/${paths.length} ${fileName}` });
|
||||||
|
|
||||||
let res: Response;
|
let res: Response;
|
||||||
try {
|
try {
|
||||||
res = await fetch('https://p.applov.in/validateHTMLContent', {
|
res = await fetch('https://p.applov.in/validateHTMLContent', {
|
||||||
method: 'POST', body: buildForm(filePath), headers,
|
method: 'POST', body: buildForm(filePath), headers: buildHeaders(),
|
||||||
});
|
});
|
||||||
} catch (err: any) { reportError('Network error (validate): ' + (err?.message || err)); continue; }
|
} catch (err: any) { reportError('Network error (validate): ' + (err?.message || err)); continue; }
|
||||||
const validateText = await res.text();
|
const validateText = await res.text();
|
||||||
@@ -96,11 +154,11 @@ async function handleUpload(panel: vscode.WebviewPanel, filePaths: string[]) {
|
|||||||
reportError(`Validation failed: ${validateText.slice(0, 300)}`); continue;
|
reportError(`Validation failed: ${validateText.slice(0, 300)}`); continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
panel.webview.postMessage({ type: 'status', message: `[${idx}/${paths.length}] Uploading ${fileName}...` });
|
panel.webview.postMessage({ type: 'status', message: `Uploading ${idx}/${paths.length} ${fileName}` });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
res = await fetch('https://p.applov.in/getCachedAdURL', {
|
res = await fetch('https://p.applov.in/getCachedAdURL', {
|
||||||
method: 'POST', body: buildForm(filePath), headers,
|
method: 'POST', body: buildForm(filePath), headers: buildHeaders(),
|
||||||
});
|
});
|
||||||
} catch (err: any) { reportError('Network error (cache): ' + (err?.message || err)); continue; }
|
} catch (err: any) { reportError('Network error (cache): ' + (err?.message || err)); continue; }
|
||||||
const cacheText = await res.text();
|
const cacheText = await res.text();
|
||||||
@@ -124,73 +182,297 @@ async function handleUpload(panel: vscode.WebviewPanel, filePaths: string[]) {
|
|||||||
panel.webview.postMessage({ type: 'done' });
|
panel.webview.postMessage({ type: 'done' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getPickerDefaultUri(): vscode.Uri | undefined {
|
||||||
|
const folders = vscode.workspace.workspaceFolders;
|
||||||
|
if (!folders || folders.length === 0) return undefined;
|
||||||
|
const root = folders[0].uri.fsPath;
|
||||||
|
const dist = path.join(root, 'dist');
|
||||||
|
if (fs.existsSync(dist) && fs.statSync(dist).isDirectory()) {
|
||||||
|
return vscode.Uri.file(dist);
|
||||||
|
}
|
||||||
|
return vscode.Uri.file(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collectHtmlFiles(root: string): Promise<string[]> {
|
||||||
|
const out: string[] = [];
|
||||||
|
const stack: string[] = [root];
|
||||||
|
while (stack.length) {
|
||||||
|
const dir = stack.pop()!;
|
||||||
|
let entries: fs.Dirent[];
|
||||||
|
try {
|
||||||
|
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const e of entries) {
|
||||||
|
const full = path.join(dir, e.name);
|
||||||
|
if (e.isDirectory()) {
|
||||||
|
if (e.name === 'node_modules' || e.name === '.git') continue;
|
||||||
|
stack.push(full);
|
||||||
|
} else if (e.isFile() && /\.html?$/i.test(e.name)) {
|
||||||
|
out.push(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function qrBaseName(name: string): string {
|
||||||
|
return (name || 'qr').replace(/\.html?$/i, '').replace(/[\\/:*?"<>|]/g, '_') || 'qr';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadQr(url: string, destPath: string): Promise<void> {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||||
|
const buf = Buffer.from(await res.arrayBuffer());
|
||||||
|
await fs.promises.writeFile(destPath, buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSaveQr(panel: vscode.WebviewPanel, url: string, name: string) {
|
||||||
|
if (!url) return;
|
||||||
|
const base = qrBaseName(name);
|
||||||
|
const defaultUri = vscode.Uri.file(path.join(require('os').homedir(), 'Downloads', `${base}.png`));
|
||||||
|
const target = await vscode.window.showSaveDialog({
|
||||||
|
defaultUri,
|
||||||
|
filters: { 'PNG Image': ['png'] },
|
||||||
|
saveLabel: 'Save QR',
|
||||||
|
});
|
||||||
|
if (!target) return;
|
||||||
|
try {
|
||||||
|
await downloadQr(url, target.fsPath);
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Saved QR: ${target.fsPath}` });
|
||||||
|
} catch (err: any) {
|
||||||
|
panel.webview.postMessage({ type: 'error', message: 'Save QR failed: ' + (err?.message || err) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSaveAllQrs(panel: vscode.WebviewPanel, items: Array<{ name: string; url: string }>) {
|
||||||
|
if (!items.length) return;
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFiles: false,
|
||||||
|
canSelectFolders: true,
|
||||||
|
canSelectMany: false,
|
||||||
|
openLabel: 'Save QRs Here',
|
||||||
|
});
|
||||||
|
if (!picked || !picked.length) return;
|
||||||
|
const dir = picked[0].fsPath;
|
||||||
|
let saved = 0;
|
||||||
|
const errors: string[] = [];
|
||||||
|
for (const it of items) {
|
||||||
|
const base = qrBaseName(it.name);
|
||||||
|
let dest = path.join(dir, `${base}.png`);
|
||||||
|
let n = 1;
|
||||||
|
while (fs.existsSync(dest)) {
|
||||||
|
dest = path.join(dir, `${base} (${n++}).png`);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await downloadQr(it.url, dest);
|
||||||
|
saved++;
|
||||||
|
} catch (err: any) {
|
||||||
|
errors.push(`${it.name}: ${err?.message || err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (errors.length) {
|
||||||
|
panel.webview.postMessage({ type: 'error', message: `Saved ${saved}/${items.length}. Errors:\n` + errors.join('\n') });
|
||||||
|
} else {
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Saved ${saved} QR${saved === 1 ? '' : 's'} to ${dir}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function getHtml(): string {
|
function getHtml(): string {
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<style>
|
<style>
|
||||||
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 16px; }
|
${getToolWebviewStyles()}
|
||||||
h2 { margin-top: 0; }
|
.selected-files { margin-top: 10px; }
|
||||||
button {
|
.qr-cell { text-align: center; }
|
||||||
background: var(--vscode-button-background); color: var(--vscode-button-foreground);
|
.qr-cell img {
|
||||||
border: none; padding: 6px 12px; border-radius: 2px; cursor: pointer;
|
width: 104px;
|
||||||
|
height: 104px;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 6px;
|
||||||
|
border-radius: var(--tool-radius);
|
||||||
|
background: #fff;
|
||||||
}
|
}
|
||||||
button:hover { background: var(--vscode-button-hoverBackground); }
|
.result-actions { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||||
button.secondary {
|
.qr-cell img { cursor: zoom-in; }
|
||||||
background: var(--vscode-button-secondaryBackground);
|
.qr-modal {
|
||||||
color: var(--vscode-button-secondaryForeground);
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
display: none;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 24px;
|
||||||
|
background: rgba(0, 0, 0, 0.72);
|
||||||
|
z-index: 10;
|
||||||
}
|
}
|
||||||
button.secondary:hover { background: var(--vscode-button-secondaryHoverBackground); }
|
.qr-modal.open { display: flex; }
|
||||||
.file-cell { display: flex; align-items: center; gap: 8px; }
|
.qr-modal img {
|
||||||
.file-name { opacity: 0.85; font-size: 12px; word-break: break-all; }
|
width: min(70vw, 520px);
|
||||||
.actions { margin-top: 12px; display: flex; gap: 8px; }
|
height: min(70vw, 520px);
|
||||||
#status { margin-top: 12px; min-height: 20px; }
|
padding: 18px;
|
||||||
.err { color: var(--vscode-errorForeground); white-space: pre-wrap; }
|
border-radius: var(--tool-radius);
|
||||||
.ok { color: var(--vscode-testing-iconPassed, var(--vscode-foreground)); }
|
background: #fff;
|
||||||
.result {
|
|
||||||
padding: 10px;
|
|
||||||
background: var(--vscode-textBlockQuote-background);
|
|
||||||
border-left: 3px solid var(--vscode-textBlockQuote-border);
|
|
||||||
word-break: break-all;
|
|
||||||
}
|
}
|
||||||
.result-actions { margin-top: 8px; display: flex; gap: 8px; }
|
.qr-results:not(.has-errors) .error-col { display: none; }
|
||||||
#results { margin-top: 12px; display: grid; grid-template-columns: repeat(auto-fill,minmax(280px,1fr)); gap: 12px; }
|
.remove-selected {
|
||||||
|
min-width: 28px;
|
||||||
|
width: 28px;
|
||||||
|
padding: 3px 0;
|
||||||
|
color: var(--vscode-errorForeground);
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.pager { margin-top: 8px; display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h2>AppLovin Playable Preview (QR)</h2>
|
<main class="tool-page">
|
||||||
<p style="opacity:0.8;font-size:12px;margin-top:0;">Upload HTML files to p.applov.in and get QR codes to scan with the AppLovin Playable Preview app (iOS/Android).</p>
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">AppLovin Playable Preview</h2>
|
||||||
|
<p class="tool-description">Upload HTML files to p.applov.in and get QR codes to scan with the AppLovin Playable Preview app.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
<div class="file-cell" style="margin-bottom:8px;">
|
<section class="tool-panel input-panel">
|
||||||
<button id="pick" class="secondary">Choose files...</button>
|
<div class="panel-header">
|
||||||
<span class="file-name" id="fileName">(no files)</span>
|
<h3 class="panel-title">Inputs</h3>
|
||||||
|
</div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
|
<button id="pick" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div class="file-name" id="fileName" style="margin-top:8px;">(no files selected)</div>
|
||||||
|
<div id="fileList" class="selected-files"></div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="upload">Upload</button>
|
||||||
|
<button id="saveAll" class="secondary" disabled>Save All</button>
|
||||||
|
<button id="regenAll" class="secondary" disabled>Regenerate</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div id="outputPanel" class="is-hidden">
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="actions">
|
<div id="qrModal" class="qr-modal" title="Click to close"><img alt="Expanded QR" /></div>
|
||||||
<button id="upload">Upload to AppLovin</button>
|
</main>
|
||||||
</div>
|
|
||||||
<div id="status"></div>
|
|
||||||
<div id="results"></div>
|
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const vscode = acquireVsCodeApi();
|
const vscode = acquireVsCodeApi();
|
||||||
|
const pickFolderBtn = document.getElementById('pickFolder');
|
||||||
const pickBtn = document.getElementById('pick');
|
const pickBtn = document.getElementById('pick');
|
||||||
|
const clearBtn = document.getElementById('clear');
|
||||||
const uploadBtn = document.getElementById('upload');
|
const uploadBtn = document.getElementById('upload');
|
||||||
const fileNameEl = document.getElementById('fileName');
|
const fileNameEl = document.getElementById('fileName');
|
||||||
|
const fileListEl = document.getElementById('fileList');
|
||||||
const statusEl = document.getElementById('status');
|
const statusEl = document.getElementById('status');
|
||||||
const resultsEl = document.getElementById('results');
|
const resultsEl = document.getElementById('results');
|
||||||
|
const outputPanel = document.getElementById('outputPanel');
|
||||||
|
const qrModal = document.getElementById('qrModal');
|
||||||
|
const saveAllBtn = document.getElementById('saveAll');
|
||||||
|
const regenAllBtn = document.getElementById('regenAll');
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
let selectedPaths = [];
|
let selectedPaths = [];
|
||||||
|
let selectedPage = 0;
|
||||||
|
let resultItems = [];
|
||||||
|
|
||||||
|
function basename(p) {
|
||||||
|
const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\\\'));
|
||||||
|
return i >= 0 ? p.slice(i + 1) : p;
|
||||||
|
}
|
||||||
|
function renderSelection() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
if (!selectedPaths.length) {
|
||||||
|
fileNameEl.textContent = '(no files selected)';
|
||||||
|
fileListEl.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fileNameEl.textContent = selectedPaths.length + ' file' + (selectedPaths.length === 1 ? '' : 's');
|
||||||
|
const maxPage = Math.max(0, Math.ceil(selectedPaths.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const start = selectedPage * PAGE_SIZE;
|
||||||
|
const visiblePaths = selectedPaths.slice(start, start + PAGE_SIZE);
|
||||||
|
fileListEl.innerHTML =
|
||||||
|
'<div class="results-panel" style="margin-top:0;">' +
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead>' +
|
||||||
|
'<tbody>' +
|
||||||
|
visiblePaths.map((p, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return (
|
||||||
|
'<tr><td class="mono wrap">' + escapeHtml(basename(p)) + '</td>' +
|
||||||
|
'<td><button class="remove-selected danger" data-index="' + i + '" title="Remove">×</button></td></tr>'
|
||||||
|
);
|
||||||
|
}).join('') +
|
||||||
|
'</tbody>' +
|
||||||
|
'</table>' +
|
||||||
|
'</div>';
|
||||||
|
fileListEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
selectedPaths.splice(Number(btn.dataset.index), 1);
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (selectedPaths.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML =
|
||||||
|
'<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
fileListEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
saveAllBtn.addEventListener('click', () => {
|
||||||
|
if (!resultItems.length) return;
|
||||||
|
vscode.postMessage({ type: 'saveAllQrs', items: resultItems });
|
||||||
|
});
|
||||||
|
|
||||||
|
regenAllBtn.addEventListener('click', () => {
|
||||||
|
const imgs = resultsEl.querySelectorAll('img[data-qr]');
|
||||||
|
imgs.forEach(img => {
|
||||||
|
const base = img.getAttribute('data-qr');
|
||||||
|
img.src = base + '&_=' + Date.now();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
qrModal.addEventListener('click', () => {
|
||||||
|
qrModal.classList.remove('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
pickFolderBtn.addEventListener('click', () => vscode.postMessage({ type: 'pickFolder' }));
|
||||||
pickBtn.addEventListener('click', () => vscode.postMessage({ type: 'pickFiles' }));
|
pickBtn.addEventListener('click', () => vscode.postMessage({ type: 'pickFiles' }));
|
||||||
|
clearBtn.addEventListener('click', () => {
|
||||||
|
selectedPaths = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
|
||||||
uploadBtn.addEventListener('click', () => {
|
uploadBtn.addEventListener('click', () => {
|
||||||
statusEl.textContent = '';
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
resultsEl.innerHTML = '';
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
if (!selectedPaths.length) {
|
if (!selectedPaths.length) {
|
||||||
statusEl.innerHTML = '<span class="err">Pick at least one HTML file first.</span>';
|
statusEl.innerHTML = '<span class="err">Pick at least one HTML file first.</span>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
uploadBtn.disabled = true;
|
uploadBtn.disabled = true;
|
||||||
|
statusEl.textContent = 'Uploading...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
resultItems = [];
|
||||||
|
saveAllBtn.disabled = true;
|
||||||
|
regenAllBtn.disabled = true;
|
||||||
vscode.postMessage({ type: 'upload', paths: selectedPaths });
|
vscode.postMessage({ type: 'upload', paths: selectedPaths });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -198,20 +480,36 @@ function getHtml(): string {
|
|||||||
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ensureResultsTable() {
|
||||||
|
let tbody = resultsEl.querySelector('tbody');
|
||||||
|
if (tbody) return tbody;
|
||||||
|
resultsEl.innerHTML =
|
||||||
|
'<table class="data-table qr-results">' +
|
||||||
|
'<thead><tr><th>File</th><th style="width:140px;">QR</th><th style="width:170px;">Actions</th><th class="error-col">Error</th></tr></thead>' +
|
||||||
|
'<tbody></tbody>' +
|
||||||
|
'</table>';
|
||||||
|
outputPanel.classList.remove('is-hidden');
|
||||||
|
return resultsEl.querySelector('tbody');
|
||||||
|
}
|
||||||
|
|
||||||
window.addEventListener('message', (e) => {
|
window.addEventListener('message', (e) => {
|
||||||
const m = e.data;
|
const m = e.data;
|
||||||
if (m.type === 'filesSelected') {
|
if (m.type === 'filesSelected') {
|
||||||
selectedPaths = m.files.map(f => f.path);
|
const added = m.files.map(f => f.path).filter(p => !selectedPaths.includes(p));
|
||||||
const names = m.files.map(f => f.name);
|
selectedPaths = selectedPaths.concat(added);
|
||||||
fileNameEl.textContent = names.length === 1
|
selectedPage = Math.max(0, Math.ceil(selectedPaths.length / PAGE_SIZE) - 1);
|
||||||
? names[0]
|
renderSelection();
|
||||||
: names.length + ' files: ' + names.slice(0, 3).join(', ') + (names.length > 3 ? '...' : '');
|
|
||||||
} else if (m.type === 'start') {
|
} else if (m.type === 'start') {
|
||||||
resultsEl.innerHTML = '';
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
resultItems = [];
|
||||||
|
saveAllBtn.disabled = true;
|
||||||
|
regenAllBtn.disabled = true;
|
||||||
} else if (m.type === 'status') {
|
} else if (m.type === 'status') {
|
||||||
statusEl.textContent = m.message;
|
statusEl.textContent = m.message;
|
||||||
statusEl.className = '';
|
statusEl.className = 'status-panel is-busy';
|
||||||
} else if (m.type === 'error') {
|
} else if (m.type === 'error') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div');
|
||||||
div.className = 'err';
|
div.className = 'err';
|
||||||
div.textContent = m.message;
|
div.textContent = m.message;
|
||||||
@@ -219,39 +517,52 @@ function getHtml(): string {
|
|||||||
statusEl.appendChild(div);
|
statusEl.appendChild(div);
|
||||||
uploadBtn.disabled = false;
|
uploadBtn.disabled = false;
|
||||||
} else if (m.type === 'fileError') {
|
} else if (m.type === 'fileError') {
|
||||||
const wrap = document.createElement('div');
|
const tbody = ensureResultsTable();
|
||||||
wrap.className = 'result';
|
resultsEl.querySelector('table').classList.add('has-errors');
|
||||||
wrap.innerHTML = '<div><strong>' + escapeHtml(m.name) + '</strong></div>' +
|
const row = document.createElement('tr');
|
||||||
'<div class="err" style="margin-top:6px;">' + escapeHtml(m.message) + '</div>';
|
row.innerHTML =
|
||||||
resultsEl.appendChild(wrap);
|
'<td class="mono wrap">' + escapeHtml(m.name) + '</td>' +
|
||||||
|
'<td class="muted">-</td>' +
|
||||||
|
'<td class="muted">-</td>' +
|
||||||
|
'<td class="err wrap error-col">' + escapeHtml(m.message) + '</td>';
|
||||||
|
tbody.appendChild(row);
|
||||||
} else if (m.type === 'fileResult') {
|
} else if (m.type === 'fileResult') {
|
||||||
const wrap = document.createElement('div');
|
const tbody = ensureResultsTable();
|
||||||
wrap.className = 'result';
|
const row = document.createElement('tr');
|
||||||
wrap.innerHTML =
|
const file = document.createElement('td');
|
||||||
'<div style="font-weight:600;margin-bottom:8px;word-break:break-all;">' + escapeHtml(m.name) + '</div>' +
|
file.className = 'mono wrap';
|
||||||
'<div style="text-align:center;margin-bottom:8px;">' +
|
file.textContent = m.name;
|
||||||
'<img src="' + m.qrImg + '" alt="QR" style="background:#fff;padding:8px;border-radius:4px;max-width:100%;" />' +
|
const qr = document.createElement('td');
|
||||||
'</div>' +
|
qr.className = 'qr-cell';
|
||||||
'<div style="font-size:11px;opacity:0.8;word-break:break-all;">Hash: ' + escapeHtml(m.hash) + '</div>';
|
qr.innerHTML = '<img src="' + m.qrImg + '" data-qr="' + m.qrImg + '" alt="QR" />';
|
||||||
|
qr.querySelector('img').addEventListener('click', (event) => {
|
||||||
|
qrModal.querySelector('img').src = event.currentTarget.src;
|
||||||
|
qrModal.classList.add('open');
|
||||||
|
});
|
||||||
|
const actionCell = document.createElement('td');
|
||||||
|
const error = document.createElement('td');
|
||||||
|
error.className = 'error-col';
|
||||||
|
error.innerHTML = '<span class="muted">-</span>';
|
||||||
const actions = document.createElement('div');
|
const actions = document.createElement('div');
|
||||||
actions.className = 'result-actions';
|
actions.className = 'result-actions';
|
||||||
const copyHash = document.createElement('button');
|
|
||||||
copyHash.textContent = 'Copy Hash';
|
|
||||||
copyHash.onclick = () => vscode.postMessage({ type: 'copy', text: m.hash });
|
|
||||||
const copyPreview = document.createElement('button');
|
|
||||||
copyPreview.textContent = 'Copy URL';
|
|
||||||
copyPreview.className = 'secondary';
|
|
||||||
copyPreview.onclick = () => vscode.postMessage({ type: 'copy', text: m.previewUrl });
|
|
||||||
const openPreview = document.createElement('button');
|
const openPreview = document.createElement('button');
|
||||||
openPreview.textContent = 'Open';
|
openPreview.textContent = 'Open';
|
||||||
openPreview.className = 'secondary';
|
openPreview.className = 'secondary';
|
||||||
openPreview.onclick = () => vscode.postMessage({ type: 'open', text: m.previewUrl });
|
openPreview.onclick = () => vscode.postMessage({ type: 'open', text: m.previewUrl });
|
||||||
actions.appendChild(copyHash);
|
const saveQr = document.createElement('button');
|
||||||
actions.appendChild(copyPreview);
|
saveQr.textContent = 'Save QR';
|
||||||
|
saveQr.className = 'secondary';
|
||||||
|
saveQr.onclick = () => vscode.postMessage({ type: 'saveQr', url: m.qrImg, name: m.name });
|
||||||
actions.appendChild(openPreview);
|
actions.appendChild(openPreview);
|
||||||
wrap.appendChild(actions);
|
actions.appendChild(saveQr);
|
||||||
resultsEl.appendChild(wrap);
|
actionCell.appendChild(actions);
|
||||||
|
row.append(file, qr, actionCell, error);
|
||||||
|
tbody.appendChild(row);
|
||||||
|
resultItems.push({ name: m.name, url: m.qrImg });
|
||||||
|
saveAllBtn.disabled = resultItems.length === 0;
|
||||||
|
regenAllBtn.disabled = resultItems.length === 0;
|
||||||
} else if (m.type === 'done') {
|
} else if (m.type === 'done') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
statusEl.innerHTML = '<span class="ok">Done.</span>';
|
statusEl.innerHTML = '<span class="ok">Done.</span>';
|
||||||
uploadBtn.disabled = false;
|
uploadBtn.disabled = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import { singletonPanel } from './shared';
|
import { getToolWebviewStyles, singletonPanel } from './shared';
|
||||||
|
|
||||||
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
||||||
|
|
||||||
export function openBase64Scanner(_context: vscode.ExtensionContext) {
|
export function openBase64Scanner(_context: vscode.ExtensionContext) {
|
||||||
const { panel, isNew } = singletonPanel(store, 'hplToolbox.base64Scanner', 'Base64 Asset Scanner');
|
const { panel, isNew } = singletonPanel(store, 'hplToolbox.base64Scanner', 'Base64 Scanner');
|
||||||
if (!isNew) return;
|
if (!isNew) return;
|
||||||
|
|
||||||
panel.webview.html = getHtml();
|
panel.webview.html = getHtml();
|
||||||
@@ -16,7 +16,8 @@ export function openBase64Scanner(_context: vscode.ExtensionContext) {
|
|||||||
if (ws) {
|
if (ws) {
|
||||||
const distPath = path.join(ws.uri.fsPath, 'dist');
|
const distPath = path.join(ws.uri.fsPath, 'dist');
|
||||||
if (fs.existsSync(distPath) && fs.statSync(distPath).isDirectory()) {
|
if (fs.existsSync(distPath) && fs.statSync(distPath).isDirectory()) {
|
||||||
panel.webview.postMessage({ type: 'folderPicked', path: distPath });
|
const files = await collectHtmlFiles(distPath);
|
||||||
|
panel.webview.postMessage({ type: 'filesPicked', paths: files });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (msg.type === 'pickFolder') {
|
} else if (msg.type === 'pickFolder') {
|
||||||
@@ -27,7 +28,8 @@ export function openBase64Scanner(_context: vscode.ExtensionContext) {
|
|||||||
openLabel: 'Select Folder',
|
openLabel: 'Select Folder',
|
||||||
});
|
});
|
||||||
if (picked && picked[0]) {
|
if (picked && picked[0]) {
|
||||||
panel.webview.postMessage({ type: 'folderPicked', path: picked[0].fsPath });
|
const files = await collectHtmlFiles(picked[0].fsPath);
|
||||||
|
panel.webview.postMessage({ type: 'filesPicked', paths: files });
|
||||||
}
|
}
|
||||||
} else if (msg.type === 'pickFiles') {
|
} else if (msg.type === 'pickFiles') {
|
||||||
const picked = await vscode.window.showOpenDialog({
|
const picked = await vscode.window.showOpenDialog({
|
||||||
@@ -56,7 +58,9 @@ export function openBase64Scanner(_context: vscode.ExtensionContext) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const results: { file: string; ok: boolean; assets: string[] }[] = [];
|
const results: { file: string; ok: boolean; assets: string[] }[] = [];
|
||||||
for (const file of targets) {
|
for (let i = 0; i < targets.length; i++) {
|
||||||
|
const file = targets[i];
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Scanning ${i + 1}/${targets.length} ${path.basename(file)}` });
|
||||||
try {
|
try {
|
||||||
const content = fs.readFileSync(file, 'utf8');
|
const content = fs.readFileSync(file, 'utf8');
|
||||||
const offenders = findNonBase64Assets(content);
|
const offenders = findNonBase64Assets(content);
|
||||||
@@ -144,46 +148,125 @@ function getHtml(): string {
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<style>
|
<style>
|
||||||
body { font-family: var(--vscode-font-family); padding: 12px; color: var(--vscode-foreground); }
|
${getToolWebviewStyles()}
|
||||||
.row { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; }
|
.asset-list { margin: 0; padding-left: 16px; }
|
||||||
input[type=text] { flex: 1; padding: 4px 6px; background: var(--vscode-input-background); color: var(--vscode-input-foreground); border: 1px solid var(--vscode-input-border); }
|
.asset-list li + li { margin-top: 3px; }
|
||||||
button { padding: 4px 12px; background: var(--vscode-button-background); color: var(--vscode-button-foreground); border: none; cursor: pointer; }
|
.selected-list { margin-top: 8px; }
|
||||||
button:hover { background: var(--vscode-button-hoverBackground); }
|
.remove-selected {
|
||||||
.row-result { display: flex; gap: 8px; padding: 2px 0; font-family: var(--vscode-editor-font-family); font-size: 12px; }
|
min-width: 28px;
|
||||||
.mark { width: 14px; flex-shrink: 0; font-weight: bold; }
|
width: 28px;
|
||||||
.ok { color: #3fb950; }
|
padding: 3px 0;
|
||||||
.bad { color: #f85149; }
|
color: var(--vscode-errorForeground);
|
||||||
.file-name { word-break: break-all; }
|
font-size: 16px;
|
||||||
.assets { color: var(--vscode-descriptionForeground); margin-left: 6px; word-break: break-all; }
|
line-height: 1;
|
||||||
.summary { margin-top: 12px; opacity: 0.8; }
|
}
|
||||||
|
.pager { margin-top: 8px; display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h2>Base64 Asset Scanner</h2>
|
<main class="tool-page">
|
||||||
<div class="row">
|
<header class="tool-header">
|
||||||
<input id="folder" type="text" placeholder="Folder to scan recursively..." />
|
<h2 class="tool-title">Base64 Scanner</h2>
|
||||||
<button id="pick">Browse Folder...</button>
|
<p class="tool-description">Scan folders or selected HTML files for asset references that are not embedded as base64 data URIs.</p>
|
||||||
<button id="pickFiles">Pick Files...</button>
|
</header>
|
||||||
<button id="scan">Scan</button>
|
|
||||||
|
<section class="tool-panel input-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3 class="panel-title">Inputs</h3>
|
||||||
|
</div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="field-row">
|
||||||
|
<input id="folder" type="hidden" />
|
||||||
|
<button id="pick" class="secondary">Select Folder</button>
|
||||||
|
<button id="pickFiles" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div id="selection" class="selected-list"></div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="scan">Scan</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="outputPanel" class="is-hidden">
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="selection" class="summary"></div>
|
</main>
|
||||||
<div id="status"></div>
|
|
||||||
<div id="results"></div>
|
|
||||||
<script>
|
<script>
|
||||||
const vscode = acquireVsCodeApi();
|
const vscode = acquireVsCodeApi();
|
||||||
vscode.postMessage({ type: 'ready' });
|
vscode.postMessage({ type: 'ready' });
|
||||||
const folderEl = document.getElementById('folder');
|
const folderEl = document.getElementById('folder');
|
||||||
const statusEl = document.getElementById('status');
|
const statusEl = document.getElementById('status');
|
||||||
const resultsEl = document.getElementById('results');
|
const resultsEl = document.getElementById('results');
|
||||||
|
const outputPanel = document.getElementById('outputPanel');
|
||||||
const selectionEl = document.getElementById('selection');
|
const selectionEl = document.getElementById('selection');
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
let pickedFolder = '';
|
||||||
let pickedFiles = [];
|
let pickedFiles = [];
|
||||||
|
let selectedPage = 0;
|
||||||
|
|
||||||
function clearFiles() {
|
function basename(p) {
|
||||||
pickedFiles = [];
|
const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\\\'));
|
||||||
selectionEl.textContent = '';
|
return i >= 0 ? p.slice(i + 1) : p;
|
||||||
}
|
}
|
||||||
|
|
||||||
folderEl.addEventListener('input', clearFiles);
|
function escapeHtml(s) {
|
||||||
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSelection() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
const items = pickedFiles.length
|
||||||
|
? pickedFiles.map((p, i) => ({ label: basename(p), index: i, type: 'file' }))
|
||||||
|
: (pickedFolder ? [{ label: pickedFolder, index: 0, type: 'folder' }] : []);
|
||||||
|
if (!items.length) {
|
||||||
|
selectionEl.innerHTML = '<span class="file-name">(no files selected)</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const maxPage = Math.max(0, Math.ceil(items.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const visibleItems = items.slice(selectedPage * PAGE_SIZE, selectedPage * PAGE_SIZE + PAGE_SIZE);
|
||||||
|
selectionEl.innerHTML =
|
||||||
|
'<div class="results-panel" style="margin-top:0;">' +
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead>' +
|
||||||
|
'<tbody>' +
|
||||||
|
visibleItems.map(item =>
|
||||||
|
'<tr><td class="mono wrap">' + escapeHtml(item.label) + '</td>' +
|
||||||
|
'<td><button class="remove-selected danger" data-index="' + item.index + '" data-type="' + item.type + '" title="Remove">×</button></td></tr>'
|
||||||
|
).join('') +
|
||||||
|
'</tbody></table>' +
|
||||||
|
'</div>';
|
||||||
|
selectionEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
if (btn.dataset.type === 'folder') {
|
||||||
|
pickedFolder = '';
|
||||||
|
folderEl.value = '';
|
||||||
|
} else {
|
||||||
|
pickedFiles.splice(Number(btn.dataset.index), 1);
|
||||||
|
}
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (items.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML =
|
||||||
|
'<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
selectionEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderSelection();
|
||||||
|
|
||||||
document.getElementById('pick').addEventListener('click', () => {
|
document.getElementById('pick').addEventListener('click', () => {
|
||||||
vscode.postMessage({ type: 'pickFolder' });
|
vscode.postMessage({ type: 'pickFolder' });
|
||||||
@@ -191,9 +274,22 @@ function getHtml(): string {
|
|||||||
document.getElementById('pickFiles').addEventListener('click', () => {
|
document.getElementById('pickFiles').addEventListener('click', () => {
|
||||||
vscode.postMessage({ type: 'pickFiles' });
|
vscode.postMessage({ type: 'pickFiles' });
|
||||||
});
|
});
|
||||||
|
document.getElementById('clear').addEventListener('click', () => {
|
||||||
|
folderEl.value = '';
|
||||||
|
pickedFiles = [];
|
||||||
|
pickedFolder = '';
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
});
|
||||||
document.getElementById('scan').addEventListener('click', () => {
|
document.getElementById('scan').addEventListener('click', () => {
|
||||||
statusEl.textContent = 'Scanning...';
|
statusEl.textContent = 'Scanning...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
resultsEl.innerHTML = '';
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
if (pickedFiles.length) {
|
if (pickedFiles.length) {
|
||||||
vscode.postMessage({ type: 'scan', files: pickedFiles });
|
vscode.postMessage({ type: 'scan', files: pickedFiles });
|
||||||
} else {
|
} else {
|
||||||
@@ -207,35 +303,68 @@ function getHtml(): string {
|
|||||||
const msg = event.data;
|
const msg = event.data;
|
||||||
if (msg.type === 'folderPicked') {
|
if (msg.type === 'folderPicked') {
|
||||||
folderEl.value = msg.path;
|
folderEl.value = msg.path;
|
||||||
clearFiles();
|
pickedFolder = msg.path;
|
||||||
|
pickedFiles = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
} else if (msg.type === 'filesPicked') {
|
} else if (msg.type === 'filesPicked') {
|
||||||
pickedFiles = msg.paths;
|
const existing = new Set(pickedFiles);
|
||||||
|
pickedFiles = pickedFiles.concat((msg.paths || []).filter(p => !existing.has(p)));
|
||||||
folderEl.value = '';
|
folderEl.value = '';
|
||||||
selectionEl.textContent = pickedFiles.length + ' file(s) selected';
|
pickedFolder = '';
|
||||||
|
selectedPage = Math.max(0, Math.ceil(pickedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
} else if (msg.type === 'status') {
|
||||||
|
statusEl.textContent = msg.message;
|
||||||
|
statusEl.className = 'status-panel is-busy';
|
||||||
} else if (msg.type === 'results') {
|
} else if (msg.type === 'results') {
|
||||||
if (msg.error) { statusEl.textContent = 'Error: ' + msg.error; return; }
|
if (msg.error) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Error: ' + msg.error;
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const total = msg.results.length;
|
const total = msg.results.length;
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
const flagged = msg.results.filter(r => !r.ok).length;
|
const flagged = msg.results.filter(r => !r.ok).length;
|
||||||
statusEl.innerHTML = '<div class="summary">Scanned ' + total + ' HTML file(s). ' + flagged + ' contain non-base64 assets.</div>';
|
statusEl.textContent = 'Scanned ' + total + ' HTML file(s). ' + flagged + ' contain non-base64 assets.';
|
||||||
resultsEl.innerHTML = '';
|
if (!total) {
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
outputPanel.classList.remove('is-hidden');
|
||||||
|
resultsEl.innerHTML =
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th style="width:90px;">Status</th><th>File</th><th style="width:90px;">Issues</th><th>Non-base64 assets</th></tr></thead>' +
|
||||||
|
'<tbody></tbody>' +
|
||||||
|
'</table>';
|
||||||
|
const tbody = resultsEl.querySelector('tbody');
|
||||||
for (const r of msg.results) {
|
for (const r of msg.results) {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('tr');
|
||||||
row.className = 'row-result';
|
const status = document.createElement('td');
|
||||||
const mark = document.createElement('span');
|
status.innerHTML = r.ok ? '<span class="badge ok">OK</span>' : '<span class="badge err">Review</span>';
|
||||||
mark.className = 'mark ' + (r.ok ? 'ok' : 'bad');
|
const name = document.createElement('td');
|
||||||
mark.textContent = r.ok ? '✓' : '✗';
|
name.className = 'mono wrap';
|
||||||
const name = document.createElement('span');
|
|
||||||
name.className = 'file-name';
|
|
||||||
name.textContent = r.file;
|
name.textContent = r.file;
|
||||||
row.appendChild(mark);
|
const count = document.createElement('td');
|
||||||
row.appendChild(name);
|
count.textContent = String(r.assets.length);
|
||||||
|
const assets = document.createElement('td');
|
||||||
|
assets.className = 'wrap';
|
||||||
if (!r.ok) {
|
if (!r.ok) {
|
||||||
const a = document.createElement('span');
|
const list = document.createElement('ul');
|
||||||
a.className = 'assets';
|
list.className = 'asset-list mono';
|
||||||
a.textContent = '— ' + r.assets.join(', ');
|
r.assets.forEach(asset => {
|
||||||
row.appendChild(a);
|
const item = document.createElement('li');
|
||||||
|
item.textContent = asset;
|
||||||
|
list.appendChild(item);
|
||||||
|
});
|
||||||
|
assets.appendChild(list);
|
||||||
|
} else {
|
||||||
|
assets.innerHTML = '<span class="muted">None</span>';
|
||||||
}
|
}
|
||||||
resultsEl.appendChild(row);
|
row.append(status, name, count, assets);
|
||||||
|
tbody.appendChild(row);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,122 +0,0 @@
|
|||||||
import * as vscode from 'vscode';
|
|
||||||
import { singletonPanel } from './shared';
|
|
||||||
|
|
||||||
const PROJECT_KEY = 'hplToolbox.dailyUpdate.lastProject';
|
|
||||||
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
|
||||||
|
|
||||||
export function openDailyUpdate(context: vscode.ExtensionContext) {
|
|
||||||
const { panel, isNew } = singletonPanel(store, 'hplToolbox.dailyUpdate', 'Daily Update');
|
|
||||||
if (!isNew) return;
|
|
||||||
|
|
||||||
const lastProject = context.globalState.get<string>(PROJECT_KEY, '');
|
|
||||||
panel.webview.html = getHtml(lastProject);
|
|
||||||
|
|
||||||
panel.webview.onDidReceiveMessage(async (msg) => {
|
|
||||||
if (msg.type === 'submit') {
|
|
||||||
const text = formatMessage(msg.payload);
|
|
||||||
await vscode.env.clipboard.writeText(text);
|
|
||||||
await context.globalState.update(PROJECT_KEY, msg.payload.project);
|
|
||||||
vscode.window.showInformationMessage('Daily update copied to clipboard.');
|
|
||||||
panel.dispose();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatMessage(p: { date: string; status: string; project: string; remarks: string }): string {
|
|
||||||
const bullets = p.remarks
|
|
||||||
.split(/\r?\n/)
|
|
||||||
.map((l) => l.replace(/^\s*[-*]\s*/, '').trim())
|
|
||||||
.filter((l) => l.length > 0)
|
|
||||||
.map((l) => `- ${l}`)
|
|
||||||
.join('\n');
|
|
||||||
|
|
||||||
const lines = [
|
|
||||||
`Date: ${formatDate(p.date)}`,
|
|
||||||
`Status: ${p.status}`,
|
|
||||||
`Project: ${p.project}`,
|
|
||||||
`Remarks:`,
|
|
||||||
bullets,
|
|
||||||
];
|
|
||||||
|
|
||||||
if (p.status === 'For OT') {
|
|
||||||
lines.push('@Joyce Lanot , @Reland Pigte, @Anthony Castor, @Angela Grace');
|
|
||||||
}
|
|
||||||
|
|
||||||
return lines.join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(iso: string): string {
|
|
||||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
|
|
||||||
if (!m) return iso;
|
|
||||||
return `${m[2]}/${m[3]}/${m[1]}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function escapeAttr(s: string): string {
|
|
||||||
return s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
|
||||||
}
|
|
||||||
|
|
||||||
function getHtml(lastProject: string): string {
|
|
||||||
const today = new Date().toISOString().slice(0, 10);
|
|
||||||
return `<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline';" />
|
|
||||||
<style>
|
|
||||||
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 16px; max-width: 520px; }
|
|
||||||
label { display: block; margin-top: 12px; font-size: 12px; opacity: 0.85; }
|
|
||||||
input, select, textarea {
|
|
||||||
width: 100%; box-sizing: border-box; margin-top: 4px; padding: 6px 8px;
|
|
||||||
background: var(--vscode-input-background); color: var(--vscode-input-foreground);
|
|
||||||
border: 1px solid var(--vscode-input-border, transparent); font-family: inherit; font-size: 13px;
|
|
||||||
}
|
|
||||||
textarea { min-height: 96px; resize: vertical; }
|
|
||||||
button {
|
|
||||||
margin-top: 16px; padding: 8px 16px; cursor: pointer;
|
|
||||||
background: var(--vscode-button-background); color: var(--vscode-button-foreground);
|
|
||||||
border: none; font-size: 13px;
|
|
||||||
}
|
|
||||||
button:hover { background: var(--vscode-button-hoverBackground); }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h2 style="margin:0 0 4px 0;">Daily Update</h2>
|
|
||||||
<div style="font-size:12px;opacity:0.7;">Submit copies the formatted text to your clipboard.</div>
|
|
||||||
|
|
||||||
<label for="date">Date</label>
|
|
||||||
<input type="date" id="date" value="${today}" />
|
|
||||||
|
|
||||||
<label for="status">Status</label>
|
|
||||||
<select id="status">
|
|
||||||
<option>Started</option>
|
|
||||||
<option>Progress</option>
|
|
||||||
<option>Finished</option>
|
|
||||||
<option>Client Feedback</option>
|
|
||||||
<option>For OT</option>
|
|
||||||
</select>
|
|
||||||
|
|
||||||
<label for="project">Project</label>
|
|
||||||
<input type="text" id="project" placeholder="Project name" value="${escapeAttr(lastProject)}" />
|
|
||||||
|
|
||||||
<label for="remarks">Remarks</label>
|
|
||||||
<textarea id="remarks" placeholder="What did you do?"></textarea>
|
|
||||||
|
|
||||||
<button id="submit">Submit</button>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
const vscode = acquireVsCodeApi();
|
|
||||||
document.getElementById('submit').addEventListener('click', () => {
|
|
||||||
vscode.postMessage({
|
|
||||||
type: 'submit',
|
|
||||||
payload: {
|
|
||||||
date: document.getElementById('date').value,
|
|
||||||
status: document.getElementById('status').value,
|
|
||||||
project: document.getElementById('project').value.trim(),
|
|
||||||
remarks: document.getElementById('remarks').value.trim(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>`;
|
|
||||||
}
|
|
||||||
1150
src/tools/deviceSimulator.ts
Normal file
1150
src/tools/deviceSimulator.ts
Normal file
File diff suppressed because it is too large
Load Diff
1709
src/tools/mintegralChecker.ts
Normal file
1709
src/tools/mintegralChecker.ts
Normal file
File diff suppressed because it is too large
Load Diff
895
src/tools/mraidChecker.ts
Normal file
895
src/tools/mraidChecker.ts
Normal file
@@ -0,0 +1,895 @@
|
|||||||
|
import * as vscode from 'vscode';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
import { getToolWebviewStyles, singletonPanel } from './shared';
|
||||||
|
|
||||||
|
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
||||||
|
|
||||||
|
type Severity = 'requirement' | 'best-practice';
|
||||||
|
|
||||||
|
interface MraidIssue {
|
||||||
|
id: string;
|
||||||
|
severity: Severity;
|
||||||
|
title: string;
|
||||||
|
detail: string;
|
||||||
|
line?: number;
|
||||||
|
reference: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MraidResult {
|
||||||
|
file: string;
|
||||||
|
ok: boolean;
|
||||||
|
issues: MraidIssue[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MraidRule {
|
||||||
|
id: string;
|
||||||
|
severity: Severity;
|
||||||
|
title: string;
|
||||||
|
detail: string;
|
||||||
|
reference: string;
|
||||||
|
test: (ctx: ScanContext) => MraidIssue | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScanContext {
|
||||||
|
filePath: string;
|
||||||
|
html: string;
|
||||||
|
scriptText: string;
|
||||||
|
lowerHtml: string;
|
||||||
|
lowerScript: string;
|
||||||
|
mraidCallLines: Map<string, number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function openMraidChecker(_context: vscode.ExtensionContext) {
|
||||||
|
const { panel, isNew } = singletonPanel(store, 'hplToolbox.mraidChecker', 'MRAID Checker');
|
||||||
|
if (!isNew) return;
|
||||||
|
|
||||||
|
panel.webview.html = getHtml();
|
||||||
|
panel.webview.onDidReceiveMessage(async (msg) => {
|
||||||
|
if (msg.type === 'ready') {
|
||||||
|
const ws = vscode.workspace.workspaceFolders?.[0];
|
||||||
|
if (ws) {
|
||||||
|
const distPath = path.join(ws.uri.fsPath, 'dist');
|
||||||
|
if (fs.existsSync(distPath) && fs.statSync(distPath).isDirectory()) {
|
||||||
|
const files = (await collectHtmlFiles(distPath)).filter(isInSupportedMraidFolderPath);
|
||||||
|
panel.webview.postMessage({ type: 'filesPicked', paths: files });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (msg.type === 'pickFolder') {
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFolders: true,
|
||||||
|
canSelectFiles: false,
|
||||||
|
canSelectMany: false,
|
||||||
|
openLabel: 'Select Folder',
|
||||||
|
});
|
||||||
|
if (picked && picked[0]) {
|
||||||
|
const files = (await collectHtmlFiles(picked[0].fsPath)).filter(isInSupportedMraidFolderPath);
|
||||||
|
panel.webview.postMessage({ type: 'filesPicked', paths: files });
|
||||||
|
}
|
||||||
|
} else if (msg.type === 'pickFiles') {
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFolders: false,
|
||||||
|
canSelectFiles: true,
|
||||||
|
canSelectMany: true,
|
||||||
|
openLabel: 'Select Files',
|
||||||
|
filters: { 'HTML': ['html', 'htm'] },
|
||||||
|
});
|
||||||
|
if (picked && picked.length) {
|
||||||
|
panel.webview.postMessage({ type: 'filesPicked', paths: picked.map(u => u.fsPath) });
|
||||||
|
}
|
||||||
|
} else if (msg.type === 'scan') {
|
||||||
|
const folder: string | undefined = msg.folder;
|
||||||
|
const files: string[] | undefined = msg.files;
|
||||||
|
let targets: string[] = [];
|
||||||
|
let baseDir = '';
|
||||||
|
let skipped = 0;
|
||||||
|
let skippedReason = '';
|
||||||
|
let noTargetsError = 'No HTML files were found.';
|
||||||
|
if (files && files.length) {
|
||||||
|
const existing = files.filter(f => fs.existsSync(f));
|
||||||
|
targets = existing;
|
||||||
|
skipped = files.length - existing.length;
|
||||||
|
skippedReason = 'missing file(s).';
|
||||||
|
noTargetsError = 'No selected HTML files were found.';
|
||||||
|
baseDir = targets.length ? commonBaseDir(targets) : '';
|
||||||
|
} else if (folder && fs.existsSync(folder)) {
|
||||||
|
const allHtmlFiles = await collectHtmlFiles(folder);
|
||||||
|
targets = allHtmlFiles.filter(isInSupportedMraidFolderPath);
|
||||||
|
skipped = allHtmlFiles.length - targets.length;
|
||||||
|
skippedReason = 'HTML file(s) outside AppLovin/ironSource/Unity folders.';
|
||||||
|
noTargetsError = 'No AppLovin, ironSource, or Unity folder HTML files were found.';
|
||||||
|
baseDir = folder;
|
||||||
|
} else {
|
||||||
|
panel.webview.postMessage({ type: 'results', results: [], error: 'Pick a folder or files first' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targets.length === 0) {
|
||||||
|
panel.webview.postMessage({
|
||||||
|
type: 'results',
|
||||||
|
results: [],
|
||||||
|
skipped,
|
||||||
|
skippedReason,
|
||||||
|
error: noTargetsError,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const results: MraidResult[] = [];
|
||||||
|
for (let i = 0; i < targets.length; i++) {
|
||||||
|
const file = targets[i];
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Scanning ${i + 1}/${targets.length} ${path.basename(file)}` });
|
||||||
|
try {
|
||||||
|
const content = fs.readFileSync(file, 'utf8');
|
||||||
|
const issues = checkMraid(content, file);
|
||||||
|
const display = baseDir ? path.relative(baseDir, file) || path.basename(file) : file;
|
||||||
|
results.push({ file: display, ok: issues.length === 0, issues });
|
||||||
|
} catch {
|
||||||
|
// Skip unreadable files, matching the scanner pattern used elsewhere.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panel.webview.postMessage({ type: 'results', results, skipped, skippedReason });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function commonBaseDir(files: string[]): string {
|
||||||
|
if (files.length === 0) return '';
|
||||||
|
if (files.length === 1) return path.dirname(files[0]);
|
||||||
|
const split = files.map(f => path.dirname(f).split(path.sep));
|
||||||
|
const first = split[0];
|
||||||
|
let i = 0;
|
||||||
|
while (i < first.length && split.every(parts => parts[i] === first[i])) i++;
|
||||||
|
return first.slice(0, i).join(path.sep);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collectHtmlFiles(root: string): Promise<string[]> {
|
||||||
|
const out: string[] = [];
|
||||||
|
const stack: string[] = [root];
|
||||||
|
while (stack.length) {
|
||||||
|
const dir = stack.pop()!;
|
||||||
|
let entries: fs.Dirent[];
|
||||||
|
try {
|
||||||
|
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const e of entries) {
|
||||||
|
const full = path.join(dir, e.name);
|
||||||
|
if (e.isDirectory()) {
|
||||||
|
if (e.name === 'node_modules' || e.name === '.git') continue;
|
||||||
|
stack.push(full);
|
||||||
|
} else if (e.isFile() && /\.html?$/i.test(e.name)) {
|
||||||
|
out.push(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkMraid(html: string, filePath = ''): MraidIssue[] {
|
||||||
|
const scriptText = extractScriptText(html);
|
||||||
|
const ctx: ScanContext = {
|
||||||
|
filePath,
|
||||||
|
html,
|
||||||
|
scriptText,
|
||||||
|
lowerHtml: html.toLowerCase(),
|
||||||
|
lowerScript: scriptText.toLowerCase(),
|
||||||
|
mraidCallLines: collectMraidCallLines(html),
|
||||||
|
};
|
||||||
|
|
||||||
|
return MRAID_RULES
|
||||||
|
.map(rule => rule.test(ctx))
|
||||||
|
.filter((issue): issue is MraidIssue => issue !== null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractScriptText(html: string): string {
|
||||||
|
const scripts: string[] = [];
|
||||||
|
const scriptRegex = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
|
||||||
|
let m: RegExpExecArray | null;
|
||||||
|
while ((m = scriptRegex.exec(html)) !== null) {
|
||||||
|
scripts.push(m[1]);
|
||||||
|
}
|
||||||
|
return scripts.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectMraidCallLines(html: string): Map<string, number> {
|
||||||
|
const calls = new Map<string, number>();
|
||||||
|
const lines = html.split(/\r?\n/);
|
||||||
|
const callRegex = /\bmraid\s*\.\s*([a-zA-Z_$][\w$]*)\s*\(/g;
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
let m: RegExpExecArray | null;
|
||||||
|
while ((m = callRegex.exec(lines[i])) !== null) {
|
||||||
|
if (!calls.has(m[1])) calls.set(m[1], i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return calls;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isInSupportedMraidFolderPath(filePath: string): boolean {
|
||||||
|
const folderParts = path.dirname(filePath)
|
||||||
|
.split(/[\\/]+/)
|
||||||
|
.map(part => part.toLowerCase());
|
||||||
|
return folderParts.some(part => [
|
||||||
|
'al',
|
||||||
|
'applovin',
|
||||||
|
'app-lovin',
|
||||||
|
'is',
|
||||||
|
'ironsource',
|
||||||
|
'iron-source',
|
||||||
|
'iron_source',
|
||||||
|
'un',
|
||||||
|
'unity',
|
||||||
|
'unityads',
|
||||||
|
'unity-ads',
|
||||||
|
'unity_ads',
|
||||||
|
].includes(part));
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMraidReference(ctx: ScanContext): boolean {
|
||||||
|
return /\bmraid\b/i.test(ctx.html);
|
||||||
|
}
|
||||||
|
|
||||||
|
function countMraidJsReferences(ctx: ScanContext): number {
|
||||||
|
return (ctx.html.match(/\bmraid\.js\b/gi) || []).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasViewportMeta(ctx: ScanContext): boolean {
|
||||||
|
return /<meta\b[^>]*\bname\s*=\s*['"]viewport['"][^>]*>/i.test(ctx.html);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMraidCall(ctx: ScanContext, method: string): boolean {
|
||||||
|
return ctx.mraidCallLines.has(method);
|
||||||
|
}
|
||||||
|
|
||||||
|
function mraidLine(ctx: ScanContext, method: string): number | undefined {
|
||||||
|
return ctx.mraidCallLines.get(method);
|
||||||
|
}
|
||||||
|
|
||||||
|
function issue(rule: MraidRule, line?: number): MraidIssue {
|
||||||
|
return {
|
||||||
|
id: rule.id,
|
||||||
|
severity: rule.severity,
|
||||||
|
title: rule.title,
|
||||||
|
detail: rule.detail,
|
||||||
|
line,
|
||||||
|
reference: rule.reference,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasReadyGate(ctx: ScanContext): boolean {
|
||||||
|
return (
|
||||||
|
/mraid\s*\.\s*addEventListener\s*\(\s*['"]ready['"]/i.test(ctx.scriptText) ||
|
||||||
|
/mraid\s*\.\s*getState\s*\(\s*\)\s*={0,2}\s*['"]loading['"]/i.test(ctx.scriptText) ||
|
||||||
|
/['"]loading['"]\s*={0,2}\s*mraid\s*\.\s*getState\s*\(\s*\)/i.test(ctx.scriptText)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasDomReadyGate(ctx: ScanContext): boolean {
|
||||||
|
return (
|
||||||
|
/document\s*\.\s*readyState/i.test(ctx.scriptText) ||
|
||||||
|
/DOMContentLoaded/i.test(ctx.scriptText) ||
|
||||||
|
/\bwindow\s*\.\s*(addEventListener\s*\(\s*['"]load['"]|onload\b)/i.test(ctx.scriptText)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasReadyListenerAndStateFallback(ctx: ScanContext): boolean {
|
||||||
|
return hasEventListener(ctx, 'ready') && hasMraidCall(ctx, 'getState');
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMraidTypeofGuard(ctx: ScanContext): boolean {
|
||||||
|
return /typeof\s+(?:window\s*\.\s*)?mraid\s*!={1,2}\s*['"]undefined['"]/i.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMraidFunctionGuard(ctx: ScanContext, method: string): boolean {
|
||||||
|
const escaped = method.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
return new RegExp(`typeof\\s+(?:window\\s*\\.\\s*)?mraid\\s*\\.\\s*${escaped}\\s*={2,3}\\s*['"]function['"]|typeof\\s+(?:window\\s*\\.\\s*)?mraid\\s*\\.\\s*${escaped}\\s*!={1,2}\\s*['"]undefined['"]`, 'i').test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMraidReadyTimeout(ctx: ScanContext): boolean {
|
||||||
|
return /setTimeout\s*\(/i.test(ctx.scriptText) && /\bmraid\b/i.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasLateMraidDetection(ctx: ScanContext): boolean {
|
||||||
|
return /setInterval\s*\(|setTimeout\s*\(|requestAnimationFrame\s*\(/i.test(ctx.scriptText) && /window\s*\.\s*mraid|\bmraid\b/i.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMraidOpenGuard(ctx: ScanContext): boolean {
|
||||||
|
return (
|
||||||
|
/typeof\s+(?:window\s*\.\s*)?mraid\s*\.\s*open\s*={2,3}\s*['"]function['"]/i.test(ctx.scriptText) ||
|
||||||
|
/typeof\s+(?:window\s*\.\s*)?mraid\s*\.\s*open\s*!={1,2}\s*['"]undefined['"]/i.test(ctx.scriptText)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMraidOpenLoadingGuard(ctx: ScanContext): boolean {
|
||||||
|
return (
|
||||||
|
/mraid\s*\.\s*getState\s*\(\s*\)\s*!={1,2}\s*['"]loading['"]/i.test(ctx.scriptText) ||
|
||||||
|
/['"]loading['"]\s*!={1,2}\s*mraid\s*\.\s*getState\s*\(\s*\)/i.test(ctx.scriptText) ||
|
||||||
|
/typeof\s+(?:window\s*\.\s*)?mraid\s*\.\s*getState\s*!={1,2}\s*['"]function['"]/i.test(ctx.scriptText) ||
|
||||||
|
(hasMraidCall(ctx, 'getState') && /\b\w+\s*!={1,2}\s*['"]loading['"]|['"]loading['"]\s*!={1,2}\s*\w+\b/i.test(ctx.scriptText)) ||
|
||||||
|
(hasMraidCall(ctx, 'getState') && /\b\w+\s*={2,3}\s*['"]loading['"][\s\S]{0,500}\bwindow\s*\.\s*open\s*\(/i.test(ctx.scriptText))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasAudioVolumeNullSafeHandling(ctx: ScanContext): boolean {
|
||||||
|
return hasEventListener(ctx, 'audioVolumeChange') && (/typeof\s+\w+\s*={2,3}\s*['"]number['"]/i.test(ctx.scriptText) || /!=\s*null|!==\s*null/i.test(ctx.scriptText));
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasLifecycleSignal(ctx: ScanContext, name: string): boolean {
|
||||||
|
return new RegExp(`\\b${name}\\b`, 'i').test(ctx.html);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasUnsupportedHyperlink(ctx: ScanContext): boolean {
|
||||||
|
return /<a\b[^>]*\bhref\s*=/i.test(ctx.html);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasTwoPartExpand(ctx: ScanContext): boolean {
|
||||||
|
return /mraid\s*\.\s*expand\s*\(\s*[^)\s]/i.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function opensVideoUrl(ctx: ScanContext): boolean {
|
||||||
|
return /mraid\s*\.\s*open\s*\(\s*[^)]*\.(mp4|m4v|mov|webm|avi|m3u8)(?:['"`?#)]|$)/i.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isInMraidNetworkPath(ctx: ScanContext): boolean {
|
||||||
|
if (!ctx.filePath) return true;
|
||||||
|
return isInSupportedMraidFolderPath(ctx.filePath) || /_(al|is|un)\.html?$/i.test(path.basename(ctx.filePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasEventListener(ctx: ScanContext, eventName: string): boolean {
|
||||||
|
const pattern = new RegExp(`mraid\\s*\\.\\s*addEventListener\\s*\\(\\s*['"]${eventName}['"]`, 'i');
|
||||||
|
return pattern.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasSupportCheck(ctx: ScanContext, feature: string): boolean {
|
||||||
|
const pattern = new RegExp(`mraid\\s*\\.\\s*supports\\s*\\(\\s*['"]${feature}['"]`, 'i');
|
||||||
|
return pattern.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function usesDirectBrowserNavigation(ctx: ScanContext): boolean {
|
||||||
|
return /\bwindow\s*\.\s*open\s*\(/i.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
function usesLocationNavigation(ctx: ScanContext): boolean {
|
||||||
|
return /\blocation\s*\.\s*(href|assign|replace)\b/i.test(ctx.scriptText);
|
||||||
|
}
|
||||||
|
|
||||||
|
const MRAID_REFERENCE = 'GUIDE.md, MRAID 3.0 specification, and MRAID 3.0 Best Practices Guide.';
|
||||||
|
|
||||||
|
const MRAID_RULES: MraidRule[] = [
|
||||||
|
{
|
||||||
|
id: 'mraid-js-missing',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'mraid.js reference not found',
|
||||||
|
detail: 'MRAID creatives for AppLovin, ironSource, and Unity must request mraid.js early in the generated HTML.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => isInMraidNetworkPath(ctx) && countMraidJsReferences(ctx) === 0 ? issue(MRAID_RULES_BY_ID['mraid-js-missing']) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mraid-js-duplicate',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'Multiple mraid.js references found',
|
||||||
|
detail: 'Request mraid.js exactly once; duplicate references can inject multiple MRAID libraries and slow or destabilize the ad.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => countMraidJsReferences(ctx) > 1 ? issue(MRAID_RULES_BY_ID['mraid-js-duplicate']) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mraid-reference',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'MRAID API reference not found',
|
||||||
|
detail: 'Playable HTML should use the injected mraid object when it depends on an MRAID container.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidReference(ctx) ? null : issue(MRAID_RULES_BY_ID['mraid-reference']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'viewport-meta',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'Viewport meta tag not found',
|
||||||
|
detail: 'MRAID creatives should include a mobile viewport meta tag so the ad scales predictably on mobile WebViews.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasViewportMeta(ctx) ? null : issue(MRAID_RULES_BY_ID['viewport-meta']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mraid-typeof-guard',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'MRAID object is not guarded',
|
||||||
|
detail: 'Guard MRAID access with typeof mraid !== "undefined" or an equivalent window.mraid guard before making MRAID calls.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidReference(ctx) && !hasMraidTypeofGuard(ctx) ? issue(MRAID_RULES_BY_ID['mraid-typeof-guard']) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'dom-ready-gate',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'DOM readiness is not guarded',
|
||||||
|
detail: 'MRAID startup should wait for DOM readiness as well as MRAID readiness before building or binding rich media content.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => !hasMraidReference(ctx) || hasDomReadyGate(ctx) ? null : issue(MRAID_RULES_BY_ID['dom-ready-gate']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ready-gate',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'MRAID ready state is not guarded',
|
||||||
|
detail: 'Gate ad startup behind mraid.ready, or call startup immediately only when mraid.getState() is not loading.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => !hasMraidReference(ctx) || hasReadyGate(ctx) ? null : issue(MRAID_RULES_BY_ID['ready-gate']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ready-state-fallback',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'MRAID ready listener/state fallback pair not found',
|
||||||
|
detail: 'Use both mraid.addEventListener("ready", ...) and mraid.getState() so startup works when ready fires before the listener attaches.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => !hasMraidReference(ctx) || hasReadyListenerAndStateFallback(ctx) ? null : issue(MRAID_RULES_BY_ID['ready-state-fallback']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ready-timeout-fallback',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'MRAID ready timeout fallback not found',
|
||||||
|
detail: 'A timeout fallback prevents startup hangs when a container never fires ready.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => !hasMraidReference(ctx) || hasMraidReadyTimeout(ctx) ? null : issue(MRAID_RULES_BY_ID['ready-timeout-fallback']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'late-mraid-detection',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'Late MRAID injection detection not found',
|
||||||
|
detail: 'Poll or retry briefly for late window.mraid injection before deciding the creative is running without MRAID.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => !hasMraidReference(ctx) || hasLateMraidDetection(ctx) ? null : issue(MRAID_RULES_BY_ID['late-mraid-detection']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'error-listener',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'No MRAID error listener found',
|
||||||
|
detail: 'Listen for mraid error events so unsupported or failed MRAID calls can be logged or handled gracefully.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => !hasMraidReference(ctx) || hasEventListener(ctx, 'error') ? null : issue(MRAID_RULES_BY_ID['error-listener']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'viewability',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'MRAID viewability fallback chain not found',
|
||||||
|
detail: 'Use exposureChange for MRAID 3.0 and keep viewableChange or isViewable() as MRAID 2.0 fallback before starting animation, audio, video, or timers.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => {
|
||||||
|
const hasVisibilitySignal = hasEventListener(ctx, 'exposureChange') && (hasMraidCall(ctx, 'isViewable') || hasEventListener(ctx, 'viewableChange'));
|
||||||
|
return !hasMraidReference(ctx) || hasVisibilitySignal ? null : issue(MRAID_RULES_BY_ID['viewability']);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'audio-volume-change',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'audioVolumeChange handling not found',
|
||||||
|
detail: 'Listen for audioVolumeChange and ignore null values; only apply volume math when the value is numeric.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => !hasMraidReference(ctx) || hasAudioVolumeNullSafeHandling(ctx) ? null : issue(MRAID_RULES_BY_ID['audio-volume-change']),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'open-api',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'Browser navigation used instead of mraid.open',
|
||||||
|
detail: 'Use mraid.open(url) for click-through navigation inside an MRAID ad container; avoid hyperlinks, location redirects, and unguarded browser navigation.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasUnsupportedHyperlink(ctx) || usesLocationNavigation(ctx) || (usesDirectBrowserNavigation(ctx) && !hasMraidCall(ctx, 'open')) ? issue(MRAID_RULES_BY_ID['open-api']) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'open-guarded-fallback',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'mraid.open guarded fallback not found',
|
||||||
|
detail: 'Guard mraid.open with function/state checks and provide a window.open fallback when MRAID is unavailable or still loading.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'open') && (!hasMraidOpenGuard(ctx) || !hasMraidOpenLoadingGuard(ctx) || !usesDirectBrowserNavigation(ctx)) ? issue(MRAID_RULES_BY_ID['open-guarded-fallback'], mraidLine(ctx, 'open')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'open-video-url',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'mraid.open appears to target video media',
|
||||||
|
detail: 'Use mraid.playVideo(url) for native video playback cases instead of mraid.open(videoUrl).',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => opensVideoUrl(ctx) && !hasMraidCall(ctx, 'playVideo') ? issue(MRAID_RULES_BY_ID['open-video-url'], mraidLine(ctx, 'open')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'close-api',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'No mraid.close call found',
|
||||||
|
detail: 'If the creative renders its own close control, wire that control to mraid.close().',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => {
|
||||||
|
const appearsToHaveCloseUi = /\b(close|dismiss|skip)\b/i.test(ctx.html);
|
||||||
|
return appearsToHaveCloseUi && !hasMraidCall(ctx, 'close') ? issue(MRAID_RULES_BY_ID['close-api']) : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'unload-fallback',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'No mraid.unload graceful failure path found',
|
||||||
|
detail: 'Use mraid.unload() when the ad cannot run or refuses to show, instead of leaving a broken or blank creative.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidReference(ctx) && !hasMraidCall(ctx, 'unload') ? issue(MRAID_RULES_BY_ID['unload-fallback']) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'resize-properties',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'mraid.resize used without setResizeProperties',
|
||||||
|
detail: 'Call mraid.setResizeProperties(...) before mraid.resize(); otherwise the container should emit an error.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'resize') && !hasMraidCall(ctx, 'setResizeProperties') ? issue(MRAID_RULES_BY_ID['resize-properties'], mraidLine(ctx, 'resize')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'use-custom-close',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'Deprecated useCustomClose found',
|
||||||
|
detail: 'MRAID 3.0 ignores useCustomClose; the host provides the mandatory close control.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'useCustomClose') || /useCustomClose/i.test(ctx.scriptText) ? issue(MRAID_RULES_BY_ID['use-custom-close'], mraidLine(ctx, 'useCustomClose')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'two-part-expand',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'Two-part expand appears to be used',
|
||||||
|
detail: 'Two-part expandable ads are deprecated in MRAID 3.0; use self-contained one-part expandables.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasTwoPartExpand(ctx) ? issue(MRAID_RULES_BY_ID['two-part-expand'], mraidLine(ctx, 'expand')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'expand-support',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'mraid.expand used without function guard',
|
||||||
|
detail: 'Guard mraid.expand with a function check before using expand behavior.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'expand') && !hasMraidFunctionGuard(ctx, 'expand') ? issue(MRAID_RULES_BY_ID['expand-support'], mraidLine(ctx, 'expand')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'resize-support',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'mraid.resize used without function guard',
|
||||||
|
detail: 'Guard mraid.resize with a function check before using resize behavior.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'resize') && !hasMraidFunctionGuard(ctx, 'resize') ? issue(MRAID_RULES_BY_ID['resize-support'], mraidLine(ctx, 'resize')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'store-picture-support',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'storePicture used without supports check',
|
||||||
|
detail: 'Call mraid.supports("storePicture") before mraid.storePicture(...).',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'storePicture') && !hasSupportCheck(ctx, 'storePicture') ? issue(MRAID_RULES_BY_ID['store-picture-support'], mraidLine(ctx, 'storePicture')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'calendar-support',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'createCalendarEvent used without supports check',
|
||||||
|
detail: 'Call mraid.supports("calendar") before mraid.createCalendarEvent(...).',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'createCalendarEvent') && !hasSupportCheck(ctx, 'calendar') ? issue(MRAID_RULES_BY_ID['calendar-support'], mraidLine(ctx, 'createCalendarEvent')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'location-support',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'getLocation used without supports check',
|
||||||
|
detail: 'Call mraid.supports("location") before mraid.getLocation(). Do not use HTML5 geolocation as a substitute in MRAID.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'getLocation') && !hasSupportCheck(ctx, 'location') ? issue(MRAID_RULES_BY_ID['location-support'], mraidLine(ctx, 'getLocation')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'vpaid-support',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'VPAID integration used without supports check',
|
||||||
|
detail: 'Call mraid.supports("vpaid") before mraid.initVpaid(...).',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'initVpaid') && !hasSupportCheck(ctx, 'vpaid') ? issue(MRAID_RULES_BY_ID['vpaid-support'], mraidLine(ctx, 'initVpaid')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'orientation-support',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'Orientation properties set without function guard',
|
||||||
|
detail: 'Guard mraid.setOrientationProperties with a function check before requiring orientation behavior.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => hasMraidCall(ctx, 'setOrientationProperties') && !hasMraidFunctionGuard(ctx, 'setOrientationProperties') ? issue(MRAID_RULES_BY_ID['orientation-support'], mraidLine(ctx, 'setOrientationProperties')) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'size-change',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'No sizeChange listener found',
|
||||||
|
detail: 'Listen for sizeChange when layout depends on container size, resize, expand, or orientation behavior.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => {
|
||||||
|
const dependsOnSize = hasMraidCall(ctx, 'getMaxSize') || hasMraidCall(ctx, 'getScreenSize') || hasMraidCall(ctx, 'resize') || hasMraidCall(ctx, 'expand') || hasMraidCall(ctx, 'setOrientationProperties');
|
||||||
|
return dependsOnSize && !hasEventListener(ctx, 'sizeChange') ? issue(MRAID_RULES_BY_ID['size-change']) : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'state-change',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'No stateChange listener found',
|
||||||
|
detail: 'Listen for stateChange when using expand, resize, close, or other state-changing container behavior.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => {
|
||||||
|
const changesState = hasMraidCall(ctx, 'expand') || hasMraidCall(ctx, 'resize') || hasMraidCall(ctx, 'close');
|
||||||
|
return changesState && !hasEventListener(ctx, 'stateChange') ? issue(MRAID_RULES_BY_ID['state-change']) : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'output-script-hygiene',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'Rejected script attributes found',
|
||||||
|
detail: 'Playable output should not contain type="module" or crossorigin on script tags; ad networks can reject ES modules/CORS attributes.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => /<script\b[^>]*(\btype\s*=\s*['"]module['"]|\bcrossorigin\b)/i.test(ctx.html) ? issue(MRAID_RULES_BY_ID['output-script-hygiene']) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'console-error',
|
||||||
|
severity: 'best-practice',
|
||||||
|
title: 'console.error found',
|
||||||
|
detail: 'The ship checklist expects no console.error calls in output; use guarded logging or remove debug error logs before submission.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => /\bconsole\s*\.\s*error\s*\(/i.test(ctx.scriptText) ? issue(MRAID_RULES_BY_ID['console-error']) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'lifecycle-stubs',
|
||||||
|
severity: 'requirement',
|
||||||
|
title: 'Playable lifecycle signals not found',
|
||||||
|
detail: 'Expose or call gameReady, gameStart, gameEnd, and gameClose so network preview tools can detect the playable lifecycle.',
|
||||||
|
reference: MRAID_REFERENCE,
|
||||||
|
test: (ctx) => {
|
||||||
|
const missing = ['gameReady', 'gameStart', 'gameEnd', 'gameClose'].filter(name => !hasLifecycleSignal(ctx, name));
|
||||||
|
if (!missing.length) return null;
|
||||||
|
const rule = MRAID_RULES_BY_ID['lifecycle-stubs'];
|
||||||
|
return { ...issue(rule), detail: `${rule.detail} Missing: ${missing.join(', ')}.` };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const MRAID_RULES_BY_ID = MRAID_RULES.reduce<Record<string, MraidRule>>((acc, rule) => {
|
||||||
|
acc[rule.id] = rule;
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
function getHtml(): string {
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<style>
|
||||||
|
${getToolWebviewStyles()}
|
||||||
|
.issues { margin: 0; padding: 0; }
|
||||||
|
.issue { list-style: none; margin: 0 0 8px; }
|
||||||
|
.issue:last-child { margin-bottom: 0; }
|
||||||
|
.severity-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
min-width: 82px;
|
||||||
|
justify-content: center;
|
||||||
|
margin-right: 6px;
|
||||||
|
padding: 1px 6px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--tool-border);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.requirement { color: var(--vscode-errorForeground); background: var(--vscode-inputValidation-errorBackground, rgba(248,81,73,0.14)); }
|
||||||
|
.best-practice { color: var(--vscode-editorWarning-foreground, #d29922); background: var(--vscode-inputValidation-warningBackground, rgba(210,153,34,0.14)); }
|
||||||
|
.issue-title { font-weight: 600; }
|
||||||
|
.issue-detail { color: var(--vscode-descriptionForeground); margin-top: 2px; }
|
||||||
|
.selected-list { margin-top: 8px; }
|
||||||
|
.pager { margin-top: 8px; display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="tool-page">
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">MRAID Checker</h2>
|
||||||
|
<p class="tool-description">Static checks for AppLovin, ironSource, and Unity HTML builds based on GUIDE.md plus the MRAID 3.0 specification and Best Practices Guide.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="tool-panel input-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3 class="panel-title">Inputs</h3>
|
||||||
|
</div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="field-row">
|
||||||
|
<input id="folder" type="hidden" />
|
||||||
|
<button id="pick" class="secondary">Select Folder</button>
|
||||||
|
<button id="pickFiles" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div id="selection" class="selected-list"></div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="scan">Scan</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="outputPanel" class="is-hidden">
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<script>
|
||||||
|
const vscode = acquireVsCodeApi();
|
||||||
|
vscode.postMessage({ type: 'ready' });
|
||||||
|
const folderEl = document.getElementById('folder');
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const resultsEl = document.getElementById('results');
|
||||||
|
const outputPanel = document.getElementById('outputPanel');
|
||||||
|
const selectionEl = document.getElementById('selection');
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
let pickedFolder = '';
|
||||||
|
let pickedFiles = [];
|
||||||
|
let selectedPage = 0;
|
||||||
|
|
||||||
|
function basename(p) {
|
||||||
|
const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\\\'));
|
||||||
|
return i >= 0 ? p.slice(i + 1) : p;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeText(value) {
|
||||||
|
return String(value).replace(/[&<>"']/g, (ch) => ({
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
"'": '''
|
||||||
|
}[ch]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSelection() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
const items = pickedFiles.length
|
||||||
|
? pickedFiles.map((p, i) => ({ label: basename(p), index: i, type: 'file' }))
|
||||||
|
: (pickedFolder ? [{ label: pickedFolder, index: 0, type: 'folder' }] : []);
|
||||||
|
if (!items.length) {
|
||||||
|
selectionEl.innerHTML = '<span class="file-name">(no files selected)</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const maxPage = Math.max(0, Math.ceil(items.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const visibleItems = items.slice(selectedPage * PAGE_SIZE, selectedPage * PAGE_SIZE + PAGE_SIZE);
|
||||||
|
selectionEl.innerHTML =
|
||||||
|
'<div class="results-panel" style="margin-top:0;">' +
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead>' +
|
||||||
|
'<tbody>' +
|
||||||
|
visibleItems.map(item =>
|
||||||
|
'<tr><td class="mono wrap">' + escapeText(item.label) + '</td>' +
|
||||||
|
'<td><button class="remove-selected danger" data-index="' + item.index + '" data-type="' + item.type + '" title="Remove">×</button></td></tr>'
|
||||||
|
).join('') +
|
||||||
|
'</tbody>' +
|
||||||
|
'</table>' +
|
||||||
|
'</div>';
|
||||||
|
selectionEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
if (btn.dataset.type === 'folder') {
|
||||||
|
pickedFolder = '';
|
||||||
|
folderEl.value = '';
|
||||||
|
} else {
|
||||||
|
pickedFiles.splice(Number(btn.dataset.index), 1);
|
||||||
|
}
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (items.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML =
|
||||||
|
'<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
selectionEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderSelection();
|
||||||
|
|
||||||
|
document.getElementById('pick').addEventListener('click', () => {
|
||||||
|
vscode.postMessage({ type: 'pickFolder' });
|
||||||
|
});
|
||||||
|
document.getElementById('pickFiles').addEventListener('click', () => {
|
||||||
|
vscode.postMessage({ type: 'pickFiles' });
|
||||||
|
});
|
||||||
|
document.getElementById('clear').addEventListener('click', () => {
|
||||||
|
folderEl.value = '';
|
||||||
|
pickedFolder = '';
|
||||||
|
pickedFiles = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
});
|
||||||
|
document.getElementById('scan').addEventListener('click', () => {
|
||||||
|
statusEl.textContent = 'Scanning...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
if (pickedFiles.length) {
|
||||||
|
vscode.postMessage({ type: 'scan', files: pickedFiles });
|
||||||
|
} else {
|
||||||
|
const folder = folderEl.value.trim();
|
||||||
|
if (!folder) { statusEl.textContent = 'Pick a folder or files first.'; return; }
|
||||||
|
vscode.postMessage({ type: 'scan', folder });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('message', (event) => {
|
||||||
|
const msg = event.data;
|
||||||
|
if (msg.type === 'folderPicked') {
|
||||||
|
folderEl.value = msg.path;
|
||||||
|
pickedFolder = msg.path;
|
||||||
|
pickedFiles = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
|
} else if (msg.type === 'filesPicked') {
|
||||||
|
const existing = new Set(pickedFiles);
|
||||||
|
pickedFiles = pickedFiles.concat((msg.paths || []).filter(p => !existing.has(p)));
|
||||||
|
folderEl.value = '';
|
||||||
|
pickedFolder = '';
|
||||||
|
selectedPage = Math.max(0, Math.ceil(pickedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
} else if (msg.type === 'status') {
|
||||||
|
statusEl.textContent = msg.message;
|
||||||
|
statusEl.className = 'status-panel is-busy';
|
||||||
|
} else if (msg.type === 'results') {
|
||||||
|
if (msg.error) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Error: ' + msg.error;
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const total = msg.results.length;
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
const withIssues = msg.results.filter(r => !r.ok).length;
|
||||||
|
const skipped = Number(msg.skipped || 0);
|
||||||
|
const skippedReason = msg.skippedReason || 'file(s).';
|
||||||
|
const skippedText = skipped ? ' Skipped ' + skipped + ' ' + skippedReason : '';
|
||||||
|
statusEl.textContent = 'Scanned ' + total + ' HTML file(s). ' + withIssues + ' file(s) need review.' + skippedText;
|
||||||
|
if (!total) {
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
outputPanel.classList.remove('is-hidden');
|
||||||
|
resultsEl.innerHTML =
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th>File</th><th>Results</th></tr></thead>' +
|
||||||
|
'<tbody></tbody>' +
|
||||||
|
'</table>';
|
||||||
|
const tbody = resultsEl.querySelector('tbody');
|
||||||
|
for (const r of msg.results) {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
const file = document.createElement('td');
|
||||||
|
file.className = 'mono wrap';
|
||||||
|
file.textContent = r.file;
|
||||||
|
const issues = document.createElement('td');
|
||||||
|
issues.className = 'wrap';
|
||||||
|
if (!r.ok) {
|
||||||
|
const list = document.createElement('ul');
|
||||||
|
list.className = 'issues';
|
||||||
|
for (const i of r.issues) {
|
||||||
|
const item = document.createElement('li');
|
||||||
|
item.className = 'issue';
|
||||||
|
const line = i.line ? ' line ' + i.line + ':' : '';
|
||||||
|
item.innerHTML =
|
||||||
|
'<span class="severity-badge ' + i.severity + '">' + escapeText(i.severity) + '</span>' +
|
||||||
|
'<span class="issue-title">' + escapeText(line + ' ' + i.title) + '</span>' +
|
||||||
|
'<div class="issue-detail">' + escapeText(i.detail) + '</div>';
|
||||||
|
list.appendChild(item);
|
||||||
|
}
|
||||||
|
issues.appendChild(list);
|
||||||
|
} else {
|
||||||
|
issues.innerHTML = '<span class="badge ok">OK</span>';
|
||||||
|
}
|
||||||
|
row.append(file, issues);
|
||||||
|
tbody.appendChild(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
671
src/tools/playworksConverter.ts
Normal file
671
src/tools/playworksConverter.ts
Normal file
@@ -0,0 +1,671 @@
|
|||||||
|
import * as vscode from 'vscode';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
import * as cp from 'child_process';
|
||||||
|
import { getToolWebviewStyles, singletonPanel } from './shared';
|
||||||
|
|
||||||
|
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
||||||
|
|
||||||
|
interface ConvertOptions {
|
||||||
|
sourcePath: string;
|
||||||
|
outputDir: string;
|
||||||
|
baseName?: string;
|
||||||
|
networks: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NetworkResult {
|
||||||
|
network: string;
|
||||||
|
file: string;
|
||||||
|
ok: boolean;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function openPlayworksConverter(_context: vscode.ExtensionContext) {
|
||||||
|
const { panel, isNew } = singletonPanel(store, 'hplToolbox.playworksConverter', 'Playworks Converter');
|
||||||
|
if (!isNew) return;
|
||||||
|
|
||||||
|
panel.webview.html = getHtml();
|
||||||
|
|
||||||
|
panel.webview.onDidReceiveMessage(async (msg) => {
|
||||||
|
switch (msg.type) {
|
||||||
|
case 'pickSource': {
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFiles: true,
|
||||||
|
canSelectFolders: false,
|
||||||
|
canSelectMany: false,
|
||||||
|
filters: { HTML: ['html', 'htm'] },
|
||||||
|
openLabel: 'Select Playworks HTML',
|
||||||
|
});
|
||||||
|
if (!picked?.[0]) return;
|
||||||
|
const srcPath = picked[0].fsPath;
|
||||||
|
const dir = path.dirname(srcPath);
|
||||||
|
panel.webview.postMessage({ type: 'sourcePicked', path: srcPath, dir, baseName: sourceBaseName(srcPath) });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'pickOutput': {
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFiles: false,
|
||||||
|
canSelectFolders: true,
|
||||||
|
canSelectMany: false,
|
||||||
|
openLabel: 'Select Output Folder',
|
||||||
|
});
|
||||||
|
if (!picked?.[0]) return;
|
||||||
|
panel.webview.postMessage({ type: 'outputPicked', path: picked[0].fsPath });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'convert': {
|
||||||
|
const opts: ConvertOptions = msg.opts;
|
||||||
|
if (!fs.existsSync(opts.sourcePath)) {
|
||||||
|
panel.webview.postMessage({ type: 'convertDone', results: [], error: 'Source file not found.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(opts.outputDir)) {
|
||||||
|
try { fs.mkdirSync(opts.outputDir, { recursive: true }); } catch {
|
||||||
|
panel.webview.postMessage({ type: 'convertDone', results: [], error: 'Could not create output folder.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let html: string;
|
||||||
|
try {
|
||||||
|
panel.webview.postMessage({ type: 'status', message: 'Reading source HTML...' });
|
||||||
|
html = fs.readFileSync(opts.sourcePath, 'utf8');
|
||||||
|
} catch (e: any) {
|
||||||
|
panel.webview.postMessage({ type: 'convertDone', results: [], error: `Could not read source: ${e.message}` });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const results: NetworkResult[] = [];
|
||||||
|
try {
|
||||||
|
panel.webview.postMessage({ type: 'status', message: 'Converting Unity...' });
|
||||||
|
results.push({ network: 'un', file: copyUnityInput(opts), ok: true });
|
||||||
|
} catch (e: any) {
|
||||||
|
results.push({ network: 'un', file: '', ok: false, error: e.message });
|
||||||
|
}
|
||||||
|
for (let i = 0; i < opts.networks.length; i++) {
|
||||||
|
const network = opts.networks[i];
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Converting ${i + 1}/${opts.networks.length} ${network}` });
|
||||||
|
try {
|
||||||
|
const filePath = await convertNetwork(html, opts, network);
|
||||||
|
results.push({ network, file: filePath, ok: true });
|
||||||
|
} catch (e: any) {
|
||||||
|
results.push({ network, file: '', ok: false, error: e.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panel.webview.postMessage({ type: 'convertDone', results });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'openOutput': {
|
||||||
|
vscode.env.openExternal(vscode.Uri.file(msg.dir));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const ZIPPED_NETWORKS = new Set(['gg', 'ap', 'vu', 'mtg']);
|
||||||
|
const SUPPORTED_NETWORKS = new Set(['al', 'is', 'fb', 'gg', 'ap', 'mo', 'vu', 'mtg', 'tt']);
|
||||||
|
const MRAID_NETWORKS = new Set(['al', 'is']);
|
||||||
|
const EXITAPI_NETWORKS = new Set(['gg', 'ap']);
|
||||||
|
const NETWORK_OUTPUT_FOLDERS: Record<string, string> = {
|
||||||
|
al: 'Applovin',
|
||||||
|
is: 'Ironsource',
|
||||||
|
fb: 'Facebook',
|
||||||
|
gg: 'GoogleAds',
|
||||||
|
ap: 'Appreciate',
|
||||||
|
mo: 'Moloco',
|
||||||
|
vu: 'Vungle',
|
||||||
|
mtg: 'Mintegral',
|
||||||
|
tt: 'TikTok',
|
||||||
|
};
|
||||||
|
|
||||||
|
function sourceBaseName(sourcePath: string): string {
|
||||||
|
return path.basename(sourcePath, path.extname(sourcePath))
|
||||||
|
.replace(/_(?:un|al|is|fb|gg|ap|mo|vu|mtg|tt)$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function outputBaseName(opts: ConvertOptions): string {
|
||||||
|
const rawBaseName = opts.baseName?.trim() || sourceBaseName(opts.sourcePath);
|
||||||
|
const withoutExtension = rawBaseName.replace(/\.html?$/i, '');
|
||||||
|
const safeBaseName = path.basename(withoutExtension).replace(/[<>:"/\\|?*]/g, '_').trim();
|
||||||
|
return safeBaseName || sourceBaseName(opts.sourcePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function convertNetwork(html: string, opts: ConvertOptions, network: string): Promise<string> {
|
||||||
|
if (!SUPPORTED_NETWORKS.has(network)) {
|
||||||
|
throw new Error(`Unsupported Playworks target network: ${network}`);
|
||||||
|
}
|
||||||
|
const transformed = transformHtml(html, network);
|
||||||
|
const needsZip = ZIPPED_NETWORKS.has(network);
|
||||||
|
const baseName = outputBaseName(opts);
|
||||||
|
const htmlFileName = `${baseName}_${network}.html`;
|
||||||
|
const outputDir = path.join(opts.outputDir, NETWORK_OUTPUT_FOLDERS[network] ?? network);
|
||||||
|
fs.mkdirSync(outputDir, { recursive: true });
|
||||||
|
|
||||||
|
if (needsZip) {
|
||||||
|
const tmpPath = path.join(outputDir, `_tmp_${Date.now()}_${network}.html`);
|
||||||
|
const zipPath = path.join(outputDir, `${baseName}_${network}.zip`);
|
||||||
|
fs.writeFileSync(tmpPath, transformed, 'utf8');
|
||||||
|
try {
|
||||||
|
await createZip(tmpPath, 'index.html', zipPath);
|
||||||
|
} finally {
|
||||||
|
try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
return zipPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outPath = path.join(outputDir, htmlFileName);
|
||||||
|
fs.writeFileSync(outPath, transformed, 'utf8');
|
||||||
|
return outPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyUnityInput(opts: ConvertOptions): string {
|
||||||
|
const baseName = outputBaseName(opts);
|
||||||
|
const outputDir = path.join(opts.outputDir, 'Unity');
|
||||||
|
const outPath = path.join(outputDir, `${baseName}_un.html`);
|
||||||
|
fs.mkdirSync(outputDir, { recursive: true });
|
||||||
|
if (path.resolve(opts.sourcePath) === path.resolve(outPath)) {
|
||||||
|
return outPath;
|
||||||
|
}
|
||||||
|
fs.copyFileSync(opts.sourcePath, outPath);
|
||||||
|
return outPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformHtml(html: string, network: string): string {
|
||||||
|
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);
|
||||||
|
let headInject = buildLifecycleScript();
|
||||||
|
if (MRAID_NETWORKS.has(network)) {
|
||||||
|
headInject += '<script src="mraid.js"></script>' + buildMraidComplianceScript();
|
||||||
|
} else if (EXITAPI_NETWORKS.has(network)) {
|
||||||
|
headInject += '<script src="exitapi.js"></script>';
|
||||||
|
}
|
||||||
|
result = injectBeforeHeadClose(result, headInject);
|
||||||
|
|
||||||
|
// Body-level flags
|
||||||
|
if (network === 'vu') {
|
||||||
|
result = injectAfterBodyOpen(result, '<script>window.__VUNGLE__=true;</script>');
|
||||||
|
} else if (network === 'mtg') {
|
||||||
|
result = addBodyOnload(result, 'gameReady()');
|
||||||
|
} else if (network === 'tt') {
|
||||||
|
result = injectAfterBodyOpen(result, '<script>window.__TIKTOK__=true;</script>');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 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', EXITAPI_NETWORKS.has(network));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeNetworkSdkScripts(html: string): string {
|
||||||
|
let result = html;
|
||||||
|
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'), '');
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
function injectBeforeHeadClose(html: string, injection: string): string {
|
||||||
|
if (/<\/head>/i.test(html)) {
|
||||||
|
return html.replace(/<\/head>/i, `${injection}\n</head>`);
|
||||||
|
}
|
||||||
|
return `${injection}\n${html}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function injectAfterBodyOpen(html: string, injection: string): string {
|
||||||
|
if (/<body\b[^>]*>/i.test(html)) {
|
||||||
|
return html.replace(/<body\b[^>]*>/i, match => `${match}\n${injection}`);
|
||||||
|
}
|
||||||
|
return `${injection}\n${html}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addBodyOnload(html: string, handler: string): string {
|
||||||
|
if (!/<body\b[^>]*>/i.test(html)) {
|
||||||
|
return `<body onload="${handler}">\n${html}`;
|
||||||
|
}
|
||||||
|
return html.replace(/<body\b([^>]*)>/i, (match, attrs: string) => {
|
||||||
|
const onloadMatch = attrs.match(/\bonload\s*=\s*(["'])(.*?)\1/i);
|
||||||
|
if (!onloadMatch) return `<body${attrs} onload="${handler}">`;
|
||||||
|
if (onloadMatch[2].includes(handler)) return match;
|
||||||
|
const updated = `${onloadMatch[2]};${handler}`;
|
||||||
|
return match.replace(onloadMatch[0], `onload=${onloadMatch[1]}${updated}${onloadMatch[1]}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function replaceCTAScript(html: string, network: string): string {
|
||||||
|
const marker = 'Luna.Unity.Playable.InstallFullGame=function';
|
||||||
|
const markerIdx = html.lastIndexOf(marker);
|
||||||
|
if (markerIdx === -1) return html;
|
||||||
|
|
||||||
|
const scriptOpenIdx = html.lastIndexOf('<script>', markerIdx);
|
||||||
|
if (scriptOpenIdx === -1) return html;
|
||||||
|
|
||||||
|
const scriptCloseIdx = html.indexOf('</script>', markerIdx);
|
||||||
|
if (scriptCloseIdx === -1) return html;
|
||||||
|
|
||||||
|
const before = html.slice(0, scriptOpenIdx);
|
||||||
|
const after = html.slice(scriptCloseIdx + '</script>'.length);
|
||||||
|
|
||||||
|
// Console restore runs after the bundle (which overrides console), before CTA
|
||||||
|
return before + buildConsoleRestoreScript() + buildCTAScript(network) + after;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restores native console methods overridden by the Playworks bundle,
|
||||||
|
// using a temporary iframe to get a fresh un-patched console reference.
|
||||||
|
function buildConsoleRestoreScript(): string {
|
||||||
|
return [
|
||||||
|
'<script>(function(){',
|
||||||
|
'try{',
|
||||||
|
'var f=document.createElement("iframe");',
|
||||||
|
'f.style.display="none";',
|
||||||
|
'document.documentElement.appendChild(f);',
|
||||||
|
'var nc=f.contentWindow.console;',
|
||||||
|
'document.documentElement.removeChild(f);',
|
||||||
|
'var methods=["log","warn","error","info","debug","dir","table","group","groupEnd","groupCollapsed","time","timeEnd","assert","count","countReset","trace"];',
|
||||||
|
'methods.forEach(function(m){try{if(typeof nc[m]==="function")window.console[m]=nc[m].bind(nc);}catch(e){}});',
|
||||||
|
'}catch(e){}',
|
||||||
|
'})();</script>',
|
||||||
|
].join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exposes gameReady/Start/End/Close stubs on window and wires them to Luna events.
|
||||||
|
// Registered in <head> so our luna:build listener fires BEFORE the Playworks bundle
|
||||||
|
// listeners (which synchronously dispatch luna:start inside their luna:build handler).
|
||||||
|
// One-time guards prevent double-calls:
|
||||||
|
// - gameReady: luna:build fires it once; mtg's onload="gameReady()" also fires it
|
||||||
|
// - gameStart: luna:start fires twice on non-MRAID networks (two Playworks listeners)
|
||||||
|
function buildLifecycleScript(): string {
|
||||||
|
return [
|
||||||
|
'<script>(function(){',
|
||||||
|
'if(typeof window.gameReady!=="function")window.gameReady=function(){};',
|
||||||
|
'if(typeof window.gameStart!=="function")window.gameStart=function(){};',
|
||||||
|
'if(typeof window.gameEnd!=="function")window.gameEnd=function(){};',
|
||||||
|
'if(typeof window.gameClose!=="function")window.gameClose=function(){};',
|
||||||
|
'var _grOnce=false,_gsOnce=false;',
|
||||||
|
'window.addEventListener("luna:build",function(){if(_grOnce)return;_grOnce=true;try{window.gameReady();}catch(e){}});',
|
||||||
|
'window.addEventListener("luna:start",function(){if(_gsOnce)return;_gsOnce=true;try{window.gameStart();}catch(e){}});',
|
||||||
|
'window.addEventListener("luna:ended",function(){try{window.gameEnd();}catch(e){}});',
|
||||||
|
'})();</script>',
|
||||||
|
].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
|
||||||
|
const closeCall = `try{window.gameClose();}catch(e){}`;
|
||||||
|
|
||||||
|
let ctaLogic: string;
|
||||||
|
switch (network) {
|
||||||
|
case 'al':
|
||||||
|
case 'is':
|
||||||
|
// 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;
|
||||||
|
case 'fb':
|
||||||
|
ctaLogic = `${closeCall}if(typeof FbPlayableAd!=="undefined"&&typeof FbPlayableAd.onCTAClick==="function"){FbPlayableAd.onCTAClick();return;}window.open(o,"_blank");`;
|
||||||
|
break;
|
||||||
|
case 'gg':
|
||||||
|
case 'ap':
|
||||||
|
// Google — exitapi.js injected in <head>
|
||||||
|
ctaLogic = `${closeCall}if(typeof ExitApi!=="undefined"&&typeof ExitApi.exit==="function"){ExitApi.exit();return;}window.open(o,"_blank");`;
|
||||||
|
break;
|
||||||
|
case 'mo':
|
||||||
|
ctaLogic = `${closeCall}if(typeof FbPlayableAd!=="undefined"&&typeof FbPlayableAd.onCTAClick==="function"){FbPlayableAd.onCTAClick();return;}if(typeof window.clickTag==="string"&&window.clickTag){window.open(window.clickTag,"_blank");return;}window.open(o,"_blank");`;
|
||||||
|
break;
|
||||||
|
case 'vu':
|
||||||
|
// Vungle — window.__VUNGLE__ flag set in body
|
||||||
|
ctaLogic = `${closeCall}try{parent.postMessage("download","*");}catch(e){}`;
|
||||||
|
break;
|
||||||
|
case 'mtg':
|
||||||
|
// Mintegral — onload="gameReady()" set on body
|
||||||
|
ctaLogic = `${closeCall}if(typeof window.install==="function"){window.install();return;}window.open(o,"_blank");`;
|
||||||
|
break;
|
||||||
|
case 'tt':
|
||||||
|
// TikTok — window.__TIKTOK__ flag set in body
|
||||||
|
ctaLogic = `${closeCall}if(typeof window.openAppStore==="function"){window.openAppStore();return;}window.open(o,"_blank");`;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
ctaLogic = `${closeCall}window.open(o,"_blank");`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<script>window.addEventListener("luna:build",(function(){Bridge.ready((function(){Luna.Unity.Playable.InstallFullGame=function(n,i){window.pi.logCta(),${urlSetup}${ctaLogic}}}))}));</script>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createZip(srcFilePath: string, nameInZip: string, destZipPath: string): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// Remove existing zip if present (Compress-Archive would fail otherwise)
|
||||||
|
if (fs.existsSync(destZipPath)) {
|
||||||
|
try { fs.unlinkSync(destZipPath); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
const psScript = [
|
||||||
|
'Add-Type -AssemblyName System.IO.Compression.FileSystem;',
|
||||||
|
`$zip=[System.IO.Compression.ZipFile]::Open('${destZipPath}','Create');`,
|
||||||
|
`[void][System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,'${srcFilePath}','${nameInZip}');`,
|
||||||
|
'$zip.Dispose()',
|
||||||
|
].join(' ');
|
||||||
|
|
||||||
|
const proc = cp.spawn('powershell.exe', ['-NonInteractive', '-Command', psScript], { stdio: ['ignore', 'pipe', 'pipe'] });
|
||||||
|
let stderr = '';
|
||||||
|
proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });
|
||||||
|
proc.on('close', (code) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve();
|
||||||
|
} else {
|
||||||
|
reject(new Error(`Zip failed (code ${code}): ${stderr.trim()}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
proc.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Webview UI ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function getHtml(): string {
|
||||||
|
const networks = [
|
||||||
|
{ tag: 'al', label: 'Applovin', note: 'HTML + mraid.js in head' },
|
||||||
|
{ tag: 'is', label: 'Ironsource', note: 'HTML + mraid.js in head' },
|
||||||
|
{ tag: 'fb', label: 'Facebook', note: 'HTML' },
|
||||||
|
{ tag: 'gg', label: 'Google Ads', note: 'ZIP + exitapi.js in head' },
|
||||||
|
{ tag: 'ap', label: 'Appreciate', note: 'ZIP + exitapi.js in head' },
|
||||||
|
{ 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: 'tt', label: 'TikTok', note: 'HTML + __TIKTOK__ flag' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const checkboxRows = networks.map(n => `
|
||||||
|
<tr>
|
||||||
|
<td style="width:70px;"><input type="checkbox" class="net-cb" data-tag="${n.tag}"${n.tag === 'tt' ? '' : ' checked'} /></td>
|
||||||
|
<td style="width:160px;"><span class="net-label">${n.label}</span> <span class="net-tag">${n.tag}</span></td>
|
||||||
|
<td><span class="net-note">${n.note}</span></td>
|
||||||
|
</tr>`).join('');
|
||||||
|
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<style>
|
||||||
|
${getToolWebviewStyles()}
|
||||||
|
.net-label { min-width: 100px; font-weight: 500; }
|
||||||
|
.net-tag { font-size: 10px; opacity: 0.6; font-weight: 400; }
|
||||||
|
.net-note { font-size: 11px; opacity: 0.6; }
|
||||||
|
.toggle-row { display: flex; gap: 8px; margin-bottom: 6px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="tool-page">
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">Playworks Converter</h2>
|
||||||
|
<p class="tool-description">Convert a Playworks HTML export into network-specific playable outputs.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="tool-panel input-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<h3 class="panel-title">Inputs</h3>
|
||||||
|
</div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Source HTML (Playworks export)</div>
|
||||||
|
<div class="field-row">
|
||||||
|
<input id="src" type="hidden" />
|
||||||
|
<button id="pickSrc" class="secondary">Select File</button>
|
||||||
|
<span id="srcName" class="file-name">(no file)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Base Filename</div>
|
||||||
|
<div class="field-row">
|
||||||
|
<input id="baseName" type="text" placeholder="Base filename..." />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Output Folder</div>
|
||||||
|
<div class="field-row">
|
||||||
|
<input id="outDir" type="text" placeholder="Output folder..." />
|
||||||
|
<button id="pickOut" class="secondary">Browse...</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Networks to Generate</div>
|
||||||
|
<div class="toggle-row">
|
||||||
|
<button id="selectAll" class="secondary">Select All</button>
|
||||||
|
<button id="selectNone" class="secondary">Select None</button>
|
||||||
|
</div>
|
||||||
|
<div class="results-panel" style="margin-top:0;">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th style="width:70px;">Use</th><th style="width:160px;">Network</th><th>Output behavior</th></tr></thead>
|
||||||
|
<tbody>${checkboxRows}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="convert" disabled>Convert</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="outputPanel" class="is-hidden">
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="openOut" class="secondary" style="display:none">Open Output Folder</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const vscode = acquireVsCodeApi();
|
||||||
|
let outputDir = '';
|
||||||
|
|
||||||
|
const srcEl = document.getElementById('src');
|
||||||
|
const srcNameEl = document.getElementById('srcName');
|
||||||
|
const outEl = document.getElementById('outDir');
|
||||||
|
const baseNameEl = document.getElementById('baseName');
|
||||||
|
const convertBtn = document.getElementById('convert');
|
||||||
|
const openOutBtn = document.getElementById('openOut');
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const resultsEl = document.getElementById('results');
|
||||||
|
const outputPanel = document.getElementById('outputPanel');
|
||||||
|
|
||||||
|
function updateConvertBtn() {
|
||||||
|
const hasNet = [...document.querySelectorAll('.net-cb')].some(c => c.checked);
|
||||||
|
convertBtn.disabled = !srcEl.value || !outEl.value || !baseNameEl.value.trim() || !hasNet;
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultOutputDir(dir) {
|
||||||
|
return dir ? dir.replace(/[\\\\/]+$/, '') + '\\\\Output' : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('pickSrc').addEventListener('click', () => vscode.postMessage({ type: 'pickSource' }));
|
||||||
|
document.getElementById('pickOut').addEventListener('click', () => vscode.postMessage({ type: 'pickOutput' }));
|
||||||
|
document.getElementById('selectAll').addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.net-cb').forEach(c => c.checked = c.dataset.tag !== 'tt');
|
||||||
|
updateConvertBtn();
|
||||||
|
});
|
||||||
|
document.getElementById('selectNone').addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.net-cb').forEach(c => c.checked = false);
|
||||||
|
updateConvertBtn();
|
||||||
|
});
|
||||||
|
document.querySelectorAll('.net-cb').forEach(c => c.addEventListener('change', updateConvertBtn));
|
||||||
|
outEl.addEventListener('input', updateConvertBtn);
|
||||||
|
baseNameEl.addEventListener('input', updateConvertBtn);
|
||||||
|
|
||||||
|
openOutBtn.addEventListener('click', () => {
|
||||||
|
if (outputDir) vscode.postMessage({ type: 'openOutput', dir: outputDir });
|
||||||
|
});
|
||||||
|
|
||||||
|
function outputDisplayName(file) {
|
||||||
|
const parts = file.split(/[\\\\/]/).filter(Boolean);
|
||||||
|
return parts.slice(-2).join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('convert').addEventListener('click', () => {
|
||||||
|
const networks = [...document.querySelectorAll('.net-cb')]
|
||||||
|
.filter(c => c.checked).map(c => c.dataset.tag);
|
||||||
|
statusEl.textContent = 'Converting...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
openOutBtn.style.display = 'none';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
convertBtn.disabled = true;
|
||||||
|
vscode.postMessage({
|
||||||
|
type: 'convert',
|
||||||
|
opts: {
|
||||||
|
sourcePath: srcEl.value,
|
||||||
|
outputDir: outEl.value,
|
||||||
|
baseName: baseNameEl.value,
|
||||||
|
networks,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('message', (event) => {
|
||||||
|
const msg = event.data;
|
||||||
|
if (msg.type === 'sourcePicked') {
|
||||||
|
srcEl.value = msg.path;
|
||||||
|
srcNameEl.textContent = msg.path.split(/[\\\\/]/).filter(Boolean).pop() || msg.path;
|
||||||
|
baseNameEl.value = msg.baseName || '';
|
||||||
|
if (!outEl.value && msg.dir) {
|
||||||
|
outEl.value = defaultOutputDir(msg.dir);
|
||||||
|
outputDir = outEl.value;
|
||||||
|
}
|
||||||
|
updateConvertBtn();
|
||||||
|
} else if (msg.type === 'outputPicked') {
|
||||||
|
outEl.value = msg.path;
|
||||||
|
outputDir = msg.path;
|
||||||
|
updateConvertBtn();
|
||||||
|
} else if (msg.type === 'status') {
|
||||||
|
statusEl.textContent = msg.message;
|
||||||
|
statusEl.className = 'status-panel is-busy';
|
||||||
|
} else if (msg.type === 'convertDone') {
|
||||||
|
convertBtn.disabled = false;
|
||||||
|
updateConvertBtn();
|
||||||
|
if (msg.error) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Error: ' + msg.error;
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const results = msg.results || [];
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
const ok = results.filter(r => r.ok).length;
|
||||||
|
statusEl.textContent = ok + ' of ' + results.length + ' network(s) converted.';
|
||||||
|
if (!results.length) {
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
outputPanel.classList.remove('is-hidden');
|
||||||
|
resultsEl.innerHTML =
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th style="width:120px;">Network</th><th style="width:90px;">Status</th><th style="width:90px;">Output</th><th>Path</th><th>Error</th></tr></thead>' +
|
||||||
|
'<tbody></tbody>' +
|
||||||
|
'</table>';
|
||||||
|
const tbody = resultsEl.querySelector('tbody');
|
||||||
|
for (const r of results) {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
const net = document.createElement('td');
|
||||||
|
net.textContent = r.network;
|
||||||
|
const status = document.createElement('td');
|
||||||
|
status.innerHTML = r.ok ? '<span class="badge ok">Done</span>' : '<span class="badge err">Failed</span>';
|
||||||
|
const outputType = document.createElement('td');
|
||||||
|
const detail = document.createElement('td');
|
||||||
|
detail.className = 'mono wrap';
|
||||||
|
const error = document.createElement('td');
|
||||||
|
error.className = 'err wrap';
|
||||||
|
if (r.ok) {
|
||||||
|
outputType.textContent = /\\.zip$/i.test(r.file) ? 'ZIP' : 'HTML';
|
||||||
|
detail.textContent = outputDisplayName(r.file);
|
||||||
|
} else {
|
||||||
|
outputType.textContent = '-';
|
||||||
|
detail.innerHTML = '<span class="muted">-</span>';
|
||||||
|
error.textContent = r.error || 'Unknown error';
|
||||||
|
}
|
||||||
|
if (r.ok) error.innerHTML = '<span class="muted">-</span>';
|
||||||
|
row.append(net, status, outputType, detail, error);
|
||||||
|
tbody.appendChild(row);
|
||||||
|
}
|
||||||
|
if (ok > 0) {
|
||||||
|
outputDir = outEl.value;
|
||||||
|
openOutBtn.style.display = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import * as vscode from 'vscode';
|
|||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import { File } from 'node:buffer';
|
import { File } from 'node:buffer';
|
||||||
import { handleClipboardAndOpen, singletonPanel } from './shared';
|
import { getToolWebviewStyles, handleClipboardAndOpen, singletonPanel } from './shared';
|
||||||
|
|
||||||
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
||||||
|
|
||||||
@@ -15,20 +15,36 @@ export function openPlecUpload(_context: vscode.ExtensionContext) {
|
|||||||
try {
|
try {
|
||||||
if (handleClipboardAndOpen(msg)) return;
|
if (handleClipboardAndOpen(msg)) return;
|
||||||
|
|
||||||
|
if (msg.type === 'pickFolder') {
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFolders: true,
|
||||||
|
canSelectFiles: false,
|
||||||
|
canSelectMany: false,
|
||||||
|
openLabel: 'Select Folder',
|
||||||
|
defaultUri: getPickerDefaultUri(),
|
||||||
|
});
|
||||||
|
if (picked && picked[0]) {
|
||||||
|
const files = await collectHtmlFiles(picked[0].fsPath);
|
||||||
|
panel.webview.postMessage({
|
||||||
|
type: 'filesSelected',
|
||||||
|
files: files.map(filePath => ({ path: filePath, name: path.basename(filePath) })),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (msg.type === 'pickFile') {
|
if (msg.type === 'pickFile') {
|
||||||
const picked = await vscode.window.showOpenDialog({
|
const picked = await vscode.window.showOpenDialog({
|
||||||
canSelectMany: false,
|
canSelectMany: true,
|
||||||
filters: { HTML: ['html', 'htm'] },
|
filters: { HTML: ['html', 'htm'] },
|
||||||
openLabel: 'Select',
|
openLabel: 'Select',
|
||||||
defaultUri: getPickerDefaultUri(),
|
defaultUri: getPickerDefaultUri(),
|
||||||
});
|
});
|
||||||
if (picked && picked[0]) {
|
if (picked && picked.length) {
|
||||||
const fp = picked[0].fsPath;
|
|
||||||
panel.webview.postMessage({
|
panel.webview.postMessage({
|
||||||
type: 'fileSelected',
|
type: 'filesSelected',
|
||||||
rowId: msg.rowId,
|
rowId: msg.rowId,
|
||||||
path: fp,
|
files: picked.map(u => ({ path: u.fsPath, name: path.basename(u.fsPath) })),
|
||||||
name: path.basename(fp),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -85,11 +101,13 @@ async function handleUpload(panel: vscode.WebviewPanel, rows: UploadRow[]) {
|
|||||||
for (let i = 0; i < valid.length; i++) {
|
for (let i = 0; i < valid.length; i++) {
|
||||||
const r = valid[i];
|
const r = valid[i];
|
||||||
const idx = i + 1;
|
const idx = i + 1;
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Preparing ${idx}/${valid.length} ${path.basename(r.path)}` });
|
||||||
const buf = fs.readFileSync(r.path);
|
const buf = fs.readFileSync(r.path);
|
||||||
const file = new File([buf], stampedNames[i], { type: 'text/html' });
|
const file = new File([buf], stampedNames[i], { type: 'text/html' });
|
||||||
form.append(`fileUpload_${idx}`, file as any);
|
form.append(`fileUpload_${idx}`, file as any);
|
||||||
form.append(`iterationNameUpload_${idx}`, encodeURI(r.iteration.replace(/\s+/g, '')));
|
form.append(`iterationNameUpload_${idx}`, encodeURI(r.iteration.replace(/\s+/g, '')));
|
||||||
}
|
}
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Uploading ${valid.length} file${valid.length === 1 ? '' : 's'}...` });
|
||||||
|
|
||||||
let res: Response;
|
let res: Response;
|
||||||
try {
|
try {
|
||||||
@@ -161,189 +179,271 @@ function getPickerDefaultUri(): vscode.Uri | undefined {
|
|||||||
return vscode.Uri.file(root);
|
return vscode.Uri.file(root);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function collectHtmlFiles(root: string): Promise<string[]> {
|
||||||
|
const out: string[] = [];
|
||||||
|
const stack: string[] = [root];
|
||||||
|
while (stack.length) {
|
||||||
|
const dir = stack.pop()!;
|
||||||
|
let entries: fs.Dirent[];
|
||||||
|
try {
|
||||||
|
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const e of entries) {
|
||||||
|
const full = path.join(dir, e.name);
|
||||||
|
if (e.isDirectory()) {
|
||||||
|
if (e.name === 'node_modules' || e.name === '.git') continue;
|
||||||
|
stack.push(full);
|
||||||
|
} else if (e.isFile() && /\.html?$/i.test(e.name)) {
|
||||||
|
out.push(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
function getHtml(): string {
|
function getHtml(): string {
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<style>
|
<style>
|
||||||
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 16px; }
|
${getToolWebviewStyles()}
|
||||||
h2 { margin-top: 0; }
|
#rows input[type=text] { width: 100%; }
|
||||||
table { width: 100%; border-collapse: collapse; margin-bottom: 12px; }
|
.file-cell { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||||
th, td { padding: 6px 8px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--vscode-panel-border); }
|
|
||||||
th { font-weight: 600; font-size: 12px; text-transform: uppercase; opacity: 0.7; }
|
|
||||||
input[type=text] {
|
|
||||||
width: 100%; padding: 4px 6px;
|
|
||||||
background: var(--vscode-input-background); color: var(--vscode-input-foreground);
|
|
||||||
border: 1px solid var(--vscode-input-border, transparent);
|
|
||||||
border-radius: 2px;
|
|
||||||
}
|
|
||||||
button {
|
|
||||||
background: var(--vscode-button-background); color: var(--vscode-button-foreground);
|
|
||||||
border: none; padding: 6px 12px; border-radius: 2px; cursor: pointer;
|
|
||||||
}
|
|
||||||
button:hover { background: var(--vscode-button-hoverBackground); }
|
|
||||||
button.secondary {
|
|
||||||
background: var(--vscode-button-secondaryBackground);
|
|
||||||
color: var(--vscode-button-secondaryForeground);
|
|
||||||
}
|
|
||||||
button.secondary:hover { background: var(--vscode-button-secondaryHoverBackground); }
|
|
||||||
.file-cell { display: flex; align-items: center; gap: 8px; }
|
|
||||||
.file-name { opacity: 0.85; font-size: 12px; word-break: break-all; }
|
|
||||||
.row-error { color: var(--vscode-errorForeground); font-size: 12px; margin-top: 4px; }
|
.row-error { color: var(--vscode-errorForeground); font-size: 12px; margin-top: 4px; }
|
||||||
.actions { margin-top: 12px; display: flex; gap: 8px; }
|
.pick { min-width: 82px; }
|
||||||
#status { margin-top: 12px; min-height: 20px; }
|
.remove-btn {
|
||||||
.err { color: var(--vscode-errorForeground); white-space: pre-wrap; }
|
min-width: 28px;
|
||||||
.ok { color: var(--vscode-testing-iconPassed, var(--vscode-foreground)); }
|
width: 28px;
|
||||||
.result {
|
padding: 3px 0;
|
||||||
margin-top: 12px; padding: 10px;
|
color: var(--vscode-errorForeground);
|
||||||
background: var(--vscode-textBlockQuote-background);
|
font-size: 16px;
|
||||||
border-left: 3px solid var(--vscode-textBlockQuote-border);
|
line-height: 1;
|
||||||
word-break: break-all;
|
|
||||||
}
|
}
|
||||||
.result a { color: var(--vscode-textLink-foreground); }
|
.result a { color: var(--vscode-textLink-foreground); }
|
||||||
.result-actions { margin-top: 8px; display: flex; gap: 8px; }
|
.result-actions { margin-top: 8px; display: flex; gap: 8px; }
|
||||||
.remove-btn { background: transparent; color: var(--vscode-foreground); padding: 4px 8px; }
|
.pager { margin-top: 8px; display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h2>PLEC Upload</h2>
|
<main class="tool-page">
|
||||||
<p style="opacity:0.8;font-size:12px;margin-top:0;">Pick HTML files, give each an iteration name, then upload. The preview link is returned by the server.</p>
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">PLEC Upload</h2>
|
||||||
|
<p class="tool-description">Pick HTML files, give each an iteration name, then upload them to PLEC.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
<table id="rows">
|
<section class="tool-panel input-panel">
|
||||||
<thead>
|
<div class="panel-header">
|
||||||
<tr>
|
<h3 class="panel-title">Inputs</h3>
|
||||||
<th style="width:45%">HTML File</th>
|
</div>
|
||||||
<th style="width:45%">Iteration Name</th>
|
<div class="panel-body">
|
||||||
<th></th>
|
<div class="control-group">
|
||||||
</tr>
|
<div class="file-row">
|
||||||
</thead>
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
<tbody></tbody>
|
<button id="pickFiles" class="secondary">Select File(s)</button>
|
||||||
</table>
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
<div class="actions">
|
<div id="emptySelection" class="file-name" style="margin-top:8px;">(no files selected)</div>
|
||||||
<button id="addRow" class="secondary">+ Add Row</button>
|
<div id="rowsPanel" class="results-panel is-hidden" style="margin-top:8px;">
|
||||||
<button id="upload">Upload</button>
|
<table id="rows" class="data-table">
|
||||||
</div>
|
<thead><tr><th>Filename</th><th style="width:240px;">Iteration Name</th><th style="width:44px;"></th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
<div id="status"></div>
|
</table>
|
||||||
<div id="results"></div>
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="upload">Upload</button>
|
||||||
|
<button id="openResult" class="secondary" disabled>Open</button>
|
||||||
|
<button id="copyResult" class="secondary" disabled>Copy Link</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const vscode = acquireVsCodeApi();
|
const vscode = acquireVsCodeApi();
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
let nextId = 1;
|
let nextId = 1;
|
||||||
|
let rows = [];
|
||||||
|
let page = 0;
|
||||||
|
let previewUrl = '';
|
||||||
const tbody = document.querySelector('#rows tbody');
|
const tbody = document.querySelector('#rows tbody');
|
||||||
const statusEl = document.getElementById('status');
|
const rowsPanel = document.getElementById('rowsPanel');
|
||||||
const resultsEl = document.getElementById('results');
|
const emptySelection = document.getElementById('emptySelection');
|
||||||
|
|
||||||
function addRow() {
|
function parseIterationName(filename) {
|
||||||
const id = 'r' + (nextId++);
|
const base = filename.replace(/\\.html?$/i, '');
|
||||||
const tr = document.createElement('tr');
|
const tokens = base.split('_');
|
||||||
tr.dataset.id = id;
|
for (const t of tokens) {
|
||||||
tr.innerHTML = \`
|
if (/^(full|\\d+clk|\\d+s(?:ec)?)$/i.test(t)) return t.toLowerCase();
|
||||||
<td>
|
}
|
||||||
<div class="file-cell">
|
return base;
|
||||||
<button class="pick secondary">Choose...</button>
|
}
|
||||||
<span class="file-name" data-name>(no file)</span>
|
const statusEl = document.getElementById('status');
|
||||||
</div>
|
const openResultBtn = document.getElementById('openResult');
|
||||||
<input type="hidden" data-path />
|
const copyResultBtn = document.getElementById('copyResult');
|
||||||
<div class="row-error" data-error></div>
|
|
||||||
</td>
|
function escapeHtml(s) {
|
||||||
<td><input type="text" data-iter placeholder="iteration name" /></td>
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
<td><button class="remove-btn" title="Remove">×</button></td>
|
|
||||||
\`;
|
|
||||||
tr.querySelector('.pick').addEventListener('click', () => {
|
|
||||||
vscode.postMessage({ type: 'pickFile', rowId: id });
|
|
||||||
});
|
|
||||||
tr.querySelector('.remove-btn').addEventListener('click', () => {
|
|
||||||
tr.remove();
|
|
||||||
if (!tbody.children.length) addRow();
|
|
||||||
});
|
|
||||||
tbody.appendChild(tr);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('addRow').addEventListener('click', addRow);
|
function addFiles(files) {
|
||||||
|
const existing = new Set(rows.map(r => r.path));
|
||||||
|
files.forEach(f => {
|
||||||
|
if (existing.has(f.path)) return;
|
||||||
|
rows.push({
|
||||||
|
id: 'r' + (nextId++),
|
||||||
|
path: f.path,
|
||||||
|
name: f.name,
|
||||||
|
iteration: parseIterationName(f.name),
|
||||||
|
error: ''
|
||||||
|
});
|
||||||
|
existing.add(f.path);
|
||||||
|
});
|
||||||
|
normalizeDuplicateIterations(files.length);
|
||||||
|
page = Math.max(0, Math.ceil(rows.length / PAGE_SIZE) - 1);
|
||||||
|
renderRows();
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeDuplicateIterations(addedCount) {
|
||||||
|
if (addedCount <= 1) return;
|
||||||
|
const added = rows.slice(Math.max(0, rows.length - addedCount));
|
||||||
|
if (!added.length) return;
|
||||||
|
const first = added[0].iteration;
|
||||||
|
if (first && added.every(r => r.iteration === first)) {
|
||||||
|
added.forEach((r, i) => {
|
||||||
|
r.iteration = String(i + 1).padStart(2, '0') + '_' + first;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderRows() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
const maxPage = Math.max(0, Math.ceil(rows.length / PAGE_SIZE) - 1);
|
||||||
|
page = Math.min(page, maxPage);
|
||||||
|
rowsPanel.classList.toggle('is-hidden', rows.length === 0);
|
||||||
|
emptySelection.classList.toggle('is-hidden', rows.length !== 0);
|
||||||
|
if (!rows.length) {
|
||||||
|
tbody.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const start = page * PAGE_SIZE;
|
||||||
|
const pageRows = rows.slice(start, start + PAGE_SIZE);
|
||||||
|
tbody.innerHTML = pageRows.map((row, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return \`
|
||||||
|
<tr data-id="\${row.id}">
|
||||||
|
<td>
|
||||||
|
<span class="mono wrap">\${escapeHtml(row.name)}</span>
|
||||||
|
<div class="row-error" data-error>\${escapeHtml(row.error || '')}</div>
|
||||||
|
</td>
|
||||||
|
<td><input type="text" data-iter data-index="\${i}" value="\${escapeHtml(row.iteration)}" /></td>
|
||||||
|
<td><button class="remove-btn danger" data-remove="\${i}" title="Remove">×</button></td>
|
||||||
|
</tr>
|
||||||
|
\`;
|
||||||
|
}).join('');
|
||||||
|
tbody.querySelectorAll('[data-iter]').forEach(input => {
|
||||||
|
input.addEventListener('input', () => {
|
||||||
|
rows[Number(input.dataset.index)].iteration = input.value;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
tbody.querySelectorAll('[data-remove]').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
rows.splice(Number(btn.dataset.remove), 1);
|
||||||
|
renderRows();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (rows.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML =
|
||||||
|
'<button class="secondary" id="prevPage"' + (page === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (page + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (page === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
document.querySelector('#rows').parentElement.after(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { page--; renderRows(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { page++; renderRows(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPreview(url) {
|
||||||
|
previewUrl = url || '';
|
||||||
|
openResultBtn.disabled = !previewUrl;
|
||||||
|
copyResultBtn.disabled = !previewUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('pickFolder').addEventListener('click', () => {
|
||||||
|
vscode.postMessage({ type: 'pickFolder' });
|
||||||
|
});
|
||||||
|
document.getElementById('pickFiles').addEventListener('click', () => {
|
||||||
|
vscode.postMessage({ type: 'pickFile' });
|
||||||
|
});
|
||||||
|
document.getElementById('clear').addEventListener('click', () => {
|
||||||
|
rows = [];
|
||||||
|
page = 0;
|
||||||
|
setPreview('');
|
||||||
|
renderRows();
|
||||||
|
statusEl.textContent = '';
|
||||||
|
});
|
||||||
|
|
||||||
document.getElementById('upload').addEventListener('click', () => {
|
document.getElementById('upload').addEventListener('click', () => {
|
||||||
clearErrors();
|
clearErrors();
|
||||||
statusEl.textContent = '';
|
statusEl.textContent = '';
|
||||||
resultsEl.innerHTML = '';
|
statusEl.classList.remove('is-busy');
|
||||||
const rows = [...tbody.querySelectorAll('tr')].map(tr => ({
|
setPreview('');
|
||||||
id: tr.dataset.id,
|
|
||||||
path: tr.querySelector('[data-path]').value,
|
|
||||||
iteration: tr.querySelector('[data-iter]').value,
|
|
||||||
})).filter(r => r.path || r.iteration);
|
|
||||||
if (rows.length === 0) {
|
if (rows.length === 0) {
|
||||||
statusEl.innerHTML = '<span class="err">Add at least one row with a file and iteration name.</span>';
|
statusEl.innerHTML = '<span class="err">Select at least one file.</span>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
statusEl.textContent = 'Uploading...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
vscode.postMessage({ type: 'upload', rows });
|
vscode.postMessage({ type: 'upload', rows });
|
||||||
});
|
});
|
||||||
|
openResultBtn.addEventListener('click', () => {
|
||||||
|
if (previewUrl) vscode.postMessage({ type: 'open', text: previewUrl });
|
||||||
|
});
|
||||||
|
copyResultBtn.addEventListener('click', () => {
|
||||||
|
if (previewUrl) vscode.postMessage({ type: 'copy', text: previewUrl });
|
||||||
|
});
|
||||||
|
|
||||||
function clearErrors() {
|
function clearErrors() {
|
||||||
document.querySelectorAll('[data-error]').forEach(el => el.textContent = '');
|
rows.forEach(row => row.error = '');
|
||||||
|
renderRows();
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('message', (e) => {
|
window.addEventListener('message', (e) => {
|
||||||
const m = e.data;
|
const m = e.data;
|
||||||
if (m.type === 'fileSelected') {
|
if (m.type === 'filesSelected') {
|
||||||
const tr = tbody.querySelector('tr[data-id="' + m.rowId + '"]');
|
addFiles(m.files || []);
|
||||||
if (!tr) return;
|
|
||||||
tr.querySelector('[data-path]').value = m.path;
|
|
||||||
tr.querySelector('[data-name]').textContent = m.name;
|
|
||||||
const iter = tr.querySelector('[data-iter]');
|
|
||||||
if (!iter.value) iter.value = m.name.replace(/\\.html?$/i, '');
|
|
||||||
} else if (m.type === 'status') {
|
} else if (m.type === 'status') {
|
||||||
statusEl.textContent = m.message;
|
statusEl.textContent = m.message;
|
||||||
statusEl.className = '';
|
statusEl.className = 'status-panel is-busy';
|
||||||
} else if (m.type === 'error') {
|
} else if (m.type === 'error') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
statusEl.innerHTML = '';
|
statusEl.innerHTML = '';
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div');
|
||||||
div.className = 'err';
|
div.className = 'err';
|
||||||
div.textContent = m.message;
|
div.textContent = m.message;
|
||||||
statusEl.appendChild(div);
|
statusEl.appendChild(div);
|
||||||
} else if (m.type === 'rowError') {
|
} else if (m.type === 'rowError') {
|
||||||
const tr = tbody.querySelector('tr[data-id="' + m.rowId + '"]');
|
statusEl.classList.remove('is-busy');
|
||||||
if (tr) tr.querySelector('[data-error]').textContent = m.message;
|
const row = rows.find(r => r.id === m.rowId);
|
||||||
|
if (row) row.error = m.message;
|
||||||
|
renderRows();
|
||||||
statusEl.innerHTML = '<span class="err">Fix row errors and retry.</span>';
|
statusEl.innerHTML = '<span class="err">Fix row errors and retry.</span>';
|
||||||
} else if (m.type === 'result') {
|
} else if (m.type === 'result') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
statusEl.innerHTML = '<span class="ok">Upload complete.</span>';
|
statusEl.innerHTML = '<span class="ok">Upload complete.</span>';
|
||||||
const wrap = document.createElement('div');
|
setPreview(m.preview);
|
||||||
wrap.className = 'result';
|
|
||||||
if (m.preview) {
|
|
||||||
wrap.innerHTML = '<div><strong>Preview:</strong> <a href="' + m.preview + '">' + m.preview + '</a></div>';
|
|
||||||
const actions = document.createElement('div');
|
|
||||||
actions.className = 'result-actions';
|
|
||||||
const copy = document.createElement('button');
|
|
||||||
copy.textContent = 'Copy';
|
|
||||||
copy.onclick = () => vscode.postMessage({ type: 'copy', text: m.preview });
|
|
||||||
const open = document.createElement('button');
|
|
||||||
open.textContent = 'Open';
|
|
||||||
open.className = 'secondary';
|
|
||||||
open.onclick = () => vscode.postMessage({ type: 'open', text: m.preview });
|
|
||||||
const showRaw = document.createElement('button');
|
|
||||||
showRaw.textContent = 'Show server response';
|
|
||||||
showRaw.className = 'secondary';
|
|
||||||
showRaw.onclick = () => {
|
|
||||||
const pre = document.createElement('pre');
|
|
||||||
pre.style.marginTop = '8px';
|
|
||||||
pre.style.whiteSpace = 'pre-wrap';
|
|
||||||
pre.textContent = m.rawText || JSON.stringify(m.raw, null, 2);
|
|
||||||
wrap.appendChild(pre);
|
|
||||||
showRaw.disabled = true;
|
|
||||||
};
|
|
||||||
actions.appendChild(copy); actions.appendChild(open); actions.appendChild(showRaw);
|
|
||||||
wrap.appendChild(actions);
|
|
||||||
} else {
|
|
||||||
wrap.innerHTML = '<div>No preview field in response. Raw JSON:</div><pre>' +
|
|
||||||
(m.rawText || JSON.stringify(m.raw, null, 2)).replace(/</g, '<') + '</pre>';
|
|
||||||
}
|
|
||||||
resultsEl.innerHTML = '';
|
|
||||||
resultsEl.appendChild(wrap);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
addRow();
|
renderRows();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>`;
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import * as path from 'path';
|
|||||||
import * as http from 'http';
|
import * as http from 'http';
|
||||||
import * as os from 'os';
|
import * as os from 'os';
|
||||||
import * as crypto from 'crypto';
|
import * as crypto from 'crypto';
|
||||||
import { handleClipboardAndOpen } from './shared';
|
import { getToolWebviewStyles, handleClipboardAndOpen } from './shared';
|
||||||
|
|
||||||
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
const store: { panel: vscode.WebviewPanel | null } = { panel: null };
|
||||||
|
|
||||||
@@ -12,7 +12,11 @@ interface ActiveShare {
|
|||||||
server: http.Server;
|
server: http.Server;
|
||||||
port: number;
|
port: number;
|
||||||
token: string;
|
token: string;
|
||||||
fileBuf: Buffer;
|
files: SharedFile[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SharedFile {
|
||||||
|
buf: Buffer;
|
||||||
filename: string;
|
filename: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,19 +61,35 @@ export function openSendToMobile(context: vscode.ExtensionContext) {
|
|||||||
try {
|
try {
|
||||||
if (handleClipboardAndOpen(msg)) return;
|
if (handleClipboardAndOpen(msg)) return;
|
||||||
|
|
||||||
|
if (msg.type === 'pickFolder') {
|
||||||
|
const picked = await vscode.window.showOpenDialog({
|
||||||
|
canSelectFolders: true,
|
||||||
|
canSelectFiles: false,
|
||||||
|
canSelectMany: false,
|
||||||
|
openLabel: 'Select Folder',
|
||||||
|
defaultUri: getPickerDefaultUri(),
|
||||||
|
});
|
||||||
|
if (picked && picked[0]) {
|
||||||
|
const files = await collectHtmlFiles(picked[0].fsPath);
|
||||||
|
panel.webview.postMessage({
|
||||||
|
type: 'fileSelected',
|
||||||
|
files: files.map(filePath => ({ path: filePath, name: path.basename(filePath) })),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (msg.type === 'pickFile') {
|
if (msg.type === 'pickFile') {
|
||||||
const picked = await vscode.window.showOpenDialog({
|
const picked = await vscode.window.showOpenDialog({
|
||||||
canSelectMany: false,
|
canSelectMany: true,
|
||||||
filters: { HTML: ['html', 'htm'] },
|
filters: { HTML: ['html', 'htm'] },
|
||||||
openLabel: 'Select',
|
openLabel: 'Select',
|
||||||
defaultUri: getPickerDefaultUri(),
|
defaultUri: getPickerDefaultUri(),
|
||||||
});
|
});
|
||||||
if (picked && picked[0]) {
|
if (picked && picked.length) {
|
||||||
const fp = picked[0].fsPath;
|
|
||||||
panel.webview.postMessage({
|
panel.webview.postMessage({
|
||||||
type: 'fileSelected',
|
type: 'fileSelected',
|
||||||
path: fp,
|
files: picked.map(u => ({ path: u.fsPath, name: path.basename(u.fsPath) })),
|
||||||
name: path.basename(fp),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -77,13 +97,22 @@ export function openSendToMobile(context: vscode.ExtensionContext) {
|
|||||||
|
|
||||||
if (msg.type === 'startShare') {
|
if (msg.type === 'startShare') {
|
||||||
stopActive();
|
stopActive();
|
||||||
const filePath: string = msg.path;
|
const filePaths: string[] = Array.isArray(msg.paths) ? msg.paths : (msg.path ? [msg.path] : []);
|
||||||
if (!filePath || !fs.existsSync(filePath)) {
|
if (!filePaths.length) {
|
||||||
panel.webview.postMessage({ type: 'error', message: 'File missing.' });
|
panel.webview.postMessage({ type: 'error', message: 'File missing.' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const fileBuf = fs.readFileSync(filePath);
|
const files: SharedFile[] = [];
|
||||||
const filename = path.basename(filePath);
|
for (let i = 0; i < filePaths.length; i++) {
|
||||||
|
const filePath = filePaths[i];
|
||||||
|
if (!filePath || !fs.existsSync(filePath)) {
|
||||||
|
panel.webview.postMessage({ type: 'error', message: 'File missing.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
panel.webview.postMessage({ type: 'status', message: `Loading ${i + 1}/${filePaths.length} ${path.basename(filePath)}` });
|
||||||
|
files.push({ buf: fs.readFileSync(filePath), filename: path.basename(filePath) });
|
||||||
|
}
|
||||||
|
panel.webview.postMessage({ type: 'status', message: 'Starting server...' });
|
||||||
const token = crypto.randomBytes(6).toString('base64url');
|
const token = crypto.randomBytes(6).toString('base64url');
|
||||||
|
|
||||||
const cfg = vscode.workspace.getConfiguration('hplToolbox.sendToMobile');
|
const cfg = vscode.workspace.getConfiguration('hplToolbox.sendToMobile');
|
||||||
@@ -93,8 +122,7 @@ export function openSendToMobile(context: vscode.ExtensionContext) {
|
|||||||
server: http.createServer(),
|
server: http.createServer(),
|
||||||
port: 0,
|
port: 0,
|
||||||
token,
|
token,
|
||||||
fileBuf,
|
files,
|
||||||
filename,
|
|
||||||
};
|
};
|
||||||
share.server.on('request', (req, res) => handleRequest(req, res, share));
|
share.server.on('request', (req, res) => handleRequest(req, res, share));
|
||||||
share.server.on('error', (err) => {
|
share.server.on('error', (err) => {
|
||||||
@@ -125,7 +153,11 @@ export function openSendToMobile(context: vscode.ExtensionContext) {
|
|||||||
iface: ip.iface,
|
iface: ip.iface,
|
||||||
url: `http://${ip.address}:${share.port}/s/${token}/`,
|
url: `http://${ip.address}:${share.port}/s/${token}/`,
|
||||||
}));
|
}));
|
||||||
panel.webview.postMessage({ type: 'sharing', urls, filename });
|
panel.webview.postMessage({
|
||||||
|
type: 'sharing',
|
||||||
|
urls,
|
||||||
|
filename: files.length === 1 ? files[0].filename : `${files.length} files`,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -141,6 +173,30 @@ export function openSendToMobile(context: vscode.ExtensionContext) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function collectHtmlFiles(root: string): Promise<string[]> {
|
||||||
|
const out: string[] = [];
|
||||||
|
const stack: string[] = [root];
|
||||||
|
while (stack.length) {
|
||||||
|
const dir = stack.pop()!;
|
||||||
|
let entries: fs.Dirent[];
|
||||||
|
try {
|
||||||
|
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const e of entries) {
|
||||||
|
const full = path.join(dir, e.name);
|
||||||
|
if (e.isDirectory()) {
|
||||||
|
if (e.name === 'node_modules' || e.name === '.git') continue;
|
||||||
|
stack.push(full);
|
||||||
|
} else if (e.isFile() && /\.html?$/i.test(e.name)) {
|
||||||
|
out.push(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
function handleRequest(req: http.IncomingMessage, res: http.ServerResponse, share: ActiveShare) {
|
function handleRequest(req: http.IncomingMessage, res: http.ServerResponse, share: ActiveShare) {
|
||||||
if (req.method !== 'GET' || !req.url) {
|
if (req.method !== 'GET' || !req.url) {
|
||||||
res.statusCode = 404;
|
res.statusCode = 404;
|
||||||
@@ -156,7 +212,7 @@ function handleRequest(req: http.IncomingMessage, res: http.ServerResponse, shar
|
|||||||
const rest = req.url.slice(prefix.length).replace(/\?.*$/, '');
|
const rest = req.url.slice(prefix.length).replace(/\?.*$/, '');
|
||||||
|
|
||||||
if (rest === '' || rest === '/') {
|
if (rest === '' || rest === '/') {
|
||||||
const body = chooserPage(share.filename);
|
const body = chooserPage(share.files);
|
||||||
res.writeHead(200, {
|
res.writeHead(200, {
|
||||||
'Content-Type': 'text/html; charset=utf-8',
|
'Content-Type': 'text/html; charset=utf-8',
|
||||||
'Cache-Control': 'no-store',
|
'Cache-Control': 'no-store',
|
||||||
@@ -165,24 +221,40 @@ function handleRequest(req: http.IncomingMessage, res: http.ServerResponse, shar
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rest === '/view') {
|
const viewMatch = rest.match(/^\/view\/(\d+)$/);
|
||||||
|
if (rest === '/view' || viewMatch) {
|
||||||
|
const index = viewMatch ? Number(viewMatch[1]) : 0;
|
||||||
|
const file = share.files[index];
|
||||||
|
if (!file) {
|
||||||
|
res.statusCode = 404;
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
res.writeHead(200, {
|
res.writeHead(200, {
|
||||||
'Content-Type': 'text/html; charset=utf-8',
|
'Content-Type': 'text/html; charset=utf-8',
|
||||||
'Cache-Control': 'no-store',
|
'Cache-Control': 'no-store',
|
||||||
});
|
});
|
||||||
res.end(share.fileBuf);
|
res.end(mobilePreviewPage(file));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rest === '/file') {
|
const fileMatch = rest.match(/^\/file\/(\d+)$/);
|
||||||
const safeName = share.filename.replace(/[^A-Za-z0-9._-]/g, '_');
|
if (rest === '/file' || fileMatch) {
|
||||||
|
const index = fileMatch ? Number(fileMatch[1]) : 0;
|
||||||
|
const file = share.files[index];
|
||||||
|
if (!file) {
|
||||||
|
res.statusCode = 404;
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const safeName = file.filename.replace(/[^A-Za-z0-9._-]/g, '_');
|
||||||
res.writeHead(200, {
|
res.writeHead(200, {
|
||||||
'Content-Type': 'application/octet-stream',
|
'Content-Type': 'application/octet-stream',
|
||||||
'Content-Disposition': `attachment; filename="${safeName}"`,
|
'Content-Disposition': `attachment; filename="${safeName}"`,
|
||||||
'Content-Length': String(share.fileBuf.length),
|
'Content-Length': String(file.buf.length),
|
||||||
'Cache-Control': 'no-store',
|
'Cache-Control': 'no-store',
|
||||||
});
|
});
|
||||||
res.end(share.fileBuf);
|
res.end(file.buf);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,10 +262,18 @@ function handleRequest(req: http.IncomingMessage, res: http.ServerResponse, shar
|
|||||||
res.end();
|
res.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
function chooserPage(filename: string): string {
|
function chooserPage(files: SharedFile[]): string {
|
||||||
const escName = filename.replace(/[&<>"]/g, (c) =>
|
const esc = (value: string) => value.replace(/[&<>"]/g, (c) =>
|
||||||
({ '&': '&', '<': '<', '>': '>', '"': '"' }[c] as string)
|
({ '&': '&', '<': '<', '>': '>', '"': '"' }[c] as string)
|
||||||
);
|
);
|
||||||
|
const items = files.map((file, index) => {
|
||||||
|
const escName = esc(file.filename);
|
||||||
|
return `<div class="item">
|
||||||
|
<div class="file">${escName}</div>
|
||||||
|
<a class="btn view" href="view/${index}">View in browser</a>
|
||||||
|
<a class="btn dl" href="file/${index}" download="${escName}">Download .html</a>
|
||||||
|
</div>`;
|
||||||
|
}).join('');
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html><head>
|
<html><head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
@@ -203,7 +283,8 @@ function chooserPage(filename: string): string {
|
|||||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
margin: 0; padding: 24px; background: #111; color: #eee; }
|
margin: 0; padding: 24px; background: #111; color: #eee; }
|
||||||
h1 { font-size: 18px; font-weight: 500; margin: 0 0 4px; opacity: 0.85; }
|
h1 { font-size: 18px; font-weight: 500; margin: 0 0 4px; opacity: 0.85; }
|
||||||
.file { font-size: 13px; opacity: 0.6; margin-bottom: 28px; word-break: break-all; }
|
.item { margin-bottom: 26px; }
|
||||||
|
.file { font-size: 13px; opacity: 0.6; margin-bottom: 10px; word-break: break-all; }
|
||||||
a.btn { display: block; padding: 18px; margin-bottom: 14px; border-radius: 10px;
|
a.btn { display: block; padding: 18px; margin-bottom: 14px; border-radius: 10px;
|
||||||
font-size: 17px; font-weight: 500; text-align: center; text-decoration: none; }
|
font-size: 17px; font-weight: 500; text-align: center; text-decoration: none; }
|
||||||
a.view { background: #2d7dff; color: white; }
|
a.view { background: #2d7dff; color: white; }
|
||||||
@@ -211,9 +292,36 @@ function chooserPage(filename: string): string {
|
|||||||
</style></head>
|
</style></head>
|
||||||
<body>
|
<body>
|
||||||
<h1>HPL Toolbox</h1>
|
<h1>HPL Toolbox</h1>
|
||||||
<div class="file">${escName}</div>
|
${items}
|
||||||
<a class="btn view" href="view">View in browser</a>
|
</body></html>`;
|
||||||
<a class="btn dl" href="file" download="${escName}">Download .html</a>
|
}
|
||||||
|
|
||||||
|
function mobilePreviewPage(file: SharedFile): string {
|
||||||
|
const playableJson = JSON.stringify(file.buf.toString('utf8')).replace(/<\/script/gi, '<\\/script');
|
||||||
|
const title = file.filename.replace(/[&<>"]/g, (c) =>
|
||||||
|
({ '&': '&', '<': '<', '>': '>', '"': '"' }[c] as string)
|
||||||
|
);
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html><head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<title>${title}</title>
|
||||||
|
<style>
|
||||||
|
html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: #000; }
|
||||||
|
iframe { position: fixed; inset: 0; width: 100%; height: 100%; border: 0; background: #000; }
|
||||||
|
.boot { position: fixed; inset: 0; display: grid; place-items: center; color: #777; font: 12px system-ui, sans-serif; }
|
||||||
|
</style>
|
||||||
|
</head><body>
|
||||||
|
<div id="boot" class="boot">Loading preview...</div>
|
||||||
|
<iframe id="playable" sandbox="allow-scripts allow-same-origin allow-pointer-lock allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"></iframe>
|
||||||
|
<script>
|
||||||
|
const playableHtml = ${playableJson};
|
||||||
|
setTimeout(() => {
|
||||||
|
const frame = document.getElementById('playable');
|
||||||
|
document.getElementById('boot').style.display = 'none';
|
||||||
|
frame.srcdoc = playableHtml;
|
||||||
|
}, 750);
|
||||||
|
</script>
|
||||||
</body></html>`;
|
</body></html>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,26 +358,8 @@ function getHtml(qrScriptUri: string): string {
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<style>
|
<style>
|
||||||
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 16px; }
|
${getToolWebviewStyles()}
|
||||||
h2 { margin-top: 0; }
|
#qr { margin-top: 14px; background: white; padding: 12px; display: inline-block; border-radius: var(--tool-radius); }
|
||||||
.row { margin-bottom: 14px; }
|
|
||||||
.file-cell { display: flex; align-items: center; gap: 8px; }
|
|
||||||
.file-name { opacity: 0.85; font-size: 12px; word-break: break-all; }
|
|
||||||
button {
|
|
||||||
background: var(--vscode-button-background); color: var(--vscode-button-foreground);
|
|
||||||
border: none; padding: 6px 12px; border-radius: 2px; cursor: pointer;
|
|
||||||
}
|
|
||||||
button:hover { background: var(--vscode-button-hoverBackground); }
|
|
||||||
button.secondary {
|
|
||||||
background: var(--vscode-button-secondaryBackground);
|
|
||||||
color: var(--vscode-button-secondaryForeground);
|
|
||||||
}
|
|
||||||
button.secondary:hover { background: var(--vscode-button-secondaryHoverBackground); }
|
|
||||||
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
||||||
.iface-list { display: flex; flex-direction: column; gap: 4px; margin-top: 6px; }
|
|
||||||
.iface-list label { font-size: 12px; cursor: pointer; }
|
|
||||||
.iface-list .meta { opacity: 0.6; margin-left: 6px; }
|
|
||||||
#qr { margin-top: 14px; background: white; padding: 12px; display: inline-block; border-radius: 4px; }
|
|
||||||
#qr svg, #qr img { display: block; }
|
#qr svg, #qr img { display: block; }
|
||||||
.url {
|
.url {
|
||||||
margin-top: 10px; padding: 8px;
|
margin-top: 10px; padding: 8px;
|
||||||
@@ -277,99 +367,170 @@ function getHtml(qrScriptUri: string): string {
|
|||||||
border-left: 3px solid var(--vscode-textBlockQuote-border);
|
border-left: 3px solid var(--vscode-textBlockQuote-border);
|
||||||
font-family: var(--vscode-editor-font-family, monospace); font-size: 12px; word-break: break-all;
|
font-family: var(--vscode-editor-font-family, monospace); font-size: 12px; word-break: break-all;
|
||||||
}
|
}
|
||||||
.url-actions { margin-top: 6px; display: flex; gap: 6px; }
|
.url-actions { margin-top: 6px; display: flex; gap: 6px; flex-wrap: wrap; }
|
||||||
#status { margin-top: 12px; min-height: 18px; }
|
.share-panel { padding: 12px; }
|
||||||
.err { color: var(--vscode-errorForeground); white-space: pre-wrap; }
|
.iface-radio { text-align: center; }
|
||||||
.ok { color: var(--vscode-testing-iconPassed, var(--vscode-foreground)); }
|
#qr { margin-top: 0; }
|
||||||
.hint { font-size: 12px; opacity: 0.7; margin-top: 8px; }
|
.selected-list { margin-top: 10px; }
|
||||||
|
.pager { margin-top: 8px; display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
|
||||||
</style>
|
</style>
|
||||||
<script src="${qrScriptUri}"></script>
|
<script src="${qrScriptUri}"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h2>Send To Mobile</h2>
|
<main class="tool-page">
|
||||||
<p style="opacity:0.8;font-size:12px;margin-top:0;">
|
<header class="tool-header">
|
||||||
Pick an HTML file, then start sharing. Scan the QR with a phone on the same WiFi.
|
<h2 class="tool-title">Send To Mobile</h2>
|
||||||
The phone gets a choice of <strong>View</strong> or <strong>Download</strong>.
|
<p class="tool-description">Pick an HTML file, then start sharing. Scan the QR with a phone on the same WiFi. The phone gets View and Download options.</p>
|
||||||
</p>
|
</header>
|
||||||
|
|
||||||
<div class="row">
|
<section class="tool-panel input-panel">
|
||||||
<div class="file-cell">
|
<div class="panel-header">
|
||||||
<button id="pick" class="secondary">Choose...</button>
|
<h3 class="panel-title">Inputs</h3>
|
||||||
<span class="file-name" id="fileName">(no file)</span>
|
|
||||||
</div>
|
</div>
|
||||||
<input type="hidden" id="filePath" />
|
<div class="panel-body">
|
||||||
</div>
|
<div class="control-group">
|
||||||
|
<div class="file-row">
|
||||||
<div class="row">
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
<button id="start">Start sharing</button>
|
<button id="pick" class="secondary">Select File(s)</button>
|
||||||
<button id="stop" class="secondary" disabled>Stop</button>
|
<button id="clear" class="secondary">Clear</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="file-name" id="fileName" style="margin-top:8px;">(no files selected)</div>
|
||||||
<div id="ifaceWrap" class="row" style="display:none;">
|
<div id="fileList" class="selected-list"></div>
|
||||||
<div style="font-size:12px;opacity:0.8;">Multiple network interfaces found. Pick the one your phone can reach:</div>
|
</div>
|
||||||
<div class="iface-list" id="ifaceList"></div>
|
<div class="action-row">
|
||||||
</div>
|
<button id="start">Start</button>
|
||||||
|
<button id="stop" class="secondary" disabled>Stop</button>
|
||||||
<div id="shareInfo" style="display:none;">
|
</div>
|
||||||
<div id="qr"></div>
|
<div id="status" class="status-panel"></div>
|
||||||
<div class="url" id="urlText"></div>
|
|
||||||
<div class="url-actions">
|
|
||||||
<button id="copyUrl" class="secondary">Copy URL</button>
|
|
||||||
<button id="openUrl" class="secondary">Open in browser</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="hint">
|
</section>
|
||||||
First run on Windows may show a firewall prompt — allow access for "Private networks".
|
|
||||||
Sharing stops automatically when this panel is closed.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="status"></div>
|
<div id="outputPanel" class="is-hidden">
|
||||||
|
<div id="ifaceWrap" class="control-group" style="display:none;">
|
||||||
|
<div class="control-label">Network Interfaces</div>
|
||||||
|
<p class="section-description">Pick the interface your phone can reach.</p>
|
||||||
|
<div class="iface-list" id="ifaceList"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="shareInfo" class="result-card share-panel" style="display:none;">
|
||||||
|
<div id="qr"></div>
|
||||||
|
<div class="muted" style="margin-top:8px;font-size:12px;">
|
||||||
|
First run on Windows may show a firewall prompt - allow access for "Private networks".
|
||||||
|
Sharing stops automatically when this panel is closed.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const vscode = acquireVsCodeApi();
|
const vscode = acquireVsCodeApi();
|
||||||
|
const pickFolderBtn = document.getElementById('pickFolder');
|
||||||
const pickBtn = document.getElementById('pick');
|
const pickBtn = document.getElementById('pick');
|
||||||
|
const clearBtn = document.getElementById('clear');
|
||||||
const startBtn = document.getElementById('start');
|
const startBtn = document.getElementById('start');
|
||||||
const stopBtn = document.getElementById('stop');
|
const stopBtn = document.getElementById('stop');
|
||||||
const fileNameEl = document.getElementById('fileName');
|
const fileNameEl = document.getElementById('fileName');
|
||||||
const filePathEl = document.getElementById('filePath');
|
const fileListEl = document.getElementById('fileList');
|
||||||
const statusEl = document.getElementById('status');
|
const statusEl = document.getElementById('status');
|
||||||
|
const outputPanel = document.getElementById('outputPanel');
|
||||||
const shareInfo = document.getElementById('shareInfo');
|
const shareInfo = document.getElementById('shareInfo');
|
||||||
const ifaceWrap = document.getElementById('ifaceWrap');
|
const ifaceWrap = document.getElementById('ifaceWrap');
|
||||||
const ifaceList = document.getElementById('ifaceList');
|
const ifaceList = document.getElementById('ifaceList');
|
||||||
const qrEl = document.getElementById('qr');
|
const qrEl = document.getElementById('qr');
|
||||||
const urlTextEl = document.getElementById('urlText');
|
|
||||||
|
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
let currentUrls = [];
|
let currentUrls = [];
|
||||||
let selectedIdx = 0;
|
let selectedIdx = 0;
|
||||||
|
let selectedPaths = [];
|
||||||
|
let selectedFiles = [];
|
||||||
|
let selectedPage = 0;
|
||||||
|
|
||||||
|
pickFolderBtn.addEventListener('click', () => vscode.postMessage({ type: 'pickFolder' }));
|
||||||
pickBtn.addEventListener('click', () => vscode.postMessage({ type: 'pickFile' }));
|
pickBtn.addEventListener('click', () => vscode.postMessage({ type: 'pickFile' }));
|
||||||
|
clearBtn.addEventListener('click', () => {
|
||||||
|
selectedPaths = [];
|
||||||
|
selectedFiles = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
});
|
||||||
|
|
||||||
startBtn.addEventListener('click', () => {
|
startBtn.addEventListener('click', () => {
|
||||||
statusEl.innerHTML = '';
|
statusEl.innerHTML = '';
|
||||||
const path = filePathEl.value;
|
outputPanel.classList.add('is-hidden');
|
||||||
if (!path) {
|
if (!selectedPaths.length) {
|
||||||
statusEl.innerHTML = '<span class="err">Pick an HTML file first.</span>';
|
statusEl.innerHTML = '<span class="err">Pick at least one HTML file first.</span>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
startBtn.disabled = true;
|
startBtn.disabled = true;
|
||||||
statusEl.textContent = 'Starting server...';
|
statusEl.textContent = 'Starting server...';
|
||||||
vscode.postMessage({ type: 'startShare', path });
|
statusEl.classList.add('is-busy');
|
||||||
|
vscode.postMessage({ type: 'startShare', paths: selectedPaths });
|
||||||
});
|
});
|
||||||
|
|
||||||
stopBtn.addEventListener('click', () => {
|
stopBtn.addEventListener('click', () => {
|
||||||
vscode.postMessage({ type: 'stopShare' });
|
vscode.postMessage({ type: 'stopShare' });
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('copyUrl').addEventListener('click', () => {
|
function escapeHtml(s) {
|
||||||
vscode.postMessage({ type: 'copy', text: currentUrls[selectedIdx]?.url || '' });
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
});
|
}
|
||||||
document.getElementById('openUrl').addEventListener('click', () => {
|
|
||||||
vscode.postMessage({ type: 'open', text: currentUrls[selectedIdx]?.url || '' });
|
function renderSelection() {
|
||||||
});
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
if (!selectedFiles.length) {
|
||||||
|
fileNameEl.textContent = '(no files selected)';
|
||||||
|
fileListEl.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fileNameEl.textContent = selectedFiles.length + ' file' + (selectedFiles.length === 1 ? '' : 's');
|
||||||
|
const maxPage = Math.max(0, Math.ceil(selectedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const start = selectedPage * PAGE_SIZE;
|
||||||
|
const visibleFiles = selectedFiles.slice(start, start + PAGE_SIZE);
|
||||||
|
fileListEl.innerHTML =
|
||||||
|
'<div class="results-panel" style="margin-top:0;">' +
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead>' +
|
||||||
|
'<tbody>' +
|
||||||
|
visibleFiles.map((file, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return (
|
||||||
|
'<tr><td class="mono wrap">' + escapeHtml(file.name) + '</td>' +
|
||||||
|
'<td><button class="remove-selected danger" data-index="' + i + '" title="Remove">×</button></td></tr>'
|
||||||
|
);
|
||||||
|
}).join('') +
|
||||||
|
'</tbody>' +
|
||||||
|
'</table>' +
|
||||||
|
'</div>';
|
||||||
|
fileListEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
const index = Number(btn.dataset.index);
|
||||||
|
selectedFiles.splice(index, 1);
|
||||||
|
selectedPaths.splice(index, 1);
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (selectedFiles.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML =
|
||||||
|
'<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
fileListEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderSelection();
|
||||||
|
|
||||||
function renderQr(url) {
|
function renderQr(url) {
|
||||||
qrEl.innerHTML = '';
|
qrEl.innerHTML = '';
|
||||||
urlTextEl.textContent = url;
|
|
||||||
try {
|
try {
|
||||||
const qr = qrcode(0, 'M');
|
const qr = qrcode(0, 'M');
|
||||||
qr.addData(url);
|
qr.addData(url);
|
||||||
@@ -389,41 +550,62 @@ function getHtml(qrScriptUri: string): string {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ifaceWrap.style.display = '';
|
ifaceWrap.style.display = '';
|
||||||
|
ifaceList.innerHTML =
|
||||||
|
'<div class="results-panel" style="margin-top:0;">' +
|
||||||
|
'<table class="data-table">' +
|
||||||
|
'<thead><tr><th style="width:70px;">Use</th><th style="width:140px;">IP</th><th>Interface</th></tr></thead>' +
|
||||||
|
'<tbody></tbody>' +
|
||||||
|
'</table>' +
|
||||||
|
'</div>';
|
||||||
|
const tbody = ifaceList.querySelector('tbody');
|
||||||
urls.forEach((u, i) => {
|
urls.forEach((u, i) => {
|
||||||
const id = 'iface_' + i;
|
const id = 'iface_' + i;
|
||||||
const label = document.createElement('label');
|
const row = document.createElement('tr');
|
||||||
label.innerHTML = '<input type="radio" name="iface" id="' + id + '"' +
|
row.innerHTML =
|
||||||
(i === selectedIdx ? ' checked' : '') + ' /> ' +
|
'<td class="iface-radio"><input type="radio" name="iface" id="' + id + '"' + (i === selectedIdx ? ' checked' : '') + ' /></td>' +
|
||||||
u.ip + '<span class="meta">(' + u.iface + ')</span>';
|
'<td class="mono wrap">' + u.ip + '</td>' +
|
||||||
label.querySelector('input').addEventListener('change', () => {
|
'<td class="wrap">' + u.iface + '</td>';
|
||||||
|
row.querySelector('input').addEventListener('change', () => {
|
||||||
selectedIdx = i;
|
selectedIdx = i;
|
||||||
renderQr(urls[i].url);
|
renderQr(urls[i].url);
|
||||||
});
|
});
|
||||||
ifaceList.appendChild(label);
|
tbody.appendChild(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('message', (e) => {
|
window.addEventListener('message', (e) => {
|
||||||
const m = e.data;
|
const m = e.data;
|
||||||
if (m.type === 'fileSelected') {
|
if (m.type === 'fileSelected') {
|
||||||
filePathEl.value = m.path;
|
const existing = new Set(selectedFiles.map(f => f.path));
|
||||||
fileNameEl.textContent = m.name;
|
selectedFiles = selectedFiles.concat((m.files || []).filter(f => !existing.has(f.path)));
|
||||||
|
selectedPaths = selectedFiles.map(f => f.path);
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
|
} else if (m.type === 'status') {
|
||||||
|
statusEl.textContent = m.message;
|
||||||
|
statusEl.className = 'status-panel is-busy';
|
||||||
} else if (m.type === 'sharing') {
|
} else if (m.type === 'sharing') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
currentUrls = m.urls;
|
currentUrls = m.urls;
|
||||||
selectedIdx = 0;
|
selectedIdx = 0;
|
||||||
statusEl.innerHTML = '<span class="ok">Sharing: ' + m.filename + '</span>';
|
statusEl.innerHTML = '<span class="ok">Sharing: ' + m.filename + '</span>';
|
||||||
|
outputPanel.classList.remove('is-hidden');
|
||||||
shareInfo.style.display = '';
|
shareInfo.style.display = '';
|
||||||
renderIfaces(m.urls);
|
renderIfaces(m.urls);
|
||||||
renderQr(m.urls[0].url);
|
renderQr(m.urls[0].url);
|
||||||
startBtn.disabled = true;
|
startBtn.disabled = true;
|
||||||
stopBtn.disabled = false;
|
stopBtn.disabled = false;
|
||||||
} else if (m.type === 'stopped') {
|
} else if (m.type === 'stopped') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
statusEl.textContent = 'Stopped.';
|
statusEl.textContent = 'Stopped.';
|
||||||
shareInfo.style.display = 'none';
|
shareInfo.style.display = 'none';
|
||||||
|
ifaceWrap.style.display = 'none';
|
||||||
|
outputPanel.classList.add('is-hidden');
|
||||||
currentUrls = [];
|
currentUrls = [];
|
||||||
startBtn.disabled = false;
|
startBtn.disabled = false;
|
||||||
stopBtn.disabled = true;
|
stopBtn.disabled = true;
|
||||||
} else if (m.type === 'error') {
|
} else if (m.type === 'error') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
statusEl.innerHTML = '<span class="err">' + (m.message || 'Error').replace(/</g, '<') + '</span>';
|
statusEl.innerHTML = '<span class="err">' + (m.message || 'Error').replace(/</g, '<') + '</span>';
|
||||||
startBtn.disabled = false;
|
startBtn.disabled = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,306 @@ export function handleClipboardAndOpen(msg: any): boolean {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getToolWebviewStyles(): string {
|
||||||
|
return `
|
||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--tool-gap-xs: 4px;
|
||||||
|
--tool-gap-sm: 8px;
|
||||||
|
--tool-gap-md: 12px;
|
||||||
|
--tool-gap-lg: 16px;
|
||||||
|
--tool-radius: 4px;
|
||||||
|
--tool-border: var(--vscode-panel-border, rgba(128, 128, 128, 0.35));
|
||||||
|
--tool-panel: var(--vscode-editorWidget-background, var(--vscode-sideBar-background));
|
||||||
|
--tool-panel-soft: var(--vscode-textBlockQuote-background, rgba(128, 128, 128, 0.08));
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
background: var(--vscode-editor-background);
|
||||||
|
color: var(--vscode-foreground);
|
||||||
|
font-family: var(--vscode-font-family);
|
||||||
|
font-size: var(--vscode-font-size);
|
||||||
|
}
|
||||||
|
.tool-page {
|
||||||
|
max-width: 1100px;
|
||||||
|
padding: 18px;
|
||||||
|
}
|
||||||
|
.tool-header {
|
||||||
|
margin-bottom: var(--tool-gap-lg);
|
||||||
|
}
|
||||||
|
.tool-title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 18px;
|
||||||
|
line-height: 1.25;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.tool-description,
|
||||||
|
.section-description,
|
||||||
|
.muted {
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
}
|
||||||
|
.tool-description {
|
||||||
|
margin: 5px 0 0;
|
||||||
|
max-width: 780px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
.tool-section {
|
||||||
|
margin-bottom: var(--tool-gap-lg);
|
||||||
|
}
|
||||||
|
.tool-panel {
|
||||||
|
margin-bottom: var(--tool-gap-lg);
|
||||||
|
border: 1px solid var(--tool-border);
|
||||||
|
border-radius: var(--tool-radius);
|
||||||
|
background: var(--tool-panel-soft);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.is-hidden,
|
||||||
|
.tool-panel.is-hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.panel-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--tool-gap-md);
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-bottom: 1px solid var(--tool-border);
|
||||||
|
background: var(--tool-panel);
|
||||||
|
}
|
||||||
|
.panel-title {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--vscode-foreground);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.45px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
.panel-body {
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
.control-group + .control-group {
|
||||||
|
margin-top: var(--tool-gap-md);
|
||||||
|
}
|
||||||
|
.control-label {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.4px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
.section-title {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
.section-description {
|
||||||
|
margin: -2px 0 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
.field-row,
|
||||||
|
.file-row,
|
||||||
|
.action-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--tool-gap-sm);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.field-row + .field-row {
|
||||||
|
margin-top: var(--tool-gap-sm);
|
||||||
|
}
|
||||||
|
input[type=text],
|
||||||
|
input[type=date],
|
||||||
|
select,
|
||||||
|
textarea {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 6px 8px;
|
||||||
|
background: var(--vscode-input-background);
|
||||||
|
color: var(--vscode-input-foreground);
|
||||||
|
border: 1px solid var(--vscode-input-border, var(--tool-border));
|
||||||
|
border-radius: var(--tool-radius);
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
input[type=text]:focus,
|
||||||
|
input[type=date]:focus,
|
||||||
|
select:focus,
|
||||||
|
textarea:focus {
|
||||||
|
outline: 1px solid var(--vscode-focusBorder);
|
||||||
|
border-color: var(--vscode-focusBorder);
|
||||||
|
}
|
||||||
|
.field-row input[type=text] {
|
||||||
|
flex: 1 1 260px;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
min-height: 28px;
|
||||||
|
padding: 5px 12px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: var(--tool-radius);
|
||||||
|
background: var(--vscode-button-background);
|
||||||
|
color: var(--vscode-button-foreground);
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
button:hover {
|
||||||
|
background: var(--vscode-button-hoverBackground);
|
||||||
|
}
|
||||||
|
button.secondary {
|
||||||
|
background: var(--vscode-button-secondaryBackground);
|
||||||
|
color: var(--vscode-button-secondaryForeground);
|
||||||
|
border-color: var(--tool-border);
|
||||||
|
}
|
||||||
|
button.secondary:hover {
|
||||||
|
background: var(--vscode-button-secondaryHoverBackground);
|
||||||
|
}
|
||||||
|
button.danger {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--vscode-errorForeground);
|
||||||
|
border-color: var(--tool-border);
|
||||||
|
}
|
||||||
|
button.danger:hover {
|
||||||
|
background: var(--vscode-inputValidation-errorBackground, rgba(248, 81, 73, 0.16));
|
||||||
|
}
|
||||||
|
.remove-selected {
|
||||||
|
min-width: 28px;
|
||||||
|
width: 28px;
|
||||||
|
padding: 3px 0;
|
||||||
|
color: var(--vscode-errorForeground);
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
.action-row {
|
||||||
|
margin-top: var(--tool-gap-md);
|
||||||
|
}
|
||||||
|
.status-panel,
|
||||||
|
.results-panel,
|
||||||
|
.result-card {
|
||||||
|
border: 1px solid var(--tool-border);
|
||||||
|
border-radius: var(--tool-radius);
|
||||||
|
background: var(--tool-panel-soft);
|
||||||
|
}
|
||||||
|
.status-panel {
|
||||||
|
min-height: 30px;
|
||||||
|
margin-top: var(--tool-gap-md);
|
||||||
|
padding: 8px 10px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.status-panel.is-busy {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.status-panel.is-busy::before {
|
||||||
|
content: "";
|
||||||
|
width: 12px;
|
||||||
|
height: 12px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
border: 2px solid color-mix(in srgb, var(--vscode-descriptionForeground) 45%, transparent);
|
||||||
|
border-top-color: var(--vscode-foreground);
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: status-spin 800ms linear infinite;
|
||||||
|
}
|
||||||
|
@keyframes status-spin {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
.status-panel:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.results-panel {
|
||||||
|
margin-top: var(--tool-gap-md);
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.results-panel:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.output-panel .results-panel {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
.result-card {
|
||||||
|
padding: 10px;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.data-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
table-layout: fixed;
|
||||||
|
}
|
||||||
|
.data-table th,
|
||||||
|
.data-table td {
|
||||||
|
padding: 8px 10px;
|
||||||
|
text-align: left;
|
||||||
|
vertical-align: top;
|
||||||
|
border-bottom: 1px solid var(--tool-border);
|
||||||
|
}
|
||||||
|
.data-table th {
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.4px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
background: var(--tool-panel);
|
||||||
|
}
|
||||||
|
.data-table tr:last-child td {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
.mono {
|
||||||
|
font-family: var(--vscode-editor-font-family, monospace);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.wrap {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.file-name {
|
||||||
|
color: var(--vscode-descriptionForeground);
|
||||||
|
font-size: 12px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.ok {
|
||||||
|
color: var(--vscode-testing-iconPassed, #3fb950);
|
||||||
|
}
|
||||||
|
.err {
|
||||||
|
color: var(--vscode-errorForeground, #f85149);
|
||||||
|
}
|
||||||
|
.warn {
|
||||||
|
color: var(--vscode-editorWarning-foreground, #d29922);
|
||||||
|
}
|
||||||
|
.badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 18px;
|
||||||
|
padding: 1px 6px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--tool-border);
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 1.2;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.badge.ok {
|
||||||
|
border-color: color-mix(in srgb, var(--vscode-testing-iconPassed, #3fb950) 45%, transparent);
|
||||||
|
background: rgba(63, 185, 80, 0.12);
|
||||||
|
}
|
||||||
|
.badge.err {
|
||||||
|
border-color: color-mix(in srgb, var(--vscode-errorForeground, #f85149) 45%, transparent);
|
||||||
|
background: var(--vscode-inputValidation-errorBackground, rgba(248, 81, 73, 0.12));
|
||||||
|
}
|
||||||
|
.badge.warn {
|
||||||
|
border-color: color-mix(in srgb, var(--vscode-editorWarning-foreground, #d29922) 45%, transparent);
|
||||||
|
background: var(--vscode-inputValidation-warningBackground, rgba(210, 153, 34, 0.12));
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
export function singletonPanel(
|
export function singletonPanel(
|
||||||
store: { panel: vscode.WebviewPanel | null },
|
store: { panel: vscode.WebviewPanel | null },
|
||||||
viewType: string,
|
viewType: string,
|
||||||
|
|||||||
80
src/updateChecker.ts
Normal file
80
src/updateChecker.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import * as vscode from 'vscode';
|
||||||
|
|
||||||
|
const REMOTE_PACKAGE_JSON_URL = 'https://gitea.hesukastro.com/hesukastro/vsix-hpl-toolbox/raw/branch/main/package.json';
|
||||||
|
|
||||||
|
interface RemotePackageJson {
|
||||||
|
version?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkForUpdates(context: vscode.ExtensionContext): Promise<void> {
|
||||||
|
const currentVersion = String(context.extension.packageJSON.version ?? '').trim();
|
||||||
|
|
||||||
|
if (!currentVersion) {
|
||||||
|
vscode.window.showWarningMessage('HPL Toolbox could not read the installed version.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const remoteVersion = await fetchRemoteVersion();
|
||||||
|
const comparison = compareVersions(remoteVersion, currentVersion);
|
||||||
|
|
||||||
|
if (comparison > 0) {
|
||||||
|
const action = await vscode.window.showInformationMessage(
|
||||||
|
`HPL Toolbox update available: ${remoteVersion} (installed: ${currentVersion}).`,
|
||||||
|
'Open Repository'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (action === 'Open Repository') {
|
||||||
|
await vscode.env.openExternal(vscode.Uri.parse('https://gitea.hesukastro.com/hesukastro/vsix-hpl-toolbox'));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
vscode.window.showInformationMessage(`HPL Toolbox is up to date (${currentVersion}).`);
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
vscode.window.showWarningMessage(`HPL Toolbox update check failed: ${message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchRemoteVersion(): Promise<string> {
|
||||||
|
const response = await fetch(REMOTE_PACKAGE_JSON_URL, {
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`remote package.json returned HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const packageJson = await response.json() as RemotePackageJson;
|
||||||
|
if (typeof packageJson.version !== 'string' || !packageJson.version.trim()) {
|
||||||
|
throw new Error('remote package.json is missing a version');
|
||||||
|
}
|
||||||
|
|
||||||
|
return packageJson.version.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareVersions(left: string, right: string): number {
|
||||||
|
const leftParts = parseVersion(left);
|
||||||
|
const rightParts = parseVersion(right);
|
||||||
|
const length = Math.max(leftParts.length, rightParts.length);
|
||||||
|
|
||||||
|
for (let index = 0; index < length; index += 1) {
|
||||||
|
const leftPart = leftParts[index] ?? 0;
|
||||||
|
const rightPart = rightParts[index] ?? 0;
|
||||||
|
|
||||||
|
if (leftPart > rightPart) return 1;
|
||||||
|
if (leftPart < rightPart) return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseVersion(version: string): number[] {
|
||||||
|
return version
|
||||||
|
.split(/[.-]/)
|
||||||
|
.map(part => Number.parseInt(part, 10))
|
||||||
|
.filter(part => Number.isFinite(part));
|
||||||
|
}
|
||||||
4
standalone/.gitignore
vendored
Normal file
4
standalone/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
hpl-toolbox.exe
|
||||||
|
config.json
|
||||||
|
.hpltoolbox.lock
|
||||||
|
debug.log
|
||||||
631
standalone/applovin.go
Normal file
631
standalone/applovin.go
Normal file
@@ -0,0 +1,631 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
urlpkg "net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var applovinUserAgents = []string{
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0",
|
||||||
|
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||||
|
}
|
||||||
|
|
||||||
|
func pickApplovinUserAgent(randomize bool) string {
|
||||||
|
if !randomize {
|
||||||
|
return applovinUserAgents[0]
|
||||||
|
}
|
||||||
|
return applovinUserAgents[rand.Intn(len(applovinUserAgents))]
|
||||||
|
}
|
||||||
|
|
||||||
|
func ApplovinPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">AppLovin Playable Preview</h2>
|
||||||
|
<p class="tool-description">Upload HTML files to p.applov.in and get QR codes to scan with the AppLovin Playable Preview app.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="tool-panel">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Inputs</h3></div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div id="dropZone" class="drop-zone">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
|
<button id="pick" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div class="drop-zone-text">or drop HTML files or folders here</div>
|
||||||
|
</div>
|
||||||
|
<div id="fileName" class="file-name" style="margin-top:8px;">(no files selected)</div>
|
||||||
|
<div id="fileList" class="selected-files"></div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="upload">Upload</button>
|
||||||
|
<button id="saveAll" class="secondary" disabled>Save All</button>
|
||||||
|
<button id="regenAll" class="secondary" disabled>Regenerate</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.qr-cell { text-align:center; }
|
||||||
|
.qr-cell img { width:104px; height:104px; max-width:100%; padding:6px; border-radius:4px; background:#fff; cursor:zoom-in; }
|
||||||
|
.result-actions { display:flex; gap:6px; flex-wrap:wrap; }
|
||||||
|
.qr-results:not(.has-errors) .error-col { display:none; }
|
||||||
|
.qr-modal { position:fixed; inset:0; display:none; align-items:center; justify-content:center; padding:24px; background:rgba(0,0,0,0.72); z-index:10; }
|
||||||
|
.qr-modal.open { display:flex; }
|
||||||
|
.qr-modal img { width:min(70vw,520px); height:min(70vw,520px); padding:18px; border-radius:4px; background:#fff; }
|
||||||
|
</style>
|
||||||
|
<div id="qrModal" class="qr-modal"><img alt="Expanded QR" /></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
let selectedPage = 0;
|
||||||
|
const pickBtn = document.getElementById('pick');
|
||||||
|
const pickFolderBtn = document.getElementById('pickFolder');
|
||||||
|
const clearBtn = document.getElementById('clear');
|
||||||
|
const uploadBtn = document.getElementById('upload');
|
||||||
|
const fileNameEl = document.getElementById('fileName');
|
||||||
|
const fileListEl = document.getElementById('fileList');
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const resultsEl = document.getElementById('results');
|
||||||
|
const saveAllBtn = document.getElementById('saveAll');
|
||||||
|
const regenAllBtn = document.getElementById('regenAll');
|
||||||
|
const qrModal = document.getElementById('qrModal');
|
||||||
|
let selectedPaths = [];
|
||||||
|
let resultItems = [];
|
||||||
|
|
||||||
|
function basename(p) {
|
||||||
|
const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
|
||||||
|
return i >= 0 ? p.slice(i + 1) : p;
|
||||||
|
}
|
||||||
|
function renderSelection() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
if (!selectedPaths.length) {
|
||||||
|
fileNameEl.textContent = '(no files selected)';
|
||||||
|
fileListEl.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fileNameEl.textContent = selectedPaths.length + ' file' + (selectedPaths.length === 1 ? '' : 's');
|
||||||
|
const maxPage = Math.max(0, Math.ceil(selectedPaths.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const start = selectedPage * PAGE_SIZE;
|
||||||
|
const visiblePaths = selectedPaths.slice(start, start + PAGE_SIZE);
|
||||||
|
fileListEl.innerHTML = '<div class="results-panel" style="margin-top:0;"><table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead><tbody>' +
|
||||||
|
visiblePaths.map((p, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return '<tr><td class="mono wrap">' + escapeHtml(basename(p)) + '</td><td><button class="remove-selected danger" data-index="' + i + '" title="Remove">×</button></td></tr>';
|
||||||
|
}).join('') + '</tbody></table></div>';
|
||||||
|
fileListEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => { selectedPaths.splice(Number(btn.dataset.index), 1); renderSelection(); });
|
||||||
|
});
|
||||||
|
if (selectedPaths.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML = '<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
fileListEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
saveAllBtn.addEventListener('click', async () => {
|
||||||
|
if (!resultItems.length) return;
|
||||||
|
saveAllBtn.disabled = true;
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/applovin/saveAllQrs', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({ items: resultItems }),
|
||||||
|
});
|
||||||
|
const j = await r.json();
|
||||||
|
statusEl.innerHTML = j.ok
|
||||||
|
? '<span class="ok">' + escapeHtml(j.message || 'Saved.') + '</span>'
|
||||||
|
: '<span class="err">' + escapeHtml(j.message || 'Save failed.') + '</span>';
|
||||||
|
} finally {
|
||||||
|
saveAllBtn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
regenAllBtn.addEventListener('click', () => {
|
||||||
|
resultsEl.querySelectorAll('img[data-qr]').forEach(img => {
|
||||||
|
const base = img.getAttribute('data-qr');
|
||||||
|
img.src = base + '&_=' + Date.now();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
setupDropZone('dropZone', statusEl, (j) => {
|
||||||
|
if (j.files && j.files.length) {
|
||||||
|
const added = j.files.map(f => f.path).filter(p => !selectedPaths.includes(p));
|
||||||
|
selectedPaths = selectedPaths.concat(added);
|
||||||
|
selectedPage = Math.max(0, Math.ceil(selectedPaths.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
}
|
||||||
|
if (j.skipped) statusEl.textContent = 'Skipped ' + j.skipped + ' non-HTML or unavailable item(s).';
|
||||||
|
});
|
||||||
|
|
||||||
|
clearBtn.addEventListener('click', () => {
|
||||||
|
selectedPaths = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
|
||||||
|
pickFolderBtn.addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/applovin/pickFolder', { method: 'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
if (j.files && j.files.length) {
|
||||||
|
const added = j.files.map(f => f.path).filter(p => !selectedPaths.includes(p));
|
||||||
|
selectedPaths = selectedPaths.concat(added);
|
||||||
|
selectedPage = Math.max(0, Math.ceil(selectedPaths.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
pickBtn.addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/applovin/pick', { method: 'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
if (j.files && j.files.length) {
|
||||||
|
const added = j.files.map(f => f.path).filter(p => !selectedPaths.includes(p));
|
||||||
|
selectedPaths = selectedPaths.concat(added);
|
||||||
|
selectedPage = Math.max(0, Math.ceil(selectedPaths.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
uploadBtn.addEventListener('click', async () => {
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
if (!selectedPaths.length) {
|
||||||
|
statusEl.innerHTML = '<span class="err">Pick at least one HTML file first.</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uploadBtn.disabled = true;
|
||||||
|
statusEl.textContent = 'Uploading...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
resultItems = [];
|
||||||
|
saveAllBtn.disabled = true;
|
||||||
|
regenAllBtn.disabled = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/applovin/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ paths: selectedPaths }),
|
||||||
|
});
|
||||||
|
if (!res.ok || !res.body) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="err">Upload failed.</span>';
|
||||||
|
uploadBtn.disabled = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const dec = new TextDecoder();
|
||||||
|
let buf = '';
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buf += dec.decode(value, { stream: true });
|
||||||
|
let nl;
|
||||||
|
while ((nl = buf.indexOf('\n')) >= 0) {
|
||||||
|
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
handle(JSON.parse(line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="err">' + (e.message || e) + '</span>';
|
||||||
|
} finally {
|
||||||
|
uploadBtn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function escapeHtml(s){
|
||||||
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureResultsTable() {
|
||||||
|
let tbody = resultsEl.querySelector('tbody');
|
||||||
|
if (tbody) return tbody;
|
||||||
|
resultsEl.innerHTML = '<table class="data-table qr-results"><thead><tr><th>File</th><th style="width:140px;">QR</th><th style="width:170px;">Actions</th><th class="error-col">Error</th></tr></thead><tbody></tbody></table>';
|
||||||
|
return resultsEl.querySelector('tbody');
|
||||||
|
}
|
||||||
|
qrModal.addEventListener('click', () => qrModal.classList.remove('open'));
|
||||||
|
|
||||||
|
function handle(m) {
|
||||||
|
if (m.type === 'status') {
|
||||||
|
statusEl.textContent = m.message;
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
} else if (m.type === 'fileError') {
|
||||||
|
const tbody = ensureResultsTable();
|
||||||
|
resultsEl.querySelector('table').classList.add('has-errors');
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
row.innerHTML = '<td class="mono wrap">' + escapeHtml(m.name) + '</td><td class="muted">-</td><td class="muted">-</td><td class="err wrap error-col">' + escapeHtml(m.message) + '</td>';
|
||||||
|
tbody.appendChild(row);
|
||||||
|
} else if (m.type === 'fileResult') {
|
||||||
|
const tbody = ensureResultsTable();
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
const file = document.createElement('td');
|
||||||
|
file.className = 'mono wrap';
|
||||||
|
file.textContent = m.name;
|
||||||
|
const qr = document.createElement('td');
|
||||||
|
qr.className = 'qr-cell';
|
||||||
|
qr.innerHTML = '<img src="' + m.qrImg + '" data-qr="' + m.qrImg + '" alt="QR" />';
|
||||||
|
qr.querySelector('img').addEventListener('click', (event) => {
|
||||||
|
qrModal.querySelector('img').src = event.currentTarget.src;
|
||||||
|
qrModal.classList.add('open');
|
||||||
|
});
|
||||||
|
const actionCell = document.createElement('td');
|
||||||
|
const error = document.createElement('td');
|
||||||
|
error.className = 'error-col';
|
||||||
|
error.innerHTML = '<span class="muted">-</span>';
|
||||||
|
const actions = document.createElement('div');
|
||||||
|
actions.className = 'result-actions';
|
||||||
|
const openBtn = document.createElement('button');
|
||||||
|
openBtn.textContent = 'Open';
|
||||||
|
openBtn.className = 'secondary';
|
||||||
|
openBtn.onclick = () => fetch('/api/open', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:m.previewUrl})});
|
||||||
|
const saveQr = document.createElement('button');
|
||||||
|
saveQr.textContent = 'Save QR';
|
||||||
|
saveQr.className = 'secondary';
|
||||||
|
saveQr.onclick = async () => {
|
||||||
|
saveQr.disabled = true;
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/applovin/saveQr', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({ name: m.name, url: m.qrImg }),
|
||||||
|
});
|
||||||
|
const j = await r.json();
|
||||||
|
statusEl.innerHTML = j.ok
|
||||||
|
? '<span class="ok">' + escapeHtml(j.message || 'Saved.') + '</span>'
|
||||||
|
: '<span class="err">' + escapeHtml(j.message || 'Save failed.') + '</span>';
|
||||||
|
} finally {
|
||||||
|
saveQr.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
actions.appendChild(openBtn); actions.appendChild(saveQr);
|
||||||
|
actionCell.appendChild(actions);
|
||||||
|
row.append(file, qr, actionCell, error);
|
||||||
|
tbody.appendChild(row);
|
||||||
|
resultItems.push({ name: m.name, url: m.qrImg });
|
||||||
|
saveAllBtn.disabled = resultItems.length === 0;
|
||||||
|
regenAllBtn.disabled = resultItems.length === 0;
|
||||||
|
} else if (m.type === 'done') {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="ok">Done.</span>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/applovin", "AppLovin Playable Preview", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ApplovinPick(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cfg := LoadConfig()
|
||||||
|
picked := PickFiles(
|
||||||
|
"Select HTML files",
|
||||||
|
[]FileFilter{{Name: "HTML", Extensions: []string{"html", "htm"}}},
|
||||||
|
true, cfg.LastPickDir,
|
||||||
|
)
|
||||||
|
if len(picked) > 0 {
|
||||||
|
cfg.LastPickDir = filepath.Dir(picked[0])
|
||||||
|
_ = SaveConfig(cfg)
|
||||||
|
}
|
||||||
|
files := make([]map[string]string, 0, len(picked))
|
||||||
|
for _, p := range picked {
|
||||||
|
files = append(files, map[string]string{"path": p, "name": filepath.Base(p)})
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"files": files})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ApplovinPickFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cfg := LoadConfig()
|
||||||
|
dir := PickFolder("Select folder", cfg.LastPickDir)
|
||||||
|
if dir == "" {
|
||||||
|
writeJSON(w, map[string]any{"files": []any{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg.LastPickDir = dir
|
||||||
|
_ = SaveConfig(cfg)
|
||||||
|
paths := collectHTMLFiles(dir)
|
||||||
|
files := make([]map[string]string, 0, len(paths))
|
||||||
|
for _, p := range paths {
|
||||||
|
files = append(files, map[string]string{"path": p, "name": filepath.Base(p)})
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"files": files})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ApplovinUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Paths []string `json:"paths"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := LoadConfig().Applovin
|
||||||
|
cookie := cfg.Cookie
|
||||||
|
delayMs := cfg.DelayMs
|
||||||
|
if delayMs < 0 {
|
||||||
|
delayMs = 0
|
||||||
|
}
|
||||||
|
randomizeUA := true
|
||||||
|
if cfg.RandomizeUserAgent != nil {
|
||||||
|
randomizeUA = *cfg.RandomizeUserAgent
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||||
|
flusher, _ := w.(http.Flusher)
|
||||||
|
|
||||||
|
send := func(obj any) {
|
||||||
|
data, _ := json.Marshal(obj)
|
||||||
|
_, _ = w.Write(append(data, '\n'))
|
||||||
|
if flusher != nil {
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
htmlRx := regexp.MustCompile(`(?i)\.html?$`)
|
||||||
|
|
||||||
|
buildForm := func(filePath string) (*bytes.Buffer, string, error) {
|
||||||
|
data, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
mw := multipart.NewWriter(&buf)
|
||||||
|
fw, err := createFormFileWithType(mw, "file", filepath.Base(filePath), "text/html")
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if _, err := fw.Write(data); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
if err := mw.Close(); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
return &buf, mw.FormDataContentType(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
doPost := func(url string, body *bytes.Buffer, contentType string) (int, string, error) {
|
||||||
|
req, err := http.NewRequest("POST", url, body)
|
||||||
|
if err != nil {
|
||||||
|
return 0, "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", contentType)
|
||||||
|
req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
|
||||||
|
req.Header.Set("Origin", "https://p.applov.in")
|
||||||
|
req.Header.Set("Referer", "https://p.applov.in/playablePreview?create=1&qr=1")
|
||||||
|
req.Header.Set("X-Requested-With", "XMLHttpRequest")
|
||||||
|
req.Header.Set("User-Agent", pickApplovinUserAgent(randomizeUA))
|
||||||
|
if cookie != "" {
|
||||||
|
req.Header.Set("Cookie", "__Host-APPLOVINID="+cookie)
|
||||||
|
}
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, "", err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
out, _ := io.ReadAll(resp.Body)
|
||||||
|
return resp.StatusCode, string(out), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, filePath := range req.Paths {
|
||||||
|
fileName := filepath.Base(filePath)
|
||||||
|
idx := i + 1
|
||||||
|
fileErr := func(msg string) {
|
||||||
|
send(map[string]any{"type": "fileError", "name": fileName, "message": msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
if filePath == "" || !fileExists(filePath) {
|
||||||
|
fileErr("File missing")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !htmlRx.MatchString(filePath) {
|
||||||
|
fileErr("Must be .html")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if i > 0 && delayMs > 0 {
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Waiting %d/%d %s", idx, len(req.Paths), fileName)})
|
||||||
|
time.Sleep(time.Duration(delayMs) * time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Validating %d/%d %s", idx, len(req.Paths), fileName)})
|
||||||
|
|
||||||
|
body, ct, err := buildForm(filePath)
|
||||||
|
if err != nil {
|
||||||
|
fileErr("Read failed: " + err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
status, respText, err := doPost("https://p.applov.in/validateHTMLContent", body, ct)
|
||||||
|
if err != nil {
|
||||||
|
fileErr("Network (validate): " + err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if status < 200 || status >= 300 {
|
||||||
|
fileErr(fmt.Sprintf("Validate HTTP %d: %s", status, truncate(respText, 300)))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var vJSON map[string]any
|
||||||
|
_ = json.Unmarshal([]byte(respText), &vJSON)
|
||||||
|
if code, ok := vJSON["code"]; ok {
|
||||||
|
if codeNum, isNum := code.(float64); isNum && codeNum != 200 {
|
||||||
|
fileErr("Validation failed: " + truncate(respText, 300))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Uploading %d/%d %s", idx, len(req.Paths), fileName)})
|
||||||
|
|
||||||
|
body, ct, err = buildForm(filePath)
|
||||||
|
if err != nil {
|
||||||
|
fileErr("Read failed: " + err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
status, respText, err = doPost("https://p.applov.in/getCachedAdURL", body, ct)
|
||||||
|
if err != nil {
|
||||||
|
fileErr("Network (cache): " + err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if status < 200 || status >= 300 {
|
||||||
|
fileErr(fmt.Sprintf("Cache HTTP %d: %s", status, truncate(respText, 300)))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var cJSON map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(respText), &cJSON); err != nil {
|
||||||
|
fileErr("Non-JSON: " + truncate(respText, 300))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
hash, _ := cJSON["results"].(string)
|
||||||
|
if hash == "" {
|
||||||
|
fileErr("No hash in response: " + truncate(respText, 300))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
send(map[string]any{
|
||||||
|
"type": "fileResult",
|
||||||
|
"name": fileName,
|
||||||
|
"hash": hash,
|
||||||
|
"previewUrl": "https://p.applov.in/getPreviewHTML?preview=" + hash,
|
||||||
|
"pageUrl": "https://p.applov.in/playablePreview?preview=" + hash + "&qr=1",
|
||||||
|
"qrImg": "https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=" + urlpkg.QueryEscape(hash),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "done"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func qrBaseName(name string) string {
|
||||||
|
base := name
|
||||||
|
if base == "" {
|
||||||
|
base = "qr"
|
||||||
|
}
|
||||||
|
base = regexp.MustCompile(`(?i)\.html?$`).ReplaceAllString(base, "")
|
||||||
|
base = regexp.MustCompile(`[\\/:*?"<>|]`).ReplaceAllString(base, "_")
|
||||||
|
if base == "" {
|
||||||
|
base = "qr"
|
||||||
|
}
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadQR(url, destPath string) error {
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
return fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(destPath, data, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ApplovinSaveQR(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.URL == "" {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "message": "Missing URL"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
base := qrBaseName(req.Name)
|
||||||
|
dest := PickSaveFile("Save QR", base+".png", []FileFilter{{Name: "PNG Image", Extensions: []string{"png"}}}, "")
|
||||||
|
if dest == "" {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "message": "Cancelled"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := downloadQR(req.URL, dest); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "message": "Save failed: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"ok": true, "message": "Saved QR: " + dest})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ApplovinSaveAllQRs(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Items []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
} `json:"items"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(req.Items) == 0 {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "message": "No items"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dir := PickFolder("Choose folder to save QRs", "")
|
||||||
|
if dir == "" {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "message": "Cancelled"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
saved := 0
|
||||||
|
errs := []string{}
|
||||||
|
for _, it := range req.Items {
|
||||||
|
base := qrBaseName(it.Name)
|
||||||
|
dest := filepath.Join(dir, base+".png")
|
||||||
|
n := 1
|
||||||
|
for fileExists(dest) {
|
||||||
|
dest = filepath.Join(dir, fmt.Sprintf("%s (%d).png", base, n))
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if err := downloadQR(it.URL, dest); err != nil {
|
||||||
|
errs = append(errs, it.Name+": "+err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
saved++
|
||||||
|
}
|
||||||
|
if len(errs) > 0 {
|
||||||
|
writeJSON(w, map[string]any{
|
||||||
|
"ok": false,
|
||||||
|
"message": fmt.Sprintf("Saved %d/%d. Errors: %s", saved, len(req.Items), strings.Join(errs, "; ")),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{
|
||||||
|
"ok": true,
|
||||||
|
"message": fmt.Sprintf("Saved %d QR%s to %s", saved, plural(saved), dir),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func plural(n int) string {
|
||||||
|
if n == 1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return "s"
|
||||||
|
}
|
||||||
1
standalone/assets/mintegral/preview-util.js
Normal file
1
standalone/assets/mintegral/preview-util.js
Normal file
File diff suppressed because one or more lines are too long
8
standalone/assets/qrcode.min.js
vendored
Normal file
8
standalone/assets/qrcode.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
377
standalone/base64.go
Normal file
377
standalone/base64.go
Normal file
@@ -0,0 +1,377 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Base64Page(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">Base64 Scanner</h2>
|
||||||
|
<p class="tool-description">Scan selected HTML files for asset references that are not embedded as base64 data URIs.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="tool-panel">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Inputs</h3></div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div id="dropZone" class="drop-zone">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
|
<button id="pickFiles" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div class="drop-zone-text">or drop HTML files or folders here</div>
|
||||||
|
</div>
|
||||||
|
<div id="selection" class="selected-list"></div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row"><button id="scan">Scan</button></div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.asset-list { margin:0; padding-left:16px; }
|
||||||
|
.asset-list li + li { margin-top:3px; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const resultsEl = document.getElementById('results');
|
||||||
|
const selectionEl = document.getElementById('selection');
|
||||||
|
let pickedFiles = [];
|
||||||
|
let selectedPage = 0;
|
||||||
|
function basename(p) { const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\')); return i >= 0 ? p.slice(i + 1) : p; }
|
||||||
|
function escapeHtml(s){ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
||||||
|
function renderSelection() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
if (!pickedFiles.length) {
|
||||||
|
selectionEl.innerHTML = '<span class="file-name">(no files selected)</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const maxPage = Math.max(0, Math.ceil(pickedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const start = selectedPage * PAGE_SIZE;
|
||||||
|
const visible = pickedFiles.slice(start, start + PAGE_SIZE);
|
||||||
|
selectionEl.innerHTML = '<div class="results-panel" style="margin-top:0;"><table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead><tbody>' +
|
||||||
|
visible.map((p, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return '<tr><td class="mono wrap">' + escapeHtml(basename(p)) + '</td><td><button class="remove-selected danger" data-index="' + i + '" title="Remove">×</button></td></tr>';
|
||||||
|
}).join('') + '</tbody></table></div>';
|
||||||
|
selectionEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => { pickedFiles.splice(Number(btn.dataset.index), 1); renderSelection(); });
|
||||||
|
});
|
||||||
|
if (pickedFiles.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML = '<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
selectionEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function addPaths(paths) {
|
||||||
|
const existing = new Set(pickedFiles);
|
||||||
|
pickedFiles = pickedFiles.concat((paths || []).filter(p => !existing.has(p)));
|
||||||
|
selectedPage = Math.max(0, Math.ceil(pickedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
}
|
||||||
|
async function readJSONStream(response, handle) {
|
||||||
|
if (!response.ok || !response.body) throw new Error('Request failed.');
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
let newline;
|
||||||
|
while ((newline = buffer.indexOf('\n')) >= 0) {
|
||||||
|
const line = buffer.slice(0, newline);
|
||||||
|
buffer = buffer.slice(newline + 1);
|
||||||
|
if (line.trim()) handle(JSON.parse(line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffer.trim()) handle(JSON.parse(buffer));
|
||||||
|
}
|
||||||
|
renderSelection();
|
||||||
|
setupDropZone('dropZone', statusEl, (j) => {
|
||||||
|
addPaths(j.paths || []);
|
||||||
|
if (j.skipped) statusEl.textContent = 'Skipped ' + j.skipped + ' non-HTML or unavailable item(s).';
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('pickFolder').addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/base64/pickFolder', { method: 'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
addPaths(j.paths || []);
|
||||||
|
});
|
||||||
|
document.getElementById('pickFiles').addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/base64/pickFiles', { method: 'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
addPaths(j.paths || []);
|
||||||
|
});
|
||||||
|
document.getElementById('clear').addEventListener('click', () => {
|
||||||
|
pickedFiles = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
document.getElementById('scan').addEventListener('click', async () => {
|
||||||
|
statusEl.textContent = 'Scanning...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
if (!pickedFiles.length) { statusEl.classList.remove('is-busy'); statusEl.textContent = 'Pick files first.'; return; }
|
||||||
|
const payload = { files: pickedFiles };
|
||||||
|
let j = null;
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/base64/scan', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload) });
|
||||||
|
await readJSONStream(r, (msg) => {
|
||||||
|
if (msg.type === 'status') {
|
||||||
|
statusEl.textContent = msg.message;
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
} else if (msg.type === 'done') {
|
||||||
|
j = msg;
|
||||||
|
} else if (msg.type === 'error') {
|
||||||
|
j = { error: msg.message };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Error: ' + (e.message || e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!j) { statusEl.classList.remove('is-busy'); statusEl.textContent = 'Error: No response.'; return; }
|
||||||
|
if (j.error) { statusEl.classList.remove('is-busy'); statusEl.textContent = 'Error: ' + j.error; return; }
|
||||||
|
const total = j.results.length;
|
||||||
|
const flagged = j.results.filter(r => !r.ok).length;
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Scanned ' + total + ' HTML file(s). ' + flagged + ' contain non-base64 assets.';
|
||||||
|
if (!total) { resultsEl.innerHTML = ''; return; }
|
||||||
|
resultsEl.innerHTML = '<table class="data-table"><thead><tr><th style="width:90px;">Status</th><th>File</th><th style="width:90px;">Issues</th><th>Non-base64 assets</th></tr></thead><tbody></tbody></table>';
|
||||||
|
const tbody = resultsEl.querySelector('tbody');
|
||||||
|
for (const rr of j.results) {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
const assets = rr.ok ? '<span class="muted">None</span>' : '<ul class="asset-list mono">' + rr.assets.map(a => '<li>' + escapeHtml(a) + '</li>').join('') + '</ul>';
|
||||||
|
row.innerHTML = '<td>' + (rr.ok ? '<span class="badge ok">OK</span>' : '<span class="badge err">Review</span>') + '</td>' +
|
||||||
|
'<td class="mono wrap">' + escapeHtml(rr.file) + '</td><td>' + rr.assets.length + '</td><td class="wrap">' + assets + '</td>';
|
||||||
|
tbody.appendChild(row);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/base64", "Base64 Scanner", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Base64PickFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
p := PickFolder("Select folder to scan", "")
|
||||||
|
if p == "" {
|
||||||
|
writeJSON(w, map[string]any{"paths": []string{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"paths": collectHTMLFiles(p)})
|
||||||
|
}
|
||||||
|
|
||||||
|
func Base64PickFiles(w http.ResponseWriter, r *http.Request) {
|
||||||
|
paths := PickFiles(
|
||||||
|
"Select HTML files",
|
||||||
|
[]FileFilter{{Name: "HTML", Extensions: []string{"html", "htm"}}},
|
||||||
|
true, "",
|
||||||
|
)
|
||||||
|
writeJSON(w, map[string]any{"paths": paths})
|
||||||
|
}
|
||||||
|
|
||||||
|
type scanResult struct {
|
||||||
|
File string `json:"file"`
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Assets []string `json:"assets"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Base64Scan(w http.ResponseWriter, r *http.Request) {
|
||||||
|
send := newJSONStream(w)
|
||||||
|
var req struct {
|
||||||
|
Folder string `json:"folder"`
|
||||||
|
Files []string `json:"files"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var targets []string
|
||||||
|
var baseDir string
|
||||||
|
|
||||||
|
if len(req.Files) > 0 {
|
||||||
|
for _, f := range req.Files {
|
||||||
|
if fileExists(f) {
|
||||||
|
targets = append(targets, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(targets) > 0 {
|
||||||
|
baseDir = commonBaseDir(targets)
|
||||||
|
}
|
||||||
|
} else if req.Folder != "" && fileExists(req.Folder) {
|
||||||
|
targets = collectHTMLFiles(req.Folder)
|
||||||
|
baseDir = req.Folder
|
||||||
|
} else {
|
||||||
|
send(map[string]any{"type": "error", "message": "Pick a folder or files first"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
results := []scanResult{}
|
||||||
|
for i, file := range targets {
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Scanning %d/%d %s", i+1, len(targets), filepath.Base(file))})
|
||||||
|
data, err := os.ReadFile(file)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
offenders := findNonBase64Assets(string(data))
|
||||||
|
display := file
|
||||||
|
if baseDir != "" {
|
||||||
|
rel, err := filepath.Rel(baseDir, file)
|
||||||
|
if err == nil && rel != "" {
|
||||||
|
display = rel
|
||||||
|
} else {
|
||||||
|
display = filepath.Base(file)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
results = append(results, scanResult{
|
||||||
|
File: display,
|
||||||
|
OK: len(offenders) == 0,
|
||||||
|
Assets: offenders,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "done", "results": results})
|
||||||
|
}
|
||||||
|
|
||||||
|
func commonBaseDir(files []string) string {
|
||||||
|
if len(files) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if len(files) == 1 {
|
||||||
|
return filepath.Dir(files[0])
|
||||||
|
}
|
||||||
|
split := make([][]string, len(files))
|
||||||
|
for i, f := range files {
|
||||||
|
split[i] = strings.Split(filepath.Dir(f), string(filepath.Separator))
|
||||||
|
}
|
||||||
|
first := split[0]
|
||||||
|
i := 0
|
||||||
|
for i < len(first) {
|
||||||
|
match := true
|
||||||
|
for _, parts := range split {
|
||||||
|
if i >= len(parts) || parts[i] != first[i] {
|
||||||
|
match = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !match {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return strings.Join(first[:i], string(filepath.Separator))
|
||||||
|
}
|
||||||
|
|
||||||
|
func collectHTMLFiles(root string) []string {
|
||||||
|
var out []string
|
||||||
|
htmlRx := regexp.MustCompile(`(?i)\.html?$`)
|
||||||
|
_ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if d.IsDir() {
|
||||||
|
name := d.Name()
|
||||||
|
if name == "node_modules" || name == ".git" {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if htmlRx.MatchString(d.Name()) {
|
||||||
|
out = append(out, path)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
scriptBlockRx = regexp.MustCompile(`(?is)<script\b[^>]*>.*?</script>`)
|
||||||
|
attrRx = regexp.MustCompile(`(?i)\b(?:src|href|poster|data-src)\s*=\s*("([^"]*)"|'([^']*)')`)
|
||||||
|
cssUrlRx = regexp.MustCompile(`(?i)url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)`)
|
||||||
|
base64DataRx = regexp.MustCompile(`(?i)^data:[^;,]*;base64,`)
|
||||||
|
mailTelRx = regexp.MustCompile(`(?i)^(mailto:|tel:)`)
|
||||||
|
)
|
||||||
|
|
||||||
|
func findNonBase64Assets(htmlSrc string) []string {
|
||||||
|
markup := scriptBlockRx.ReplaceAllString(htmlSrc, "")
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var out []string
|
||||||
|
add := func(u string) {
|
||||||
|
if u == "" || seen[u] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[u] = true
|
||||||
|
out = append(out, u)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, m := range attrRx.FindAllStringSubmatch(markup, -1) {
|
||||||
|
url := m[2]
|
||||||
|
if url == "" {
|
||||||
|
url = m[3]
|
||||||
|
}
|
||||||
|
url = strings.TrimSpace(url)
|
||||||
|
if url == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isAssetReference(url) && !base64DataRx.MatchString(url) {
|
||||||
|
add(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range cssUrlRx.FindAllStringSubmatch(markup, -1) {
|
||||||
|
url := m[1]
|
||||||
|
if url == "" {
|
||||||
|
url = m[2]
|
||||||
|
}
|
||||||
|
if url == "" {
|
||||||
|
url = m[3]
|
||||||
|
}
|
||||||
|
url = strings.TrimSpace(url)
|
||||||
|
if url == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !base64DataRx.MatchString(url) {
|
||||||
|
add(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out == nil {
|
||||||
|
out = []string{}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAssetReference(url string) bool {
|
||||||
|
if strings.HasPrefix(url, "#") || strings.HasPrefix(strings.ToLower(url), "javascript:") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if mailTelRx.MatchString(url) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
229
standalone/changelog.go
Normal file
229
standalone/changelog.go
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"html"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ChangelogPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
markdown := readChangelog()
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">Changelog</h2>
|
||||||
|
<p class="tool-description">Loaded from README.md.</p>
|
||||||
|
</header>
|
||||||
|
<section class="tool-panel changelog-panel">
|
||||||
|
<div class="panel-body changelog-content">
|
||||||
|
` + renderChangelogMarkdown(markdown) + `
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<style>
|
||||||
|
.changelog-panel { max-width: 840px; }
|
||||||
|
.changelog-content h1 { margin: 0 0 14px; font-size: 20px; line-height: 1.25; }
|
||||||
|
.changelog-content h2 { margin: 18px 0 8px; padding-top: 12px; border-top: 1px solid #333; font-size: 15px; line-height: 1.3; }
|
||||||
|
.changelog-content h3 { margin: 14px 0 6px; font-size: 13px; line-height: 1.3; }
|
||||||
|
.changelog-content ul { margin: 6px 0 12px; padding-left: 20px; }
|
||||||
|
.changelog-content li { margin: 4px 0; line-height: 1.45; }
|
||||||
|
.changelog-content li.nested { margin-left: 18px; }
|
||||||
|
.changelog-content p { margin: 8px 0; line-height: 1.5; }
|
||||||
|
.changelog-content code { font-family: Consolas, monospace; font-size: 0.95em; background: rgba(128,128,128,0.12); padding: 1px 4px; border-radius: 3px; }
|
||||||
|
.changelog-block { margin: 8px 0 18px; padding: 10px 12px; border: 1px solid #333; border-radius: 4px; background: rgba(128,128,128,0.08); }
|
||||||
|
.change-section { margin: 8px 0 4px; font-weight: 600; }
|
||||||
|
.changelog-block ul { margin: 4px 0 10px; }
|
||||||
|
</style>`
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/changelog", "Changelog", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func readChangelog() string {
|
||||||
|
if embeddedReadme != "" {
|
||||||
|
return embeddedReadme
|
||||||
|
}
|
||||||
|
for _, start := range changelogSearchRoots() {
|
||||||
|
for _, candidate := range changelogCandidates(start) {
|
||||||
|
data, err := os.ReadFile(candidate)
|
||||||
|
if err == nil {
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "# Changelog\n\nREADME.md was not found."
|
||||||
|
}
|
||||||
|
|
||||||
|
func changelogSearchRoots() []string {
|
||||||
|
roots := []string{}
|
||||||
|
if wd, err := os.Getwd(); err == nil {
|
||||||
|
roots = append(roots, wd)
|
||||||
|
}
|
||||||
|
roots = append(roots, appDir())
|
||||||
|
return roots
|
||||||
|
}
|
||||||
|
|
||||||
|
func changelogCandidates(start string) []string {
|
||||||
|
candidates := []string{}
|
||||||
|
dir := filepath.Clean(start)
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
candidates = append(candidates, filepath.Join(dir, "README.md"))
|
||||||
|
parent := filepath.Dir(dir)
|
||||||
|
if parent == dir {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
dir = parent
|
||||||
|
}
|
||||||
|
return candidates
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderChangelogMarkdown(markdown string) string {
|
||||||
|
lines := strings.Split(strings.ReplaceAll(markdown, "\r\n", "\n"), "\n")
|
||||||
|
var out strings.Builder
|
||||||
|
inList := false
|
||||||
|
inCodeBlock := false
|
||||||
|
codeLines := []string{}
|
||||||
|
closeList := func() {
|
||||||
|
if inList {
|
||||||
|
out.WriteString("</ul>")
|
||||||
|
inList = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, rawLine := range lines {
|
||||||
|
if strings.TrimSpace(rawLine) == "```" {
|
||||||
|
closeList()
|
||||||
|
if inCodeBlock {
|
||||||
|
out.WriteString(renderChangelogBlock(codeLines))
|
||||||
|
codeLines = []string{}
|
||||||
|
inCodeBlock = false
|
||||||
|
} else {
|
||||||
|
inCodeBlock = true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if inCodeBlock {
|
||||||
|
codeLines = append(codeLines, rawLine)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
line := strings.TrimSpace(rawLine)
|
||||||
|
if line == "" {
|
||||||
|
closeList()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "### ") {
|
||||||
|
closeList()
|
||||||
|
out.WriteString("<h2>" + renderInlineMarkdown(strings.TrimSpace(line[4:])) + "</h2>")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "## ") {
|
||||||
|
closeList()
|
||||||
|
out.WriteString("<h2>" + renderInlineMarkdown(strings.TrimSpace(line[3:])) + "</h2>")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "# ") {
|
||||||
|
closeList()
|
||||||
|
out.WriteString("<h1>" + renderInlineMarkdown(strings.TrimSpace(line[2:])) + "</h1>")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "**") && strings.HasSuffix(line, "**") && len(line) > 4 {
|
||||||
|
closeList()
|
||||||
|
out.WriteString("<h2>" + html.EscapeString(strings.TrimSuffix(strings.TrimPrefix(line, "**"), "**")) + "</h2>")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "- ") {
|
||||||
|
if !inList {
|
||||||
|
out.WriteString("<ul>")
|
||||||
|
inList = true
|
||||||
|
}
|
||||||
|
out.WriteString("<li>" + renderInlineMarkdown(strings.TrimSpace(line[2:])) + "</li>")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
closeList()
|
||||||
|
out.WriteString("<p>" + renderInlineMarkdown(line) + "</p>")
|
||||||
|
}
|
||||||
|
if inCodeBlock {
|
||||||
|
out.WriteString(renderChangelogBlock(codeLines))
|
||||||
|
}
|
||||||
|
closeList()
|
||||||
|
return out.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderChangelogBlock(lines []string) string {
|
||||||
|
var out strings.Builder
|
||||||
|
inList := false
|
||||||
|
closeList := func() {
|
||||||
|
if inList {
|
||||||
|
out.WriteString("</ul>")
|
||||||
|
inList = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.WriteString(`<div class="changelog-block">`)
|
||||||
|
for _, rawLine := range lines {
|
||||||
|
line := strings.TrimSpace(rawLine)
|
||||||
|
if line == "" {
|
||||||
|
closeList()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "- ") {
|
||||||
|
if !inList {
|
||||||
|
out.WriteString("<ul>")
|
||||||
|
inList = true
|
||||||
|
}
|
||||||
|
className := ""
|
||||||
|
if leadingSpaceCount(rawLine) >= 8 {
|
||||||
|
className = ` class="nested"`
|
||||||
|
}
|
||||||
|
out.WriteString("<li" + className + ">" + renderInlineMarkdown(strings.TrimSpace(line[2:])) + "</li>")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
closeList()
|
||||||
|
out.WriteString(`<div class="change-section">` + renderInlineMarkdown(line) + `</div>`)
|
||||||
|
}
|
||||||
|
closeList()
|
||||||
|
out.WriteString("</div>")
|
||||||
|
return out.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderInlineMarkdown(value string) string {
|
||||||
|
escaped := html.EscapeString(value)
|
||||||
|
escaped = replaceDelimited(escaped, "**", "strong")
|
||||||
|
escaped = replaceDelimited(escaped, "`", "code")
|
||||||
|
return escaped
|
||||||
|
}
|
||||||
|
|
||||||
|
func replaceDelimited(value, marker, tag string) string {
|
||||||
|
var out strings.Builder
|
||||||
|
for {
|
||||||
|
start := strings.Index(value, marker)
|
||||||
|
if start < 0 {
|
||||||
|
out.WriteString(value)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
end := strings.Index(value[start+len(marker):], marker)
|
||||||
|
if end < 0 {
|
||||||
|
out.WriteString(value)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
end += start + len(marker)
|
||||||
|
out.WriteString(value[:start])
|
||||||
|
out.WriteString("<" + tag + ">")
|
||||||
|
out.WriteString(value[start+len(marker) : end])
|
||||||
|
out.WriteString("</" + tag + ">")
|
||||||
|
value = value[end+len(marker):]
|
||||||
|
}
|
||||||
|
return out.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func leadingSpaceCount(value string) int {
|
||||||
|
count := 0
|
||||||
|
for _, ch := range value {
|
||||||
|
if ch != ' ' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
1017
standalone/device_simulator.go
Normal file
1017
standalone/device_simulator.go
Normal file
File diff suppressed because it is too large
Load Diff
9
standalone/go.mod
Normal file
9
standalone/go.mod
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
module hpltoolbox
|
||||||
|
|
||||||
|
go 1.22
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 // indirect
|
||||||
|
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
|
||||||
|
golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e // indirect
|
||||||
|
)
|
||||||
7
standalone/go.sum
Normal file
7
standalone/go.sum
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 h1:ftnsTqIUH57XQEF+PnXX9++nlHCzdkuB5zbWyMMruZo=
|
||||||
|
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo=
|
||||||
|
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
|
||||||
|
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
||||||
|
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e h1:f5mksnk+hgXHnImpZoWj64ja99j9zV7YUgrVG95uFE4=
|
||||||
|
golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
53
standalone/home.go
Normal file
53
standalone/home.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func HomePage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cfg := LoadConfig()
|
||||||
|
var items strings.Builder
|
||||||
|
for _, n := range visibleNavItems(cfg.BetaToolsEnabled) {
|
||||||
|
if n.Path == "/" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
badge := ""
|
||||||
|
if n.Beta {
|
||||||
|
badge = ` <span class="beta-pill">Beta</span>`
|
||||||
|
}
|
||||||
|
items.WriteString(`<button type="button" class="home-tool" draggable="true" data-path="` + n.Path + `"><span class="home-tool-title">` + n.Label + badge + `</span><span class="home-tool-desc">` + n.Description + `</span></button>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">HPL Toolbox</h2>
|
||||||
|
<p class="tool-description">Standalone build. Pick a tool to open.</p>
|
||||||
|
</header>
|
||||||
|
<div class="home-tools">
|
||||||
|
` + items.String() + `
|
||||||
|
</div>
|
||||||
|
<style>
|
||||||
|
.home-tools { display:flex; flex-direction:column; gap:8px; max-width:620px; }
|
||||||
|
.home-tool {
|
||||||
|
display:block;
|
||||||
|
width:100%;
|
||||||
|
min-height:52px;
|
||||||
|
padding:9px 11px;
|
||||||
|
color:#ddd;
|
||||||
|
text-align:left;
|
||||||
|
background:#2a2d2e;
|
||||||
|
border:1px solid #333;
|
||||||
|
border-radius:5px;
|
||||||
|
cursor:pointer;
|
||||||
|
font:inherit;
|
||||||
|
}
|
||||||
|
.home-tool:hover { background:#33373a; border-color:#007fd4; }
|
||||||
|
.home-tool.dragging { opacity:0.55; }
|
||||||
|
.home-tool-title { display:flex; align-items:center; justify-content:space-between; gap:8px; font-size:12px; font-weight:600; }
|
||||||
|
.home-tool-desc { display:block; margin-top:4px; color:#a7a7a7; font-size:11px; line-height:1.35; }
|
||||||
|
</style>
|
||||||
|
`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/", "Home", body)))
|
||||||
|
}
|
||||||
BIN
standalone/hpl.ico
Normal file
BIN
standalone/hpl.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
BIN
standalone/hpltoolbox.exe
Normal file
BIN
standalone/hpltoolbox.exe
Normal file
Binary file not shown.
36
standalone/json.go
Normal file
36
standalone/json.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newJSONStream(w http.ResponseWriter) func(any) {
|
||||||
|
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
flusher, _ := w.(http.Flusher)
|
||||||
|
return func(v any) {
|
||||||
|
data, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
data = []byte(fmt.Sprintf(`{"type":"error","message":%q}`, err.Error()))
|
||||||
|
}
|
||||||
|
_, _ = w.Write(data)
|
||||||
|
_, _ = w.Write([]byte("\n"))
|
||||||
|
if flusher != nil {
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func pluralS(n int) string {
|
||||||
|
if n == 1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return "s"
|
||||||
|
}
|
||||||
903
standalone/layout.go
Normal file
903
standalone/layout.go
Normal file
@@ -0,0 +1,903 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const SharedCSS = `
|
||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--tool-gap-sm: 8px;
|
||||||
|
--tool-gap-md: 12px;
|
||||||
|
--tool-gap-lg: 16px;
|
||||||
|
--tool-radius: 5px;
|
||||||
|
--tool-border: #333;
|
||||||
|
--tool-panel: #252526;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html { min-height: 100%; }
|
||||||
|
body {
|
||||||
|
min-height: 100vh;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: var(--sidebar-width, 236px) minmax(0, 1fr);
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
background: #1e1e1e; color: #ddd;
|
||||||
|
margin: 0; padding: 0;
|
||||||
|
}
|
||||||
|
body.sidebar-collapsed { --sidebar-width: 56px; }
|
||||||
|
.sidebar {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 10px 8px;
|
||||||
|
background: #252526;
|
||||||
|
border-right: 1px solid #333;
|
||||||
|
font-size: 13px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.sidebar-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
min-height: 32px;
|
||||||
|
padding: 0 2px 6px;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
}
|
||||||
|
.sidebar-title {
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
color: #ddd;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.45px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.sidebar-toggle {
|
||||||
|
width: 32px;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
background: transparent;
|
||||||
|
color: #ddd;
|
||||||
|
border: 1px solid #444;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.sidebar-toggle:hover { background: #2a2d2e; }
|
||||||
|
.sidebar-nav {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.sidebar .nav-link {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 34px;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 28px minmax(0, 1fr);
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
background: transparent;
|
||||||
|
color: #ddd;
|
||||||
|
border: 0;
|
||||||
|
padding: 4px 8px 4px 4px;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.sidebar .nav-link:hover { background: #2a2d2e; }
|
||||||
|
.sidebar .nav-link.active { background: #094771; color: #fff; }
|
||||||
|
.sidebar .nav-link.dragging { opacity: 0.55; }
|
||||||
|
.nav-icon {
|
||||||
|
width: 28px;
|
||||||
|
height: 26px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: rgba(128,128,128,0.12);
|
||||||
|
color: #ddd;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0;
|
||||||
|
}
|
||||||
|
.nav-text {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.beta-pill { margin-left: 4px; padding: 1px 4px; border: 1px solid #555; border-radius: 3px; font-size: 10px; opacity: 0.7; text-transform: uppercase; }
|
||||||
|
.app-shell {
|
||||||
|
min-width: 0;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.content { flex: 1; width: 100%; padding: 18px; max-width: 1100px; margin: 0 auto; }
|
||||||
|
.app-footer {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: auto auto 0;
|
||||||
|
padding: 8px 18px 14px;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr auto 1fr;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
color: #a7a7a7;
|
||||||
|
font-size: 10px;
|
||||||
|
border-top: 1px solid #333;
|
||||||
|
}
|
||||||
|
.beta-tools-toggle {
|
||||||
|
justify-self: start;
|
||||||
|
padding: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: #a7a7a7;
|
||||||
|
border: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
opacity: 0.72;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.beta-tools-toggle:hover { background: transparent; opacity: 1; text-decoration: underline; }
|
||||||
|
.app-footer-version { opacity: 0.75; text-align: center; white-space: nowrap; }
|
||||||
|
.app-footer-link { justify-self: end; padding: 0; background: transparent; color: #a7a7a7; border: 0; cursor: pointer; font: inherit; opacity: 0.72; }
|
||||||
|
.app-footer-link:hover { background: transparent; opacity: 1; text-decoration: underline; }
|
||||||
|
.app-footer-version-button { justify-self: center; padding: 0; background: transparent; color: #a7a7a7; border: 0; cursor: pointer; font: inherit; opacity: 0.75; text-align: center; white-space: nowrap; }
|
||||||
|
.app-footer-version-button:hover { background: transparent; opacity: 1; text-decoration: underline; }
|
||||||
|
.toast-box {
|
||||||
|
position: fixed;
|
||||||
|
right: 18px;
|
||||||
|
bottom: 18px;
|
||||||
|
z-index: 50;
|
||||||
|
max-width: min(420px, calc(100vw - 36px));
|
||||||
|
padding: 10px 12px;
|
||||||
|
display: none;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
color: #ddd;
|
||||||
|
background: #252526;
|
||||||
|
border: 1px solid #444;
|
||||||
|
border-left: 3px solid #007fd4;
|
||||||
|
border-radius: 5px;
|
||||||
|
box-shadow: 0 10px 28px rgba(0,0,0,0.35);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
.toast-box.is-visible { display: flex; }
|
||||||
|
.toast-box.is-update { border-left-color: #ffd580; }
|
||||||
|
.toast-box.is-current { border-left-color: #89d185; }
|
||||||
|
.toast-box.is-error { border-left-color: #f48771; }
|
||||||
|
.toast-message { min-width: 0; flex: 1; overflow-wrap: anywhere; }
|
||||||
|
.toast-action {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 4px 8px;
|
||||||
|
background: #0e639c;
|
||||||
|
color: #fff;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 2px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.toast-close {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
background: transparent;
|
||||||
|
color: #a7a7a7;
|
||||||
|
border: 0;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.toast-close:hover { background: rgba(255,255,255,0.08); color: #fff; }
|
||||||
|
body.sidebar-collapsed .sidebar { align-items: stretch; }
|
||||||
|
body.sidebar-collapsed .sidebar-title,
|
||||||
|
body.sidebar-collapsed .nav-text,
|
||||||
|
body.sidebar-collapsed .beta-pill { display: none; }
|
||||||
|
body.sidebar-collapsed .sidebar .nav-link {
|
||||||
|
grid-template-columns: 28px;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 4px;
|
||||||
|
}
|
||||||
|
body.sidebar-collapsed .sidebar-header { justify-content: center; padding-left: 0; padding-right: 0; }
|
||||||
|
body.sidebar-collapsed .sidebar-toggle { width: 38px; }
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
body { grid-template-columns: 1fr; }
|
||||||
|
.sidebar {
|
||||||
|
position: static;
|
||||||
|
height: auto;
|
||||||
|
max-height: 48vh;
|
||||||
|
border-right: 0;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
}
|
||||||
|
body.sidebar-collapsed .sidebar { max-height: 50px; }
|
||||||
|
}
|
||||||
|
h2 { margin: 0; font-size: 18px; line-height: 1.25; font-weight: 600; }
|
||||||
|
.tool-header { margin-bottom: var(--tool-gap-lg); }
|
||||||
|
.tool-title { margin: 0; font-size: 18px; line-height: 1.25; font-weight: 600; }
|
||||||
|
.tool-description, .section-description, .muted { color: #a7a7a7; }
|
||||||
|
.tool-description { margin: 5px 0 0; max-width: 780px; font-size: 12px; line-height: 1.45; }
|
||||||
|
.tool-panel { margin-bottom: var(--tool-gap-lg); border: 1px solid var(--tool-border); border-radius: var(--tool-radius); background: rgba(128,128,128,0.08); overflow: hidden; }
|
||||||
|
.panel-header { padding: 10px 12px; border-bottom: 1px solid var(--tool-border); background: var(--tool-panel); }
|
||||||
|
.panel-title { margin: 0; color: #ddd; font-size: 12px; font-weight: 700; letter-spacing: 0.45px; text-transform: uppercase; }
|
||||||
|
.panel-body { padding: 12px; }
|
||||||
|
.control-group + .control-group { margin-top: var(--tool-gap-md); }
|
||||||
|
.control-label { margin: 0 0 6px; color: #a7a7a7; font-size: 11px; font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; }
|
||||||
|
.file-row, .field-row, .action-row { display: flex; align-items: center; gap: var(--tool-gap-sm); flex-wrap: wrap; }
|
||||||
|
.action-row { margin-top: var(--tool-gap-md); }
|
||||||
|
input[type=text], input[type=date], select, textarea {
|
||||||
|
box-sizing: border-box; padding: 6px 8px;
|
||||||
|
background: #3c3c3c; color: #ddd;
|
||||||
|
border: 1px solid #3c3c3c; border-radius: 2px;
|
||||||
|
font-family: inherit; font-size: 13px;
|
||||||
|
}
|
||||||
|
input[type=text]:focus, input[type=date]:focus, select:focus, textarea:focus {
|
||||||
|
outline: 1px solid #007fd4; border-color: #007fd4;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
background: #0e639c; color: #fff;
|
||||||
|
border: none; padding: 6px 14px; border-radius: 2px; cursor: pointer; font-size: 13px;
|
||||||
|
}
|
||||||
|
button:hover { background: #1177bb; }
|
||||||
|
button.secondary { background: #3a3d41; color: #ddd; }
|
||||||
|
button.secondary:hover { background: #45494e; }
|
||||||
|
button.danger { background: transparent; color: #f48771; border: 1px solid #444; }
|
||||||
|
button.danger:hover { background: rgba(244,135,113,0.14); }
|
||||||
|
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||||
|
.status-panel, .results-panel, .result-card { border: 1px solid var(--tool-border); border-radius: var(--tool-radius); background: rgba(128,128,128,0.08); }
|
||||||
|
.status-panel { min-height: 30px; margin-top: var(--tool-gap-md); padding: 8px 10px; white-space: pre-wrap; }
|
||||||
|
.status-panel.is-busy { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.status-panel.is-busy::before { content: ""; width: 12px; height: 12px; flex: 0 0 auto; border: 2px solid rgba(167,167,167,0.35); border-top-color: #ddd; border-radius: 50%; animation: status-spin 800ms linear infinite; }
|
||||||
|
@keyframes status-spin { to { transform: rotate(360deg); } }
|
||||||
|
.status-panel:empty { display: none; }
|
||||||
|
.results-panel { margin-top: var(--tool-gap-md); overflow: auto; }
|
||||||
|
.results-panel:empty { display: none; }
|
||||||
|
.result-card { padding: 10px; word-break: break-word; }
|
||||||
|
.data-table { width: 100%; border-collapse: collapse; table-layout: fixed; }
|
||||||
|
.data-table th, .data-table td { padding: 8px 10px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--tool-border); }
|
||||||
|
.data-table th { color: #a7a7a7; font-size: 11px; font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; background: var(--tool-panel); }
|
||||||
|
.data-table tr:last-child td { border-bottom: none; }
|
||||||
|
.mono { font-family: Consolas, "Courier New", monospace; font-size: 12px; }
|
||||||
|
.wrap { overflow-wrap: anywhere; word-break: break-word; }
|
||||||
|
.file-name { color: #a7a7a7; font-size: 12px; overflow-wrap: anywhere; }
|
||||||
|
.drop-zone {
|
||||||
|
margin-top: 8px;
|
||||||
|
min-height: 44px;
|
||||||
|
display: grid;
|
||||||
|
justify-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px dashed #444;
|
||||||
|
border-radius: var(--tool-radius);
|
||||||
|
color: #a7a7a7;
|
||||||
|
background: rgba(128,128,128,0.08);
|
||||||
|
font-size: 12px;
|
||||||
|
text-align: center;
|
||||||
|
transition: border-color 120ms ease, background-color 120ms ease, color 120ms ease;
|
||||||
|
}
|
||||||
|
.drop-zone .file-row { justify-content: center; }
|
||||||
|
.drop-zone-text { color: #a7a7a7; font-size: 12px; }
|
||||||
|
.drop-zone.is-dragover {
|
||||||
|
border-color: #007fd4;
|
||||||
|
color: #ddd;
|
||||||
|
background: rgba(0,127,212,0.12);
|
||||||
|
}
|
||||||
|
.selected-list, .selected-files { margin-top: 8px; }
|
||||||
|
.remove-selected, .remove-btn { min-width: 28px; width: 28px; padding: 3px 0; color: #f48771; font-size: 16px; line-height: 1; }
|
||||||
|
.pager { margin-top: 8px; display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
|
||||||
|
.badge { display: inline-flex; align-items: center; min-height: 18px; padding: 1px 6px; border-radius: 999px; border: 1px solid #444; font-size: 11px; line-height: 1.2; white-space: nowrap; }
|
||||||
|
.badge.ok { color: #89d185; background: rgba(137,209,133,0.12); }
|
||||||
|
.badge.err { color: #f48771; background: rgba(244,135,113,0.14); }
|
||||||
|
.badge.warn { color: #ffd580; background: rgba(210,153,34,0.16); }
|
||||||
|
.is-hidden { display: none !important; }
|
||||||
|
.err { color: #f48771; white-space: pre-wrap; }
|
||||||
|
.ok { color: #89d185; }
|
||||||
|
.hint { font-size: 12px; opacity: 0.7; }
|
||||||
|
`
|
||||||
|
|
||||||
|
const SharedDropZoneScript = `
|
||||||
|
function extractDroppedPaths(dataTransfer) {
|
||||||
|
const paths = [];
|
||||||
|
const add = (value) => {
|
||||||
|
if (!value) return;
|
||||||
|
const trimmed = String(value).trim();
|
||||||
|
if (trimmed && !paths.includes(trimmed)) paths.push(trimmed);
|
||||||
|
};
|
||||||
|
const addPathText = (text) => {
|
||||||
|
const value = String(text || '');
|
||||||
|
if (!value) return;
|
||||||
|
const uriMatches = value.match(/file:\/\/(?:\/[A-Za-z]:)?[^\\r\\n\\0]+/gi) || [];
|
||||||
|
uriMatches.forEach(add);
|
||||||
|
const quotedMatches = value.match(/"([^"]+)"|'([^']+)'/g) || [];
|
||||||
|
quotedMatches.forEach(match => add(match.replace(/^["']|["']$/g, '')));
|
||||||
|
value.split(/[\r\n\0]+/).forEach(line => {
|
||||||
|
let rest = line.trim();
|
||||||
|
if (!rest || rest.startsWith('#')) return;
|
||||||
|
while (rest.length) {
|
||||||
|
const driveMatches = [...rest.matchAll(/[A-Za-z]:\\/g)].map(m => m.index).filter(i => typeof i === 'number');
|
||||||
|
if (driveMatches.length <= 1) {
|
||||||
|
add(rest);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const next = driveMatches[1];
|
||||||
|
add(rest.slice(0, next).trim());
|
||||||
|
rest = rest.slice(next).trim();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const addLines = (text) => {
|
||||||
|
addPathText(text);
|
||||||
|
};
|
||||||
|
try { addLines(dataTransfer.getData('text/uri-list')); } catch {}
|
||||||
|
try { addLines(dataTransfer.getData('text/plain')); } catch {}
|
||||||
|
for (const file of Array.from(dataTransfer.files || [])) {
|
||||||
|
add(file.path);
|
||||||
|
}
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function extractDroppedHtmlFiles(dataTransfer) {
|
||||||
|
const files = [];
|
||||||
|
const seen = new Set();
|
||||||
|
const droppedFiles = Array.from(dataTransfer.files || []);
|
||||||
|
const entries = [];
|
||||||
|
const handlePromises = [];
|
||||||
|
for (const item of Array.from(dataTransfer.items || [])) {
|
||||||
|
if (typeof item.getAsFileSystemHandle === 'function') {
|
||||||
|
handlePromises.push(item.getAsFileSystemHandle().catch(() => null));
|
||||||
|
}
|
||||||
|
let entry = typeof item.webkitGetAsEntry === 'function' ? item.webkitGetAsEntry() : null;
|
||||||
|
if (!entry && typeof item.getAsEntry === 'function') entry = item.getAsEntry();
|
||||||
|
if (entry) entries.push(entry);
|
||||||
|
}
|
||||||
|
const addFile = async (file, name) => {
|
||||||
|
const fileName = name || file.name || 'dropped.html';
|
||||||
|
if (!/\.html?$/i.test(fileName)) return;
|
||||||
|
const key = fileName + ':' + file.size + ':' + file.lastModified;
|
||||||
|
if (seen.has(key)) return;
|
||||||
|
seen.add(key);
|
||||||
|
files.push({ name: fileName, content: await file.text() });
|
||||||
|
};
|
||||||
|
const readEntry = async (entry, prefix) => {
|
||||||
|
if (!entry) return;
|
||||||
|
if (entry.isFile) {
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
entry.file(async (file) => {
|
||||||
|
await addFile(file, (prefix || '') + file.name);
|
||||||
|
resolve();
|
||||||
|
}, () => resolve());
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (entry.isDirectory) {
|
||||||
|
const reader = entry.createReader();
|
||||||
|
while (true) {
|
||||||
|
const entries = await new Promise(resolve => reader.readEntries(resolve, () => resolve([])));
|
||||||
|
if (!entries.length) break;
|
||||||
|
for (const child of entries) await readEntry(child, (prefix || '') + entry.name + '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const readHandle = async (handle, prefix) => {
|
||||||
|
if (!handle) return;
|
||||||
|
if (handle.kind === 'file') {
|
||||||
|
try {
|
||||||
|
const file = await handle.getFile();
|
||||||
|
await addFile(file, (prefix || '') + file.name);
|
||||||
|
} catch {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (handle.kind === 'directory') {
|
||||||
|
try {
|
||||||
|
for await (const child of handle.values()) {
|
||||||
|
await readHandle(child, (prefix || '') + handle.name + '/');
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (const file of droppedFiles) await addFile(file, file.name);
|
||||||
|
for (const entry of entries) await readEntry(entry, '');
|
||||||
|
for (const handle of await Promise.all(handlePromises)) await readHandle(handle, '');
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupDropZone(id, statusElement, onResolved) {
|
||||||
|
const zone = document.getElementById(id);
|
||||||
|
if (!zone) return;
|
||||||
|
const fallback = 'This view could not read dropped file paths. Use Select File(s) or Select Folder instead.';
|
||||||
|
const setMessage = (text) => {
|
||||||
|
if (statusElement) statusElement.textContent = text || '';
|
||||||
|
};
|
||||||
|
['dragenter', 'dragover'].forEach(type => {
|
||||||
|
zone.addEventListener(type, (event) => {
|
||||||
|
if (event.target && event.target.closest && event.target.closest('button, input')) return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
zone.classList.add('is-dragover');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
['dragleave', 'dragend'].forEach(type => {
|
||||||
|
zone.addEventListener(type, (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
zone.classList.remove('is-dragover');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
zone.addEventListener('drop', async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
zone.classList.remove('is-dragover');
|
||||||
|
const paths = extractDroppedPaths(event.dataTransfer);
|
||||||
|
const files = await extractDroppedHtmlFiles(event.dataTransfer);
|
||||||
|
if (!paths.length && !files.length) {
|
||||||
|
setMessage(fallback);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setMessage('');
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/drop/resolve', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ paths, files }),
|
||||||
|
});
|
||||||
|
const j = await r.json();
|
||||||
|
if (typeof onResolved === 'function') onResolved(j);
|
||||||
|
} catch (e) {
|
||||||
|
setMessage('Could not read dropped items: ' + (e.message || e));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
`
|
||||||
|
|
||||||
|
type navItem struct {
|
||||||
|
Path string
|
||||||
|
Label string
|
||||||
|
Description string
|
||||||
|
Beta bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var navItems = []navItem{
|
||||||
|
{Path: "/", Label: "Home"},
|
||||||
|
{Path: "/plec", Label: "PLEC Upload", Description: "Upload HTML to the internal PLEC server"},
|
||||||
|
{Path: "/applovin", Label: "AppLovin Playable Preview", Description: "Upload to p.applov.in (QR preview)"},
|
||||||
|
{Path: "/base64", Label: "Base64 Scanner", Description: "Find non-base64 assets in HTML"},
|
||||||
|
{Path: "/mobile", Label: "Send To Mobile", Description: "Share HTML to a phone via LAN + QR"},
|
||||||
|
{Path: "/mraid", Label: "MRAID Checker", Description: "Check MRAID requirements and best practices"},
|
||||||
|
{Path: "/mintegral", Label: "Mintegral Checker", Description: "Validate Mintegral playable ZIPs against PlayTurbo checks"},
|
||||||
|
{Path: "/playworks", Label: "Playworks Converter", Description: "Convert Playworks HTML to per-network variants", Beta: true},
|
||||||
|
{Path: "/device-simulator", Label: "Device Simulator", Description: "Preview HTML playables inside mobile device frames"},
|
||||||
|
}
|
||||||
|
|
||||||
|
func visibleNavItems(betaToolsEnabled bool) []navItem {
|
||||||
|
out := make([]navItem, 0, len(navItems))
|
||||||
|
for _, n := range navItems {
|
||||||
|
if n.Beta && !betaToolsEnabled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, n)
|
||||||
|
}
|
||||||
|
return sortNavItemsForDisplay(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortNavItemsForDisplay(items []navItem) []navItem {
|
||||||
|
out := append([]navItem(nil), items...)
|
||||||
|
for i := 0; i < len(out); i++ {
|
||||||
|
for j := i + 1; j < len(out); j++ {
|
||||||
|
if out[i].Beta && !out[j].Beta {
|
||||||
|
out[i], out[j] = out[j], out[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func betaToolCount() int {
|
||||||
|
count := 0
|
||||||
|
for _, n := range navItems {
|
||||||
|
if n.Beta {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
func navInitials(label string) string {
|
||||||
|
switch label {
|
||||||
|
case "Base64 Scanner":
|
||||||
|
return "B64"
|
||||||
|
case "AppLovin Playable Preview":
|
||||||
|
return "APP"
|
||||||
|
case "Mintegral Checker":
|
||||||
|
return "MiC"
|
||||||
|
case "Device Simulator":
|
||||||
|
return "DS"
|
||||||
|
}
|
||||||
|
words := strings.Fields(label)
|
||||||
|
if len(words) == 0 {
|
||||||
|
return "?"
|
||||||
|
}
|
||||||
|
if len(words) == 1 {
|
||||||
|
r := []rune(words[0])
|
||||||
|
if len(r) == 0 {
|
||||||
|
return "?"
|
||||||
|
}
|
||||||
|
return strings.ToUpper(string(r[0]))
|
||||||
|
}
|
||||||
|
first := []rune(words[0])
|
||||||
|
second := []rune(words[1])
|
||||||
|
if len(first) == 0 || len(second) == 0 {
|
||||||
|
return strings.ToUpper(string([]rune(label)[0]))
|
||||||
|
}
|
||||||
|
return strings.ToUpper(string(first[0]) + string(second[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Page(activePath, title, body string) string {
|
||||||
|
cfg := LoadConfig()
|
||||||
|
betaToolsEnabled := cfg.BetaToolsEnabled
|
||||||
|
var tabs strings.Builder
|
||||||
|
for _, n := range visibleNavItems(betaToolsEnabled) {
|
||||||
|
cls := ""
|
||||||
|
if n.Path == activePath {
|
||||||
|
cls = " active"
|
||||||
|
}
|
||||||
|
label := n.Label
|
||||||
|
if n.Beta {
|
||||||
|
label += `<span class="beta-pill">Beta</span>`
|
||||||
|
}
|
||||||
|
tabs.WriteString(`<button type="button" class="nav-link` + cls + `" data-path="` + n.Path + `" draggable="` + boolAttr(n.Path != "/") + `" title="` + n.Label + `"><span class="nav-icon">` + navInitials(n.Label) + `</span><span class="nav-text">` + label + `</span></button>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
betaButtonLabel := "Show beta"
|
||||||
|
if betaToolsEnabled {
|
||||||
|
betaButtonLabel = "Hide beta"
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html><head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<title>` + title + ` — HPL Toolbox</title>
|
||||||
|
<style>` + SharedCSS + `</style>
|
||||||
|
<script>` + SharedDropZoneScript + `</script>
|
||||||
|
</head><body>
|
||||||
|
<aside class="sidebar">
|
||||||
|
<div class="sidebar-header">
|
||||||
|
<span class="sidebar-title">HPL Toolbox</span>
|
||||||
|
<button id="sidebarToggle" class="sidebar-toggle" title="Toggle sidebar" aria-label="Toggle sidebar">☰</button>
|
||||||
|
</div>
|
||||||
|
<nav class="sidebar-nav">` + tabs.String() + `</nav>
|
||||||
|
</aside>
|
||||||
|
<div class="app-shell">
|
||||||
|
<div class="content">` + body + `</div>
|
||||||
|
<div class="app-footer">
|
||||||
|
<button id="betaToolsToggle" class="beta-tools-toggle" data-enabled="` + boolAttr(betaToolsEnabled) + `">` + betaButtonLabel + `</button>
|
||||||
|
<button id="updateCheck" type="button" class="app-footer-version-button" title="Check for updates">` + AppVersion + ` - JJGC 00784</button>
|
||||||
|
<button type="button" class="app-footer-link" data-path="/changelog">Changelog</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="toastBox" class="toast-box" role="status" aria-live="polite">
|
||||||
|
<span id="toastMessage" class="toast-message"></span>
|
||||||
|
<button id="toastAction" type="button" class="toast-action is-hidden">Open Repository</button>
|
||||||
|
<button id="toastClose" type="button" class="toast-close" aria-label="Close">x</button>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
if (localStorage.getItem('hplSidebarCollapsed') === 'true') {
|
||||||
|
document.body.classList.add('sidebar-collapsed');
|
||||||
|
}
|
||||||
|
document.getElementById('sidebarToggle').addEventListener('click', () => {
|
||||||
|
const collapsed = document.body.classList.toggle('sidebar-collapsed');
|
||||||
|
localStorage.setItem('hplSidebarCollapsed', collapsed ? 'true' : 'false');
|
||||||
|
});
|
||||||
|
document.querySelectorAll('[data-path]').forEach((element) => {
|
||||||
|
element.addEventListener('click', () => {
|
||||||
|
if (element.dataset.dragging === 'true') {
|
||||||
|
element.dataset.dragging = 'false';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const path = element.dataset.path;
|
||||||
|
if (path) window.location.href = path;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const TOOL_ORDER_KEY = 'hplToolbox.toolOrder.v1';
|
||||||
|
function getToolOrder() {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(localStorage.getItem(TOOL_ORDER_KEY) || '[]');
|
||||||
|
return Array.isArray(parsed) ? parsed.filter(path => typeof path === 'string') : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function setToolOrder(paths) {
|
||||||
|
localStorage.setItem(TOOL_ORDER_KEY, JSON.stringify(paths));
|
||||||
|
}
|
||||||
|
function applyStoredToolOrder(container, selector) {
|
||||||
|
if (!container) return;
|
||||||
|
const order = getToolOrder();
|
||||||
|
if (!order.length) return;
|
||||||
|
const elements = Array.from(container.querySelectorAll(selector));
|
||||||
|
const byPath = new Map(elements.map(el => [el.dataset.path, el]));
|
||||||
|
const home = byPath.get('/');
|
||||||
|
const ordered = order.map(path => byPath.get(path)).filter(Boolean);
|
||||||
|
const orderedSet = new Set(ordered);
|
||||||
|
const remaining = elements.filter(el => el !== home && !orderedSet.has(el));
|
||||||
|
if (home) container.appendChild(home);
|
||||||
|
ordered.concat(remaining).forEach(el => container.appendChild(el));
|
||||||
|
}
|
||||||
|
function setupToolReorder(container, selector) {
|
||||||
|
if (!container) return;
|
||||||
|
applyStoredToolOrder(container, selector);
|
||||||
|
let dragged = null;
|
||||||
|
container.querySelectorAll(selector).forEach(element => {
|
||||||
|
if (element.dataset.path === '/') return;
|
||||||
|
element.addEventListener('dragstart', event => {
|
||||||
|
dragged = element;
|
||||||
|
element.classList.add('dragging');
|
||||||
|
event.dataTransfer.effectAllowed = 'move';
|
||||||
|
event.dataTransfer.setData('text/plain', element.dataset.path || '');
|
||||||
|
});
|
||||||
|
element.addEventListener('dragend', () => {
|
||||||
|
element.classList.remove('dragging');
|
||||||
|
element.dataset.dragging = 'true';
|
||||||
|
dragged = null;
|
||||||
|
const paths = Array.from(container.querySelectorAll(selector))
|
||||||
|
.map(el => el.dataset.path)
|
||||||
|
.filter(path => path && path !== '/');
|
||||||
|
setToolOrder(paths);
|
||||||
|
setTimeout(() => { element.dataset.dragging = 'false'; }, 0);
|
||||||
|
});
|
||||||
|
element.addEventListener('dragover', event => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!dragged || dragged === element || element.dataset.path === '/') return;
|
||||||
|
const rect = element.getBoundingClientRect();
|
||||||
|
const after = event.clientY > rect.top + rect.height / 2;
|
||||||
|
container.insertBefore(dragged, after ? element.nextSibling : element);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setupToolReorder(document.querySelector('.sidebar-nav'), '.nav-link');
|
||||||
|
setupToolReorder(document.querySelector('.home-tools'), '.home-tool');
|
||||||
|
document.getElementById('betaToolsToggle').addEventListener('click', async (event) => {
|
||||||
|
const enabled = event.currentTarget.dataset.enabled === 'true';
|
||||||
|
await fetch('/api/betaTools', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ enabled: !enabled }),
|
||||||
|
});
|
||||||
|
window.location.reload();
|
||||||
|
});
|
||||||
|
const toastBox = document.getElementById('toastBox');
|
||||||
|
const toastMessage = document.getElementById('toastMessage');
|
||||||
|
const toastAction = document.getElementById('toastAction');
|
||||||
|
const toastClose = document.getElementById('toastClose');
|
||||||
|
let toastTimer = null;
|
||||||
|
let updateRepositoryUrl = '';
|
||||||
|
function showToast(message, status, repositoryUrl) {
|
||||||
|
window.clearTimeout(toastTimer);
|
||||||
|
updateRepositoryUrl = repositoryUrl || '';
|
||||||
|
toastMessage.textContent = message || '';
|
||||||
|
toastAction.classList.toggle('is-hidden', !updateRepositoryUrl);
|
||||||
|
toastBox.className = 'toast-box is-visible is-' + (status || 'current');
|
||||||
|
toastTimer = window.setTimeout(() => {
|
||||||
|
toastBox.classList.remove('is-visible');
|
||||||
|
}, updateRepositoryUrl ? 9000 : 5000);
|
||||||
|
}
|
||||||
|
async function checkForUpdates(showCurrent) {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/update/check');
|
||||||
|
const result = await response.json();
|
||||||
|
if (result.status === 'current' && !showCurrent) return;
|
||||||
|
showToast(result.message || 'HPL Toolbox update check finished.', result.status, result.repositoryUrl);
|
||||||
|
} catch (error) {
|
||||||
|
showToast('HPL Toolbox update check failed: ' + (error.message || error), 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.getElementById('updateCheck').addEventListener('click', () => {
|
||||||
|
checkForUpdates(true);
|
||||||
|
});
|
||||||
|
toastClose.addEventListener('click', () => {
|
||||||
|
window.clearTimeout(toastTimer);
|
||||||
|
toastBox.classList.remove('is-visible');
|
||||||
|
});
|
||||||
|
toastAction.addEventListener('click', async () => {
|
||||||
|
if (!updateRepositoryUrl) return;
|
||||||
|
await fetch('/api/open', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ url: updateRepositoryUrl }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (sessionStorage.getItem('hplToolboxUpdateChecked') !== 'true') {
|
||||||
|
sessionStorage.setItem('hplToolboxUpdateChecked', 'true');
|
||||||
|
checkForUpdates(true);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body></html>`
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolAttr(v bool) string {
|
||||||
|
if v {
|
||||||
|
return "true"
|
||||||
|
}
|
||||||
|
return "false"
|
||||||
|
}
|
||||||
|
|
||||||
|
func DropResolveEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
type droppedFile struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
}
|
||||||
|
var req struct {
|
||||||
|
Paths []string `json:"paths"`
|
||||||
|
Files []droppedFile `json:"files"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"files": []any{}, "paths": []string{}, "skipped": 0, "error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var outPaths []string
|
||||||
|
skipped := 0
|
||||||
|
addFile := func(p string) {
|
||||||
|
if !isHTMLPath(p) {
|
||||||
|
skipped++
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := strings.ToLower(filepath.Clean(p))
|
||||||
|
if seen[key] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[key] = true
|
||||||
|
outPaths = append(outPaths, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, raw := range req.Paths {
|
||||||
|
p := normalizeDroppedPath(raw)
|
||||||
|
if p == "" {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
info, err := os.Stat(p)
|
||||||
|
if err != nil {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
for _, filePath := range collectHTMLFiles(p) {
|
||||||
|
addFile(filePath)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if info.Mode().IsRegular() {
|
||||||
|
addFile(p)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
skipped++
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(req.Files) > 0 {
|
||||||
|
cleanupStaleStandaloneDropDirs()
|
||||||
|
dir, err := os.MkdirTemp("", "hpltoolbox-drop-")
|
||||||
|
if err != nil {
|
||||||
|
skipped += len(req.Files)
|
||||||
|
} else {
|
||||||
|
for _, file := range req.Files {
|
||||||
|
if !isHTMLPath(file.Name) {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name := safeStandaloneDropName(file.Name)
|
||||||
|
target := filepath.Join(dir, name)
|
||||||
|
ext := filepath.Ext(name)
|
||||||
|
base := strings.TrimSuffix(name, ext)
|
||||||
|
for i := 1; fileExists(target); i++ {
|
||||||
|
target = filepath.Join(dir, fmt.Sprintf("%s_%d%s", base, i, ext))
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(target, []byte(file.Content), 0644); err != nil {
|
||||||
|
skipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addFile(target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
files := make([]map[string]string, 0, len(outPaths))
|
||||||
|
for _, p := range outPaths {
|
||||||
|
files = append(files, map[string]string{"path": p, "name": filepath.Base(p)})
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"files": files, "paths": outPaths, "skipped": skipped})
|
||||||
|
}
|
||||||
|
|
||||||
|
func safeStandaloneDropName(name string) string {
|
||||||
|
base := filepath.Base(name)
|
||||||
|
base = strings.Map(func(r rune) rune {
|
||||||
|
switch r {
|
||||||
|
case '<', '>', ':', '"', '/', '\\', '|', '?', '*':
|
||||||
|
return '_'
|
||||||
|
default:
|
||||||
|
if r < 32 {
|
||||||
|
return '_'
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
}, base)
|
||||||
|
base = strings.TrimSpace(base)
|
||||||
|
if base == "" {
|
||||||
|
return "dropped.html"
|
||||||
|
}
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanupStaleStandaloneDropDirs() {
|
||||||
|
root := os.TempDir()
|
||||||
|
entries, err := os.ReadDir(root)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cutoff := time.Now().Add(-24 * time.Hour)
|
||||||
|
for _, entry := range entries {
|
||||||
|
if !entry.IsDir() || !strings.HasPrefix(entry.Name(), "hpltoolbox-drop-") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dir := filepath.Join(root, entry.Name())
|
||||||
|
info, err := entry.Info()
|
||||||
|
if err == nil && info.ModTime().Before(cutoff) {
|
||||||
|
_ = os.RemoveAll(dir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeDroppedPath(value string) string {
|
||||||
|
result := strings.Trim(strings.TrimSpace(value), `"'`)
|
||||||
|
if strings.HasPrefix(strings.ToLower(result), "file://") {
|
||||||
|
result = strings.TrimPrefix(result, "file://")
|
||||||
|
if decoded, err := url.PathUnescape(result); err == nil {
|
||||||
|
result = decoded
|
||||||
|
}
|
||||||
|
if len(result) >= 3 && result[0] == '/' && result[2] == ':' {
|
||||||
|
result = result[1:]
|
||||||
|
}
|
||||||
|
result = filepath.FromSlash(result)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func isHTMLPath(p string) bool {
|
||||||
|
ext := strings.ToLower(filepath.Ext(p))
|
||||||
|
return ext == ".html" || ext == ".htm"
|
||||||
|
}
|
||||||
|
|
||||||
|
func BetaToolsEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := LoadConfig()
|
||||||
|
cfg.BetaToolsEnabled = req.Enabled
|
||||||
|
if err := SaveConfig(cfg); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"ok": true})
|
||||||
|
}
|
||||||
212
standalone/main.go
Normal file
212
standalone/main.go
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
webview "github.com/jchv/go-webview2"
|
||||||
|
)
|
||||||
|
|
||||||
|
var AppVersion = "dev"
|
||||||
|
|
||||||
|
var currentHwnd atomic.Uintptr
|
||||||
|
|
||||||
|
func setupFileLogging() {
|
||||||
|
logPath := filepath.Join(userDataDir(), "debug.log")
|
||||||
|
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.SetOutput(f)
|
||||||
|
log.SetFlags(log.LstdFlags | log.Lshortfile)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
setupFileLogging()
|
||||||
|
log.Printf("HPL Toolbox starting (pid=%d)", os.Getpid())
|
||||||
|
|
||||||
|
if focusExistingInstance() {
|
||||||
|
log.Printf("Another instance is running; focused it and exiting.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
port := listener.Addr().(*net.TCPAddr).Port
|
||||||
|
log.Printf("Server listening on 127.0.0.1:%d", port)
|
||||||
|
|
||||||
|
mux := buildMux()
|
||||||
|
srv := &http.Server{Handler: mux}
|
||||||
|
go func() {
|
||||||
|
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Printf("Server error: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := writeLockFile(port); err != nil {
|
||||||
|
log.Printf("Failed to write lock file: %v", err)
|
||||||
|
}
|
||||||
|
defer removeLockFile()
|
||||||
|
|
||||||
|
webviewTmp, err := os.MkdirTemp("", "hpltoolbox-wv2-*")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to create webview temp dir: %v", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(webviewTmp)
|
||||||
|
|
||||||
|
w := webview.NewWithOptions(webview.WebViewOptions{
|
||||||
|
Debug: false,
|
||||||
|
AutoFocus: true,
|
||||||
|
DataPath: webviewTmp,
|
||||||
|
WindowOptions: webview.WindowOptions{
|
||||||
|
Title: "HPL Toolbox " + AppVersion,
|
||||||
|
Width: 1100,
|
||||||
|
Height: 720,
|
||||||
|
IconId: 1,
|
||||||
|
Center: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if w == nil {
|
||||||
|
log.Fatalln("Failed to create webview.")
|
||||||
|
}
|
||||||
|
defer w.Destroy()
|
||||||
|
|
||||||
|
// Stash HWND for the /api/focus handler.
|
||||||
|
currentHwnd.Store(uintptr(w.Window()))
|
||||||
|
|
||||||
|
w.SetSize(1100, 720, webview.HintNone)
|
||||||
|
w.Navigate(fmt.Sprintf("http://127.0.0.1:%d/", port))
|
||||||
|
w.Run()
|
||||||
|
|
||||||
|
// Window closed — shut the server down cleanly.
|
||||||
|
log.Printf("Window closed; shutting down server.")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_ = srv.Shutdown(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildMux() *http.ServeMux {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
|
// Pages
|
||||||
|
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/" && r.URL.Path != "/home" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
HomePage(w, r)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /plec", PlecPage)
|
||||||
|
mux.HandleFunc("GET /applovin", ApplovinPage)
|
||||||
|
mux.HandleFunc("GET /base64", Base64Page)
|
||||||
|
mux.HandleFunc("GET /mraid", MraidPage)
|
||||||
|
mux.HandleFunc("GET /mintegral", MintegralPage)
|
||||||
|
mux.HandleFunc("GET /mobile", MobilePage)
|
||||||
|
mux.HandleFunc("GET /playworks", PlayworksPage)
|
||||||
|
mux.HandleFunc("GET /device-simulator", DeviceSimulatorPage)
|
||||||
|
mux.HandleFunc("GET /changelog", ChangelogPage)
|
||||||
|
mux.HandleFunc("GET /assets/qrcode.min.js", MobileQrScript)
|
||||||
|
|
||||||
|
// Shared API
|
||||||
|
mux.HandleFunc("POST /api/clipboard", ClipboardEndpoint)
|
||||||
|
mux.HandleFunc("POST /api/open", OpenEndpoint)
|
||||||
|
mux.HandleFunc("POST /api/focus", FocusEndpoint)
|
||||||
|
mux.HandleFunc("POST /api/betaTools", BetaToolsEndpoint)
|
||||||
|
mux.HandleFunc("GET /api/update/check", UpdateCheckEndpoint)
|
||||||
|
mux.HandleFunc("POST /api/drop/resolve", DropResolveEndpoint)
|
||||||
|
|
||||||
|
// PLEC
|
||||||
|
mux.HandleFunc("POST /api/plec/pick", PlecPick)
|
||||||
|
mux.HandleFunc("POST /api/plec/pickFolder", PlecPickFolder)
|
||||||
|
mux.HandleFunc("POST /api/plec/upload", PlecUpload)
|
||||||
|
|
||||||
|
// AppLovin
|
||||||
|
mux.HandleFunc("POST /api/applovin/pick", ApplovinPick)
|
||||||
|
mux.HandleFunc("POST /api/applovin/pickFolder", ApplovinPickFolder)
|
||||||
|
mux.HandleFunc("POST /api/applovin/upload", ApplovinUpload)
|
||||||
|
mux.HandleFunc("POST /api/applovin/saveQr", ApplovinSaveQR)
|
||||||
|
mux.HandleFunc("POST /api/applovin/saveAllQrs", ApplovinSaveAllQRs)
|
||||||
|
|
||||||
|
// Base64
|
||||||
|
mux.HandleFunc("POST /api/base64/pickFolder", Base64PickFolder)
|
||||||
|
mux.HandleFunc("POST /api/base64/pickFiles", Base64PickFiles)
|
||||||
|
mux.HandleFunc("POST /api/base64/scan", Base64Scan)
|
||||||
|
|
||||||
|
// MRAID Checker
|
||||||
|
mux.HandleFunc("POST /api/mraid/pickFolder", MraidPickFolder)
|
||||||
|
mux.HandleFunc("POST /api/mraid/pickFiles", MraidPickFiles)
|
||||||
|
mux.HandleFunc("POST /api/mraid/scan", MraidScan)
|
||||||
|
|
||||||
|
// Mintegral Checker
|
||||||
|
mux.HandleFunc("POST /api/mintegral/pick", MintegralPick)
|
||||||
|
mux.HandleFunc("POST /api/mintegral/load", MintegralLoad)
|
||||||
|
mux.HandleFunc("GET /mintegral/runtime", MintegralRuntimePage)
|
||||||
|
mux.HandleFunc("GET /mintegral/ad", MintegralAd)
|
||||||
|
mux.HandleFunc("GET /mintegral/monitor.js", MintegralMonitor)
|
||||||
|
mux.HandleFunc("GET /mintegral/preview-util.js", MintegralPreviewUtil)
|
||||||
|
|
||||||
|
// Send To Mobile
|
||||||
|
mux.HandleFunc("POST /api/mobile/pick", MobilePick)
|
||||||
|
mux.HandleFunc("POST /api/mobile/pickFolder", MobilePickFolder)
|
||||||
|
mux.HandleFunc("POST /api/mobile/start", MobileStart)
|
||||||
|
mux.HandleFunc("POST /api/mobile/stop", MobileStop)
|
||||||
|
|
||||||
|
// Playworks Converter
|
||||||
|
mux.HandleFunc("POST /api/playworks/pickSource", PlayworksPickSource)
|
||||||
|
mux.HandleFunc("POST /api/playworks/pickOutput", PlayworksPickOutput)
|
||||||
|
mux.HandleFunc("POST /api/playworks/convert", PlayworksConvert)
|
||||||
|
|
||||||
|
// Device Simulator
|
||||||
|
mux.HandleFunc("POST /api/device-simulator/pick", DeviceSimulatorPick)
|
||||||
|
mux.HandleFunc("POST /api/device-simulator/load", DeviceSimulatorLoad)
|
||||||
|
mux.HandleFunc("GET /api/device-simulator/preview/", DeviceSimulatorPreview)
|
||||||
|
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
|
||||||
|
// FocusEndpoint brings the webview window to the foreground. Used by a second
|
||||||
|
// instance that wants to focus the running one before exiting.
|
||||||
|
func FocusEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hwnd := currentHwnd.Load()
|
||||||
|
if hwnd != 0 {
|
||||||
|
restoreAndFocus(hwnd)
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
user32 = syscall.NewLazyDLL("user32.dll")
|
||||||
|
procShowWindow = user32.NewProc("ShowWindow")
|
||||||
|
procSetForeground = user32.NewProc("SetForegroundWindow")
|
||||||
|
procIsIconic = user32.NewProc("IsIconic")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
swRestore = 9
|
||||||
|
swShow = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
func restoreAndFocus(hwnd uintptr) {
|
||||||
|
// If minimized, restore. Otherwise just ensure it's shown.
|
||||||
|
iconic, _, _ := procIsIconic.Call(hwnd)
|
||||||
|
if iconic != 0 {
|
||||||
|
_, _, _ = procShowWindow.Call(hwnd, swRestore)
|
||||||
|
} else {
|
||||||
|
_, _, _ = procShowWindow.Call(hwnd, swShow)
|
||||||
|
}
|
||||||
|
_, _, _ = procSetForeground.Call(hwnd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Silence "imported and not used" complaints if any.
|
||||||
|
var _ = unsafe.Sizeof(int(0))
|
||||||
545
standalone/mintegral.go
Normal file
545
standalone/mintegral.go
Normal file
@@ -0,0 +1,545 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
_ "embed"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed assets/mintegral/preview-util.js
|
||||||
|
var mintegralPreviewUtil string
|
||||||
|
|
||||||
|
const (
|
||||||
|
mintegralZipLimit = 5 * 1024 * 1024
|
||||||
|
mintegralHTMLLimit = 5 * 1024 * 1024
|
||||||
|
)
|
||||||
|
|
||||||
|
type mintegralCheck struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Detail string `json:"detail"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type mintegralZipEntry struct {
|
||||||
|
Name string
|
||||||
|
CompressedSize uint64
|
||||||
|
UncompressedSize uint64
|
||||||
|
Data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type mintegralRuntimePayload struct {
|
||||||
|
FileName string `json:"fileName"`
|
||||||
|
ZipSize int64 `json:"zipSize"`
|
||||||
|
HTML string `json:"html"`
|
||||||
|
Checks []mintegralCheck `json:"checks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var mintegralRuntime = struct {
|
||||||
|
sync.RWMutex
|
||||||
|
payload *mintegralRuntimePayload
|
||||||
|
}{}
|
||||||
|
|
||||||
|
func MintegralPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">Mintegral Checker</h2>
|
||||||
|
<p class="tool-description">Validates a Mintegral playable ad ZIP against PlayTurbo requirements. Runtime checks update live as you interact with the playable.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="tool-panel input-panel">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Input</h3></div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-label">Playable ZIP</div>
|
||||||
|
<div id="dropZone" class="drop-zone">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickBtn" class="secondary">Select File</button>
|
||||||
|
<button id="reloadBtn" class="secondary" style="display:none">Reload</button>
|
||||||
|
</div>
|
||||||
|
<div class="drop-zone-text">or drop a Mintegral ZIP here</div>
|
||||||
|
</div>
|
||||||
|
<div class="file-name" id="fileName" style="margin-top:8px;">(no file selected)</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="tool-panel embedded-runtime" id="runtimePanel" style="display:none">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Runtime Checker</h3></div>
|
||||||
|
<iframe id="runtimeFrame"></iframe>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.embedded-runtime { height: calc(100vh - 260px); min-height: 360px; }
|
||||||
|
.embedded-runtime iframe { width:100%; height:calc(100% - 39px); min-height:0; border:0; background:#1e1e1e; display:block; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const fileNameEl = document.getElementById('fileName');
|
||||||
|
const runtimePanel = document.getElementById('runtimePanel');
|
||||||
|
const runtimeFrame = document.getElementById('runtimeFrame');
|
||||||
|
const reloadBtn = document.getElementById('reloadBtn');
|
||||||
|
let currentPath = '';
|
||||||
|
function basename(p){ const i=Math.max(p.lastIndexOf('/'),p.lastIndexOf('\\')); return i>=0?p.slice(i+1):p; }
|
||||||
|
async function loadZip(path){
|
||||||
|
if(!path){ statusEl.textContent='Pick a ZIP first.'; return; }
|
||||||
|
currentPath = path;
|
||||||
|
statusEl.textContent = 'Reading ' + basename(path) + '...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
runtimeFrame.src = 'about:blank';
|
||||||
|
runtimePanel.style.display = 'none';
|
||||||
|
const r = await fetch('/api/mintegral/load', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({path})});
|
||||||
|
const j = await r.json();
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
if(j.error){ statusEl.textContent = 'Error: ' + j.error; return; }
|
||||||
|
fileNameEl.textContent = j.fileName + ' (' + Math.round(j.zipSize / 1024) + ' KB)';
|
||||||
|
statusEl.textContent = '';
|
||||||
|
reloadBtn.style.display = '';
|
||||||
|
runtimePanel.style.display = 'block';
|
||||||
|
runtimeFrame.src = j.runtimeUrl;
|
||||||
|
}
|
||||||
|
document.getElementById('pickBtn').addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/mintegral/pick', {method:'POST'});
|
||||||
|
const j = await r.json();
|
||||||
|
if(j.path) loadZip(j.path);
|
||||||
|
});
|
||||||
|
reloadBtn.addEventListener('click', () => loadZip(currentPath));
|
||||||
|
const dropZone = document.getElementById('dropZone');
|
||||||
|
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('is-dragover'); });
|
||||||
|
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('is-dragover'));
|
||||||
|
dropZone.addEventListener('drop', e => {
|
||||||
|
e.preventDefault();
|
||||||
|
dropZone.classList.remove('is-dragover');
|
||||||
|
const paths = extractDroppedPaths(e.dataTransfer).filter(p => /\.zip$/i.test(p));
|
||||||
|
if(!paths.length){ statusEl.textContent = 'Drop a ZIP file.'; return; }
|
||||||
|
loadZip(paths[0]);
|
||||||
|
});
|
||||||
|
</script>`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/mintegral", "Mintegral Checker", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func MintegralPick(w http.ResponseWriter, r *http.Request) {
|
||||||
|
paths := PickFiles("Select Mintegral ZIP", []FileFilter{{Name: "ZIP", Extensions: []string{"zip"}}}, false, "")
|
||||||
|
path := ""
|
||||||
|
if len(paths) > 0 {
|
||||||
|
path = paths[0]
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"path": path})
|
||||||
|
}
|
||||||
|
|
||||||
|
func MintegralLoad(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
payload, err := loadMintegralZip(req.Path)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, map[string]any{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mintegralRuntime.Lock()
|
||||||
|
mintegralRuntime.payload = payload
|
||||||
|
mintegralRuntime.Unlock()
|
||||||
|
writeJSON(w, map[string]any{
|
||||||
|
"fileName": payload.FileName,
|
||||||
|
"zipSize": payload.ZipSize,
|
||||||
|
"runtimeUrl": "/mintegral/runtime",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func MintegralRuntimePage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
mintegralRuntime.RLock()
|
||||||
|
payload := mintegralRuntime.payload
|
||||||
|
mintegralRuntime.RUnlock()
|
||||||
|
if payload == nil {
|
||||||
|
http.Error(w, "No Mintegral ZIP loaded.", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write([]byte(mintegralRuntimeHTML(payload)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func MintegralAd(w http.ResponseWriter, r *http.Request) {
|
||||||
|
mintegralRuntime.RLock()
|
||||||
|
payload := mintegralRuntime.payload
|
||||||
|
mintegralRuntime.RUnlock()
|
||||||
|
if payload == nil {
|
||||||
|
http.Error(w, "No Mintegral ZIP loaded.", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write([]byte(payload.HTML))
|
||||||
|
}
|
||||||
|
|
||||||
|
func MintegralPreviewUtil(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write([]byte(mintegralPreviewUtil))
|
||||||
|
}
|
||||||
|
|
||||||
|
func MintegralMonitor(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write([]byte(mintegralMonitorScript))
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadMintegralZip(zipPath string) (*mintegralRuntimePayload, error) {
|
||||||
|
if zipPath == "" {
|
||||||
|
return nil, fmt.Errorf("Pick a ZIP first.")
|
||||||
|
}
|
||||||
|
info, err := os.Stat(zipPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
return nil, fmt.Errorf("Expected a ZIP file, got a folder.")
|
||||||
|
}
|
||||||
|
entries, err := readMintegralZip(zipPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var index *mintegralZipEntry
|
||||||
|
for i := range entries {
|
||||||
|
if entries[i].Name == "index.html" {
|
||||||
|
index = &entries[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
htmlText := ""
|
||||||
|
if index != nil {
|
||||||
|
htmlText = string(index.Data)
|
||||||
|
}
|
||||||
|
checks := runMintegralStaticChecks(htmlText, entries, info.Size())
|
||||||
|
return &mintegralRuntimePayload{
|
||||||
|
FileName: filepath.Base(zipPath),
|
||||||
|
ZipSize: info.Size(),
|
||||||
|
HTML: injectMintegralMonitoring(htmlText),
|
||||||
|
Checks: checks,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readMintegralZip(zipPath string) ([]mintegralZipEntry, error) {
|
||||||
|
zr, err := zip.OpenReader(zipPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer zr.Close()
|
||||||
|
entries := make([]mintegralZipEntry, 0, len(zr.File))
|
||||||
|
for _, f := range zr.File {
|
||||||
|
if strings.HasSuffix(f.Name, "/") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rc, err := f.Open()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(rc)
|
||||||
|
_ = rc.Close()
|
||||||
|
if err != nil {
|
||||||
|
data = nil
|
||||||
|
}
|
||||||
|
entries = append(entries, mintegralZipEntry{
|
||||||
|
Name: filepath.ToSlash(f.Name),
|
||||||
|
CompressedSize: f.CompressedSize64,
|
||||||
|
UncompressedSize: f.UncompressedSize64,
|
||||||
|
Data: data,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func injectMintegralMonitoring(htmlText string) string {
|
||||||
|
stub := `<script src="/mintegral/preview-util.js"></script>
|
||||||
|
<script src="/mintegral/monitor.js"></script>`
|
||||||
|
if regexp.MustCompile(`(?i)<head\b[^>]*>`).MatchString(htmlText) {
|
||||||
|
return regexp.MustCompile(`(?i)<head\b[^>]*>`).ReplaceAllStringFunc(htmlText, func(m string) string {
|
||||||
|
return m + "\n" + stub
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return stub + "\n" + htmlText
|
||||||
|
}
|
||||||
|
|
||||||
|
func runMintegralStaticChecks(htmlText string, entries []mintegralZipEntry, zipSize int64) []mintegralCheck {
|
||||||
|
scripts := mintegralExtractScripts(htmlText)
|
||||||
|
return []mintegralCheck{
|
||||||
|
mintegralCheckHTML(htmlText),
|
||||||
|
mintegralCheckCTA(scripts),
|
||||||
|
mintegralCheckGameEnd(scripts),
|
||||||
|
mintegralCheckGameReady(htmlText, scripts),
|
||||||
|
mintegralCheckGameStart(scripts),
|
||||||
|
mintegralCheckGameClose(scripts),
|
||||||
|
mintegralCheckFileHandling(htmlText),
|
||||||
|
mintegralCheckFileSpec(entries, zipSize),
|
||||||
|
mintegralCheckStorage(scripts),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralExtractScripts(htmlText string) string {
|
||||||
|
re := regexp.MustCompile(`(?is)<script\b[^>]*>(.*?)</script>`)
|
||||||
|
matches := re.FindAllStringSubmatch(htmlText, -1)
|
||||||
|
parts := make([]string, 0, len(matches))
|
||||||
|
for _, m := range matches {
|
||||||
|
parts = append(parts, m[1])
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckHTML(htmlText string) mintegralCheck {
|
||||||
|
issues := []string{}
|
||||||
|
if !regexp.MustCompile(`(?i)^\s*<!DOCTYPE\s+html\s*>`).MatchString(htmlText) {
|
||||||
|
issues = append(issues, "Missing <!DOCTYPE html>")
|
||||||
|
}
|
||||||
|
if !regexp.MustCompile(`(?i)<meta\b[^>]*\bcharset\s*=`).MatchString(htmlText) {
|
||||||
|
issues = append(issues, "Missing charset meta tag")
|
||||||
|
}
|
||||||
|
if !regexp.MustCompile(`(?i)<meta\b[^>]*\bname\s*=\s*["']viewport["']`).MatchString(htmlText) {
|
||||||
|
issues = append(issues, "Missing viewport meta tag")
|
||||||
|
}
|
||||||
|
if regexp.MustCompile(`(?i)<script\b[^>]*\btype\s*=\s*["']module["']`).MatchString(htmlText) {
|
||||||
|
issues = append(issues, `type="module" on script tag`)
|
||||||
|
}
|
||||||
|
if regexp.MustCompile(`(?i)<script\b[^>]*\bcrossorigin\b`).MatchString(htmlText) {
|
||||||
|
issues = append(issues, "crossorigin attribute on script tag")
|
||||||
|
}
|
||||||
|
if !regexp.MustCompile(`(?i)</html\s*>`).MatchString(htmlText) {
|
||||||
|
issues = append(issues, "Missing </html> closing tag")
|
||||||
|
}
|
||||||
|
if len(issues) == 0 {
|
||||||
|
return mintegralCheck{ID: "html-requirements", Status: "pass", Detail: "Valid HTML structure"}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "html-requirements", Status: "fail", Detail: strings.Join(issues, "; ")}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckCTA(scripts string) mintegralCheck {
|
||||||
|
if regexp.MustCompile(`\bwindow\.install\b|\btypeof\s+window\.install`).MatchString(scripts) {
|
||||||
|
return mintegralCheck{ID: "cta-method", Status: "pass", Detail: "window.install() referenced in scripts"}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "cta-method", Status: "fail", Detail: "window.install() not found - Mintegral CTA requires window.install()"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckGameEnd(scripts string) mintegralCheck {
|
||||||
|
if regexp.MustCompile(`\bgameEnd\b`).MatchString(scripts) {
|
||||||
|
return mintegralCheck{ID: "game-end", Status: "pass", Detail: "gameEnd() found in scripts"}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "game-end", Status: "fail", Detail: "gameEnd() not found"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckGameReady(htmlText, scripts string) mintegralCheck {
|
||||||
|
inScript := regexp.MustCompile(`\bgameReady\b`).MatchString(scripts)
|
||||||
|
inOnload := regexp.MustCompile(`(?i)\bonload\s*=\s*["'][^"']*\bgameReady\b`).MatchString(htmlText)
|
||||||
|
if !inScript && !inOnload {
|
||||||
|
return mintegralCheck{ID: "game-ready", Status: "fail", Detail: "gameReady() not found"}
|
||||||
|
}
|
||||||
|
if !inOnload {
|
||||||
|
return mintegralCheck{ID: "game-ready", Status: "warn", Detail: `gameReady() found but not wired to body onload - Mintegral requires onload="gameReady()"`}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "game-ready", Status: "pass", Detail: "gameReady() wired to body onload"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckGameStart(scripts string) mintegralCheck {
|
||||||
|
if regexp.MustCompile(`\bgameStart\b`).MatchString(scripts) {
|
||||||
|
return mintegralCheck{ID: "game-start", Status: "pass", Detail: "gameStart() found in scripts"}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "game-start", Status: "fail", Detail: "gameStart() not found"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckGameClose(scripts string) mintegralCheck {
|
||||||
|
if regexp.MustCompile(`\bgameClose\b`).MatchString(scripts) {
|
||||||
|
return mintegralCheck{ID: "game-close", Status: "pass", Detail: "gameClose() found in scripts"}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "game-close", Status: "fail", Detail: "gameClose() not found"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckFileHandling(htmlText string) mintegralCheck {
|
||||||
|
re := regexp.MustCompile(`(?i)(?:src|href|action)\s*=\s*["'](https?://[^"']+)["']|url\s*\(\s*["']?(https?://[^)"'\s]+)`)
|
||||||
|
matches := re.FindAllStringSubmatch(htmlText, -1)
|
||||||
|
seen := map[string]bool{}
|
||||||
|
found := []string{}
|
||||||
|
for _, m := range matches {
|
||||||
|
u := m[1]
|
||||||
|
if u == "" {
|
||||||
|
u = m[2]
|
||||||
|
}
|
||||||
|
if u != "" && !seen[u] {
|
||||||
|
seen[u] = true
|
||||||
|
found = append(found, u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(found) == 0 {
|
||||||
|
return mintegralCheck{ID: "file-handling", Status: "pass", Detail: "All assets are inline - no external URLs detected"}
|
||||||
|
}
|
||||||
|
detail := fmt.Sprintf("%d external URL(s): %s", len(found), strings.Join(found[:minInt(2, len(found))], ", "))
|
||||||
|
if len(found) > 2 {
|
||||||
|
detail += fmt.Sprintf(" (+%d more)", len(found)-2)
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "file-handling", Status: "fail", Detail: detail}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckFileSpec(entries []mintegralZipEntry, zipSize int64) mintegralCheck {
|
||||||
|
issues := []string{}
|
||||||
|
var index *mintegralZipEntry
|
||||||
|
for i := range entries {
|
||||||
|
if entries[i].Name == "index.html" {
|
||||||
|
index = &entries[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if index == nil {
|
||||||
|
nested := ""
|
||||||
|
for _, e := range entries {
|
||||||
|
if regexp.MustCompile(`(?i)/index\.html$`).MatchString(e.Name) {
|
||||||
|
nested = e.Name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if nested != "" {
|
||||||
|
issues = append(issues, fmt.Sprintf("index.html found at '%s' - must be at ZIP root", nested))
|
||||||
|
} else {
|
||||||
|
issues = append(issues, "index.html not found in ZIP")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if zipSize > mintegralZipLimit {
|
||||||
|
issues = append(issues, fmt.Sprintf("ZIP size %.2f MB exceeds 5 MB limit", float64(zipSize)/1024/1024))
|
||||||
|
}
|
||||||
|
if index != nil && index.UncompressedSize > mintegralHTMLLimit {
|
||||||
|
issues = append(issues, fmt.Sprintf("index.html %.2f MB uncompressed exceeds 5 MB", float64(index.UncompressedSize)/1024/1024))
|
||||||
|
}
|
||||||
|
if len(issues) > 0 {
|
||||||
|
return mintegralCheck{ID: "file-spec", Status: "fail", Detail: strings.Join(issues, "; ")}
|
||||||
|
}
|
||||||
|
extras := []string{}
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.Name != "index.html" {
|
||||||
|
extras = append(extras, e.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sizeStr := fmt.Sprintf("index.html %.0f KB, ZIP %.0f KB", float64(index.UncompressedSize)/1024, float64(zipSize)/1024)
|
||||||
|
if len(extras) > 0 {
|
||||||
|
return mintegralCheck{ID: "file-spec", Status: "warn", Detail: fmt.Sprintf("%s; %d extra file(s) in ZIP (%s)", sizeStr, len(extras), strings.Join(extras, ", "))}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "file-spec", Status: "pass", Detail: sizeStr}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralCheckStorage(scripts string) mintegralCheck {
|
||||||
|
issues := []string{}
|
||||||
|
if regexp.MustCompile(`\blocalStorage\s*\.\s*setItem\s*\(`).MatchString(scripts) {
|
||||||
|
issues = append(issues, "localStorage.setItem")
|
||||||
|
}
|
||||||
|
if regexp.MustCompile(`\bsessionStorage\s*\.\s*setItem\s*\(`).MatchString(scripts) {
|
||||||
|
issues = append(issues, "sessionStorage.setItem")
|
||||||
|
}
|
||||||
|
if regexp.MustCompile(`\bdocument\.cookie\s*=`).MatchString(scripts) {
|
||||||
|
issues = append(issues, "document.cookie write")
|
||||||
|
}
|
||||||
|
if len(issues) == 0 {
|
||||||
|
return mintegralCheck{ID: "storage", Status: "pass", Detail: "No persistent storage writes detected"}
|
||||||
|
}
|
||||||
|
return mintegralCheck{ID: "storage", Status: "fail", Detail: "Forbidden storage write(s): " + strings.Join(issues, ", ")}
|
||||||
|
}
|
||||||
|
|
||||||
|
func minInt(a, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintegralRuntimeHTML(payload *mintegralRuntimePayload) string {
|
||||||
|
boot, _ := json.Marshal(map[string]any{
|
||||||
|
"fileName": payload.FileName,
|
||||||
|
"zipSize": payload.ZipSize,
|
||||||
|
"checks": payload.Checks,
|
||||||
|
})
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||||
|
<title>Mintegral Runtime Checker</title>
|
||||||
|
<style>
|
||||||
|
:root{color-scheme:dark;--gap-xs:4px;--gap-sm:8px;--gap-md:12px;--radius:4px;--border:#333;--panel:#252526;--panel-soft:rgba(128,128,128,.08);--fg:#ddd;--muted:#a7a7a7;--ok:#89d185;--err:#f48771;--warn:#ffd580}
|
||||||
|
*{box-sizing:border-box}html,body{width:100%;height:100%;overflow:hidden}body{margin:0;background:#1e1e1e;color:var(--fg);font-family:Segoe UI,Arial,sans-serif;font-size:13px}
|
||||||
|
main{height:100vh;display:grid;grid-template-columns:minmax(360px,1fr) minmax(320px,420px);gap:var(--gap-md);padding:var(--gap-md);overflow:hidden}
|
||||||
|
.panel{border:1px solid var(--border);background:var(--panel-soft);border-radius:var(--radius);overflow:hidden}.head{display:flex;align-items:center;justify-content:space-between;gap:var(--gap-md);padding:10px 12px;border-bottom:1px solid var(--border);background:var(--panel)}
|
||||||
|
h1{margin:0;font-size:12px;font-weight:700;letter-spacing:.45px;text-transform:uppercase}.sub{color:var(--muted);font-size:12px;overflow-wrap:anywhere}.head-meta{display:flex;align-items:center;justify-content:flex-end;gap:6px;min-width:0;white-space:nowrap}.head-meta .sub{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.head-meta .sub+.sub::before{content:"|";margin-right:6px;color:var(--border)}
|
||||||
|
.title-actions{display:flex;gap:var(--gap-xs)}button{min-height:28px;padding:5px 12px;border:1px solid transparent;border-radius:var(--radius);background:#0e639c;color:#fff;font:inherit;cursor:pointer}.icon-btn{width:28px;height:28px;min-height:28px;padding:0;display:grid;place-items:center;font-size:15px;line-height:1;background:#3a3d41;color:#ddd;border-color:#444}.icon-btn[aria-pressed=true]{color:var(--ok)}
|
||||||
|
.runtime-side{display:grid;grid-template-rows:minmax(0,1fr);min-height:0}.playable-panel{min-height:0;display:flex;flex-direction:column}.playable-body{min-height:0;flex:1;display:flex;flex-direction:column;padding:10px}.preview-stage{min-height:0;flex:1;display:grid;place-items:center;overflow:hidden;container-type:size}.device{width:min(100cqw,calc(100cqh*.5625));max-width:100%;aspect-ratio:9/16;margin:auto}.screen{position:relative;width:100%;height:100%;background:#000;border-radius:4px;overflow:hidden}iframe{position:absolute;inset:0;width:100%;height:100%;border:0;background:#000}
|
||||||
|
.tab-panel{min-height:0;display:flex;flex-direction:column}.tabs{display:flex;gap:var(--gap-xs);padding:8px 8px 0;background:var(--panel);border-bottom:1px solid var(--border)}.tab{min-height:28px;padding:4px 10px;background:#3a3d41;color:#ddd;border-color:#444;border-bottom:0;border-radius:var(--radius) var(--radius) 0 0}.tab.active{background:var(--panel-soft)}.tab-content{min-height:0;flex:1;display:none;overflow:auto}.tab-content.active{display:block}
|
||||||
|
ol{list-style:none;margin:0;padding:0}.check{display:flex;gap:10px;padding:10px 12px;border-bottom:1px solid var(--border)}.num{flex:0 0 22px;height:22px;border:1px solid var(--border);border-radius:50%;display:grid;place-items:center;color:var(--muted);background:var(--panel);font-size:10px;font-weight:700}.label{font-size:12px;font-weight:600}.detail{margin-top:3px;color:var(--muted);font-size:11px;line-height:1.35;overflow-wrap:anywhere}.badge{display:inline-flex;min-height:18px;margin-left:6px;padding:1px 6px;border:1px solid var(--border);border-radius:999px;font-size:11px}.badge.pass{color:var(--ok);background:rgba(137,209,133,.12)}.badge.fail{color:var(--err);background:rgba(244,135,113,.14)}.badge.warn{color:var(--warn);background:rgba(210,153,34,.16)}.badge.waiting{color:var(--muted)}
|
||||||
|
ul.log{list-style:none;margin:0;padding:0;overflow:auto;font-family:Consolas,monospace;font-size:12px;height:100%}ul.log li{display:flex;gap:8px;padding:4px 8px;border-bottom:1px solid var(--border)}.time{color:var(--muted);flex:0 0 auto}.msg{white-space:pre-wrap;overflow-wrap:anywhere;min-width:0}.level{font-weight:700}.pass{color:var(--ok)}.fail{color:var(--err)}.warn{color:var(--warn)}
|
||||||
|
@media(max-width:900px){html,body{overflow:auto}main{height:auto;min-height:100vh;grid-template-columns:1fr;overflow:visible}.playable-panel{height:min(72vh,640px);min-height:360px}.tab-panel{min-height:360px}}@media(max-height:700px) and (max-width:900px){.playable-panel{height:calc(100vh - 24px);min-height:300px}}
|
||||||
|
</style></head><body>
|
||||||
|
<main>
|
||||||
|
<section class="runtime-side"><section class="panel playable-panel"><div class="head"><h1>Playable</h1><div class="title-actions"><button id="muteBtn" class="icon-btn" title="Mute" aria-label="Mute" aria-pressed="false">🔇</button><button id="reloadBtn" class="icon-btn" title="Reload" aria-label="Reload">↻</button></div></div><div class="playable-body"><div class="preview-stage"><div class="device"><div class="screen"><iframe id="adFrame" src="/mintegral/ad?preview=true&loading=0&review=1"></iframe></div></div></div></div></section></section>
|
||||||
|
<section class="panel tab-panel"><div class="head"><h1>Checks</h1><div class="head-meta"><div class="sub" id="bridge">Starting...</div><div class="sub" id="timer">60s</div></div></div><div class="tabs"><button class="tab active" data-tab="checksTab">Checklist</button><button class="tab" data-tab="eventsTab">Events</button></div><ol class="tab-content active" id="checksTab"></ol><ul class="log tab-content" id="eventsTab"></ul></section>
|
||||||
|
</main>
|
||||||
|
<script>const BOOT=` + string(boot) + `;</script>
|
||||||
|
<script>` + mintegralRuntimeJS + `</script>
|
||||||
|
</body></html>`
|
||||||
|
}
|
||||||
|
|
||||||
|
const mintegralRuntimeJS = `
|
||||||
|
const CHECKS=[
|
||||||
|
{id:'html-requirements',num:1,label:'HTML Requirements',runtimeEvent:null},{id:'cta-method',num:2,label:'CTA Call Method',runtimeEvent:'install'},{id:'game-end',num:3,label:'Game End Call Method',runtimeEvent:'gameEnd'},{id:'game-ready',num:4,label:'Game Ready Call Method',runtimeEvent:'gameReady'},{id:'game-start',num:5,label:'Game Start Call Method',runtimeEvent:'gameStart'},{id:'game-close',num:6,label:'Game Close Call Method',runtimeEvent:'gameClose'},{id:'file-handling',num:7,label:'File Handling Method',runtimeEvent:null},{id:'file-spec',num:8,label:'File Spec',runtimeEvent:null},{id:'storage',num:9,label:'Storage Requirements',runtimeEvent:null},{id:'code-exception',num:10,label:'Code Exception',runtimeEvent:'exception'}];
|
||||||
|
const EVENT_TO_CHECK={};CHECKS.forEach(c=>{if(c.runtimeEvent)EVENT_TO_CHECK[c.runtimeEvent]=c.id;});
|
||||||
|
const SDK_TYPE_TO_CHECK={game_ready:'game-ready',game_end:'game-end',game_start:'game-start',game_close:'game-close',install:'cta-method',outer_chain:'file-handling',base64:'file-handling',code:'code-exception'};
|
||||||
|
const state={checks:{},seconds:0,muted:false,connected:false,timer:null,timeout:60,codeCleanAfter:5,hasSentNoRetry:false};
|
||||||
|
CHECKS.forEach(c=>state.checks[c.id]={status:'pending',detail:'',runtimeStatus:c.runtimeEvent?'waiting':null,runtimeDetail:''});
|
||||||
|
BOOT.checks.forEach(r=>{const ch=state.checks[r.id];if(ch){ch.status=r.status;ch.detail=r.detail;}});
|
||||||
|
state.checks['code-exception'].status='pass';state.checks['code-exception'].runtimeStatus='monitoring';
|
||||||
|
['cta-method','game-end','game-ready','game-start','game-close'].forEach(id=>{if(state.checks[id].status==='fail')state.checks[id].runtimeStatus=null;});
|
||||||
|
const checksEl=document.getElementById('checksTab'),eventLog=document.getElementById('eventsTab'),adFrame=document.getElementById('adFrame'),muteBtn=document.getElementById('muteBtn');
|
||||||
|
document.querySelectorAll('.tab').forEach(btn=>btn.addEventListener('click',()=>{document.querySelectorAll('.tab').forEach(b=>b.classList.remove('active'));document.querySelectorAll('.tab-content').forEach(p=>p.classList.remove('active'));btn.classList.add('active');document.getElementById(btn.dataset.tab).classList.add('active');}));
|
||||||
|
function resetChecks(){if(state.timer)clearInterval(state.timer);state.seconds=0;state.connected=false;state.hasSentNoRetry=false;CHECKS.forEach(c=>state.checks[c.id]={status:'pending',detail:'',runtimeStatus:c.runtimeEvent?'waiting':null,runtimeDetail:''});BOOT.checks.forEach(r=>{const ch=state.checks[r.id];if(ch){ch.status=r.status;ch.detail=r.detail;}});state.checks['code-exception'].status='pass';state.checks['code-exception'].runtimeStatus='monitoring';['cta-method','game-end','game-ready','game-start','game-close'].forEach(id=>{if(state.checks[id].status==='fail')state.checks[id].runtimeStatus=null;});eventLog.innerHTML='';document.getElementById('bridge').textContent='Starting...';document.getElementById('timer').textContent=state.timeout+'s';render();state.timer=startRuntimeTimer();}
|
||||||
|
function esc(s){return String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}
|
||||||
|
function addLog(list,name,cls,msg){const d=new Date(),li=document.createElement('li');li.innerHTML='<span class="time">'+String(d.getMinutes()).padStart(2,'0')+':'+String(d.getSeconds()).padStart(2,'0')+'</span><span class="level '+(cls||'')+'">'+esc(name)+'</span><span class="msg">'+esc(msg||'')+'</span>';list.appendChild(li);list.scrollTop=list.scrollHeight;}
|
||||||
|
function render(){checksEl.innerHTML=CHECKS.map(c=>{const ch=state.checks[c.id];let s=ch.status,d=ch.detail;if(ch.runtimeStatus==='waiting'&&ch.status==='pass'){s='waiting';d=ch.detail+' - awaiting runtime confirmation';}else if(ch.runtimeStatus==='monitoring'){s='waiting';d='Monitoring for exceptions...';}else if(ch.runtimeStatus==='pass'){s='pass';d=(ch.detail||'')+(ch.runtimeDetail?' - '+ch.runtimeDetail:'');}else if(ch.runtimeStatus==='fail'){s='fail';d=ch.runtimeDetail||ch.detail;}else if(ch.runtimeStatus==='timeout'&&ch.status==='pass'){s='warn';d=ch.detail+' - not fired within '+state.timeout+'s';}else if(ch.runtimeStatus==='clean'){s='pass';d='No exceptions detected';}return '<li class="check"><span class="num">'+c.num+'</span><span><div class="label">'+esc(c.label)+' <span class="badge '+s+'">'+s.toUpperCase()+'</span></div><div class="detail">'+esc(d||'')+'</div></span></li>';}).join('');}
|
||||||
|
function sdkCheck(type,value,msg){const id=SDK_TYPE_TO_CHECK[type],ch=state.checks[id];if(!ch)return;const pass=value===1||value===true;if(type==='code'){ch.status='fail';ch.runtimeStatus='fail';ch.runtimeDetail=msg||'JS error detected';addLog(eventLog,'code error','fail',ch.runtimeDetail);}else if(type==='outer_chain'){ch.runtimeStatus=pass?'pass':'fail';ch.runtimeDetail=pass?'No external resources at runtime':'External resources detected at runtime';addLog(eventLog,type,pass?'pass':'fail',ch.runtimeDetail);}else if(type==='base64'){if(!pass){ch.status='fail';ch.runtimeStatus='fail';ch.runtimeDetail='Non-JS/HTML assets must be base64';addLog(eventLog,type,'warn',ch.runtimeDetail);}}else{if(pass&&(ch.runtimeStatus==='waiting'||ch.runtimeStatus===null)){ch.runtimeStatus='pass';ch.runtimeDetail='Confirmed by SDK at '+state.seconds+'s';addLog(eventLog,type,'pass','');}else if(!pass&&(ch.runtimeStatus==='waiting'||ch.runtimeStatus===null)){ch.runtimeStatus='fail';ch.runtimeDetail=type+' not defined';addLog(eventLog,type,'warn',ch.runtimeDetail);}}render();done();}
|
||||||
|
function inferAll(text){const s=String(text||''),out=[];if(/(^|[^a-z])gameReady([^a-z]|$)|previewer:gameReady|game_ready|\bDISPLAYED\b|\bLOADED\b/i.test(s))out.push('gameReady');if(/(^|[^a-z])gameStart([^a-z]|$)|previewer:gameStart|game_start|\bCHALLENGE_STARTED\b/i.test(s))out.push('gameStart');if(/(^|[^a-z])gameEnd([^a-z]|$)|previewer:gameEnd|game_end|\bCHALLENGE_SOLVED\b|\bENDCARD_SHOWN\b/i.test(s))out.push('gameEnd');if(/(^|[^a-z])gameClose([^a-z]|$)|previewer:gameClose|game_close/i.test(s))out.push('gameClose');if(/(^|[^a-z])install([^a-z]|$)|previewer:install|\bCTA_CLICKED\b/i.test(s))out.push('install');return out;}
|
||||||
|
function handle(msg){const name=msg.name,extra=msg.extra||{};if(name==='__ping__'){state.connected=true;document.getElementById('bridge').textContent='Monitor connected';addLog(eventLog,'Monitor connected','pass','');return;}if(name==='sdkCheck'){sdkCheck(extra.type,extra.value,extra.msg||'');return;}if(name==='console'){inferAll(extra.text||'').forEach(ev=>handle({name:ev,extra:{source:'console'}}));return;}if(name==='diagnostic'){addLog(eventLog,extra.label||'diagnostic','warn',extra.detail||'');return;}if(name==='audioContext'){addLog(eventLog,'Audio captured','pass',extra.routed?'master gain ready':'context only');return;}if(name==='exception'){const ch=state.checks['code-exception'];ch.status='fail';ch.runtimeStatus='fail';ch.runtimeDetail=extra.message||'Unhandled exception';addLog(eventLog,'exception','fail',ch.runtimeDetail);render();done();return;}const id=EVENT_TO_CHECK[name];if(id){const ch=state.checks[id];if(ch.runtimeStatus==='waiting'||ch.runtimeStatus===null){ch.runtimeStatus='pass';ch.runtimeDetail=(extra.source==='console'?'Seen in console at ':'Fired at ')+state.seconds+'s';addLog(eventLog,name,'pass',extra.source==='console'?'from console':'');render();done();}}}
|
||||||
|
window.__hplMtgNotify=(name,extra)=>handle({name,extra:extra||{}});
|
||||||
|
window.addEventListener('message',e=>{const m=e.data;if(!m)return;if(m.type==='lifecycle')handle(m);else if(typeof m.type==='string'&&m.type.startsWith('previewer:')){const map={'previewer:gameReady':'gameReady','previewer:gameStart':'gameStart','previewer:install':'install','previewer:gameEnd':'gameEnd','previewer:gameClose':'gameClose'};if(map[m.type])handle({name:map[m.type],extra:{}});if(m.type==='previewer:review'&&m.data&&Array.isArray(m.data.reviewResult)){if(!state.hasSentNoRetry){state.hasSentNoRetry=true;try{adFrame.contentWindow.postMessage({type:'previewer:review',data:{reviewResult:{no_game_retry:true}}},'*');}catch(e){}}m.data.reviewResult.forEach(r=>sdkCheck(r.type,r.value,r.msg||''));}}});
|
||||||
|
function applyMute(){try{const cw=adFrame.contentWindow;if(!cw)return;cw.__hplMuted=state.muted;if(typeof cw.__hplApplyMutedState==='function')cw.__hplApplyMutedState();(cw.__hplMasterGains||[]).forEach(g=>{try{if(g&&g.gain)g.gain.value=state.muted?0:1;}catch(e){}});(cw.__hplMediaElements||[]).forEach(el=>{try{el.muted=state.muted;el.volume=state.muted?0:1;}catch(e){}});}catch(e){}}
|
||||||
|
function renderMuteButton(){muteBtn.innerHTML=state.muted?'🔈':'🔇';muteBtn.title=state.muted?'Unmute':'Mute';muteBtn.setAttribute('aria-label',state.muted?'Unmute':'Mute');muteBtn.setAttribute('aria-pressed',state.muted?'true':'false');}
|
||||||
|
muteBtn.onclick=()=>{state.muted=!state.muted;renderMuteButton();applyMute();addLog(eventLog,state.muted?'Muted':'Unmuted','pass','');};
|
||||||
|
document.getElementById('reloadBtn').onclick=()=>{resetChecks();document.getElementById('bridge').textContent='Reloading...';adFrame.src='/mintegral/ad?preview=true&loading=0&review=1&t='+Date.now();};
|
||||||
|
['pointerdown','click','touchstart','keydown'].forEach(evt=>window.addEventListener(evt,()=>setTimeout(applyMute,0),true));
|
||||||
|
function markCodeClean(){const ch=state.checks['code-exception'];if(ch&&ch.runtimeStatus==='monitoring'){ch.runtimeStatus='clean';ch.runtimeDetail='No exceptions detected';addLog(eventLog,'code clean','pass',ch.runtimeDetail);render();}}
|
||||||
|
function done(){const othersDone=CHECKS.every(c=>c.id==='code-exception'||!c.runtimeEvent||state.checks[c.id].runtimeStatus!=='waiting');if(othersDone)markCodeClean();if(CHECKS.every(c=>!c.runtimeEvent||!['waiting','monitoring'].includes(state.checks[c.id].runtimeStatus))){clearInterval(state.timer);document.getElementById('timer').textContent='Runtime complete';}}
|
||||||
|
function startRuntimeTimer(){return setInterval(()=>{state.seconds++;document.getElementById('timer').textContent=Math.max(0,state.timeout-state.seconds)+'s';if(state.seconds===2&&!state.connected){document.getElementById('bridge').textContent='Monitor not connected';addLog(eventLog,'Monitor not connected','fail','Check browser DevTools console for blocked inline script/CSP errors.');}if(state.seconds>=state.codeCleanAfter)markCodeClean();done();if(state.seconds>=state.timeout){clearInterval(state.timer);CHECKS.forEach(c=>{const ch=state.checks[c.id];if(ch.runtimeStatus==='waiting')ch.runtimeStatus='timeout';if(ch.runtimeStatus==='monitoring'){ch.runtimeStatus='clean';ch.runtimeDetail='No exceptions detected';}});render();document.getElementById('timer').textContent='Runtime complete';}},1000);}
|
||||||
|
state.timer=startRuntimeTimer();renderMuteButton();render();
|
||||||
|
`
|
||||||
|
|
||||||
|
const mintegralMonitorScript = `
|
||||||
|
(function(){
|
||||||
|
window.__hplMtgEvents=window.__hplMtgEvents||[];
|
||||||
|
function notify(n,extra){window.__hplMtgEvents.push({name:n,extra:extra||{}});try{if(typeof parent.__hplMtgNotify==='function')parent.__hplMtgNotify(n,extra||{});}catch(e){}try{parent.postMessage({type:'lifecycle',name:n,extra:extra||{}},'*');}catch(e){}}
|
||||||
|
notify('__ping__');
|
||||||
|
function applyMutedState(){var muted=!!window.__hplMuted;try{(window.__hplMasterGains||[]).forEach(function(g){try{if(g&&g.gain)g.gain.value=muted?0:1;}catch(e){}});(window.__hplMediaElements||[]).forEach(function(el){try{el.muted=muted;el.volume=muted?0:1;}catch(e){}});}catch(e){}}
|
||||||
|
window.__hplApplyMutedState=applyMutedState;
|
||||||
|
try{(function(){var OrigAC=window.AudioContext||window.webkitAudioContext;if(!OrigAC||OrigAC.__hplProxy)return;window.__hplAudioContexts=[];window.__hplMasterGains=[];window.__hplAudioDestinations=[];function ACProxy(opts){var ctx=arguments.length?new OrigAC(opts):new OrigAC();var dest=ctx.destination,gain=null;try{gain=ctx.createGain();gain.gain.value=window.__hplMuted?0:1;gain.connect(dest);if(window.AudioNode&&window.AudioNode.prototype&&!window.AudioNode.prototype.connect.__hpl){var origConnect=window.AudioNode.prototype.connect;var connectProxy=function(target){var args=Array.prototype.slice.call(arguments);try{var idx=window.__hplAudioDestinations.indexOf(args[0]);if(idx>=0&&window.__hplMasterGains[idx])args[0]=window.__hplMasterGains[idx];}catch(e){}return origConnect.apply(this,args);};connectProxy.__hpl=true;window.AudioNode.prototype.connect=connectProxy;}}catch(e){}window.__hplAudioContexts.push(ctx);if(gain)window.__hplMasterGains.push(gain);if(gain)window.__hplAudioDestinations.push(dest);notify('audioContext',{state:ctx.state||'',routed:!!gain});return ctx;}ACProxy.prototype=OrigAC.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(ACProxy,OrigAC);ACProxy.__hplProxy=true;window.AudioContext=ACProxy;window.webkitAudioContext=ACProxy;})();}catch(e){}
|
||||||
|
try{window.__hplMediaElements=[];var mediaPlay=window.HTMLMediaElement&&window.HTMLMediaElement.prototype&&window.HTMLMediaElement.prototype.play;if(mediaPlay&&!mediaPlay.__hpl){var playProxy=function(){window.__hplMediaElements.push(this);applyMutedState();notify('audioContext',{state:'media-play',routed:true});return mediaPlay.apply(this,arguments);};playProxy.__hpl=true;window.HTMLMediaElement.prototype.play=playProxy;}}catch(e){}
|
||||||
|
function patchMwInit(obj){if(!obj||obj.__hplMwPatched)return;obj.__hplMwPatched=true;obj._hasReview=function(){return true;};obj._isPreview=function(){return true;};var _oe=obj.emitCheckData;if(typeof _oe==='function'){obj.emitCheckData=function(d){_oe.call(obj,d);if(d&&d.type)notify('sdkCheck',{type:d.type,value:d.value,msg:d.msg||''});};}}
|
||||||
|
var _mwInit=window.MW_INIT||null;patchMwInit(_mwInit);try{Object.defineProperty(window,'MW_INIT',{configurable:true,enumerable:true,get:function(){return _mwInit;},set:function(obj){_mwInit=obj;patchMwInit(obj);}});}catch(e){}
|
||||||
|
var _owp=window.postMessage;window.postMessage=function(data,origin,transfer){if(data&&typeof data.type==='string'){var pm={'previewer:gameReady':'gameReady','previewer:gameStart':'gameStart','previewer:gameEnd':'gameEnd','previewer:gameClose':'gameClose','previewer:install':'install','previewer:gameRetry':'gameRetry'};if(pm[data.type])notify(pm[data.type]);}return _owp.apply(this,arguments);};
|
||||||
|
function mkAccess(name,onCall){var existing,_v;try{existing=window[name];Object.defineProperty(window,name,{configurable:true,enumerable:true,get:function(){return _v;},set:function(fn){var orig=fn;if(typeof orig==='function'){var w=function(){onCall();return orig.apply(this,arguments);};w.__hpl=true;_v=w;}else{_v=orig;}}});if(typeof existing==='function')window[name]=existing;}catch(e){}}
|
||||||
|
var _lh={gameReady:function(){notify('gameReady');setTimeout(function(){notify('sdkCheck',{type:'game_start',value:typeof window.gameStart==='function'?1:0});notify('sdkCheck',{type:'game_close',value:typeof window.gameClose==='function'?1:0});},100);},gameEnd:function(){notify('sdkCheck',{type:'game_end',value:1});},gameStart:function(){notify('sdkCheck',{type:'game_start',value:1});},gameClose:function(){notify('sdkCheck',{type:'game_close',value:1});},install:function(){notify('sdkCheck',{type:'install',value:1});}};
|
||||||
|
mkAccess('gameReady',_lh.gameReady);mkAccess('gameEnd',_lh.gameEnd);mkAccess('gameStart',_lh.gameStart);mkAccess('gameClose',_lh.gameClose);if(typeof window.install!=='function'){var _installW=function(){_lh.install();};_installW.__hpl=true;window.install=_installW;}
|
||||||
|
window.addEventListener('load',function(){Object.keys(_lh).forEach(function(name){var fn=window[name];if(typeof fn==='function'&&!fn.__hpl){var orig=fn,h=_lh[name];var w=function(){h();return orig.apply(this,arguments);};w.__hpl=true;try{window[name]=w;}catch(e){}}else if(typeof fn!=='function'){var ww=function(){_lh[name]();};ww.__hpl=true;try{window[name]=ww;}catch(e){}}});},true);
|
||||||
|
window.onerror=function(msg,src,line){notify('exception',{message:String(msg),line:line||0,source:src||''});return false;};
|
||||||
|
window.addEventListener('unhandledrejection',function(e){notify('exception',{message:String(e&&e.reason||'Unhandled promise rejection')});});
|
||||||
|
})();
|
||||||
|
`
|
||||||
|
|
||||||
|
var _ = html.EscapeString
|
||||||
597
standalone/mobile.go
Normal file
597
standalone/mobile.go
Normal file
@@ -0,0 +1,597 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
_ "embed"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed assets/qrcode.min.js
|
||||||
|
var qrcodeJS []byte
|
||||||
|
|
||||||
|
type activeShare struct {
|
||||||
|
server *http.Server
|
||||||
|
listener net.Listener
|
||||||
|
port int
|
||||||
|
token string
|
||||||
|
files []sharedFile
|
||||||
|
}
|
||||||
|
|
||||||
|
type sharedFile struct {
|
||||||
|
buf []byte
|
||||||
|
filename string
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
activeMu sync.Mutex
|
||||||
|
active *activeShare
|
||||||
|
)
|
||||||
|
|
||||||
|
func stopActiveShare() {
|
||||||
|
activeMu.Lock()
|
||||||
|
defer activeMu.Unlock()
|
||||||
|
if active != nil {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_ = active.server.Shutdown(ctx)
|
||||||
|
active = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func MobileQrScript(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||||
|
_, _ = w.Write(qrcodeJS)
|
||||||
|
}
|
||||||
|
|
||||||
|
func MobilePage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">Send To Mobile</h2>
|
||||||
|
<p class="tool-description">Pick HTML files, then start sharing. Scan the QR with a phone on the same WiFi.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="tool-panel">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Inputs</h3></div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div id="dropZone" class="drop-zone">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
|
<button id="pick" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div class="drop-zone-text">or drop HTML files or folders here</div>
|
||||||
|
</div>
|
||||||
|
<div id="fileName" class="file-name" style="margin-top:8px;">(no files selected)</div>
|
||||||
|
<div id="fileList" class="selected-list"></div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="start">Start</button>
|
||||||
|
<button id="stop" class="secondary" disabled>Stop</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="ifaceWrap" class="control-group" style="display:none;margin-bottom:14px;">
|
||||||
|
<div class="control-label">Network Interfaces</div>
|
||||||
|
<div id="ifaceList"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="shareInfo" class="result-card" style="display:none;">
|
||||||
|
<div id="qr" style="background:#fff;padding:12px;display:inline-block;border-radius:4px;"></div>
|
||||||
|
<div class="muted" style="margin-top:8px;font-size:12px;">
|
||||||
|
First run on Windows may show a firewall prompt - allow access for Private networks.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="/assets/qrcode.min.js"></script>
|
||||||
|
<script>
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
const pickFolderBtn = document.getElementById('pickFolder');
|
||||||
|
const pickBtn = document.getElementById('pick');
|
||||||
|
const clearBtn = document.getElementById('clear');
|
||||||
|
const startBtn = document.getElementById('start');
|
||||||
|
const stopBtn = document.getElementById('stop');
|
||||||
|
const fileNameEl = document.getElementById('fileName');
|
||||||
|
const fileListEl = document.getElementById('fileList');
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const shareInfo = document.getElementById('shareInfo');
|
||||||
|
const ifaceWrap = document.getElementById('ifaceWrap');
|
||||||
|
const ifaceList = document.getElementById('ifaceList');
|
||||||
|
const qrEl = document.getElementById('qr');
|
||||||
|
|
||||||
|
let currentUrls = [];
|
||||||
|
let selectedIdx = 0;
|
||||||
|
let selectedFiles = [];
|
||||||
|
let selectedPaths = [];
|
||||||
|
let selectedPage = 0;
|
||||||
|
|
||||||
|
function escapeHtml(s){ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
||||||
|
function renderSelection() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
if (!selectedFiles.length) {
|
||||||
|
fileNameEl.textContent = '(no files selected)';
|
||||||
|
fileListEl.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fileNameEl.textContent = selectedFiles.length + ' file' + (selectedFiles.length === 1 ? '' : 's');
|
||||||
|
const maxPage = Math.max(0, Math.ceil(selectedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const start = selectedPage * PAGE_SIZE;
|
||||||
|
const visible = selectedFiles.slice(start, start + PAGE_SIZE);
|
||||||
|
fileListEl.innerHTML = '<div class="results-panel" style="margin-top:0;"><table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead><tbody>' +
|
||||||
|
visible.map((file, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return '<tr><td class="mono wrap">' + escapeHtml(file.name) + '</td><td><button class="remove-selected danger" data-index="' + i + '" title="Remove">×</button></td></tr>';
|
||||||
|
}).join('') + '</tbody></table></div>';
|
||||||
|
fileListEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
const index = Number(btn.dataset.index);
|
||||||
|
selectedFiles.splice(index, 1);
|
||||||
|
selectedPaths.splice(index, 1);
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (selectedFiles.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML = '<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
fileListEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function addFiles(files) {
|
||||||
|
const existing = new Set(selectedFiles.map(f => f.path));
|
||||||
|
selectedFiles = selectedFiles.concat((files || []).filter(f => !existing.has(f.path)));
|
||||||
|
selectedPaths = selectedFiles.map(f => f.path);
|
||||||
|
selectedPage = Math.max(0, Math.ceil(selectedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
}
|
||||||
|
async function readJSONStream(response, handle) {
|
||||||
|
if (!response.ok || !response.body) throw new Error('Request failed.');
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
let newline;
|
||||||
|
while ((newline = buffer.indexOf('\n')) >= 0) {
|
||||||
|
const line = buffer.slice(0, newline);
|
||||||
|
buffer = buffer.slice(newline + 1);
|
||||||
|
if (line.trim()) handle(JSON.parse(line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffer.trim()) handle(JSON.parse(buffer));
|
||||||
|
}
|
||||||
|
renderSelection();
|
||||||
|
setupDropZone('dropZone', statusEl, (j) => {
|
||||||
|
addFiles(j.files || []);
|
||||||
|
if (j.skipped) statusEl.textContent = 'Skipped ' + j.skipped + ' non-HTML or unavailable item(s).';
|
||||||
|
});
|
||||||
|
|
||||||
|
pickFolderBtn.addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/mobile/pickFolder', { method:'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
addFiles(j.files || []);
|
||||||
|
});
|
||||||
|
pickBtn.addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/mobile/pick', { method:'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
addFiles(j.files || []);
|
||||||
|
});
|
||||||
|
clearBtn.addEventListener('click', () => {
|
||||||
|
selectedFiles = [];
|
||||||
|
selectedPaths = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
|
||||||
|
startBtn.addEventListener('click', async () => {
|
||||||
|
statusEl.innerHTML = '';
|
||||||
|
if (!selectedPaths.length) {
|
||||||
|
statusEl.innerHTML = '<span class="err">Pick at least one HTML file first.</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startBtn.disabled = true;
|
||||||
|
statusEl.textContent = 'Starting server...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
let j = null;
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/mobile/start', {
|
||||||
|
method:'POST', headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({ paths: selectedPaths }),
|
||||||
|
});
|
||||||
|
await readJSONStream(r, (msg) => {
|
||||||
|
if (msg.type === 'status') {
|
||||||
|
statusEl.textContent = msg.message;
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
} else if (msg.type === 'done') {
|
||||||
|
j = msg;
|
||||||
|
} else if (msg.type === 'error') {
|
||||||
|
j = { error: msg.message };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="err">' + (e.message || e) + '</span>';
|
||||||
|
startBtn.disabled = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!j) { statusEl.classList.remove('is-busy'); statusEl.innerHTML = '<span class="err">No response.</span>'; startBtn.disabled = false; return; }
|
||||||
|
if (j.error) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="err">' + j.error + '</span>';
|
||||||
|
startBtn.disabled = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
currentUrls = j.urls;
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
selectedIdx = 0;
|
||||||
|
statusEl.innerHTML = '<span class="ok">Sharing: ' + j.filename + '</span>';
|
||||||
|
shareInfo.style.display = '';
|
||||||
|
renderIfaces(j.urls);
|
||||||
|
renderQr(j.urls[0].url);
|
||||||
|
stopBtn.disabled = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
stopBtn.addEventListener('click', async () => {
|
||||||
|
await fetch('/api/mobile/stop', { method:'POST' });
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Stopped.';
|
||||||
|
shareInfo.style.display = 'none';
|
||||||
|
currentUrls = [];
|
||||||
|
startBtn.disabled = false;
|
||||||
|
stopBtn.disabled = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
function renderQr(url) {
|
||||||
|
qrEl.innerHTML = '';
|
||||||
|
try {
|
||||||
|
const qr = qrcode(0, 'M');
|
||||||
|
qr.addData(url);
|
||||||
|
qr.make();
|
||||||
|
qrEl.innerHTML = qr.createSvgTag({ cellSize: 5, margin: 2, scalable: true });
|
||||||
|
const svg = qrEl.querySelector('svg');
|
||||||
|
if (svg) { svg.setAttribute('width','240'); svg.setAttribute('height','240'); }
|
||||||
|
} catch (e) {
|
||||||
|
qrEl.textContent = 'QR render failed: ' + e.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderIfaces(urls) {
|
||||||
|
ifaceList.innerHTML = '';
|
||||||
|
if (urls.length <= 1) { ifaceWrap.style.display = 'none'; return; }
|
||||||
|
ifaceWrap.style.display = '';
|
||||||
|
ifaceList.innerHTML = '<div class="results-panel" style="margin-top:0;"><table class="data-table"><thead><tr><th style="width:70px;">Use</th><th style="width:140px;">IP</th><th>Interface</th></tr></thead><tbody></tbody></table></div>';
|
||||||
|
const tbody = ifaceList.querySelector('tbody');
|
||||||
|
urls.forEach((u, i) => {
|
||||||
|
const id = 'iface_' + i;
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
row.innerHTML = '<td style="text-align:center;"><input type="radio" name="iface" id="' + id + '"' + (i === selectedIdx ? ' checked' : '') + ' /></td>' +
|
||||||
|
'<td class="mono wrap">' + u.ip + '</td><td class="wrap">' + u.iface + '</td>';
|
||||||
|
row.querySelector('input').addEventListener('change', () => {
|
||||||
|
selectedIdx = i;
|
||||||
|
renderQr(urls[i].url);
|
||||||
|
});
|
||||||
|
tbody.appendChild(row);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/mobile", "Send To Mobile", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func MobilePick(w http.ResponseWriter, r *http.Request) {
|
||||||
|
picked := PickFiles(
|
||||||
|
"Select HTML",
|
||||||
|
[]FileFilter{{Name: "HTML", Extensions: []string{"html", "htm"}}},
|
||||||
|
true, "",
|
||||||
|
)
|
||||||
|
if len(picked) == 0 {
|
||||||
|
writeJSON(w, map[string]any{"files": []any{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files := make([]map[string]string, 0, len(picked))
|
||||||
|
for _, p := range picked {
|
||||||
|
files = append(files, map[string]string{"path": p, "name": filepath.Base(p)})
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"files": files})
|
||||||
|
}
|
||||||
|
|
||||||
|
func MobilePickFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
dir := PickFolder("Select folder", "")
|
||||||
|
if dir == "" {
|
||||||
|
writeJSON(w, map[string]any{"files": []any{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
paths := collectHTMLFiles(dir)
|
||||||
|
files := make([]map[string]string, 0, len(paths))
|
||||||
|
for _, p := range paths {
|
||||||
|
files = append(files, map[string]string{"path": p, "name": filepath.Base(p)})
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"files": files})
|
||||||
|
}
|
||||||
|
|
||||||
|
func MobileStart(w http.ResponseWriter, r *http.Request) {
|
||||||
|
stopActiveShare()
|
||||||
|
send := newJSONStream(w)
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Paths []string `json:"paths"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
paths := req.Paths
|
||||||
|
if len(paths) == 0 && req.Path != "" {
|
||||||
|
paths = []string{req.Path}
|
||||||
|
}
|
||||||
|
if len(paths) == 0 {
|
||||||
|
send(map[string]any{"type": "error", "message": "File missing."})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files := make([]sharedFile, 0, len(paths))
|
||||||
|
for i, p := range paths {
|
||||||
|
if p == "" || !fileExists(p) {
|
||||||
|
send(map[string]any{"type": "error", "message": "File missing."})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Loading %d/%d %s", i+1, len(paths), filepath.Base(p))})
|
||||||
|
fileBuf, err := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Read failed: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files = append(files, sharedFile{buf: fileBuf, filename: filepath.Base(p)})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6 random bytes -> base64url, no padding
|
||||||
|
tokenBytes := make([]byte, 6)
|
||||||
|
if _, err := rand.Read(tokenBytes); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Token gen failed: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := strings.TrimRight(base64.URLEncoding.EncodeToString(tokenBytes), "=")
|
||||||
|
|
||||||
|
cfgPort := LoadConfig().SendToMobile.Port
|
||||||
|
send(map[string]any{"type": "status", "message": "Starting server..."})
|
||||||
|
listener, err := net.Listen("tcp", "0.0.0.0:"+strconv.Itoa(cfgPort))
|
||||||
|
if err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Failed to bind: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
port := listener.Addr().(*net.TCPAddr).Port
|
||||||
|
|
||||||
|
share := &activeShare{
|
||||||
|
listener: listener,
|
||||||
|
port: port,
|
||||||
|
token: token,
|
||||||
|
files: files,
|
||||||
|
}
|
||||||
|
share.server = &http.Server{Handler: shareHandler(share)}
|
||||||
|
|
||||||
|
go func() { _ = share.server.Serve(listener) }()
|
||||||
|
|
||||||
|
ips := getLanIPs()
|
||||||
|
if len(ips) == 0 {
|
||||||
|
_ = share.server.Close()
|
||||||
|
send(map[string]any{"type": "error", "message": "No non-loopback IPv4 interface found. Are you on a network?"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
activeMu.Lock()
|
||||||
|
active = share
|
||||||
|
activeMu.Unlock()
|
||||||
|
|
||||||
|
type urlInfo struct {
|
||||||
|
IP string `json:"ip"`
|
||||||
|
Iface string `json:"iface"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
}
|
||||||
|
urls := make([]urlInfo, 0, len(ips))
|
||||||
|
for _, ip := range ips {
|
||||||
|
urls = append(urls, urlInfo{
|
||||||
|
IP: ip.address,
|
||||||
|
Iface: ip.iface,
|
||||||
|
URL: fmt.Sprintf("http://%s:%d/s/%s/", ip.address, port, token),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
filename := fmt.Sprintf("%d files", len(files))
|
||||||
|
if len(files) == 1 {
|
||||||
|
filename = files[0].filename
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "done", "urls": urls, "filename": filename})
|
||||||
|
}
|
||||||
|
|
||||||
|
func MobileStop(w http.ResponseWriter, r *http.Request) {
|
||||||
|
stopActiveShare()
|
||||||
|
writeJSON(w, map[string]any{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func shareHandler(s *activeShare) http.Handler {
|
||||||
|
prefix := "/s/" + s.token
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet || !strings.HasPrefix(r.URL.Path, prefix) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rest := strings.TrimPrefix(r.URL.Path, prefix)
|
||||||
|
switch rest {
|
||||||
|
case "", "/":
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write([]byte(chooserPage(s.files)))
|
||||||
|
case "/view":
|
||||||
|
fallthrough
|
||||||
|
case "/view/0":
|
||||||
|
if len(s.files) == 0 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write([]byte(mobilePreviewPage(s.files[0])))
|
||||||
|
case "/file":
|
||||||
|
fallthrough
|
||||||
|
case "/file/0":
|
||||||
|
if len(s.files) == 0 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
safeName := safeFilename(s.files[0].filename)
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="`+safeName+`"`)
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(len(s.files[0].buf)))
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write(s.files[0].buf)
|
||||||
|
default:
|
||||||
|
if strings.HasPrefix(rest, "/view/") || strings.HasPrefix(rest, "/file/") {
|
||||||
|
parts := strings.Split(strings.Trim(rest, "/"), "/")
|
||||||
|
if len(parts) == 2 {
|
||||||
|
idx, err := strconv.Atoi(parts[1])
|
||||||
|
if err == nil && idx >= 0 && idx < len(s.files) {
|
||||||
|
file := s.files[idx]
|
||||||
|
if parts[0] == "view" {
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write([]byte(mobilePreviewPage(file)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
safeName := safeFilename(file.filename)
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="`+safeName+`"`)
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(len(file.buf)))
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write(file.buf)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func mobilePreviewPage(file sharedFile) string {
|
||||||
|
playableJSON, _ := json.Marshal(string(file.buf))
|
||||||
|
playableScriptValue := strings.ReplaceAll(string(playableJSON), "</script", "<\\/script")
|
||||||
|
playableScriptValue = strings.ReplaceAll(playableScriptValue, "</SCRIPT", "<\\/SCRIPT")
|
||||||
|
title := html.EscapeString(file.filename)
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html><head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<title>` + title + `</title>
|
||||||
|
<style>
|
||||||
|
html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: #000; }
|
||||||
|
iframe { position: fixed; inset: 0; width: 100%; height: 100%; border: 0; background: #000; }
|
||||||
|
.boot { position: fixed; inset: 0; display: grid; place-items: center; color: #777; font: 12px system-ui, sans-serif; }
|
||||||
|
</style>
|
||||||
|
</head><body>
|
||||||
|
<div id="boot" class="boot">Loading preview...</div>
|
||||||
|
<iframe id="playable" sandbox="allow-scripts allow-same-origin allow-pointer-lock allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"></iframe>
|
||||||
|
<script>
|
||||||
|
const playableHtml = ` + playableScriptValue + `;
|
||||||
|
setTimeout(() => {
|
||||||
|
const frame = document.getElementById('playable');
|
||||||
|
document.getElementById('boot').style.display = 'none';
|
||||||
|
frame.srcdoc = playableHtml;
|
||||||
|
}, 750);
|
||||||
|
</script>
|
||||||
|
</body></html>`
|
||||||
|
}
|
||||||
|
|
||||||
|
var unsafeFilenameRx = regexp.MustCompile(`[^A-Za-z0-9._-]`)
|
||||||
|
|
||||||
|
func safeFilename(s string) string { return unsafeFilenameRx.ReplaceAllString(s, "_") }
|
||||||
|
|
||||||
|
func chooserPage(files []sharedFile) string {
|
||||||
|
var items strings.Builder
|
||||||
|
for i, file := range files {
|
||||||
|
escName := html.EscapeString(file.filename)
|
||||||
|
items.WriteString(`<div class="item"><div class="file">` + escName + `</div>
|
||||||
|
<a class="btn view" href="view/` + strconv.Itoa(i) + `">View in browser</a>
|
||||||
|
<a class="btn dl" href="file/` + strconv.Itoa(i) + `" download="` + escName + `">Download .html</a></div>`)
|
||||||
|
}
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html><head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Send To Mobile</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
margin: 0; padding: 24px; background: #111; color: #eee; }
|
||||||
|
h1 { font-size: 18px; font-weight: 500; margin: 0 0 4px; opacity: 0.85; }
|
||||||
|
.item { margin-bottom: 26px; }
|
||||||
|
.file { font-size: 13px; opacity: 0.6; margin-bottom: 10px; word-break: break-all; }
|
||||||
|
a.btn { display: block; padding: 18px; margin-bottom: 14px; border-radius: 10px;
|
||||||
|
font-size: 17px; font-weight: 500; text-align: center; text-decoration: none; }
|
||||||
|
a.view { background: #2d7dff; color: white; }
|
||||||
|
a.dl { background: #2a2a2a; color: #eee; border: 1px solid #3a3a3a; }
|
||||||
|
</style></head>
|
||||||
|
<body>
|
||||||
|
<h1>HPL Toolbox</h1>
|
||||||
|
` + items.String() + `
|
||||||
|
</body></html>`
|
||||||
|
}
|
||||||
|
|
||||||
|
type lanIP struct {
|
||||||
|
address string
|
||||||
|
iface string
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLanIPs() []lanIP {
|
||||||
|
var out []lanIP
|
||||||
|
ifaces, err := net.Interfaces()
|
||||||
|
if err != nil {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
for _, iface := range ifaces {
|
||||||
|
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addrs, err := iface.Addrs()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, a := range addrs {
|
||||||
|
ipNet, ok := a.(*net.IPNet)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ip4 := ipNet.IP.To4()
|
||||||
|
if ip4 == nil || ip4.IsLoopback() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, lanIP{address: ip4.String(), iface: iface.Name})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
725
standalone/mraid.go
Normal file
725
standalone/mraid.go
Normal file
@@ -0,0 +1,725 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type mraidIssue struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Severity string `json:"severity"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Detail string `json:"detail"`
|
||||||
|
Line int `json:"line,omitempty"`
|
||||||
|
Reference string `json:"reference"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type mraidResult struct {
|
||||||
|
File string `json:"file"`
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Issues []mraidIssue `json:"issues"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type mraidRule struct {
|
||||||
|
ID string
|
||||||
|
Severity string
|
||||||
|
Title string
|
||||||
|
Detail string
|
||||||
|
Reference string
|
||||||
|
Test func(mraidContext, mraidRule) *mraidIssue
|
||||||
|
}
|
||||||
|
|
||||||
|
type mraidContext struct {
|
||||||
|
FilePath string
|
||||||
|
HTML string
|
||||||
|
ScriptText string
|
||||||
|
MraidCallLines map[string]int
|
||||||
|
}
|
||||||
|
|
||||||
|
func MraidPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">MRAID Checker</h2>
|
||||||
|
<p class="tool-description">Static checks for AppLovin, ironSource, and Unity HTML builds based on GUIDE.md plus the MRAID 3.0 specification and Best Practices Guide.</p>
|
||||||
|
</header>
|
||||||
|
<section class="tool-panel">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Inputs</h3></div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div id="dropZone" class="drop-zone">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
|
<button id="pickFiles" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div class="drop-zone-text">or drop HTML files or folders here</div>
|
||||||
|
</div>
|
||||||
|
<div id="selection" class="selected-list"></div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row"><button id="scan">Scan</button></div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.row-result { padding:8px 0; border-bottom:1px solid #333; }
|
||||||
|
.file-head { display:flex; gap:8px; align-items:baseline; font-family:Consolas, monospace; font-size:12px; }
|
||||||
|
.mark { width:20px; flex-shrink:0; font-weight:bold; }
|
||||||
|
.mark.ok { color:#3fb950; } .mark.bad { color:#f85149; }
|
||||||
|
.file-name { word-break:break-all; }
|
||||||
|
.counts { opacity:0.7; margin-left:auto; white-space:nowrap; }
|
||||||
|
.issues { margin:6px 0 0 28px; padding:0; }
|
||||||
|
.issue { list-style:none; margin:6px 0; }
|
||||||
|
.badge { display:inline-block; min-width:82px; margin-right:6px; padding:1px 5px; border-radius:3px; font-size:11px; text-align:center; }
|
||||||
|
.requirement { color:#ffb4ad; background:rgba(248,81,73,0.18); }
|
||||||
|
.best-practice { color:#ffd580; background:rgba(210,153,34,0.18); }
|
||||||
|
.issue-title { font-weight:600; }
|
||||||
|
.issue-detail { opacity:0.72; margin-top:2px; }
|
||||||
|
.summary { opacity:0.85; margin-bottom:6px; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const folderEl = document.getElementById('folder');
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const resultsEl = document.getElementById('results');
|
||||||
|
const selectionEl = document.getElementById('selection');
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
let pickedFiles = [];
|
||||||
|
let selectedPage = 0;
|
||||||
|
function escapeText(value){ return String(value).replace(/[&<>"']/g, ch => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch])); }
|
||||||
|
function basename(p) { const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\')); return i >= 0 ? p.slice(i + 1) : p; }
|
||||||
|
function renderSelection() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
if (!pickedFiles.length) {
|
||||||
|
selectionEl.innerHTML = '<span class="file-name">(no files selected)</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const maxPage = Math.max(0, Math.ceil(pickedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
selectedPage = Math.min(selectedPage, maxPage);
|
||||||
|
const start = selectedPage * PAGE_SIZE;
|
||||||
|
const visible = pickedFiles.slice(start, start + PAGE_SIZE);
|
||||||
|
selectionEl.innerHTML = '<div class="results-panel" style="margin-top:0;"><table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead><tbody>' +
|
||||||
|
visible.map((p, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return '<tr><td class="mono wrap">' + escapeText(basename(p)) + '</td><td><button class="remove-selected danger" data-index="' + i + '" title="Remove">×</button></td></tr>';
|
||||||
|
}).join('') + '</tbody></table></div>';
|
||||||
|
selectionEl.querySelectorAll('.remove-selected').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => { pickedFiles.splice(Number(btn.dataset.index), 1); renderSelection(); });
|
||||||
|
});
|
||||||
|
if (pickedFiles.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML = '<button class="secondary" id="prevPage"' + (selectedPage === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (selectedPage + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (selectedPage === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
selectionEl.appendChild(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { selectedPage--; renderSelection(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { selectedPage++; renderSelection(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function addPaths(paths) {
|
||||||
|
const existing = new Set(pickedFiles);
|
||||||
|
pickedFiles = pickedFiles.concat((paths || []).filter(p => !existing.has(p)));
|
||||||
|
selectedPage = Math.max(0, Math.ceil(pickedFiles.length / PAGE_SIZE) - 1);
|
||||||
|
renderSelection();
|
||||||
|
}
|
||||||
|
async function readJSONStream(response, handle) {
|
||||||
|
if (!response.ok || !response.body) throw new Error('Request failed.');
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
let newline;
|
||||||
|
while ((newline = buffer.indexOf('\n')) >= 0) {
|
||||||
|
const line = buffer.slice(0, newline);
|
||||||
|
buffer = buffer.slice(newline + 1);
|
||||||
|
if (line.trim()) handle(JSON.parse(line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffer.trim()) handle(JSON.parse(buffer));
|
||||||
|
}
|
||||||
|
renderSelection();
|
||||||
|
setupDropZone('dropZone', statusEl, (j) => {
|
||||||
|
addPaths(j.paths || []);
|
||||||
|
if (j.skipped) statusEl.textContent = 'Skipped ' + j.skipped + ' non-HTML or unavailable item(s).';
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('pickFolder').addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/mraid/pickFolder', { method: 'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
addPaths(j.paths || []);
|
||||||
|
});
|
||||||
|
document.getElementById('pickFiles').addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/mraid/pickFiles', { method: 'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
addPaths(j.paths || []);
|
||||||
|
});
|
||||||
|
document.getElementById('clear').addEventListener('click', () => {
|
||||||
|
pickedFiles = [];
|
||||||
|
selectedPage = 0;
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
renderSelection();
|
||||||
|
});
|
||||||
|
document.getElementById('scan').addEventListener('click', async () => {
|
||||||
|
statusEl.textContent = 'Scanning...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
if (!pickedFiles.length) { statusEl.classList.remove('is-busy'); statusEl.textContent = 'Pick files first.'; return; }
|
||||||
|
const payload = { files: pickedFiles };
|
||||||
|
let j = null;
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/mraid/scan', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload) });
|
||||||
|
await readJSONStream(r, (msg) => {
|
||||||
|
if (msg.type === 'status') {
|
||||||
|
statusEl.textContent = msg.message;
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
} else if (msg.type === 'done') {
|
||||||
|
j = msg;
|
||||||
|
} else if (msg.type === 'error') {
|
||||||
|
j = { error: msg.message, results: msg.results || [], skipped: msg.skipped, skippedReason: msg.skippedReason };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Error: ' + (e.message || e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!j) { statusEl.classList.remove('is-busy'); statusEl.textContent = 'Error: No response.'; return; }
|
||||||
|
if (j.error) { statusEl.classList.remove('is-busy'); statusEl.textContent = 'Error: ' + j.error; return; }
|
||||||
|
const total = j.results.length;
|
||||||
|
const withIssues = j.results.filter(r => !r.ok).length;
|
||||||
|
const requirements = j.results.reduce((n, r) => n + r.issues.filter(i => i.severity === 'requirement').length, 0);
|
||||||
|
const bestPractices = j.results.reduce((n, r) => n + r.issues.filter(i => i.severity === 'best-practice').length, 0);
|
||||||
|
const skipped = Number(j.skipped || 0);
|
||||||
|
const skippedReason = j.skippedReason || 'file(s).';
|
||||||
|
const skippedText = skipped ? ' Skipped ' + skipped + ' ' + skippedReason : '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = 'Scanned ' + total + ' HTML file(s). ' + withIssues + ' file(s) need review.' + skippedText;
|
||||||
|
if (!total) { resultsEl.innerHTML = ''; return; }
|
||||||
|
resultsEl.innerHTML = '<table class="data-table"><thead><tr><th>File</th><th>Results</th></tr></thead><tbody></tbody></table>';
|
||||||
|
const tbody = resultsEl.querySelector('tbody');
|
||||||
|
for (const rr of j.results) {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
const file = document.createElement('td');
|
||||||
|
file.className = 'mono wrap';
|
||||||
|
file.textContent = rr.file;
|
||||||
|
const result = document.createElement('td');
|
||||||
|
result.className = 'wrap';
|
||||||
|
if (!rr.ok) {
|
||||||
|
const list = document.createElement('ul');
|
||||||
|
list.className = 'issues';
|
||||||
|
for (const i of rr.issues) {
|
||||||
|
const item = document.createElement('li');
|
||||||
|
item.className = 'issue';
|
||||||
|
const line = i.line ? ' line ' + i.line + ':' : '';
|
||||||
|
item.innerHTML = '<span class="badge ' + i.severity + '">' + escapeText(i.severity) + '</span><span class="issue-title">' + escapeText(line + ' ' + i.title) + '</span><div class="issue-detail">' + escapeText(i.detail) + '</div>';
|
||||||
|
list.appendChild(item);
|
||||||
|
}
|
||||||
|
result.appendChild(list);
|
||||||
|
} else {
|
||||||
|
result.innerHTML = '<span class="badge ok">OK</span>';
|
||||||
|
}
|
||||||
|
row.append(file, result);
|
||||||
|
tbody.appendChild(row);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/mraid", "MRAID Checker", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func MraidPickFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
p := PickFolder("Select folder to scan", "")
|
||||||
|
if p == "" {
|
||||||
|
writeJSON(w, map[string]any{"paths": []string{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files := []string{}
|
||||||
|
for _, f := range collectHTMLFiles(p) {
|
||||||
|
if isInSupportedMraidFolderPath(f) {
|
||||||
|
files = append(files, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"paths": files})
|
||||||
|
}
|
||||||
|
|
||||||
|
func MraidPickFiles(w http.ResponseWriter, r *http.Request) {
|
||||||
|
paths := PickFiles("Select HTML files", []FileFilter{{Name: "HTML", Extensions: []string{"html", "htm"}}}, true, "")
|
||||||
|
writeJSON(w, map[string]any{"paths": paths})
|
||||||
|
}
|
||||||
|
|
||||||
|
func MraidScan(w http.ResponseWriter, r *http.Request) {
|
||||||
|
send := newJSONStream(w)
|
||||||
|
var req struct {
|
||||||
|
Folder string `json:"folder"`
|
||||||
|
Files []string `json:"files"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error(), "results": []mraidResult{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var targets []string
|
||||||
|
var baseDir string
|
||||||
|
skipped := 0
|
||||||
|
skippedReason := ""
|
||||||
|
noTargetsError := "No HTML files were found."
|
||||||
|
if len(req.Files) > 0 {
|
||||||
|
var existing []string
|
||||||
|
for _, f := range req.Files {
|
||||||
|
if fileExists(f) {
|
||||||
|
existing = append(existing, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
targets = existing
|
||||||
|
skipped = len(req.Files) - len(existing)
|
||||||
|
skippedReason = "missing file(s)."
|
||||||
|
noTargetsError = "No selected HTML files were found."
|
||||||
|
if len(targets) > 0 {
|
||||||
|
baseDir = commonBaseDir(targets)
|
||||||
|
}
|
||||||
|
} else if req.Folder != "" && fileExists(req.Folder) {
|
||||||
|
all := collectHTMLFiles(req.Folder)
|
||||||
|
for _, f := range all {
|
||||||
|
if isInSupportedMraidFolderPath(f) {
|
||||||
|
targets = append(targets, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
skipped = len(all) - len(targets)
|
||||||
|
skippedReason = "HTML file(s) outside AppLovin/ironSource/Unity folders."
|
||||||
|
noTargetsError = "No AppLovin, ironSource, or Unity folder HTML files were found."
|
||||||
|
baseDir = req.Folder
|
||||||
|
} else {
|
||||||
|
send(map[string]any{"type": "error", "message": "Pick a folder or files first", "results": []mraidResult{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(targets) == 0 {
|
||||||
|
send(map[string]any{"type": "error", "message": noTargetsError, "results": []mraidResult{}, "skipped": skipped, "skippedReason": skippedReason})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
results := []mraidResult{}
|
||||||
|
for i, file := range targets {
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Scanning %d/%d %s", i+1, len(targets), filepath.Base(file))})
|
||||||
|
data, err := os.ReadFile(file)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
issues := checkMraid(string(data), file)
|
||||||
|
display := file
|
||||||
|
if baseDir != "" {
|
||||||
|
if rel, err := filepath.Rel(baseDir, file); err == nil && rel != "" {
|
||||||
|
display = rel
|
||||||
|
} else {
|
||||||
|
display = filepath.Base(file)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
results = append(results, mraidResult{File: display, OK: len(issues) == 0, Issues: issues})
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "done", "results": results, "skipped": skipped, "skippedReason": skippedReason})
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
mraidScriptRx = regexp.MustCompile(`(?is)<script\b[^>]*>(.*?)</script>`)
|
||||||
|
mraidCallRx = regexp.MustCompile(`(?i)\bmraid\s*\.\s*([a-zA-Z_$][\w$]*)\s*\(`)
|
||||||
|
mraidReferenceRx = regexp.MustCompile(`(?i)\bmraid\b`)
|
||||||
|
mraidJsRx = regexp.MustCompile(`(?i)\bmraid\.js\b`)
|
||||||
|
mraidViewportRx = regexp.MustCompile(`(?i)<meta\b[^>]*\bname\s*=\s*['"]viewport['"][^>]*>`)
|
||||||
|
mraidWindowOpenRx = regexp.MustCompile(`(?i)\bwindow\s*\.\s*open\s*\(`)
|
||||||
|
mraidLocationNavRx = regexp.MustCompile(`(?i)\blocation\s*\.\s*(href|assign|replace)\b`)
|
||||||
|
mraidHyperlinkRx = regexp.MustCompile(`(?i)<a\b[^>]*\bhref\s*=`)
|
||||||
|
mraidCloseUiRx = regexp.MustCompile(`(?i)\b(close|dismiss|skip)\b`)
|
||||||
|
mraidLoadingLeftRx = regexp.MustCompile(`(?i)mraid\s*\.\s*getState\s*\(\s*\)\s*={0,2}\s*['"]loading['"]`)
|
||||||
|
mraidLoadingRightRx = regexp.MustCompile(`(?i)['"]loading['"]\s*={0,2}\s*mraid\s*\.\s*getState\s*\(\s*\)`)
|
||||||
|
mraidDomReadyRx = regexp.MustCompile(`(?i)document\s*\.\s*readyState|DOMContentLoaded|\bwindow\s*\.\s*(addEventListener\s*\(\s*['"]load['"]|onload\b)`)
|
||||||
|
mraidTypeofGuardRx = regexp.MustCompile(`(?i)typeof\s+(window\s*\.\s*)?mraid\s*!={1,2}\s*['"]undefined['"]`)
|
||||||
|
mraidReadyTimeoutRx = regexp.MustCompile(`(?is)setTimeout\s*\(.*mraid|mraid.*setTimeout\s*\(`)
|
||||||
|
mraidLateDetectionRx = regexp.MustCompile(`(?i)(setInterval\s*\(|setTimeout\s*\(|requestAnimationFrame\s*\().*(window\s*\.\s*mraid|\bmraid\b)|(window\s*\.\s*mraid|\bmraid\b).*(setInterval\s*\(|setTimeout\s*\(|requestAnimationFrame\s*\()`)
|
||||||
|
mraidOpenGuardRx = regexp.MustCompile(`(?i)typeof\s+(window\s*\.\s*)?mraid\s*\.\s*open\s*={2,3}\s*['"]function['"]|typeof\s+(window\s*\.\s*)?mraid\s*\.\s*open\s*!={1,2}\s*['"]undefined['"]`)
|
||||||
|
mraidOpenLoadingGuardRx = regexp.MustCompile(`(?i)mraid\s*\.\s*getState\s*\(\s*\)\s*!={1,2}\s*['"]loading['"]|['"]loading['"]\s*!={1,2}\s*mraid\s*\.\s*getState\s*\(\s*\)|typeof\s+(window\s*\.\s*)?mraid\s*\.\s*getState\s*!={1,2}\s*['"]function['"]`)
|
||||||
|
mraidVariableLoadingGuardRx = regexp.MustCompile(`(?i)\b\w+\s*!={1,2}\s*['"]loading['"]|['"]loading['"]\s*!={1,2}\s*\w+\b`)
|
||||||
|
mraidLoadingFallbackRx = regexp.MustCompile(`(?is)\b\w+\s*={2,3}\s*['"]loading['"].{0,500}\bwindow\s*\.\s*open\s*\(`)
|
||||||
|
mraidAudioSafeRx = regexp.MustCompile(`(?i)typeof\s+\w+\s*={2,3}\s*['"]number['"]|!=\s*null|!==\s*null`)
|
||||||
|
mraidTwoPartExpandRx = regexp.MustCompile(`(?i)mraid\s*\.\s*expand\s*\(\s*[^)\s]`)
|
||||||
|
mraidVideoOpenRx = regexp.MustCompile(`(?i)mraid\s*\.\s*open\s*\(\s*[^)]*\.(mp4|m4v|mov|webm|avi|m3u8)(['"` + "`" + `?#)]|$)`)
|
||||||
|
mraidRejectedScriptAttrsRx = regexp.MustCompile(`(?i)<script\b[^>]*(\btype\s*=\s*['"]module['"]|\bcrossorigin\b)`)
|
||||||
|
mraidConsoleErrorRx = regexp.MustCompile(`(?i)\bconsole\s*\.\s*error\s*\(`)
|
||||||
|
)
|
||||||
|
|
||||||
|
const mraidReference = "GUIDE.md, MRAID 3.0 specification, and MRAID 3.0 Best Practices Guide."
|
||||||
|
|
||||||
|
func isInSupportedMraidFolderPath(filePath string) bool {
|
||||||
|
supported := map[string]bool{
|
||||||
|
"al": true,
|
||||||
|
"applovin": true,
|
||||||
|
"app-lovin": true,
|
||||||
|
"is": true,
|
||||||
|
"ironsource": true,
|
||||||
|
"iron-source": true,
|
||||||
|
"iron_source": true,
|
||||||
|
"un": true,
|
||||||
|
"unity": true,
|
||||||
|
"unityads": true,
|
||||||
|
"unity-ads": true,
|
||||||
|
"unity_ads": true,
|
||||||
|
}
|
||||||
|
parts := strings.FieldsFunc(strings.ToLower(filepath.Dir(filePath)), func(r rune) bool {
|
||||||
|
return r == '/' || r == '\\'
|
||||||
|
})
|
||||||
|
for _, part := range parts {
|
||||||
|
if supported[part] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkMraid(htmlSrc string, filePath ...string) []mraidIssue {
|
||||||
|
sourcePath := ""
|
||||||
|
if len(filePath) > 0 {
|
||||||
|
sourcePath = filePath[0]
|
||||||
|
}
|
||||||
|
ctx := mraidContext{
|
||||||
|
FilePath: sourcePath,
|
||||||
|
HTML: htmlSrc,
|
||||||
|
ScriptText: extractMraidScriptText(htmlSrc),
|
||||||
|
MraidCallLines: collectMraidCallLines(htmlSrc),
|
||||||
|
}
|
||||||
|
var out []mraidIssue
|
||||||
|
for _, rule := range mraidRules {
|
||||||
|
if found := rule.Test(ctx, rule); found != nil {
|
||||||
|
out = append(out, *found)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out == nil {
|
||||||
|
out = []mraidIssue{}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractMraidScriptText(htmlSrc string) string {
|
||||||
|
var parts []string
|
||||||
|
for _, m := range mraidScriptRx.FindAllStringSubmatch(htmlSrc, -1) {
|
||||||
|
parts = append(parts, m[1])
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func collectMraidCallLines(htmlSrc string) map[string]int {
|
||||||
|
out := map[string]int{}
|
||||||
|
for idx, line := range strings.Split(htmlSrc, "\n") {
|
||||||
|
for _, m := range mraidCallRx.FindAllStringSubmatch(line, -1) {
|
||||||
|
if _, ok := out[m[1]]; !ok {
|
||||||
|
out[m[1]] = idx + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func mraidHasReference(ctx mraidContext) bool { return mraidReferenceRx.MatchString(ctx.HTML) }
|
||||||
|
func mraidCountJSReferences(ctx mraidContext) int {
|
||||||
|
return len(mraidJsRx.FindAllStringIndex(ctx.HTML, -1))
|
||||||
|
}
|
||||||
|
func mraidHasViewport(ctx mraidContext) bool { return mraidViewportRx.MatchString(ctx.HTML) }
|
||||||
|
func mraidIsNetworkTarget(ctx mraidContext) bool {
|
||||||
|
if ctx.FilePath == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
name := strings.ToLower(filepath.Base(ctx.FilePath))
|
||||||
|
return isInSupportedMraidFolderPath(ctx.FilePath) ||
|
||||||
|
strings.HasSuffix(name, "_al.html") || strings.HasSuffix(name, "_is.html") || strings.HasSuffix(name, "_un.html") ||
|
||||||
|
strings.HasSuffix(name, "_al.htm") || strings.HasSuffix(name, "_is.htm") || strings.HasSuffix(name, "_un.htm")
|
||||||
|
}
|
||||||
|
func mraidHasCall(ctx mraidContext, method string) bool {
|
||||||
|
_, ok := ctx.MraidCallLines[method]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
func mraidLine(ctx mraidContext, method string) int { return ctx.MraidCallLines[method] }
|
||||||
|
|
||||||
|
func mraidHasFunctionGuard(ctx mraidContext, method string) bool {
|
||||||
|
escaped := regexp.QuoteMeta(method)
|
||||||
|
rx := regexp.MustCompile(`(?i)typeof\s+(window\s*\.\s*)?mraid\s*\.\s*` + escaped + `\s*={2,3}\s*['"]function['"]|typeof\s+(window\s*\.\s*)?mraid\s*\.\s*` + escaped + `\s*!={1,2}\s*['"]undefined['"]`)
|
||||||
|
return rx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mraidHasEventListener(ctx mraidContext, eventName string) bool {
|
||||||
|
rx := regexp.MustCompile(`(?i)mraid\s*\.\s*addEventListener\s*\(\s*['"]` + regexp.QuoteMeta(eventName) + `['"]`)
|
||||||
|
return rx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mraidHasSupportCheck(ctx mraidContext, feature string) bool {
|
||||||
|
rx := regexp.MustCompile(`(?i)mraid\s*\.\s*supports\s*\(\s*['"]` + regexp.QuoteMeta(feature) + `['"]`)
|
||||||
|
return rx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mraidHasReadyGate(ctx mraidContext) bool {
|
||||||
|
return mraidHasEventListener(ctx, "ready") || mraidLoadingLeftRx.MatchString(ctx.ScriptText) || mraidLoadingRightRx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mraidHasDomReadyGate(ctx mraidContext) bool { return mraidDomReadyRx.MatchString(ctx.ScriptText) }
|
||||||
|
func mraidHasReadyStateFallback(ctx mraidContext) bool {
|
||||||
|
return mraidHasEventListener(ctx, "ready") && mraidHasCall(ctx, "getState")
|
||||||
|
}
|
||||||
|
func mraidHasTypeofGuard(ctx mraidContext) bool {
|
||||||
|
return mraidTypeofGuardRx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
func mraidHasReadyTimeout(ctx mraidContext) bool {
|
||||||
|
return mraidReadyTimeoutRx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
func mraidHasLateDetection(ctx mraidContext) bool {
|
||||||
|
return mraidLateDetectionRx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
func mraidHasOpenGuard(ctx mraidContext) bool { return mraidOpenGuardRx.MatchString(ctx.ScriptText) }
|
||||||
|
func mraidHasOpenLoadingGuard(ctx mraidContext) bool {
|
||||||
|
return mraidOpenLoadingGuardRx.MatchString(ctx.ScriptText) ||
|
||||||
|
(mraidHasCall(ctx, "getState") && mraidVariableLoadingGuardRx.MatchString(ctx.ScriptText)) ||
|
||||||
|
(mraidHasCall(ctx, "getState") && mraidLoadingFallbackRx.MatchString(ctx.ScriptText))
|
||||||
|
}
|
||||||
|
func mraidUsesBrowserNavigation(ctx mraidContext) bool {
|
||||||
|
return mraidWindowOpenRx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
func mraidUsesLocationNavigation(ctx mraidContext) bool {
|
||||||
|
return mraidLocationNavRx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
func mraidHasAudioVolumeSafeHandling(ctx mraidContext) bool {
|
||||||
|
return mraidHasEventListener(ctx, "audioVolumeChange") && mraidAudioSafeRx.MatchString(ctx.ScriptText)
|
||||||
|
}
|
||||||
|
func mraidHasLifecycleSignal(ctx mraidContext, name string) bool {
|
||||||
|
return regexp.MustCompile(`(?i)\b` + regexp.QuoteMeta(name) + `\b`).MatchString(ctx.HTML)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mraidIssueFrom(rule mraidRule, line int) *mraidIssue {
|
||||||
|
found := mraidIssue{ID: rule.ID, Severity: rule.Severity, Title: rule.Title, Detail: rule.Detail, Reference: rule.Reference}
|
||||||
|
if line > 0 {
|
||||||
|
found.Line = line
|
||||||
|
}
|
||||||
|
return &found
|
||||||
|
}
|
||||||
|
|
||||||
|
var mraidRules = []mraidRule{
|
||||||
|
{ID: "mraid-js-missing", Severity: "requirement", Title: "mraid.js reference not found", Detail: "MRAID creatives for AppLovin, ironSource, and Unity must request mraid.js early in the generated HTML.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidIsNetworkTarget(ctx) && mraidCountJSReferences(ctx) == 0 {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "mraid-js-duplicate", Severity: "requirement", Title: "Multiple mraid.js references found", Detail: "Request mraid.js exactly once; duplicate references can inject multiple MRAID libraries and slow or destabilize the ad.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidCountJSReferences(ctx) > 1 {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "mraid-reference", Severity: "requirement", Title: "MRAID API reference not found", Detail: "Playable HTML should use the injected mraid object when it depends on an MRAID container.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasReference(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "viewport-meta", Severity: "best-practice", Title: "Viewport meta tag not found", Detail: "MRAID creatives should include a mobile viewport meta tag so the ad scales predictably on mobile WebViews.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasViewport(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "mraid-typeof-guard", Severity: "requirement", Title: "MRAID object is not guarded", Detail: "Guard MRAID access with typeof mraid !== \"undefined\" or an equivalent window.mraid guard before making MRAID calls.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasReference(ctx) && !mraidHasTypeofGuard(ctx) {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "dom-ready-gate", Severity: "requirement", Title: "DOM readiness is not guarded", Detail: "MRAID startup should wait for DOM readiness as well as MRAID readiness before building or binding rich media content.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if !mraidHasReference(ctx) || mraidHasDomReadyGate(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "ready-gate", Severity: "requirement", Title: "MRAID ready state is not guarded", Detail: "Gate ad startup behind mraid.ready, or call startup immediately only when mraid.getState() is not loading.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if !mraidHasReference(ctx) || mraidHasReadyGate(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "ready-state-fallback", Severity: "requirement", Title: "MRAID ready listener/state fallback pair not found", Detail: "Use both mraid.addEventListener(\"ready\", ...) and mraid.getState() so startup works when ready fires before the listener attaches.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if !mraidHasReference(ctx) || mraidHasReadyStateFallback(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "ready-timeout-fallback", Severity: "best-practice", Title: "MRAID ready timeout fallback not found", Detail: "A timeout fallback prevents startup hangs when a container never fires ready.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if !mraidHasReference(ctx) || mraidHasReadyTimeout(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "late-mraid-detection", Severity: "best-practice", Title: "Late MRAID injection detection not found", Detail: "Poll or retry briefly for late window.mraid injection before deciding the creative is running without MRAID.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if !mraidHasReference(ctx) || mraidHasLateDetection(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "error-listener", Severity: "best-practice", Title: "No MRAID error listener found", Detail: "Listen for mraid error events so unsupported or failed MRAID calls can be logged or handled gracefully.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if !mraidHasReference(ctx) || mraidHasEventListener(ctx, "error") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "viewability", Severity: "best-practice", Title: "MRAID viewability fallback chain not found", Detail: "Use exposureChange for MRAID 3.0 and keep viewableChange or isViewable() as MRAID 2.0 fallback before starting animation, audio, video, or timers.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
hasVisibility := mraidHasEventListener(ctx, "exposureChange") && (mraidHasCall(ctx, "isViewable") || mraidHasEventListener(ctx, "viewableChange"))
|
||||||
|
if !mraidHasReference(ctx) || hasVisibility {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "audio-volume-change", Severity: "best-practice", Title: "audioVolumeChange handling not found", Detail: "Listen for audioVolumeChange and ignore null values; only apply volume math when the value is numeric.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if !mraidHasReference(ctx) || mraidHasAudioVolumeSafeHandling(ctx) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}},
|
||||||
|
{ID: "open-api", Severity: "requirement", Title: "Browser navigation used instead of mraid.open", Detail: "Use mraid.open(url) for click-through navigation inside an MRAID ad container; avoid hyperlinks, location redirects, and unguarded browser navigation.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHyperlinkRx.MatchString(ctx.HTML) || mraidUsesLocationNavigation(ctx) || (mraidUsesBrowserNavigation(ctx) && !mraidHasCall(ctx, "open")) {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "open-guarded-fallback", Severity: "requirement", Title: "mraid.open guarded fallback not found", Detail: "Guard mraid.open with function/state checks and provide a window.open fallback when MRAID is unavailable or still loading.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "open") && (!mraidHasOpenGuard(ctx) || !mraidHasOpenLoadingGuard(ctx) || !mraidUsesBrowserNavigation(ctx)) {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "open"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "open-video-url", Severity: "best-practice", Title: "mraid.open appears to target video media", Detail: "Use mraid.playVideo(url) for native video playback cases instead of mraid.open(videoUrl).", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidVideoOpenRx.MatchString(ctx.ScriptText) && !mraidHasCall(ctx, "playVideo") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "open"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "close-api", Severity: "best-practice", Title: "No mraid.close call found", Detail: "If the creative renders its own close control, wire that control to mraid.close().", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidCloseUiRx.MatchString(ctx.HTML) && !mraidHasCall(ctx, "close") {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "unload-fallback", Severity: "best-practice", Title: "No mraid.unload graceful failure path found", Detail: "Use mraid.unload() when the ad cannot run or refuses to show, instead of leaving a broken or blank creative.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasReference(ctx) && !mraidHasCall(ctx, "unload") {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "resize-properties", Severity: "requirement", Title: "mraid.resize used without setResizeProperties", Detail: "Call mraid.setResizeProperties(...) before mraid.resize(); otherwise the container should emit an error.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "resize") && !mraidHasCall(ctx, "setResizeProperties") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "resize"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "use-custom-close", Severity: "best-practice", Title: "Deprecated useCustomClose found", Detail: "MRAID 3.0 ignores useCustomClose; the host provides the mandatory close control.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "useCustomClose") || regexp.MustCompile(`(?i)useCustomClose`).MatchString(ctx.ScriptText) {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "useCustomClose"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "two-part-expand", Severity: "best-practice", Title: "Two-part expand appears to be used", Detail: "Two-part expandable ads are deprecated in MRAID 3.0; use self-contained one-part expandables.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidTwoPartExpandRx.MatchString(ctx.ScriptText) {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "expand"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "expand-support", Severity: "requirement", Title: "mraid.expand used without function guard", Detail: "Guard mraid.expand with a function check before using expand behavior.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "expand") && !mraidHasFunctionGuard(ctx, "expand") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "expand"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "resize-support", Severity: "requirement", Title: "mraid.resize used without function guard", Detail: "Guard mraid.resize with a function check before using resize behavior.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "resize") && !mraidHasFunctionGuard(ctx, "resize") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "resize"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "store-picture-support", Severity: "requirement", Title: "storePicture used without supports check", Detail: "Call mraid.supports(\"storePicture\") before mraid.storePicture(...).", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "storePicture") && !mraidHasSupportCheck(ctx, "storePicture") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "storePicture"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "calendar-support", Severity: "requirement", Title: "createCalendarEvent used without supports check", Detail: "Call mraid.supports(\"calendar\") before mraid.createCalendarEvent(...).", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "createCalendarEvent") && !mraidHasSupportCheck(ctx, "calendar") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "createCalendarEvent"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "location-support", Severity: "requirement", Title: "getLocation used without supports check", Detail: "Call mraid.supports(\"location\") before mraid.getLocation(). Do not use HTML5 geolocation as a substitute in MRAID.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "getLocation") && !mraidHasSupportCheck(ctx, "location") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "getLocation"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "vpaid-support", Severity: "requirement", Title: "VPAID integration used without supports check", Detail: "Call mraid.supports(\"vpaid\") before mraid.initVpaid(...).", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "initVpaid") && !mraidHasSupportCheck(ctx, "vpaid") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "initVpaid"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "orientation-support", Severity: "best-practice", Title: "Orientation properties set without function guard", Detail: "Guard mraid.setOrientationProperties with a function check before requiring orientation behavior.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidHasCall(ctx, "setOrientationProperties") && !mraidHasFunctionGuard(ctx, "setOrientationProperties") {
|
||||||
|
return mraidIssueFrom(rule, mraidLine(ctx, "setOrientationProperties"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "size-change", Severity: "best-practice", Title: "No sizeChange listener found", Detail: "Listen for sizeChange when layout depends on container size, resize, expand, or orientation behavior.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
depends := mraidHasCall(ctx, "getMaxSize") || mraidHasCall(ctx, "getScreenSize") || mraidHasCall(ctx, "resize") || mraidHasCall(ctx, "expand") || mraidHasCall(ctx, "setOrientationProperties")
|
||||||
|
if depends && !mraidHasEventListener(ctx, "sizeChange") {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "state-change", Severity: "best-practice", Title: "No stateChange listener found", Detail: "Listen for stateChange when using expand, resize, close, or other state-changing container behavior.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
changes := mraidHasCall(ctx, "expand") || mraidHasCall(ctx, "resize") || mraidHasCall(ctx, "close")
|
||||||
|
if changes && !mraidHasEventListener(ctx, "stateChange") {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "output-script-hygiene", Severity: "requirement", Title: "Rejected script attributes found", Detail: "Playable output should not contain type=\"module\" or crossorigin on script tags; ad networks can reject ES modules/CORS attributes.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidRejectedScriptAttrsRx.MatchString(ctx.HTML) {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "console-error", Severity: "best-practice", Title: "console.error found", Detail: "The ship checklist expects no console.error calls in output; use guarded logging or remove debug error logs before submission.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
if mraidConsoleErrorRx.MatchString(ctx.ScriptText) {
|
||||||
|
return mraidIssueFrom(rule, 0)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}},
|
||||||
|
{ID: "lifecycle-stubs", Severity: "requirement", Title: "Playable lifecycle signals not found", Detail: "Expose or call gameReady, gameStart, gameEnd, and gameClose so network preview tools can detect the playable lifecycle.", Reference: mraidReference, Test: func(ctx mraidContext, rule mraidRule) *mraidIssue {
|
||||||
|
missing := []string{}
|
||||||
|
for _, name := range []string{"gameReady", "gameStart", "gameEnd", "gameClose"} {
|
||||||
|
if !mraidHasLifecycleSignal(ctx, name) {
|
||||||
|
missing = append(missing, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(missing) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
found := mraidIssueFrom(rule, 0)
|
||||||
|
found.Detail = found.Detail + " Missing: " + strings.Join(missing, ", ") + "."
|
||||||
|
return found
|
||||||
|
}},
|
||||||
|
}
|
||||||
93
standalone/mraid_dogcat3_test.go
Normal file
93
standalone/mraid_dogcat3_test.go
Normal 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
|
||||||
|
}
|
||||||
232
standalone/platform.go
Normal file
232
standalone/platform.go
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PlecConfig struct {
|
||||||
|
UploadUrl string `json:"uploadUrl"`
|
||||||
|
OriginUrl string `json:"originUrl"`
|
||||||
|
PreviewBase string `json:"previewBase"`
|
||||||
|
SkipExistsCheck bool `json:"skipExistsCheck"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApplovinConfig struct {
|
||||||
|
Cookie string `json:"cookie"`
|
||||||
|
DelayMs int `json:"delayMs"`
|
||||||
|
RandomizeUserAgent *bool `json:"randomizeUserAgent,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SendToMobileConfig struct {
|
||||||
|
Port int `json:"port"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AppConfig struct {
|
||||||
|
Plec PlecConfig `json:"plec"`
|
||||||
|
Applovin ApplovinConfig `json:"applovin"`
|
||||||
|
SendToMobile SendToMobileConfig `json:"sendToMobile"`
|
||||||
|
BetaToolsEnabled bool `json:"betaToolsEnabled"`
|
||||||
|
LastPickDir string `json:"lastPickDir,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var configMu sync.Mutex
|
||||||
|
|
||||||
|
// userDataDir returns %LOCALAPPDATA%\HPLToolbox, creating it if needed.
|
||||||
|
// All mutable app files (config, lock, logs, WebView2 cache) live here so
|
||||||
|
// they are never placed next to the executable, which may be on a synced or
|
||||||
|
// antivirus-watched drive and would cause message-loop stalls.
|
||||||
|
func userDataDir() string {
|
||||||
|
local := os.Getenv("LOCALAPPDATA")
|
||||||
|
if local == "" {
|
||||||
|
local = os.Getenv("APPDATA")
|
||||||
|
}
|
||||||
|
if local == "" {
|
||||||
|
return appDir()
|
||||||
|
}
|
||||||
|
dir := filepath.Join(local, "HPLToolbox")
|
||||||
|
_ = os.MkdirAll(dir, 0755)
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultConfig() AppConfig {
|
||||||
|
return AppConfig{
|
||||||
|
Plec: PlecConfig{
|
||||||
|
UploadUrl: "http://167.99.227.249/src/upload_HTML_Experimental.php",
|
||||||
|
OriginUrl: "http://167.99.227.249",
|
||||||
|
PreviewBase: "https://playable.applovindemo.com/phaser/",
|
||||||
|
SkipExistsCheck: false,
|
||||||
|
},
|
||||||
|
Applovin: ApplovinConfig{Cookie: "", DelayMs: 5000},
|
||||||
|
SendToMobile: SendToMobileConfig{Port: 0},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func appDir() string {
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
wd, _ := os.Getwd()
|
||||||
|
return wd
|
||||||
|
}
|
||||||
|
// `go run` puts the exe in a temp dir; fall back to cwd in that case.
|
||||||
|
resolved, err := filepath.EvalSymlinks(exe)
|
||||||
|
if err == nil {
|
||||||
|
exe = resolved
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(exe)
|
||||||
|
if strings.Contains(strings.ToLower(dir), "go-build") {
|
||||||
|
wd, _ := os.Getwd()
|
||||||
|
return wd
|
||||||
|
}
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
|
||||||
|
func configPath() string {
|
||||||
|
return filepath.Join(userDataDir(), "config.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadConfig() AppConfig {
|
||||||
|
configMu.Lock()
|
||||||
|
defer configMu.Unlock()
|
||||||
|
cfg := defaultConfig()
|
||||||
|
data, err := os.ReadFile(configPath())
|
||||||
|
if err != nil {
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(data, &cfg)
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func SaveConfig(cfg AppConfig) error {
|
||||||
|
configMu.Lock()
|
||||||
|
defer configMu.Unlock()
|
||||||
|
data, err := json.MarshalIndent(cfg, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(configPath(), data, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
func OpenInBrowser(url string) {
|
||||||
|
cmd := hiddenCommand("rundll32.exe", "url.dll,FileProtocolHandler", url)
|
||||||
|
_ = cmd.Start()
|
||||||
|
}
|
||||||
|
|
||||||
|
func CopyToClipboard(text string) error {
|
||||||
|
cmd := hiddenCommand("clip")
|
||||||
|
cmd.Stdin = strings.NewReader(text)
|
||||||
|
return cmd.Run()
|
||||||
|
}
|
||||||
|
|
||||||
|
type FileFilter struct {
|
||||||
|
Name string
|
||||||
|
Extensions []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func psEscape(s string) string { return strings.ReplaceAll(s, "'", "''") }
|
||||||
|
|
||||||
|
func hiddenCommand(name string, args ...string) *exec.Cmd {
|
||||||
|
cmd := exec.Command(name, args...)
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||||
|
HideWindow: true,
|
||||||
|
CreationFlags: 0x08000000,
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func PickFiles(title string, filters []FileFilter, multi bool, initialDir string) []string {
|
||||||
|
filterStr := "All files|*.*"
|
||||||
|
if len(filters) > 0 {
|
||||||
|
parts := make([]string, 0, len(filters))
|
||||||
|
for _, f := range filters {
|
||||||
|
exts := make([]string, 0, len(f.Extensions))
|
||||||
|
for _, e := range f.Extensions {
|
||||||
|
exts = append(exts, "*."+e)
|
||||||
|
}
|
||||||
|
parts = append(parts, fmt.Sprintf("%s|%s", f.Name, strings.Join(exts, ";")))
|
||||||
|
}
|
||||||
|
filterStr = strings.Join(parts, "|")
|
||||||
|
}
|
||||||
|
multiStr := "false"
|
||||||
|
if multi {
|
||||||
|
multiStr = "true"
|
||||||
|
}
|
||||||
|
script := fmt.Sprintf(`
|
||||||
|
Add-Type -AssemblyName System.Windows.Forms
|
||||||
|
$dlg = New-Object System.Windows.Forms.OpenFileDialog
|
||||||
|
$dlg.Title = '%s'
|
||||||
|
$dlg.Filter = '%s'
|
||||||
|
$dlg.Multiselect = $%s
|
||||||
|
if ('%s'.Length -gt 0) { $dlg.InitialDirectory = '%s' }
|
||||||
|
if ($dlg.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
|
||||||
|
$dlg.FileNames | ForEach-Object { Write-Output $_ }
|
||||||
|
}
|
||||||
|
`, psEscape(title), psEscape(filterStr), multiStr, psEscape(initialDir), psEscape(initialDir))
|
||||||
|
out, err := hiddenCommand("powershell", "-NoProfile", "-NonInteractive", "-STA", "-Command", script).Output()
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
lines := strings.Split(string(out), "\n")
|
||||||
|
result := make([]string, 0, len(lines))
|
||||||
|
for _, l := range lines {
|
||||||
|
t := strings.TrimSpace(l)
|
||||||
|
if t != "" {
|
||||||
|
result = append(result, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func PickSaveFile(title, defaultName string, filters []FileFilter, initialDir string) string {
|
||||||
|
filterStr := "All files|*.*"
|
||||||
|
if len(filters) > 0 {
|
||||||
|
parts := make([]string, 0, len(filters))
|
||||||
|
for _, f := range filters {
|
||||||
|
exts := make([]string, 0, len(f.Extensions))
|
||||||
|
for _, e := range f.Extensions {
|
||||||
|
exts = append(exts, "*."+e)
|
||||||
|
}
|
||||||
|
parts = append(parts, fmt.Sprintf("%s|%s", f.Name, strings.Join(exts, ";")))
|
||||||
|
}
|
||||||
|
filterStr = strings.Join(parts, "|")
|
||||||
|
}
|
||||||
|
script := fmt.Sprintf(`
|
||||||
|
Add-Type -AssemblyName System.Windows.Forms
|
||||||
|
$dlg = New-Object System.Windows.Forms.SaveFileDialog
|
||||||
|
$dlg.Title = '%s'
|
||||||
|
$dlg.Filter = '%s'
|
||||||
|
$dlg.FileName = '%s'
|
||||||
|
if ('%s'.Length -gt 0) { $dlg.InitialDirectory = '%s' }
|
||||||
|
if ($dlg.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
|
||||||
|
Write-Output $dlg.FileName
|
||||||
|
}
|
||||||
|
`, psEscape(title), psEscape(filterStr), psEscape(defaultName), psEscape(initialDir), psEscape(initialDir))
|
||||||
|
out, err := hiddenCommand("powershell", "-NoProfile", "-NonInteractive", "-STA", "-Command", script).Output()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
func PickFolder(title, initialDir string) string {
|
||||||
|
script := fmt.Sprintf(`
|
||||||
|
Add-Type -AssemblyName System.Windows.Forms
|
||||||
|
$dlg = New-Object System.Windows.Forms.FolderBrowserDialog
|
||||||
|
$dlg.Description = '%s'
|
||||||
|
if ('%s'.Length -gt 0) { $dlg.SelectedPath = '%s' }
|
||||||
|
if ($dlg.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
|
||||||
|
Write-Output $dlg.SelectedPath
|
||||||
|
}
|
||||||
|
`, psEscape(title), psEscape(initialDir), psEscape(initialDir))
|
||||||
|
out, err := hiddenCommand("powershell", "-NoProfile", "-NonInteractive", "-STA", "-Command", script).Output()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(out))
|
||||||
|
}
|
||||||
728
standalone/playworks.go
Normal file
728
standalone/playworks.go
Normal file
@@ -0,0 +1,728 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type playworksConvertOptions struct {
|
||||||
|
SourcePath string `json:"sourcePath"`
|
||||||
|
OutputDir string `json:"outputDir"`
|
||||||
|
BaseName string `json:"baseName"`
|
||||||
|
Networks []string `json:"networks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type playworksNetworkResult struct {
|
||||||
|
Network string `json:"network"`
|
||||||
|
File string `json:"file"`
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlayworksPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">Playworks Converter</h2>
|
||||||
|
<p class="tool-description">Convert a Playworks HTML export into network-specific playable outputs.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.net-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(250px,1fr)); gap:4px 12px; }
|
||||||
|
.net-row { display:flex; align-items:center; gap:8px; padding:6px 8px; cursor:pointer; user-select:none; border:1px solid #333; border-radius:4px; background:rgba(128,128,128,0.06); }
|
||||||
|
.net-label { min-width:100px; font-weight:500; }
|
||||||
|
.net-tag { font-size:10px; opacity:0.6; font-weight:400; }
|
||||||
|
.net-note { font-size:11px; opacity:0.6; }
|
||||||
|
.toggle-row { display:flex; gap:8px; margin-bottom:6px; }
|
||||||
|
.toggle-row button { font-size:11px; padding:2px 8px; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<section class="tool-panel">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Inputs</h3></div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Source HTML (Playworks export)</div>
|
||||||
|
<div id="dropZone" class="drop-zone">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickSrc" class="secondary">Select File</button>
|
||||||
|
<button id="clearSrc" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div class="drop-zone-text">or drop a Playworks HTML file here</div>
|
||||||
|
</div>
|
||||||
|
<input id="src" type="hidden" />
|
||||||
|
<div id="sourceSelection" class="selected-list"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Base Filename</div>
|
||||||
|
<div class="field-row">
|
||||||
|
<input id="baseName" type="text" placeholder="Base filename..." style="flex:1;" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Output Folder</div>
|
||||||
|
<div class="field-row">
|
||||||
|
<input id="outDir" type="text" placeholder="Output folder..." style="flex:1;" />
|
||||||
|
<button id="pickOut" class="secondary">Select Folder</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="control-label">Networks to generate</div>
|
||||||
|
<div class="toggle-row">
|
||||||
|
<button id="selectAll" class="secondary">All</button>
|
||||||
|
<button id="selectNone" class="secondary">None</button>
|
||||||
|
</div>
|
||||||
|
<div class="net-grid">
|
||||||
|
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="al" checked /><span class="net-label">Applovin <span class="net-tag">al</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="is" checked /><span class="net-label">Ironsource <span class="net-tag">is</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="fb" checked /><span class="net-label">Facebook <span class="net-tag">fb</span></span><span class="net-note">HTML</span></label>
|
||||||
|
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="gg" checked /><span class="net-label">Google Ads <span class="net-tag">gg</span></span><span class="net-note">ZIP + exitapi.js in head</span></label>
|
||||||
|
<label class="net-row"><input type="checkbox" class="net-cb" data-tag="ap" checked /><span class="net-label">Appreciate <span class="net-tag">ap</span></span><span class="net-note">ZIP + exitapi.js in head</span></label>
|
||||||
|
<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="tt" /><span class="net-label">TikTok <span class="net-tag">tt</span></span><span class="net-note">HTML + __TIKTOK__ flag</span></label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="convert" disabled>Convert</button>
|
||||||
|
<button id="openOut" class="secondary" disabled>Open Output Folder</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div id="results" class="results-panel"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let outputDir = '';
|
||||||
|
const srcEl = document.getElementById('src');
|
||||||
|
const outEl = document.getElementById('outDir');
|
||||||
|
const baseNameEl = document.getElementById('baseName');
|
||||||
|
const convertBtn = document.getElementById('convert');
|
||||||
|
const openOutBtn = document.getElementById('openOut');
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const resultsEl = document.getElementById('results');
|
||||||
|
const sourceSelectionEl = document.getElementById('sourceSelection');
|
||||||
|
|
||||||
|
async function readJSONStream(response, handle) {
|
||||||
|
if (!response.ok || !response.body) throw new Error('Request failed.');
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
let newline;
|
||||||
|
while ((newline = buffer.indexOf('\n')) >= 0) {
|
||||||
|
const line = buffer.slice(0, newline);
|
||||||
|
buffer = buffer.slice(newline + 1);
|
||||||
|
if (line.trim()) handle(JSON.parse(line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffer.trim()) handle(JSON.parse(buffer));
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateConvertBtn() {
|
||||||
|
const hasNet = [...document.querySelectorAll('.net-cb')].some(c => c.checked);
|
||||||
|
convertBtn.disabled = !srcEl.value || !outEl.value || !baseNameEl.value.trim() || !hasNet;
|
||||||
|
}
|
||||||
|
|
||||||
|
function basename(p) {
|
||||||
|
const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
|
||||||
|
return i >= 0 ? p.slice(i + 1) : p;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s){
|
||||||
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSourceSelection() {
|
||||||
|
if (!srcEl.value) {
|
||||||
|
sourceSelectionEl.innerHTML = '<span class="file-name">(no file selected)</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sourceSelectionEl.innerHTML = '<div class="results-panel" style="margin-top:0;"><table class="data-table">' +
|
||||||
|
'<thead><tr><th>Filename</th><th style="width:44px;"></th></tr></thead><tbody>' +
|
||||||
|
'<tr><td class="mono wrap">' + escapeHtml(basename(srcEl.value)) + '</td><td><button id="removeSource" class="remove-selected danger" title="Remove">×</button></td></tr>' +
|
||||||
|
'</tbody></table></div>';
|
||||||
|
document.getElementById('removeSource').addEventListener('click', clearSource);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSource(path, baseName, dir) {
|
||||||
|
srcEl.value = path || '';
|
||||||
|
baseNameEl.value = baseName || '';
|
||||||
|
if (!outEl.value && dir) { outEl.value = defaultOutputDir(dir); outputDir = outEl.value; }
|
||||||
|
renderSourceSelection();
|
||||||
|
updateConvertBtn();
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultOutputDir(dir) {
|
||||||
|
return dir ? dir.replace(/[\\\/]+$/, '') + '\\Output' : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSource() {
|
||||||
|
srcEl.value = '';
|
||||||
|
baseNameEl.value = '';
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
renderSourceSelection();
|
||||||
|
updateConvertBtn();
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('pickSrc').addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/playworks/pickSource', { method:'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
if (j.path) {
|
||||||
|
setSource(j.path, j.baseName || '', j.dir || '');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.getElementById('clearSrc').addEventListener('click', clearSource);
|
||||||
|
document.getElementById('pickOut').addEventListener('click', async () => {
|
||||||
|
const r = await fetch('/api/playworks/pickOutput', { method:'POST' });
|
||||||
|
const j = await r.json();
|
||||||
|
if (j.path) { outEl.value = j.path; outputDir = j.path; updateConvertBtn(); }
|
||||||
|
});
|
||||||
|
document.getElementById('selectAll').addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.net-cb').forEach(c => c.checked = c.dataset.tag !== 'tt');
|
||||||
|
updateConvertBtn();
|
||||||
|
});
|
||||||
|
document.getElementById('selectNone').addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.net-cb').forEach(c => c.checked = false);
|
||||||
|
updateConvertBtn();
|
||||||
|
});
|
||||||
|
document.querySelectorAll('.net-cb').forEach(c => c.addEventListener('change', updateConvertBtn));
|
||||||
|
outEl.addEventListener('input', updateConvertBtn);
|
||||||
|
baseNameEl.addEventListener('input', updateConvertBtn);
|
||||||
|
openOutBtn.addEventListener('click', () => {
|
||||||
|
if (outputDir) fetch('/api/open', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ url: outputDir }) });
|
||||||
|
});
|
||||||
|
|
||||||
|
function outputDisplayName(file) {
|
||||||
|
const parts = file.split(/[\\\\/]/).filter(Boolean);
|
||||||
|
return parts.slice(-2).join('/');
|
||||||
|
}
|
||||||
|
setupDropZone('dropZone', statusEl, (j) => {
|
||||||
|
const paths = j.paths || [];
|
||||||
|
if (!paths.length) {
|
||||||
|
if (j.skipped) statusEl.textContent = 'Skipped ' + j.skipped + ' non-HTML or unavailable item(s).';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const sourcePath = paths[0];
|
||||||
|
const droppedBase = basename(sourcePath).replace(/\\.html?$/i, '').replace(/_(?:un|al|is|fb|gg|ap|mo|vu|mtg|tt)$/i, '');
|
||||||
|
const i = Math.max(sourcePath.lastIndexOf('/'), sourcePath.lastIndexOf('\\\\'));
|
||||||
|
setSource(sourcePath, droppedBase, i >= 0 ? sourcePath.slice(0, i) : '');
|
||||||
|
const skipped = Number(j.skipped || 0) + Math.max(0, paths.length - 1);
|
||||||
|
if (skipped) statusEl.textContent = 'Using first dropped HTML file. Skipped ' + skipped + ' other item(s).';
|
||||||
|
});
|
||||||
|
renderSourceSelection();
|
||||||
|
|
||||||
|
document.getElementById('convert').addEventListener('click', async () => {
|
||||||
|
const networks = [...document.querySelectorAll('.net-cb')].filter(c => c.checked).map(c => c.dataset.tag);
|
||||||
|
statusEl.textContent = 'Converting...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
resultsEl.innerHTML = '';
|
||||||
|
openOutBtn.disabled = true;
|
||||||
|
convertBtn.disabled = true;
|
||||||
|
const res = await fetch('/api/playworks/convert', {
|
||||||
|
method:'POST',
|
||||||
|
headers:{'Content-Type':'application/json'},
|
||||||
|
body: JSON.stringify({ sourcePath: srcEl.value, outputDir: outEl.value, baseName: baseNameEl.value, networks })
|
||||||
|
});
|
||||||
|
let msg = null;
|
||||||
|
try {
|
||||||
|
await readJSONStream(res, (event) => {
|
||||||
|
if (event.type === 'status') {
|
||||||
|
statusEl.textContent = event.message;
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
} else if (event.type === 'done') {
|
||||||
|
msg = event;
|
||||||
|
} else if (event.type === 'error') {
|
||||||
|
msg = { error: event.message, results: event.results || [] };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
msg = { error: e.message || e, results: [] };
|
||||||
|
}
|
||||||
|
convertBtn.disabled = false;
|
||||||
|
updateConvertBtn();
|
||||||
|
if (!msg) { msg = { error: 'No response.', results: [] }; }
|
||||||
|
if (msg.error) { statusEl.classList.remove('is-busy'); statusEl.textContent = 'Error: ' + msg.error; return; }
|
||||||
|
const results = msg.results || [];
|
||||||
|
const ok = results.filter(r => r.ok).length;
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.textContent = ok + ' of ' + results.length + ' network(s) converted.';
|
||||||
|
if (!results.length) { resultsEl.innerHTML = ''; return; }
|
||||||
|
resultsEl.innerHTML = '<table class="data-table"><thead><tr><th style="width:120px;">Network</th><th style="width:90px;">Status</th><th>Output Path</th><th>Error</th></tr></thead><tbody></tbody></table>';
|
||||||
|
const tbody = resultsEl.querySelector('tbody');
|
||||||
|
for (const r of results) {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
row.innerHTML = '<td class="mono">' + r.network + '</td>' +
|
||||||
|
'<td>' + (r.ok ? '<span class="badge ok">OK</span>' : '<span class="badge err">Error</span>') + '</td>' +
|
||||||
|
'<td class="mono wrap">' + (r.ok ? outputDisplayName(r.file) : '<span class="muted">-</span>') + '</td>' +
|
||||||
|
'<td class="err wrap">' + (r.ok ? '' : (r.error || 'Unknown error')) + '</td>';
|
||||||
|
tbody.appendChild(row);
|
||||||
|
}
|
||||||
|
if (ok > 0) { outputDir = outEl.value; openOutBtn.disabled = false; }
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/playworks", "Playworks Converter", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlayworksPickSource(w http.ResponseWriter, r *http.Request) {
|
||||||
|
picked := PickFiles("Select Playworks HTML", []FileFilter{{Name: "HTML", Extensions: []string{"html", "htm"}}}, false, "")
|
||||||
|
if len(picked) == 0 {
|
||||||
|
writeJSON(w, map[string]any{})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"path": picked[0], "dir": filepath.Dir(picked[0]), "baseName": playworksSourceBaseName(picked[0])})
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlayworksPickOutput(w http.ResponseWriter, r *http.Request) {
|
||||||
|
writeJSON(w, map[string]any{"path": PickFolder("Select Output Folder", "")})
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlayworksConvert(w http.ResponseWriter, r *http.Request) {
|
||||||
|
send := newJSONStream(w)
|
||||||
|
var opts playworksConvertOptions
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&opts); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error(), "results": []playworksNetworkResult{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !fileExists(opts.SourcePath) {
|
||||||
|
send(map[string]any{"type": "error", "message": "Source file not found.", "results": []playworksNetworkResult{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(opts.OutputDir, 0755); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Could not create output folder.", "results": []playworksNetworkResult{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "status", "message": "Reading source HTML..."})
|
||||||
|
data, err := os.ReadFile(opts.SourcePath)
|
||||||
|
if err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Could not read source: " + err.Error(), "results": []playworksNetworkResult{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
results := []playworksNetworkResult{}
|
||||||
|
send(map[string]any{"type": "status", "message": "Converting Unity..."})
|
||||||
|
unityPath, err := copyPlayworksUnityInput(data, opts)
|
||||||
|
if err != nil {
|
||||||
|
results = append(results, playworksNetworkResult{Network: "un", OK: false, Error: err.Error()})
|
||||||
|
} else {
|
||||||
|
results = append(results, playworksNetworkResult{Network: "un", File: unityPath, OK: true})
|
||||||
|
}
|
||||||
|
for i, network := range opts.Networks {
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Converting %d/%d %s", i+1, len(opts.Networks), network)})
|
||||||
|
filePath, err := convertPlayworksNetwork(string(data), opts, network)
|
||||||
|
if err != nil {
|
||||||
|
results = append(results, playworksNetworkResult{Network: network, OK: false, Error: err.Error()})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
results = append(results, playworksNetworkResult{Network: network, File: filePath, OK: true})
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "done", "results": results})
|
||||||
|
}
|
||||||
|
|
||||||
|
var playworksSuffixRx = regexp.MustCompile(`_(?:un|al|is|fb|gg|ap|mo|vu|mtg|tt)$`)
|
||||||
|
var playworksMraidScriptRx = regexp.MustCompile(`(?i)<script\b[^>]*\bsrc\s*=\s*["']mraid\.js["'][^>]*>\s*</script>\s*`)
|
||||||
|
var playworksExitapiScriptRx = regexp.MustCompile(`(?i)<script\b[^>]*\bsrc\s*=\s*["']exitapi\.js["'][^>]*>\s*</script>\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))
|
||||||
|
return playworksSuffixRx.ReplaceAllString(base, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func playworksOutputBaseName(opts playworksConvertOptions) string {
|
||||||
|
baseName := strings.TrimSpace(opts.BaseName)
|
||||||
|
if baseName == "" {
|
||||||
|
baseName = playworksSourceBaseName(opts.SourcePath)
|
||||||
|
}
|
||||||
|
baseName = strings.TrimSuffix(baseName, filepath.Ext(baseName))
|
||||||
|
baseName = filepath.Base(baseName)
|
||||||
|
baseName = strings.Map(func(r rune) rune {
|
||||||
|
switch r {
|
||||||
|
case '<', '>', ':', '"', '/', '\\', '|', '?', '*':
|
||||||
|
return '_'
|
||||||
|
default:
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
}, baseName)
|
||||||
|
baseName = strings.TrimSpace(baseName)
|
||||||
|
if baseName == "" {
|
||||||
|
return playworksSourceBaseName(opts.SourcePath)
|
||||||
|
}
|
||||||
|
return baseName
|
||||||
|
}
|
||||||
|
|
||||||
|
func convertPlayworksNetwork(htmlSrc string, opts playworksConvertOptions, network string) (string, error) {
|
||||||
|
if !playworksIsSupportedNetwork(network) {
|
||||||
|
return "", fmt.Errorf("unsupported Playworks target network: %s", network)
|
||||||
|
}
|
||||||
|
transformed := transformPlayworksHTML(htmlSrc, network)
|
||||||
|
baseName := playworksOutputBaseName(opts)
|
||||||
|
htmlFileName := fmt.Sprintf("%s_%s.html", baseName, network)
|
||||||
|
outputDir := filepath.Join(opts.OutputDir, playworksNetworkOutputFolder(network))
|
||||||
|
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if playworksNeedsZip(network) {
|
||||||
|
zipPath := filepath.Join(outputDir, fmt.Sprintf("%s_%s.zip", baseName, network))
|
||||||
|
if err := createSingleFileZip([]byte(transformed), "index.html", zipPath); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return zipPath, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
outPath := filepath.Join(outputDir, htmlFileName)
|
||||||
|
if err := os.WriteFile(outPath, []byte(transformed), 0644); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return outPath, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyPlayworksUnityInput(data []byte, opts playworksConvertOptions) (string, error) {
|
||||||
|
baseName := playworksOutputBaseName(opts)
|
||||||
|
outputDir := filepath.Join(opts.OutputDir, "Unity")
|
||||||
|
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
outPath := filepath.Join(outputDir, fmt.Sprintf("%s_un.html", baseName))
|
||||||
|
if err := os.WriteFile(outPath, data, 0644); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return outPath, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func playworksNetworkOutputFolder(network string) string {
|
||||||
|
switch network {
|
||||||
|
case "al":
|
||||||
|
return "Applovin"
|
||||||
|
case "is":
|
||||||
|
return "Ironsource"
|
||||||
|
case "fb":
|
||||||
|
return "Facebook"
|
||||||
|
case "gg":
|
||||||
|
return "GoogleAds"
|
||||||
|
case "ap":
|
||||||
|
return "Appreciate"
|
||||||
|
case "mo":
|
||||||
|
return "Moloco"
|
||||||
|
case "vu":
|
||||||
|
return "Vungle"
|
||||||
|
case "mtg":
|
||||||
|
return "Mintegral"
|
||||||
|
case "tt":
|
||||||
|
return "TikTok"
|
||||||
|
default:
|
||||||
|
return network
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func playworksNeedsZip(network string) bool {
|
||||||
|
return network == "gg" || network == "ap" || network == "vu" || network == "mtg"
|
||||||
|
}
|
||||||
|
|
||||||
|
func playworksIsMraidNetwork(network string) bool {
|
||||||
|
return network == "al" || network == "is"
|
||||||
|
}
|
||||||
|
|
||||||
|
func playworksIsExitapiNetwork(network string) bool {
|
||||||
|
return network == "gg" || network == "ap"
|
||||||
|
}
|
||||||
|
|
||||||
|
func playworksIsSupportedNetwork(network string) bool {
|
||||||
|
switch network {
|
||||||
|
case "al", "is", "fb", "gg", "ap", "mo", "vu", "mtg", "tt":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func transformPlayworksHTML(htmlSrc, network string) string {
|
||||||
|
result := sanitizePlayworksHTML(htmlSrc)
|
||||||
|
headInject := buildPlayworksLifecycleScript()
|
||||||
|
if playworksIsMraidNetwork(network) {
|
||||||
|
headInject += `<script src="mraid.js"></script>` + buildPlayworksMraidComplianceScript()
|
||||||
|
} else if playworksIsExitapiNetwork(network) {
|
||||||
|
headInject += `<script src="exitapi.js"></script>`
|
||||||
|
}
|
||||||
|
result = injectPlayworksBeforeHeadClose(result, headInject)
|
||||||
|
|
||||||
|
if network == "vu" {
|
||||||
|
result = injectPlayworksAfterBodyOpen(result, `<script>window.__VUNGLE__=true;</script>`)
|
||||||
|
} else if network == "mtg" {
|
||||||
|
result = addPlayworksBodyOnload(result, "gameReady()")
|
||||||
|
} else if network == "tt" {
|
||||||
|
result = injectPlayworksAfterBodyOpen(result, `<script>window.__TIKTOK__=true;</script>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 trimPlayworksAfterFirstHTMLClose(htmlSrc string) string {
|
||||||
|
loc := playworksHtmlCloseRx.FindStringIndex(htmlSrc)
|
||||||
|
if loc == nil {
|
||||||
|
return htmlSrc
|
||||||
|
}
|
||||||
|
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", playworksIsExitapiNetwork(network))
|
||||||
|
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 {
|
||||||
|
loc := playworksHeadCloseRx.FindStringIndex(htmlSrc)
|
||||||
|
if loc != nil {
|
||||||
|
return htmlSrc[:loc[0]] + injection + "\n" + htmlSrc[loc[0]:]
|
||||||
|
}
|
||||||
|
return injection + "\n" + htmlSrc
|
||||||
|
}
|
||||||
|
|
||||||
|
func injectPlayworksAfterBodyOpen(htmlSrc, injection string) string {
|
||||||
|
loc := playworksBodyOpenRx.FindStringIndex(htmlSrc)
|
||||||
|
if loc == nil {
|
||||||
|
return injection + "\n" + htmlSrc
|
||||||
|
}
|
||||||
|
return htmlSrc[:loc[1]] + "\n" + injection + htmlSrc[loc[1]:]
|
||||||
|
}
|
||||||
|
|
||||||
|
func addPlayworksBodyOnload(htmlSrc, handler string) string {
|
||||||
|
loc := playworksBodyTagRx.FindStringSubmatchIndex(htmlSrc)
|
||||||
|
if loc == nil {
|
||||||
|
return `<body onload="` + handler + `">` + "\n" + htmlSrc
|
||||||
|
}
|
||||||
|
attrs := htmlSrc[loc[2]:loc[3]]
|
||||||
|
onloadStart, onloadEnd, quote, valueStart, valueEnd := findPlayworksOnloadAttr(attrs)
|
||||||
|
if onloadStart == -1 {
|
||||||
|
updated := `<body` + attrs + ` onload="` + handler + `">`
|
||||||
|
return htmlSrc[:loc[0]] + updated + htmlSrc[loc[1]:]
|
||||||
|
}
|
||||||
|
value := attrs[valueStart:valueEnd]
|
||||||
|
if strings.Contains(value, handler) {
|
||||||
|
return htmlSrc
|
||||||
|
}
|
||||||
|
replacement := `onload=` + quote + value + `;` + handler + quote
|
||||||
|
updatedAttrs := attrs[:onloadStart] + replacement + attrs[onloadEnd:]
|
||||||
|
updatedTag := `<body` + updatedAttrs + `>`
|
||||||
|
return htmlSrc[:loc[0]] + updatedTag + htmlSrc[loc[1]:]
|
||||||
|
}
|
||||||
|
|
||||||
|
func findPlayworksOnloadAttr(attrs string) (start int, end int, quote string, valueStart int, valueEnd int) {
|
||||||
|
lower := strings.ToLower(attrs)
|
||||||
|
idx := strings.Index(lower, "onload")
|
||||||
|
for idx != -1 {
|
||||||
|
if idx > 0 {
|
||||||
|
prev := lower[idx-1]
|
||||||
|
if (prev >= 'a' && prev <= 'z') || (prev >= '0' && prev <= '9') || prev == '-' || prev == '_' {
|
||||||
|
next := strings.Index(lower[idx+len("onload"):], "onload")
|
||||||
|
if next == -1 {
|
||||||
|
return -1, -1, "", -1, -1
|
||||||
|
}
|
||||||
|
idx += len("onload") + next
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pos := idx + len("onload")
|
||||||
|
for pos < len(attrs) && (attrs[pos] == ' ' || attrs[pos] == '\t' || attrs[pos] == '\n' || attrs[pos] == '\r') {
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
if pos >= len(attrs) || attrs[pos] != '=' {
|
||||||
|
return -1, -1, "", -1, -1
|
||||||
|
}
|
||||||
|
pos++
|
||||||
|
for pos < len(attrs) && (attrs[pos] == ' ' || attrs[pos] == '\t' || attrs[pos] == '\n' || attrs[pos] == '\r') {
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
if pos >= len(attrs) || (attrs[pos] != '"' && attrs[pos] != '\'') {
|
||||||
|
return -1, -1, "", -1, -1
|
||||||
|
}
|
||||||
|
q := attrs[pos]
|
||||||
|
valueStart = pos + 1
|
||||||
|
valueEnd = strings.IndexByte(attrs[valueStart:], q)
|
||||||
|
if valueEnd == -1 {
|
||||||
|
return -1, -1, "", -1, -1
|
||||||
|
}
|
||||||
|
valueEnd += valueStart
|
||||||
|
return idx, valueEnd + 1, string(q), valueStart, valueEnd
|
||||||
|
}
|
||||||
|
return -1, -1, "", -1, -1
|
||||||
|
}
|
||||||
|
|
||||||
|
func replacePlayworksCTAScript(htmlSrc, network string) string {
|
||||||
|
marker := "Luna.Unity.Playable.InstallFullGame=function"
|
||||||
|
markerIdx := strings.LastIndex(htmlSrc, marker)
|
||||||
|
if markerIdx == -1 {
|
||||||
|
return htmlSrc
|
||||||
|
}
|
||||||
|
scriptOpenIdx := strings.LastIndex(htmlSrc[:markerIdx], "<script>")
|
||||||
|
if scriptOpenIdx == -1 {
|
||||||
|
return htmlSrc
|
||||||
|
}
|
||||||
|
scriptCloseRel := strings.Index(htmlSrc[markerIdx:], "</script>")
|
||||||
|
if scriptCloseRel == -1 {
|
||||||
|
return htmlSrc
|
||||||
|
}
|
||||||
|
scriptCloseIdx := markerIdx + scriptCloseRel
|
||||||
|
return htmlSrc[:scriptOpenIdx] + buildPlayworksConsoleRestoreScript() + buildPlayworksCTAScript(network) + htmlSrc[scriptCloseIdx+len("</script>"):]
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildPlayworksConsoleRestoreScript() string {
|
||||||
|
return strings.Join([]string{
|
||||||
|
`<script>(function(){`,
|
||||||
|
`try{`,
|
||||||
|
`var f=document.createElement("iframe");`,
|
||||||
|
`f.style.display="none";`,
|
||||||
|
`document.documentElement.appendChild(f);`,
|
||||||
|
`var nc=f.contentWindow.console;`,
|
||||||
|
`document.documentElement.removeChild(f);`,
|
||||||
|
`var methods=["log","warn","error","info","debug","dir","table","group","groupEnd","groupCollapsed","time","timeEnd","assert","count","countReset","trace"];`,
|
||||||
|
`methods.forEach(function(m){try{if(typeof nc[m]==="function")window.console[m]=nc[m].bind(nc);}catch(e){}});`,
|
||||||
|
`}catch(e){}`,
|
||||||
|
`})();</script>`,
|
||||||
|
}, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildPlayworksLifecycleScript() string {
|
||||||
|
return strings.Join([]string{
|
||||||
|
`<script>(function(){`,
|
||||||
|
`if(typeof window.gameReady!=="function")window.gameReady=function(){};`,
|
||||||
|
`if(typeof window.gameStart!=="function")window.gameStart=function(){};`,
|
||||||
|
`if(typeof window.gameEnd!=="function")window.gameEnd=function(){};`,
|
||||||
|
`if(typeof window.gameClose!=="function")window.gameClose=function(){};`,
|
||||||
|
`var _grOnce=false,_gsOnce=false;`,
|
||||||
|
`window.addEventListener("luna:build",function(){if(_grOnce)return;_grOnce=true;try{window.gameReady();}catch(e){}});`,
|
||||||
|
`window.addEventListener("luna:start",function(){if(_gsOnce)return;_gsOnce=true;try{window.gameStart();}catch(e){}});`,
|
||||||
|
`window.addEventListener("luna:ended",function(){try{window.gameEnd();}catch(e){}});`,
|
||||||
|
`})();</script>`,
|
||||||
|
}, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
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":
|
||||||
|
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");`
|
||||||
|
case "gg", "ap":
|
||||||
|
ctaLogic = closeCall + `if(typeof ExitApi!=="undefined"&&typeof ExitApi.exit==="function"){ExitApi.exit();return;}window.open(o,"_blank");`
|
||||||
|
case "mo":
|
||||||
|
ctaLogic = closeCall + `if(typeof FbPlayableAd!=="undefined"&&typeof FbPlayableAd.onCTAClick==="function"){FbPlayableAd.onCTAClick();return;}if(typeof window.clickTag==="string"&&window.clickTag){window.open(window.clickTag,"_blank");return;}window.open(o,"_blank");`
|
||||||
|
case "vu":
|
||||||
|
ctaLogic = closeCall + `try{parent.postMessage("download","*");}catch(e){}`
|
||||||
|
case "mtg":
|
||||||
|
ctaLogic = closeCall + `if(typeof window.install==="function"){window.install();return;}window.open(o,"_blank");`
|
||||||
|
case "tt":
|
||||||
|
ctaLogic = closeCall + `if(typeof window.openAppStore==="function"){window.openAppStore();return;}window.open(o,"_blank");`
|
||||||
|
}
|
||||||
|
return `<script>window.addEventListener("luna:build",(function(){Bridge.ready((function(){Luna.Unity.Playable.InstallFullGame=function(n,i){window.pi.logCta(),` + urlSetup + ctaLogic + `}}))}));</script>`
|
||||||
|
}
|
||||||
|
|
||||||
|
func createSingleFileZip(data []byte, nameInZip, destZipPath string) error {
|
||||||
|
_ = os.Remove(destZipPath)
|
||||||
|
out, err := os.Create(destZipPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer out.Close()
|
||||||
|
|
||||||
|
zw := zip.NewWriter(out)
|
||||||
|
entry, err := zw.Create(nameInZip)
|
||||||
|
if err != nil {
|
||||||
|
_ = zw.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := entry.Write(data); err != nil {
|
||||||
|
_ = zw.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return zw.Close()
|
||||||
|
}
|
||||||
36
standalone/playworks_export_test.go
Normal file
36
standalone/playworks_export_test.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
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", "DogCat3_Full.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",
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := copyPlayworksUnityInput(data, opts); err != nil {
|
||||||
|
t.Fatalf("copy unity input: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, network := range []string{"al", "ap", "fb", "gg", "is", "mo", "mtg", "vu"} {
|
||||||
|
if _, err := convertPlayworksNetwork(string(data), opts, network); err != nil {
|
||||||
|
t.Fatalf("convert %s: %v", network, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
75
standalone/playworks_test.go
Normal file
75
standalone/playworks_test.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTransformPlayworksHTMLNetworkRequirements(t *testing.T) {
|
||||||
|
sourcePath := filepath.Join("..", "aiAssets", "DogCat3_Full.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: "gg", wantExitapi: 1},
|
||||||
|
{network: "ap", 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
494
standalone/plec.go
Normal file
494
standalone/plec.go
Normal file
@@ -0,0 +1,494 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
urlpkg "net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func PlecPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body := `
|
||||||
|
<header class="tool-header">
|
||||||
|
<h2 class="tool-title">PLEC Upload</h2>
|
||||||
|
<p class="tool-description">Pick HTML files, give each an iteration name, then upload them to PLEC.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="tool-panel">
|
||||||
|
<div class="panel-header"><h3 class="panel-title">Inputs</h3></div>
|
||||||
|
<div class="panel-body">
|
||||||
|
<div class="control-group">
|
||||||
|
<div id="dropZone" class="drop-zone">
|
||||||
|
<div class="file-row">
|
||||||
|
<button id="pickFolder" class="secondary">Select Folder</button>
|
||||||
|
<button id="pickFiles" class="secondary">Select File(s)</button>
|
||||||
|
<button id="clear" class="secondary">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div class="drop-zone-text">or drop HTML files or folders here</div>
|
||||||
|
</div>
|
||||||
|
<div id="emptySelection" class="file-name" style="margin-top:8px;">(no files selected)</div>
|
||||||
|
<div id="rowsPanel" class="results-panel is-hidden" style="margin-top:8px;">
|
||||||
|
<table id="rows" class="data-table">
|
||||||
|
<thead><tr><th>Filename</th><th style="width:240px;">Iteration Name</th><th style="width:44px;"></th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="action-row">
|
||||||
|
<button id="upload">Upload</button>
|
||||||
|
<button id="openResult" class="secondary" disabled>Open</button>
|
||||||
|
<button id="copyResult" class="secondary" disabled>Copy Link</button>
|
||||||
|
</div>
|
||||||
|
<div id="status" class="status-panel"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.row-error { color:#f48771; font-size:12px; margin-top:4px; }
|
||||||
|
#rows input[type=text] { width: 100%; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const PAGE_SIZE = 5;
|
||||||
|
let nextId = 1;
|
||||||
|
let rows = [];
|
||||||
|
let page = 0;
|
||||||
|
let previewUrl = '';
|
||||||
|
const tbody = document.querySelector('#rows tbody');
|
||||||
|
const statusEl = document.getElementById('status');
|
||||||
|
const rowsPanel = document.getElementById('rowsPanel');
|
||||||
|
const emptySelection = document.getElementById('emptySelection');
|
||||||
|
const openResultBtn = document.getElementById('openResult');
|
||||||
|
const copyResultBtn = document.getElementById('copyResult');
|
||||||
|
|
||||||
|
function parseIterationName(filename) {
|
||||||
|
const base = filename.replace(/\.html?$/i, '');
|
||||||
|
const tokens = base.split('_');
|
||||||
|
for (const t of tokens) {
|
||||||
|
if (/^(full|\d+clk|\d+s(?:ec)?)$/i.test(t)) return t.toLowerCase();
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s){
|
||||||
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
|
}
|
||||||
|
function addFiles(files) {
|
||||||
|
const existing = new Set(rows.map(r => r.path));
|
||||||
|
const before = rows.length;
|
||||||
|
(files || []).forEach(f => {
|
||||||
|
if (existing.has(f.path)) return;
|
||||||
|
rows.push({ id:'r' + (nextId++), path:f.path, name:f.name, iteration:parseIterationName(f.name), error:'' });
|
||||||
|
existing.add(f.path);
|
||||||
|
});
|
||||||
|
const added = rows.length - before;
|
||||||
|
if (added > 1) {
|
||||||
|
const batch = rows.slice(rows.length - added);
|
||||||
|
const first = batch[0].iteration;
|
||||||
|
if (first && batch.every(r => r.iteration === first)) {
|
||||||
|
batch.forEach((r, i) => r.iteration = String(i + 1).padStart(2, '0') + '_' + first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
page = Math.max(0, Math.ceil(rows.length / PAGE_SIZE) - 1);
|
||||||
|
renderRows();
|
||||||
|
}
|
||||||
|
async function readJSONStream(response, handle) {
|
||||||
|
if (!response.ok || !response.body) throw new Error('Request failed.');
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
let newline;
|
||||||
|
while ((newline = buffer.indexOf('\n')) >= 0) {
|
||||||
|
const line = buffer.slice(0, newline);
|
||||||
|
buffer = buffer.slice(newline + 1);
|
||||||
|
if (line.trim()) handle(JSON.parse(line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffer.trim()) handle(JSON.parse(buffer));
|
||||||
|
}
|
||||||
|
function renderRows() {
|
||||||
|
const oldPager = document.getElementById('selectedPager');
|
||||||
|
if (oldPager) oldPager.remove();
|
||||||
|
rowsPanel.classList.toggle('is-hidden', rows.length === 0);
|
||||||
|
emptySelection.classList.toggle('is-hidden', rows.length !== 0);
|
||||||
|
if (!rows.length) { tbody.innerHTML = ''; return; }
|
||||||
|
const maxPage = Math.max(0, Math.ceil(rows.length / PAGE_SIZE) - 1);
|
||||||
|
page = Math.min(page, maxPage);
|
||||||
|
const start = page * PAGE_SIZE;
|
||||||
|
const pageRows = rows.slice(start, start + PAGE_SIZE);
|
||||||
|
tbody.innerHTML = pageRows.map((row, offset) => {
|
||||||
|
const i = start + offset;
|
||||||
|
return '<tr data-id="' + row.id + '">' +
|
||||||
|
'<td><span class="mono wrap">' + escapeHtml(row.name) + '</span><div class="row-error">' + escapeHtml(row.error || '') + '</div></td>' +
|
||||||
|
'<td><input type="text" data-iter data-index="' + i + '" value="' + escapeHtml(row.iteration) + '" /></td>' +
|
||||||
|
'<td><button class="remove-btn danger" data-remove="' + i + '" title="Remove">×</button></td>' +
|
||||||
|
'</tr>';
|
||||||
|
}).join('');
|
||||||
|
tbody.querySelectorAll('[data-iter]').forEach(input => {
|
||||||
|
input.addEventListener('input', () => rows[Number(input.dataset.index)].iteration = input.value);
|
||||||
|
});
|
||||||
|
tbody.querySelectorAll('[data-remove]').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => { rows.splice(Number(btn.dataset.remove), 1); renderRows(); });
|
||||||
|
});
|
||||||
|
if (rows.length > PAGE_SIZE) {
|
||||||
|
const pager = document.createElement('div');
|
||||||
|
pager.id = 'selectedPager';
|
||||||
|
pager.className = 'pager';
|
||||||
|
pager.innerHTML = '<button class="secondary" id="prevPage"' + (page === 0 ? ' disabled' : '') + '>Previous</button>' +
|
||||||
|
'<span class="file-name">Page ' + (page + 1) + ' of ' + (maxPage + 1) + '</span>' +
|
||||||
|
'<button class="secondary" id="nextPage"' + (page === maxPage ? ' disabled' : '') + '>Next</button>';
|
||||||
|
rowsPanel.after(pager);
|
||||||
|
pager.querySelector('#prevPage').addEventListener('click', () => { page--; renderRows(); });
|
||||||
|
pager.querySelector('#nextPage').addEventListener('click', () => { page++; renderRows(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function setPreview(url) {
|
||||||
|
previewUrl = url || '';
|
||||||
|
openResultBtn.disabled = !previewUrl;
|
||||||
|
copyResultBtn.disabled = !previewUrl;
|
||||||
|
}
|
||||||
|
setupDropZone('dropZone', statusEl, (j) => {
|
||||||
|
addFiles(j.files || []);
|
||||||
|
if (j.skipped) statusEl.textContent = 'Skipped ' + j.skipped + ' non-HTML or unavailable item(s).';
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('pickFolder').addEventListener('click', async () => {
|
||||||
|
const res = await fetch('/api/plec/pickFolder', { method: 'POST' });
|
||||||
|
const j = await res.json();
|
||||||
|
addFiles(j.files || []);
|
||||||
|
});
|
||||||
|
document.getElementById('pickFiles').addEventListener('click', async () => {
|
||||||
|
const res = await fetch('/api/plec/pick', { method: 'POST' });
|
||||||
|
const j = await res.json();
|
||||||
|
addFiles(j.files || []);
|
||||||
|
});
|
||||||
|
document.getElementById('clear').addEventListener('click', () => {
|
||||||
|
rows = [];
|
||||||
|
page = 0;
|
||||||
|
setPreview('');
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
renderRows();
|
||||||
|
});
|
||||||
|
openResultBtn.addEventListener('click', () => {
|
||||||
|
if (previewUrl) fetch('/api/open', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ url: previewUrl }) });
|
||||||
|
});
|
||||||
|
copyResultBtn.addEventListener('click', () => {
|
||||||
|
if (previewUrl) fetch('/api/clipboard', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ text: previewUrl }) });
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('upload').addEventListener('click', async () => {
|
||||||
|
rows.forEach(row => row.error = '');
|
||||||
|
renderRows();
|
||||||
|
statusEl.textContent = '';
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
setPreview('');
|
||||||
|
if (rows.length === 0) {
|
||||||
|
statusEl.innerHTML = '<span class="err">Select at least one file.</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
statusEl.textContent = 'Uploading...';
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
let j = null;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/plec/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ rows }),
|
||||||
|
});
|
||||||
|
await readJSONStream(res, (msg) => {
|
||||||
|
if (msg.type === 'status') {
|
||||||
|
statusEl.textContent = msg.message;
|
||||||
|
statusEl.classList.add('is-busy');
|
||||||
|
} else if (msg.type === 'done') {
|
||||||
|
j = msg;
|
||||||
|
} else if (msg.type === 'error') {
|
||||||
|
j = { error: msg.message };
|
||||||
|
} else if (msg.type === 'rowErrors') {
|
||||||
|
j = { rowErrors: msg.rowErrors };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="err">' + (e.message || e) + '</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!j) { statusEl.classList.remove('is-busy'); statusEl.innerHTML = '<span class="err">No response.</span>'; return; }
|
||||||
|
if (j.rowErrors) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
for (const re of j.rowErrors) {
|
||||||
|
const row = rows.find(r => r.id === re.id);
|
||||||
|
if (row) row.error = re.message;
|
||||||
|
}
|
||||||
|
renderRows();
|
||||||
|
statusEl.innerHTML = '<span class="err">Fix row errors and retry.</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (j.error) {
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="err">' + j.error + '</span>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
statusEl.classList.remove('is-busy');
|
||||||
|
statusEl.innerHTML = '<span class="ok">Upload complete.</span>';
|
||||||
|
setPreview(j.preview);
|
||||||
|
});
|
||||||
|
|
||||||
|
renderRows();
|
||||||
|
</script>
|
||||||
|
`
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write([]byte(Page("/plec", "PLEC Upload", body)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlecPick(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cfg := LoadConfig()
|
||||||
|
picked := PickFiles(
|
||||||
|
"Select HTML",
|
||||||
|
[]FileFilter{{Name: "HTML", Extensions: []string{"html", "htm"}}},
|
||||||
|
true, cfg.LastPickDir,
|
||||||
|
)
|
||||||
|
if len(picked) == 0 {
|
||||||
|
writeJSON(w, map[string]any{"files": []any{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg.LastPickDir = filepath.Dir(picked[0])
|
||||||
|
_ = SaveConfig(cfg)
|
||||||
|
files := make([]map[string]string, 0, len(picked))
|
||||||
|
for _, p := range picked {
|
||||||
|
files = append(files, map[string]string{"path": p, "name": filepath.Base(p)})
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"files": files})
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlecPickFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cfg := LoadConfig()
|
||||||
|
dir := PickFolder("Select folder", cfg.LastPickDir)
|
||||||
|
if dir == "" {
|
||||||
|
writeJSON(w, map[string]any{"files": []any{}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg.LastPickDir = dir
|
||||||
|
_ = SaveConfig(cfg)
|
||||||
|
paths := collectHTMLFiles(dir)
|
||||||
|
files := make([]map[string]string, 0, len(paths))
|
||||||
|
for _, p := range paths {
|
||||||
|
files = append(files, map[string]string{"path": p, "name": filepath.Base(p)})
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"files": files})
|
||||||
|
}
|
||||||
|
|
||||||
|
type plecRow struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Iteration string `json:"iteration"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlecUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
send := newJSONStream(w)
|
||||||
|
var req struct {
|
||||||
|
Rows []plecRow `json:"rows"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg := LoadConfig().Plec
|
||||||
|
|
||||||
|
type rowErr struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
var rowErrors []rowErr
|
||||||
|
var valid []plecRow
|
||||||
|
htmlRx := regexp.MustCompile(`(?i)\.html?$`)
|
||||||
|
|
||||||
|
for _, row := range req.Rows {
|
||||||
|
if row.Path == "" || !fileExists(row.Path) {
|
||||||
|
rowErrors = append(rowErrors, rowErr{row.ID, "File missing"})
|
||||||
|
} else if strings.TrimSpace(row.Iteration) == "" {
|
||||||
|
rowErrors = append(rowErrors, rowErr{row.ID, "Iteration name required"})
|
||||||
|
} else if !htmlRx.MatchString(row.Path) {
|
||||||
|
rowErrors = append(rowErrors, rowErr{row.ID, "Must be .html"})
|
||||||
|
} else {
|
||||||
|
valid = append(valid, row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(rowErrors) > 0 {
|
||||||
|
send(map[string]any{"type": "rowErrors", "rowErrors": rowErrors})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(valid) == 0 {
|
||||||
|
send(map[string]any{"type": "error", "message": "Nothing to upload."})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
stamp := time.Now().Format("20060102150405")
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
mw := multipart.NewWriter(&buf)
|
||||||
|
for i, row := range valid {
|
||||||
|
idx := i + 1
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Preparing %d/%d %s", idx, len(valid), filepath.Base(row.Path))})
|
||||||
|
data, err := os.ReadFile(row.Path)
|
||||||
|
if err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Read failed: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stampedName := appendTimestamp(filepath.Base(row.Path), stamp)
|
||||||
|
fw, err := createFormFileWithType(mw, fmt.Sprintf("fileUpload_%d", idx), stampedName, "text/html")
|
||||||
|
if err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := fw.Write(data); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
iter := urlpkg.QueryEscape(strings.ReplaceAll(row.Iteration, " ", ""))
|
||||||
|
// Original uses encodeURI which keeps more chars than QueryEscape; emulate by un-escaping safe chars.
|
||||||
|
iter = encodeURICompatible(strings.ReplaceAll(row.Iteration, " ", ""))
|
||||||
|
if err := mw.WriteField(fmt.Sprintf("iterationNameUpload_%d", idx), iter); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := mw.Close(); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
send(map[string]any{"type": "status", "message": fmt.Sprintf("Uploading %d file%s...", len(valid), pluralS(len(valid)))})
|
||||||
|
httpReq, err := http.NewRequest("POST", cfg.UploadUrl, &buf)
|
||||||
|
if err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httpReq.Header.Set("Content-Type", mw.FormDataContentType())
|
||||||
|
httpReq.Header.Set("Origin", cfg.OriginUrl)
|
||||||
|
httpReq.Header.Set("Referer", cfg.OriginUrl+"/")
|
||||||
|
httpReq.Header.Set("User-Agent", "Mozilla/5.0 (HPL-Toolbox-Standalone)")
|
||||||
|
httpReq.Header.Set("X-Requested-With", "XMLHttpRequest")
|
||||||
|
httpReq.Header.Set("Accept", "*/*")
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Network error: " + err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
send(map[string]any{"type": "error", "message": fmt.Sprintf("HTTP %d\n%s", resp.StatusCode, truncate(string(respBody), 800))})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var parsed map[string]any
|
||||||
|
if err := json.Unmarshal(respBody, &parsed); err != nil {
|
||||||
|
send(map[string]any{"type": "error", "message": "Server returned non-JSON:\n" + truncate(string(respBody), 800)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var preview any
|
||||||
|
if v, ok := parsed["preview"]; ok && v != nil {
|
||||||
|
preview = v
|
||||||
|
} else if v, ok := parsed["previewURL"]; ok {
|
||||||
|
preview = v
|
||||||
|
}
|
||||||
|
send(map[string]any{"type": "done", "preview": preview, "raw": parsed, "rawText": string(respBody)})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ClipboardEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := CopyToClipboard(req.Text); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func OpenEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeJSON(w, map[string]any{"ok": false, "error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
OpenInBrowser(req.URL)
|
||||||
|
writeJSON(w, map[string]any{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileExists(p string) bool {
|
||||||
|
_, err := os.Stat(p)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendTimestamp(filename, stamp string) string {
|
||||||
|
ext := filepath.Ext(filename)
|
||||||
|
base := filename
|
||||||
|
if ext != "" {
|
||||||
|
base = filename[:len(filename)-len(ext)]
|
||||||
|
}
|
||||||
|
return base + "_" + stamp + ext
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncate(s string, n int) string {
|
||||||
|
if len(s) <= n {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return s[:n]
|
||||||
|
}
|
||||||
|
|
||||||
|
// createFormFileWithType is like multipart.Writer.CreateFormFile but lets us
|
||||||
|
// override the Content-Type (CreateFormFile hardcodes "application/octet-stream").
|
||||||
|
func createFormFileWithType(mw *multipart.Writer, field, filename, contentType string) (io.Writer, error) {
|
||||||
|
h := make(map[string][]string)
|
||||||
|
h["Content-Disposition"] = []string{
|
||||||
|
fmt.Sprintf(`form-data; name=%q; filename=%q`, field, filename),
|
||||||
|
}
|
||||||
|
h["Content-Type"] = []string{contentType}
|
||||||
|
return mw.CreatePart(h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// encodeURICompatible mimics JS encodeURI() — keeps A-Za-z0-9 and these
|
||||||
|
// reserved/mark chars: ;,/?:@&=+$-_.!~*'()#
|
||||||
|
func encodeURICompatible(s string) string {
|
||||||
|
keep := func(c byte) bool {
|
||||||
|
if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch c {
|
||||||
|
case ';', ',', '/', '?', ':', '@', '&', '=', '+', '$',
|
||||||
|
'-', '_', '.', '!', '~', '*', '\'', '(', ')', '#':
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
c := s[i]
|
||||||
|
if keep(c) {
|
||||||
|
b.WriteByte(c)
|
||||||
|
} else {
|
||||||
|
b.WriteString(fmt.Sprintf("%%%02X", c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
5
standalone/readme_embed_dev.go
Normal file
5
standalone/readme_embed_dev.go
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build !release
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
const embeddedReadme = ""
|
||||||
8
standalone/readme_embed_release.go
Normal file
8
standalone/readme_embed_release.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
//go:build release
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import _ "embed"
|
||||||
|
|
||||||
|
//go:embed README.md
|
||||||
|
var embeddedReadme string
|
||||||
BIN
standalone/rsrc.syso
Normal file
BIN
standalone/rsrc.syso
Normal file
Binary file not shown.
68
standalone/single_instance.go
Normal file
68
standalone/single_instance.go
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func lockFilePath() string {
|
||||||
|
return filepath.Join(userDataDir(), ".hpltoolbox.lock")
|
||||||
|
}
|
||||||
|
|
||||||
|
// focusExistingInstance returns true if another instance was found and
|
||||||
|
// successfully asked to focus its window. In that case the caller should exit.
|
||||||
|
// Returns false if no live instance exists (and clears any stale lock).
|
||||||
|
func focusExistingInstance() bool {
|
||||||
|
data, err := os.ReadFile(lockFilePath())
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
parts := strings.Split(strings.TrimSpace(string(data)), "\n")
|
||||||
|
if len(parts) != 2 {
|
||||||
|
_ = os.Remove(lockFilePath())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
pid, errPid := strconv.Atoi(strings.TrimSpace(parts[0]))
|
||||||
|
port, errPort := strconv.Atoi(strings.TrimSpace(parts[1]))
|
||||||
|
if errPid != nil || errPort != nil {
|
||||||
|
_ = os.Remove(lockFilePath())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quick liveness check: PID must exist.
|
||||||
|
if proc, err := os.FindProcess(pid); err != nil || proc == nil {
|
||||||
|
_ = os.Remove(lockFilePath())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ask the running instance to focus its window.
|
||||||
|
client := &http.Client{Timeout: 1500 * time.Millisecond}
|
||||||
|
url := fmt.Sprintf("http://127.0.0.1:%d/api/focus", port)
|
||||||
|
resp, err := client.Post(url, "application/json", bytes.NewReader(nil))
|
||||||
|
if err != nil {
|
||||||
|
// Lock file is stale (process died but didn't clean up).
|
||||||
|
_ = os.Remove(lockFilePath())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
_ = os.Remove(lockFilePath())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLockFile(port int) error {
|
||||||
|
content := fmt.Sprintf("%d\n%d\n", os.Getpid(), port)
|
||||||
|
return os.WriteFile(lockFilePath(), []byte(content), 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeLockFile() {
|
||||||
|
_ = os.Remove(lockFilePath())
|
||||||
|
}
|
||||||
127
standalone/update_checker.go
Normal file
127
standalone/update_checker.go
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const remotePackageJSONURL = "https://gitea.hesukastro.com/hesukastro/vsix-hpl-toolbox/raw/branch/main/package.json"
|
||||||
|
const updateRepositoryURL = "https://gitea.hesukastro.com/hesukastro/vsix-hpl-toolbox"
|
||||||
|
|
||||||
|
type updateCheckResponse struct {
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CurrentVersion string `json:"currentVersion"`
|
||||||
|
RemoteVersion string `json:"remoteVersion,omitempty"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
RepositoryURL string `json:"repositoryUrl,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateCheckEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
remoteVersion, err := fetchRemoteVersion()
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, updateCheckResponse{
|
||||||
|
OK: false,
|
||||||
|
Status: "error",
|
||||||
|
CurrentVersion: AppVersion,
|
||||||
|
Message: "HPL Toolbox update check failed: " + err.Error(),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
comparison := compareVersions(remoteVersion, AppVersion)
|
||||||
|
if comparison > 0 {
|
||||||
|
writeJSON(w, updateCheckResponse{
|
||||||
|
OK: true,
|
||||||
|
Status: "update",
|
||||||
|
CurrentVersion: AppVersion,
|
||||||
|
RemoteVersion: remoteVersion,
|
||||||
|
Message: fmt.Sprintf("HPL Toolbox update available: %s (installed: %s).", remoteVersion, AppVersion),
|
||||||
|
RepositoryURL: updateRepositoryURL,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, updateCheckResponse{
|
||||||
|
OK: true,
|
||||||
|
Status: "current",
|
||||||
|
CurrentVersion: AppVersion,
|
||||||
|
RemoteVersion: remoteVersion,
|
||||||
|
Message: fmt.Sprintf("HPL Toolbox is up to date (%s).", AppVersion),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchRemoteVersion() (string, error) {
|
||||||
|
client := http.Client{Timeout: 10 * time.Second}
|
||||||
|
req, err := http.NewRequest(http.MethodGet, remotePackageJSONURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
return "", fmt.Errorf("remote package.json returned HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
var packageJSON struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&packageJSON); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(packageJSON.Version) == "" {
|
||||||
|
return "", fmt.Errorf("remote package.json is missing a version")
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.TrimSpace(packageJSON.Version), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareVersions(left, right string) int {
|
||||||
|
leftParts := parseVersionParts(left)
|
||||||
|
rightParts := parseVersionParts(right)
|
||||||
|
length := len(leftParts)
|
||||||
|
if len(rightParts) > length {
|
||||||
|
length = len(rightParts)
|
||||||
|
}
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
leftPart := 0
|
||||||
|
rightPart := 0
|
||||||
|
if i < len(leftParts) {
|
||||||
|
leftPart = leftParts[i]
|
||||||
|
}
|
||||||
|
if i < len(rightParts) {
|
||||||
|
rightPart = rightParts[i]
|
||||||
|
}
|
||||||
|
if leftPart > rightPart {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if leftPart < rightPart {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseVersionParts(version string) []int {
|
||||||
|
fields := strings.FieldsFunc(version, func(r rune) bool {
|
||||||
|
return r == '.' || r == '-'
|
||||||
|
})
|
||||||
|
parts := make([]int, 0, len(fields))
|
||||||
|
for _, field := range fields {
|
||||||
|
part, err := strconv.Atoi(field)
|
||||||
|
if err == nil {
|
||||||
|
parts = append(parts, part)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parts
|
||||||
|
}
|
||||||
66
tools.json
Normal file
66
tools.json
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"id": "plec",
|
||||||
|
"title": "PLEC Upload",
|
||||||
|
"description": "Upload HTML to internal PLEC server",
|
||||||
|
"command": "hplToolbox.openPlecUpload",
|
||||||
|
"path": "/plec",
|
||||||
|
"beta": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "applovin",
|
||||||
|
"title": "AppLovin Playable Preview",
|
||||||
|
"description": "Upload to p.applov.in (QR preview)",
|
||||||
|
"command": "hplToolbox.openApplovinUpload",
|
||||||
|
"path": "/applovin",
|
||||||
|
"beta": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "base64",
|
||||||
|
"title": "Base64 Scanner",
|
||||||
|
"description": "Find non-base64 assets in HTML",
|
||||||
|
"command": "hplToolbox.openBase64Scanner",
|
||||||
|
"path": "/base64",
|
||||||
|
"beta": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "mobile",
|
||||||
|
"title": "Send To Mobile",
|
||||||
|
"description": "Share HTML to a phone via LAN + QR",
|
||||||
|
"command": "hplToolbox.openSendToMobile",
|
||||||
|
"path": "/mobile",
|
||||||
|
"beta": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "mraid",
|
||||||
|
"title": "MRAID Checker",
|
||||||
|
"description": "Check MRAID requirements and best practices",
|
||||||
|
"command": "hplToolbox.openMraidChecker",
|
||||||
|
"path": "/mraid",
|
||||||
|
"beta": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "playworks",
|
||||||
|
"title": "Playworks Converter",
|
||||||
|
"description": "Convert Playworks HTML to per-network variants",
|
||||||
|
"command": "hplToolbox.openPlayworksConverter",
|
||||||
|
"path": "/playworks",
|
||||||
|
"beta": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "mintegral",
|
||||||
|
"title": "Mintegral Checker",
|
||||||
|
"description": "Validate a Mintegral playable ZIP against PlayTurbo requirements",
|
||||||
|
"command": "hplToolbox.openMintegralChecker",
|
||||||
|
"path": "/mintegral",
|
||||||
|
"beta": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "device-simulator",
|
||||||
|
"title": "Device Simulator",
|
||||||
|
"description": "Preview HTML playables inside accurate mobile device frames with notch and Dynamic Island overlays",
|
||||||
|
"command": "hplToolbox.openDeviceSimulator",
|
||||||
|
"path": "/device-simulator",
|
||||||
|
"beta": false
|
||||||
|
}
|
||||||
|
]
|
||||||
Reference in New Issue
Block a user