diff --git a/.gitignore b/.gitignore index 0373d8e..e830da5 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,6 @@ android/.idea/ *.iml .DS_Store + +# Example app keeps its Xcode project +!example-app/ios/App/App.xcodeproj/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b65f80..faadba9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,104 @@ # Changelog -## 0.1.0 (2026-10-09) +All notable changes to this project are documented in this file. +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). -- First release: Capacitor 8 plugin for Unity LevelPlay rewarded and interstitial ads (ad-unit API). +## [Unreleased] + +## [0.3.0] - 2026-10-10 + +Banners, native ads, impression-level revenue, segments, dynamic user id, placement capping and Capacitor 7 support. +Fully backwards compatible with 0.2.x. + +### Added (API) +- `docs/design-0.3.md`: banner, native ad, impression data, placement, segment and dynamic user id design with the + exact LevelPlay 9.6.1 Android / iOS mappings, overlay positioning, error codes, Capacitor 7 findings, test plan. +- TypeScript API (`@since 0.3.0`): `getCapabilities`, `setSegment`, `setDynamicUserId`, `isPlacementCapped`, + `getReward`, `createBanner` / `loadBanner` / `showBanner` / `hideBanner` / `setBannerLayout` / `destroyBanner`, + `loadNativeAd` / `showNativeAd` / `setNativeAdRect` / `hideNativeAd` / `destroyNativeAd`; events `adInfoChanged`, + `impressionData`, `banner*` and `nativeAd*`. +- `AdInfo` gains optional `ab`, `segmentName`, `encryptedCPM`, `creativeId`, `conversionValue` (iOS) and `adSize`. +- Web stubs for every new method. + +### Added (Android) +- Banners in a pass-through overlay above the WebView: presets, `ADAPTIVE` (width in dp = CSS px, recreated on + rotation), `CUSTOM` sizes, top / bottom / center with offsets, safe area from the WebView's on-screen rect and the + window insets, several banners by id, every `banner*` event. +- Native ads with the plugin's `small` and `medium` templates (colours, corner radius, fonts) and `nativeAd*` events. +- `impressionData` from per-ad listeners, queued (max 100) until the first JS listener; `adInfoChanged`; + `getCapabilities`, `setSegment`, `setDynamicUserId`, `isPlacementCapped`, `getReward`. +- `AdInfo` fields `ab`, `segmentName`, `encryptedCPM`, `creativeId`, `adSize` on Android. +- JVM unit tests for the overlay geometry and argument validation (`bun run verify:android`). +- `BannerSize` `CUSTOM` with `customSize`, `NativeAdTemplateStyle` fonts, banner ids in `LEVELPLAY_DEMO`. + +### Added (iOS) +- Banners in a pass-through overlay inside the WebView: presets, `ADAPTIVE` (width in pt = CSS px, recreated when the + safe-area width changes), `CUSTOM` sizes, top / bottom / center with offsets, safe area, several banners by id, every + `banner*` event. +- Native ads with the plugin's `small` and `medium` templates built in code (`ISNativeAdView` binding; colours, corner + radius, system or web-asset fonts) and `nativeAd*` events. +- `impressionData` from per-ad delegates (with `conversionValue`), queued (max 100) until the first JS listener; + native impressions synthesised; `adInfoChanged`; `getCapabilities`, `setSegment`, `setDynamicUserId`, + `isPlacementCapped`, `getReward`; cleanup of banners and native ads when the plugin is released. +- `AdInfo` fields `ab`, `segmentName`, `encryptedCPM`, `creativeId`, `conversionValue`, `adSize` on iOS. + +### Added (tooling and docs) +- `bun run test`: `bun test` for the web stub (unimplemented rejections vs no-ops), `LEVELPLAY_DEMO` and the exports, + plus a compile-only check of the public API (`tsc -p test`); `verify` runs it. +- `example-app/`: a minimal Capacitor 8 app (HTML + TypeScript, esbuild) with the demo ids and buttons for every + format, segments and an impression log; Android and iOS (SPM) platforms committed. Not part of the npm package. +- README: banners, native ads (style options), impression data, segments / user id / placements, error codes, + limitations, example app, Capacitor 7. + +### Changed +- Capacitor 7 support: `peerDependencies` `@capacitor/core >=7.0.0`; `Package.swift` depends on `capacitor-swift-pm` + `"7.0.0"..<"9.0.0"`; iOS deployment target 14.0 in `Package.swift` and the podspec (was 15.0); Android + `minSdkVersion` fallback 23 (was 24). Checked by building a Capacitor 7.6.9 app for Android and the iOS simulator. + +## [0.2.1] - 2026-10-10 + +### Changed +- Author and copyright: CRTkafa (LICENSE, `package.json`, README, podspec). +- `repository.url` is the plain repo address (npmjs.com shows it readable instead of `git+https://….git`). +- Android Java package and Gradle namespace renamed to `fyi.crt.capacitor.levelplay`. Run `npx cap sync` after + updating; no API or behaviour changes. + +## [0.2.0] - 2026-10-10 + +First public release on npm. No behaviour changes to the native bridges since 0.1.0. + +### Added +- Complete README: compatibility table, iOS (SPM and CocoaPods) and Android setup, usage guide, mediation adapters + (Gradle, Swift packages, local-package workaround for networks without an official Swift package), privacy and + ATT guide, troubleshooting, FAQ. +- API reference generated from the JSDoc in `src/definitions.ts` with `@capacitor/docgen` (`bun run docgen`, also + part of `bun run build`); `dist/docs.json` ships with the package. +- JSDoc with `@since` for every method, option, event and type. +- `verify:android` script and a standalone Gradle setup (`android/settings.gradle`, Gradle wrapper 8.14.3) that builds + the Android library against `@capacitor/android` (dev dependency). +- `CONTRIBUTING.md`. + +### Changed +- `package.json`: description, author, `homepage`, `bugs`, `repository`, keywords, + `engines` (Node 22+, as Capacitor 8), `files` (adds `CHANGELOG.md`). +- Podspec: homepage from `package.json`, source is `https://git.crt.fyi/CRT/capacitor-levelplay.git` at tag + `v`. +- `tsconfig.json`: no explicit `lib` (same defaults for `target: es2017`), so docgen resolves `Promise` types. + +## [0.1.0] - 2026-10-09 + +### Added +- Capacitor 8 plugin for Unity LevelPlay rewarded and interstitial ads (ad-unit API). - iOS: Swift Package Manager with the official LevelPlay-Swift-Package (SDK 9.6.1); podspec on `IronSourceSDK ~> 9.6.1`. - Android: `com.unity3d.ads-mediation:mediation-sdk:9.6.1` from Maven Central, Play services ids, consumer ProGuard rules. - API: `initialize`, `setConsent` (GDPR / CCPA / COPPA), `setMetaData`, iOS ATT, load / show / isReady per ad unit, `launchTestSuite`, `validateIntegration`, events `loaded` `loadFailed` `displayed` `displayFailed` `clicked` `closed` `rewarded`. Show calls resolve after close with `{ shown, rewarded, reward?, error? }`. - `LEVELPLAY_DEMO`: Unity's public demo app keys and ad unit ids. + +[Unreleased]: https://git.crt.fyi/CRT/capacitor-levelplay/compare/v0.3.0...main +[0.3.0]: https://git.crt.fyi/CRT/capacitor-levelplay/compare/v0.2.1...v0.3.0 +[0.2.1]: https://git.crt.fyi/CRT/capacitor-levelplay/compare/v0.2.0...v0.2.1 +[0.2.0]: https://git.crt.fyi/CRT/capacitor-levelplay/compare/v0.1.0...v0.2.0 +[0.1.0]: https://git.crt.fyi/CRT/capacitor-levelplay/releases/tag/v0.1.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c5835bc --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,30 @@ +# Contributing + +Thanks for helping. Bug reports, questions and feature requests go to the +[issue tracker](https://git.crt.fyi/CRT/capacitor-levelplay/issues). For a bug, include the plugin version, the +LevelPlay SDK and adapter versions, the platform and OS version, and the native log (Xcode console or +`adb logcat | grep -E "LevelPlay|IronSource|IntegrationHelper"`). + +## Development + +Requirements: [Bun](https://bun.sh), Xcode 26+ for iOS, JDK 21 and the Android SDK for Android. + +```sh +bun install +bun run build # docgen (README API section) + dist/ +bun run typecheck +bun run verify:ios # xcodebuild the Swift package (iOS simulator) +JAVA_HOME=$(/usr/libexec/java_home -v 21) bun run verify:android +``` + +- The public API lives in `src/definitions.ts`. Document every method, option and event with JSDoc (`@since`), then + run `bun run build` so the API section of `README.md` is regenerated. Do not edit between the `docgen` markers by hand. +- Keep the Android (`android/src/main/java/...`) and iOS (`ios/Sources/...`) bridges in step: same method names, same + result and event shapes. +- `dist/` is committed so the package can be installed from git; rebuild it in the same commit as source changes. +- Add an entry under `Unreleased` in `CHANGELOG.md`. + +## Pull requests + +Keep them focused, describe what changed and how you tested it (device or simulator, OS version, network). By +contributing you agree that your work is released under the [MIT License](LICENSE). diff --git a/CapacitorLevelplay.podspec b/CapacitorLevelplay.podspec index cad99e2..1f267c2 100644 --- a/CapacitorLevelplay.podspec +++ b/CapacitorLevelplay.podspec @@ -1,18 +1,21 @@ require 'json' package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) +repo = 'https://git.crt.fyi/CRT/capacitor-levelplay' Pod::Spec.new do |s| s.name = 'CapacitorLevelplay' s.version = package['version'] - s.summary = package['description'] + s.summary = 'Capacitor plugin for Unity LevelPlay rewarded and interstitial ads.' + s.description = package['description'] s.license = package['license'] - s.homepage = package['repository']['url'] + s.homepage = package['homepage'] s.author = package['author'] - s.source = { :git => package['repository']['url'], :tag => 'v' + package['version'] } + s.source = { :git => "#{repo}.git", :tag => "v#{s.version}" } s.source_files = 'ios/Sources/**/*.{swift,h,m}' - s.ios.deployment_target = '15.0' + s.ios.deployment_target = '14.0' s.dependency 'Capacitor' + # Unity LevelPlay SDK (ironSource), https://cocoapods.org/pods/IronSourceSDK s.dependency 'IronSourceSDK', '~> 9.6.1' s.frameworks = 'AppTrackingTransparency' s.swift_version = '5.9' diff --git a/LICENSE b/LICENSE index 02c6a85..2e4bee1 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 VOX Games +Copyright (c) 2026 CRTkafa Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Package.swift b/Package.swift index f529980..e47a5c6 100644 --- a/Package.swift +++ b/Package.swift @@ -3,14 +3,14 @@ import PackageDescription let package = Package( name: "CapacitorLevelplay", - platforms: [.iOS(.v15)], + platforms: [.iOS(.v14)], products: [ .library( name: "CapacitorLevelplay", targets: ["LevelPlayPlugin"]) ], dependencies: [ - .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0"), + .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", "7.0.0"..<"9.0.0"), // Official Unity LevelPlay SDK (binary xcframework + Ad Quality), https://github.com/ironsource-mobile/LevelPlay-Swift-Package .package(url: "https://github.com/ironsource-mobile/LevelPlay-Swift-Package.git", "9.6.1"..<"10.0.0") ], diff --git a/README.md b/README.md index c27e698..15ee513 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,143 @@ # capacitor-levelplay -Capacitor 8 plugin for [Unity LevelPlay](https://docs.unity.com/en-us/grow/levelplay) (formerly ironSource) mediation: -**rewarded** and **interstitial** ads on Android and iOS, using LevelPlay's current ad-unit API -(`LevelPlay.init`, `LevelPlayRewardedAd` / `LPMRewardedAd`, `LevelPlayInterstitialAd` / `LPMInterstitialAd`). -No banners, no native ads. +[![npm version](https://img.shields.io/npm/v/capacitor-levelplay.svg)](https://www.npmjs.com/package/capacitor-levelplay) +[![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) +[![Capacitor 7 | 8](https://img.shields.io/badge/Capacitor-7%20%7C%208-119eff.svg)](https://capacitorjs.com) +[![LevelPlay SDK 9.6.1](https://img.shields.io/badge/LevelPlay%20SDK-9.6.1-222.svg)](https://docs.unity.com/en-us/grow/levelplay) -| | | +Capacitor 7 and 8 plugin for [Unity LevelPlay](https://docs.unity.com/en-us/grow/levelplay) (formerly ironSource) +mediation: **rewarded**, **interstitial**, **banner** and **native** ads on Android and iOS, plus impression-level +revenue data, built on LevelPlay's current **ad-unit API** (`LevelPlay.init`, `LevelPlayRewardedAd` / `LPMRewardedAd`, +`LevelPlayInterstitialAd` / `LPMInterstitialAd`, `LevelPlayBannerAdView` / `LPMBannerAdView`, `LevelPlayNativeAd`). + +```ts +import { LevelPlay } from 'capacitor-levelplay'; + +await LevelPlay.initialize({ appKey: 'your-app-key' }); +await LevelPlay.loadRewarded({ adUnitId: 'your-rewarded-ad-unit' }); +// ... +const result = await LevelPlay.showRewarded({ adUnitId: 'your-rewarded-ad-unit' }); +if (result.rewarded) grantCoins(result.reward!.amount); +``` + +## Contents + +- [Features](#features) +- [Compatibility](#compatibility) +- [Install](#install) +- [iOS setup](#ios-setup) +- [Android setup](#android-setup) +- [Quick start](#quick-start) +- [Usage guide](#usage-guide) +- [Example app](#example-app) +- [Mediation adapters](#mediation-adapters) +- [Privacy and consent](#privacy-and-consent) +- [Limitations](#limitations) +- [Troubleshooting](#troubleshooting) +- [FAQ](#faq) +- [API reference](#api) +- [Contributing](#contributing) +- [License](#license) + +## Features + +- **Rewarded and interstitial ads** with LevelPlay's ad-unit API (SDK 9.x). One native ad object per ad unit id, so + several rewarded or interstitial ad units can be used side by side. +- **Promise-based show**: `showRewarded` / `showInterstitial` resolve after the ad closes with + `{ shown, rewarded, reward?, error?, adInfo? }`. They never reject because an ad was not ready, and the plugin handles + networks that deliver the reward after the close callback. +- **Swift Package Manager first on iOS**: the plugin's `Package.swift` depends on Unity's official + [LevelPlay-Swift-Package](https://github.com/ironsource-mobile/LevelPlay-Swift-Package), so `npx cap sync` on an SPM + project really pulls the SDK. A podspec (`IronSourceSDK`) is included for CocoaPods projects. +- **App Tracking Transparency** helper on iOS (`requestTrackingAuthorization`, `getTrackingAuthorizationStatus`). +- **GDPR, CCPA and COPPA** signals through LevelPlay's privacy settings API, settable before init. +- **Integration Test Suite** and **integration validation** (`launchTestSuite`, `validateIntegration`) for checking + adapters during development. +- **Typed events** (`loaded`, `loadFailed`, `displayed`, `displayFailed`, `clicked`, `closed`, `rewarded`) with ad + info including impression revenue. +- **Banners** (0.3.0): standard sizes, adaptive (follows the safe-area width and rotation), and custom sizes; placed at + the top, bottom or centre with offsets, inside the safe area, in a pass-through overlay above the WebView (touches + beside a banner reach the page). Several banners at once, addressed by `bannerId`. +- **Native ads** (0.3.0): the plugin's `small` and `medium` templates, styled from JS (colours, corner radius, fonts) + and placed over any rectangle of the page, typically a placeholder element's `getBoundingClientRect()`. +- **Impression-level revenue** (0.3.0): `impressionData` for rewarded, interstitial, banner and native ads, queued + (up to 100) until the first listener so early impressions are not lost; `adInfoChanged` for full-screen ads. +- **Segments, dynamic user id, placement capping and rewards** (0.3.0): `setSegment`, `setDynamicUserId`, + `isPlacementCapped`, `getReward`. +- **Capabilities** (0.3.0): `getCapabilities()` tells what the current platform supports. +- **Demo ids** (`LEVELPLAY_DEMO`) from Unity's public sample apps for test ads during development. +- Web stub: on the web nothing is ever ready and shows resolve `{ shown: false }`, so the same game code runs in a + browser. + +## Compatibility + +| | Version | |---|---| -| Capacitor | 8 | -| LevelPlay SDK | Android `com.unity3d.ads-mediation:mediation-sdk:9.6.1` (Maven Central) · iOS `9.6.1` via the official [LevelPlay-Swift-Package](https://github.com/ironsource-mobile/LevelPlay-Swift-Package) (`IronSourceSDK` pod for CocoaPods) | -| iOS | 15+, Swift Package Manager first (the plugin's `Package.swift` really pulls the SDK); a podspec is included for CocoaPods projects | -| Android | minSdk 24, Java 21 | +| Capacitor | 7 and 8 (`@capacitor/core` >= 7.0.0) | +| Unity LevelPlay SDK | 9.6.1 (Android `com.unity3d.ads-mediation:mediation-sdk:9.6.1`; iOS `LevelPlay-Swift-Package` 9.6.1 up to < 10, or the `IronSourceSDK ~> 9.6.1` pod) | +| iOS | 14.0+ deployment target (Capacitor 7 default; Capacitor 8 apps use 15.0) | +| Xcode | 16+ for Capacitor 7, 26+ for Capacitor 8; tested with Xcode 27 (which needs an app target of iOS 15.0+) | +| Android | minSdk 23+, compileSdk / targetSdk 35 (Capacitor 7) or 36 (Capacitor 8), taken from the app's `variables.gradle` | +| Java | JDK 21 for Gradle builds | +| Node.js | 20+ (Capacitor 7 CLI), 22+ (Capacitor 8 CLI) | -Why another LevelPlay plugin: the existing `capacitor-levelplay-ads` package targets CocoaPods first and its -`Package.swift` does not depend on the LevelPlay SDK; this one is SPM-first, pulls the SDK under SPM, and exposes only -the ad-unit API. +| Plugin | Capacitor | LevelPlay SDK | +|---|---|---| +| 0.3.x | 7, 8 | 9.6.1 | +| 0.2.x | 8 | 9.6.1 | +| 0.1.x | 8 | 9.6.1 | ## Install ```sh -npm install capacitor-levelplay # or: bun add capacitor-levelplay +npm install capacitor-levelplay npx cap sync ``` -### iOS setup +```sh +bun add capacitor-levelplay && bunx cap sync +yarn add capacitor-levelplay && yarn cap sync +pnpm add capacitor-levelplay && pnpm cap sync +``` -1. **`-ObjC` linker flag** (required by LevelPlay): App target > Build Settings > *Other Linker Flags* > add `-ObjC`. -2. **Info.plist**: +## iOS setup + +### Swift Package Manager (default) + +Capacitor 8 projects (and Capacitor 7 projects created with `--packagemanager SPM`) need nothing extra: `npx cap sync` adds the plugin to `CapApp-SPM/Package.swift` +and Xcode resolves the LevelPlay package (a binary xcframework, roughly 27 MB) on the next build. + +### CocoaPods (alternative) + +CocoaPods projects get the `CapacitorLevelplay` pod from `npx cap sync`; it depends on `Capacitor` and +`IronSourceSDK ~> 9.6.1`. Run `pod install` (or `npx cap sync ios`) as usual. Mediation adapters are then added as pods +(`IronSourceAdapter`) in the app's `Podfile`. + +### `-ObjC` linker flag + +LevelPlay requires it: App target > **Build Settings** > **Linking** > **Other Linker Flags** > add `-ObjC`. + +### Info.plist ```xml - + +NSUserTrackingUsageDescription +Your data will be used to deliver ads that are more relevant to you. + + SKAdNetworkItems SKAdNetworkIdentifier su67r6k2v3.skadnetwork + - -NSUserTrackingUsageDescription -Your data will be used to deliver ads that are more relevant to you. - + + NSAdvertisingAttributionReportEndpoint https://postbacks-is.com/ + NSAppTransportSecurity @@ -52,17 +146,32 @@ npx cap sync ``` -With SPM, `npx cap sync` adds the plugin to `CapApp-SPM/Package.swift`; Xcode resolves the LevelPlay package -(binary xcframework, about 27 MB download) on the next build. +**Generating `SKAdNetworkItems`.** `su67r6k2v3.skadnetwork` is LevelPlay's (ironSource Ads) id. Every mediated network +needs its own ids as well. Use Unity's [SKAdNetwork ID manager](https://docs.unity.com/en-us/grow/levelplay/sdk/ios/skadnetwork-id-manager) +to export the combined list for the networks you enable, or merge each network's official list yourself (for example +Unity Ads publishes `https://skan.mz.unity3d.com/v3/partner/skadnetworks.plist.json`). A small script that downloads +the lists, extracts every `xxxxxxxxxx.skadnetwork` id, de-duplicates them and rewrites the `SKAdNetworkItems` array keeps +this repeatable; re-run it whenever you add a network and before each release. Some lists also carry AdAttributionKit +ids (`.adattributionkit`), which go into the `AdNetworkIdentifiers` array. -### Android setup +Full checklist: Unity's [iOS SDK integration](https://docs.unity.com/en-us/grow/levelplay/sdk/ios/sdk-integration) guide. -Nothing beyond `npx cap sync`: the plugin module declares `mediation-sdk` (Maven Central) plus the Play services -`ads-identifier`, `appset` and `basement` artifacts, and the SDK's manifest brings its activities, providers and the -`INTERNET` / `ACCESS_NETWORK_STATE` permissions. The plugin adds `com.google.android.gms.permission.AD_ID` -(remove it with `tools:node="remove"` in a child-directed app). +## Android setup -Optional overrides in the app's `android/variables.gradle`: +Nothing beyond `npx cap sync` for most apps: + +- **Repositories**: the SDK and all LevelPlay adapters are on Maven Central. Capacitor's default + `android/build.gradle` already lists `google()` and `mavenCentral()`; keep both. +- **Permissions**: the plugin's manifest adds `com.google.android.gms.permission.AD_ID` (required for the advertising id + on Android 13+). The SDK's own manifest brings `INTERNET`, `ACCESS_NETWORK_STATE`, its activities and providers. A + child-directed app can strip `AD_ID` from its manifest with `tools:node="remove"`. +- **Dependencies**: the plugin module declares `mediation-sdk` plus the Play services `ads-identifier`, `appset` and + `basement` artifacts the LevelPlay guide asks for. +- **ProGuard / R8**: the core keep rules ship as consumer rules. If you minify, add the per-network rules from Unity's + [Android SDK integration](https://docs.unity.com/en-us/grow/levelplay/sdk/android/sdk-integration) guide for each + adapter you add. + +Optional: pin a different 9.x SDK from the app's `android/variables.gradle`: ```gradle ext { @@ -70,40 +179,285 @@ ext { } ``` -Mediation adapters (Unity Ads, AdMob, AppLovin, ...) go into the app module, e.g. -`implementation 'com.unity3d.ads-mediation:unityads-adapter:5.+'`; see Unity's -[mediation networks](https://docs.unity.com/en-us/grow/levelplay/sdk/android/mediation-networks) page. -If you minify, the core keep rules ship as consumer ProGuard rules; add the per-network rules yourself. +Gradle in Capacitor 7 and 8 projects needs **JDK 21** (see [Troubleshooting](#android-build-fails-with-unsupported-class-file-major-version)). -## Usage +## Quick start ```ts -import { LevelPlay, LEVELPLAY_DEMO } from 'capacitor-levelplay'; import { Capacitor } from '@capacitor/core'; +import { LevelPlay, LEVELPLAY_DEMO } from 'capacitor-levelplay'; +// Unity's public demo ids serve test ads. Replace them with your own before release. const ids = Capacitor.getPlatform() === 'ios' ? LEVELPLAY_DEMO.ios : LEVELPLAY_DEMO.android; -await LevelPlay.requestTrackingAuthorization(); // iOS ATT prompt; no-op elsewhere -await LevelPlay.setConsent({ gdprConsent: true, ccpaDoNotSell: false }); // from your CMP -await LevelPlay.initialize({ appKey: ids.appKey }); +export async function startAds(): Promise { + await LevelPlay.requestTrackingAuthorization(); // iOS ATT prompt; resolves 'unavailable' elsewhere + await LevelPlay.initialize({ + appKey: ids.appKey, + consent: { gdprConsent: false }, // until your CMP says otherwise, see "Privacy and consent" + }); + await LevelPlay.loadRewarded({ adUnitId: ids.rewarded }); + await LevelPlay.loadInterstitial({ adUnitId: ids.interstitial }); +} -await LevelPlay.addListener('loaded', (e) => console.log('loaded', e.format, e.adUnitId)); -await LevelPlay.loadRewarded({ adUnitId: ids.rewarded }); - -// later, when the user taps "watch video": -const { ready } = await LevelPlay.isReady({ format: 'rewarded', adUnitId: ids.rewarded }); -if (ready) { - const r = await LevelPlay.showRewarded({ adUnitId: ids.rewarded }); - if (r.rewarded) grantReward(r.reward); - await LevelPlay.loadRewarded({ adUnitId: ids.rewarded }); // preload the next one +export async function watchVideoForCoins(): Promise { + const result = await LevelPlay.showRewarded({ adUnitId: ids.rewarded }); + void LevelPlay.loadRewarded({ adUnitId: ids.rewarded }); // preload the next one + return result.rewarded ? (result.reward?.amount ?? 0) : 0; } ``` -`showRewarded` / `showInterstitial` resolve **after the ad closes** (or failed to display) with -`{ shown, rewarded, reward?, error?, adInfo? }`. They never reject because an ad is not ready; they resolve -`{ shown: false, error: { code: -1, message: 'Ad not ready' } }`. Reward and close callbacks can arrive in either order -on some networks; the plugin waits up to 1 s after the close for a late reward before resolving. Grant rewards only -when `rewarded` is `true` (or on the `rewarded` event). +## Usage guide + +### Initialise with consent + +Initialise once, as early as is sensible, after consent is known (and on iOS after the ATT prompt). Ads can only be +loaded after `initialize` resolves. + +```ts +const { status } = await LevelPlay.requestTrackingAuthorization(); // iOS only, see Privacy and consent + +const { sdkVersion } = await LevelPlay.initialize({ + appKey: ids.appKey, + userId: playerId, // optional: needed for server-to-server reward callbacks + consent: { + gdprConsent: cmpSaysYes, // EEA / UK / CH users: false until a CMP collected consent + ccpaDoNotSell: false, // true if a US user opted out of sale / sharing + coppa: false, // true for child-directed treatment + }, +}); +``` + +`initialize` rejects with the SDK's init error (`code`, `message`); you can call it again later. Calling it after a +successful init resolves immediately, and concurrent calls share one init. + +### Rewarded ads + +```ts +const REWARDED = ids.rewarded; + +await LevelPlay.loadRewarded({ adUnitId: REWARDED }); + +// When the player taps "Watch a video": +const { ready } = await LevelPlay.isReady({ format: 'rewarded', adUnitId: REWARDED }); +if (!ready) { + showToast('No video available right now'); +} else { + const result = await LevelPlay.showRewarded({ adUnitId: REWARDED, placementName: 'DoubleCoins' }); + if (result.rewarded && result.reward) { + grant(result.reward.name, result.reward.amount); + } else if (result.error) { + console.warn('rewarded not shown', result.error.code, result.error.message); + } + await LevelPlay.loadRewarded({ adUnitId: REWARDED }); // always load the next one +} +``` + +- The show promise resolves **after the ad closes** (or failed to display). +- Grant the reward only when `rewarded` is `true`. The reward and close callbacks can arrive in either order on some + networks; the plugin waits up to 1 second after the close for a late reward before resolving. +- When the ad is not ready, the promise resolves `{ shown: false, rewarded: false, error: { code: -1, message: 'Ad not ready' } }`. +- `placementName` is optional and refers to a placement configured in the LevelPlay dashboard (capping, pacing, reward). +- For server-side rewards, pass `userId` to `initialize` and configure server-to-server callbacks in the dashboard. + +### Interstitial ads + +```ts +await LevelPlay.loadInterstitial({ adUnitId: ids.interstitial }); + +// At a natural break, for example between levels: +const result = await LevelPlay.showInterstitial({ adUnitId: ids.interstitial }); +// result.shown tells you whether it was displayed; game flow continues after the close. +void LevelPlay.loadInterstitial({ adUnitId: ids.interstitial }); +``` + +### Listening to events + +Load results arrive only as events, so listen for `loaded` / `loadFailed` if you want to drive UI or retry logic. + +```ts +import type { PluginListenerHandle } from '@capacitor/core'; + +const handles: PluginListenerHandle[] = [ + await LevelPlay.addListener('loaded', (e) => console.log('loaded', e.format, e.adUnitId, e.adInfo?.adNetwork)), + await LevelPlay.addListener('loadFailed', (e) => { + console.warn('load failed', e.format, e.error.code, e.error.message); + setTimeout(() => { + void (e.format === 'rewarded' + ? LevelPlay.loadRewarded({ adUnitId: e.adUnitId }) + : LevelPlay.loadInterstitial({ adUnitId: e.adUnitId })); + }, 30_000); // retry later; use an increasing backoff in production + }), + await LevelPlay.addListener('displayed', (e) => trackImpression(e.adInfo?.revenue, e.adInfo?.adNetwork)), + await LevelPlay.addListener('rewarded', (e) => console.log('reward', e.reward.name, e.reward.amount)), + await LevelPlay.addListener('closed', (e) => resumeAudio()), +]; + +// later +await Promise.all(handles.map((h) => h.remove())); +// or: await LevelPlay.removeAllListeners(); +``` + +Every event carries `{ format: 'rewarded' | 'interstitial', adUnitId, adInfo? }`, plus `error` on `loadFailed` / +`displayFailed` and `reward` on `rewarded`. + +### Checking readiness + +`isReady({ format, adUnitId })` returns the native `isAdReady()` for that ad unit. It is `false` for an ad unit that was +never loaded. Use it to enable or disable a "watch video" button. + +### Banners + +A banner is created hidden, then loaded and shown. `createBanner` resolves the banner's size and on-screen frame (CSS +px, relative to the WebView viewport), so the page can leave room for it. + +```ts +const banner = await LevelPlay.createBanner({ + adUnitId: ids.banner, + bannerId: 'main', // optional; defaults to adUnitId + size: 'ADAPTIVE', // BANNER 320x50, LARGE 320x90, MEDIUM_RECTANGLE 300x250, LEADERBOARD 728x90, ADAPTIVE, CUSTOM + position: 'bottom', // 'top' | 'bottom' | 'center' + offsetY: 0, // CSS px, away from the edge + respectSafeArea: true, // default: stays clear of notches, status bar, navigation bar and home indicator +}); +document.body.style.paddingBottom = `${banner.frame.height}px`; + +await LevelPlay.addListener('bannerLoaded', (e) => console.log('banner', e.bannerId, e.frame)); +await LevelPlay.addListener('bannerLoadFailed', (e) => console.warn('banner failed', e.error.code)); +await LevelPlay.loadBanner({ bannerId: 'main' }); // once per banner object; the SDK refreshes and retries by itself +await LevelPlay.showBanner({ bannerId: 'main' }); + +await LevelPlay.setBannerLayout({ bannerId: 'main', position: 'top' }); // move it +await LevelPlay.hideBanner({ bannerId: 'main' }); // hidden banners pause auto refresh +await LevelPlay.destroyBanner({ bannerId: 'main' }); +``` + +- `ADAPTIVE` uses the safe-area width (or `adaptiveWidth` in CSS px) and is recreated and reloaded automatically when + that width changes, for example on rotation, keeping its id, position and visibility. +- `CUSTOM` takes `customSize: { width, height }` in CSS px. +- Banner events: `bannerLoaded`, `bannerLoadFailed`, `bannerDisplayed`, `bannerDisplayFailed`, `bannerClicked`, + `bannerExpanded`, `bannerCollapsed`, `bannerLeftApplication`, all with `{ bannerId, adUnitId, adInfo?, frame? }`. + +| Top and bottom (Android) | Rotated, adaptive (Android) | +|---|---| +| ![Adaptive banners at the top and bottom](docs/images/android/banners-top-bottom.png) | ![Adaptive banner recreated after rotation](docs/images/android/banners-landscape-rotated.png) | + +### Native ads + +Native ads are drawn by the plugin's templates (`small`: a row at least 90 px tall, no media; `medium`: with a media +view, about 300 x 350) and placed over a +rectangle of the page, usually a placeholder element. Check `getCapabilities()` first. + +```ts +const caps = await LevelPlay.getCapabilities(); +if (caps.nativeAd && caps.nativeAdTemplates.includes('small')) { + const slot = document.getElementById('native-slot')!; // e.g. a 90 px tall div + + await LevelPlay.addListener('nativeAdLoaded', async (e) => { + const r = slot.getBoundingClientRect(); + await LevelPlay.showNativeAd({ nativeAdId: e.nativeAdId, rect: { x: r.left, y: r.top, width: r.width, height: r.height } }); + }); + await LevelPlay.addListener('nativeAdLoadFailed', (e) => console.warn('native failed', e.error.code)); + + await LevelPlay.loadNativeAd({ + nativeAdId: 'feed-1', + template: 'small', + placementName: 'Feed', // optional + style: { + backgroundColor: '#ffffff', + titleColor: '#111111', + bodyColor: '#555555', + callToActionBackgroundColor: '#2f6fed', + callToActionTextColor: '#ffffff', + cornerRadius: 8, + titleFont: { family: 'fonts/Inter-SemiBold.ttf', size: 15 }, // a web asset path or a system family + bodyFont: { size: 13 }, + callToActionFont: { family: 'Helvetica', size: 14 }, + }, + }); +} + +// keep it on the placeholder while the page scrolls or resizes +await LevelPlay.setNativeAdRect({ nativeAdId: 'feed-1', rect: { x: 16, y: 420, width: 343, height: 90 } }); +await LevelPlay.hideNativeAd({ nativeAdId: 'feed-1' }); +await LevelPlay.destroyNativeAd({ nativeAdId: 'feed-1' }); +``` + +Style options (`NativeAdTemplateStyle`): `backgroundColor`, `titleColor`, `bodyColor`, `callToActionBackgroundColor`, +`callToActionTextColor` (`#RRGGBB` or `#RRGGBBAA`), `cornerRadius` (CSS px), and `titleFont`, `bodyFont`, `callToActionFont` +(`{ family?, size? }`; a `.ttf` / `.otf` path is read from the app's web assets, anything else is a system font family; +a missing font falls back to the system font). The template texts "Ad" and "Open" can be localised with the app +resources `levelplay_native_ad_badge` and `levelplay_native_ad_cta_fallback` (Android `strings.xml`, iOS +`Localizable.strings`). + +Native events: `nativeAdLoaded`, `nativeAdLoadFailed`, `nativeAdImpression`, `nativeAdClicked`, all with +`{ nativeAdId, placementName?, adInfo? }`. + +### Impression-level revenue + +```ts +await LevelPlay.addListener('impressionData', (d) => { + // d.adFormat as the SDK reports it ('Rewarded Video', 'Interstitial', 'Banner', 'nativead' ...); d.revenue in USD + analytics.logAdImpression({ network: d.adNetwork, format: d.adFormat, revenue: d.revenue ?? 0, currency: 'USD' }); +}); +``` + +Impressions that happen before the first listener (for example a banner shown during app start) are queued, up to 100, +and delivered in order when the first `impressionData` listener is added. `d.allData` carries every raw field of the +SDK's impression object. `adInfoChanged` fires when the ad info of a loaded rewarded or interstitial ad changes. + +### Segments, user id, placements + +```ts +await LevelPlay.setSegment({ segmentName: 'whales', level: 12, isPaying: true, iapTotal: 49.99, customParameters: { cohort: 'b' } }); +await LevelPlay.setDynamicUserId({ userId: 'player-123' }); // { valid } ; used for server-to-server rewards + +const { capped } = await LevelPlay.isPlacementCapped({ format: 'rewarded', placementName: 'Shop' }); +const reward = await LevelPlay.getReward({ adUnitId: ids.rewarded, placementName: 'Shop' }); // { name, amount } +await LevelPlay.showRewarded({ adUnitId: ids.rewarded, placementName: 'Shop' }); +``` + +`setSegment` takes at most 5 custom parameters, keys and values 1-32 letters and digits (SDK limits); invalid input +rejects with `INVALID_ARGUMENT` instead of being dropped silently by the SDK. + +### Error codes + +Calls reject with a `code`: `INVALID_ARGUMENT`, `NOT_INITIALIZED` (banner / native before `initialize()`), +`ALREADY_EXISTS` (banner id in use), `NOT_FOUND` (unknown banner or native id), `NOT_LOADED` (`showNativeAd` before +`nativeAdLoaded`), `UNSUPPORTED`, `NO_ACTIVITY` (Android) / `NO_VIEW_CONTROLLER` (iOS), `UNIMPLEMENTED` (web). +`hideBanner` and the `destroy*` calls resolve for unknown ids. Ad load and show errors arrive in events as +`{ code, message }` with the SDK's code (509 is "no fill"). + +### Integration Test Suite + +The [Integration Test Suite](https://docs.unity.com/en-us/grow/levelplay/sdk/android/integration-test-suite) shows every +configured network, its adapter status and lets you request test ads per network. + +```ts +await LevelPlay.initialize({ appKey: ids.appKey, testSuite: true }); // sets is_test_suite=enable before init +await LevelPlay.launchTestSuite(); +``` + +Development builds only. Unity recommends not calling other LevelPlay APIs before launching the suite, and the suite +supports portrait orientation only. + +### Validate the integration + +```ts +await LevelPlay.validateIntegration(); +``` + +Writes LevelPlay's integration helper report to the native log: the Xcode console on iOS, logcat tag +`IntegrationHelper` on Android (`adb logcat | grep IntegrationHelper`). Each network is listed with its adapter and SDK +version and `VERIFIED` when everything is in place. Remove the call from release builds. + +### Meta data + +Network-specific and SDK flags go through `setMetaData` before init, for example: + +```ts +await LevelPlay.setMetaData({ key: 'is_deviceid_optout', value: 'true' }); +``` ### Demo ids @@ -111,60 +465,1828 @@ when `rewarded` is `true` (or on the `rewarded` event). ([Mediation-Demo-Apps](https://github.com/ironsource-mobile/Mediation-Demo-Apps)). They serve test ads; never ship them. -| platform | app key | rewarded | interstitial | -|---|---|---|---| -| Android | `25b63cf85` | `syz3d8ekts22q0or` | `h3xw38h9214adgxo` | -| iOS | `8545d445` | `qwouvdrkuwivay5q` | `wmgt0712uuux8ju4` | +| Platform | App key | Rewarded | Interstitial | Banner | +|---|---|---|---|---| +| Android | `25b63cf85` | `syz3d8ekts22q0or` | `h3xw38h9214adgxo` | `4fpetq4lhe5lsw3e` | +| iOS | `8545d445` | `qwouvdrkuwivay5q` | `wmgt0712uuux8ju4` | `iep3rxsyp9na3rw8` | -### Integration Test Suite +The sample apps have no native ad unit; native ads load with the app key's default placement. -```ts -await LevelPlay.initialize({ appKey, testSuite: true }); // sets is_test_suite=enable before init -await LevelPlay.launchTestSuite(); +### Web + +LevelPlay has no web SDK. On the web `initialize` and `launchTestSuite` reject as unimplemented, `isReady` is always +`false` and shows resolve `{ shown: false, rewarded: false, error: { code: -1, ... } }`. `getCapabilities()` reports +nothing supported; `createBanner`, `showBanner`, `setBannerLayout`, `loadNativeAd` and `showNativeAd` reject as +unimplemented; `setSegment`, `loadBanner`, hide and destroy calls are no-ops; `setDynamicUserId` resolves +`{ valid: false }`, `isPlacementCapped` `{ capped: false }` and `getReward` `{ name: '', amount: 0 }`. + +## Example app + +[`example-app/`](example-app/) is a minimal Capacitor 8 app (HTML + TypeScript) that uses the plugin from this +repository with the demo ids: initialize, rewarded, interstitial, banner top / bottom / hide / destroy, native small / +medium, segment and an impression log. See its [README](example-app/README.md) for the steps. + +## Mediation adapters + +The plugin brings the LevelPlay SDK (which includes ironSource Ads). Every other network is an adapter plus that +network's SDK, added **to your app**, not to the plugin. Pick versions from Unity's adapter tables +([Android](https://docs.unity.com/en-us/grow/levelplay/sdk/android/mediation-networks), +[iOS](https://docs.unity.com/en-us/grow/levelplay/sdk/ios/mediation-networks)) and take each adapter together with the +network SDK version it was built for (the adapter changelog says "Supporting SDK version ..."). Then enable the network +in the LevelPlay dashboard. + +### Android (Gradle) + +Adapters live on Maven Central under `com.unity3d.ads-mediation:-adapter:`. Add each adapter and the +network SDK to `android/app/build.gradle`: + +```gradle +dependencies { + // Unity Ads + implementation 'com.unity3d.ads-mediation:unityads-adapter:' + implementation 'com.unity3d.ads:unity-ads:' + // Liftoff Monetize (Vungle) + implementation 'com.unity3d.ads-mediation:vungle-adapter:' + implementation 'com.vungle:vungle-ads:' +} ``` -Development builds only. The suite is portrait only. +List the network SDK explicitly: the adapter artifacts do not pull it in. Some networks need more (Google AdMob, for +example, needs its `com.google.android.gms.ads.APPLICATION_ID` meta-data in `AndroidManifest.xml`, or the app crashes at +launch); check the network's page in Unity's docs. -### Privacy +### iOS (Swift Package Manager) -`setConsent({ gdprConsent?, ccpaDoNotSell?, coppa? })` maps to `LevelPlayPrivacySettings` (Android) / -`LPMPrivacySettings` (iOS): `setGDPRConsent`, `setCCPA`, `setCOPPA` (SDK 9.5+ APIs). Call it before `initialize` -(or pass `consent` to `initialize`). LevelPlay also reads a Google UMP / IAB TCF CMP's consent string by itself. -Raw meta data flags (for example `is_deviceid_optout`) go through `setMetaData({ key, value })`. +Unity publishes official adapter packages on GitHub as +`https://github.com/ironsource-mobile/LevelPlay--Adapter-Swift-Package` (for example +`LevelPlay-UnityAds-Adapter-Swift-Package`, `LevelPlay-Vungle-Adapter-Swift-Package`). In Xcode: **File > Add Package +Dependencies**, enter the URL, choose an exact version and add the product to the **App** target. Each package pulls +its network SDK and LevelPlay-Swift-Package 9.x, which resolves to the same copy the plugin uses. + +**Networks without an official Swift package.** Not every network has one (at the time of writing, InMobi does not). +Two options: + +1. Use CocoaPods for the project and add the `IronSourceAdapter` pod. +2. Keep SPM and wrap the adapter in a small **local Swift package** that mirrors the official packages: a + `binaryTarget` pointing at the adapter zip Unity publishes for CocoaPods (the URL is in the adapter's podspec, pin its + SHA-256 with `swift package compute-checksum`), a dependency on the network's own Swift package at the version the + adapter supports, a dependency on `LevelPlay-Swift-Package` 9.x, and an empty Swift source file for the wrapper + target. Add the local package to the App target via **Add Package Dependencies > Add Local...**. + + ```swift + // swift-tools-version: 5.9 + import PackageDescription + + let package = Package( + name: "LevelPlay-Example-Adapter", + platforms: [.iOS(.v13)], + products: [.library(name: "ExampleAdapter", targets: ["ExampleAdapter"])], + dependencies: [ + .package(url: "https://github.com//SDK-Swift-Package.git", exact: ""), + .package(url: "https://github.com/ironsource-mobile/LevelPlay-Swift-Package.git", "9.0.0"..<"10.0.0"), + ], + targets: [ + .target( + name: "ExampleAdapter", // Sources/ExampleAdapter/ExampleAdapter.swift can be empty + dependencies: [ + "ExampleAdapterBinary", + .product(name: "", package: "SDK-Swift-Package"), + .product(name: "UnityMediationSDK", package: "LevelPlay-Swift-Package"), + ]), + .binaryTarget( + name: "ExampleAdapterBinary", + url: "", + checksum: ""), + ] + ) + ``` + + Add any system libraries the network's manual-integration guide lists as `linkerSettings`. + +After adding networks: update `SKAdNetworkItems` ([iOS setup](#infoplist)), rebuild both platforms and run +`validateIntegration()`. + +## Privacy and consent + +LevelPlay recommends setting privacy signals **before** `initialize`. Pass them as `consent` to `initialize` or call +`setConsent` first; call `setConsent` again whenever the user changes their choice. They map to +`LevelPlayPrivacySettings` (Android) and `LPMPrivacySettings` (iOS): `setGDPRConsent`, `setCCPA`, `setCOPPA`. See +Unity's [regulation settings](https://docs.unity.com/en-us/grow/levelplay/sdk/ios/regulation-advanced-settings). + +- **GDPR (EEA, UK, Switzerland)**: pass `gdprConsent: false` until a consent management platform (CMP) collected + consent, then `true` or `false` according to the user's choice. If you use an IAB TCF v2 CMP (for example Google + UMP), LevelPlay and many networks also read the TCF consent string the CMP stores on the device. +- **CCPA and other US state laws**: `ccpaDoNotSell: true` when the user opted out of the sale or sharing of personal + data. +- **COPPA**: `coppa: true` for users who must get child-directed treatment. Child-directed apps should also strip the + `AD_ID` permission on Android and should not show the ATT prompt. + +### App Tracking Transparency (iOS) + +Without ATT authorization the IDFA is zeros and ads earn less, so ask before init: + +1. Add `NSUserTrackingUsageDescription` to `Info.plist`. +2. Call `requestTrackingAuthorization()` **when the app is active** (iOS ignores the request while the app is still + launching or in the background) and **before** `initialize`. Show your CMP first if you have one. +3. iOS shows the system prompt only once; later calls resolve the stored status. Use + `getTrackingAuthorizationStatus()` to read it without prompting. + +```ts +const { status } = await LevelPlay.getTrackingAuthorizationStatus(); +if (status === 'notDetermined') await LevelPlay.requestTrackingAuthorization(); +await LevelPlay.initialize({ appKey }); +``` + +## Limitations + +- **Native ads need per-network setup.** Only networks that serve native ads through LevelPlay fill them, and each + needs its adapter and a native ad configuration in the dashboard. The public demo app key has no native + configuration on Android (508 "No Native Ad configurations found"); on iOS it filled from ironSource Ads in testing. +- **Native ads use the plugin's templates.** Custom native layouts in HTML are not possible: the SDK requires its own + native views (and the network's privacy icon) to record impressions and clicks. +- **`loadBanner` is one-shot** per banner object (an SDK rule in 9.6.1): a second call is ignored and the SDK retries + on its refresh interval. To retry right away, `destroyBanner` + `createBanner` + `loadBanner`. +- **`-ObjC` is required on iOS**, also for the new APIs: without it `setSegment` crashes with an unrecognized selector. +- **No `adInfoChanged` for banners and native ads**: the SDK only reports it for rewarded and interstitial ads. +- **`lifetimeRevenue` is not typed** in `ImpressionData`; read it from `allData.lifetimeRevenue` when present. +- **Overlay ads**: banners and native ads are native views above the WebView, so CSS cannot clip, transform or + animate them; move them with `setBannerLayout` / `setNativeAdRect` and hide them under your own modals. + +## Troubleshooting + +### Loads fail with 509 "No fill" +Common and usually not a bug. An app that is not live in its store yet (or not approved in the LevelPlay dashboard) +gets little or no real demand. Use the demo ids (`LEVELPLAY_DEMO`) or the Integration Test Suite with test ads to +check your integration, and retry loads with a backoff in production. Unity's +[troubleshooting guide](https://docs.unity.com/en-us/grow/levelplay/sdk/ios/troubleshoot-no-ads-displaying) lists +more causes. + +### Unity Ads: "Invalid Game ID" +The Unity Ads adapter is started with the game id configured on the Unity Ads instance in LevelPlay. If Unity Ads +answers "Invalid Game ID: ..." (iOS: "Initialization failed: not found"), the Unity Ads project or game is not +active, or the instance uses a game id from another project. Check the game ids in the Unity dashboard and that they +belong to the project linked to your LevelPlay app. + +### Android build fails with "Unsupported class file major version" +Gradle for Capacitor 8 must run on **JDK 21**. Android Studio's bundled runtime can be newer than the Gradle version +supports (for example "Unsupported class file major version 69" with Java 25). Point Gradle at a JDK 21: + +```sh +export JAVA_HOME=$(/usr/libexec/java_home -v 21) # macOS +cd android && ./gradlew assembleDebug +``` + +In Android Studio: **Settings > Build, Execution, Deployment > Build Tools > Gradle > Gradle JDK**. + +### iOS: "No such module 'IronSource'" or the package does not update +- Run `npx cap sync ios` after every install or upgrade of the plugin; it rewrites `CapApp-SPM/Package.swift`. +- In Xcode: **File > Packages > Reset Package Caches**, then **Resolve Package Versions**. +- Still stuck: quit Xcode, delete `~/Library/Developer/Xcode/DerivedData/-*` and + `~/Library/Caches/org.swift.swiftpm`, then reopen. +- CocoaPods projects: `cd ios/App && pod install --repo-update`. + +### iOS: crash or missing symbols at launch +Check the `-ObjC` linker flag on the App target. + +### Nothing happens on `showRewarded` +`showRewarded` resolves `{ shown: false, error: { code: -1, message: 'Ad not ready' } }` when no ad is loaded for that ad +unit. Make sure you called `loadRewarded` with the same `adUnitId` after `initialize` resolved, and wait for the +`loaded` event (or `isReady`). + +## FAQ + +**Which LevelPlay API does it use?** +LevelPlay's ad-unit API, the current API in SDK 9.x: `LevelPlay.init` with an init request, +`LevelPlayRewardedAd` / `LevelPlayInterstitialAd` on Android and `LPMRewardedAd` / `LPMInterstitialAd` on iOS. The +legacy `IronSource.*` placement API is not used. + +**Can I use more than one ad unit per format?** +Yes. Every call takes an `adUnitId`, and the plugin keeps one native ad object per id. + +**Does it support banners or native ads?** +Yes, since 0.3.0: banners in every LevelPlay size (including adaptive and custom sizes) and native ads in two +templates. See [Banners](#banners) and [Native ads](#native-ads). + +**Does it work with Capacitor 7?** +Yes, since 0.3.0 (`@capacitor/core` >= 7.0.0). Android and iOS (Swift Package Manager) builds were checked with a +Capacitor 7.6.9 app. + +**How is this different from `capacitor-levelplay-ads`?** +Both are Capacitor plugins for LevelPlay and both use the ad-unit API. The differences, as of `capacitor-levelplay-ads` +0.1.42: + +| | `capacitor-levelplay` | `capacitor-levelplay-ads` | +|---|---|---| +| iOS integration | SPM first: `Package.swift` depends on `LevelPlay-Swift-Package`; podspec as alternative | CocoaPods first; its `Package.swift` does not depend on the SDK (SDK code is compiled out unless you add a package yourself) | +| Formats | rewarded, interstitial, banner, native (templates) | banner, rewarded, interstitial | +| Ad units | any number per format side by side, addressed by `adUnitId` | one ad object per format at a time | +| Show result | promise resolves after close with `{ shown, rewarded, reward }` | outcome via events | +| Consent | GDPR / CCPA / COPPA flags; bring your own CMP | built-in consent flows (own consent modal, optional Usercentrics / InMobi CMP) | +| Adapters | added by the app (Gradle / Swift packages / pods) | helper script that injects adapter pods from `package.json` | + +Pick the one that fits your project. + +**Is the LevelPlay SDK bundled?** +No. The plugin declares the SDK as a dependency (Maven Central, Swift package or pod). The SDK is proprietary and +covered by Unity's terms. ## API -| method | description | -|---|---| -| `initialize({ appKey, userId?, testSuite?, adaptersDebug?, consent? })` | `LevelPlay.init`; resolves `{ sdkVersion }` on success, rejects with the init error. Idempotent. | -| `getSdkVersion()` | `{ sdkVersion }` | -| `setConsent({ gdprConsent?, ccpaDoNotSell?, coppa? })` | privacy signals | -| `setMetaData({ key, value })` | `LevelPlay.setMetaData` | -| `requestTrackingAuthorization()` / `getTrackingAuthorizationStatus()` | iOS ATT, `{ status }`; `unavailable` on Android / web | -| `loadRewarded({ adUnitId })` / `loadInterstitial({ adUnitId })` | start a load; outcome via `loaded` / `loadFailed` | -| `showRewarded({ adUnitId, placementName? })` / `showInterstitial(...)` | show; resolves after close with the result | -| `isReady({ format, adUnitId })` | `{ ready }` | -| `launchTestSuite()` | LevelPlay Integration Test Suite | -| `validateIntegration()` | integration helper report in the native log | + -Events (`addListener`): `loaded`, `loadFailed`, `displayed`, `displayFailed`, `clicked`, `closed`, `rewarded`. -Every event carries `{ format: 'rewarded' | 'interstitial', adUnitId, adInfo? }`, plus `error` (failures) or `reward`. -Full types with JSDoc: [`src/definitions.ts`](src/definitions.ts). +* [`initialize(...)`](#initialize) +* [`getSdkVersion()`](#getsdkversion) +* [`setConsent(...)`](#setconsent) +* [`setMetaData(...)`](#setmetadata) +* [`requestTrackingAuthorization()`](#requesttrackingauthorization) +* [`getTrackingAuthorizationStatus()`](#gettrackingauthorizationstatus) +* [`loadRewarded(...)`](#loadrewarded) +* [`showRewarded(...)`](#showrewarded) +* [`loadInterstitial(...)`](#loadinterstitial) +* [`showInterstitial(...)`](#showinterstitial) +* [`isReady(...)`](#isready) +* [`launchTestSuite()`](#launchtestsuite) +* [`validateIntegration()`](#validateintegration) +* [`getCapabilities()`](#getcapabilities) +* [`setSegment(...)`](#setsegment) +* [`setDynamicUserId(...)`](#setdynamicuserid) +* [`isPlacementCapped(...)`](#isplacementcapped) +* [`getReward(...)`](#getreward) +* [`createBanner(...)`](#createbanner) +* [`loadBanner(...)`](#loadbanner) +* [`showBanner(...)`](#showbanner) +* [`hideBanner(...)`](#hidebanner) +* [`setBannerLayout(...)`](#setbannerlayout) +* [`destroyBanner(...)`](#destroybanner) +* [`loadNativeAd(...)`](#loadnativead) +* [`showNativeAd(...)`](#shownativead) +* [`setNativeAdRect(...)`](#setnativeadrect) +* [`hideNativeAd(...)`](#hidenativead) +* [`destroyNativeAd(...)`](#destroynativead) +* [`addListener('loaded', ...)`](#addlistenerloaded-) +* [`addListener('loadFailed', ...)`](#addlistenerloadfailed-) +* [`addListener('displayed', ...)`](#addlistenerdisplayed-) +* [`addListener('displayFailed', ...)`](#addlistenerdisplayfailed-) +* [`addListener('clicked', ...)`](#addlistenerclicked-) +* [`addListener('closed', ...)`](#addlistenerclosed-) +* [`addListener('rewarded', ...)`](#addlistenerrewarded-) +* [`addListener('adInfoChanged', ...)`](#addlisteneradinfochanged-) +* [`addListener('impressionData', ...)`](#addlistenerimpressiondata-) +* [`addListener('bannerLoaded', ...)`](#addlistenerbannerloaded-) +* [`addListener('bannerLoadFailed', ...)`](#addlistenerbannerloadfailed-) +* [`addListener('bannerDisplayed', ...)`](#addlistenerbannerdisplayed-) +* [`addListener('bannerDisplayFailed', ...)`](#addlistenerbannerdisplayfailed-) +* [`addListener('bannerClicked', ...)`](#addlistenerbannerclicked-) +* [`addListener('bannerExpanded', ...)`](#addlistenerbannerexpanded-) +* [`addListener('bannerCollapsed', ...)`](#addlistenerbannercollapsed-) +* [`addListener('bannerLeftApplication', ...)`](#addlistenerbannerleftapplication-) +* [`addListener('nativeAdLoaded', ...)`](#addlistenernativeadloaded-) +* [`addListener('nativeAdLoadFailed', ...)`](#addlistenernativeadloadfailed-) +* [`addListener('nativeAdImpression', ...)`](#addlistenernativeadimpression-) +* [`addListener('nativeAdClicked', ...)`](#addlistenernativeadclicked-) +* [`removeAllListeners()`](#removealllisteners) +* [Interfaces](#interfaces) +* [Type Aliases](#type-aliases) -On the web the plugin is a stub: `initialize` rejects as unimplemented, nothing is ever ready and shows resolve -`{ shown: false }`. + -## Development + + + +Unity LevelPlay ads (ad-unit API): rewarded, interstitial and (since 0.3.0) banner and native ads, impression-level +revenue, segments and placement capping. + +### initialize(...) + +```typescript +initialize(options: InitOptions) => Promise +``` + +Initialise the LevelPlay SDK (`LevelPlay.init`). Resolves on init success, rejects with the init error +(code and message from the SDK) otherwise. Calling it again after a successful init resolves immediately; +concurrent calls share one init. Load ads only after this resolves. + +Set consent (and on iOS ask for ATT) before calling it. + +On the web it rejects as unimplemented. + +| Param | Type | +| ------------- | --------------------------------------------------- | +| **`options`** | InitOptions | + +**Returns:** Promise<InitResult> + +**Since:** 0.1.0 + +-------------------- + + +### getSdkVersion() + +```typescript +getSdkVersion() => Promise +``` + +Native LevelPlay SDK version. Works before init. + +**Returns:** Promise<InitResult> + +**Since:** 0.1.0 + +-------------------- + + +### setConsent(...) + +```typescript +setConsent(options: ConsentOptions) => Promise +``` + +Forward GDPR / CCPA / COPPA signals to LevelPlay. Call it before `initialize()` when you +can, and again whenever the user changes their choice. + +| Param | Type | +| ------------- | --------------------------------------------------------- | +| **`options`** | ConsentOptions | + +**Since:** 0.1.0 + +-------------------- + + +### setMetaData(...) + +```typescript +setMetaData(options: MetaDataOptions) => Promise +``` + +Raw `LevelPlay.setMetaData(key, value)` for SDK or network-specific flags. Call it before init. + +| Param | Type | +| ------------- | ----------------------------------------------------------- | +| **`options`** | MetaDataOptions | + +**Since:** 0.1.0 + +-------------------- + + +### requestTrackingAuthorization() + +```typescript +requestTrackingAuthorization() => Promise +``` + +iOS: show the App Tracking Transparency prompt and resolve with the resulting status. Needs +`NSUserTrackingUsageDescription` in `Info.plist`. iOS only shows the prompt once; later calls resolve the stored +status. Call it before `initialize()`, while the app is active. + +Android and web: resolves `unavailable`. + +**Returns:** Promise<TrackingResult> + +**Since:** 0.1.0 + +-------------------- + + +### getTrackingAuthorizationStatus() + +```typescript +getTrackingAuthorizationStatus() => Promise +``` + +Current App Tracking Transparency status without prompting (iOS). Android and web: `unavailable`. + +**Returns:** Promise<TrackingResult> + +**Since:** 0.1.0 + +-------------------- + + +### loadRewarded(...) + +```typescript +loadRewarded(options: AdUnitOptions) => Promise +``` + +Start loading a rewarded ad for the ad unit. The native ad object is created on first use and reused for the +ad unit. Resolves once the request is issued; the outcome arrives as a `loaded` or `loadFailed` event. +Load the next ad after each show. + +| Param | Type | +| ------------- | ------------------------------------------------------- | +| **`options`** | AdUnitOptions | + +**Since:** 0.1.0 + +-------------------- + + +### showRewarded(...) + +```typescript +showRewarded(options: ShowOptions) => Promise +``` + +Show a loaded rewarded ad. Resolves after the ad closed (or failed to display) with what happened. The reward +and close callbacks can arrive in either order on some networks, so the plugin waits up to 1 second after the close +for a late reward. Never rejects for "not ready": resolves `{ shown: false, rewarded: false, error }` instead. + +| Param | Type | +| ------------- | --------------------------------------------------- | +| **`options`** | ShowOptions | + +**Returns:** Promise<ShowResult> + +**Since:** 0.1.0 + +-------------------- + + +### loadInterstitial(...) + +```typescript +loadInterstitial(options: AdUnitOptions) => Promise +``` + +Start loading an interstitial ad for the ad unit. Works like `loadRewarded()`. + +| Param | Type | +| ------------- | ------------------------------------------------------- | +| **`options`** | AdUnitOptions | + +**Since:** 0.1.0 + +-------------------- + + +### showInterstitial(...) + +```typescript +showInterstitial(options: ShowOptions) => Promise +``` + +Show a loaded interstitial. Resolves after it closed (or failed to display). Never rejects for "not ready". + +| Param | Type | +| ------------- | --------------------------------------------------- | +| **`options`** | ShowOptions | + +**Returns:** Promise<ShowResult> + +**Since:** 0.1.0 + +-------------------- + + +### isReady(...) + +```typescript +isReady(options: IsReadyOptions) => Promise +``` + +`isAdReady()` of the native ad object for this ad unit. `false` when the ad unit was never loaded. + +| Param | Type | +| ------------- | --------------------------------------------------------- | +| **`options`** | IsReadyOptions | + +**Returns:** Promise<IsReadyResult> + +**Since:** 0.1.0 + +-------------------- + + +### launchTestSuite() + +```typescript +launchTestSuite() => Promise +``` + +Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first. +Development builds only. Rejects on the web. + +**Since:** 0.1.0 + +-------------------- + + +### validateIntegration() + +```typescript +validateIntegration() => Promise +``` + +Write the LevelPlay integration helper report to the native log (Xcode console; Android logcat tag +`IntegrationHelper`): SDK, adapter and network SDK versions, each `VERIFIED` or not. Development only. + +**Since:** 0.1.0 + +-------------------- + + +### getCapabilities() + +```typescript +getCapabilities() => Promise +``` + +What this platform supports (banners, native ad templates, impression data, `adInfoChanged`). Works before init. +Web: everything `false`. + +**Returns:** Promise<Capabilities> + +**Since:** 0.3.0 + +-------------------- + + +### setSegment(...) + +```typescript +setSegment(options: SegmentOptions) => Promise +``` + +Set the user segment (`LevelPlay.setSegment` with a `LevelPlaySegment` / `LPMSegment`). Call it before +`initialize()` so the first ad requests use it; later calls apply to the following requests. Rejects with +`INVALID_ARGUMENT` when `customParameters` break the SDK limits. Web: no-op. + +| Param | Type | +| ------------- | --------------------------------------------------------- | +| **`options`** | SegmentOptions | + +**Since:** 0.3.0 + +-------------------- + + +### setDynamicUserId(...) + +```typescript +setDynamicUserId(options: DynamicUserIdOptions) => Promise +``` + +Set or change the dynamic user id used in server-to-server reward callbacks (`LevelPlay.setDynamicUserId` on +both platforms). Set it before `showRewarded()`. Web: resolves `{ valid: false }`. + +| Param | Type | +| ------------- | --------------------------------------------------------------------- | +| **`options`** | DynamicUserIdOptions | + +**Returns:** Promise<DynamicUserIdResult> + +**Since:** 0.3.0 + +-------------------- + + +### isPlacementCapped(...) + +```typescript +isPlacementCapped(options: PlacementCappedOptions) => Promise +``` + +Whether a rewarded or interstitial placement is capped right now (static +`LevelPlayRewardedAd.isPlacementCapped` / `LevelPlayInterstitialAd.isPlacementCapped` on Android, +`LPMRewardedAd.isPlacementCapped:` / `LPMInterstitialAd.isPlacementCapped:` on iOS). Works without a loaded ad. +Web: `{ capped: false }`. + +| Param | Type | +| ------------- | ------------------------------------------------------------------------- | +| **`options`** | PlacementCappedOptions | + +**Returns:** Promise<PlacementCappedResult> + +**Since:** 0.3.0 + +-------------------- + + +### getReward(...) + +```typescript +getReward(options: GetRewardOptions) => Promise +``` + +The reward configured for a rewarded ad unit or one of its placements (`LevelPlayRewardedAd.getReward(placement)` / +`LPMRewardedAd getReward(placementName:)`), for "watch a video for N coins" buttons. The SDK returns +`{ name: '', amount: 0 }` when it has no reward configuration (for example before init). Web: the same empty +reward. + +| Param | Type | +| ------------- | ------------------------------------------------------------- | +| **`options`** | GetRewardOptions | + +**Returns:** Promise<Reward> + +**Since:** 0.3.0 + +-------------------- + + +### createBanner(...) + +```typescript +createBanner(options: CreateBannerOptions) => Promise +``` + +Create a banner (`LevelPlayBannerAdView` / `LPMBannerAdView`) for the ad unit and attach it, hidden, in a +pass-through overlay above the WebView. Requires a finished `initialize()` (`NOT_INITIALIZED` otherwise). Rejects +with `ALREADY_EXISTS` when `bannerId` is in use; destroy it first. Does not load: call `loadBanner()`. +Web: rejects as unimplemented. + +| Param | Type | +| ------------- | ------------------------------------------------------------------- | +| **`options`** | CreateBannerOptions | + +**Returns:** Promise<BannerResult> + +**Since:** 0.3.0 + +-------------------- + + +### loadBanner(...) + +```typescript +loadBanner(options: BannerIdOptions) => Promise +``` + +Load the banner (`loadAd()` / `loadAdWithViewController:`). The outcome arrives as `bannerLoaded` or +`bannerLoadFailed`; after the first load the SDK refreshes the banner on the dashboard interval. The SDK accepts +one load per banner object: calling it again has no effect (Android logs "Banner load already called"), so to retry +right away after `bannerLoadFailed`, destroy the banner and create it again. Web: no-op. + +| Param | Type | +| ------------- | ----------------------------------------------------------- | +| **`options`** | BannerIdOptions | + +**Since:** 0.3.0 + +-------------------- + + +### showBanner(...) + +```typescript +showBanner(options: BannerIdOptions) => Promise +``` + +Make the banner visible and resume auto refresh (`resumeAutoRefresh`). Can be called before the load finished; +the creative appears when it arrives. Web: rejects as unimplemented. + +| Param | Type | +| ------------- | ----------------------------------------------------------- | +| **`options`** | BannerIdOptions | + +**Returns:** Promise<BannerResult> + +**Since:** 0.3.0 + +-------------------- + + +### hideBanner(...) + +```typescript +hideBanner(options: BannerIdOptions) => Promise +``` + +Hide the banner and pause auto refresh (`pauseAutoRefresh`) so hidden banners do not burn impressions. The view +stays attached; `showBanner()` brings it back. Web: no-op. + +| Param | Type | +| ------------- | ----------------------------------------------------------- | +| **`options`** | BannerIdOptions | + +**Since:** 0.3.0 + +-------------------- + + +### setBannerLayout(...) + +```typescript +setBannerLayout(options: SetBannerLayoutOptions) => Promise +``` + +Move a banner (position, offsets, safe area). Resolves with the new frame. Web: rejects as unimplemented. + +| Param | Type | +| ------------- | ------------------------------------------------------------------------- | +| **`options`** | SetBannerLayoutOptions | + +**Returns:** Promise<BannerResult> + +**Since:** 0.3.0 + +-------------------- + + +### destroyBanner(...) + +```typescript +destroyBanner(options: BannerIdOptions) => Promise +``` + +Remove the banner from the screen and `destroy()` it. A destroyed banner cannot be reused; create a new one. +Resolves also for unknown ids. Web: no-op. + +| Param | Type | +| ------------- | ----------------------------------------------------------- | +| **`options`** | BannerIdOptions | + +**Since:** 0.3.0 + +-------------------- + + +### loadNativeAd(...) + +```typescript +loadNativeAd(options: LoadNativeAdOptions) => Promise +``` + +Load a native ad into a slot. Following the SDK rule "one native ad object per load", it destroys the slot's +previous ad (hiding it if shown), builds a new `LevelPlayNativeAd` with the placement and loads it. The outcome +arrives as `nativeAdLoaded` or `nativeAdLoadFailed`. Requires a finished `initialize()`. Rejects with +`UNSUPPORTED` when `getCapabilities().nativeAd` is `false` or the template is not listed there. Web: rejects as +unimplemented. + +| Param | Type | +| ------------- | ------------------------------------------------------------------- | +| **`options`** | LoadNativeAdOptions | + +**Since:** 0.3.0 + +-------------------- + + +### showNativeAd(...) + +```typescript +showNativeAd(options: NativeAdRectOptions) => Promise +``` + +Render the loaded native ad into its template, register the asset views with the SDK +(`NativeAdLayout.registerNativeAdViews` / `ISNativeAdView registerNativeAdViews:`) and place it at `rect` above the +WebView. Rejects with `NOT_LOADED` before `nativeAdLoaded`. The impression is reported by `nativeAdImpression`. +Web: rejects as unimplemented. + +| Param | Type | +| ------------- | ------------------------------------------------------------------- | +| **`options`** | NativeAdRectOptions | + +**Since:** 0.3.0 + +-------------------- + + +### setNativeAdRect(...) + +```typescript +setNativeAdRect(options: NativeAdRectOptions) => Promise +``` + +Move or resize a shown native ad, for example after the placeholder element moved. Web: no-op. + +| Param | Type | +| ------------- | ------------------------------------------------------------------- | +| **`options`** | NativeAdRectOptions | + +**Since:** 0.3.0 + +-------------------- + + +### hideNativeAd(...) + +```typescript +hideNativeAd(options: NativeAdIdOptions) => Promise +``` + +Hide a shown native ad (the view stays registered; `showNativeAd()` shows it again). Web: no-op. + +| Param | Type | +| ------------- | --------------------------------------------------------------- | +| **`options`** | NativeAdIdOptions | + +**Since:** 0.3.0 + +-------------------- + + +### destroyNativeAd(...) + +```typescript +destroyNativeAd(options: NativeAdIdOptions) => Promise +``` + +Remove the native ad view and `destroyAd()` it. Resolves also for unknown ids. Web: no-op. + +| Param | Type | +| ------------- | --------------------------------------------------------------- | +| **`options`** | NativeAdIdOptions | + +**Since:** 0.3.0 + +-------------------- + + +### addListener('loaded', ...) + +```typescript +addListener(eventName: 'loaded', listenerFunc: (event: AdEvent) => void) => Promise +``` + +An ad finished loading for the ad unit and can be shown. + +| Param | Type | +| ------------------ | --------------------------------------------------------------- | +| **`eventName`** | 'loaded' | +| **`listenerFunc`** | (event: AdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.1.0 + +-------------------- + + +### addListener('loadFailed', ...) + +```typescript +addListener(eventName: 'loadFailed', listenerFunc: (event: AdErrorEvent) => void) => Promise +``` + +Loading failed, for example `509` (no fill). Retry later with a backoff. + +| Param | Type | +| ------------------ | ------------------------------------------------------------------------- | +| **`eventName`** | 'loadFailed' | +| **`listenerFunc`** | (event: AdErrorEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.1.0 + +-------------------- + + +### addListener('displayed', ...) + +```typescript +addListener(eventName: 'displayed', listenerFunc: (event: AdEvent) => void) => Promise +``` + +The ad was displayed (impression). `adInfo.revenue` is available here. + +| Param | Type | +| ------------------ | --------------------------------------------------------------- | +| **`eventName`** | 'displayed' | +| **`listenerFunc`** | (event: AdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.1.0 + +-------------------- + + +### addListener('displayFailed', ...) + +```typescript +addListener(eventName: 'displayFailed', listenerFunc: (event: AdErrorEvent) => void) => Promise +``` + +The ad failed to display. The pending show call resolves with the same error. + +| Param | Type | +| ------------------ | ------------------------------------------------------------------------- | +| **`eventName`** | 'displayFailed' | +| **`listenerFunc`** | (event: AdErrorEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.1.0 + +-------------------- + + +### addListener('clicked', ...) + +```typescript +addListener(eventName: 'clicked', listenerFunc: (event: AdEvent) => void) => Promise +``` + +The user clicked the ad. + +| Param | Type | +| ------------------ | --------------------------------------------------------------- | +| **`eventName`** | 'clicked' | +| **`listenerFunc`** | (event: AdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.1.0 + +-------------------- + + +### addListener('closed', ...) + +```typescript +addListener(eventName: 'closed', listenerFunc: (event: AdEvent) => void) => Promise +``` + +The ad was closed and the app is back in front. + +| Param | Type | +| ------------------ | --------------------------------------------------------------- | +| **`eventName`** | 'closed' | +| **`listenerFunc`** | (event: AdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.1.0 + +-------------------- + + +### addListener('rewarded', ...) + +```typescript +addListener(eventName: 'rewarded', listenerFunc: (event: AdRewardEvent) => void) => Promise +``` + +Rewarded only: the user earned the reward. Can fire before or after `closed`. + +| Param | Type | +| ------------------ | --------------------------------------------------------------------------- | +| **`eventName`** | 'rewarded' | +| **`listenerFunc`** | (event: AdRewardEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.1.0 + +-------------------- + + +### addListener('adInfoChanged', ...) + +```typescript +addListener(eventName: 'adInfoChanged', listenerFunc: (event: AdEvent) => void) => Promise +``` + +Rewarded and interstitial: the SDK reloaded the ad in the background and its ad info (network, revenue ...) +changed (`onAdInfoChanged` / `didChangeAdInfo:`). Banners and native ads have no such callback in SDK 9.6.1. + +| Param | Type | +| ------------------ | --------------------------------------------------------------- | +| **`eventName`** | 'adInfoChanged' | +| **`listenerFunc`** | (event: AdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('impressionData', ...) + +```typescript +addListener(eventName: 'impressionData', listenerFunc: (event: ImpressionData) => void) => Promise +``` + +Impression-level revenue data for every rewarded, interstitial and banner impression (per-ad +`setImpressionDataListener` / `setImpressionDataDelegate:`, attached by the plugin to every ad object it creates), +plus native ad impressions synthesised from the native ad info (`adFormat: 'nativead'`, `adInfo` fields only). +Add the listener at any time, also before `initialize()`; nothing is delivered before the first ad shows. + +| Param | Type | +| ------------------ | ----------------------------------------------------------------------------- | +| **`eventName`** | 'impressionData' | +| **`listenerFunc`** | (event: ImpressionData) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerLoaded', ...) + +```typescript +addListener(eventName: 'bannerLoaded', listenerFunc: (event: BannerEvent) => void) => Promise +``` + +A banner loaded or refreshed with a new creative. + +| Param | Type | +| ------------------ | ----------------------------------------------------------------------- | +| **`eventName`** | 'bannerLoaded' | +| **`listenerFunc`** | (event: BannerEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerLoadFailed', ...) + +```typescript +addListener(eventName: 'bannerLoadFailed', listenerFunc: (event: BannerErrorEvent) => void) => Promise +``` + +A banner load (or refresh) failed. The SDK keeps retrying on its refresh interval. + +| Param | Type | +| ------------------ | --------------------------------------------------------------------------------- | +| **`eventName`** | 'bannerLoadFailed' | +| **`listenerFunc`** | (event: BannerErrorEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerDisplayed', ...) + +```typescript +addListener(eventName: 'bannerDisplayed', listenerFunc: (event: BannerEvent) => void) => Promise +``` + +A banner creative was displayed on screen (impression). + +| Param | Type | +| ------------------ | ----------------------------------------------------------------------- | +| **`eventName`** | 'bannerDisplayed' | +| **`listenerFunc`** | (event: BannerEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerDisplayFailed', ...) + +```typescript +addListener(eventName: 'bannerDisplayFailed', listenerFunc: (event: BannerErrorEvent) => void) => Promise +``` + +A banner creative failed to display. + +| Param | Type | +| ------------------ | --------------------------------------------------------------------------------- | +| **`eventName`** | 'bannerDisplayFailed' | +| **`listenerFunc`** | (event: BannerErrorEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerClicked', ...) + +```typescript +addListener(eventName: 'bannerClicked', listenerFunc: (event: BannerEvent) => void) => Promise +``` + +The user clicked a banner. + +| Param | Type | +| ------------------ | ----------------------------------------------------------------------- | +| **`eventName`** | 'bannerClicked' | +| **`listenerFunc`** | (event: BannerEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerExpanded', ...) + +```typescript +addListener(eventName: 'bannerExpanded', listenerFunc: (event: BannerEvent) => void) => Promise +``` + +A banner opened full screen (for example an expandable creative). Pause the game. + +| Param | Type | +| ------------------ | ----------------------------------------------------------------------- | +| **`eventName`** | 'bannerExpanded' | +| **`listenerFunc`** | (event: BannerEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerCollapsed', ...) + +```typescript +addListener(eventName: 'bannerCollapsed', listenerFunc: (event: BannerEvent) => void) => Promise +``` + +A banner returned to its normal size. Resume the game. + +| Param | Type | +| ------------------ | ----------------------------------------------------------------------- | +| **`eventName`** | 'bannerCollapsed' | +| **`listenerFunc`** | (event: BannerEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('bannerLeftApplication', ...) + +```typescript +addListener(eventName: 'bannerLeftApplication', listenerFunc: (event: BannerEvent) => void) => Promise +``` + +A banner click sent the user out of the app (browser or store). + +| Param | Type | +| ------------------ | ----------------------------------------------------------------------- | +| **`eventName`** | 'bannerLeftApplication' | +| **`listenerFunc`** | (event: BannerEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('nativeAdLoaded', ...) + +```typescript +addListener(eventName: 'nativeAdLoaded', listenerFunc: (event: NativeAdEvent) => void) => Promise +``` + +A native ad loaded and can be shown with `showNativeAd()`. + +| Param | Type | +| ------------------ | --------------------------------------------------------------------------- | +| **`eventName`** | 'nativeAdLoaded' | +| **`listenerFunc`** | (event: NativeAdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('nativeAdLoadFailed', ...) + +```typescript +addListener(eventName: 'nativeAdLoadFailed', listenerFunc: (event: NativeAdErrorEvent) => void) => Promise +``` + +A native ad failed to load. Load again later (the plugin already destroyed the failed ad object). + +| Param | Type | +| ------------------ | ------------------------------------------------------------------------------------- | +| **`eventName`** | 'nativeAdLoadFailed' | +| **`listenerFunc`** | (event: NativeAdErrorEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('nativeAdImpression', ...) + +```typescript +addListener(eventName: 'nativeAdImpression', listenerFunc: (event: NativeAdEvent) => void) => Promise +``` + +A shown native ad recorded its impression (first pixel visible). + +| Param | Type | +| ------------------ | --------------------------------------------------------------------------- | +| **`eventName`** | 'nativeAdImpression' | +| **`listenerFunc`** | (event: NativeAdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### addListener('nativeAdClicked', ...) + +```typescript +addListener(eventName: 'nativeAdClicked', listenerFunc: (event: NativeAdEvent) => void) => Promise +``` + +The user clicked a native ad. + +| Param | Type | +| ------------------ | --------------------------------------------------------------------------- | +| **`eventName`** | 'nativeAdClicked' | +| **`listenerFunc`** | (event: NativeAdEvent) => void | + +**Returns:** Promise<PluginListenerHandle> + +**Since:** 0.3.0 + +-------------------- + + +### removeAllListeners() + +```typescript +removeAllListeners() => Promise +``` + +Remove every listener of this plugin. + +**Since:** 0.1.0 + +-------------------- + + +### Interfaces + + +#### InitResult + +Result of `initialize()` and `getSdkVersion()`. + +| Prop | Type | Description | Since | +| ---------------- | ------------------- | -------------------------------------------------------------------- | ----- | +| **`sdkVersion`** | string | Native LevelPlay SDK version, for example `9.6.1`. `web` on the web. | 0.1.0 | + + +#### InitOptions + +Options for `initialize()`. + +| Prop | Type | Description | Default | Since | +| ------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ----- | +| **`appKey`** | string | LevelPlay app key from the LevelPlay dashboard. Android and iOS apps have different keys. | | 0.1.0 | +| **`userId`** | string | Optional user id. Needed for server-to-server reward callbacks and the Ad Quality user journey. | | 0.1.0 | +| **`testSuite`** | boolean | Enable the LevelPlay Integration Test Suite: sets the `is_test_suite=enable` meta data before init. Call `launchTestSuite()` after `initialize` resolves. Never ship this enabled. | false | 0.1.0 | +| **`adaptersDebug`** | boolean | Turn on debug logs of the mediated ad network adapters (`LevelPlay.setAdaptersDebug(true)`). Development only. | false | 0.1.0 | +| **`consent`** | ConsentOptions | Privacy signals applied right before init (LevelPlay recommends setting them before the SDK starts). Same as calling `setConsent()` first. | | 0.1.0 | + + +#### ConsentOptions + +Privacy signals forwarded to LevelPlay (`LevelPlayPrivacySettings` on Android, `LPMPrivacySettings` on iOS). +Omitted fields are left untouched. + +| Prop | Type | Description | Since | +| ------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----- | +| **`gdprConsent`** | boolean | GDPR: `true` when the user consented to personalised ads and data processing, `false` when they did not. For users in the EEA, UK and Switzerland pass `false` until a consent management platform (CMP) says otherwise. | 0.1.0 | +| **`ccpaDoNotSell`** | boolean | CCPA and other US state privacy laws: `true` when the user opted OUT of the sale or sharing of personal data ("do not sell"), `false` otherwise. | 0.1.0 | +| **`coppa`** | boolean | COPPA: `true` when the user must be treated as a child (child-directed treatment). | 0.1.0 | + + +#### MetaDataOptions + +Options for `setMetaData()`. + +| Prop | Type | Description | Since | +| ----------- | ------------------- | --------------------------------------------------------------------------------------------- | ----- | +| **`key`** | string | Meta data key, for example `is_deviceid_optout` or a network-specific flag from Unity's docs. | 0.1.0 | +| **`value`** | string | Meta data value, always a string (for example `"true"`). | 0.1.0 | + + +#### TrackingResult + +Result of `requestTrackingAuthorization()` and +`getTrackingAuthorizationStatus()`. + +| Prop | Type | Description | Since | +| ------------ | --------------------------------------------------------- | ------------------------------------------------------------------------------ | ----- | +| **`status`** | TrackingStatus | iOS App Tracking Transparency status. Always `unavailable` on Android and web. | 0.1.0 | + + +#### AdUnitOptions + +Identifies one ad unit. + +| Prop | Type | Description | Since | +| -------------- | ------------------- | ----------------------------------------------------------------------------------------------------- | ----- | +| **`adUnitId`** | string | Ad unit id from the LevelPlay dashboard (Ad units page). Android and iOS ad units have different ids. | 0.1.0 | + + +#### ShowResult + +Result of `showRewarded()` and `showInterstitial()`, resolved after the ad +closed or failed to display. + +| Prop | Type | Description | Since | +| -------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----- | +| **`shown`** | boolean | The ad was displayed (the `displayed` event fired). | 0.1.0 | +| **`rewarded`** | boolean | Rewarded only: the reward callback fired for this show. Grant the reward only when this is `true`. Always `false` for interstitials. | 0.1.0 | +| **`reward`** | Reward | The reward, present when `rewarded` is `true`. | 0.1.0 | +| **`error`** | AdError | Present when the ad was not ready (`code: -1`) or failed to display. | 0.1.0 | +| **`adInfo`** | AdInfo | Info of the displayed ad. | 0.1.0 | + + +#### Reward + +The reward of a rewarded ad, as configured in the LevelPlay dashboard (per ad unit or placement). + +| Prop | Type | Description | Since | +| ------------ | ------------------- | ---------------------------------------- | ----- | +| **`name`** | string | Name of the reward, for example `Coins`. | 0.1.0 | +| **`amount`** | number | Amount of the reward. | 0.1.0 | + + +#### AdError + +Error reported by the SDK (load / display failures) or by the plugin. + +| Prop | Type | Description | Since | +| ------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------- | ----- | +| **`code`** | number | LevelPlay error code, for example `509` (no fill). `-1` is used by the plugin for "Ad not ready" and for the web stub. | 0.1.0 | +| **`message`** | string | Human readable message. | 0.1.0 | + + +#### AdInfo + +Subset of the native `LevelPlayAdInfo` (Android) / `LPMAdInfo` (iOS) that is useful in JavaScript. +Fields the SDK does not report are omitted. + +| Prop | Type | Description | Since | +| --------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | +| **`adId`** | string | Unique id of this ad. | 0.1.0 | +| **`adUnitId`** | string | Ad unit id. | 0.1.0 | +| **`adUnitName`** | string | Ad unit name from the dashboard. | 0.1.0 | +| **`adFormat`** | string | Ad format as reported by the SDK. | 0.1.0 | +| **`placementName`** | string | Placement name of the show call, when one was used. | 0.1.0 | +| **`adNetwork`** | string | Name of the mediated network that served the ad. | 0.1.0 | +| **`instanceName`** | string | Mediation instance name. | 0.1.0 | +| **`instanceId`** | string | Mediation instance id. | 0.1.0 | +| **`country`** | string | Country code of the impression. | 0.1.0 | +| **`auctionId`** | string | Auction id. | 0.1.0 | +| **`revenue`** | number | Impression revenue in USD as reported by the SDK (may be absent or 0 before display). | 0.1.0 | +| **`precision`** | string | Revenue precision as reported by the SDK. | 0.1.0 | +| **`ab`** | string | A/B test group of the user (`ab`). | 0.3.0 | +| **`segmentName`** | string | Segment name of the user, see `setSegment()`. | 0.3.0 | +| **`encryptedCPM`** | string | Encrypted CPM (`encryptedCPM`). | 0.3.0 | +| **`creativeId`** | string | Creative id of the served ad, when the network reports one. | 0.3.0 | +| **`conversionValue`** | number | iOS only: SKAdNetwork conversion value (`LPMAdInfo.conversionValue`). Android's `LevelPlayAdInfo` has no such field in SDK 9.6.1, so it is always absent there. | 0.3.0 | +| **`adSize`** | AdSizeInfo | Size of the ad. Banners only (`LevelPlayAdInfo.getAdSize()` / `LPMAdInfo.adSize`). | 0.3.0 | + + +#### AdSizeInfo + +A resolved ad size as reported by the SDK (`LevelPlayAdSize` / `LPMAdSize`). Width and height are in dp on Android +and points on iOS, which equal CSS px in the WebView at the default zoom. + +| Prop | Type | Description | Since | +| ----------------- | -------------------- | ---------------------------------------------------------------- | ----- | +| **`width`** | number | Width in CSS px (dp / pt). | 0.3.0 | +| **`height`** | number | Height in CSS px (dp / pt). | 0.3.0 | +| **`description`** | string | SDK description of the size, for example `BANNER` or `ADAPTIVE`. | 0.3.0 | +| **`isAdaptive`** | boolean | `true` for an adaptive size. | 0.3.0 | + + +#### ShowOptions + +Options for `showRewarded()` and `showInterstitial()`: `adUnitId` (see AdUnitOptions) plus an optional placement. + +| Prop | Type | Description | Since | +| ------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ----- | +| **`placementName`** | string | Optional placement name configured in the LevelPlay dashboard (capping, pacing and reward per placement). Omit it to use the default placement. | 0.1.0 | + + +#### IsReadyResult + +Result of `isReady()`. + +| Prop | Type | Description | Since | +| ----------- | -------------------- | ----------------------------------------------- | ----- | +| **`ready`** | boolean | `true` when a loaded ad can be shown right now. | 0.1.0 | + + +#### IsReadyOptions + +Options for `isReady()`: `adUnitId` (see AdUnitOptions) plus the format. + +| Prop | Type | Description | Since | +| ------------ | --------------------------------------------- | ---------------------- | ----- | +| **`format`** | AdFormat | Format of the ad unit. | 0.1.0 | + + +#### Capabilities + +Result of `getCapabilities()`: what this platform build of the plugin can do. Check it instead of the platform +name, so the same game code runs on Android, iOS and the web. + +| Prop | Type | Description | Since | +| ----------------------- | ------------------------------- | ------------------------------------------------------------------------------- | ----- | +| **`banner`** | boolean | Banner ads (`createBanner()` and friends) are available. | 0.3.0 | +| **`nativeAd`** | boolean | Native ads (`loadNativeAd()` and friends) are available. | 0.3.0 | +| **`nativeAdTemplates`** | NativeAdTemplate[] | Native ad templates this platform can render. Empty when `nativeAd` is `false`. | 0.3.0 | +| **`impressionData`** | boolean | The `impressionData` event is delivered. | 0.3.0 | +| **`adInfoChanged`** | boolean | The `adInfoChanged` event is delivered (rewarded and interstitial only). | 0.3.0 | + + +#### SegmentOptions + +Options for `setSegment()` (`LevelPlaySegment` / `LPMSegment`). Omitted fields are not sent. + +| Prop | Type | Description | Since | +| ---------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | +| **`segmentName`** | string | Segment name. | 0.3.0 | +| **`level`** | number | User level (integer). | 0.3.0 | +| **`isPaying`** | boolean | The user has paid in the app. | 0.3.0 | +| **`userCreationDate`** | number | When the user was created, in milliseconds since the Unix epoch (`Date.now()` style). | 0.3.0 | +| **`iapTotal`** | number | Total in-app purchase amount of the user (USD). | 0.3.0 | +| **`customParameters`** | { [key: string]: string; } | Custom segment parameters. SDK 9.6.1 limits: at most 5 pairs; keys and values 1-32 characters, letters and digits only (`^[a-zA-Z0-9]*$`). The plugin rejects with `INVALID_ARGUMENT` instead of letting the SDK silently drop pairs. | 0.3.0 | + + +#### DynamicUserIdResult + +Result of `setDynamicUserId()`. + +| Prop | Type | Description | Since | +| ----------- | -------------------- | ------------------------------------------------------------------------------------------- | ----- | +| **`valid`** | boolean | The SDK accepted the id (`LevelPlay.setDynamicUserId` returns a boolean on both platforms). | 0.3.0 | + + +#### DynamicUserIdOptions + +Options for `setDynamicUserId()`. + +| Prop | Type | Description | Since | +| ------------ | ------------------- | ----------------------------------------------------------------------------------------------- | ----- | +| **`userId`** | string | Dynamic user id, forwarded in server-to-server reward callbacks. Can change during the session. | 0.3.0 | + + +#### PlacementCappedResult + +Result of `isPlacementCapped()`. + +| Prop | Type | Description | Since | +| ------------ | -------------------- | ------------------------------------------------------------------------------------ | ----- | +| **`capped`** | boolean | `true` when the placement reached its capping or pacing limit; showing it now fails. | 0.3.0 | + + +#### PlacementCappedOptions + +Options for `isPlacementCapped()`. + +| Prop | Type | Description | Since | +| ------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----- | +| **`format`** | AdFormat | Format of the placement. LevelPlay 9.6.1 has capping checks for rewarded and interstitial only. | 0.3.0 | +| **`placementName`** | string | Placement name from the LevelPlay dashboard. | 0.3.0 | + + +#### GetRewardOptions + +Options for `getReward()`: `adUnitId` (see AdUnitOptions) plus an optional placement. + +| Prop | Type | Description | Since | +| ------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------- | ----- | +| **`placementName`** | string | Placement whose reward to read. Its reward takes precedence over the ad unit reward. Omit for the ad unit reward. | 0.3.0 | + + +#### BannerResult + +Result of `createBanner()`, `showBanner()` and `setBannerLayout()`. + +| Prop | Type | Description | Since | +| -------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ----- | +| **`bannerId`** | string | The banner id. | 0.3.0 | +| **`adSize`** | AdSizeInfo | Requested ad size (the creative may be smaller for adaptive sizes; it is centred in this frame). | 0.3.0 | +| **`frame`** | Rect | Where the banner frame is (or will be, while hidden) in CSS px, relative to the WebView viewport. Use it to pad game UI away from the banner. | 0.3.0 | +| **`visible`** | boolean | The banner view is currently visible. | 0.3.0 | + + +#### Rect + +A rectangle in CSS px, relative to the top-left corner of the WebView viewport (the same space as +`element.getBoundingClientRect()` without page scroll). + +| Prop | Type | Description | Since | +| ------------ | ------------------- | -------------------- | ----- | +| **`x`** | number | Left edge in CSS px. | 0.3.0 | +| **`y`** | number | Top edge in CSS px. | 0.3.0 | +| **`width`** | number | Width in CSS px. | 0.3.0 | +| **`height`** | number | Height in CSS px. | 0.3.0 | + + +#### CreateBannerOptions + +Options for `createBanner()`. + +| Prop | Type | Description | Default | Since | +| ------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ----- | +| **`bannerId`** | string | Plugin-side id of this banner, used by every other banner method and in banner events. Lets one ad unit back several banners. Defaults to `adUnitId`. | | 0.3.0 | +| **`size`** | BannerSize | Size preset. | 'ADAPTIVE' | 0.3.0 | +| **`customSize`** | BannerCustomSize | `CUSTOM` only: the banner size. When `customSize` is set and `size` is omitted, `size` defaults to `CUSTOM`. | | 0.3.0 | +| **`adaptiveWidth`** | number | `ADAPTIVE` only: width in CSS px to compute the adaptive size for. Defaults to the width of the WebView's safe area; in that case the plugin recreates and reloads the banner automatically when that width changes (rotation, split screen, window resize), keeping its id, layout and visibility. A fixed `adaptiveWidth` is never recreated. | | 0.3.0 | +| **`placementName`** | string | Placement name (reporting only for banners). Applied through the banner config before the first load. | | 0.3.0 | +| **`bidFloor`** | number | Bid floor in USD (`LevelPlayBannerAdView.Config.Builder.setBidFloor` / `LPMBannerAdViewConfigBuilder set(bidFloor:)`). | | 0.3.0 | + + +#### BannerCustomSize + +Width and height of a `CUSTOM` banner, in CSS px (dp on Android, points on iOS). + +| Prop | Type | Description | Since | +| ------------ | ------------------- | ------------------------------------ | ----- | +| **`width`** | number | Width in CSS px (positive integer). | 0.3.0 | +| **`height`** | number | Height in CSS px (positive integer). | 0.3.0 | + + +#### BannerIdOptions + +Identifies one banner created with `createBanner()`. + +| Prop | Type | Description | Since | +| -------------- | ------------------- | ------------------------------------------------------------------------------------ | ----- | +| **`bannerId`** | string | Plugin-side banner id passed to `createBanner()` (defaults to the ad unit id there). | 0.3.0 | + + +#### SetBannerLayoutOptions + +Options for `setBannerLayout()`: `bannerId` plus the layout fields (see BannerLayoutOptions). + + +#### LoadNativeAdOptions + +Options for `loadNativeAd()`. + +| Prop | Type | Description | Default | Since | +| ------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | ----- | +| **`placementName`** | string | Placement name. LevelPlay 9.6.1 native ads are addressed by placement only (`LevelPlayNativeAd.Builder .withPlacementName` / `LevelPlayNativeAdBuilder withPlacementName:`); there is no ad unit id for native ads in this SDK version. Omit it for the default placement. | | 0.3.0 | +| **`template`** | NativeAdTemplate | Template used when the ad is shown. | 'medium' | 0.3.0 | +| **`style`** | NativeAdTemplateStyle | Template styling. | | 0.3.0 | + + +#### NativeAdTemplateStyle + +Optional styling of a native ad template. Colours are CSS hex strings (`#RRGGBB` or `#RRGGBBAA`). + +| Prop | Type | Description | Default | Since | +| --------------------------------- | ----------------------------------------------------- | ---------------------------------------- | -------------- | ----- | +| **`backgroundColor`** | string | Template background. | | 0.3.0 | +| **`titleColor`** | string | Title text colour. | | 0.3.0 | +| **`bodyColor`** | string | Body and advertiser text colour. | | 0.3.0 | +| **`callToActionBackgroundColor`** | string | Call-to-action button background. | | 0.3.0 | +| **`callToActionTextColor`** | string | Call-to-action button text colour. | | 0.3.0 | +| **`cornerRadius`** | number | Corner radius of the template in CSS px. | 0 | 0.3.0 | +| **`titleFont`** | NativeAdFont | Title font. | | 0.3.0 | +| **`bodyFont`** | NativeAdFont | Body and advertiser font. | | 0.3.0 | +| **`callToActionFont`** | NativeAdFont | Call-to-action button font. | | 0.3.0 | + + +#### NativeAdFont + +A font of a native ad template text. Omitted fields keep the template default (system font). + +| Prop | Type | Description | Since | +| ------------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | +| **`family`** | string | Font family. Either a system family name (Android: `sans-serif`, `sans-serif-medium`, `serif`, `monospace` ...; iOS: a `UIFont` family or PostScript name such as `Avenir Next` or `Menlo-Bold`), or the path of a `.ttf` / `.otf` file inside the app's web assets, relative to the web root (for example `fonts/Inter-Bold.ttf`, the same file the page loads with `@font-face`). Unknown families fall back to the system font. | 0.3.0 | +| **`size`** | number | Font size in CSS px (dp / pt; not scaled by the system font size setting, like text in the WebView). | 0.3.0 | + + +#### NativeAdRectOptions + +Options for `showNativeAd()` and `setNativeAdRect()`. + +| Prop | Type | Description | Since | +| ---------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----- | +| **`rect`** | Rect | Where the template goes, in CSS px relative to the WebView viewport (for example a placeholder element's `getBoundingClientRect()`). | 0.3.0 | + + +#### NativeAdIdOptions + +Identifies one native ad slot. + +| Prop | Type | Description | Since | +| ---------------- | ------------------- | ------------------------------------- | ----- | +| **`nativeAdId`** | string | Plugin-side id of the native ad slot. | 0.3.0 | + + +#### PluginListenerHandle + +| Prop | Type | +| ------------ | ----------------------------------------- | +| **`remove`** | () => Promise<void> | + + +#### AdEvent + +Payload of the `loaded`, `displayed`, `clicked` and `closed` events. + +| Prop | Type | Description | Since | +| -------------- | --------------------------------------------- | -------------------------------------------------------- | ----- | +| **`format`** | AdFormat | Format of the ad unit that fired the event. | 0.1.0 | +| **`adUnitId`** | string | Ad unit that fired the event. | 0.1.0 | +| **`adInfo`** | AdInfo | Ad info, when the SDK provides it (not on `loadFailed`). | 0.1.0 | + + +#### AdErrorEvent + +Payload of the `loadFailed` and `displayFailed` events: the AdEvent fields plus `error`. + +| Prop | Type | Description | Since | +| ----------- | ------------------------------------------- | ---------------- | ----- | +| **`error`** | AdError | What went wrong. | 0.1.0 | + + +#### AdRewardEvent + +Payload of the `rewarded` event: the AdEvent fields plus `reward`. + +| Prop | Type | Description | Since | +| ------------ | ----------------------------------------- | ------------------ | ----- | +| **`reward`** | Reward | The reward earned. | 0.1.0 | + + +#### ImpressionData + +Impression-level revenue data (`LevelPlayImpressionData` on Android, `LPMImpressionData` on iOS). Every field the +SDK 9.6.1 data class exposes is mapped; fields the SDK leaves empty are omitted. + +Not available in SDK 9.6.1 on either platform: `lifetimeRevenue` (removed from the impression data class). If the +server ever sends extra keys they are still visible in `allData`. + +| Prop | Type | Description | Since | +| --------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | +| **`adFormat`** | string | Which ad format produced the impression, as the SDK reports it (for example `Rewarded Video`, `Interstitial`, `Banner`, or `nativead` for impressions synthesised from native ad info). | 0.3.0 | +| **`auctionId`** | string | Auction id. | 0.3.0 | +| **`adUnitId`** | string | Mediation ad unit id (`mediationAdUnitId`). | 0.3.0 | +| **`adUnitName`** | string | Mediation ad unit name (`mediationAdUnitName`). | 0.3.0 | +| **`adNetwork`** | string | Mediated network that served the ad. | 0.3.0 | +| **`instanceName`** | string | Mediation instance name. | 0.3.0 | +| **`instanceId`** | string | Mediation instance id. | 0.3.0 | +| **`country`** | string | Country code. | 0.3.0 | +| **`placement`** | string | Placement name of the impression. | 0.3.0 | +| **`revenue`** | number | Revenue of this impression in USD. | 0.3.0 | +| **`precision`** | string | Revenue precision (for example `BID`, `RATE`, `ESTIMATED`). | 0.3.0 | +| **`ab`** | string | A/B test group. | 0.3.0 | +| **`segmentName`** | string | Segment name, see `setSegment()`. | 0.3.0 | +| **`encryptedCPM`** | string | Encrypted CPM (`encryptedCPM` on Android, `encryptedCpm` on iOS). | 0.3.0 | +| **`creativeId`** | string | Creative id. | 0.3.0 | +| **`conversionValue`** | number | iOS only: SKAdNetwork conversion value. | 0.3.0 | +| **`allData`** | { [key: string]: unknown; } | The raw `allData` map of the SDK (`getAllData()` JSON on Android, `allData` dictionary on iOS). Keys and value types are SDK defined and may change between SDK versions. | 0.3.0 | + + +#### BannerEvent + +Payload of the `banner*` events. + +| Prop | Type | Description | Since | +| -------------- | ----------------------------------------- | -------------------------------------------------------------- | ----- | +| **`bannerId`** | string | Banner that fired the event. | 0.3.0 | +| **`adUnitId`** | string | Ad unit of the banner. | 0.3.0 | +| **`adInfo`** | AdInfo | Ad info, when the SDK provides it (not on `bannerLoadFailed`). | 0.3.0 | +| **`frame`** | Rect | Current frame of the banner in CSS px. | 0.3.0 | + + +#### BannerErrorEvent + +Payload of `bannerLoadFailed` and `bannerDisplayFailed`. + +| Prop | Type | Description | Since | +| ----------- | ------------------------------------------- | ---------------- | ----- | +| **`error`** | AdError | What went wrong. | 0.3.0 | + + +#### NativeAdEvent + +Payload of the `nativeAd*` events. + +| Prop | Type | Description | Since | +| ------------------- | ----------------------------------------------------- | ---------------------------------------------------------------- | ----- | +| **`nativeAdId`** | string | Native ad slot that fired the event. | 0.3.0 | +| **`placementName`** | string | Placement passed to `loadNativeAd()`, if any. | 0.3.0 | +| **`adInfo`** | NativeAdInfo | Ad info, when the SDK provides it (not on `nativeAdLoadFailed`). | 0.3.0 | + + +#### NativeAdInfo + +Ad info of a native ad (`AdInfo` on Android / `ISAdInfo` on iOS: the older ironSource info type, which has no ad +unit, ad id or placement fields). + +| Prop | Type | Description | Since | +| --------------------- | ------------------- | --------------------------------------- | ----- | +| **`auctionId`** | string | Auction id. | 0.3.0 | +| **`adNetwork`** | string | Mediated network that served the ad. | 0.3.0 | +| **`instanceName`** | string | Mediation instance name. | 0.3.0 | +| **`instanceId`** | string | Mediation instance id. | 0.3.0 | +| **`country`** | string | Country code. | 0.3.0 | +| **`revenue`** | number | Impression revenue in USD. | 0.3.0 | +| **`precision`** | string | Revenue precision. | 0.3.0 | +| **`ab`** | string | A/B test group. | 0.3.0 | +| **`segmentName`** | string | Segment name. | 0.3.0 | +| **`encryptedCPM`** | string | Encrypted CPM. | 0.3.0 | +| **`conversionValue`** | number | iOS only: SKAdNetwork conversion value. | 0.3.0 | + + +#### NativeAdErrorEvent + +Payload of `nativeAdLoadFailed`. + +| Prop | Type | Description | Since | +| ----------- | ------------------------------------------- | ---------------- | ----- | +| **`error`** | AdError | What went wrong. | 0.3.0 | + + +### Type Aliases + + +#### TrackingStatus + +iOS App Tracking Transparency status. `unavailable` on Android, on the web and on unknown future iOS values. + +'authorized' | 'denied' | 'restricted' | 'notDetermined' | 'unavailable' + + +#### AdFormat + +Full-screen ad formats (`loadRewarded` / `loadInterstitial` family and the `loaded` ... `rewarded` events). +Banners and native ads have their own methods and `banner*` / `nativeAd*` events (since 0.3.0), so this union +stays unchanged for 0.2.x code. + +'rewarded' | 'interstitial' + + +#### NativeAdTemplate + +Native ad template rendered by the plugin (the LevelPlay SDK ships no template views; the plugin provides its own +layouts, like Unity's Flutter and React Native wrappers do). + +- `small`: icon, title, advertiser, body, call to action; no media view. Recommended 300 x 175 or a row at least + 90 px tall. +- `medium`: the `small` assets plus a media view. Recommended 300 x 350. + +'small' | 'medium' + + +#### BannerSize + +Banner size presets, named after the SDK constants (`LevelPlayAdSize.BANNER` / `LPMAdSize.bannerSize()` ...). + +- `BANNER`: 320 x 50 +- `LARGE`: 320 x 90 +- `MEDIUM_RECTANGLE`: 300 x 250 +- `LEADERBOARD`: 728 x 90 (tablets) +- `ADAPTIVE`: `LevelPlayAdSize.createAdaptiveAdSize(context, width)` / `LPMAdSize.createAdaptiveAdSize(withWidth:)`; + the SDK picks the height (and BANNER or LEADERBOARD as fallback) for the given width. Requires a finished + `initialize()`. +- `CUSTOM`: `LevelPlayAdSize.createCustomSize(width, height)` / `LPMAdSize.customSizeWithWidth:height:` with + `customSize`. Few networks fill custom sizes; prefer a preset or `ADAPTIVE`. + +'BANNER' | 'LARGE' | 'MEDIUM_RECTANGLE' | 'LEADERBOARD' | 'ADAPTIVE' | 'CUSTOM' + + + +## Contributing + +Issues and pull requests are welcome on the [issue tracker](https://git.crt.fyi/CRT/capacitor-levelplay/issues). See +[CONTRIBUTING.md](CONTRIBUTING.md). ```sh bun install -bun run build # dist/ (esm + cjs + iife) -bun run verify:ios # xcodebuild the Swift package +bun run build # docgen + dist/ (esm, cjs, iife) +bun run typecheck +bun run verify:ios # xcodebuild the Swift package for the iOS simulator +bun run verify:android # Gradle build of the Android library (JDK 21, Android SDK) ``` -`dist/` is committed so the package can be installed straight from git. +Release notes: [CHANGELOG.md](CHANGELOG.md). ## License -MIT (see [LICENSE](LICENSE)). The Unity LevelPlay SDK itself is proprietary and governed by Unity's terms; this -plugin only declares it as a dependency and does not redistribute it. +[MIT](LICENSE) © CRTkafa + +The Unity LevelPlay SDK and the mediated network SDKs are proprietary and governed by their owners' terms. This plugin +only declares them as dependencies and does not redistribute them. LevelPlay, ironSource and Unity are trademarks of +Unity Technologies; this project is not affiliated with or endorsed by Unity. diff --git a/android/build.gradle b/android/build.gradle index 16083da..4b8facd 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -22,10 +22,10 @@ buildscript { apply plugin: 'com.android.library' android { - namespace = "com.voxgames.capacitor.levelplay" + namespace = "fyi.crt.capacitor.levelplay" compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36 defaultConfig { - minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 24 + minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 23 targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36 versionCode 1 versionName "1.0" diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..23192e2 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +# Standalone build of the plugin library (`bun run verify:android`). Not used by consuming apps. +org.gradle.jvmargs=-Xmx1536m +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7705927 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/proguard-rules.pro b/android/proguard-rules.pro index cdd2f94..0d44886 100644 --- a/android/proguard-rules.pro +++ b/android/proguard-rules.pro @@ -12,4 +12,4 @@ -dontwarn com.iab.omid.** -keep class com.iab.omid.** {*;} -keepattributes JavascriptInterface --keep class com.voxgames.capacitor.levelplay.** { *; } +-keep class fyi.crt.capacitor.levelplay.** { *; } diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..1c79088 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,4 @@ +// Standalone build of the plugin library, used by `bun run verify:android` (needs `bun install` first). +// Consuming apps do not use this file: `npx cap sync` includes the module from their own settings. +include ':capacitor-android' +project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor') diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/BannerManager.java b/android/src/main/java/fyi/crt/capacitor/levelplay/BannerManager.java new file mode 100644 index 0000000..3bd2617 --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/BannerManager.java @@ -0,0 +1,405 @@ +package fyi.crt.capacitor.levelplay; + +import android.app.Activity; +import android.os.Handler; +import android.os.Looper; +import android.view.View; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import com.getcapacitor.JSObject; +import com.unity3d.mediation.LevelPlayAdError; +import com.unity3d.mediation.LevelPlayAdInfo; +import com.unity3d.mediation.LevelPlayAdSize; +import com.unity3d.mediation.banner.LevelPlayBannerAdView; +import com.unity3d.mediation.banner.LevelPlayBannerAdViewListener; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Banners (design §3, §6): LevelPlayBannerAdView instances keyed by bannerId, laid out in the OverlayHost. + * Main thread only; SDK callbacks are re-posted to the main thread. + */ +final class BannerManager { + + interface Host { + @Nullable + Activity activity(); + + /** The overlay, attached on first use; null when the WebView has no parent. */ + @Nullable + OverlayHost overlay(); + + boolean initialized(); + + void emit(String event, JSObject data); + + com.unity3d.mediation.impression.LevelPlayImpressionDataListener impressionListener(); + } + + /** Owner decision Q4: adaptive banners follow safe-area width changes after the layout settled. */ + private static final long ADAPTIVE_RECREATE_DELAY_MS = 250; + + private final Host host; + private final Handler main = new Handler(Looper.getMainLooper()); + private final Map slots = new LinkedHashMap<>(); + private final Runnable adaptiveCheck = this::recreateChangedAdaptive; + + BannerManager(Host host) { + this.host = host; + } + + private static final class Slot { + + final String bannerId; + final String adUnitId; + final String size; + @Nullable + final Integer fixedAdaptiveWidth; + final int customWidth; + final int customHeight; + @Nullable + final String placementName; + @Nullable + final Double bidFloor; + String position = "bottom"; + double offsetX; + double offsetY; + boolean respectSafeArea = true; + + LevelPlayBannerAdView view; + LevelPlayAdSize adSize; + /** CSS px width the adaptive size was computed for. */ + int adaptiveWidthUsed; + boolean visible; + boolean loadRequested; + double[] frame = OverlayMath.rect(0, 0, 0, 0); + + Slot( + String bannerId, + String adUnitId, + String size, + @Nullable Integer fixedAdaptiveWidth, + int customWidth, + int customHeight, + @Nullable String placementName, + @Nullable Double bidFloor + ) { + this.bannerId = bannerId; + this.adUnitId = adUnitId; + this.size = size; + this.fixedAdaptiveWidth = fixedAdaptiveWidth; + this.customWidth = customWidth; + this.customHeight = customHeight; + this.placementName = placementName; + this.bidFloor = bidFloor; + } + } + + // ---------------------------------------------------------------------------------------------- API + + JSObject create(JSObject o) throws CallError { + String adUnitId = o.getString("adUnitId"); + if (adUnitId == null || adUnitId.isEmpty()) throw CallError.invalid("adUnitId is required"); + String bannerId = nonEmpty(o.getString("bannerId"), adUnitId); + JSObject custom = o.getJSObject("customSize"); + String size = o.getString("size"); + if (size == null) size = custom != null ? "CUSTOM" : "ADAPTIVE"; + if (!OverlayMath.isBannerSize(size)) throw CallError.invalid("Unknown banner size '" + size + "'"); + int cw = 0, ch = 0; + if ("CUSTOM".equals(size)) { + if (custom == null) throw CallError.invalid("size CUSTOM needs customSize { width, height }"); + cw = positiveInt(custom, "customSize.width", "width"); + ch = positiveInt(custom, "customSize.height", "height"); + } + Integer fixedWidth = null; + if (o.has("adaptiveWidth") && !o.isNull("adaptiveWidth")) { + fixedWidth = positiveInt(o, "adaptiveWidth", "adaptiveWidth"); + } + Double bidFloor = null; + if (o.has("bidFloor") && !o.isNull("bidFloor")) { + Object v = o.opt("bidFloor"); + if (!(v instanceof Number) || ((Number) v).doubleValue() < 0) throw CallError.invalid("bidFloor must be a number >= 0"); + bidFloor = ((Number) v).doubleValue(); + } + String placement = o.getString("placementName"); + if (placement != null && placement.isEmpty()) placement = null; + + Slot s = new Slot(bannerId, adUnitId, size, fixedWidth, cw, ch, placement, bidFloor); + applyLayout(s, o); + + if (!host.initialized()) throw new CallError("NOT_INITIALIZED", "Call initialize() and wait for it before createBanner()"); + if (slots.containsKey(bannerId)) throw new CallError("ALREADY_EXISTS", "Banner '" + bannerId + "' already exists; destroy it first"); + Activity activity = host.activity(); + if (activity == null) throw new CallError("NO_ACTIVITY", "No activity to attach the banner to"); + OverlayHost overlay = host.overlay(); + if (overlay == null) throw new CallError("NO_ACTIVITY", "The WebView is not attached to a view hierarchy"); + + buildView(s, activity, overlay); + slots.put(bannerId, s); + relayout(s, overlay); + return result(s); + } + + void load(String bannerId) throws CallError { + Slot s = require(bannerId); + s.loadRequested = true; + s.view.loadAd(); + } + + JSObject show(String bannerId) throws CallError { + Slot s = require(bannerId); + OverlayHost overlay = host.overlay(); + s.visible = true; + s.view.setVisibility(View.VISIBLE); + s.view.bringToFront(); + s.view.resumeAutoRefresh(); + if (overlay != null) relayout(s, overlay); + return result(s); + } + + void hide(String bannerId) { + Slot s = slots.get(bannerId); + if (s == null) return; + s.visible = false; + s.view.setVisibility(View.GONE); + s.view.pauseAutoRefresh(); + } + + JSObject setLayout(JSObject o) throws CallError { + Slot s = require(o.getString("bannerId")); + applyLayout(s, o); + OverlayHost overlay = host.overlay(); + if (overlay != null) relayout(s, overlay); + return result(s); + } + + void destroy(String bannerId) { + Slot s = slots.remove(bannerId); + if (s != null) destroyView(s); + } + + void destroyAll() { + main.removeCallbacks(adaptiveCheck); + for (Slot s : new ArrayList<>(slots.values())) destroyView(s); + slots.clear(); + } + + boolean isEmpty() { + return slots.isEmpty(); + } + + /** Overlay layout pass: re-place every banner and schedule the adaptive width check (Q4). */ + void onLayoutChanged(OverlayHost overlay) { + boolean adaptiveChanged = false; + for (Slot s : slots.values()) { + relayout(s, overlay); + if (followsWidth(s) && currentAdaptiveWidth(s, overlay) != s.adaptiveWidthUsed) adaptiveChanged = true; + } + main.removeCallbacks(adaptiveCheck); + if (adaptiveChanged) main.postDelayed(adaptiveCheck, ADAPTIVE_RECREATE_DELAY_MS); + } + + // ---------------------------------------------------------------------------------------------- internals + + private Slot require(@Nullable String bannerId) throws CallError { + if (bannerId == null || bannerId.isEmpty()) throw CallError.invalid("bannerId is required"); + Slot s = slots.get(bannerId); + if (s == null) throw CallError.notFound("Banner", bannerId); + return s; + } + + private static void applyLayout(Slot s, JSObject o) throws CallError { + if (o.has("position") && !o.isNull("position")) { + String p = o.getString("position"); + if (!OverlayMath.isPosition(p)) throw CallError.invalid("position must be 'top', 'bottom' or 'center'"); + s.position = p; + } + if (o.has("offsetX") && !o.isNull("offsetX")) s.offsetX = finite(o, "offsetX"); + if (o.has("offsetY") && !o.isNull("offsetY")) s.offsetY = finite(o, "offsetY"); + if (o.has("respectSafeArea") && !o.isNull("respectSafeArea")) { + Object v = o.opt("respectSafeArea"); + if (!(v instanceof Boolean)) throw CallError.invalid("respectSafeArea must be a boolean"); + s.respectSafeArea = (Boolean) v; + } + } + + private static double finite(JSObject o, String key) throws CallError { + Object v = o.opt(key); + if (!(v instanceof Number)) throw CallError.invalid(key + " must be a number"); + double d = ((Number) v).doubleValue(); + if (Double.isNaN(d) || Double.isInfinite(d)) throw CallError.invalid(key + " must be finite"); + return d; + } + + private static int positiveInt(JSObject o, String label, String key) throws CallError { + Object v = o.opt(key); + if (!(v instanceof Number)) throw CallError.invalid(label + " must be a positive number"); + double d = ((Number) v).doubleValue(); + if (!(d >= 1) || Double.isInfinite(d)) throw CallError.invalid(label + " must be a positive number"); + return (int) Math.round(d); + } + + private static String nonEmpty(@Nullable String v, String fallback) { + return v == null || v.isEmpty() ? fallback : v; + } + + private static boolean followsWidth(Slot s) { + return "ADAPTIVE".equals(s.size) && s.fixedAdaptiveWidth == null; + } + + private static double[] area(Slot s, OverlayHost overlay) { + return s.respectSafeArea ? overlay.safeAreaCss() : overlay.webViewCss(); + } + + private static int currentAdaptiveWidth(Slot s, OverlayHost overlay) { + return (int) Math.floor(area(s, overlay)[2]); + } + + @Nullable + private LevelPlayAdSize resolveSize(Slot s, Activity activity, OverlayHost overlay) { + switch (s.size) { + case "BANNER": + return LevelPlayAdSize.BANNER; + case "LARGE": + return LevelPlayAdSize.LARGE; + case "MEDIUM_RECTANGLE": + return LevelPlayAdSize.MEDIUM_RECTANGLE; + case "LEADERBOARD": + return LevelPlayAdSize.LEADERBOARD; + case "CUSTOM": + return LevelPlayAdSize.createCustomSize(s.customWidth, s.customHeight); + default: { + // The SDK width unit is dp (bytecode of createAdaptiveAdSize, design §3.2), i.e. CSS px. + int width = s.fixedAdaptiveWidth != null ? s.fixedAdaptiveWidth : currentAdaptiveWidth(s, overlay); + s.adaptiveWidthUsed = width; + return LevelPlayAdSize.createAdaptiveAdSize(activity, width > 0 ? width : null); + } + } + } + + private void buildView(Slot s, Activity activity, OverlayHost overlay) throws CallError { + LevelPlayAdSize size = resolveSize(s, activity, overlay); + if (size == null) throw new CallError("NOT_INITIALIZED", "The SDK returned no adaptive size (initialize() not finished)"); + LevelPlayBannerAdView.Config.Builder b = new LevelPlayBannerAdView.Config.Builder().setAdSize(size); + if (s.bidFloor != null) b.setBidFloor(s.bidFloor); + if (s.placementName != null) b.setPlacementName(s.placementName); + LevelPlayBannerAdView v = new LevelPlayBannerAdView(activity, s.adUnitId, b.build()); + v.setBannerListener(new Listener(s, v)); + v.setImpressionDataListener(host.impressionListener()); + v.setVisibility(s.visible ? View.VISIBLE : View.GONE); + s.view = v; + s.adSize = size; + overlay.add(v); + } + + private void relayout(Slot s, OverlayHost overlay) { + s.frame = OverlayMath.bannerFrame(area(s, overlay), s.adSize.getWidth(), s.adSize.getHeight(), s.position, s.offsetX, s.offsetY); + overlay.place(s.view, s.frame); + } + + private void destroyView(Slot s) { + OverlayHost overlay = host.overlay(); + s.view.destroy(); + if (overlay != null) overlay.remove(s.view); + } + + /** Q4: recreate adaptive banners whose safe-area width changed; keeps id, layout, visibility; reloads if loaded. */ + private void recreateChangedAdaptive() { + Activity activity = host.activity(); + OverlayHost overlay = host.overlay(); + if (activity == null || overlay == null) return; + for (Slot s : slots.values()) { + if (!followsWidth(s) || currentAdaptiveWidth(s, overlay) == s.adaptiveWidthUsed) continue; + if (currentAdaptiveWidth(s, overlay) <= 0) continue; + destroyView(s); + try { + buildView(s, activity, overlay); + } catch (CallError e) { + continue; + } + relayout(s, overlay); + if (s.loadRequested) s.view.loadAd(); + if (!s.visible) s.view.pauseAutoRefresh(); + } + } + + private JSObject result(Slot s) { + JSObject r = new JSObject(); + r.put("bannerId", s.bannerId); + r.put("adSize", Mappers.adSize(s.adSize)); + r.put("frame", Mappers.rect(s.frame)); + r.put("visible", s.visible); + return r; + } + + private JSObject event(Slot s, @Nullable LevelPlayAdInfo info) { + JSObject o = new JSObject(); + o.put("bannerId", s.bannerId); + o.put("adUnitId", s.adUnitId); + if (info != null) o.put("adInfo", Mappers.adInfo(info)); + o.put("frame", Mappers.rect(s.frame)); + return o; + } + + /** One listener per view: callbacks of a view that was replaced (Q4) or destroyed are dropped. */ + private final class Listener implements LevelPlayBannerAdViewListener { + + private final Slot slot; + private final LevelPlayBannerAdView view; + + Listener(Slot slot, LevelPlayBannerAdView view) { + this.slot = slot; + this.view = view; + } + + private void post(String name, @Nullable LevelPlayAdInfo info, @Nullable LevelPlayAdError error) { + main.post(() -> { + if (slot.view != view || slots.get(slot.bannerId) != slot) return; + JSObject o = event(slot, info); + if (error != null) o.put("error", Mappers.error(error.getErrorCode(), error.getErrorMessage())); + host.emit(name, o); + }); + } + + @Override + public void onAdLoaded(@NonNull LevelPlayAdInfo adInfo) { + post("bannerLoaded", adInfo, null); + } + + @Override + public void onAdLoadFailed(@NonNull LevelPlayAdError error) { + post("bannerLoadFailed", null, error); + } + + @Override + public void onAdDisplayed(@NonNull LevelPlayAdInfo adInfo) { + post("bannerDisplayed", adInfo, null); + } + + @Override + public void onAdDisplayFailed(@NonNull LevelPlayAdInfo adInfo, @NonNull LevelPlayAdError error) { + post("bannerDisplayFailed", adInfo, error); + } + + @Override + public void onAdClicked(@NonNull LevelPlayAdInfo adInfo) { + post("bannerClicked", adInfo, null); + } + + @Override + public void onAdExpanded(@NonNull LevelPlayAdInfo adInfo) { + post("bannerExpanded", adInfo, null); + } + + @Override + public void onAdCollapsed(@NonNull LevelPlayAdInfo adInfo) { + post("bannerCollapsed", adInfo, null); + } + + @Override + public void onAdLeftApplication(@NonNull LevelPlayAdInfo adInfo) { + post("bannerLeftApplication", adInfo, null); + } + } +} diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/CallError.java b/android/src/main/java/fyi/crt/capacitor/levelplay/CallError.java new file mode 100644 index 0000000..bb1205c --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/CallError.java @@ -0,0 +1,20 @@ +package fyi.crt.capacitor.levelplay; + +/** A promise rejection with one of the plugin's string codes (INVALID_ARGUMENT, NOT_FOUND ...). */ +final class CallError extends Exception { + + final String code; + + CallError(String code, String message) { + super(message); + this.code = code; + } + + static CallError invalid(String message) { + return new CallError("INVALID_ARGUMENT", message); + } + + static CallError notFound(String what, String id) { + return new CallError("NOT_FOUND", what + " '" + id + "' not found"); + } +} diff --git a/android/src/main/java/com/voxgames/capacitor/levelplay/LevelPlayPlugin.java b/android/src/main/java/fyi/crt/capacitor/levelplay/LevelPlayPlugin.java similarity index 56% rename from android/src/main/java/com/voxgames/capacitor/levelplay/LevelPlayPlugin.java rename to android/src/main/java/fyi/crt/capacitor/levelplay/LevelPlayPlugin.java index ba47509..051bc9d 100644 --- a/android/src/main/java/com/voxgames/capacitor/levelplay/LevelPlayPlugin.java +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/LevelPlayPlugin.java @@ -1,6 +1,7 @@ -package com.voxgames.capacitor.levelplay; +package fyi.crt.capacitor.levelplay; import android.app.Activity; +import android.content.res.Configuration; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; @@ -18,24 +19,34 @@ import com.unity3d.mediation.LevelPlayInitError; import com.unity3d.mediation.LevelPlayInitListener; import com.unity3d.mediation.LevelPlayInitRequest; import com.unity3d.mediation.LevelPlayPrivacySettings; +import com.unity3d.mediation.impression.LevelPlayImpressionDataListener; import com.unity3d.mediation.interstitial.LevelPlayInterstitialAd; import com.unity3d.mediation.interstitial.LevelPlayInterstitialAdListener; import com.unity3d.mediation.rewarded.LevelPlayReward; import com.unity3d.mediation.rewarded.LevelPlayRewardedAd; import com.unity3d.mediation.rewarded.LevelPlayRewardedAdListener; +import com.unity3d.mediation.segment.LevelPlaySegment; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.json.JSONArray; /** - * Capacitor bridge for the Unity LevelPlay SDK (ad-unit API: LevelPlayRewardedAd / LevelPlayInterstitialAd). - * Rewarded and interstitial only. Every SDK call runs on the main thread; plugin state is only touched there. + * Capacitor bridge for the Unity LevelPlay SDK (ad-unit API: LevelPlayRewardedAd / LevelPlayInterstitialAd / + * LevelPlayBannerAdView, plus LevelPlayNativeAd). Every SDK call and every view operation runs on the main thread; + * plugin state is only touched there. */ @CapacitorPlugin(name = "LevelPlay") public class LevelPlayPlugin extends Plugin { private static final long LATE_REWARD_GRACE_MS = 1000; + /** Impressions kept while no JS impressionData listener exists (owner decision Q2); the oldest is dropped. */ + static final int IMPRESSION_QUEUE_CAP = 100; + static final String EVENT_IMPRESSION = "impressionData"; private enum InitState { IDLE, @@ -48,6 +59,43 @@ public class LevelPlayPlugin extends Plugin { private final List pendingInits = new ArrayList<>(); private final Map rewarded = new HashMap<>(); private final Map interstitials = new HashMap<>(); + private final ArrayDeque impressionQueue = new ArrayDeque<>(); + @Nullable + private OverlayHost overlay; + private final BannerManager banners = new BannerManager(new BannerManager.Host() { + @Nullable + @Override + public Activity activity() { + return getActivity(); + } + + @Nullable + @Override + public OverlayHost overlay() { + return LevelPlayPlugin.this.overlay(); + } + + @Override + public boolean initialized() { + return initState == InitState.DONE; + } + + @Override + public void emit(String event, JSObject data) { + notifyListeners(event, data); + } + + @Override + public LevelPlayImpressionDataListener impressionListener() { + return impressionListener; + } + }); + + /** Attached to every rewarded, interstitial and banner object (per-ad listeners, owner decision Q1). */ + final LevelPlayImpressionDataListener impressionListener = data -> { + JSObject o = Mappers.impression(data); + main.post(() -> emitImpression(o)); + }; // ---------------------------------------------------------------------------------------------- init / settings @@ -267,6 +315,303 @@ public class LevelPlayPlugin extends Plugin { }); } + // ---------------------------------------------------------------------------------------------- 0.3.0: capabilities, user + + @PluginMethod + public void getCapabilities(PluginCall call) { + JSObject r = new JSObject(); + r.put("banner", true); + r.put("nativeAd", true); + r.put("nativeAdTemplates", new JSONArray().put("small").put("medium")); + r.put("impressionData", true); + r.put("adInfoChanged", true); + call.resolve(r); + } + + @PluginMethod + public void setSegment(PluginCall call) { + JSObject o = call.getData(); + LevelPlaySegment segment = new LevelPlaySegment(); + try { + String name = o.getString("segmentName"); + if (name != null) segment.setSegmentName(name); + Number level = number(o, "level"); + if (level != null) { + if (level.doubleValue() != Math.rint(level.doubleValue())) throw CallError.invalid("level must be an integer"); + segment.setLevel(level.intValue()); + } + if (o.has("isPaying")) { + Object paying = o.opt("isPaying"); + if (!(paying instanceof Boolean)) throw CallError.invalid("isPaying must be a boolean"); + segment.setPaying((Boolean) paying); + } + Number created = number(o, "userCreationDate"); + if (created != null) segment.setUserCreationDate(created.longValue()); + Number iap = number(o, "iapTotal"); + if (iap != null) segment.setIapTotal(iap.doubleValue()); + JSObject custom = o.getJSObject("customParameters"); + if (custom == null && o.has("customParameters") && !o.isNull("customParameters")) { + throw CallError.invalid("customParameters must be an object of strings"); + } + if (custom != null) { + Map params = new LinkedHashMap<>(); + Iterator keys = custom.keys(); + while (keys.hasNext()) { + String k = keys.next(); + params.put(k, custom.opt(k)); + } + String err = OverlayMath.customParamsError(params); + if (err != null) throw CallError.invalid(err); + for (Map.Entry e : params.entrySet()) segment.setCustom(e.getKey(), (String) e.getValue()); + } + } catch (CallError e) { + reject(call, e); + return; + } + main.post(() -> { + LevelPlay.setSegment(segment); + call.resolve(); + }); + } + + @Nullable + private static Number number(JSObject o, String key) throws CallError { + if (!o.has(key) || o.isNull(key)) return null; + Object v = o.opt(key); + if (!(v instanceof Number)) throw CallError.invalid(key + " must be a number"); + double d = ((Number) v).doubleValue(); + if (Double.isNaN(d) || Double.isInfinite(d)) throw CallError.invalid(key + " must be finite"); + return (Number) v; + } + + @PluginMethod + public void setDynamicUserId(PluginCall call) { + String userId = call.getString("userId"); + if (userId == null || userId.isEmpty()) { + call.reject("userId is required", "INVALID_ARGUMENT"); + return; + } + main.post(() -> { + JSObject r = new JSObject(); + r.put("valid", LevelPlay.setDynamicUserId(userId)); + call.resolve(r); + }); + } + + @PluginMethod + public void isPlacementCapped(PluginCall call) { + String format = call.getString("format"); + String placement = call.getString("placementName"); + if (!"rewarded".equals(format) && !"interstitial".equals(format)) { + call.reject("format must be 'rewarded' or 'interstitial'", "INVALID_ARGUMENT"); + return; + } + if (placement == null || placement.isEmpty()) { + call.reject("placementName is required", "INVALID_ARGUMENT"); + return; + } + main.post(() -> { + boolean capped = "interstitial".equals(format) + ? LevelPlayInterstitialAd.isPlacementCapped(placement) + : LevelPlayRewardedAd.isPlacementCapped(placement); + JSObject r = new JSObject(); + r.put("capped", capped); + call.resolve(r); + }); + } + + @PluginMethod + public void getReward(PluginCall call) { + String adUnitId = requireAdUnit(call); + if (adUnitId == null) return; + String placement = call.getString("placementName"); + main.post(() -> { + LevelPlayRewardedAd ad = rewardedHolder(adUnitId).ad; + LevelPlayReward r = placement != null && !placement.isEmpty() ? ad.getReward(placement) : ad.getReward(); + call.resolve(Mappers.reward(r)); + }); + } + + // ---------------------------------------------------------------------------------------------- 0.3.0: banners + + @PluginMethod + public void createBanner(PluginCall call) { + JSObject o = call.getData(); + onMain(call, () -> call.resolve(banners.create(o))); + } + + @PluginMethod + public void loadBanner(PluginCall call) { + String id = call.getString("bannerId"); + onMain(call, () -> { + banners.load(id); + call.resolve(); + }); + } + + @PluginMethod + public void showBanner(PluginCall call) { + String id = call.getString("bannerId"); + onMain(call, () -> call.resolve(banners.show(id))); + } + + @PluginMethod + public void hideBanner(PluginCall call) { + String id = call.getString("bannerId"); + onMain(call, () -> { + banners.hide(id); + call.resolve(); + }); + } + + @PluginMethod + public void setBannerLayout(PluginCall call) { + JSObject o = call.getData(); + onMain(call, () -> call.resolve(banners.setLayout(o))); + } + + @PluginMethod + public void destroyBanner(PluginCall call) { + String id = call.getString("bannerId"); + onMain(call, () -> { + banners.destroy(id); + call.resolve(); + }); + } + + // ---------------------------------------------------------------------------------------------- 0.3.0: native ads + + private final NativeAdManager nativeAds = new NativeAdManager(new NativeAdManager.Host() { + @Nullable + @Override + public Activity activity() { + return getActivity(); + } + + @Nullable + @Override + public OverlayHost overlay() { + return LevelPlayPlugin.this.overlay(); + } + + @Override + public boolean initialized() { + return initState == InitState.DONE; + } + + @Override + public void emit(String event, JSObject data) { + notifyListeners(event, data); + } + + @Override + public void impression(JSObject data) { + emitImpression(data); + } + }); + + @PluginMethod + public void loadNativeAd(PluginCall call) { + JSObject o = call.getData(); + onMain(call, () -> { + nativeAds.load(o); + call.resolve(); + }); + } + + @PluginMethod + public void showNativeAd(PluginCall call) { + String id = call.getString("nativeAdId"); + JSObject rect = call.getObject("rect"); + onMain(call, () -> { + nativeAds.show(id, rect); + call.resolve(); + }); + } + + @PluginMethod + public void setNativeAdRect(PluginCall call) { + String id = call.getString("nativeAdId"); + JSObject rect = call.getObject("rect"); + onMain(call, () -> { + nativeAds.setRect(id, rect); + call.resolve(); + }); + } + + @PluginMethod + public void hideNativeAd(PluginCall call) { + String id = call.getString("nativeAdId"); + onMain(call, () -> { + nativeAds.hide(id); + call.resolve(); + }); + } + + @PluginMethod + public void destroyNativeAd(PluginCall call) { + String id = call.getString("nativeAdId"); + onMain(call, () -> { + nativeAds.destroy(id); + call.resolve(); + }); + } + + // ---------------------------------------------------------------------------------------------- overlay, lifecycle + + /** Main thread. The pass-through overlay above the WebView, attached on first use (design §6.2). */ + @Nullable + private OverlayHost overlay() { + if (overlay == null && bridge != null) overlay = OverlayHost.attach(bridge.getWebView(), this::onOverlayLayoutChanged); + return overlay; + } + + private void onOverlayLayoutChanged() { + if (overlay == null) return; + banners.onLayoutChanged(overlay); + nativeAds.onLayoutChanged(overlay); + } + + @Override + protected void handleOnConfigurationChanged(Configuration newConfig) { + super.handleOnConfigurationChanged(newConfig); + main.post(() -> { + if (overlay != null) overlay.postRelayout(); + }); + } + + @Override + protected void handleOnDestroy() { + super.handleOnDestroy(); + Runnable cleanup = () -> { + banners.destroyAll(); + nativeAds.destroyAll(); + if (overlay != null) { + overlay.detach(); + overlay = null; + } + }; + if (Looper.myLooper() == Looper.getMainLooper()) cleanup.run(); + else main.post(cleanup); + } + + private interface MainTask { + void run() throws CallError; + } + + /** Runs on the main thread; a CallError rejects the call with its code. */ + private void onMain(PluginCall call, MainTask task) { + main.post(() -> { + try { + task.run(); + } catch (CallError e) { + reject(call, e); + } catch (RuntimeException e) { + call.reject(e.getMessage() != null ? e.getMessage() : e.toString(), "ERROR", e); + } + }); + } + // ---------------------------------------------------------------------------------------------- helpers @Nullable @@ -297,35 +642,45 @@ public class LevelPlayPlugin extends Plugin { } private static JSObject info(@Nullable LevelPlayAdInfo i) { - JSObject o = new JSObject(); - if (i == null) return o; - o.put("adId", i.getAdId()); - o.put("adUnitId", i.getAdUnitId()); - o.put("adUnitName", i.getAdUnitName()); - o.put("adFormat", i.getAdFormat()); - o.put("placementName", i.getPlacementName()); - o.put("adNetwork", i.getAdNetwork()); - o.put("instanceName", i.getInstanceName()); - o.put("instanceId", i.getInstanceId()); - o.put("country", i.getCountry()); - o.put("auctionId", i.getAuctionId()); - o.put("precision", i.getPrecision()); - o.put("revenue", i.getRevenue()); - return o; + return Mappers.adInfo(i); } private static JSObject error(int code, String message) { - JSObject e = new JSObject(); - e.put("code", code); - e.put("message", message); - return e; + return Mappers.error(code, message); } private static JSObject reward(LevelPlayReward r) { - JSObject o = new JSObject(); - o.put("name", r.getName()); - o.put("amount", r.getAmount()); - return o; + return Mappers.reward(r); + } + + static void reject(PluginCall call, CallError e) { + call.reject(e.getMessage(), e.code); + } + + // ---------------------------------------------------------------------------------------------- impression data + + /** Main thread. Sends directly when a JS listener exists, otherwise queues (capped). */ + private void emitImpression(JSObject o) { + if (hasListeners(EVENT_IMPRESSION)) { + notifyListeners(EVENT_IMPRESSION, o); + return; + } + impressionQueue.addLast(o); + while (impressionQueue.size() > IMPRESSION_QUEUE_CAP) impressionQueue.removeFirst(); + } + + private void flushImpressions() { + while (!impressionQueue.isEmpty() && hasListeners(EVENT_IMPRESSION)) { + notifyListeners(EVENT_IMPRESSION, impressionQueue.removeFirst()); + } + } + + /** Same as Plugin.addListener, then flushes impressions queued before the first impressionData listener. */ + @Override + @PluginMethod(returnType = PluginMethod.RETURN_NONE) + public void addListener(PluginCall call) { + super.addListener(call); + if (EVENT_IMPRESSION.equals(call.getString("eventName"))) main.post(this::flushImpressions); } private JSObject event(String format, String adUnitId, @Nullable LevelPlayAdInfo adInfo) { @@ -351,6 +706,7 @@ public class LevelPlayPlugin extends Plugin { this.adUnitId = adUnitId; this.ad = new LevelPlayRewardedAd(adUnitId); this.ad.setListener(this); + this.ad.setImpressionDataListener(impressionListener); } void begin(PluginCall c) { @@ -436,7 +792,9 @@ public class LevelPlayPlugin extends Plugin { } @Override - public void onAdInfoChanged(@NonNull LevelPlayAdInfo adInfo) {} + public void onAdInfoChanged(@NonNull LevelPlayAdInfo adInfo) { + main.post(() -> notifyListeners("adInfoChanged", event("rewarded", adUnitId, adInfo))); + } } private final class InterstitialHolder implements LevelPlayInterstitialAdListener { @@ -451,6 +809,7 @@ public class LevelPlayPlugin extends Plugin { this.adUnitId = adUnitId; this.ad = new LevelPlayInterstitialAd(adUnitId); this.ad.setListener(this); + this.ad.setImpressionDataListener(impressionListener); } void begin(PluginCall c) { @@ -520,6 +879,8 @@ public class LevelPlayPlugin extends Plugin { } @Override - public void onAdInfoChanged(@NonNull LevelPlayAdInfo adInfo) {} + public void onAdInfoChanged(@NonNull LevelPlayAdInfo adInfo) { + main.post(() -> notifyListeners("adInfoChanged", event("interstitial", adUnitId, adInfo))); + } } } diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/Mappers.java b/android/src/main/java/fyi/crt/capacitor/levelplay/Mappers.java new file mode 100644 index 0000000..3a792d3 --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/Mappers.java @@ -0,0 +1,117 @@ +package fyi.crt.capacitor.levelplay; + +import androidx.annotation.Nullable; +import com.getcapacitor.JSObject; +import com.ironsource.mediationsdk.adunit.adapter.utility.AdInfo; +import com.unity3d.mediation.LevelPlayAdInfo; +import com.unity3d.mediation.LevelPlayAdSize; +import com.unity3d.mediation.impression.LevelPlayImpressionData; +import com.unity3d.mediation.rewarded.LevelPlayReward; + +/** SDK objects to the JSON shapes of src/definitions.ts. Null SDK values are omitted (JSONObject.put(k, null) removes k). */ +final class Mappers { + + private Mappers() {} + + static JSObject adInfo(@Nullable LevelPlayAdInfo i) { + JSObject o = new JSObject(); + if (i == null) return o; + o.put("adId", i.getAdId()); + o.put("adUnitId", i.getAdUnitId()); + o.put("adUnitName", i.getAdUnitName()); + o.put("adFormat", i.getAdFormat()); + o.put("placementName", i.getPlacementName()); + o.put("adNetwork", i.getAdNetwork()); + o.put("instanceName", i.getInstanceName()); + o.put("instanceId", i.getInstanceId()); + o.put("country", i.getCountry()); + o.put("auctionId", i.getAuctionId()); + o.put("precision", i.getPrecision()); + o.put("revenue", i.getRevenue()); + o.put("ab", i.getAb()); + o.put("segmentName", i.getSegmentName()); + o.put("encryptedCPM", i.getEncryptedCPM()); + o.put("creativeId", i.getCreativeId()); + LevelPlayAdSize size = i.getAdSize(); + if (size != null) o.put("adSize", adSize(size)); + return o; + } + + static JSObject adSize(LevelPlayAdSize s) { + JSObject o = new JSObject(); + o.put("width", s.getWidth()); + o.put("height", s.getHeight()); + o.put("description", s.getDescription()); + o.put("isAdaptive", s.isAdaptive()); + return o; + } + + static JSObject impression(LevelPlayImpressionData d) { + JSObject o = new JSObject(); + o.put("adFormat", d.getAdFormat()); + o.put("auctionId", d.getAuctionId()); + o.put("adUnitId", d.getMediationAdUnitId()); + o.put("adUnitName", d.getMediationAdUnitName()); + o.put("adNetwork", d.getAdNetwork()); + o.put("instanceName", d.getInstanceName()); + o.put("instanceId", d.getInstanceId()); + o.put("country", d.getCountry()); + o.put("placement", d.getPlacement()); + Double revenue = d.getRevenue(); + if (revenue != null) o.put("revenue", revenue.doubleValue()); + o.put("precision", d.getPrecision()); + o.put("ab", d.getAb()); + o.put("segmentName", d.getSegmentName()); + o.put("encryptedCPM", d.getEncryptedCPM()); + o.put("creativeId", d.getCreativeId()); + if (d.getAllData() != null) o.put("allData", d.getAllData()); + return o; + } + + /** Native ads use the older ironSource AdInfo (no ad unit, ad id or placement). */ + static JSObject nativeAdInfo(@Nullable AdInfo i) { + JSObject o = new JSObject(); + if (i == null) return o; + o.put("auctionId", i.getAuctionId()); + o.put("adNetwork", i.getAdNetwork()); + o.put("instanceName", i.getInstanceName()); + o.put("instanceId", i.getInstanceId()); + o.put("country", i.getCountry()); + o.put("revenue", i.getRevenue()); + o.put("precision", i.getPrecision()); + o.put("ab", i.getAb()); + o.put("segmentName", i.getSegmentName()); + o.put("encryptedCPM", i.getEncryptedCPM()); + return o; + } + + /** impressionData synthesised from a native ad impression (no per-ad impression listener for native ads in 9.6.1). */ + static JSObject nativeImpression(@Nullable AdInfo i) { + JSObject o = nativeAdInfo(i); + o.put("adFormat", "nativead"); + return o; + } + + static JSObject error(int code, @Nullable String message) { + JSObject e = new JSObject(); + e.put("code", code); + e.put("message", message != null ? message : ""); + return e; + } + + static JSObject reward(@Nullable LevelPlayReward r) { + JSObject o = new JSObject(); + o.put("name", r != null && r.getName() != null ? r.getName() : ""); + o.put("amount", r != null ? r.getAmount() : 0); + return o; + } + + static JSObject rect(double[] r) { + JSObject o = new JSObject(); + o.put("x", r[0]); + o.put("y", r[1]); + o.put("width", r[2]); + o.put("height", r[3]); + return o; + } +} diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdManager.java b/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdManager.java new file mode 100644 index 0000000..1542f62 --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdManager.java @@ -0,0 +1,254 @@ +package fyi.crt.capacitor.levelplay; + +import android.app.Activity; +import android.os.Handler; +import android.os.Looper; +import android.view.View; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import com.getcapacitor.JSObject; +import com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAd; +import com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAdListener; +import com.ironsource.mediationsdk.ads.nativead.NativeAdLayout; +import com.ironsource.mediationsdk.adunit.adapter.utility.AdInfo; +import com.ironsource.mediationsdk.logger.IronSourceError; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Native ads (design §4): one LevelPlayNativeAd per load and slot, rendered into the plugin's templates and placed in + * the OverlayHost at a WebView-local CSS rect. Main thread only; SDK callbacks are re-posted to the main thread. + */ +final class NativeAdManager { + + interface Host { + @Nullable + Activity activity(); + + @Nullable + OverlayHost overlay(); + + boolean initialized(); + + void emit(String event, JSObject data); + + /** impressionData synthesised from the native ad info (no per-ad impression listener for native ads). */ + void impression(JSObject data); + } + + private final Host host; + private final Handler main = new Handler(Looper.getMainLooper()); + private final Map slots = new LinkedHashMap<>(); + + NativeAdManager(Host host) { + this.host = host; + } + + private static final class Slot { + + final String id; + @Nullable + final String placementName; + final String template; + final NativeAdStyle style; + @Nullable + LevelPlayNativeAd ad; + boolean loaded; + @Nullable + NativeAdLayout view; + @Nullable + double[] rect; + boolean visible; + + Slot(String id, @Nullable String placementName, String template, NativeAdStyle style) { + this.id = id; + this.placementName = placementName; + this.template = template; + this.style = style; + } + } + + // ---------------------------------------------------------------------------------------------- API + + void load(JSObject o) throws CallError { + String id = requireId(o.getString("nativeAdId")); + String template = o.getString("template", "medium"); + if (!"small".equals(template) && !"medium".equals(template)) { + throw new CallError("UNSUPPORTED", "Template '" + template + "' is not supported (small, medium)"); + } + NativeAdStyle style = NativeAdStyle.parse(o.getJSObject("style")); + String placement = o.getString("placementName"); + if (placement != null && placement.isEmpty()) placement = null; + if (!host.initialized()) throw new CallError("NOT_INITIALIZED", "Call initialize() and wait for it before loadNativeAd()"); + Activity activity = host.activity(); + if (activity == null) throw new CallError("NO_ACTIVITY", "No activity to load the native ad with"); + + // "Destroy the ad object and create a new one for every new load" (Unity). + Slot old = slots.remove(id); + if (old != null) destroySlot(old); + + Slot s = new Slot(id, placement, template, style); + LevelPlayNativeAd.Builder b = new LevelPlayNativeAd.Builder().withActivity(activity).withListener(new Listener(s)); + if (placement != null) b.withPlacementName(placement); + s.ad = b.build(); + slots.put(id, s); + s.ad.loadAd(); + } + + void show(String nativeAdId, @Nullable JSObject rect) throws CallError { + Slot s = require(nativeAdId); + double[] r = parseRect(rect); + if (!s.loaded || s.ad == null) throw new CallError("NOT_LOADED", "Native ad '" + nativeAdId + "' is not loaded"); + OverlayHost overlay = host.overlay(); + Activity activity = host.activity(); + if (overlay == null || activity == null) throw new CallError("NO_ACTIVITY", "No activity / WebView to show the native ad in"); + if (s.view == null) { + s.view = NativeAdTemplate.build(activity, s.template, s.style, s.ad); + s.view.setVisibility(View.GONE); + overlay.add(s.view); + } + s.rect = r; + s.visible = true; + place(s, overlay); + s.view.setVisibility(View.VISIBLE); + s.view.bringToFront(); + } + + void setRect(String nativeAdId, @Nullable JSObject rect) throws CallError { + Slot s = require(nativeAdId); + s.rect = parseRect(rect); + OverlayHost overlay = host.overlay(); + if (overlay != null && s.view != null) place(s, overlay); + } + + void hide(String nativeAdId) throws CallError { + Slot s = require(nativeAdId); + s.visible = false; + if (s.view != null) s.view.setVisibility(View.GONE); + } + + void destroy(@Nullable String nativeAdId) { + if (nativeAdId == null) return; + Slot s = slots.remove(nativeAdId); + if (s != null) destroySlot(s); + } + + void destroyAll() { + for (Slot s : new ArrayList<>(slots.values())) destroySlot(s); + slots.clear(); + } + + void onLayoutChanged(OverlayHost overlay) { + for (Slot s : slots.values()) if (s.view != null && s.rect != null) place(s, overlay); + } + + // ---------------------------------------------------------------------------------------------- internals + + private static String requireId(@Nullable String id) throws CallError { + if (id == null || id.isEmpty()) throw CallError.invalid("nativeAdId is required"); + return id; + } + + private Slot require(@Nullable String id) throws CallError { + Slot s = slots.get(requireId(id)); + if (s == null) throw CallError.notFound("Native ad", id); + return s; + } + + private static double[] parseRect(@Nullable JSObject r) throws CallError { + if (r == null) throw CallError.invalid("rect { x, y, width, height } is required"); + double[] out = new double[4]; + String[] keys = { "x", "y", "width", "height" }; + for (int i = 0; i < 4; i++) { + Object v = r.opt(keys[i]); + if (!(v instanceof Number)) throw CallError.invalid("rect." + keys[i] + " must be a number"); + double d = ((Number) v).doubleValue(); + if (Double.isNaN(d) || Double.isInfinite(d)) throw CallError.invalid("rect." + keys[i] + " must be finite"); + out[i] = d; + } + if (out[2] < 0 || out[3] < 0) throw CallError.invalid("rect width and height must be >= 0"); + return out; + } + + /** Native rects are taken literally (the page laid them out), only clamped to the WebView (design §6.3). */ + private static void place(Slot s, OverlayHost overlay) { + if (s.view == null || s.rect == null) return; + overlay.place(s.view, OverlayMath.intersect(s.rect, overlay.webViewCss())); + } + + private void destroySlot(Slot s) { + if (s.view != null) { + OverlayHost overlay = host.overlay(); + if (overlay != null) overlay.remove(s.view); + s.view = null; + } + if (s.ad != null) { + s.ad.destroyAd(); + s.ad = null; + } + s.loaded = false; + } + + private JSObject event(Slot s, @Nullable AdInfo info) { + JSObject o = new JSObject(); + o.put("nativeAdId", s.id); + if (s.placementName != null) o.put("placementName", s.placementName); + if (info != null) o.put("adInfo", Mappers.nativeAdInfo(info)); + return o; + } + + /** One listener per load; callbacks of an ad object that was replaced or destroyed are dropped. */ + private final class Listener implements LevelPlayNativeAdListener { + + private final Slot slot; + + Listener(Slot slot) { + this.slot = slot; + } + + private boolean current(@Nullable LevelPlayNativeAd ad) { + return slots.get(slot.id) == slot && slot.ad != null && slot.ad == ad; + } + + @Override + public void onAdLoaded(@NonNull LevelPlayNativeAd ad, @NonNull AdInfo adInfo) { + main.post(() -> { + if (!current(ad)) return; + slot.loaded = true; + host.emit("nativeAdLoaded", event(slot, adInfo)); + }); + } + + @Override + public void onAdLoadFailed(@NonNull LevelPlayNativeAd ad, @NonNull IronSourceError error) { + main.post(() -> { + if (!current(ad)) return; + // The failed ad object is destroyed; the slot stays (NOT_LOADED) until the next loadNativeAd(). + slot.ad.destroyAd(); + slot.ad = null; + slot.loaded = false; + JSObject o = event(slot, null); + o.put("error", Mappers.error(error.getErrorCode(), error.getErrorMessage())); + host.emit("nativeAdLoadFailed", o); + }); + } + + @Override + public void onAdImpression(@NonNull LevelPlayNativeAd ad, @NonNull AdInfo adInfo) { + main.post(() -> { + if (!current(ad)) return; + host.emit("nativeAdImpression", event(slot, adInfo)); + host.impression(Mappers.nativeImpression(adInfo)); + }); + } + + @Override + public void onAdClicked(@NonNull LevelPlayNativeAd ad, @NonNull AdInfo adInfo) { + main.post(() -> { + if (!current(ad)) return; + host.emit("nativeAdClicked", event(slot, adInfo)); + }); + } + } +} diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdStyle.java b/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdStyle.java new file mode 100644 index 0000000..828ece8 --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdStyle.java @@ -0,0 +1,75 @@ +package fyi.crt.capacitor.levelplay; + +import androidx.annotation.Nullable; +import com.getcapacitor.JSObject; + +/** Parsed NativeAdTemplateStyle (src/definitions.ts). Colours are ARGB; sizes are CSS px (dp). */ +final class NativeAdStyle { + + static final class Font { + + @Nullable + final String family; + + @Nullable + final Double size; + + Font(@Nullable String family, @Nullable Double size) { + this.family = family; + this.size = size; + } + } + + int backgroundColor = 0xFFFFFFFF; + int titleColor = 0xFF202124; + int bodyColor = 0xFF5F6368; + int callToActionBackgroundColor = 0xFF1A73E8; + int callToActionTextColor = 0xFFFFFFFF; + double cornerRadius = 0; + Font titleFont = new Font(null, null); + Font bodyFont = new Font(null, null); + Font callToActionFont = new Font(null, null); + + static NativeAdStyle parse(@Nullable JSObject o) throws CallError { + NativeAdStyle s = new NativeAdStyle(); + if (o == null) return s; + s.backgroundColor = color(o, "backgroundColor", s.backgroundColor); + s.titleColor = color(o, "titleColor", s.titleColor); + s.bodyColor = color(o, "bodyColor", s.bodyColor); + s.callToActionBackgroundColor = color(o, "callToActionBackgroundColor", s.callToActionBackgroundColor); + s.callToActionTextColor = color(o, "callToActionTextColor", s.callToActionTextColor); + if (o.has("cornerRadius") && !o.isNull("cornerRadius")) { + Object v = o.opt("cornerRadius"); + if (!(v instanceof Number) || !(((Number) v).doubleValue() >= 0)) throw CallError.invalid("style.cornerRadius must be >= 0"); + s.cornerRadius = ((Number) v).doubleValue(); + } + s.titleFont = font(o, "titleFont"); + s.bodyFont = font(o, "bodyFont"); + s.callToActionFont = font(o, "callToActionFont"); + return s; + } + + private static int color(JSObject o, String key, int fallback) throws CallError { + if (!o.has(key) || o.isNull(key)) return fallback; + Integer c = OverlayMath.parseColor(o.optString(key, null)); + if (c == null) throw CallError.invalid("style." + key + " must be #RRGGBB or #RRGGBBAA"); + return c; + } + + private static Font font(JSObject o, String key) throws CallError { + if (!o.has(key) || o.isNull(key)) return new Font(null, null); + JSObject f = o.getJSObject(key); + if (f == null) throw CallError.invalid("style." + key + " must be an object { family?, size? }"); + String family = f.getString("family"); + if (family != null && family.trim().isEmpty()) family = null; + Double size = null; + if (f.has("size") && !f.isNull("size")) { + Object v = f.opt("size"); + if (!(v instanceof Number) || !(((Number) v).doubleValue() > 0) || Double.isInfinite(((Number) v).doubleValue())) { + throw CallError.invalid("style." + key + ".size must be a positive number"); + } + size = ((Number) v).doubleValue(); + } + return new Font(family, size); + } +} diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdTemplate.java b/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdTemplate.java new file mode 100644 index 0000000..6e4f6d9 --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/NativeAdTemplate.java @@ -0,0 +1,328 @@ +package fyi.crt.capacitor.levelplay; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.GradientDrawable; +import android.net.Uri; +import android.os.Handler; +import android.os.Looper; +import android.text.TextUtils; +import android.util.Log; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import androidx.annotation.Nullable; +import com.ironsource.mediationsdk.ads.nativead.LevelPlayMediaView; +import com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAd; +import com.ironsource.mediationsdk.ads.nativead.NativeAdLayout; +import com.ironsource.mediationsdk.ads.nativead.interfaces.NativeAdDataInterface; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * The plugin's own native ad templates (the SDK ships none, design §4.1), built in code so every style value applies + * directly. Both draw an "Ad" badge and keep the bottom-left corner free for the network's privacy / AdChoices icon. + * + * - small: [icon] [title / Ad + advertiser / body] [CTA], one row; fits rows from about 90 px tall. + * - medium: [icon] [title / Ad + advertiser], body, media view (fills the rest), CTA aligned right. + */ +final class NativeAdTemplate { + + private static final String TAG = "LevelPlay"; + private static final int BADGE_BG = 0xFFFFC107; + private static final int BADGE_TEXT = 0xFF202124; + private static final Map ASSET_FONTS = new HashMap<>(); + private static final ExecutorService IO = Executors.newSingleThreadExecutor(); + + private NativeAdTemplate() {} + + /** The template's asset views, created and styled but not filled. */ + static final class Views { + + final NativeAdLayout root; + final TextView title; + final TextView advertiser; + final TextView body; + final ImageView icon; + final Button cta; + + @Nullable + final LevelPlayMediaView media; + + Views(NativeAdLayout root, TextView title, TextView advertiser, TextView body, ImageView icon, Button cta, @Nullable LevelPlayMediaView media) { + this.root = root; + this.title = title; + this.advertiser = advertiser; + this.body = body; + this.icon = icon; + this.cta = cta; + this.media = media; + } + } + + /** Renders a loaded ad: create, fill from the ad's assets, hand the views to the SDK and register them. */ + static NativeAdLayout build(Context ctx, String template, NativeAdStyle style, LevelPlayNativeAd ad) { + Views v = create(ctx, template, style); + fill(v, ad.getTitle(), ad.getAdvertiser(), ad.getBody(), ad.getCallToAction(), ad.getIcon()); + v.root.setTitleView(v.title); + v.root.setAdvertiserView(v.advertiser); + v.root.setBodyView(v.body); + v.root.setIconView(v.icon); + v.root.setCallToActionView(v.cta); + if (v.media != null) v.root.setMediaView(v.media); + v.root.registerNativeAdViews(ad); + return v.root; + } + + static Views create(Context ctx, String template, NativeAdStyle style) { + boolean medium = "medium".equals(template); + NativeAdLayout root = new NativeAdLayout(ctx); + GradientDrawable bg = new GradientDrawable(); + bg.setColor(style.backgroundColor); + bg.setCornerRadius(dp(ctx, style.cornerRadius)); + root.setBackground(bg); + root.setClipToOutline(true); + // The template consumes touches inside its bounds so taps between asset views do not reach the game. + root.setClickable(true); + + ImageView icon = new ImageView(ctx); + icon.setScaleType(ImageView.ScaleType.CENTER_CROP); + GradientDrawable iconBg = new GradientDrawable(); + iconBg.setCornerRadius(dp(ctx, 6)); + iconBg.setColor(0x14000000); + icon.setBackground(iconBg); + icon.setClipToOutline(true); + + TextView title = text(ctx, style.titleColor, 15, style.titleFont, true); + title.setMaxLines(medium ? 2 : 1); + + TextView badge = text(ctx, BADGE_TEXT, 10, style.bodyFont, true); + badge.setText(R.string.levelplay_native_ad_badge); + badge.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); + GradientDrawable badgeBg = new GradientDrawable(); + badgeBg.setColor(BADGE_BG); + badgeBg.setCornerRadius(dp(ctx, 3)); + badge.setBackground(badgeBg); + int bp = (int) dp(ctx, 4); + badge.setPadding(bp, 0, bp, 0); + + TextView advertiser = text(ctx, style.bodyColor, 12, style.bodyFont, false); + advertiser.setMaxLines(1); + + TextView body = text(ctx, style.bodyColor, 12, style.bodyFont, false); + body.setMaxLines(2); + + Button cta = new Button(ctx); + cta.setAllCaps(false); + cta.setStateListAnimator(null); + cta.setMinWidth(0); + cta.setMinimumWidth(0); + cta.setMinHeight(0); + cta.setMinimumHeight(0); + cta.setSingleLine(true); + cta.setEllipsize(TextUtils.TruncateAt.END); + cta.setTextColor(style.callToActionTextColor); + applyFont(ctx, cta, style.callToActionFont, 13, true); + GradientDrawable ctaBg = new GradientDrawable(); + ctaBg.setColor(style.callToActionBackgroundColor); + ctaBg.setCornerRadius(dp(ctx, 6)); + cta.setBackground(ctaBg); + int cp = (int) dp(ctx, 12); + cta.setPadding(cp, 0, cp, 0); + cta.setGravity(Gravity.CENTER); + + // Badge + advertiser row. + LinearLayout adRow = new LinearLayout(ctx); + adRow.setOrientation(LinearLayout.HORIZONTAL); + adRow.setGravity(Gravity.CENTER_VERTICAL); + adRow.addView(badge, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + LinearLayout.LayoutParams advLp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1); + advLp.leftMargin = (int) dp(ctx, 6); + adRow.addView(advertiser, advLp); + + LevelPlayMediaView media = null; + int pad = (int) dp(ctx, medium ? 10 : 8); + if (medium) { + LinearLayout col = new LinearLayout(ctx); + col.setOrientation(LinearLayout.VERTICAL); + col.setPadding(pad, pad, pad, pad); + + LinearLayout header = new LinearLayout(ctx); + header.setOrientation(LinearLayout.HORIZONTAL); + header.setGravity(Gravity.CENTER_VERTICAL); + int is = (int) dp(ctx, 40); + header.addView(icon, new LinearLayout.LayoutParams(is, is)); + LinearLayout texts = new LinearLayout(ctx); + texts.setOrientation(LinearLayout.VERTICAL); + texts.addView(title); + texts.addView(adRow); + LinearLayout.LayoutParams tLp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1); + tLp.leftMargin = (int) dp(ctx, 8); + header.addView(texts, tLp); + col.addView(header); + + LinearLayout.LayoutParams bodyLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + bodyLp.topMargin = (int) dp(ctx, 6); + col.addView(body, bodyLp); + + media = new LevelPlayMediaView(ctx); + LinearLayout.LayoutParams mLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1); + mLp.topMargin = (int) dp(ctx, 8); + col.addView(media, mLp); + + // CTA on the right: the bottom-left corner stays free for the AdChoices icon. + LinearLayout.LayoutParams ctaLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) dp(ctx, 36)); + ctaLp.topMargin = (int) dp(ctx, 8); + ctaLp.gravity = Gravity.END; + col.addView(cta, ctaLp); + root.addView(col, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + } else { + LinearLayout row = new LinearLayout(ctx); + row.setOrientation(LinearLayout.HORIZONTAL); + row.setGravity(Gravity.CENTER_VERTICAL); + row.setPadding(pad, pad, pad, pad); + int is = (int) dp(ctx, 48); + row.addView(icon, new LinearLayout.LayoutParams(is, is)); + LinearLayout texts = new LinearLayout(ctx); + texts.setOrientation(LinearLayout.VERTICAL); + texts.addView(title); + texts.addView(adRow); + texts.addView(body); + LinearLayout.LayoutParams tLp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1); + tLp.leftMargin = (int) dp(ctx, 8); + tLp.rightMargin = (int) dp(ctx, 8); + row.addView(texts, tLp); + row.addView(cta, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) dp(ctx, 36))); + root.addView(row, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + } + + return new Views(root, title, advertiser, body, icon, cta, media); + } + + static void fill( + Views v, + @Nullable String title, + @Nullable String advertiser, + @Nullable String body, + @Nullable String callToAction, + @Nullable NativeAdDataInterface.Image icon + ) { + setOrHide(v.title, title); + setOrHide(v.advertiser, advertiser); + setOrHide(v.body, body); + if (callToAction != null && !callToAction.isEmpty()) v.cta.setText(callToAction); + else v.cta.setText(R.string.levelplay_native_ad_cta_fallback); + bindIcon(v.icon, icon); + } + + private static TextView text(Context ctx, int color, double defaultSize, NativeAdStyle.Font font, boolean bold) { + TextView t = new TextView(ctx); + t.setTextColor(color); + t.setEllipsize(TextUtils.TruncateAt.END); + t.setIncludeFontPadding(false); + applyFont(ctx, t, font, defaultSize, bold); + return t; + } + + private static void applyFont(Context ctx, TextView t, NativeAdStyle.Font font, double defaultSize, boolean bold) { + // CSS px = dp, and like WebView text it ignores the system font scale. + t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, (float) (font.size != null ? font.size : defaultSize)); + Typeface tf = typeface(ctx, font.family, bold); + t.setTypeface(tf); + } + + /** System family name, or a .ttf / .otf file in the web assets (Capacitor copies the web dir to assets/public). */ + static Typeface typeface(Context ctx, @Nullable String family, boolean bold) { + int style = bold ? Typeface.BOLD : Typeface.NORMAL; + if (family == null) return Typeface.defaultFromStyle(style); + String lower = family.toLowerCase(java.util.Locale.ROOT); + if (lower.endsWith(".ttf") || lower.endsWith(".otf")) { + String path = family; + while (path.startsWith("/")) path = path.substring(1); + if (path.startsWith("./")) path = path.substring(2); + String asset = "public/" + path; + synchronized (ASSET_FONTS) { + Typeface cached = ASSET_FONTS.get(asset); + if (cached != null) return cached; + try { + Typeface tf = Typeface.createFromAsset(ctx.getAssets(), asset); + ASSET_FONTS.put(asset, tf); + return tf; + } catch (RuntimeException e) { + Log.w(TAG, "Native ad font not found in assets: " + asset + "; using the system font"); + return Typeface.defaultFromStyle(style); + } + } + } + return Typeface.create(family, style); + } + + private static void setOrHide(TextView v, @Nullable String text) { + if (text == null || text.trim().isEmpty()) { + v.setText(""); + v.setVisibility(View.GONE); + } else { + v.setText(text); + v.setVisibility(View.VISIBLE); + } + } + + private static void bindIcon(ImageView icon, @Nullable NativeAdDataInterface.Image image) { + if (image == null) { + icon.setVisibility(View.GONE); + return; + } + Drawable d = image.getDrawable(); + if (d != null) { + icon.setImageDrawable(d); + return; + } + Uri uri = image.getUri(); + if (uri == null || uri.getScheme() == null || !uri.getScheme().startsWith("http")) { + icon.setVisibility(View.GONE); + return; + } + // Some adapters only give a URL: fetch it off the main thread. + Handler main = new Handler(Looper.getMainLooper()); + String url = uri.toString(); + IO.execute(() -> { + Bitmap bmp = null; + HttpURLConnection c = null; + try { + c = (HttpURLConnection) new URL(url).openConnection(); + c.setConnectTimeout(10000); + c.setReadTimeout(10000); + try (InputStream in = c.getInputStream()) { + bmp = BitmapFactory.decodeStream(in); + } + } catch (Exception e) { + Log.w(TAG, "Native ad icon download failed: " + e); + } finally { + if (c != null) c.disconnect(); + } + Bitmap result = bmp; + main.post(() -> { + if (result != null) icon.setImageBitmap(result); + else icon.setVisibility(View.GONE); + }); + }); + } + + static float dp(Context ctx, double v) { + return (float) (v * ctx.getResources().getDisplayMetrics().density); + } +} diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/OverlayHost.java b/android/src/main/java/fyi/crt/capacitor/levelplay/OverlayHost.java new file mode 100644 index 0000000..1a367ca --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/OverlayHost.java @@ -0,0 +1,159 @@ +package fyi.crt.capacitor.levelplay; + +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import androidx.annotation.Nullable; +import androidx.core.graphics.Insets; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowInsetsCompat; + +/** + * Plugin-owned, pass-through FrameLayout above the WebView (design §6.2). It is a sibling of the WebView in the + * WebView's parent, added right after it so it draws on top. It is neither clickable nor focusable and has no touch + * listener, so touches outside its (visible) children fall through to the WebView. + * + * Public geometry is CSS px relative to the WebView's top-left corner (1 CSS px = 1 dp in a Capacitor WebView). + * Children are positioned with FrameLayout margins measured from the WebView's offset inside the host, so the host + * does not need to share the WebView's bounds (Capacitor 8 may pad the parent; Capacitor 7 may set WebView margins). + * Main thread only. + */ +final class OverlayHost { + + interface Listener { + /** The WebView or the host moved / resized, or the window insets changed. Called posted, never mid-layout. */ + void onOverlayLayoutChanged(); + } + + final FrameLayout view; + private final View webView; + private final Listener listener; + private final float density; + private boolean relayoutPosted; + private final View.OnLayoutChangeListener layoutListener = (v, l, t, r, b, ol, ot, or, ob) -> { + if (l != ol || t != ot || r != or || b != ob) postRelayout(); + }; + private final Runnable relayout = () -> { + relayoutPosted = false; + listenerRelayout(); + }; + + private OverlayHost(View webView, ViewGroup parent, Listener listener) { + this.webView = webView; + this.listener = listener; + this.density = webView.getResources().getDisplayMetrics().density; + view = new FrameLayout(webView.getContext()); + view.setClickable(false); + view.setFocusable(false); + view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); + view.setClipChildren(true); + int index = parent.indexOfChild(webView) + 1; + parent.addView(view, index, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + webView.addOnLayoutChangeListener(layoutListener); + view.addOnLayoutChangeListener(layoutListener); + // Insets are only observed; returning them unconsumed keeps Capacitor's own handling on the WebView intact. + ViewCompat.setOnApplyWindowInsetsListener(view, (v, insets) -> { + postRelayout(); + return insets; + }); + } + + /** Attaches a host next to the WebView, or returns null when the WebView has no parent ViewGroup yet. */ + @Nullable + static OverlayHost attach(@Nullable View webView, Listener listener) { + if (webView == null || !(webView.getParent() instanceof ViewGroup)) return null; + return new OverlayHost(webView, (ViewGroup) webView.getParent(), listener); + } + + void detach() { + webView.removeOnLayoutChangeListener(layoutListener); + view.removeOnLayoutChangeListener(layoutListener); + ViewCompat.setOnApplyWindowInsetsListener(view, null); + view.removeCallbacks(relayout); + view.removeAllViews(); + if (view.getParent() instanceof ViewGroup) ((ViewGroup) view.getParent()).removeView(view); + } + + void postRelayout() { + if (relayoutPosted) return; + relayoutPosted = true; + view.post(relayout); + } + + private void listenerRelayout() { + listener.onOverlayLayoutChanged(); + } + + float density() { + return density; + } + + int toPx(double css) { + return (int) Math.round(css * density); + } + + /** The WebView's own rect in CSS px (origin 0, 0). */ + double[] webViewCss() { + return OverlayMath.rect(0, 0, webView.getWidth() / (double) density, webView.getHeight() / (double) density); + } + + /** WebView rect ∩ (window − system bars − display cutout), in WebView-local CSS px (design §6.3). */ + double[] safeAreaCss() { + int[] loc = new int[2]; + webView.getLocationInWindow(loc); + View root = webView.getRootView(); + int il = 0, it = 0, ir = 0, ib = 0; + WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(webView); + if (insets != null) { + Insets i = insets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout()); + il = i.left; + it = i.top; + ir = i.right; + ib = i.bottom; + } + return OverlayMath.safeAreaCss( + loc[0], + loc[1], + webView.getWidth(), + webView.getHeight(), + root.getWidth(), + root.getHeight(), + il, + it, + ir, + ib, + density + ); + } + + /** Adds a child (hidden or not, as the caller set it) on top of the other overlay children. */ + void add(View child) { + if (child.getParent() instanceof ViewGroup) ((ViewGroup) child.getParent()).removeView(child); + view.addView(child, new FrameLayout.LayoutParams(0, 0)); + } + + void remove(View child) { + if (child.getParent() == view) view.removeView(child); + } + + /** Places a child at a WebView-local CSS rect. */ + void place(View child, double[] css) { + int[] wv = new int[2]; + int[] host = new int[2]; + webView.getLocationInWindow(wv); + view.getLocationInWindow(host); + int left = wv[0] - host[0] + toPx(css[0]); + int top = wv[1] - host[1] + toPx(css[1]); + int w = Math.max(0, toPx(css[2])); + int h = Math.max(0, toPx(css[3])); + ViewGroup.LayoutParams raw = child.getLayoutParams(); + FrameLayout.LayoutParams lp = raw instanceof FrameLayout.LayoutParams ? (FrameLayout.LayoutParams) raw : new FrameLayout.LayoutParams(w, h); + if (lp.width == w && lp.height == h && lp.leftMargin == left && lp.topMargin == top && raw == lp) return; + lp.width = w; + lp.height = h; + lp.leftMargin = left; + lp.topMargin = top; + lp.gravity = android.view.Gravity.TOP | android.view.Gravity.LEFT; + child.setLayoutParams(lp); + } +} diff --git a/android/src/main/java/fyi/crt/capacitor/levelplay/OverlayMath.java b/android/src/main/java/fyi/crt/capacitor/levelplay/OverlayMath.java new file mode 100644 index 0000000..f596580 --- /dev/null +++ b/android/src/main/java/fyi/crt/capacitor/levelplay/OverlayMath.java @@ -0,0 +1,120 @@ +package fyi.crt.capacitor.levelplay; + +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Pure helpers (no Android, no SDK types) for overlay geometry and argument validation, unit tested on the JVM. + * Rects are {@code double[]{x, y, width, height}}. + */ +final class OverlayMath { + + /** LevelPlaySegment.setCustom limits read from the 9.6.1 bytecode: 1-32 chars, letters and digits, at most 5. */ + static final int MAX_CUSTOM_PARAMS = 5; + static final int MAX_CUSTOM_LENGTH = 32; + private static final Pattern ALNUM = Pattern.compile("^[a-zA-Z0-9]+$"); + private static final Pattern HEX_COLOR = Pattern.compile("^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$"); + + private OverlayMath() {} + + static double[] rect(double x, double y, double w, double h) { + return new double[] { x, y, w, h }; + } + + /** Intersection of two rects; an empty intersection has zero width / height at the clamped origin. */ + static double[] intersect(double[] a, double[] b) { + double l = Math.max(a[0], b[0]); + double t = Math.max(a[1], b[1]); + double r = Math.min(a[0] + a[2], b[0] + b[2]); + double btm = Math.min(a[1] + a[3], b[1] + b[3]); + return rect(l, t, Math.max(0, r - l), Math.max(0, btm - t)); + } + + /** + * Safe area of the WebView in WebView-local CSS px: the WebView's on-screen rect (window px) intersected with the + * window minus the system insets (window px), shifted to the WebView origin and divided by the density. + */ + static double[] safeAreaCss( + int wvLeft, + int wvTop, + int wvWidth, + int wvHeight, + int windowWidth, + int windowHeight, + int insetLeft, + int insetTop, + int insetRight, + int insetBottom, + float density + ) { + double[] web = rect(wvLeft, wvTop, wvWidth, wvHeight); + double[] safe = rect(insetLeft, insetTop, windowWidth - insetLeft - insetRight, windowHeight - insetTop - insetBottom); + double[] s = intersect(web, safe); + return rect((s[0] - wvLeft) / density, (s[1] - wvTop) / density, s[2] / density, s[3] / density); + } + + /** Banner frame inside {@code area} (design §6.4): centred horizontally, anchored top / bottom / center. */ + static double[] bannerFrame(double[] area, double width, double height, String position, double offsetX, double offsetY) { + double x = area[0] + (area[2] - width) / 2 + offsetX; + double y; + switch (position) { + case "top": + y = area[1] + offsetY; + break; + case "center": + y = area[1] + (area[3] - height) / 2 + offsetY; + break; + default: + y = area[1] + area[3] - height + offsetY; + break; + } + return rect(x, y, width, height); + } + + static boolean isPosition(String p) { + return "top".equals(p) || "bottom".equals(p) || "center".equals(p); + } + + static boolean isBannerSize(String s) { + switch (s) { + case "BANNER": + case "LARGE": + case "MEDIUM_RECTANGLE": + case "LEADERBOARD": + case "ADAPTIVE": + case "CUSTOM": + return true; + default: + return false; + } + } + + /** Error message for segment custom parameters that break the SDK limits, or null when they are fine. */ + static String customParamsError(Map params) { + if (params.size() > MAX_CUSTOM_PARAMS) { + return "customParameters: at most " + MAX_CUSTOM_PARAMS + " pairs (got " + params.size() + ")"; + } + for (Map.Entry e : params.entrySet()) { + String k = e.getKey(); + if (!validToken(k)) return "customParameters: key '" + k + "' must be 1-32 letters or digits"; + Object v = e.getValue(); + if (!(v instanceof String)) return "customParameters: value of '" + k + "' must be a string"; + if (!validToken((String) v)) return "customParameters: value of '" + k + "' must be 1-32 letters or digits"; + } + return null; + } + + private static boolean validToken(String s) { + return s != null && s.length() >= 1 && s.length() <= MAX_CUSTOM_LENGTH && ALNUM.matcher(s).matches(); + } + + /** CSS {@code #RRGGBB} / {@code #RRGGBBAA} to Android ARGB, or null when malformed. */ + static Integer parseColor(String css) { + if (css == null || !HEX_COLOR.matcher(css).matches()) return null; + long v = Long.parseLong(css.substring(1), 16); + if (css.length() == 7) return (int) (0xFF000000L | v); + long rgb = v >>> 8; + long a = v & 0xFF; + return (int) ((a << 24) | rgb); + } +} diff --git a/android/src/main/res/values/strings.xml b/android/src/main/res/values/strings.xml new file mode 100644 index 0000000..3add140 --- /dev/null +++ b/android/src/main/res/values/strings.xml @@ -0,0 +1,6 @@ + + + + Ad + Open + diff --git a/android/src/test/java/fyi/crt/capacitor/levelplay/OverlayMathTest.java b/android/src/test/java/fyi/crt/capacitor/levelplay/OverlayMathTest.java new file mode 100644 index 0000000..6f2c766 --- /dev/null +++ b/android/src/test/java/fyi/crt/capacitor/levelplay/OverlayMathTest.java @@ -0,0 +1,102 @@ +package fyi.crt.capacitor.levelplay; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.Test; + +public class OverlayMathTest { + + private static final double EPS = 1e-9; + + @Test + public void intersectOverlapsAndEmpty() { + assertArrayEquals(new double[] { 10, 20, 90, 80 }, OverlayMath.intersect(OverlayMath.rect(0, 0, 100, 100), OverlayMath.rect(10, 20, 200, 200)), EPS); + double[] none = OverlayMath.intersect(OverlayMath.rect(0, 0, 10, 10), OverlayMath.rect(20, 20, 5, 5)); + assertEquals(0, none[2], EPS); + assertEquals(0, none[3], EPS); + } + + @Test + public void safeAreaEdgeToEdgeWebView() { + // 1080 x 2400 window at density 2.625; WebView covers the window; status bar 63 px, nav bar 126 px. + double[] s = OverlayMath.safeAreaCss(0, 0, 1080, 2400, 1080, 2400, 0, 63, 0, 126, 2.625f); + assertArrayEquals(new double[] { 0, 24, 1080 / 2.625, (2400 - 63 - 126) / 2.625 }, s, EPS); + } + + @Test + public void safeAreaWebViewAlreadyInset() { + // Capacitor native insets handling: the WebView itself sits between the bars, so the safe area is all of it. + double[] s = OverlayMath.safeAreaCss(0, 63, 1080, 2211, 1080, 2400, 0, 63, 0, 126, 2.625f); + assertArrayEquals(new double[] { 0, 0, 1080 / 2.625, 2211 / 2.625 }, s, EPS); + } + + @Test + public void safeAreaLandscapeCutout() { + // Landscape with a 100 px cutout on the left and a 120 px nav bar on the right; density 2. + double[] s = OverlayMath.safeAreaCss(0, 0, 2400, 1080, 2400, 1080, 100, 50, 120, 0, 2f); + assertArrayEquals(new double[] { 50, 25, (2400 - 220) / 2.0, (1080 - 50) / 2.0 }, s, EPS); + } + + @Test + public void bannerFramePositions() { + double[] area = OverlayMath.rect(0, 24, 411, 800); + assertArrayEquals(new double[] { 45.5, 24, 320, 50 }, OverlayMath.bannerFrame(area, 320, 50, "top", 0, 0), EPS); + assertArrayEquals(new double[] { 45.5, 774, 320, 50 }, OverlayMath.bannerFrame(area, 320, 50, "bottom", 0, 0), EPS); + assertArrayEquals(new double[] { 45.5, 399, 320, 50 }, OverlayMath.bannerFrame(area, 320, 50, "center", 0, 0), EPS); + assertArrayEquals(new double[] { 55.5, 764, 320, 50 }, OverlayMath.bannerFrame(area, 320, 50, "bottom", 10, -10), EPS); + } + + @Test + public void positionsAndSizes() { + assertTrue(OverlayMath.isPosition("top")); + assertFalse(OverlayMath.isPosition("left")); + assertTrue(OverlayMath.isBannerSize("CUSTOM")); + assertTrue(OverlayMath.isBannerSize("ADAPTIVE")); + assertFalse(OverlayMath.isBannerSize("SMART")); + } + + @Test + public void customParams() { + Map ok = new LinkedHashMap<>(); + ok.put("tier", "gold"); + ok.put("ab1", "B"); + assertNull(OverlayMath.customParamsError(ok)); + + Map badChar = new LinkedHashMap<>(); + badChar.put("my-key", "x"); + assertNotNull(OverlayMath.customParamsError(badChar)); + + Map empty = new LinkedHashMap<>(); + empty.put("k", ""); + assertNotNull(OverlayMath.customParamsError(empty)); + + Map tooLong = new LinkedHashMap<>(); + tooLong.put("k", "123456789012345678901234567890123"); + assertNotNull(OverlayMath.customParamsError(tooLong)); + + Map notString = new LinkedHashMap<>(); + notString.put("k", 5); + assertNotNull(OverlayMath.customParamsError(notString)); + + Map six = new LinkedHashMap<>(); + for (int i = 0; i < 6; i++) six.put("k" + i, "v"); + assertNotNull(OverlayMath.customParamsError(six)); + } + + @Test + public void colors() { + assertEquals(Integer.valueOf(0xFF112233), OverlayMath.parseColor("#112233")); + assertEquals(Integer.valueOf(0x80112233), OverlayMath.parseColor("#11223380")); + assertNull(OverlayMath.parseColor("112233")); + assertNull(OverlayMath.parseColor("#12345")); + assertNull(OverlayMath.parseColor("red")); + assertNull(OverlayMath.parseColor(null)); + } +} diff --git a/dist/docs.json b/dist/docs.json new file mode 100644 index 0000000..094cfd3 --- /dev/null +++ b/dist/docs.json @@ -0,0 +1,3704 @@ +{ + "api": { + "name": "LevelPlayPlugin", + "slug": "levelplayplugin", + "docs": "Unity LevelPlay ads (ad-unit API): rewarded, interstitial and (since 0.3.0) banner and native ads, impression-level\nrevenue, segments and placement capping.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [ + { + "name": "initialize", + "signature": "(options: InitOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "InitOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Initialise the LevelPlay SDK (`LevelPlay.init`). Resolves on init success, rejects with the init error\n(code and message from the SDK) otherwise. Calling it again after a successful init resolves immediately;\nconcurrent calls share one init. Load ads only after this resolves.\n\nSet consent (and on iOS ask for ATT) before calling it.\n\nOn the web it rejects as unimplemented.", + "complexTypes": [ + "InitResult", + "InitOptions" + ], + "slug": "initialize" + }, + { + "name": "getSdkVersion", + "signature": "() => Promise", + "parameters": [], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Native LevelPlay SDK version. Works before init.", + "complexTypes": [ + "InitResult" + ], + "slug": "getsdkversion" + }, + { + "name": "setConsent", + "signature": "(options: ConsentOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "ConsentOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Forward GDPR / CCPA / COPPA signals to LevelPlay. Call it before `initialize()` when you\ncan, and again whenever the user changes their choice.", + "complexTypes": [ + "ConsentOptions" + ], + "slug": "setconsent" + }, + { + "name": "setMetaData", + "signature": "(options: MetaDataOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "MetaDataOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Raw `LevelPlay.setMetaData(key, value)` for SDK or network-specific flags. Call it before init.", + "complexTypes": [ + "MetaDataOptions" + ], + "slug": "setmetadata" + }, + { + "name": "requestTrackingAuthorization", + "signature": "() => Promise", + "parameters": [], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "iOS: show the App Tracking Transparency prompt and resolve with the resulting status. Needs\n`NSUserTrackingUsageDescription` in `Info.plist`. iOS only shows the prompt once; later calls resolve the stored\nstatus. Call it before `initialize()`, while the app is active.\n\nAndroid and web: resolves `unavailable`.", + "complexTypes": [ + "TrackingResult" + ], + "slug": "requesttrackingauthorization" + }, + { + "name": "getTrackingAuthorizationStatus", + "signature": "() => Promise", + "parameters": [], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Current App Tracking Transparency status without prompting (iOS). Android and web: `unavailable`.", + "complexTypes": [ + "TrackingResult" + ], + "slug": "gettrackingauthorizationstatus" + }, + { + "name": "loadRewarded", + "signature": "(options: AdUnitOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "AdUnitOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Start loading a rewarded ad for the ad unit. The native ad object is created on first use and reused for the\nad unit. Resolves once the request is issued; the outcome arrives as a `loaded` or `loadFailed` event.\nLoad the next ad after each show.", + "complexTypes": [ + "AdUnitOptions" + ], + "slug": "loadrewarded" + }, + { + "name": "showRewarded", + "signature": "(options: ShowOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "ShowOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Show a loaded rewarded ad. Resolves after the ad closed (or failed to display) with what happened. The reward\nand close callbacks can arrive in either order on some networks, so the plugin waits up to 1 second after the close\nfor a late reward. Never rejects for \"not ready\": resolves `{ shown: false, rewarded: false, error }` instead.", + "complexTypes": [ + "ShowResult", + "ShowOptions" + ], + "slug": "showrewarded" + }, + { + "name": "loadInterstitial", + "signature": "(options: AdUnitOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "AdUnitOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Start loading an interstitial ad for the ad unit. Works like `loadRewarded()`.", + "complexTypes": [ + "AdUnitOptions" + ], + "slug": "loadinterstitial" + }, + { + "name": "showInterstitial", + "signature": "(options: ShowOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "ShowOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Show a loaded interstitial. Resolves after it closed (or failed to display). Never rejects for \"not ready\".", + "complexTypes": [ + "ShowResult", + "ShowOptions" + ], + "slug": "showinterstitial" + }, + { + "name": "isReady", + "signature": "(options: IsReadyOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "IsReadyOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "`isAdReady()` of the native ad object for this ad unit. `false` when the ad unit was never loaded.", + "complexTypes": [ + "IsReadyResult", + "IsReadyOptions" + ], + "slug": "isready" + }, + { + "name": "launchTestSuite", + "signature": "() => Promise", + "parameters": [], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first.\nDevelopment builds only. Rejects on the web.", + "complexTypes": [], + "slug": "launchtestsuite" + }, + { + "name": "validateIntegration", + "signature": "() => Promise", + "parameters": [], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Write the LevelPlay integration helper report to the native log (Xcode console; Android logcat tag\n`IntegrationHelper`): SDK, adapter and network SDK versions, each `VERIFIED` or not. Development only.", + "complexTypes": [], + "slug": "validateintegration" + }, + { + "name": "getCapabilities", + "signature": "() => Promise", + "parameters": [], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "What this platform supports (banners, native ad templates, impression data, `adInfoChanged`). Works before init.\nWeb: everything `false`.", + "complexTypes": [ + "Capabilities" + ], + "slug": "getcapabilities" + }, + { + "name": "setSegment", + "signature": "(options: SegmentOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "SegmentOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Set the user segment (`LevelPlay.setSegment` with a `LevelPlaySegment` / `LPMSegment`). Call it before\n`initialize()` so the first ad requests use it; later calls apply to the following requests. Rejects with\n`INVALID_ARGUMENT` when `customParameters` break the SDK limits. Web: no-op.", + "complexTypes": [ + "SegmentOptions" + ], + "slug": "setsegment" + }, + { + "name": "setDynamicUserId", + "signature": "(options: DynamicUserIdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "DynamicUserIdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Set or change the dynamic user id used in server-to-server reward callbacks (`LevelPlay.setDynamicUserId` on\nboth platforms). Set it before `showRewarded()`. Web: resolves `{ valid: false }`.", + "complexTypes": [ + "DynamicUserIdResult", + "DynamicUserIdOptions" + ], + "slug": "setdynamicuserid" + }, + { + "name": "isPlacementCapped", + "signature": "(options: PlacementCappedOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "PlacementCappedOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Whether a rewarded or interstitial placement is capped right now (static\n`LevelPlayRewardedAd.isPlacementCapped` / `LevelPlayInterstitialAd.isPlacementCapped` on Android,\n`LPMRewardedAd.isPlacementCapped:` / `LPMInterstitialAd.isPlacementCapped:` on iOS). Works without a loaded ad.\nWeb: `{ capped: false }`.", + "complexTypes": [ + "PlacementCappedResult", + "PlacementCappedOptions" + ], + "slug": "isplacementcapped" + }, + { + "name": "getReward", + "signature": "(options: GetRewardOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "GetRewardOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "The reward configured for a rewarded ad unit or one of its placements (`LevelPlayRewardedAd.getReward(placement)` /\n`LPMRewardedAd getReward(placementName:)`), for \"watch a video for N coins\" buttons. The SDK returns\n`{ name: '', amount: 0 }` when it has no reward configuration (for example before init). Web: the same empty\nreward.", + "complexTypes": [ + "Reward", + "GetRewardOptions" + ], + "slug": "getreward" + }, + { + "name": "createBanner", + "signature": "(options: CreateBannerOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "CreateBannerOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Create a banner (`LevelPlayBannerAdView` / `LPMBannerAdView`) for the ad unit and attach it, hidden, in a\npass-through overlay above the WebView. Requires a finished `initialize()` (`NOT_INITIALIZED` otherwise). Rejects\nwith `ALREADY_EXISTS` when `bannerId` is in use; destroy it first. Does not load: call `loadBanner()`.\nWeb: rejects as unimplemented.", + "complexTypes": [ + "BannerResult", + "CreateBannerOptions" + ], + "slug": "createbanner" + }, + { + "name": "loadBanner", + "signature": "(options: BannerIdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "BannerIdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Load the banner (`loadAd()` / `loadAdWithViewController:`). The outcome arrives as `bannerLoaded` or\n`bannerLoadFailed`; after the first load the SDK refreshes the banner on the dashboard interval. The SDK accepts\none load per banner object: calling it again has no effect (Android logs \"Banner load already called\"), so to retry\nright away after `bannerLoadFailed`, destroy the banner and create it again. Web: no-op.", + "complexTypes": [ + "BannerIdOptions" + ], + "slug": "loadbanner" + }, + { + "name": "showBanner", + "signature": "(options: BannerIdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "BannerIdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Make the banner visible and resume auto refresh (`resumeAutoRefresh`). Can be called before the load finished;\nthe creative appears when it arrives. Web: rejects as unimplemented.", + "complexTypes": [ + "BannerResult", + "BannerIdOptions" + ], + "slug": "showbanner" + }, + { + "name": "hideBanner", + "signature": "(options: BannerIdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "BannerIdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Hide the banner and pause auto refresh (`pauseAutoRefresh`) so hidden banners do not burn impressions. The view\nstays attached; `showBanner()` brings it back. Web: no-op.", + "complexTypes": [ + "BannerIdOptions" + ], + "slug": "hidebanner" + }, + { + "name": "setBannerLayout", + "signature": "(options: SetBannerLayoutOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "SetBannerLayoutOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Move a banner (position, offsets, safe area). Resolves with the new frame. Web: rejects as unimplemented.", + "complexTypes": [ + "BannerResult", + "SetBannerLayoutOptions" + ], + "slug": "setbannerlayout" + }, + { + "name": "destroyBanner", + "signature": "(options: BannerIdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "BannerIdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Remove the banner from the screen and `destroy()` it. A destroyed banner cannot be reused; create a new one.\nResolves also for unknown ids. Web: no-op.", + "complexTypes": [ + "BannerIdOptions" + ], + "slug": "destroybanner" + }, + { + "name": "loadNativeAd", + "signature": "(options: LoadNativeAdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "LoadNativeAdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Load a native ad into a slot. Following the SDK rule \"one native ad object per load\", it destroys the slot's\nprevious ad (hiding it if shown), builds a new `LevelPlayNativeAd` with the placement and loads it. The outcome\narrives as `nativeAdLoaded` or `nativeAdLoadFailed`. Requires a finished `initialize()`. Rejects with\n`UNSUPPORTED` when `getCapabilities().nativeAd` is `false` or the template is not listed there. Web: rejects as\nunimplemented.", + "complexTypes": [ + "LoadNativeAdOptions" + ], + "slug": "loadnativead" + }, + { + "name": "showNativeAd", + "signature": "(options: NativeAdRectOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "NativeAdRectOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Render the loaded native ad into its template, register the asset views with the SDK\n(`NativeAdLayout.registerNativeAdViews` / `ISNativeAdView registerNativeAdViews:`) and place it at `rect` above the\nWebView. Rejects with `NOT_LOADED` before `nativeAdLoaded`. The impression is reported by `nativeAdImpression`.\nWeb: rejects as unimplemented.", + "complexTypes": [ + "NativeAdRectOptions" + ], + "slug": "shownativead" + }, + { + "name": "setNativeAdRect", + "signature": "(options: NativeAdRectOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "NativeAdRectOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Move or resize a shown native ad, for example after the placeholder element moved. Web: no-op.", + "complexTypes": [ + "NativeAdRectOptions" + ], + "slug": "setnativeadrect" + }, + { + "name": "hideNativeAd", + "signature": "(options: NativeAdIdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "NativeAdIdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Hide a shown native ad (the view stays registered; `showNativeAd()` shows it again). Web: no-op.", + "complexTypes": [ + "NativeAdIdOptions" + ], + "slug": "hidenativead" + }, + { + "name": "destroyNativeAd", + "signature": "(options: NativeAdIdOptions) => Promise", + "parameters": [ + { + "name": "options", + "docs": "", + "type": "NativeAdIdOptions" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Remove the native ad view and `destroyAd()` it. Resolves also for unknown ids. Web: no-op.", + "complexTypes": [ + "NativeAdIdOptions" + ], + "slug": "destroynativead" + }, + { + "name": "addListener", + "signature": "(eventName: 'loaded', listenerFunc: (event: AdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'loaded'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "An ad finished loading for the ad unit and can be shown.", + "complexTypes": [ + "PluginListenerHandle", + "AdEvent" + ], + "slug": "addlistenerloaded-" + }, + { + "name": "addListener", + "signature": "(eventName: 'loadFailed', listenerFunc: (event: AdErrorEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'loadFailed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdErrorEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Loading failed, for example `509` (no fill). Retry later with a backoff.", + "complexTypes": [ + "PluginListenerHandle", + "AdErrorEvent" + ], + "slug": "addlistenerloadfailed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'displayed', listenerFunc: (event: AdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'displayed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "The ad was displayed (impression). `adInfo.revenue` is available here.", + "complexTypes": [ + "PluginListenerHandle", + "AdEvent" + ], + "slug": "addlistenerdisplayed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'displayFailed', listenerFunc: (event: AdErrorEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'displayFailed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdErrorEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "The ad failed to display. The pending show call resolves with the same error.", + "complexTypes": [ + "PluginListenerHandle", + "AdErrorEvent" + ], + "slug": "addlistenerdisplayfailed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'clicked', listenerFunc: (event: AdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'clicked'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "The user clicked the ad.", + "complexTypes": [ + "PluginListenerHandle", + "AdEvent" + ], + "slug": "addlistenerclicked-" + }, + { + "name": "addListener", + "signature": "(eventName: 'closed', listenerFunc: (event: AdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'closed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "The ad was closed and the app is back in front.", + "complexTypes": [ + "PluginListenerHandle", + "AdEvent" + ], + "slug": "addlistenerclosed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'rewarded', listenerFunc: (event: AdRewardEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'rewarded'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdRewardEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Rewarded only: the user earned the reward. Can fire before or after `closed`.", + "complexTypes": [ + "PluginListenerHandle", + "AdRewardEvent" + ], + "slug": "addlistenerrewarded-" + }, + { + "name": "addListener", + "signature": "(eventName: 'adInfoChanged', listenerFunc: (event: AdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'adInfoChanged'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: AdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Rewarded and interstitial: the SDK reloaded the ad in the background and its ad info (network, revenue ...)\nchanged (`onAdInfoChanged` / `didChangeAdInfo:`). Banners and native ads have no such callback in SDK 9.6.1.", + "complexTypes": [ + "PluginListenerHandle", + "AdEvent" + ], + "slug": "addlisteneradinfochanged-" + }, + { + "name": "addListener", + "signature": "(eventName: 'impressionData', listenerFunc: (event: ImpressionData) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'impressionData'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: ImpressionData) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "Impression-level revenue data for every rewarded, interstitial and banner impression (per-ad\n`setImpressionDataListener` / `setImpressionDataDelegate:`, attached by the plugin to every ad object it creates),\nplus native ad impressions synthesised from the native ad info (`adFormat: 'nativead'`, `adInfo` fields only).\nAdd the listener at any time, also before `initialize()`; nothing is delivered before the first ad shows.", + "complexTypes": [ + "PluginListenerHandle", + "ImpressionData" + ], + "slug": "addlistenerimpressiondata-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerLoaded', listenerFunc: (event: BannerEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerLoaded'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A banner loaded or refreshed with a new creative.", + "complexTypes": [ + "PluginListenerHandle", + "BannerEvent" + ], + "slug": "addlistenerbannerloaded-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerLoadFailed', listenerFunc: (event: BannerErrorEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerLoadFailed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerErrorEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A banner load (or refresh) failed. The SDK keeps retrying on its refresh interval.", + "complexTypes": [ + "PluginListenerHandle", + "BannerErrorEvent" + ], + "slug": "addlistenerbannerloadfailed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerDisplayed', listenerFunc: (event: BannerEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerDisplayed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A banner creative was displayed on screen (impression).", + "complexTypes": [ + "PluginListenerHandle", + "BannerEvent" + ], + "slug": "addlistenerbannerdisplayed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerDisplayFailed', listenerFunc: (event: BannerErrorEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerDisplayFailed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerErrorEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A banner creative failed to display.", + "complexTypes": [ + "PluginListenerHandle", + "BannerErrorEvent" + ], + "slug": "addlistenerbannerdisplayfailed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerClicked', listenerFunc: (event: BannerEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerClicked'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "The user clicked a banner.", + "complexTypes": [ + "PluginListenerHandle", + "BannerEvent" + ], + "slug": "addlistenerbannerclicked-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerExpanded', listenerFunc: (event: BannerEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerExpanded'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A banner opened full screen (for example an expandable creative). Pause the game.", + "complexTypes": [ + "PluginListenerHandle", + "BannerEvent" + ], + "slug": "addlistenerbannerexpanded-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerCollapsed', listenerFunc: (event: BannerEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerCollapsed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A banner returned to its normal size. Resume the game.", + "complexTypes": [ + "PluginListenerHandle", + "BannerEvent" + ], + "slug": "addlistenerbannercollapsed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'bannerLeftApplication', listenerFunc: (event: BannerEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'bannerLeftApplication'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: BannerEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A banner click sent the user out of the app (browser or store).", + "complexTypes": [ + "PluginListenerHandle", + "BannerEvent" + ], + "slug": "addlistenerbannerleftapplication-" + }, + { + "name": "addListener", + "signature": "(eventName: 'nativeAdLoaded', listenerFunc: (event: NativeAdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'nativeAdLoaded'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: NativeAdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A native ad loaded and can be shown with `showNativeAd()`.", + "complexTypes": [ + "PluginListenerHandle", + "NativeAdEvent" + ], + "slug": "addlistenernativeadloaded-" + }, + { + "name": "addListener", + "signature": "(eventName: 'nativeAdLoadFailed', listenerFunc: (event: NativeAdErrorEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'nativeAdLoadFailed'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: NativeAdErrorEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A native ad failed to load. Load again later (the plugin already destroyed the failed ad object).", + "complexTypes": [ + "PluginListenerHandle", + "NativeAdErrorEvent" + ], + "slug": "addlistenernativeadloadfailed-" + }, + { + "name": "addListener", + "signature": "(eventName: 'nativeAdImpression', listenerFunc: (event: NativeAdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'nativeAdImpression'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: NativeAdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "A shown native ad recorded its impression (first pixel visible).", + "complexTypes": [ + "PluginListenerHandle", + "NativeAdEvent" + ], + "slug": "addlistenernativeadimpression-" + }, + { + "name": "addListener", + "signature": "(eventName: 'nativeAdClicked', listenerFunc: (event: NativeAdEvent) => void) => Promise", + "parameters": [ + { + "name": "eventName", + "docs": "", + "type": "'nativeAdClicked'" + }, + { + "name": "listenerFunc", + "docs": "", + "type": "(event: NativeAdEvent) => void" + } + ], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.3.0" + } + ], + "docs": "The user clicked a native ad.", + "complexTypes": [ + "PluginListenerHandle", + "NativeAdEvent" + ], + "slug": "addlistenernativeadclicked-" + }, + { + "name": "removeAllListeners", + "signature": "() => Promise", + "parameters": [], + "returns": "Promise", + "tags": [ + { + "name": "since", + "text": "0.1.0" + } + ], + "docs": "Remove every listener of this plugin.", + "complexTypes": [], + "slug": "removealllisteners" + } + ], + "properties": [] + }, + "interfaces": [ + { + "name": "InitResult", + "slug": "initresult", + "docs": "Result of `initialize()` and `getSdkVersion()`.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "sdkVersion", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Native LevelPlay SDK version, for example `9.6.1`. `web` on the web.", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "InitOptions", + "slug": "initoptions", + "docs": "Options for `initialize()`.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "appKey", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "LevelPlay app key from the LevelPlay dashboard. Android and iOS apps have different keys.", + "complexTypes": [], + "type": "string" + }, + { + "name": "userId", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Optional user id. Needed for server-to-server reward callbacks and the Ad Quality user journey.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "testSuite", + "tags": [ + { + "text": "false", + "name": "default" + }, + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Enable the LevelPlay Integration Test Suite: sets the `is_test_suite=enable` meta data before init.\nCall `launchTestSuite()` after `initialize` resolves. Never ship this enabled.", + "complexTypes": [], + "type": "boolean | undefined" + }, + { + "name": "adaptersDebug", + "tags": [ + { + "text": "false", + "name": "default" + }, + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Turn on debug logs of the mediated ad network adapters (`LevelPlay.setAdaptersDebug(true)`). Development only.", + "complexTypes": [], + "type": "boolean | undefined" + }, + { + "name": "consent", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Privacy signals applied right before init (LevelPlay recommends setting them before the SDK starts).\nSame as calling `setConsent()` first.", + "complexTypes": [ + "ConsentOptions" + ], + "type": "ConsentOptions" + } + ] + }, + { + "name": "ConsentOptions", + "slug": "consentoptions", + "docs": "Privacy signals forwarded to LevelPlay (`LevelPlayPrivacySettings` on Android, `LPMPrivacySettings` on iOS).\nOmitted fields are left untouched.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "gdprConsent", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "GDPR: `true` when the user consented to personalised ads and data processing, `false` when they did not.\nFor users in the EEA, UK and Switzerland pass `false` until a consent management platform (CMP) says otherwise.", + "complexTypes": [], + "type": "boolean | undefined" + }, + { + "name": "ccpaDoNotSell", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "CCPA and other US state privacy laws: `true` when the user opted OUT of the sale or sharing of personal data\n(\"do not sell\"), `false` otherwise.", + "complexTypes": [], + "type": "boolean | undefined" + }, + { + "name": "coppa", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "COPPA: `true` when the user must be treated as a child (child-directed treatment).", + "complexTypes": [], + "type": "boolean | undefined" + } + ] + }, + { + "name": "MetaDataOptions", + "slug": "metadataoptions", + "docs": "Options for `setMetaData()`.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "key", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Meta data key, for example `is_deviceid_optout` or a network-specific flag from Unity's docs.", + "complexTypes": [], + "type": "string" + }, + { + "name": "value", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Meta data value, always a string (for example `\"true\"`).", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "TrackingResult", + "slug": "trackingresult", + "docs": "Result of `requestTrackingAuthorization()` and\n`getTrackingAuthorizationStatus()`.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "status", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "iOS App Tracking Transparency status. Always `unavailable` on Android and web.", + "complexTypes": [ + "TrackingStatus" + ], + "type": "TrackingStatus" + } + ] + }, + { + "name": "AdUnitOptions", + "slug": "adunitoptions", + "docs": "Identifies one ad unit.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "adUnitId", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Ad unit id from the LevelPlay dashboard (Ad units page). Android and iOS ad units have different ids.", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "ShowResult", + "slug": "showresult", + "docs": "Result of `showRewarded()` and `showInterstitial()`, resolved after the ad\nclosed or failed to display.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "shown", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "The ad was displayed (the `displayed` event fired).", + "complexTypes": [], + "type": "boolean" + }, + { + "name": "rewarded", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Rewarded only: the reward callback fired for this show. Grant the reward only when this is `true`.\nAlways `false` for interstitials.", + "complexTypes": [], + "type": "boolean" + }, + { + "name": "reward", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "The reward, present when `rewarded` is `true`.", + "complexTypes": [ + "Reward" + ], + "type": "Reward" + }, + { + "name": "error", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Present when the ad was not ready (`code: -1`) or failed to display.", + "complexTypes": [ + "AdError" + ], + "type": "AdError" + }, + { + "name": "adInfo", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Info of the displayed ad.", + "complexTypes": [ + "AdInfo" + ], + "type": "AdInfo" + } + ] + }, + { + "name": "Reward", + "slug": "reward", + "docs": "The reward of a rewarded ad, as configured in the LevelPlay dashboard (per ad unit or placement).", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "name", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Name of the reward, for example `Coins`.", + "complexTypes": [], + "type": "string" + }, + { + "name": "amount", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Amount of the reward.", + "complexTypes": [], + "type": "number" + } + ] + }, + { + "name": "AdError", + "slug": "aderror", + "docs": "Error reported by the SDK (load / display failures) or by the plugin.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "code", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "LevelPlay error code, for example `509` (no fill). `-1` is used by the plugin for \"Ad not ready\" and for the web\nstub.", + "complexTypes": [], + "type": "number" + }, + { + "name": "message", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Human readable message.", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "AdInfo", + "slug": "adinfo", + "docs": "Subset of the native `LevelPlayAdInfo` (Android) / `LPMAdInfo` (iOS) that is useful in JavaScript.\nFields the SDK does not report are omitted.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "adId", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Unique id of this ad.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adUnitId", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Ad unit id.", + "complexTypes": [], + "type": "string" + }, + { + "name": "adUnitName", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Ad unit name from the dashboard.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adFormat", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Ad format as reported by the SDK.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "placementName", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Placement name of the show call, when one was used.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adNetwork", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Name of the mediated network that served the ad.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "instanceName", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Mediation instance name.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "instanceId", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Mediation instance id.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "country", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Country code of the impression.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "auctionId", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Auction id.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "revenue", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Impression revenue in USD as reported by the SDK (may be absent or 0 before display).", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "precision", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Revenue precision as reported by the SDK.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "ab", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "A/B test group of the user (`ab`).", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "segmentName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Segment name of the user, see `setSegment()`.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "encryptedCPM", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Encrypted CPM (`encryptedCPM`).", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "creativeId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Creative id of the served ad, when the network reports one.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "conversionValue", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "iOS only: SKAdNetwork conversion value (`LPMAdInfo.conversionValue`). Android's `LevelPlayAdInfo` has no such\nfield in SDK 9.6.1, so it is always absent there.", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "adSize", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Size of the ad. Banners only (`LevelPlayAdInfo.getAdSize()` / `LPMAdInfo.adSize`).", + "complexTypes": [ + "AdSizeInfo" + ], + "type": "AdSizeInfo" + } + ] + }, + { + "name": "AdSizeInfo", + "slug": "adsizeinfo", + "docs": "A resolved ad size as reported by the SDK (`LevelPlayAdSize` / `LPMAdSize`). Width and height are in dp on Android\nand points on iOS, which equal CSS px in the WebView at the default zoom.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "width", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Width in CSS px (dp / pt).", + "complexTypes": [], + "type": "number" + }, + { + "name": "height", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Height in CSS px (dp / pt).", + "complexTypes": [], + "type": "number" + }, + { + "name": "description", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "SDK description of the size, for example `BANNER` or `ADAPTIVE`.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "isAdaptive", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "`true` for an adaptive size.", + "complexTypes": [], + "type": "boolean | undefined" + } + ] + }, + { + "name": "ShowOptions", + "slug": "showoptions", + "docs": "Options for `showRewarded()` and `showInterstitial()`: `adUnitId` (see AdUnitOptions) plus an optional placement.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "placementName", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Optional placement name configured in the LevelPlay dashboard (capping, pacing and reward per placement).\nOmit it to use the default placement.", + "complexTypes": [], + "type": "string | undefined" + } + ] + }, + { + "name": "IsReadyResult", + "slug": "isreadyresult", + "docs": "Result of `isReady()`.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "ready", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "`true` when a loaded ad can be shown right now.", + "complexTypes": [], + "type": "boolean" + } + ] + }, + { + "name": "IsReadyOptions", + "slug": "isreadyoptions", + "docs": "Options for `isReady()`: `adUnitId` (see AdUnitOptions) plus the format.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "format", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Format of the ad unit.", + "complexTypes": [ + "AdFormat" + ], + "type": "AdFormat" + } + ] + }, + { + "name": "Capabilities", + "slug": "capabilities", + "docs": "Result of `getCapabilities()`: what this platform build of the plugin can do. Check it instead of the platform\nname, so the same game code runs on Android, iOS and the web.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "banner", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Banner ads (`createBanner()` and friends) are available.", + "complexTypes": [], + "type": "boolean" + }, + { + "name": "nativeAd", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Native ads (`loadNativeAd()` and friends) are available.", + "complexTypes": [], + "type": "boolean" + }, + { + "name": "nativeAdTemplates", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Native ad templates this platform can render. Empty when `nativeAd` is `false`.", + "complexTypes": [ + "NativeAdTemplate" + ], + "type": "NativeAdTemplate[]" + }, + { + "name": "impressionData", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "The `impressionData` event is delivered.", + "complexTypes": [], + "type": "boolean" + }, + { + "name": "adInfoChanged", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "The `adInfoChanged` event is delivered (rewarded and interstitial only).", + "complexTypes": [], + "type": "boolean" + } + ] + }, + { + "name": "SegmentOptions", + "slug": "segmentoptions", + "docs": "Options for `setSegment()` (`LevelPlaySegment` / `LPMSegment`). Omitted fields are not sent.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "segmentName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Segment name.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "level", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "User level (integer).", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "isPaying", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "The user has paid in the app.", + "complexTypes": [], + "type": "boolean | undefined" + }, + { + "name": "userCreationDate", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "When the user was created, in milliseconds since the Unix epoch (`Date.now()` style).", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "iapTotal", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Total in-app purchase amount of the user (USD).", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "customParameters", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Custom segment parameters. SDK 9.6.1 limits: at most 5 pairs; keys and values 1-32 characters, letters and digits\nonly (`^[a-zA-Z0-9]*$`). The plugin rejects with `INVALID_ARGUMENT` instead of letting the SDK silently drop pairs.", + "complexTypes": [], + "type": "{ [key: string]: string; } | undefined" + } + ] + }, + { + "name": "DynamicUserIdResult", + "slug": "dynamicuseridresult", + "docs": "Result of `setDynamicUserId()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "valid", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "The SDK accepted the id (`LevelPlay.setDynamicUserId` returns a boolean on both platforms).", + "complexTypes": [], + "type": "boolean" + } + ] + }, + { + "name": "DynamicUserIdOptions", + "slug": "dynamicuseridoptions", + "docs": "Options for `setDynamicUserId()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "userId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Dynamic user id, forwarded in server-to-server reward callbacks. Can change during the session.", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "PlacementCappedResult", + "slug": "placementcappedresult", + "docs": "Result of `isPlacementCapped()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "capped", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "`true` when the placement reached its capping or pacing limit; showing it now fails.", + "complexTypes": [], + "type": "boolean" + } + ] + }, + { + "name": "PlacementCappedOptions", + "slug": "placementcappedoptions", + "docs": "Options for `isPlacementCapped()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "format", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Format of the placement. LevelPlay 9.6.1 has capping checks for rewarded and interstitial only.", + "complexTypes": [ + "AdFormat" + ], + "type": "AdFormat" + }, + { + "name": "placementName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Placement name from the LevelPlay dashboard.", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "GetRewardOptions", + "slug": "getrewardoptions", + "docs": "Options for `getReward()`: `adUnitId` (see AdUnitOptions) plus an optional placement.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "placementName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Placement whose reward to read. Its reward takes precedence over the ad unit reward. Omit for the ad unit reward.", + "complexTypes": [], + "type": "string | undefined" + } + ] + }, + { + "name": "BannerResult", + "slug": "bannerresult", + "docs": "Result of `createBanner()`, `showBanner()` and `setBannerLayout()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "bannerId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "The banner id.", + "complexTypes": [], + "type": "string" + }, + { + "name": "adSize", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Requested ad size (the creative may be smaller for adaptive sizes; it is centred in this frame).", + "complexTypes": [ + "AdSizeInfo" + ], + "type": "AdSizeInfo" + }, + { + "name": "frame", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Where the banner frame is (or will be, while hidden) in CSS px, relative to the WebView viewport. Use it to pad\ngame UI away from the banner.", + "complexTypes": [ + "Rect" + ], + "type": "Rect" + }, + { + "name": "visible", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "The banner view is currently visible.", + "complexTypes": [], + "type": "boolean" + } + ] + }, + { + "name": "Rect", + "slug": "rect", + "docs": "A rectangle in CSS px, relative to the top-left corner of the WebView viewport (the same space as\n`element.getBoundingClientRect()` without page scroll).", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "x", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Left edge in CSS px.", + "complexTypes": [], + "type": "number" + }, + { + "name": "y", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Top edge in CSS px.", + "complexTypes": [], + "type": "number" + }, + { + "name": "width", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Width in CSS px.", + "complexTypes": [], + "type": "number" + }, + { + "name": "height", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Height in CSS px.", + "complexTypes": [], + "type": "number" + } + ] + }, + { + "name": "CreateBannerOptions", + "slug": "createbanneroptions", + "docs": "Options for `createBanner()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "bannerId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Plugin-side id of this banner, used by every other banner method and in banner events. Lets one ad unit back\nseveral banners. Defaults to `adUnitId`.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "size", + "tags": [ + { + "text": "'ADAPTIVE'", + "name": "default" + }, + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Size preset.", + "complexTypes": [ + "BannerSize" + ], + "type": "BannerSize" + }, + { + "name": "customSize", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "`CUSTOM` only: the banner size. When `customSize` is set and `size` is omitted, `size` defaults to `CUSTOM`.", + "complexTypes": [ + "BannerCustomSize" + ], + "type": "BannerCustomSize" + }, + { + "name": "adaptiveWidth", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "`ADAPTIVE` only: width in CSS px to compute the adaptive size for. Defaults to the width of the WebView's safe\narea; in that case the plugin recreates and reloads the banner automatically when that width changes (rotation,\nsplit screen, window resize), keeping its id, layout and visibility. A fixed `adaptiveWidth` is never recreated.", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "placementName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Placement name (reporting only for banners). Applied through the banner config before the first load.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "bidFloor", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Bid floor in USD (`LevelPlayBannerAdView.Config.Builder.setBidFloor` / `LPMBannerAdViewConfigBuilder set(bidFloor:)`).", + "complexTypes": [], + "type": "number | undefined" + } + ] + }, + { + "name": "BannerCustomSize", + "slug": "bannercustomsize", + "docs": "Width and height of a `CUSTOM` banner, in CSS px (dp on Android, points on iOS).", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "width", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Width in CSS px (positive integer).", + "complexTypes": [], + "type": "number" + }, + { + "name": "height", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Height in CSS px (positive integer).", + "complexTypes": [], + "type": "number" + } + ] + }, + { + "name": "BannerIdOptions", + "slug": "banneridoptions", + "docs": "Identifies one banner created with `createBanner()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "bannerId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Plugin-side banner id passed to `createBanner()` (defaults to the ad unit id there).", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "SetBannerLayoutOptions", + "slug": "setbannerlayoutoptions", + "docs": "Options for `setBannerLayout()`: `bannerId` plus the layout fields (see BannerLayoutOptions).", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [] + }, + { + "name": "LoadNativeAdOptions", + "slug": "loadnativeadoptions", + "docs": "Options for `loadNativeAd()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "placementName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Placement name. LevelPlay 9.6.1 native ads are addressed by placement only (`LevelPlayNativeAd.Builder\n.withPlacementName` / `LevelPlayNativeAdBuilder withPlacementName:`); there is no ad unit id for native ads in\nthis SDK version. Omit it for the default placement.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "template", + "tags": [ + { + "text": "'medium'", + "name": "default" + }, + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Template used when the ad is shown.", + "complexTypes": [ + "NativeAdTemplate" + ], + "type": "NativeAdTemplate" + }, + { + "name": "style", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Template styling.", + "complexTypes": [ + "NativeAdTemplateStyle" + ], + "type": "NativeAdTemplateStyle" + } + ] + }, + { + "name": "NativeAdTemplateStyle", + "slug": "nativeadtemplatestyle", + "docs": "Optional styling of a native ad template. Colours are CSS hex strings (`#RRGGBB` or `#RRGGBBAA`).", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "backgroundColor", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Template background.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "titleColor", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Title text colour.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "bodyColor", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Body and advertiser text colour.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "callToActionBackgroundColor", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Call-to-action button background.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "callToActionTextColor", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Call-to-action button text colour.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "cornerRadius", + "tags": [ + { + "text": "0", + "name": "default" + }, + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Corner radius of the template in CSS px.", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "titleFont", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Title font.", + "complexTypes": [ + "NativeAdFont" + ], + "type": "NativeAdFont" + }, + { + "name": "bodyFont", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Body and advertiser font.", + "complexTypes": [ + "NativeAdFont" + ], + "type": "NativeAdFont" + }, + { + "name": "callToActionFont", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Call-to-action button font.", + "complexTypes": [ + "NativeAdFont" + ], + "type": "NativeAdFont" + } + ] + }, + { + "name": "NativeAdFont", + "slug": "nativeadfont", + "docs": "A font of a native ad template text. Omitted fields keep the template default (system font).", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "family", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Font family. Either a system family name (Android: `sans-serif`, `sans-serif-medium`, `serif`, `monospace` ...;\niOS: a `UIFont` family or PostScript name such as `Avenir Next` or `Menlo-Bold`), or the path of a `.ttf` / `.otf`\nfile inside the app's web assets, relative to the web root (for example `fonts/Inter-Bold.ttf`, the same file the\npage loads with `@font-face`). Unknown families fall back to the system font.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "size", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Font size in CSS px (dp / pt; not scaled by the system font size setting, like text in the WebView).", + "complexTypes": [], + "type": "number | undefined" + } + ] + }, + { + "name": "NativeAdRectOptions", + "slug": "nativeadrectoptions", + "docs": "Options for `showNativeAd()` and `setNativeAdRect()`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "rect", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Where the template goes, in CSS px relative to the WebView viewport (for example a placeholder element's\n`getBoundingClientRect()`).", + "complexTypes": [ + "Rect" + ], + "type": "Rect" + } + ] + }, + { + "name": "NativeAdIdOptions", + "slug": "nativeadidoptions", + "docs": "Identifies one native ad slot.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "nativeAdId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Plugin-side id of the native ad slot.", + "complexTypes": [], + "type": "string" + } + ] + }, + { + "name": "PluginListenerHandle", + "slug": "pluginlistenerhandle", + "docs": "", + "tags": [], + "methods": [], + "properties": [ + { + "name": "remove", + "tags": [], + "docs": "", + "complexTypes": [], + "type": "() => Promise" + } + ] + }, + { + "name": "AdEvent", + "slug": "adevent", + "docs": "Payload of the `loaded`, `displayed`, `clicked` and `closed` events.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "format", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Format of the ad unit that fired the event.", + "complexTypes": [ + "AdFormat" + ], + "type": "AdFormat" + }, + { + "name": "adUnitId", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Ad unit that fired the event.", + "complexTypes": [], + "type": "string" + }, + { + "name": "adInfo", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "Ad info, when the SDK provides it (not on `loadFailed`).", + "complexTypes": [ + "AdInfo" + ], + "type": "AdInfo" + } + ] + }, + { + "name": "AdErrorEvent", + "slug": "aderrorevent", + "docs": "Payload of the `loadFailed` and `displayFailed` events: the AdEvent fields plus `error`.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "error", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "What went wrong.", + "complexTypes": [ + "AdError" + ], + "type": "AdError" + } + ] + }, + { + "name": "AdRewardEvent", + "slug": "adrewardevent", + "docs": "Payload of the `rewarded` event: the AdEvent fields plus `reward`.", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "reward", + "tags": [ + { + "text": "0.1.0", + "name": "since" + } + ], + "docs": "The reward earned.", + "complexTypes": [ + "Reward" + ], + "type": "Reward" + } + ] + }, + { + "name": "ImpressionData", + "slug": "impressiondata", + "docs": "Impression-level revenue data (`LevelPlayImpressionData` on Android, `LPMImpressionData` on iOS). Every field the\nSDK 9.6.1 data class exposes is mapped; fields the SDK leaves empty are omitted.\n\nNot available in SDK 9.6.1 on either platform: `lifetimeRevenue` (removed from the impression data class). If the\nserver ever sends extra keys they are still visible in `allData`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "adFormat", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Which ad format produced the impression, as the SDK reports it (for example `Rewarded Video`, `Interstitial`,\n`Banner`, or `nativead` for impressions synthesised from native ad info).", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "auctionId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Auction id.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adUnitId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediation ad unit id (`mediationAdUnitId`).", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adUnitName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediation ad unit name (`mediationAdUnitName`).", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adNetwork", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediated network that served the ad.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "instanceName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediation instance name.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "instanceId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediation instance id.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "country", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Country code.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "placement", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Placement name of the impression.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "revenue", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Revenue of this impression in USD.", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "precision", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Revenue precision (for example `BID`, `RATE`, `ESTIMATED`).", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "ab", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "A/B test group.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "segmentName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Segment name, see `setSegment()`.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "encryptedCPM", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Encrypted CPM (`encryptedCPM` on Android, `encryptedCpm` on iOS).", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "creativeId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Creative id.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "conversionValue", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "iOS only: SKAdNetwork conversion value.", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "allData", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "The raw `allData` map of the SDK (`getAllData()` JSON on Android, `allData` dictionary on iOS). Keys and value\ntypes are SDK defined and may change between SDK versions.", + "complexTypes": [], + "type": "{ [key: string]: unknown; } | undefined" + } + ] + }, + { + "name": "BannerEvent", + "slug": "bannerevent", + "docs": "Payload of the `banner*` events.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "bannerId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Banner that fired the event.", + "complexTypes": [], + "type": "string" + }, + { + "name": "adUnitId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Ad unit of the banner.", + "complexTypes": [], + "type": "string" + }, + { + "name": "adInfo", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Ad info, when the SDK provides it (not on `bannerLoadFailed`).", + "complexTypes": [ + "AdInfo" + ], + "type": "AdInfo" + }, + { + "name": "frame", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Current frame of the banner in CSS px.", + "complexTypes": [ + "Rect" + ], + "type": "Rect" + } + ] + }, + { + "name": "BannerErrorEvent", + "slug": "bannererrorevent", + "docs": "Payload of `bannerLoadFailed` and `bannerDisplayFailed`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "error", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "What went wrong.", + "complexTypes": [ + "AdError" + ], + "type": "AdError" + } + ] + }, + { + "name": "NativeAdEvent", + "slug": "nativeadevent", + "docs": "Payload of the `nativeAd*` events.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "nativeAdId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Native ad slot that fired the event.", + "complexTypes": [], + "type": "string" + }, + { + "name": "placementName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Placement passed to `loadNativeAd()`, if any.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adInfo", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Ad info, when the SDK provides it (not on `nativeAdLoadFailed`).", + "complexTypes": [ + "NativeAdInfo" + ], + "type": "NativeAdInfo" + } + ] + }, + { + "name": "NativeAdInfo", + "slug": "nativeadinfo", + "docs": "Ad info of a native ad (`AdInfo` on Android / `ISAdInfo` on iOS: the older ironSource info type, which has no ad\nunit, ad id or placement fields).", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "auctionId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Auction id.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "adNetwork", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediated network that served the ad.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "instanceName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediation instance name.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "instanceId", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Mediation instance id.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "country", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Country code.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "revenue", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Impression revenue in USD.", + "complexTypes": [], + "type": "number | undefined" + }, + { + "name": "precision", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Revenue precision.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "ab", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "A/B test group.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "segmentName", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Segment name.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "encryptedCPM", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "Encrypted CPM.", + "complexTypes": [], + "type": "string | undefined" + }, + { + "name": "conversionValue", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "iOS only: SKAdNetwork conversion value.", + "complexTypes": [], + "type": "number | undefined" + } + ] + }, + { + "name": "NativeAdErrorEvent", + "slug": "nativeaderrorevent", + "docs": "Payload of `nativeAdLoadFailed`.", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "methods": [], + "properties": [ + { + "name": "error", + "tags": [ + { + "text": "0.3.0", + "name": "since" + } + ], + "docs": "What went wrong.", + "complexTypes": [ + "AdError" + ], + "type": "AdError" + } + ] + } + ], + "enums": [], + "typeAliases": [ + { + "name": "TrackingStatus", + "slug": "trackingstatus", + "docs": "iOS App Tracking Transparency status. `unavailable` on Android, on the web and on unknown future iOS values.", + "types": [ + { + "text": "'authorized'", + "complexTypes": [] + }, + { + "text": "'denied'", + "complexTypes": [] + }, + { + "text": "'restricted'", + "complexTypes": [] + }, + { + "text": "'notDetermined'", + "complexTypes": [] + }, + { + "text": "'unavailable'", + "complexTypes": [] + } + ] + }, + { + "name": "AdFormat", + "slug": "adformat", + "docs": "Full-screen ad formats (`loadRewarded` / `loadInterstitial` family and the `loaded` ... `rewarded` events).\nBanners and native ads have their own methods and `banner*` / `nativeAd*` events (since 0.3.0), so this union\nstays unchanged for 0.2.x code.", + "types": [ + { + "text": "'rewarded'", + "complexTypes": [] + }, + { + "text": "'interstitial'", + "complexTypes": [] + } + ] + }, + { + "name": "NativeAdTemplate", + "slug": "nativeadtemplate", + "docs": "Native ad template rendered by the plugin (the LevelPlay SDK ships no template views; the plugin provides its own\nlayouts, like Unity's Flutter and React Native wrappers do).\n\n- `small`: icon, title, advertiser, body, call to action; no media view. Recommended 300 x 175 or a row at least\n 90 px tall.\n- `medium`: the `small` assets plus a media view. Recommended 300 x 350.", + "types": [ + { + "text": "'small'", + "complexTypes": [] + }, + { + "text": "'medium'", + "complexTypes": [] + } + ] + }, + { + "name": "BannerSize", + "slug": "bannersize", + "docs": "Banner size presets, named after the SDK constants (`LevelPlayAdSize.BANNER` / `LPMAdSize.bannerSize()` ...).\n\n- `BANNER`: 320 x 50\n- `LARGE`: 320 x 90\n- `MEDIUM_RECTANGLE`: 300 x 250\n- `LEADERBOARD`: 728 x 90 (tablets)\n- `ADAPTIVE`: `LevelPlayAdSize.createAdaptiveAdSize(context, width)` / `LPMAdSize.createAdaptiveAdSize(withWidth:)`;\n the SDK picks the height (and BANNER or LEADERBOARD as fallback) for the given width. Requires a finished\n `initialize()`.\n- `CUSTOM`: `LevelPlayAdSize.createCustomSize(width, height)` / `LPMAdSize.customSizeWithWidth:height:` with\n `customSize`. Few networks fill custom sizes; prefer a preset or `ADAPTIVE`.", + "types": [ + { + "text": "'BANNER'", + "complexTypes": [] + }, + { + "text": "'LARGE'", + "complexTypes": [] + }, + { + "text": "'MEDIUM_RECTANGLE'", + "complexTypes": [] + }, + { + "text": "'LEADERBOARD'", + "complexTypes": [] + }, + { + "text": "'ADAPTIVE'", + "complexTypes": [] + }, + { + "text": "'CUSTOM'", + "complexTypes": [] + } + ] + } + ], + "pluginConfigs": [] +} \ No newline at end of file diff --git a/dist/esm/definitions.d.ts b/dist/esm/definitions.d.ts index d055414..429ae74 100644 --- a/dist/esm/definitions.d.ts +++ b/dist/esm/definitions.d.ts @@ -1,155 +1,1615 @@ import type { PluginListenerHandle } from '@capacitor/core'; -/** Full-screen ad formats supported by this plugin. Banners and native ads are intentionally not exposed. */ +/** + * Full-screen ad formats (`loadRewarded` / `loadInterstitial` family and the `loaded` ... `rewarded` events). + * Banners and native ads have their own methods and `banner*` / `nativeAd*` events (since 0.3.0), so this union + * stays unchanged for 0.2.x code. + * + * @since 0.1.0 + */ export type AdFormat = 'rewarded' | 'interstitial'; +/** + * Options for `initialize()`. + * + * @since 0.1.0 + */ export interface InitOptions { - /** LevelPlay app key from the LevelPlay dashboard (one per platform). */ + /** + * LevelPlay app key from the LevelPlay dashboard. Android and iOS apps have different keys. + * + * @since 0.1.0 + */ appKey: string; - /** Optional user id, needed for server-to-server reward callbacks and the Ad Quality user journey. */ + /** + * Optional user id. Needed for server-to-server reward callbacks and the Ad Quality user journey. + * + * @since 0.1.0 + */ userId?: string; /** - * Enable the LevelPlay Integration Test Suite (sets the `is_test_suite=enable` meta data before init). - * Call {@link LevelPlayPlugin.launchTestSuite} after init resolves. Never ship this enabled. + * Enable the LevelPlay Integration Test Suite: sets the `is_test_suite=enable` meta data before init. + * Call `launchTestSuite()` after `initialize` resolves. Never ship this enabled. + * + * @default false + * @since 0.1.0 */ testSuite?: boolean; - /** Turn on mediated ad network debug logs (`setAdaptersDebug`). Development only. */ + /** + * Turn on debug logs of the mediated ad network adapters (`LevelPlay.setAdaptersDebug(true)`). Development only. + * + * @default false + * @since 0.1.0 + */ adaptersDebug?: boolean; /** - * Privacy flags applied right before init (LevelPlay recommends setting them before the SDK starts). - * Same as calling {@link LevelPlayPlugin.setConsent} first. + * Privacy signals applied right before init (LevelPlay recommends setting them before the SDK starts). + * Same as calling `setConsent()` first. + * + * @since 0.1.0 */ consent?: ConsentOptions; } +/** + * Result of `initialize()` and `getSdkVersion()`. + * + * @since 0.1.0 + */ export interface InitResult { - /** Native LevelPlay SDK version, for example `9.6.1`. */ + /** + * Native LevelPlay SDK version, for example `9.6.1`. `web` on the web. + * + * @since 0.1.0 + */ sdkVersion: string; } /** * Privacy signals forwarded to LevelPlay (`LevelPlayPrivacySettings` on Android, `LPMPrivacySettings` on iOS). * Omitted fields are left untouched. + * + * @since 0.1.0 */ export interface ConsentOptions { - /** GDPR: `true` when the user consented to personalised ads / data processing. */ + /** + * GDPR: `true` when the user consented to personalised ads and data processing, `false` when they did not. + * For users in the EEA, UK and Switzerland pass `false` until a consent management platform (CMP) says otherwise. + * + * @since 0.1.0 + */ gdprConsent?: boolean; - /** CCPA / US state privacy: `true` when the user opted OUT of the sale or sharing of personal data. */ + /** + * CCPA and other US state privacy laws: `true` when the user opted OUT of the sale or sharing of personal data + * ("do not sell"), `false` otherwise. + * + * @since 0.1.0 + */ ccpaDoNotSell?: boolean; - /** COPPA: `true` when the user must be treated as a child (child-directed treatment). */ + /** + * COPPA: `true` when the user must be treated as a child (child-directed treatment). + * + * @since 0.1.0 + */ coppa?: boolean; } +/** + * Options for `setMetaData()`. + * + * @since 0.1.0 + */ export interface MetaDataOptions { + /** + * Meta data key, for example `is_deviceid_optout` or a network-specific flag from Unity's docs. + * + * @since 0.1.0 + */ key: string; + /** + * Meta data value, always a string (for example `"true"`). + * + * @since 0.1.0 + */ value: string; } +/** + * Identifies one ad unit. + * + * @since 0.1.0 + */ export interface AdUnitOptions { - /** Ad unit id from the LevelPlay dashboard. */ + /** + * Ad unit id from the LevelPlay dashboard (Ad units page). Android and iOS ad units have different ids. + * + * @since 0.1.0 + */ adUnitId: string; } +/** + * Options for `showRewarded()` and `showInterstitial()`: `adUnitId` (see AdUnitOptions) plus an optional placement. + * + * @since 0.1.0 + */ export interface ShowOptions extends AdUnitOptions { - /** Optional placement name configured in the LevelPlay dashboard (capping / pacing / reward per placement). */ + /** + * Optional placement name configured in the LevelPlay dashboard (capping, pacing and reward per placement). + * Omit it to use the default placement. + * + * @since 0.1.0 + */ placementName?: string; } +/** + * Options for `isReady()`: `adUnitId` (see AdUnitOptions) plus the format. + * + * @since 0.1.0 + */ export interface IsReadyOptions extends AdUnitOptions { + /** + * Format of the ad unit. + * + * @since 0.1.0 + */ format: AdFormat; } +/** + * Result of `isReady()`. + * + * @since 0.1.0 + */ export interface IsReadyResult { + /** + * `true` when a loaded ad can be shown right now. + * + * @since 0.1.0 + */ ready: boolean; } +/** + * The reward of a rewarded ad, as configured in the LevelPlay dashboard (per ad unit or placement). + * + * @since 0.1.0 + */ export interface Reward { + /** + * Name of the reward, for example `Coins`. + * + * @since 0.1.0 + */ name: string; + /** + * Amount of the reward. + * + * @since 0.1.0 + */ amount: number; } +/** + * Error reported by the SDK (load / display failures) or by the plugin. + * + * @since 0.1.0 + */ export interface AdError { + /** + * LevelPlay error code, for example `509` (no fill). `-1` is used by the plugin for "Ad not ready" and for the web + * stub. + * + * @since 0.1.0 + */ code: number; + /** + * Human readable message. + * + * @since 0.1.0 + */ message: string; } -/** Subset of the native `LevelPlayAdInfo` / `LPMAdInfo` that is useful in JavaScript. */ +/** + * Subset of the native `LevelPlayAdInfo` (Android) / `LPMAdInfo` (iOS) that is useful in JavaScript. + * Fields the SDK does not report are omitted. + * + * @since 0.1.0 + */ export interface AdInfo { + /** + * Unique id of this ad. + * + * @since 0.1.0 + */ adId?: string; + /** + * Ad unit id. + * + * @since 0.1.0 + */ adUnitId: string; + /** + * Ad unit name from the dashboard. + * + * @since 0.1.0 + */ adUnitName?: string; + /** + * Ad format as reported by the SDK. + * + * @since 0.1.0 + */ adFormat?: string; + /** + * Placement name of the show call, when one was used. + * + * @since 0.1.0 + */ placementName?: string; + /** + * Name of the mediated network that served the ad. + * + * @since 0.1.0 + */ adNetwork?: string; + /** + * Mediation instance name. + * + * @since 0.1.0 + */ instanceName?: string; + /** + * Mediation instance id. + * + * @since 0.1.0 + */ instanceId?: string; + /** + * Country code of the impression. + * + * @since 0.1.0 + */ country?: string; + /** + * Auction id. + * + * @since 0.1.0 + */ auctionId?: string; - /** Impression revenue in USD as reported by the SDK (may be absent before display). */ + /** + * Impression revenue in USD as reported by the SDK (may be absent or 0 before display). + * + * @since 0.1.0 + */ revenue?: number; + /** + * Revenue precision as reported by the SDK. + * + * @since 0.1.0 + */ precision?: string; + /** + * A/B test group of the user (`ab`). + * + * @since 0.3.0 + */ + ab?: string; + /** + * Segment name of the user, see `setSegment()`. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * Encrypted CPM (`encryptedCPM`). + * + * @since 0.3.0 + */ + encryptedCPM?: string; + /** + * Creative id of the served ad, when the network reports one. + * + * @since 0.3.0 + */ + creativeId?: string; + /** + * iOS only: SKAdNetwork conversion value (`LPMAdInfo.conversionValue`). Android's `LevelPlayAdInfo` has no such + * field in SDK 9.6.1, so it is always absent there. + * + * @since 0.3.0 + */ + conversionValue?: number; + /** + * Size of the ad. Banners only (`LevelPlayAdInfo.getAdSize()` / `LPMAdInfo.adSize`). + * + * @since 0.3.0 + */ + adSize?: AdSizeInfo; } +/** + * A resolved ad size as reported by the SDK (`LevelPlayAdSize` / `LPMAdSize`). Width and height are in dp on Android + * and points on iOS, which equal CSS px in the WebView at the default zoom. + * + * @since 0.3.0 + */ +export interface AdSizeInfo { + /** + * Width in CSS px (dp / pt). + * + * @since 0.3.0 + */ + width: number; + /** + * Height in CSS px (dp / pt). + * + * @since 0.3.0 + */ + height: number; + /** + * SDK description of the size, for example `BANNER` or `ADAPTIVE`. + * + * @since 0.3.0 + */ + description?: string; + /** + * `true` for an adaptive size. + * + * @since 0.3.0 + */ + isAdaptive?: boolean; +} +/** + * Result of `showRewarded()` and `showInterstitial()`, resolved after the ad + * closed or failed to display. + * + * @since 0.1.0 + */ export interface ShowResult { - /** The ad was displayed (`displayed` fired). */ + /** + * The ad was displayed (the `displayed` event fired). + * + * @since 0.1.0 + */ shown: boolean; - /** Rewarded only: the reward callback fired for this show. Grant the reward only when this is true. */ + /** + * Rewarded only: the reward callback fired for this show. Grant the reward only when this is `true`. + * Always `false` for interstitials. + * + * @since 0.1.0 + */ rewarded: boolean; + /** + * The reward, present when `rewarded` is `true`. + * + * @since 0.1.0 + */ reward?: Reward; - /** Present when the ad was not ready or failed to display. */ + /** + * Present when the ad was not ready (`code: -1`) or failed to display. + * + * @since 0.1.0 + */ error?: AdError; + /** + * Info of the displayed ad. + * + * @since 0.1.0 + */ adInfo?: AdInfo; } +/** + * Payload of the `loaded`, `displayed`, `clicked` and `closed` events. + * + * @since 0.1.0 + */ export interface AdEvent { + /** + * Format of the ad unit that fired the event. + * + * @since 0.1.0 + */ format: AdFormat; + /** + * Ad unit that fired the event. + * + * @since 0.1.0 + */ adUnitId: string; + /** + * Ad info, when the SDK provides it (not on `loadFailed`). + * + * @since 0.1.0 + */ adInfo?: AdInfo; } +/** + * Payload of the `loadFailed` and `displayFailed` events: the AdEvent fields plus `error`. + * + * @since 0.1.0 + */ export interface AdErrorEvent extends AdEvent { + /** + * What went wrong. + * + * @since 0.1.0 + */ error: AdError; } +/** + * Payload of the `rewarded` event: the AdEvent fields plus `reward`. + * + * @since 0.1.0 + */ export interface AdRewardEvent extends AdEvent { + /** + * The reward earned. + * + * @since 0.1.0 + */ reward: Reward; } +/** + * iOS App Tracking Transparency status. `unavailable` on Android, on the web and on unknown future iOS values. + * + * @since 0.1.0 + */ export type TrackingStatus = 'authorized' | 'denied' | 'restricted' | 'notDetermined' | 'unavailable'; +/** + * Result of `requestTrackingAuthorization()` and + * `getTrackingAuthorizationStatus()`. + * + * @since 0.1.0 + */ export interface TrackingResult { - /** iOS App Tracking Transparency status. Always `unavailable` on Android and web. */ + /** + * iOS App Tracking Transparency status. Always `unavailable` on Android and web. + * + * @since 0.1.0 + */ status: TrackingStatus; } +/** + * Result of `getCapabilities()`: what this platform build of the plugin can do. Check it instead of the platform + * name, so the same game code runs on Android, iOS and the web. + * + * @since 0.3.0 + */ +export interface Capabilities { + /** + * Banner ads (`createBanner()` and friends) are available. + * + * @since 0.3.0 + */ + banner: boolean; + /** + * Native ads (`loadNativeAd()` and friends) are available. + * + * @since 0.3.0 + */ + nativeAd: boolean; + /** + * Native ad templates this platform can render. Empty when `nativeAd` is `false`. + * + * @since 0.3.0 + */ + nativeAdTemplates: NativeAdTemplate[]; + /** + * The `impressionData` event is delivered. + * + * @since 0.3.0 + */ + impressionData: boolean; + /** + * The `adInfoChanged` event is delivered (rewarded and interstitial only). + * + * @since 0.3.0 + */ + adInfoChanged: boolean; +} +/** + * A rectangle in CSS px, relative to the top-left corner of the WebView viewport (the same space as + * `element.getBoundingClientRect()` without page scroll). + * + * @since 0.3.0 + */ +export interface Rect { + /** + * Left edge in CSS px. + * + * @since 0.3.0 + */ + x: number; + /** + * Top edge in CSS px. + * + * @since 0.3.0 + */ + y: number; + /** + * Width in CSS px. + * + * @since 0.3.0 + */ + width: number; + /** + * Height in CSS px. + * + * @since 0.3.0 + */ + height: number; +} +/** + * Banner size presets, named after the SDK constants (`LevelPlayAdSize.BANNER` / `LPMAdSize.bannerSize()` ...). + * + * - `BANNER`: 320 x 50 + * - `LARGE`: 320 x 90 + * - `MEDIUM_RECTANGLE`: 300 x 250 + * - `LEADERBOARD`: 728 x 90 (tablets) + * - `ADAPTIVE`: `LevelPlayAdSize.createAdaptiveAdSize(context, width)` / `LPMAdSize.createAdaptiveAdSize(withWidth:)`; + * the SDK picks the height (and BANNER or LEADERBOARD as fallback) for the given width. Requires a finished + * `initialize()`. + * - `CUSTOM`: `LevelPlayAdSize.createCustomSize(width, height)` / `LPMAdSize.customSizeWithWidth:height:` with + * `customSize`. Few networks fill custom sizes; prefer a preset or `ADAPTIVE`. + * + * @since 0.3.0 + */ +export type BannerSize = 'BANNER' | 'LARGE' | 'MEDIUM_RECTANGLE' | 'LEADERBOARD' | 'ADAPTIVE' | 'CUSTOM'; +/** + * Width and height of a `CUSTOM` banner, in CSS px (dp on Android, points on iOS). + * + * @since 0.3.0 + */ +export interface BannerCustomSize { + /** + * Width in CSS px (positive integer). + * + * @since 0.3.0 + */ + width: number; + /** + * Height in CSS px (positive integer). + * + * @since 0.3.0 + */ + height: number; +} +/** + * Vertical anchor of a banner inside the WebView's safe area. Banners are always horizontally centred; use + * `offsetX` to move them sideways. + * + * @since 0.3.0 + */ +export type BannerPosition = 'top' | 'bottom' | 'center'; +/** + * Identifies one banner created with `createBanner()`. + * + * @since 0.3.0 + */ +export interface BannerIdOptions { + /** + * Plugin-side banner id passed to `createBanner()` (defaults to the ad unit id there). + * + * @since 0.3.0 + */ + bannerId: string; +} +/** + * Where a banner sits over the WebView. + * + * @since 0.3.0 + */ +export interface BannerLayoutOptions { + /** + * Vertical anchor. + * + * @default 'bottom' + * @since 0.3.0 + */ + position?: BannerPosition; + /** + * Horizontal offset from the centred position in CSS px (positive moves right). + * + * @default 0 + * @since 0.3.0 + */ + offsetX?: number; + /** + * Vertical offset from the anchored position in CSS px (positive moves down). + * + * @default 0 + * @since 0.3.0 + */ + offsetY?: number; + /** + * Keep the banner inside the safe area (status bar, notch / display cutout, home indicator, navigation bar), measured + * against the WebView's own on-screen rect. Set `false` to anchor to the raw WebView edges. + * + * @default true + * @since 0.3.0 + */ + respectSafeArea?: boolean; +} +/** + * Options for `createBanner()`. + * + * @since 0.3.0 + */ +export interface CreateBannerOptions extends AdUnitOptions, BannerLayoutOptions { + /** + * Plugin-side id of this banner, used by every other banner method and in banner events. Lets one ad unit back + * several banners. Defaults to `adUnitId`. + * + * @since 0.3.0 + */ + bannerId?: string; + /** + * Size preset. + * + * @default 'ADAPTIVE' + * @since 0.3.0 + */ + size?: BannerSize; + /** + * `CUSTOM` only: the banner size. When `customSize` is set and `size` is omitted, `size` defaults to `CUSTOM`. + * + * @since 0.3.0 + */ + customSize?: BannerCustomSize; + /** + * `ADAPTIVE` only: width in CSS px to compute the adaptive size for. Defaults to the width of the WebView's safe + * area; in that case the plugin recreates and reloads the banner automatically when that width changes (rotation, + * split screen, window resize), keeping its id, layout and visibility. A fixed `adaptiveWidth` is never recreated. + * + * @since 0.3.0 + */ + adaptiveWidth?: number; + /** + * Placement name (reporting only for banners). Applied through the banner config before the first load. + * + * @since 0.3.0 + */ + placementName?: string; + /** + * Bid floor in USD (`LevelPlayBannerAdView.Config.Builder.setBidFloor` / `LPMBannerAdViewConfigBuilder set(bidFloor:)`). + * + * @since 0.3.0 + */ + bidFloor?: number; +} +/** + * Options for `setBannerLayout()`: `bannerId` plus the layout fields (see BannerLayoutOptions). + * + * @since 0.3.0 + */ +export interface SetBannerLayoutOptions extends BannerIdOptions, BannerLayoutOptions { +} +/** + * Result of `createBanner()`, `showBanner()` and `setBannerLayout()`. + * + * @since 0.3.0 + */ +export interface BannerResult { + /** + * The banner id. + * + * @since 0.3.0 + */ + bannerId: string; + /** + * Requested ad size (the creative may be smaller for adaptive sizes; it is centred in this frame). + * + * @since 0.3.0 + */ + adSize: AdSizeInfo; + /** + * Where the banner frame is (or will be, while hidden) in CSS px, relative to the WebView viewport. Use it to pad + * game UI away from the banner. + * + * @since 0.3.0 + */ + frame: Rect; + /** + * The banner view is currently visible. + * + * @since 0.3.0 + */ + visible: boolean; +} +/** + * Payload of the `banner*` events. + * + * @since 0.3.0 + */ +export interface BannerEvent { + /** + * Banner that fired the event. + * + * @since 0.3.0 + */ + bannerId: string; + /** + * Ad unit of the banner. + * + * @since 0.3.0 + */ + adUnitId: string; + /** + * Ad info, when the SDK provides it (not on `bannerLoadFailed`). + * + * @since 0.3.0 + */ + adInfo?: AdInfo; + /** + * Current frame of the banner in CSS px. + * + * @since 0.3.0 + */ + frame?: Rect; +} +/** + * Payload of `bannerLoadFailed` and `bannerDisplayFailed`. + * + * @since 0.3.0 + */ +export interface BannerErrorEvent extends BannerEvent { + /** + * What went wrong. + * + * @since 0.3.0 + */ + error: AdError; +} +/** + * Native ad template rendered by the plugin (the LevelPlay SDK ships no template views; the plugin provides its own + * layouts, like Unity's Flutter and React Native wrappers do). + * + * - `small`: icon, title, advertiser, body, call to action; no media view. Recommended 300 x 175 or a row at least + * 90 px tall. + * - `medium`: the `small` assets plus a media view. Recommended 300 x 350. + * + * @since 0.3.0 + */ +export type NativeAdTemplate = 'small' | 'medium'; +/** + * Optional styling of a native ad template. Colours are CSS hex strings (`#RRGGBB` or `#RRGGBBAA`). + * + * @since 0.3.0 + */ +export interface NativeAdTemplateStyle { + /** + * Template background. + * + * @since 0.3.0 + */ + backgroundColor?: string; + /** + * Title text colour. + * + * @since 0.3.0 + */ + titleColor?: string; + /** + * Body and advertiser text colour. + * + * @since 0.3.0 + */ + bodyColor?: string; + /** + * Call-to-action button background. + * + * @since 0.3.0 + */ + callToActionBackgroundColor?: string; + /** + * Call-to-action button text colour. + * + * @since 0.3.0 + */ + callToActionTextColor?: string; + /** + * Corner radius of the template in CSS px. + * + * @default 0 + * @since 0.3.0 + */ + cornerRadius?: number; + /** + * Title font. + * + * @since 0.3.0 + */ + titleFont?: NativeAdFont; + /** + * Body and advertiser font. + * + * @since 0.3.0 + */ + bodyFont?: NativeAdFont; + /** + * Call-to-action button font. + * + * @since 0.3.0 + */ + callToActionFont?: NativeAdFont; +} +/** + * A font of a native ad template text. Omitted fields keep the template default (system font). + * + * @since 0.3.0 + */ +export interface NativeAdFont { + /** + * Font family. Either a system family name (Android: `sans-serif`, `sans-serif-medium`, `serif`, `monospace` ...; + * iOS: a `UIFont` family or PostScript name such as `Avenir Next` or `Menlo-Bold`), or the path of a `.ttf` / `.otf` + * file inside the app's web assets, relative to the web root (for example `fonts/Inter-Bold.ttf`, the same file the + * page loads with `@font-face`). Unknown families fall back to the system font. + * + * @since 0.3.0 + */ + family?: string; + /** + * Font size in CSS px (dp / pt; not scaled by the system font size setting, like text in the WebView). + * + * @since 0.3.0 + */ + size?: number; +} +/** + * Identifies one native ad slot. + * + * @since 0.3.0 + */ +export interface NativeAdIdOptions { + /** + * Plugin-side id of the native ad slot. + * + * @since 0.3.0 + */ + nativeAdId: string; +} +/** + * Options for `loadNativeAd()`. + * + * @since 0.3.0 + */ +export interface LoadNativeAdOptions extends NativeAdIdOptions { + /** + * Placement name. LevelPlay 9.6.1 native ads are addressed by placement only (`LevelPlayNativeAd.Builder + * .withPlacementName` / `LevelPlayNativeAdBuilder withPlacementName:`); there is no ad unit id for native ads in + * this SDK version. Omit it for the default placement. + * + * @since 0.3.0 + */ + placementName?: string; + /** + * Template used when the ad is shown. + * + * @default 'medium' + * @since 0.3.0 + */ + template?: NativeAdTemplate; + /** + * Template styling. + * + * @since 0.3.0 + */ + style?: NativeAdTemplateStyle; +} +/** + * Options for `showNativeAd()` and `setNativeAdRect()`. + * + * @since 0.3.0 + */ +export interface NativeAdRectOptions extends NativeAdIdOptions { + /** + * Where the template goes, in CSS px relative to the WebView viewport (for example a placeholder element's + * `getBoundingClientRect()`). + * + * @since 0.3.0 + */ + rect: Rect; +} +/** + * Ad info of a native ad (`AdInfo` on Android / `ISAdInfo` on iOS: the older ironSource info type, which has no ad + * unit, ad id or placement fields). + * + * @since 0.3.0 + */ +export interface NativeAdInfo { + /** + * Auction id. + * + * @since 0.3.0 + */ + auctionId?: string; + /** + * Mediated network that served the ad. + * + * @since 0.3.0 + */ + adNetwork?: string; + /** + * Mediation instance name. + * + * @since 0.3.0 + */ + instanceName?: string; + /** + * Mediation instance id. + * + * @since 0.3.0 + */ + instanceId?: string; + /** + * Country code. + * + * @since 0.3.0 + */ + country?: string; + /** + * Impression revenue in USD. + * + * @since 0.3.0 + */ + revenue?: number; + /** + * Revenue precision. + * + * @since 0.3.0 + */ + precision?: string; + /** + * A/B test group. + * + * @since 0.3.0 + */ + ab?: string; + /** + * Segment name. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * Encrypted CPM. + * + * @since 0.3.0 + */ + encryptedCPM?: string; + /** + * iOS only: SKAdNetwork conversion value. + * + * @since 0.3.0 + */ + conversionValue?: number; +} +/** + * Payload of the `nativeAd*` events. + * + * @since 0.3.0 + */ +export interface NativeAdEvent { + /** + * Native ad slot that fired the event. + * + * @since 0.3.0 + */ + nativeAdId: string; + /** + * Placement passed to `loadNativeAd()`, if any. + * + * @since 0.3.0 + */ + placementName?: string; + /** + * Ad info, when the SDK provides it (not on `nativeAdLoadFailed`). + * + * @since 0.3.0 + */ + adInfo?: NativeAdInfo; +} +/** + * Payload of `nativeAdLoadFailed`. + * + * @since 0.3.0 + */ +export interface NativeAdErrorEvent extends NativeAdEvent { + /** + * What went wrong. + * + * @since 0.3.0 + */ + error: AdError; +} +/** + * Impression-level revenue data (`LevelPlayImpressionData` on Android, `LPMImpressionData` on iOS). Every field the + * SDK 9.6.1 data class exposes is mapped; fields the SDK leaves empty are omitted. + * + * Not available in SDK 9.6.1 on either platform: `lifetimeRevenue` (removed from the impression data class). If the + * server ever sends extra keys they are still visible in `allData`. + * + * @since 0.3.0 + */ +export interface ImpressionData { + /** + * Which ad format produced the impression, as the SDK reports it (for example `Rewarded Video`, `Interstitial`, + * `Banner`, or `nativead` for impressions synthesised from native ad info). + * + * @since 0.3.0 + */ + adFormat?: string; + /** + * Auction id. + * + * @since 0.3.0 + */ + auctionId?: string; + /** + * Mediation ad unit id (`mediationAdUnitId`). + * + * @since 0.3.0 + */ + adUnitId?: string; + /** + * Mediation ad unit name (`mediationAdUnitName`). + * + * @since 0.3.0 + */ + adUnitName?: string; + /** + * Mediated network that served the ad. + * + * @since 0.3.0 + */ + adNetwork?: string; + /** + * Mediation instance name. + * + * @since 0.3.0 + */ + instanceName?: string; + /** + * Mediation instance id. + * + * @since 0.3.0 + */ + instanceId?: string; + /** + * Country code. + * + * @since 0.3.0 + */ + country?: string; + /** + * Placement name of the impression. + * + * @since 0.3.0 + */ + placement?: string; + /** + * Revenue of this impression in USD. + * + * @since 0.3.0 + */ + revenue?: number; + /** + * Revenue precision (for example `BID`, `RATE`, `ESTIMATED`). + * + * @since 0.3.0 + */ + precision?: string; + /** + * A/B test group. + * + * @since 0.3.0 + */ + ab?: string; + /** + * Segment name, see `setSegment()`. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * Encrypted CPM (`encryptedCPM` on Android, `encryptedCpm` on iOS). + * + * @since 0.3.0 + */ + encryptedCPM?: string; + /** + * Creative id. + * + * @since 0.3.0 + */ + creativeId?: string; + /** + * iOS only: SKAdNetwork conversion value. + * + * @since 0.3.0 + */ + conversionValue?: number; + /** + * The raw `allData` map of the SDK (`getAllData()` JSON on Android, `allData` dictionary on iOS). Keys and value + * types are SDK defined and may change between SDK versions. + * + * @since 0.3.0 + */ + allData?: { + [key: string]: unknown; + }; +} +/** + * Options for `isPlacementCapped()`. + * + * @since 0.3.0 + */ +export interface PlacementCappedOptions { + /** + * Format of the placement. LevelPlay 9.6.1 has capping checks for rewarded and interstitial only. + * + * @since 0.3.0 + */ + format: AdFormat; + /** + * Placement name from the LevelPlay dashboard. + * + * @since 0.3.0 + */ + placementName: string; +} +/** + * Result of `isPlacementCapped()`. + * + * @since 0.3.0 + */ +export interface PlacementCappedResult { + /** + * `true` when the placement reached its capping or pacing limit; showing it now fails. + * + * @since 0.3.0 + */ + capped: boolean; +} +/** + * Options for `getReward()`: `adUnitId` (see AdUnitOptions) plus an optional placement. + * + * @since 0.3.0 + */ +export interface GetRewardOptions extends AdUnitOptions { + /** + * Placement whose reward to read. Its reward takes precedence over the ad unit reward. Omit for the ad unit reward. + * + * @since 0.3.0 + */ + placementName?: string; +} +/** + * Options for `setSegment()` (`LevelPlaySegment` / `LPMSegment`). Omitted fields are not sent. + * + * @since 0.3.0 + */ +export interface SegmentOptions { + /** + * Segment name. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * User level (integer). + * + * @since 0.3.0 + */ + level?: number; + /** + * The user has paid in the app. + * + * @since 0.3.0 + */ + isPaying?: boolean; + /** + * When the user was created, in milliseconds since the Unix epoch (`Date.now()` style). + * + * @since 0.3.0 + */ + userCreationDate?: number; + /** + * Total in-app purchase amount of the user (USD). + * + * @since 0.3.0 + */ + iapTotal?: number; + /** + * Custom segment parameters. SDK 9.6.1 limits: at most 5 pairs; keys and values 1-32 characters, letters and digits + * only (`^[a-zA-Z0-9]*$`). The plugin rejects with `INVALID_ARGUMENT` instead of letting the SDK silently drop pairs. + * + * @since 0.3.0 + */ + customParameters?: { + [key: string]: string; + }; +} +/** + * Options for `setDynamicUserId()`. + * + * @since 0.3.0 + */ +export interface DynamicUserIdOptions { + /** + * Dynamic user id, forwarded in server-to-server reward callbacks. Can change during the session. + * + * @since 0.3.0 + */ + userId: string; +} +/** + * Result of `setDynamicUserId()`. + * + * @since 0.3.0 + */ +export interface DynamicUserIdResult { + /** + * The SDK accepted the id (`LevelPlay.setDynamicUserId` returns a boolean on both platforms). + * + * @since 0.3.0 + */ + valid: boolean; +} +/** + * Event names emitted by the plugin. + * + * @since 0.1.0 + */ +export type LevelPlayEventName = 'loaded' | 'loadFailed' | 'displayed' | 'displayFailed' | 'clicked' | 'closed' | 'rewarded' | 'adInfoChanged' | 'impressionData' | 'bannerLoaded' | 'bannerLoadFailed' | 'bannerDisplayed' | 'bannerDisplayFailed' | 'bannerClicked' | 'bannerExpanded' | 'bannerCollapsed' | 'bannerLeftApplication' | 'nativeAdLoaded' | 'nativeAdLoadFailed' | 'nativeAdImpression' | 'nativeAdClicked'; +/** + * Unity LevelPlay ads (ad-unit API): rewarded, interstitial and (since 0.3.0) banner and native ads, impression-level + * revenue, segments and placement capping. + * + * @since 0.1.0 + */ export interface LevelPlayPlugin { /** - * Initialise the LevelPlay SDK. Resolves on `onInitSuccess`, rejects with the init error otherwise. - * Calling it again after a successful init resolves immediately. Load ads only after this resolves. + * Initialise the LevelPlay SDK (`LevelPlay.init`). Resolves on init success, rejects with the init error + * (code and message from the SDK) otherwise. Calling it again after a successful init resolves immediately; + * concurrent calls share one init. Load ads only after this resolves. + * + * Set consent (and on iOS ask for ATT) before calling it. + * + * On the web it rejects as unimplemented. + * + * @since 0.1.0 */ initialize(options: InitOptions): Promise; - /** Native SDK version (available before init). */ + /** + * Native LevelPlay SDK version. Works before init. + * + * @since 0.1.0 + */ getSdkVersion(): Promise; - /** Forward GDPR / CCPA / COPPA signals. Call before {@link initialize} when you can. */ + /** + * Forward GDPR / CCPA / COPPA signals to LevelPlay. Call it before `initialize()` when you + * can, and again whenever the user changes their choice. + * + * @since 0.1.0 + */ setConsent(options: ConsentOptions): Promise; - /** Raw `LevelPlay.setMetaData(key, value)` for network-specific flags. Call before init. */ + /** + * Raw `LevelPlay.setMetaData(key, value)` for SDK or network-specific flags. Call it before init. + * + * @since 0.1.0 + */ setMetaData(options: MetaDataOptions): Promise; /** - * iOS: show the App Tracking Transparency prompt (needs `NSUserTrackingUsageDescription` in Info.plist) and resolve - * with the resulting status. Call it before {@link initialize}. Android / web: resolves `unavailable`. + * iOS: show the App Tracking Transparency prompt and resolve with the resulting status. Needs + * `NSUserTrackingUsageDescription` in `Info.plist`. iOS only shows the prompt once; later calls resolve the stored + * status. Call it before `initialize()`, while the app is active. + * + * Android and web: resolves `unavailable`. + * + * @since 0.1.0 */ requestTrackingAuthorization(): Promise; - /** Current ATT status without prompting (iOS). Android / web: `unavailable`. */ + /** + * Current App Tracking Transparency status without prompting (iOS). Android and web: `unavailable`. + * + * @since 0.1.0 + */ getTrackingAuthorizationStatus(): Promise; /** - * Start loading a rewarded ad for the ad unit (the ad object is created on first use and reused). - * Resolves once the request is issued; the outcome arrives as `loaded` / `loadFailed` events. + * Start loading a rewarded ad for the ad unit. The native ad object is created on first use and reused for the + * ad unit. Resolves once the request is issued; the outcome arrives as a `loaded` or `loadFailed` event. + * Load the next ad after each show. + * + * @since 0.1.0 */ loadRewarded(options: AdUnitOptions): Promise; /** - * Show a loaded rewarded ad. Resolves after the ad closes (or failed to display) with what happened. - * Never rejects for "not ready": resolves `{ shown: false, error }` instead. + * Show a loaded rewarded ad. Resolves after the ad closed (or failed to display) with what happened. The reward + * and close callbacks can arrive in either order on some networks, so the plugin waits up to 1 second after the close + * for a late reward. Never rejects for "not ready": resolves `{ shown: false, rewarded: false, error }` instead. + * + * @since 0.1.0 */ showRewarded(options: ShowOptions): Promise; - /** Start loading an interstitial ad (see {@link loadRewarded}). */ + /** + * Start loading an interstitial ad for the ad unit. Works like `loadRewarded()`. + * + * @since 0.1.0 + */ loadInterstitial(options: AdUnitOptions): Promise; - /** Show a loaded interstitial. Resolves after it closes (or failed to display). */ + /** + * Show a loaded interstitial. Resolves after it closed (or failed to display). Never rejects for "not ready". + * + * @since 0.1.0 + */ showInterstitial(options: ShowOptions): Promise; - /** `isAdReady()` of the ad object for this ad unit (`false` when it was never loaded). */ + /** + * `isAdReady()` of the native ad object for this ad unit. `false` when the ad unit was never loaded. + * + * @since 0.1.0 + */ isReady(options: IsReadyOptions): Promise; - /** Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first. */ + /** + * Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first. + * Development builds only. Rejects on the web. + * + * @since 0.1.0 + */ launchTestSuite(): Promise; - /** Log the LevelPlay integration helper report to the native console (development only). */ + /** + * Write the LevelPlay integration helper report to the native log (Xcode console; Android logcat tag + * `IntegrationHelper`): SDK, adapter and network SDK versions, each `VERIFIED` or not. Development only. + * + * @since 0.1.0 + */ validateIntegration(): Promise; + /** + * What this platform supports (banners, native ad templates, impression data, `adInfoChanged`). Works before init. + * Web: everything `false`. + * + * @since 0.3.0 + */ + getCapabilities(): Promise; + /** + * Set the user segment (`LevelPlay.setSegment` with a `LevelPlaySegment` / `LPMSegment`). Call it before + * `initialize()` so the first ad requests use it; later calls apply to the following requests. Rejects with + * `INVALID_ARGUMENT` when `customParameters` break the SDK limits. Web: no-op. + * + * @since 0.3.0 + */ + setSegment(options: SegmentOptions): Promise; + /** + * Set or change the dynamic user id used in server-to-server reward callbacks (`LevelPlay.setDynamicUserId` on + * both platforms). Set it before `showRewarded()`. Web: resolves `{ valid: false }`. + * + * @since 0.3.0 + */ + setDynamicUserId(options: DynamicUserIdOptions): Promise; + /** + * Whether a rewarded or interstitial placement is capped right now (static + * `LevelPlayRewardedAd.isPlacementCapped` / `LevelPlayInterstitialAd.isPlacementCapped` on Android, + * `LPMRewardedAd.isPlacementCapped:` / `LPMInterstitialAd.isPlacementCapped:` on iOS). Works without a loaded ad. + * Web: `{ capped: false }`. + * + * @since 0.3.0 + */ + isPlacementCapped(options: PlacementCappedOptions): Promise; + /** + * The reward configured for a rewarded ad unit or one of its placements (`LevelPlayRewardedAd.getReward(placement)` / + * `LPMRewardedAd getReward(placementName:)`), for "watch a video for N coins" buttons. The SDK returns + * `{ name: '', amount: 0 }` when it has no reward configuration (for example before init). Web: the same empty + * reward. + * + * @since 0.3.0 + */ + getReward(options: GetRewardOptions): Promise; + /** + * Create a banner (`LevelPlayBannerAdView` / `LPMBannerAdView`) for the ad unit and attach it, hidden, in a + * pass-through overlay above the WebView. Requires a finished `initialize()` (`NOT_INITIALIZED` otherwise). Rejects + * with `ALREADY_EXISTS` when `bannerId` is in use; destroy it first. Does not load: call `loadBanner()`. + * Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + createBanner(options: CreateBannerOptions): Promise; + /** + * Load the banner (`loadAd()` / `loadAdWithViewController:`). The outcome arrives as `bannerLoaded` or + * `bannerLoadFailed`; after the first load the SDK refreshes the banner on the dashboard interval. The SDK accepts + * one load per banner object: calling it again has no effect (Android logs "Banner load already called"), so to retry + * right away after `bannerLoadFailed`, destroy the banner and create it again. Web: no-op. + * + * @since 0.3.0 + */ + loadBanner(options: BannerIdOptions): Promise; + /** + * Make the banner visible and resume auto refresh (`resumeAutoRefresh`). Can be called before the load finished; + * the creative appears when it arrives. Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + showBanner(options: BannerIdOptions): Promise; + /** + * Hide the banner and pause auto refresh (`pauseAutoRefresh`) so hidden banners do not burn impressions. The view + * stays attached; `showBanner()` brings it back. Web: no-op. + * + * @since 0.3.0 + */ + hideBanner(options: BannerIdOptions): Promise; + /** + * Move a banner (position, offsets, safe area). Resolves with the new frame. Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + setBannerLayout(options: SetBannerLayoutOptions): Promise; + /** + * Remove the banner from the screen and `destroy()` it. A destroyed banner cannot be reused; create a new one. + * Resolves also for unknown ids. Web: no-op. + * + * @since 0.3.0 + */ + destroyBanner(options: BannerIdOptions): Promise; + /** + * Load a native ad into a slot. Following the SDK rule "one native ad object per load", it destroys the slot's + * previous ad (hiding it if shown), builds a new `LevelPlayNativeAd` with the placement and loads it. The outcome + * arrives as `nativeAdLoaded` or `nativeAdLoadFailed`. Requires a finished `initialize()`. Rejects with + * `UNSUPPORTED` when `getCapabilities().nativeAd` is `false` or the template is not listed there. Web: rejects as + * unimplemented. + * + * @since 0.3.0 + */ + loadNativeAd(options: LoadNativeAdOptions): Promise; + /** + * Render the loaded native ad into its template, register the asset views with the SDK + * (`NativeAdLayout.registerNativeAdViews` / `ISNativeAdView registerNativeAdViews:`) and place it at `rect` above the + * WebView. Rejects with `NOT_LOADED` before `nativeAdLoaded`. The impression is reported by `nativeAdImpression`. + * Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + showNativeAd(options: NativeAdRectOptions): Promise; + /** + * Move or resize a shown native ad, for example after the placeholder element moved. Web: no-op. + * + * @since 0.3.0 + */ + setNativeAdRect(options: NativeAdRectOptions): Promise; + /** + * Hide a shown native ad (the view stays registered; `showNativeAd()` shows it again). Web: no-op. + * + * @since 0.3.0 + */ + hideNativeAd(options: NativeAdIdOptions): Promise; + /** + * Remove the native ad view and `destroyAd()` it. Resolves also for unknown ids. Web: no-op. + * + * @since 0.3.0 + */ + destroyNativeAd(options: NativeAdIdOptions): Promise; + /** + * An ad finished loading for the ad unit and can be shown. + * + * @since 0.1.0 + */ addListener(eventName: 'loaded', listenerFunc: (event: AdEvent) => void): Promise; + /** + * Loading failed, for example `509` (no fill). Retry later with a backoff. + * + * @since 0.1.0 + */ addListener(eventName: 'loadFailed', listenerFunc: (event: AdErrorEvent) => void): Promise; + /** + * The ad was displayed (impression). `adInfo.revenue` is available here. + * + * @since 0.1.0 + */ addListener(eventName: 'displayed', listenerFunc: (event: AdEvent) => void): Promise; + /** + * The ad failed to display. The pending show call resolves with the same error. + * + * @since 0.1.0 + */ addListener(eventName: 'displayFailed', listenerFunc: (event: AdErrorEvent) => void): Promise; + /** + * The user clicked the ad. + * + * @since 0.1.0 + */ addListener(eventName: 'clicked', listenerFunc: (event: AdEvent) => void): Promise; + /** + * The ad was closed and the app is back in front. + * + * @since 0.1.0 + */ addListener(eventName: 'closed', listenerFunc: (event: AdEvent) => void): Promise; + /** + * Rewarded only: the user earned the reward. Can fire before or after `closed`. + * + * @since 0.1.0 + */ addListener(eventName: 'rewarded', listenerFunc: (event: AdRewardEvent) => void): Promise; + /** + * Rewarded and interstitial: the SDK reloaded the ad in the background and its ad info (network, revenue ...) + * changed (`onAdInfoChanged` / `didChangeAdInfo:`). Banners and native ads have no such callback in SDK 9.6.1. + * + * @since 0.3.0 + */ + addListener(eventName: 'adInfoChanged', listenerFunc: (event: AdEvent) => void): Promise; + /** + * Impression-level revenue data for every rewarded, interstitial and banner impression (per-ad + * `setImpressionDataListener` / `setImpressionDataDelegate:`, attached by the plugin to every ad object it creates), + * plus native ad impressions synthesised from the native ad info (`adFormat: 'nativead'`, `adInfo` fields only). + * Add the listener at any time, also before `initialize()`; nothing is delivered before the first ad shows. + * + * @since 0.3.0 + */ + addListener(eventName: 'impressionData', listenerFunc: (event: ImpressionData) => void): Promise; + /** + * A banner loaded or refreshed with a new creative. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerLoaded', listenerFunc: (event: BannerEvent) => void): Promise; + /** + * A banner load (or refresh) failed. The SDK keeps retrying on its refresh interval. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerLoadFailed', listenerFunc: (event: BannerErrorEvent) => void): Promise; + /** + * A banner creative was displayed on screen (impression). + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerDisplayed', listenerFunc: (event: BannerEvent) => void): Promise; + /** + * A banner creative failed to display. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerDisplayFailed', listenerFunc: (event: BannerErrorEvent) => void): Promise; + /** + * The user clicked a banner. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerClicked', listenerFunc: (event: BannerEvent) => void): Promise; + /** + * A banner opened full screen (for example an expandable creative). Pause the game. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerExpanded', listenerFunc: (event: BannerEvent) => void): Promise; + /** + * A banner returned to its normal size. Resume the game. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerCollapsed', listenerFunc: (event: BannerEvent) => void): Promise; + /** + * A banner click sent the user out of the app (browser or store). + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerLeftApplication', listenerFunc: (event: BannerEvent) => void): Promise; + /** + * A native ad loaded and can be shown with `showNativeAd()`. + * + * @since 0.3.0 + */ + addListener(eventName: 'nativeAdLoaded', listenerFunc: (event: NativeAdEvent) => void): Promise; + /** + * A native ad failed to load. Load again later (the plugin already destroyed the failed ad object). + * + * @since 0.3.0 + */ + addListener(eventName: 'nativeAdLoadFailed', listenerFunc: (event: NativeAdErrorEvent) => void): Promise; + /** + * A shown native ad recorded its impression (first pixel visible). + * + * @since 0.3.0 + */ + addListener(eventName: 'nativeAdImpression', listenerFunc: (event: NativeAdEvent) => void): Promise; + /** + * The user clicked a native ad. + * + * @since 0.3.0 + */ + addListener(eventName: 'nativeAdClicked', listenerFunc: (event: NativeAdEvent) => void): Promise; + /** + * Remove every listener of this plugin. + * + * @since 0.1.0 + */ removeAllListeners(): Promise; } -/** Event names emitted by the plugin. */ -export type LevelPlayEventName = 'loaded' | 'loadFailed' | 'displayed' | 'displayFailed' | 'clicked' | 'closed' | 'rewarded'; diff --git a/dist/esm/definitions.js.map b/dist/esm/definitions.js.map index 2344ece..571ed4a 100644 --- a/dist/esm/definitions.js.map +++ b/dist/esm/definitions.js.map @@ -1 +1 @@ -{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\n/** Full-screen ad formats supported by this plugin. Banners and native ads are intentionally not exposed. */\nexport type AdFormat = 'rewarded' | 'interstitial';\n\nexport interface InitOptions {\n /** LevelPlay app key from the LevelPlay dashboard (one per platform). */\n appKey: string;\n /** Optional user id, needed for server-to-server reward callbacks and the Ad Quality user journey. */\n userId?: string;\n /**\n * Enable the LevelPlay Integration Test Suite (sets the `is_test_suite=enable` meta data before init).\n * Call {@link LevelPlayPlugin.launchTestSuite} after init resolves. Never ship this enabled.\n */\n testSuite?: boolean;\n /** Turn on mediated ad network debug logs (`setAdaptersDebug`). Development only. */\n adaptersDebug?: boolean;\n /**\n * Privacy flags applied right before init (LevelPlay recommends setting them before the SDK starts).\n * Same as calling {@link LevelPlayPlugin.setConsent} first.\n */\n consent?: ConsentOptions;\n}\n\nexport interface InitResult {\n /** Native LevelPlay SDK version, for example `9.6.1`. */\n sdkVersion: string;\n}\n\n/**\n * Privacy signals forwarded to LevelPlay (`LevelPlayPrivacySettings` on Android, `LPMPrivacySettings` on iOS).\n * Omitted fields are left untouched.\n */\nexport interface ConsentOptions {\n /** GDPR: `true` when the user consented to personalised ads / data processing. */\n gdprConsent?: boolean;\n /** CCPA / US state privacy: `true` when the user opted OUT of the sale or sharing of personal data. */\n ccpaDoNotSell?: boolean;\n /** COPPA: `true` when the user must be treated as a child (child-directed treatment). */\n coppa?: boolean;\n}\n\nexport interface MetaDataOptions {\n key: string;\n value: string;\n}\n\nexport interface AdUnitOptions {\n /** Ad unit id from the LevelPlay dashboard. */\n adUnitId: string;\n}\n\nexport interface ShowOptions extends AdUnitOptions {\n /** Optional placement name configured in the LevelPlay dashboard (capping / pacing / reward per placement). */\n placementName?: string;\n}\n\nexport interface IsReadyOptions extends AdUnitOptions {\n format: AdFormat;\n}\n\nexport interface IsReadyResult {\n ready: boolean;\n}\n\nexport interface Reward {\n name: string;\n amount: number;\n}\n\nexport interface AdError {\n code: number;\n message: string;\n}\n\n/** Subset of the native `LevelPlayAdInfo` / `LPMAdInfo` that is useful in JavaScript. */\nexport interface AdInfo {\n adId?: string;\n adUnitId: string;\n adUnitName?: string;\n adFormat?: string;\n placementName?: string;\n adNetwork?: string;\n instanceName?: string;\n instanceId?: string;\n country?: string;\n auctionId?: string;\n /** Impression revenue in USD as reported by the SDK (may be absent before display). */\n revenue?: number;\n precision?: string;\n}\n\nexport interface ShowResult {\n /** The ad was displayed (`displayed` fired). */\n shown: boolean;\n /** Rewarded only: the reward callback fired for this show. Grant the reward only when this is true. */\n rewarded: boolean;\n reward?: Reward;\n /** Present when the ad was not ready or failed to display. */\n error?: AdError;\n adInfo?: AdInfo;\n}\n\nexport interface AdEvent {\n format: AdFormat;\n adUnitId: string;\n adInfo?: AdInfo;\n}\n\nexport interface AdErrorEvent extends AdEvent {\n error: AdError;\n}\n\nexport interface AdRewardEvent extends AdEvent {\n reward: Reward;\n}\n\nexport type TrackingStatus = 'authorized' | 'denied' | 'restricted' | 'notDetermined' | 'unavailable';\n\nexport interface TrackingResult {\n /** iOS App Tracking Transparency status. Always `unavailable` on Android and web. */\n status: TrackingStatus;\n}\n\nexport interface LevelPlayPlugin {\n /**\n * Initialise the LevelPlay SDK. Resolves on `onInitSuccess`, rejects with the init error otherwise.\n * Calling it again after a successful init resolves immediately. Load ads only after this resolves.\n */\n initialize(options: InitOptions): Promise;\n\n /** Native SDK version (available before init). */\n getSdkVersion(): Promise;\n\n /** Forward GDPR / CCPA / COPPA signals. Call before {@link initialize} when you can. */\n setConsent(options: ConsentOptions): Promise;\n\n /** Raw `LevelPlay.setMetaData(key, value)` for network-specific flags. Call before init. */\n setMetaData(options: MetaDataOptions): Promise;\n\n /**\n * iOS: show the App Tracking Transparency prompt (needs `NSUserTrackingUsageDescription` in Info.plist) and resolve\n * with the resulting status. Call it before {@link initialize}. Android / web: resolves `unavailable`.\n */\n requestTrackingAuthorization(): Promise;\n\n /** Current ATT status without prompting (iOS). Android / web: `unavailable`. */\n getTrackingAuthorizationStatus(): Promise;\n\n /**\n * Start loading a rewarded ad for the ad unit (the ad object is created on first use and reused).\n * Resolves once the request is issued; the outcome arrives as `loaded` / `loadFailed` events.\n */\n loadRewarded(options: AdUnitOptions): Promise;\n\n /**\n * Show a loaded rewarded ad. Resolves after the ad closes (or failed to display) with what happened.\n * Never rejects for \"not ready\": resolves `{ shown: false, error }` instead.\n */\n showRewarded(options: ShowOptions): Promise;\n\n /** Start loading an interstitial ad (see {@link loadRewarded}). */\n loadInterstitial(options: AdUnitOptions): Promise;\n\n /** Show a loaded interstitial. Resolves after it closes (or failed to display). */\n showInterstitial(options: ShowOptions): Promise;\n\n /** `isAdReady()` of the ad object for this ad unit (`false` when it was never loaded). */\n isReady(options: IsReadyOptions): Promise;\n\n /** Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first. */\n launchTestSuite(): Promise;\n\n /** Log the LevelPlay integration helper report to the native console (development only). */\n validateIntegration(): Promise;\n\n addListener(eventName: 'loaded', listenerFunc: (event: AdEvent) => void): Promise;\n addListener(eventName: 'loadFailed', listenerFunc: (event: AdErrorEvent) => void): Promise;\n addListener(eventName: 'displayed', listenerFunc: (event: AdEvent) => void): Promise;\n addListener(eventName: 'displayFailed', listenerFunc: (event: AdErrorEvent) => void): Promise;\n addListener(eventName: 'clicked', listenerFunc: (event: AdEvent) => void): Promise;\n addListener(eventName: 'closed', listenerFunc: (event: AdEvent) => void): Promise;\n addListener(eventName: 'rewarded', listenerFunc: (event: AdRewardEvent) => void): Promise;\n\n removeAllListeners(): Promise;\n}\n\n/** Event names emitted by the plugin. */\nexport type LevelPlayEventName = 'loaded' | 'loadFailed' | 'displayed' | 'displayFailed' | 'clicked' | 'closed' | 'rewarded';\n"]} \ No newline at end of file +{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\n/**\n * Full-screen ad formats (`loadRewarded` / `loadInterstitial` family and the `loaded` ... `rewarded` events).\n * Banners and native ads have their own methods and `banner*` / `nativeAd*` events (since 0.3.0), so this union\n * stays unchanged for 0.2.x code.\n *\n * @since 0.1.0\n */\nexport type AdFormat = 'rewarded' | 'interstitial';\n\n/**\n * Options for `initialize()`.\n *\n * @since 0.1.0\n */\nexport interface InitOptions {\n /**\n * LevelPlay app key from the LevelPlay dashboard. Android and iOS apps have different keys.\n *\n * @since 0.1.0\n */\n appKey: string;\n /**\n * Optional user id. Needed for server-to-server reward callbacks and the Ad Quality user journey.\n *\n * @since 0.1.0\n */\n userId?: string;\n /**\n * Enable the LevelPlay Integration Test Suite: sets the `is_test_suite=enable` meta data before init.\n * Call `launchTestSuite()` after `initialize` resolves. Never ship this enabled.\n *\n * @default false\n * @since 0.1.0\n */\n testSuite?: boolean;\n /**\n * Turn on debug logs of the mediated ad network adapters (`LevelPlay.setAdaptersDebug(true)`). Development only.\n *\n * @default false\n * @since 0.1.0\n */\n adaptersDebug?: boolean;\n /**\n * Privacy signals applied right before init (LevelPlay recommends setting them before the SDK starts).\n * Same as calling `setConsent()` first.\n *\n * @since 0.1.0\n */\n consent?: ConsentOptions;\n}\n\n/**\n * Result of `initialize()` and `getSdkVersion()`.\n *\n * @since 0.1.0\n */\nexport interface InitResult {\n /**\n * Native LevelPlay SDK version, for example `9.6.1`. `web` on the web.\n *\n * @since 0.1.0\n */\n sdkVersion: string;\n}\n\n/**\n * Privacy signals forwarded to LevelPlay (`LevelPlayPrivacySettings` on Android, `LPMPrivacySettings` on iOS).\n * Omitted fields are left untouched.\n *\n * @since 0.1.0\n */\nexport interface ConsentOptions {\n /**\n * GDPR: `true` when the user consented to personalised ads and data processing, `false` when they did not.\n * For users in the EEA, UK and Switzerland pass `false` until a consent management platform (CMP) says otherwise.\n *\n * @since 0.1.0\n */\n gdprConsent?: boolean;\n /**\n * CCPA and other US state privacy laws: `true` when the user opted OUT of the sale or sharing of personal data\n * (\"do not sell\"), `false` otherwise.\n *\n * @since 0.1.0\n */\n ccpaDoNotSell?: boolean;\n /**\n * COPPA: `true` when the user must be treated as a child (child-directed treatment).\n *\n * @since 0.1.0\n */\n coppa?: boolean;\n}\n\n/**\n * Options for `setMetaData()`.\n *\n * @since 0.1.0\n */\nexport interface MetaDataOptions {\n /**\n * Meta data key, for example `is_deviceid_optout` or a network-specific flag from Unity's docs.\n *\n * @since 0.1.0\n */\n key: string;\n /**\n * Meta data value, always a string (for example `\"true\"`).\n *\n * @since 0.1.0\n */\n value: string;\n}\n\n/**\n * Identifies one ad unit.\n *\n * @since 0.1.0\n */\nexport interface AdUnitOptions {\n /**\n * Ad unit id from the LevelPlay dashboard (Ad units page). Android and iOS ad units have different ids.\n *\n * @since 0.1.0\n */\n adUnitId: string;\n}\n\n/**\n * Options for `showRewarded()` and `showInterstitial()`: `adUnitId` (see AdUnitOptions) plus an optional placement.\n *\n * @since 0.1.0\n */\nexport interface ShowOptions extends AdUnitOptions {\n /**\n * Optional placement name configured in the LevelPlay dashboard (capping, pacing and reward per placement).\n * Omit it to use the default placement.\n *\n * @since 0.1.0\n */\n placementName?: string;\n}\n\n/**\n * Options for `isReady()`: `adUnitId` (see AdUnitOptions) plus the format.\n *\n * @since 0.1.0\n */\nexport interface IsReadyOptions extends AdUnitOptions {\n /**\n * Format of the ad unit.\n *\n * @since 0.1.0\n */\n format: AdFormat;\n}\n\n/**\n * Result of `isReady()`.\n *\n * @since 0.1.0\n */\nexport interface IsReadyResult {\n /**\n * `true` when a loaded ad can be shown right now.\n *\n * @since 0.1.0\n */\n ready: boolean;\n}\n\n/**\n * The reward of a rewarded ad, as configured in the LevelPlay dashboard (per ad unit or placement).\n *\n * @since 0.1.0\n */\nexport interface Reward {\n /**\n * Name of the reward, for example `Coins`.\n *\n * @since 0.1.0\n */\n name: string;\n /**\n * Amount of the reward.\n *\n * @since 0.1.0\n */\n amount: number;\n}\n\n/**\n * Error reported by the SDK (load / display failures) or by the plugin.\n *\n * @since 0.1.0\n */\nexport interface AdError {\n /**\n * LevelPlay error code, for example `509` (no fill). `-1` is used by the plugin for \"Ad not ready\" and for the web\n * stub.\n *\n * @since 0.1.0\n */\n code: number;\n /**\n * Human readable message.\n *\n * @since 0.1.0\n */\n message: string;\n}\n\n/**\n * Subset of the native `LevelPlayAdInfo` (Android) / `LPMAdInfo` (iOS) that is useful in JavaScript.\n * Fields the SDK does not report are omitted.\n *\n * @since 0.1.0\n */\nexport interface AdInfo {\n /**\n * Unique id of this ad.\n *\n * @since 0.1.0\n */\n adId?: string;\n /**\n * Ad unit id.\n *\n * @since 0.1.0\n */\n adUnitId: string;\n /**\n * Ad unit name from the dashboard.\n *\n * @since 0.1.0\n */\n adUnitName?: string;\n /**\n * Ad format as reported by the SDK.\n *\n * @since 0.1.0\n */\n adFormat?: string;\n /**\n * Placement name of the show call, when one was used.\n *\n * @since 0.1.0\n */\n placementName?: string;\n /**\n * Name of the mediated network that served the ad.\n *\n * @since 0.1.0\n */\n adNetwork?: string;\n /**\n * Mediation instance name.\n *\n * @since 0.1.0\n */\n instanceName?: string;\n /**\n * Mediation instance id.\n *\n * @since 0.1.0\n */\n instanceId?: string;\n /**\n * Country code of the impression.\n *\n * @since 0.1.0\n */\n country?: string;\n /**\n * Auction id.\n *\n * @since 0.1.0\n */\n auctionId?: string;\n /**\n * Impression revenue in USD as reported by the SDK (may be absent or 0 before display).\n *\n * @since 0.1.0\n */\n revenue?: number;\n /**\n * Revenue precision as reported by the SDK.\n *\n * @since 0.1.0\n */\n precision?: string;\n /**\n * A/B test group of the user (`ab`).\n *\n * @since 0.3.0\n */\n ab?: string;\n /**\n * Segment name of the user, see `setSegment()`.\n *\n * @since 0.3.0\n */\n segmentName?: string;\n /**\n * Encrypted CPM (`encryptedCPM`).\n *\n * @since 0.3.0\n */\n encryptedCPM?: string;\n /**\n * Creative id of the served ad, when the network reports one.\n *\n * @since 0.3.0\n */\n creativeId?: string;\n /**\n * iOS only: SKAdNetwork conversion value (`LPMAdInfo.conversionValue`). Android's `LevelPlayAdInfo` has no such\n * field in SDK 9.6.1, so it is always absent there.\n *\n * @since 0.3.0\n */\n conversionValue?: number;\n /**\n * Size of the ad. Banners only (`LevelPlayAdInfo.getAdSize()` / `LPMAdInfo.adSize`).\n *\n * @since 0.3.0\n */\n adSize?: AdSizeInfo;\n}\n\n/**\n * A resolved ad size as reported by the SDK (`LevelPlayAdSize` / `LPMAdSize`). Width and height are in dp on Android\n * and points on iOS, which equal CSS px in the WebView at the default zoom.\n *\n * @since 0.3.0\n */\nexport interface AdSizeInfo {\n /**\n * Width in CSS px (dp / pt).\n *\n * @since 0.3.0\n */\n width: number;\n /**\n * Height in CSS px (dp / pt).\n *\n * @since 0.3.0\n */\n height: number;\n /**\n * SDK description of the size, for example `BANNER` or `ADAPTIVE`.\n *\n * @since 0.3.0\n */\n description?: string;\n /**\n * `true` for an adaptive size.\n *\n * @since 0.3.0\n */\n isAdaptive?: boolean;\n}\n\n/**\n * Result of `showRewarded()` and `showInterstitial()`, resolved after the ad\n * closed or failed to display.\n *\n * @since 0.1.0\n */\nexport interface ShowResult {\n /**\n * The ad was displayed (the `displayed` event fired).\n *\n * @since 0.1.0\n */\n shown: boolean;\n /**\n * Rewarded only: the reward callback fired for this show. Grant the reward only when this is `true`.\n * Always `false` for interstitials.\n *\n * @since 0.1.0\n */\n rewarded: boolean;\n /**\n * The reward, present when `rewarded` is `true`.\n *\n * @since 0.1.0\n */\n reward?: Reward;\n /**\n * Present when the ad was not ready (`code: -1`) or failed to display.\n *\n * @since 0.1.0\n */\n error?: AdError;\n /**\n * Info of the displayed ad.\n *\n * @since 0.1.0\n */\n adInfo?: AdInfo;\n}\n\n/**\n * Payload of the `loaded`, `displayed`, `clicked` and `closed` events.\n *\n * @since 0.1.0\n */\nexport interface AdEvent {\n /**\n * Format of the ad unit that fired the event.\n *\n * @since 0.1.0\n */\n format: AdFormat;\n /**\n * Ad unit that fired the event.\n *\n * @since 0.1.0\n */\n adUnitId: string;\n /**\n * Ad info, when the SDK provides it (not on `loadFailed`).\n *\n * @since 0.1.0\n */\n adInfo?: AdInfo;\n}\n\n/**\n * Payload of the `loadFailed` and `displayFailed` events: the AdEvent fields plus `error`.\n *\n * @since 0.1.0\n */\nexport interface AdErrorEvent extends AdEvent {\n /**\n * What went wrong.\n *\n * @since 0.1.0\n */\n error: AdError;\n}\n\n/**\n * Payload of the `rewarded` event: the AdEvent fields plus `reward`.\n *\n * @since 0.1.0\n */\nexport interface AdRewardEvent extends AdEvent {\n /**\n * The reward earned.\n *\n * @since 0.1.0\n */\n reward: Reward;\n}\n\n/**\n * iOS App Tracking Transparency status. `unavailable` on Android, on the web and on unknown future iOS values.\n *\n * @since 0.1.0\n */\nexport type TrackingStatus = 'authorized' | 'denied' | 'restricted' | 'notDetermined' | 'unavailable';\n\n/**\n * Result of `requestTrackingAuthorization()` and\n * `getTrackingAuthorizationStatus()`.\n *\n * @since 0.1.0\n */\nexport interface TrackingResult {\n /**\n * iOS App Tracking Transparency status. Always `unavailable` on Android and web.\n *\n * @since 0.1.0\n */\n status: TrackingStatus;\n}\n\n// ------------------------------------------------------------------------------------------------ 0.3.0: capabilities\n\n/**\n * Result of `getCapabilities()`: what this platform build of the plugin can do. Check it instead of the platform\n * name, so the same game code runs on Android, iOS and the web.\n *\n * @since 0.3.0\n */\nexport interface Capabilities {\n /**\n * Banner ads (`createBanner()` and friends) are available.\n *\n * @since 0.3.0\n */\n banner: boolean;\n /**\n * Native ads (`loadNativeAd()` and friends) are available.\n *\n * @since 0.3.0\n */\n nativeAd: boolean;\n /**\n * Native ad templates this platform can render. Empty when `nativeAd` is `false`.\n *\n * @since 0.3.0\n */\n nativeAdTemplates: NativeAdTemplate[];\n /**\n * The `impressionData` event is delivered.\n *\n * @since 0.3.0\n */\n impressionData: boolean;\n /**\n * The `adInfoChanged` event is delivered (rewarded and interstitial only).\n *\n * @since 0.3.0\n */\n adInfoChanged: boolean;\n}\n\n// ------------------------------------------------------------------------------------------------ 0.3.0: geometry\n\n/**\n * A rectangle in CSS px, relative to the top-left corner of the WebView viewport (the same space as\n * `element.getBoundingClientRect()` without page scroll).\n *\n * @since 0.3.0\n */\nexport interface Rect {\n /**\n * Left edge in CSS px.\n *\n * @since 0.3.0\n */\n x: number;\n /**\n * Top edge in CSS px.\n *\n * @since 0.3.0\n */\n y: number;\n /**\n * Width in CSS px.\n *\n * @since 0.3.0\n */\n width: number;\n /**\n * Height in CSS px.\n *\n * @since 0.3.0\n */\n height: number;\n}\n\n// ------------------------------------------------------------------------------------------------ 0.3.0: banners\n\n/**\n * Banner size presets, named after the SDK constants (`LevelPlayAdSize.BANNER` / `LPMAdSize.bannerSize()` ...).\n *\n * - `BANNER`: 320 x 50\n * - `LARGE`: 320 x 90\n * - `MEDIUM_RECTANGLE`: 300 x 250\n * - `LEADERBOARD`: 728 x 90 (tablets)\n * - `ADAPTIVE`: `LevelPlayAdSize.createAdaptiveAdSize(context, width)` / `LPMAdSize.createAdaptiveAdSize(withWidth:)`;\n * the SDK picks the height (and BANNER or LEADERBOARD as fallback) for the given width. Requires a finished\n * `initialize()`.\n * - `CUSTOM`: `LevelPlayAdSize.createCustomSize(width, height)` / `LPMAdSize.customSizeWithWidth:height:` with\n * `customSize`. Few networks fill custom sizes; prefer a preset or `ADAPTIVE`.\n *\n * @since 0.3.0\n */\nexport type BannerSize = 'BANNER' | 'LARGE' | 'MEDIUM_RECTANGLE' | 'LEADERBOARD' | 'ADAPTIVE' | 'CUSTOM';\n\n/**\n * Width and height of a `CUSTOM` banner, in CSS px (dp on Android, points on iOS).\n *\n * @since 0.3.0\n */\nexport interface BannerCustomSize {\n /**\n * Width in CSS px (positive integer).\n *\n * @since 0.3.0\n */\n width: number;\n /**\n * Height in CSS px (positive integer).\n *\n * @since 0.3.0\n */\n height: number;\n}\n\n/**\n * Vertical anchor of a banner inside the WebView's safe area. Banners are always horizontally centred; use\n * `offsetX` to move them sideways.\n *\n * @since 0.3.0\n */\nexport type BannerPosition = 'top' | 'bottom' | 'center';\n\n/**\n * Identifies one banner created with `createBanner()`.\n *\n * @since 0.3.0\n */\nexport interface BannerIdOptions {\n /**\n * Plugin-side banner id passed to `createBanner()` (defaults to the ad unit id there).\n *\n * @since 0.3.0\n */\n bannerId: string;\n}\n\n/**\n * Where a banner sits over the WebView.\n *\n * @since 0.3.0\n */\nexport interface BannerLayoutOptions {\n /**\n * Vertical anchor.\n *\n * @default 'bottom'\n * @since 0.3.0\n */\n position?: BannerPosition;\n /**\n * Horizontal offset from the centred position in CSS px (positive moves right).\n *\n * @default 0\n * @since 0.3.0\n */\n offsetX?: number;\n /**\n * Vertical offset from the anchored position in CSS px (positive moves down).\n *\n * @default 0\n * @since 0.3.0\n */\n offsetY?: number;\n /**\n * Keep the banner inside the safe area (status bar, notch / display cutout, home indicator, navigation bar), measured\n * against the WebView's own on-screen rect. Set `false` to anchor to the raw WebView edges.\n *\n * @default true\n * @since 0.3.0\n */\n respectSafeArea?: boolean;\n}\n\n/**\n * Options for `createBanner()`.\n *\n * @since 0.3.0\n */\nexport interface CreateBannerOptions extends AdUnitOptions, BannerLayoutOptions {\n /**\n * Plugin-side id of this banner, used by every other banner method and in banner events. Lets one ad unit back\n * several banners. Defaults to `adUnitId`.\n *\n * @since 0.3.0\n */\n bannerId?: string;\n /**\n * Size preset.\n *\n * @default 'ADAPTIVE'\n * @since 0.3.0\n */\n size?: BannerSize;\n /**\n * `CUSTOM` only: the banner size. When `customSize` is set and `size` is omitted, `size` defaults to `CUSTOM`.\n *\n * @since 0.3.0\n */\n customSize?: BannerCustomSize;\n /**\n * `ADAPTIVE` only: width in CSS px to compute the adaptive size for. Defaults to the width of the WebView's safe\n * area; in that case the plugin recreates and reloads the banner automatically when that width changes (rotation,\n * split screen, window resize), keeping its id, layout and visibility. A fixed `adaptiveWidth` is never recreated.\n *\n * @since 0.3.0\n */\n adaptiveWidth?: number;\n /**\n * Placement name (reporting only for banners). Applied through the banner config before the first load.\n *\n * @since 0.3.0\n */\n placementName?: string;\n /**\n * Bid floor in USD (`LevelPlayBannerAdView.Config.Builder.setBidFloor` / `LPMBannerAdViewConfigBuilder set(bidFloor:)`).\n *\n * @since 0.3.0\n */\n bidFloor?: number;\n}\n\n/**\n * Options for `setBannerLayout()`: `bannerId` plus the layout fields (see BannerLayoutOptions).\n *\n * @since 0.3.0\n */\nexport interface SetBannerLayoutOptions extends BannerIdOptions, BannerLayoutOptions {}\n\n/**\n * Result of `createBanner()`, `showBanner()` and `setBannerLayout()`.\n *\n * @since 0.3.0\n */\nexport interface BannerResult {\n /**\n * The banner id.\n *\n * @since 0.3.0\n */\n bannerId: string;\n /**\n * Requested ad size (the creative may be smaller for adaptive sizes; it is centred in this frame).\n *\n * @since 0.3.0\n */\n adSize: AdSizeInfo;\n /**\n * Where the banner frame is (or will be, while hidden) in CSS px, relative to the WebView viewport. Use it to pad\n * game UI away from the banner.\n *\n * @since 0.3.0\n */\n frame: Rect;\n /**\n * The banner view is currently visible.\n *\n * @since 0.3.0\n */\n visible: boolean;\n}\n\n/**\n * Payload of the `banner*` events.\n *\n * @since 0.3.0\n */\nexport interface BannerEvent {\n /**\n * Banner that fired the event.\n *\n * @since 0.3.0\n */\n bannerId: string;\n /**\n * Ad unit of the banner.\n *\n * @since 0.3.0\n */\n adUnitId: string;\n /**\n * Ad info, when the SDK provides it (not on `bannerLoadFailed`).\n *\n * @since 0.3.0\n */\n adInfo?: AdInfo;\n /**\n * Current frame of the banner in CSS px.\n *\n * @since 0.3.0\n */\n frame?: Rect;\n}\n\n/**\n * Payload of `bannerLoadFailed` and `bannerDisplayFailed`.\n *\n * @since 0.3.0\n */\nexport interface BannerErrorEvent extends BannerEvent {\n /**\n * What went wrong.\n *\n * @since 0.3.0\n */\n error: AdError;\n}\n\n// ------------------------------------------------------------------------------------------------ 0.3.0: native ads\n\n/**\n * Native ad template rendered by the plugin (the LevelPlay SDK ships no template views; the plugin provides its own\n * layouts, like Unity's Flutter and React Native wrappers do).\n *\n * - `small`: icon, title, advertiser, body, call to action; no media view. Recommended 300 x 175 or a row at least\n * 90 px tall.\n * - `medium`: the `small` assets plus a media view. Recommended 300 x 350.\n *\n * @since 0.3.0\n */\nexport type NativeAdTemplate = 'small' | 'medium';\n\n/**\n * Optional styling of a native ad template. Colours are CSS hex strings (`#RRGGBB` or `#RRGGBBAA`).\n *\n * @since 0.3.0\n */\nexport interface NativeAdTemplateStyle {\n /**\n * Template background.\n *\n * @since 0.3.0\n */\n backgroundColor?: string;\n /**\n * Title text colour.\n *\n * @since 0.3.0\n */\n titleColor?: string;\n /**\n * Body and advertiser text colour.\n *\n * @since 0.3.0\n */\n bodyColor?: string;\n /**\n * Call-to-action button background.\n *\n * @since 0.3.0\n */\n callToActionBackgroundColor?: string;\n /**\n * Call-to-action button text colour.\n *\n * @since 0.3.0\n */\n callToActionTextColor?: string;\n /**\n * Corner radius of the template in CSS px.\n *\n * @default 0\n * @since 0.3.0\n */\n cornerRadius?: number;\n /**\n * Title font.\n *\n * @since 0.3.0\n */\n titleFont?: NativeAdFont;\n /**\n * Body and advertiser font.\n *\n * @since 0.3.0\n */\n bodyFont?: NativeAdFont;\n /**\n * Call-to-action button font.\n *\n * @since 0.3.0\n */\n callToActionFont?: NativeAdFont;\n}\n\n/**\n * A font of a native ad template text. Omitted fields keep the template default (system font).\n *\n * @since 0.3.0\n */\nexport interface NativeAdFont {\n /**\n * Font family. Either a system family name (Android: `sans-serif`, `sans-serif-medium`, `serif`, `monospace` ...;\n * iOS: a `UIFont` family or PostScript name such as `Avenir Next` or `Menlo-Bold`), or the path of a `.ttf` / `.otf`\n * file inside the app's web assets, relative to the web root (for example `fonts/Inter-Bold.ttf`, the same file the\n * page loads with `@font-face`). Unknown families fall back to the system font.\n *\n * @since 0.3.0\n */\n family?: string;\n /**\n * Font size in CSS px (dp / pt; not scaled by the system font size setting, like text in the WebView).\n *\n * @since 0.3.0\n */\n size?: number;\n}\n\n/**\n * Identifies one native ad slot.\n *\n * @since 0.3.0\n */\nexport interface NativeAdIdOptions {\n /**\n * Plugin-side id of the native ad slot.\n *\n * @since 0.3.0\n */\n nativeAdId: string;\n}\n\n/**\n * Options for `loadNativeAd()`.\n *\n * @since 0.3.0\n */\nexport interface LoadNativeAdOptions extends NativeAdIdOptions {\n /**\n * Placement name. LevelPlay 9.6.1 native ads are addressed by placement only (`LevelPlayNativeAd.Builder\n * .withPlacementName` / `LevelPlayNativeAdBuilder withPlacementName:`); there is no ad unit id for native ads in\n * this SDK version. Omit it for the default placement.\n *\n * @since 0.3.0\n */\n placementName?: string;\n /**\n * Template used when the ad is shown.\n *\n * @default 'medium'\n * @since 0.3.0\n */\n template?: NativeAdTemplate;\n /**\n * Template styling.\n *\n * @since 0.3.0\n */\n style?: NativeAdTemplateStyle;\n}\n\n/**\n * Options for `showNativeAd()` and `setNativeAdRect()`.\n *\n * @since 0.3.0\n */\nexport interface NativeAdRectOptions extends NativeAdIdOptions {\n /**\n * Where the template goes, in CSS px relative to the WebView viewport (for example a placeholder element's\n * `getBoundingClientRect()`).\n *\n * @since 0.3.0\n */\n rect: Rect;\n}\n\n/**\n * Ad info of a native ad (`AdInfo` on Android / `ISAdInfo` on iOS: the older ironSource info type, which has no ad\n * unit, ad id or placement fields).\n *\n * @since 0.3.0\n */\nexport interface NativeAdInfo {\n /**\n * Auction id.\n *\n * @since 0.3.0\n */\n auctionId?: string;\n /**\n * Mediated network that served the ad.\n *\n * @since 0.3.0\n */\n adNetwork?: string;\n /**\n * Mediation instance name.\n *\n * @since 0.3.0\n */\n instanceName?: string;\n /**\n * Mediation instance id.\n *\n * @since 0.3.0\n */\n instanceId?: string;\n /**\n * Country code.\n *\n * @since 0.3.0\n */\n country?: string;\n /**\n * Impression revenue in USD.\n *\n * @since 0.3.0\n */\n revenue?: number;\n /**\n * Revenue precision.\n *\n * @since 0.3.0\n */\n precision?: string;\n /**\n * A/B test group.\n *\n * @since 0.3.0\n */\n ab?: string;\n /**\n * Segment name.\n *\n * @since 0.3.0\n */\n segmentName?: string;\n /**\n * Encrypted CPM.\n *\n * @since 0.3.0\n */\n encryptedCPM?: string;\n /**\n * iOS only: SKAdNetwork conversion value.\n *\n * @since 0.3.0\n */\n conversionValue?: number;\n}\n\n/**\n * Payload of the `nativeAd*` events.\n *\n * @since 0.3.0\n */\nexport interface NativeAdEvent {\n /**\n * Native ad slot that fired the event.\n *\n * @since 0.3.0\n */\n nativeAdId: string;\n /**\n * Placement passed to `loadNativeAd()`, if any.\n *\n * @since 0.3.0\n */\n placementName?: string;\n /**\n * Ad info, when the SDK provides it (not on `nativeAdLoadFailed`).\n *\n * @since 0.3.0\n */\n adInfo?: NativeAdInfo;\n}\n\n/**\n * Payload of `nativeAdLoadFailed`.\n *\n * @since 0.3.0\n */\nexport interface NativeAdErrorEvent extends NativeAdEvent {\n /**\n * What went wrong.\n *\n * @since 0.3.0\n */\n error: AdError;\n}\n\n// ------------------------------------------------------------------------------------------------ 0.3.0: revenue\n\n/**\n * Impression-level revenue data (`LevelPlayImpressionData` on Android, `LPMImpressionData` on iOS). Every field the\n * SDK 9.6.1 data class exposes is mapped; fields the SDK leaves empty are omitted.\n *\n * Not available in SDK 9.6.1 on either platform: `lifetimeRevenue` (removed from the impression data class). If the\n * server ever sends extra keys they are still visible in `allData`.\n *\n * @since 0.3.0\n */\nexport interface ImpressionData {\n /**\n * Which ad format produced the impression, as the SDK reports it (for example `Rewarded Video`, `Interstitial`,\n * `Banner`, or `nativead` for impressions synthesised from native ad info).\n *\n * @since 0.3.0\n */\n adFormat?: string;\n /**\n * Auction id.\n *\n * @since 0.3.0\n */\n auctionId?: string;\n /**\n * Mediation ad unit id (`mediationAdUnitId`).\n *\n * @since 0.3.0\n */\n adUnitId?: string;\n /**\n * Mediation ad unit name (`mediationAdUnitName`).\n *\n * @since 0.3.0\n */\n adUnitName?: string;\n /**\n * Mediated network that served the ad.\n *\n * @since 0.3.0\n */\n adNetwork?: string;\n /**\n * Mediation instance name.\n *\n * @since 0.3.0\n */\n instanceName?: string;\n /**\n * Mediation instance id.\n *\n * @since 0.3.0\n */\n instanceId?: string;\n /**\n * Country code.\n *\n * @since 0.3.0\n */\n country?: string;\n /**\n * Placement name of the impression.\n *\n * @since 0.3.0\n */\n placement?: string;\n /**\n * Revenue of this impression in USD.\n *\n * @since 0.3.0\n */\n revenue?: number;\n /**\n * Revenue precision (for example `BID`, `RATE`, `ESTIMATED`).\n *\n * @since 0.3.0\n */\n precision?: string;\n /**\n * A/B test group.\n *\n * @since 0.3.0\n */\n ab?: string;\n /**\n * Segment name, see `setSegment()`.\n *\n * @since 0.3.0\n */\n segmentName?: string;\n /**\n * Encrypted CPM (`encryptedCPM` on Android, `encryptedCpm` on iOS).\n *\n * @since 0.3.0\n */\n encryptedCPM?: string;\n /**\n * Creative id.\n *\n * @since 0.3.0\n */\n creativeId?: string;\n /**\n * iOS only: SKAdNetwork conversion value.\n *\n * @since 0.3.0\n */\n conversionValue?: number;\n /**\n * The raw `allData` map of the SDK (`getAllData()` JSON on Android, `allData` dictionary on iOS). Keys and value\n * types are SDK defined and may change between SDK versions.\n *\n * @since 0.3.0\n */\n allData?: { [key: string]: unknown };\n}\n\n// ------------------------------------------------------------------------------------------------ 0.3.0: placements\n\n/**\n * Options for `isPlacementCapped()`.\n *\n * @since 0.3.0\n */\nexport interface PlacementCappedOptions {\n /**\n * Format of the placement. LevelPlay 9.6.1 has capping checks for rewarded and interstitial only.\n *\n * @since 0.3.0\n */\n format: AdFormat;\n /**\n * Placement name from the LevelPlay dashboard.\n *\n * @since 0.3.0\n */\n placementName: string;\n}\n\n/**\n * Result of `isPlacementCapped()`.\n *\n * @since 0.3.0\n */\nexport interface PlacementCappedResult {\n /**\n * `true` when the placement reached its capping or pacing limit; showing it now fails.\n *\n * @since 0.3.0\n */\n capped: boolean;\n}\n\n/**\n * Options for `getReward()`: `adUnitId` (see AdUnitOptions) plus an optional placement.\n *\n * @since 0.3.0\n */\nexport interface GetRewardOptions extends AdUnitOptions {\n /**\n * Placement whose reward to read. Its reward takes precedence over the ad unit reward. Omit for the ad unit reward.\n *\n * @since 0.3.0\n */\n placementName?: string;\n}\n\n// ------------------------------------------------------------------------------------------------ 0.3.0: user\n\n/**\n * Options for `setSegment()` (`LevelPlaySegment` / `LPMSegment`). Omitted fields are not sent.\n *\n * @since 0.3.0\n */\nexport interface SegmentOptions {\n /**\n * Segment name.\n *\n * @since 0.3.0\n */\n segmentName?: string;\n /**\n * User level (integer).\n *\n * @since 0.3.0\n */\n level?: number;\n /**\n * The user has paid in the app.\n *\n * @since 0.3.0\n */\n isPaying?: boolean;\n /**\n * When the user was created, in milliseconds since the Unix epoch (`Date.now()` style).\n *\n * @since 0.3.0\n */\n userCreationDate?: number;\n /**\n * Total in-app purchase amount of the user (USD).\n *\n * @since 0.3.0\n */\n iapTotal?: number;\n /**\n * Custom segment parameters. SDK 9.6.1 limits: at most 5 pairs; keys and values 1-32 characters, letters and digits\n * only (`^[a-zA-Z0-9]*$`). The plugin rejects with `INVALID_ARGUMENT` instead of letting the SDK silently drop pairs.\n *\n * @since 0.3.0\n */\n customParameters?: { [key: string]: string };\n}\n\n/**\n * Options for `setDynamicUserId()`.\n *\n * @since 0.3.0\n */\nexport interface DynamicUserIdOptions {\n /**\n * Dynamic user id, forwarded in server-to-server reward callbacks. Can change during the session.\n *\n * @since 0.3.0\n */\n userId: string;\n}\n\n/**\n * Result of `setDynamicUserId()`.\n *\n * @since 0.3.0\n */\nexport interface DynamicUserIdResult {\n /**\n * The SDK accepted the id (`LevelPlay.setDynamicUserId` returns a boolean on both platforms).\n *\n * @since 0.3.0\n */\n valid: boolean;\n}\n\n/**\n * Event names emitted by the plugin.\n *\n * @since 0.1.0\n */\nexport type LevelPlayEventName =\n | 'loaded'\n | 'loadFailed'\n | 'displayed'\n | 'displayFailed'\n | 'clicked'\n | 'closed'\n | 'rewarded'\n | 'adInfoChanged'\n | 'impressionData'\n | 'bannerLoaded'\n | 'bannerLoadFailed'\n | 'bannerDisplayed'\n | 'bannerDisplayFailed'\n | 'bannerClicked'\n | 'bannerExpanded'\n | 'bannerCollapsed'\n | 'bannerLeftApplication'\n | 'nativeAdLoaded'\n | 'nativeAdLoadFailed'\n | 'nativeAdImpression'\n | 'nativeAdClicked';\n\n/**\n * Unity LevelPlay ads (ad-unit API): rewarded, interstitial and (since 0.3.0) banner and native ads, impression-level\n * revenue, segments and placement capping.\n *\n * @since 0.1.0\n */\nexport interface LevelPlayPlugin {\n /**\n * Initialise the LevelPlay SDK (`LevelPlay.init`). Resolves on init success, rejects with the init error\n * (code and message from the SDK) otherwise. Calling it again after a successful init resolves immediately;\n * concurrent calls share one init. Load ads only after this resolves.\n *\n * Set consent (and on iOS ask for ATT) before calling it.\n *\n * On the web it rejects as unimplemented.\n *\n * @since 0.1.0\n */\n initialize(options: InitOptions): Promise;\n\n /**\n * Native LevelPlay SDK version. Works before init.\n *\n * @since 0.1.0\n */\n getSdkVersion(): Promise;\n\n /**\n * Forward GDPR / CCPA / COPPA signals to LevelPlay. Call it before `initialize()` when you\n * can, and again whenever the user changes their choice.\n *\n * @since 0.1.0\n */\n setConsent(options: ConsentOptions): Promise;\n\n /**\n * Raw `LevelPlay.setMetaData(key, value)` for SDK or network-specific flags. Call it before init.\n *\n * @since 0.1.0\n */\n setMetaData(options: MetaDataOptions): Promise;\n\n /**\n * iOS: show the App Tracking Transparency prompt and resolve with the resulting status. Needs\n * `NSUserTrackingUsageDescription` in `Info.plist`. iOS only shows the prompt once; later calls resolve the stored\n * status. Call it before `initialize()`, while the app is active.\n *\n * Android and web: resolves `unavailable`.\n *\n * @since 0.1.0\n */\n requestTrackingAuthorization(): Promise;\n\n /**\n * Current App Tracking Transparency status without prompting (iOS). Android and web: `unavailable`.\n *\n * @since 0.1.0\n */\n getTrackingAuthorizationStatus(): Promise;\n\n /**\n * Start loading a rewarded ad for the ad unit. The native ad object is created on first use and reused for the\n * ad unit. Resolves once the request is issued; the outcome arrives as a `loaded` or `loadFailed` event.\n * Load the next ad after each show.\n *\n * @since 0.1.0\n */\n loadRewarded(options: AdUnitOptions): Promise;\n\n /**\n * Show a loaded rewarded ad. Resolves after the ad closed (or failed to display) with what happened. The reward\n * and close callbacks can arrive in either order on some networks, so the plugin waits up to 1 second after the close\n * for a late reward. Never rejects for \"not ready\": resolves `{ shown: false, rewarded: false, error }` instead.\n *\n * @since 0.1.0\n */\n showRewarded(options: ShowOptions): Promise;\n\n /**\n * Start loading an interstitial ad for the ad unit. Works like `loadRewarded()`.\n *\n * @since 0.1.0\n */\n loadInterstitial(options: AdUnitOptions): Promise;\n\n /**\n * Show a loaded interstitial. Resolves after it closed (or failed to display). Never rejects for \"not ready\".\n *\n * @since 0.1.0\n */\n showInterstitial(options: ShowOptions): Promise;\n\n /**\n * `isAdReady()` of the native ad object for this ad unit. `false` when the ad unit was never loaded.\n *\n * @since 0.1.0\n */\n isReady(options: IsReadyOptions): Promise;\n\n /**\n * Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first.\n * Development builds only. Rejects on the web.\n *\n * @since 0.1.0\n */\n launchTestSuite(): Promise;\n\n /**\n * Write the LevelPlay integration helper report to the native log (Xcode console; Android logcat tag\n * `IntegrationHelper`): SDK, adapter and network SDK versions, each `VERIFIED` or not. Development only.\n *\n * @since 0.1.0\n */\n validateIntegration(): Promise;\n\n /**\n * What this platform supports (banners, native ad templates, impression data, `adInfoChanged`). Works before init.\n * Web: everything `false`.\n *\n * @since 0.3.0\n */\n getCapabilities(): Promise;\n\n /**\n * Set the user segment (`LevelPlay.setSegment` with a `LevelPlaySegment` / `LPMSegment`). Call it before\n * `initialize()` so the first ad requests use it; later calls apply to the following requests. Rejects with\n * `INVALID_ARGUMENT` when `customParameters` break the SDK limits. Web: no-op.\n *\n * @since 0.3.0\n */\n setSegment(options: SegmentOptions): Promise;\n\n /**\n * Set or change the dynamic user id used in server-to-server reward callbacks (`LevelPlay.setDynamicUserId` on\n * both platforms). Set it before `showRewarded()`. Web: resolves `{ valid: false }`.\n *\n * @since 0.3.0\n */\n setDynamicUserId(options: DynamicUserIdOptions): Promise;\n\n /**\n * Whether a rewarded or interstitial placement is capped right now (static\n * `LevelPlayRewardedAd.isPlacementCapped` / `LevelPlayInterstitialAd.isPlacementCapped` on Android,\n * `LPMRewardedAd.isPlacementCapped:` / `LPMInterstitialAd.isPlacementCapped:` on iOS). Works without a loaded ad.\n * Web: `{ capped: false }`.\n *\n * @since 0.3.0\n */\n isPlacementCapped(options: PlacementCappedOptions): Promise;\n\n /**\n * The reward configured for a rewarded ad unit or one of its placements (`LevelPlayRewardedAd.getReward(placement)` /\n * `LPMRewardedAd getReward(placementName:)`), for \"watch a video for N coins\" buttons. The SDK returns\n * `{ name: '', amount: 0 }` when it has no reward configuration (for example before init). Web: the same empty\n * reward.\n *\n * @since 0.3.0\n */\n getReward(options: GetRewardOptions): Promise;\n\n /**\n * Create a banner (`LevelPlayBannerAdView` / `LPMBannerAdView`) for the ad unit and attach it, hidden, in a\n * pass-through overlay above the WebView. Requires a finished `initialize()` (`NOT_INITIALIZED` otherwise). Rejects\n * with `ALREADY_EXISTS` when `bannerId` is in use; destroy it first. Does not load: call `loadBanner()`.\n * Web: rejects as unimplemented.\n *\n * @since 0.3.0\n */\n createBanner(options: CreateBannerOptions): Promise;\n\n /**\n * Load the banner (`loadAd()` / `loadAdWithViewController:`). The outcome arrives as `bannerLoaded` or\n * `bannerLoadFailed`; after the first load the SDK refreshes the banner on the dashboard interval. The SDK accepts\n * one load per banner object: calling it again has no effect (Android logs \"Banner load already called\"), so to retry\n * right away after `bannerLoadFailed`, destroy the banner and create it again. Web: no-op.\n *\n * @since 0.3.0\n */\n loadBanner(options: BannerIdOptions): Promise;\n\n /**\n * Make the banner visible and resume auto refresh (`resumeAutoRefresh`). Can be called before the load finished;\n * the creative appears when it arrives. Web: rejects as unimplemented.\n *\n * @since 0.3.0\n */\n showBanner(options: BannerIdOptions): Promise;\n\n /**\n * Hide the banner and pause auto refresh (`pauseAutoRefresh`) so hidden banners do not burn impressions. The view\n * stays attached; `showBanner()` brings it back. Web: no-op.\n *\n * @since 0.3.0\n */\n hideBanner(options: BannerIdOptions): Promise;\n\n /**\n * Move a banner (position, offsets, safe area). Resolves with the new frame. Web: rejects as unimplemented.\n *\n * @since 0.3.0\n */\n setBannerLayout(options: SetBannerLayoutOptions): Promise;\n\n /**\n * Remove the banner from the screen and `destroy()` it. A destroyed banner cannot be reused; create a new one.\n * Resolves also for unknown ids. Web: no-op.\n *\n * @since 0.3.0\n */\n destroyBanner(options: BannerIdOptions): Promise;\n\n /**\n * Load a native ad into a slot. Following the SDK rule \"one native ad object per load\", it destroys the slot's\n * previous ad (hiding it if shown), builds a new `LevelPlayNativeAd` with the placement and loads it. The outcome\n * arrives as `nativeAdLoaded` or `nativeAdLoadFailed`. Requires a finished `initialize()`. Rejects with\n * `UNSUPPORTED` when `getCapabilities().nativeAd` is `false` or the template is not listed there. Web: rejects as\n * unimplemented.\n *\n * @since 0.3.0\n */\n loadNativeAd(options: LoadNativeAdOptions): Promise;\n\n /**\n * Render the loaded native ad into its template, register the asset views with the SDK\n * (`NativeAdLayout.registerNativeAdViews` / `ISNativeAdView registerNativeAdViews:`) and place it at `rect` above the\n * WebView. Rejects with `NOT_LOADED` before `nativeAdLoaded`. The impression is reported by `nativeAdImpression`.\n * Web: rejects as unimplemented.\n *\n * @since 0.3.0\n */\n showNativeAd(options: NativeAdRectOptions): Promise;\n\n /**\n * Move or resize a shown native ad, for example after the placeholder element moved. Web: no-op.\n *\n * @since 0.3.0\n */\n setNativeAdRect(options: NativeAdRectOptions): Promise;\n\n /**\n * Hide a shown native ad (the view stays registered; `showNativeAd()` shows it again). Web: no-op.\n *\n * @since 0.3.0\n */\n hideNativeAd(options: NativeAdIdOptions): Promise;\n\n /**\n * Remove the native ad view and `destroyAd()` it. Resolves also for unknown ids. Web: no-op.\n *\n * @since 0.3.0\n */\n destroyNativeAd(options: NativeAdIdOptions): Promise;\n\n /**\n * An ad finished loading for the ad unit and can be shown.\n *\n * @since 0.1.0\n */\n addListener(eventName: 'loaded', listenerFunc: (event: AdEvent) => void): Promise;\n\n /**\n * Loading failed, for example `509` (no fill). Retry later with a backoff.\n *\n * @since 0.1.0\n */\n addListener(eventName: 'loadFailed', listenerFunc: (event: AdErrorEvent) => void): Promise;\n\n /**\n * The ad was displayed (impression). `adInfo.revenue` is available here.\n *\n * @since 0.1.0\n */\n addListener(eventName: 'displayed', listenerFunc: (event: AdEvent) => void): Promise;\n\n /**\n * The ad failed to display. The pending show call resolves with the same error.\n *\n * @since 0.1.0\n */\n addListener(\n eventName: 'displayFailed',\n listenerFunc: (event: AdErrorEvent) => void,\n ): Promise;\n\n /**\n * The user clicked the ad.\n *\n * @since 0.1.0\n */\n addListener(eventName: 'clicked', listenerFunc: (event: AdEvent) => void): Promise;\n\n /**\n * The ad was closed and the app is back in front.\n *\n * @since 0.1.0\n */\n addListener(eventName: 'closed', listenerFunc: (event: AdEvent) => void): Promise;\n\n /**\n * Rewarded only: the user earned the reward. Can fire before or after `closed`.\n *\n * @since 0.1.0\n */\n addListener(eventName: 'rewarded', listenerFunc: (event: AdRewardEvent) => void): Promise;\n\n /**\n * Rewarded and interstitial: the SDK reloaded the ad in the background and its ad info (network, revenue ...)\n * changed (`onAdInfoChanged` / `didChangeAdInfo:`). Banners and native ads have no such callback in SDK 9.6.1.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'adInfoChanged', listenerFunc: (event: AdEvent) => void): Promise;\n\n /**\n * Impression-level revenue data for every rewarded, interstitial and banner impression (per-ad\n * `setImpressionDataListener` / `setImpressionDataDelegate:`, attached by the plugin to every ad object it creates),\n * plus native ad impressions synthesised from the native ad info (`adFormat: 'nativead'`, `adInfo` fields only).\n * Add the listener at any time, also before `initialize()`; nothing is delivered before the first ad shows.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'impressionData', listenerFunc: (event: ImpressionData) => void): Promise;\n\n /**\n * A banner loaded or refreshed with a new creative.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'bannerLoaded', listenerFunc: (event: BannerEvent) => void): Promise;\n\n /**\n * A banner load (or refresh) failed. The SDK keeps retrying on its refresh interval.\n *\n * @since 0.3.0\n */\n addListener(\n eventName: 'bannerLoadFailed',\n listenerFunc: (event: BannerErrorEvent) => void,\n ): Promise;\n\n /**\n * A banner creative was displayed on screen (impression).\n *\n * @since 0.3.0\n */\n addListener(eventName: 'bannerDisplayed', listenerFunc: (event: BannerEvent) => void): Promise;\n\n /**\n * A banner creative failed to display.\n *\n * @since 0.3.0\n */\n addListener(\n eventName: 'bannerDisplayFailed',\n listenerFunc: (event: BannerErrorEvent) => void,\n ): Promise;\n\n /**\n * The user clicked a banner.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'bannerClicked', listenerFunc: (event: BannerEvent) => void): Promise;\n\n /**\n * A banner opened full screen (for example an expandable creative). Pause the game.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'bannerExpanded', listenerFunc: (event: BannerEvent) => void): Promise;\n\n /**\n * A banner returned to its normal size. Resume the game.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'bannerCollapsed', listenerFunc: (event: BannerEvent) => void): Promise;\n\n /**\n * A banner click sent the user out of the app (browser or store).\n *\n * @since 0.3.0\n */\n addListener(\n eventName: 'bannerLeftApplication',\n listenerFunc: (event: BannerEvent) => void,\n ): Promise;\n\n /**\n * A native ad loaded and can be shown with `showNativeAd()`.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'nativeAdLoaded', listenerFunc: (event: NativeAdEvent) => void): Promise;\n\n /**\n * A native ad failed to load. Load again later (the plugin already destroyed the failed ad object).\n *\n * @since 0.3.0\n */\n addListener(\n eventName: 'nativeAdLoadFailed',\n listenerFunc: (event: NativeAdErrorEvent) => void,\n ): Promise;\n\n /**\n * A shown native ad recorded its impression (first pixel visible).\n *\n * @since 0.3.0\n */\n addListener(\n eventName: 'nativeAdImpression',\n listenerFunc: (event: NativeAdEvent) => void,\n ): Promise;\n\n /**\n * The user clicked a native ad.\n *\n * @since 0.3.0\n */\n addListener(eventName: 'nativeAdClicked', listenerFunc: (event: NativeAdEvent) => void): Promise;\n\n /**\n * Remove every listener of this plugin.\n *\n * @since 0.1.0\n */\n removeAllListeners(): Promise;\n}\n"]} \ No newline at end of file diff --git a/dist/esm/demo.d.ts b/dist/esm/demo.d.ts index cb0883d..f2724ed 100644 --- a/dist/esm/demo.d.ts +++ b/dist/esm/demo.d.ts @@ -2,6 +2,7 @@ * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only. + * The sample apps have no native ad placement; native ads load with the default placement of the app key. * Replace them with your own ids from the LevelPlay dashboard before release. */ export declare const LEVELPLAY_DEMO: { @@ -9,10 +10,12 @@ export declare const LEVELPLAY_DEMO: { readonly appKey: "25b63cf85"; readonly rewarded: "syz3d8ekts22q0or"; readonly interstitial: "h3xw38h9214adgxo"; + readonly banner: "4fpetq4lhe5lsw3e"; }; readonly ios: { readonly appKey: "8545d445"; readonly rewarded: "qwouvdrkuwivay5q"; readonly interstitial: "wmgt0712uuux8ju4"; + readonly banner: "iep3rxsyp9na3rw8"; }; }; diff --git a/dist/esm/demo.js b/dist/esm/demo.js index 5173e38..59bf5ad 100644 --- a/dist/esm/demo.js +++ b/dist/esm/demo.js @@ -2,6 +2,7 @@ * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only. + * The sample apps have no native ad placement; native ads load with the default placement of the app key. * Replace them with your own ids from the LevelPlay dashboard before release. */ export const LEVELPLAY_DEMO = { @@ -9,11 +10,13 @@ export const LEVELPLAY_DEMO = { appKey: '25b63cf85', rewarded: 'syz3d8ekts22q0or', interstitial: 'h3xw38h9214adgxo', + banner: '4fpetq4lhe5lsw3e', }, ios: { appKey: '8545d445', rewarded: 'qwouvdrkuwivay5q', interstitial: 'wmgt0712uuux8ju4', + banner: 'iep3rxsyp9na3rw8', }, }; //# sourceMappingURL=demo.js.map \ No newline at end of file diff --git a/dist/esm/demo.js.map b/dist/esm/demo.js.map index 6490be4..8ffd4da 100644 --- a/dist/esm/demo.js.map +++ b/dist/esm/demo.js.map @@ -1 +1 @@ -{"version":3,"file":"demo.js","sourceRoot":"","sources":["../../src/demo.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,OAAO,EAAE;QACP,MAAM,EAAE,WAAW;QACnB,QAAQ,EAAE,kBAAkB;QAC5B,YAAY,EAAE,kBAAkB;KACjC;IACD,GAAG,EAAE;QACH,MAAM,EAAE,UAAU;QAClB,QAAQ,EAAE,kBAAkB;QAC5B,YAAY,EAAE,kBAAkB;KACjC;CACO,CAAC","sourcesContent":["/**\n * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps\n * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and\n * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only.\n * Replace them with your own ids from the LevelPlay dashboard before release.\n */\nexport const LEVELPLAY_DEMO = {\n android: {\n appKey: '25b63cf85',\n rewarded: 'syz3d8ekts22q0or',\n interstitial: 'h3xw38h9214adgxo',\n },\n ios: {\n appKey: '8545d445',\n rewarded: 'qwouvdrkuwivay5q',\n interstitial: 'wmgt0712uuux8ju4',\n },\n} as const;\n"]} \ No newline at end of file +{"version":3,"file":"demo.js","sourceRoot":"","sources":["../../src/demo.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,OAAO,EAAE;QACP,MAAM,EAAE,WAAW;QACnB,QAAQ,EAAE,kBAAkB;QAC5B,YAAY,EAAE,kBAAkB;QAChC,MAAM,EAAE,kBAAkB;KAC3B;IACD,GAAG,EAAE;QACH,MAAM,EAAE,UAAU;QAClB,QAAQ,EAAE,kBAAkB;QAC5B,YAAY,EAAE,kBAAkB;QAChC,MAAM,EAAE,kBAAkB;KAC3B;CACO,CAAC","sourcesContent":["/**\n * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps\n * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and\n * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only.\n * The sample apps have no native ad placement; native ads load with the default placement of the app key.\n * Replace them with your own ids from the LevelPlay dashboard before release.\n */\nexport const LEVELPLAY_DEMO = {\n android: {\n appKey: '25b63cf85',\n rewarded: 'syz3d8ekts22q0or',\n interstitial: 'h3xw38h9214adgxo',\n banner: '4fpetq4lhe5lsw3e',\n },\n ios: {\n appKey: '8545d445',\n rewarded: 'qwouvdrkuwivay5q',\n interstitial: 'wmgt0712uuux8ju4',\n banner: 'iep3rxsyp9na3rw8',\n },\n} as const;\n"]} \ No newline at end of file diff --git a/dist/esm/web.d.ts b/dist/esm/web.d.ts index bcbb825..955f59d 100644 --- a/dist/esm/web.d.ts +++ b/dist/esm/web.d.ts @@ -1,8 +1,12 @@ import { WebPlugin } from '@capacitor/core'; -import type { AdUnitOptions, ConsentOptions, InitOptions, InitResult, IsReadyResult, LevelPlayPlugin, MetaDataOptions, ShowResult, TrackingResult } from './definitions'; +import type { AdUnitOptions, BannerIdOptions, BannerResult, Capabilities, ConsentOptions, CreateBannerOptions, DynamicUserIdOptions, DynamicUserIdResult, GetRewardOptions, InitOptions, InitResult, IsReadyResult, LevelPlayPlugin, LoadNativeAdOptions, MetaDataOptions, NativeAdIdOptions, NativeAdRectOptions, PlacementCappedOptions, PlacementCappedResult, Reward, SegmentOptions, SetBannerLayoutOptions, ShowResult, TrackingResult } from './definitions'; /** * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves * as "not shown" so callers can treat the web like a no-fill platform without special casing. + * + * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy + * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`, + * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`. */ export declare class LevelPlayWeb extends WebPlugin implements LevelPlayPlugin { private static readonly NO_FILL; @@ -19,4 +23,20 @@ export declare class LevelPlayWeb extends WebPlugin implements LevelPlayPlugin { isReady(): Promise; launchTestSuite(): Promise; validateIntegration(): Promise; + getCapabilities(): Promise; + setSegment(_options: SegmentOptions): Promise; + setDynamicUserId(_options: DynamicUserIdOptions): Promise; + isPlacementCapped(_options: PlacementCappedOptions): Promise; + getReward(_options: GetRewardOptions): Promise; + createBanner(_options: CreateBannerOptions): Promise; + loadBanner(_options: BannerIdOptions): Promise; + showBanner(_options: BannerIdOptions): Promise; + hideBanner(_options: BannerIdOptions): Promise; + setBannerLayout(_options: SetBannerLayoutOptions): Promise; + destroyBanner(_options: BannerIdOptions): Promise; + loadNativeAd(_options: LoadNativeAdOptions): Promise; + showNativeAd(_options: NativeAdRectOptions): Promise; + setNativeAdRect(_options: NativeAdRectOptions): Promise; + hideNativeAd(_options: NativeAdIdOptions): Promise; + destroyNativeAd(_options: NativeAdIdOptions): Promise; } diff --git a/dist/esm/web.js b/dist/esm/web.js index ef4d816..d7200c5 100644 --- a/dist/esm/web.js +++ b/dist/esm/web.js @@ -2,6 +2,10 @@ import { WebPlugin } from '@capacitor/core'; /** * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves * as "not shown" so callers can treat the web like a no-fill platform without special casing. + * + * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy + * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`, + * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`. */ export class LevelPlayWeb extends WebPlugin { async initialize(_options) { @@ -43,6 +47,54 @@ export class LevelPlayWeb extends WebPlugin { async validateIntegration() { /* nothing to validate */ } + async getCapabilities() { + return { banner: false, nativeAd: false, nativeAdTemplates: [], impressionData: false, adInfoChanged: false }; + } + async setSegment(_options) { + /* nothing to forward */ + } + async setDynamicUserId(_options) { + return { valid: false }; + } + async isPlacementCapped(_options) { + return { capped: false }; + } + async getReward(_options) { + return { name: '', amount: 0 }; + } + async createBanner(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async loadBanner(_options) { + /* never fills */ + } + async showBanner(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async hideBanner(_options) { + /* nothing shown */ + } + async setBannerLayout(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async destroyBanner(_options) { + /* nothing to destroy */ + } + async loadNativeAd(_options) { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + async showNativeAd(_options) { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + async setNativeAdRect(_options) { + /* nothing shown */ + } + async hideNativeAd(_options) { + /* nothing shown */ + } + async destroyNativeAd(_options) { + /* nothing to destroy */ + } } LevelPlayWeb.NO_FILL = { shown: false, diff --git a/dist/esm/web.js.map b/dist/esm/web.js.map index 006f397..42e39b5 100644 --- a/dist/esm/web.js.map +++ b/dist/esm/web.js.map @@ -1 +1 @@ -{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAc5C;;;GAGG;AACH,MAAM,OAAO,YAAa,SAAQ,SAAS;IAOzC,KAAK,CAAC,UAAU,CAAC,QAAqB;QACpC,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,aAAa;QACjB,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAwB;QACvC,wBAAwB;IAC1B,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,QAAyB;QACzC,wBAAwB;IAC1B,CAAC;IAED,KAAK,CAAC,4BAA4B;QAChC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,8BAA8B;QAClC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAAuB;QACxC,iBAAiB;IACnB,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAAuB;QACxC,yBAAY,YAAY,CAAC,OAAO,EAAG;IACrC,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,QAAuB;QAC5C,iBAAiB;IACnB,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,QAAuB;QAC5C,yBAAY,YAAY,CAAC,OAAO,EAAG;IACrC,CAAC;IAED,KAAK,CAAC,OAAO;QACX,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,eAAe;QACnB,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,mBAAmB;QACvB,yBAAyB;IAC3B,CAAC;;AAxDuB,oBAAO,GAAe;IAC5C,KAAK,EAAE,KAAK;IACZ,QAAQ,EAAE,KAAK;IACf,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,uCAAuC,EAAE;CACtE,CAAC","sourcesContent":["import { WebPlugin } from '@capacitor/core';\n\nimport type {\n AdUnitOptions,\n ConsentOptions,\n InitOptions,\n InitResult,\n IsReadyResult,\n LevelPlayPlugin,\n MetaDataOptions,\n ShowResult,\n TrackingResult,\n} from './definitions';\n\n/**\n * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves\n * as \"not shown\" so callers can treat the web like a no-fill platform without special casing.\n */\nexport class LevelPlayWeb extends WebPlugin implements LevelPlayPlugin {\n private static readonly NO_FILL: ShowResult = {\n shown: false,\n rewarded: false,\n error: { code: -1, message: 'LevelPlay is not available on the web' },\n };\n\n async initialize(_options: InitOptions): Promise {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n\n async getSdkVersion(): Promise {\n return { sdkVersion: 'web' };\n }\n\n async setConsent(_options: ConsentOptions): Promise {\n /* nothing to forward */\n }\n\n async setMetaData(_options: MetaDataOptions): Promise {\n /* nothing to forward */\n }\n\n async requestTrackingAuthorization(): Promise {\n return { status: 'unavailable' };\n }\n\n async getTrackingAuthorizationStatus(): Promise {\n return { status: 'unavailable' };\n }\n\n async loadRewarded(_options: AdUnitOptions): Promise {\n /* never fills */\n }\n\n async showRewarded(_options: AdUnitOptions): Promise {\n return { ...LevelPlayWeb.NO_FILL };\n }\n\n async loadInterstitial(_options: AdUnitOptions): Promise {\n /* never fills */\n }\n\n async showInterstitial(_options: AdUnitOptions): Promise {\n return { ...LevelPlayWeb.NO_FILL };\n }\n\n async isReady(): Promise {\n return { ready: false };\n }\n\n async launchTestSuite(): Promise {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n\n async validateIntegration(): Promise {\n /* nothing to validate */\n }\n}\n"]} \ No newline at end of file +{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AA6B5C;;;;;;;GAOG;AACH,MAAM,OAAO,YAAa,SAAQ,SAAS;IAOzC,KAAK,CAAC,UAAU,CAAC,QAAqB;QACpC,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,aAAa;QACjB,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAwB;QACvC,wBAAwB;IAC1B,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,QAAyB;QACzC,wBAAwB;IAC1B,CAAC;IAED,KAAK,CAAC,4BAA4B;QAChC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,8BAA8B;QAClC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAAuB;QACxC,iBAAiB;IACnB,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAAuB;QACxC,yBAAY,YAAY,CAAC,OAAO,EAAG;IACrC,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,QAAuB;QAC5C,iBAAiB;IACnB,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,QAAuB;QAC5C,yBAAY,YAAY,CAAC,OAAO,EAAG;IACrC,CAAC;IAED,KAAK,CAAC,OAAO;QACX,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,eAAe;QACnB,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,mBAAmB;QACvB,yBAAyB;IAC3B,CAAC;IAED,KAAK,CAAC,eAAe;QACnB,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,iBAAiB,EAAE,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC;IAChH,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAwB;QACvC,wBAAwB;IAC1B,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,QAA8B;QACnD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,QAAgC;QACtD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,QAA0B;QACxC,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;IACjC,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA6B;QAC9C,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC,CAAC;IAC9E,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAyB;QACxC,iBAAiB;IACnB,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAyB;QACxC,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC,CAAC;IAC9E,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAyB;QACxC,mBAAmB;IACrB,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,QAAgC;QACpD,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC,CAAC;IAC9E,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,QAAyB;QAC3C,wBAAwB;IAC1B,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA6B;QAC9C,MAAM,IAAI,CAAC,aAAa,CAAC,oDAAoD,CAAC,CAAC;IACjF,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA6B;QAC9C,MAAM,IAAI,CAAC,aAAa,CAAC,oDAAoD,CAAC,CAAC;IACjF,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,QAA6B;QACjD,mBAAmB;IACrB,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA2B;QAC5C,mBAAmB;IACrB,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,QAA2B;QAC/C,wBAAwB;IAC1B,CAAC;;AAxHuB,oBAAO,GAAe;IAC5C,KAAK,EAAE,KAAK;IACZ,QAAQ,EAAE,KAAK;IACf,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,uCAAuC,EAAE;CACtE,CAAC","sourcesContent":["import { WebPlugin } from '@capacitor/core';\n\nimport type {\n AdUnitOptions,\n BannerIdOptions,\n BannerResult,\n Capabilities,\n ConsentOptions,\n CreateBannerOptions,\n DynamicUserIdOptions,\n DynamicUserIdResult,\n GetRewardOptions,\n InitOptions,\n InitResult,\n IsReadyResult,\n LevelPlayPlugin,\n LoadNativeAdOptions,\n MetaDataOptions,\n NativeAdIdOptions,\n NativeAdRectOptions,\n PlacementCappedOptions,\n PlacementCappedResult,\n Reward,\n SegmentOptions,\n SetBannerLayoutOptions,\n ShowResult,\n TrackingResult,\n} from './definitions';\n\n/**\n * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves\n * as \"not shown\" so callers can treat the web like a no-fill platform without special casing.\n *\n * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy\n * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`,\n * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`.\n */\nexport class LevelPlayWeb extends WebPlugin implements LevelPlayPlugin {\n private static readonly NO_FILL: ShowResult = {\n shown: false,\n rewarded: false,\n error: { code: -1, message: 'LevelPlay is not available on the web' },\n };\n\n async initialize(_options: InitOptions): Promise {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n\n async getSdkVersion(): Promise {\n return { sdkVersion: 'web' };\n }\n\n async setConsent(_options: ConsentOptions): Promise {\n /* nothing to forward */\n }\n\n async setMetaData(_options: MetaDataOptions): Promise {\n /* nothing to forward */\n }\n\n async requestTrackingAuthorization(): Promise {\n return { status: 'unavailable' };\n }\n\n async getTrackingAuthorizationStatus(): Promise {\n return { status: 'unavailable' };\n }\n\n async loadRewarded(_options: AdUnitOptions): Promise {\n /* never fills */\n }\n\n async showRewarded(_options: AdUnitOptions): Promise {\n return { ...LevelPlayWeb.NO_FILL };\n }\n\n async loadInterstitial(_options: AdUnitOptions): Promise {\n /* never fills */\n }\n\n async showInterstitial(_options: AdUnitOptions): Promise {\n return { ...LevelPlayWeb.NO_FILL };\n }\n\n async isReady(): Promise {\n return { ready: false };\n }\n\n async launchTestSuite(): Promise {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n\n async validateIntegration(): Promise {\n /* nothing to validate */\n }\n\n async getCapabilities(): Promise {\n return { banner: false, nativeAd: false, nativeAdTemplates: [], impressionData: false, adInfoChanged: false };\n }\n\n async setSegment(_options: SegmentOptions): Promise {\n /* nothing to forward */\n }\n\n async setDynamicUserId(_options: DynamicUserIdOptions): Promise {\n return { valid: false };\n }\n\n async isPlacementCapped(_options: PlacementCappedOptions): Promise {\n return { capped: false };\n }\n\n async getReward(_options: GetRewardOptions): Promise {\n return { name: '', amount: 0 };\n }\n\n async createBanner(_options: CreateBannerOptions): Promise {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n\n async loadBanner(_options: BannerIdOptions): Promise {\n /* never fills */\n }\n\n async showBanner(_options: BannerIdOptions): Promise {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n\n async hideBanner(_options: BannerIdOptions): Promise {\n /* nothing shown */\n }\n\n async setBannerLayout(_options: SetBannerLayoutOptions): Promise {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n\n async destroyBanner(_options: BannerIdOptions): Promise {\n /* nothing to destroy */\n }\n\n async loadNativeAd(_options: LoadNativeAdOptions): Promise {\n throw this.unimplemented('LevelPlay native ads are not available on the web.');\n }\n\n async showNativeAd(_options: NativeAdRectOptions): Promise {\n throw this.unimplemented('LevelPlay native ads are not available on the web.');\n }\n\n async setNativeAdRect(_options: NativeAdRectOptions): Promise {\n /* nothing shown */\n }\n\n async hideNativeAd(_options: NativeAdIdOptions): Promise {\n /* nothing shown */\n }\n\n async destroyNativeAd(_options: NativeAdIdOptions): Promise {\n /* nothing to destroy */\n }\n}\n"]} \ No newline at end of file diff --git a/dist/plugin.cjs.js b/dist/plugin.cjs.js index 2911d37..c1eca96 100644 --- a/dist/plugin.cjs.js +++ b/dist/plugin.cjs.js @@ -6,6 +6,7 @@ var core = require('@capacitor/core'); * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only. + * The sample apps have no native ad placement; native ads load with the default placement of the app key. * Replace them with your own ids from the LevelPlay dashboard before release. */ const LEVELPLAY_DEMO = { @@ -13,11 +14,13 @@ const LEVELPLAY_DEMO = { appKey: '25b63cf85', rewarded: 'syz3d8ekts22q0or', interstitial: 'h3xw38h9214adgxo', + banner: '4fpetq4lhe5lsw3e', }, ios: { appKey: '8545d445', rewarded: 'qwouvdrkuwivay5q', interstitial: 'wmgt0712uuux8ju4', + banner: 'iep3rxsyp9na3rw8', }, }; @@ -28,6 +31,10 @@ const LevelPlay = core.registerPlugin('LevelPlay', { /** * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves * as "not shown" so callers can treat the web like a no-fill platform without special casing. + * + * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy + * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`, + * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`. */ class LevelPlayWeb extends core.WebPlugin { async initialize(_options) { @@ -69,6 +76,54 @@ class LevelPlayWeb extends core.WebPlugin { async validateIntegration() { /* nothing to validate */ } + async getCapabilities() { + return { banner: false, nativeAd: false, nativeAdTemplates: [], impressionData: false, adInfoChanged: false }; + } + async setSegment(_options) { + /* nothing to forward */ + } + async setDynamicUserId(_options) { + return { valid: false }; + } + async isPlacementCapped(_options) { + return { capped: false }; + } + async getReward(_options) { + return { name: '', amount: 0 }; + } + async createBanner(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async loadBanner(_options) { + /* never fills */ + } + async showBanner(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async hideBanner(_options) { + /* nothing shown */ + } + async setBannerLayout(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async destroyBanner(_options) { + /* nothing to destroy */ + } + async loadNativeAd(_options) { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + async showNativeAd(_options) { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + async setNativeAdRect(_options) { + /* nothing shown */ + } + async hideNativeAd(_options) { + /* nothing shown */ + } + async destroyNativeAd(_options) { + /* nothing to destroy */ + } } LevelPlayWeb.NO_FILL = { shown: false, diff --git a/dist/plugin.cjs.js.map b/dist/plugin.cjs.js.map index 4d13f30..f6c9e5c 100644 --- a/dist/plugin.cjs.js.map +++ b/dist/plugin.cjs.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin.cjs.js","sources":["esm/demo.js","esm/index.js","esm/web.js"],"sourcesContent":["/**\n * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps\n * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and\n * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only.\n * Replace them with your own ids from the LevelPlay dashboard before release.\n */\nexport const LEVELPLAY_DEMO = {\n android: {\n appKey: '25b63cf85',\n rewarded: 'syz3d8ekts22q0or',\n interstitial: 'h3xw38h9214adgxo',\n },\n ios: {\n appKey: '8545d445',\n rewarded: 'qwouvdrkuwivay5q',\n interstitial: 'wmgt0712uuux8ju4',\n },\n};\n//# sourceMappingURL=demo.js.map","import { registerPlugin } from '@capacitor/core';\nconst LevelPlay = registerPlugin('LevelPlay', {\n web: () => import('./web').then((m) => new m.LevelPlayWeb()),\n});\nexport * from './definitions';\nexport { LEVELPLAY_DEMO } from './demo';\nexport { LevelPlay };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves\n * as \"not shown\" so callers can treat the web like a no-fill platform without special casing.\n */\nexport class LevelPlayWeb extends WebPlugin {\n async initialize(_options) {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async getSdkVersion() {\n return { sdkVersion: 'web' };\n }\n async setConsent(_options) {\n /* nothing to forward */\n }\n async setMetaData(_options) {\n /* nothing to forward */\n }\n async requestTrackingAuthorization() {\n return { status: 'unavailable' };\n }\n async getTrackingAuthorizationStatus() {\n return { status: 'unavailable' };\n }\n async loadRewarded(_options) {\n /* never fills */\n }\n async showRewarded(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async loadInterstitial(_options) {\n /* never fills */\n }\n async showInterstitial(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async isReady() {\n return { ready: false };\n }\n async launchTestSuite() {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async validateIntegration() {\n /* nothing to validate */\n }\n}\nLevelPlayWeb.NO_FILL = {\n shown: false,\n rewarded: false,\n error: { code: -1, message: 'LevelPlay is not available on the web' },\n};\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG;AAC9B,IAAI,OAAO,EAAE;AACb,QAAQ,MAAM,EAAE,WAAW;AAC3B,QAAQ,QAAQ,EAAE,kBAAkB;AACpC,QAAQ,YAAY,EAAE,kBAAkB;AACxC,KAAK;AACL,IAAI,GAAG,EAAE;AACT,QAAQ,MAAM,EAAE,UAAU;AAC1B,QAAQ,QAAQ,EAAE,kBAAkB;AACpC,QAAQ,YAAY,EAAE,kBAAkB;AACxC,KAAK;AACL;;AChBK,MAAC,SAAS,GAAGA,mBAAc,CAAC,WAAW,EAAE;AAC9C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY,EAAE,CAAC;AAChE,CAAC;;ACFD;AACA;AACA;AACA;AACO,MAAM,YAAY,SAASC,cAAS,CAAC;AAC5C,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;AAC1E,IAAI;AACJ,IAAI,MAAM,aAAa,GAAG;AAC1B,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE;AACpC,IAAI;AACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B;AACA,IAAI;AACJ,IAAI,MAAM,WAAW,CAAC,QAAQ,EAAE;AAChC;AACA,IAAI;AACJ,IAAI,MAAM,4BAA4B,GAAG;AACzC,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;AACxC,IAAI;AACJ,IAAI,MAAM,8BAA8B,GAAG;AAC3C,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;AACxC,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC;AACA,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;AACtD,IAAI;AACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;AACrC;AACA,IAAI;AACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;AACrC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;AACtD,IAAI;AACJ,IAAI,MAAM,OAAO,GAAG;AACpB,QAAQ,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE;AAC/B,IAAI;AACJ,IAAI,MAAM,eAAe,GAAG;AAC5B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;AAC1E,IAAI;AACJ,IAAI,MAAM,mBAAmB,GAAG;AAChC;AACA,IAAI;AACJ;AACA,YAAY,CAAC,OAAO,GAAG;AACvB,IAAI,KAAK,EAAE,KAAK;AAChB,IAAI,QAAQ,EAAE,KAAK;AACnB,IAAI,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,uCAAuC,EAAE;AACzE,CAAC;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"plugin.cjs.js","sources":["esm/demo.js","esm/index.js","esm/web.js"],"sourcesContent":["/**\n * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps\n * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and\n * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only.\n * The sample apps have no native ad placement; native ads load with the default placement of the app key.\n * Replace them with your own ids from the LevelPlay dashboard before release.\n */\nexport const LEVELPLAY_DEMO = {\n android: {\n appKey: '25b63cf85',\n rewarded: 'syz3d8ekts22q0or',\n interstitial: 'h3xw38h9214adgxo',\n banner: '4fpetq4lhe5lsw3e',\n },\n ios: {\n appKey: '8545d445',\n rewarded: 'qwouvdrkuwivay5q',\n interstitial: 'wmgt0712uuux8ju4',\n banner: 'iep3rxsyp9na3rw8',\n },\n};\n//# sourceMappingURL=demo.js.map","import { registerPlugin } from '@capacitor/core';\nconst LevelPlay = registerPlugin('LevelPlay', {\n web: () => import('./web').then((m) => new m.LevelPlayWeb()),\n});\nexport * from './definitions';\nexport { LEVELPLAY_DEMO } from './demo';\nexport { LevelPlay };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves\n * as \"not shown\" so callers can treat the web like a no-fill platform without special casing.\n *\n * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy\n * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`,\n * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`.\n */\nexport class LevelPlayWeb extends WebPlugin {\n async initialize(_options) {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async getSdkVersion() {\n return { sdkVersion: 'web' };\n }\n async setConsent(_options) {\n /* nothing to forward */\n }\n async setMetaData(_options) {\n /* nothing to forward */\n }\n async requestTrackingAuthorization() {\n return { status: 'unavailable' };\n }\n async getTrackingAuthorizationStatus() {\n return { status: 'unavailable' };\n }\n async loadRewarded(_options) {\n /* never fills */\n }\n async showRewarded(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async loadInterstitial(_options) {\n /* never fills */\n }\n async showInterstitial(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async isReady() {\n return { ready: false };\n }\n async launchTestSuite() {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async validateIntegration() {\n /* nothing to validate */\n }\n async getCapabilities() {\n return { banner: false, nativeAd: false, nativeAdTemplates: [], impressionData: false, adInfoChanged: false };\n }\n async setSegment(_options) {\n /* nothing to forward */\n }\n async setDynamicUserId(_options) {\n return { valid: false };\n }\n async isPlacementCapped(_options) {\n return { capped: false };\n }\n async getReward(_options) {\n return { name: '', amount: 0 };\n }\n async createBanner(_options) {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n async loadBanner(_options) {\n /* never fills */\n }\n async showBanner(_options) {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n async hideBanner(_options) {\n /* nothing shown */\n }\n async setBannerLayout(_options) {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n async destroyBanner(_options) {\n /* nothing to destroy */\n }\n async loadNativeAd(_options) {\n throw this.unimplemented('LevelPlay native ads are not available on the web.');\n }\n async showNativeAd(_options) {\n throw this.unimplemented('LevelPlay native ads are not available on the web.');\n }\n async setNativeAdRect(_options) {\n /* nothing shown */\n }\n async hideNativeAd(_options) {\n /* nothing shown */\n }\n async destroyNativeAd(_options) {\n /* nothing to destroy */\n }\n}\nLevelPlayWeb.NO_FILL = {\n shown: false,\n rewarded: false,\n error: { code: -1, message: 'LevelPlay is not available on the web' },\n};\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG;AAC9B,IAAI,OAAO,EAAE;AACb,QAAQ,MAAM,EAAE,WAAW;AAC3B,QAAQ,QAAQ,EAAE,kBAAkB;AACpC,QAAQ,YAAY,EAAE,kBAAkB;AACxC,QAAQ,MAAM,EAAE,kBAAkB;AAClC,KAAK;AACL,IAAI,GAAG,EAAE;AACT,QAAQ,MAAM,EAAE,UAAU;AAC1B,QAAQ,QAAQ,EAAE,kBAAkB;AACpC,QAAQ,YAAY,EAAE,kBAAkB;AACxC,QAAQ,MAAM,EAAE,kBAAkB;AAClC,KAAK;AACL;;ACnBK,MAAC,SAAS,GAAGA,mBAAc,CAAC,WAAW,EAAE;AAC9C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY,EAAE,CAAC;AAChE,CAAC;;ACFD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,YAAY,SAASC,cAAS,CAAC;AAC5C,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;AAC1E,IAAI;AACJ,IAAI,MAAM,aAAa,GAAG;AAC1B,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE;AACpC,IAAI;AACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B;AACA,IAAI;AACJ,IAAI,MAAM,WAAW,CAAC,QAAQ,EAAE;AAChC;AACA,IAAI;AACJ,IAAI,MAAM,4BAA4B,GAAG;AACzC,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;AACxC,IAAI;AACJ,IAAI,MAAM,8BAA8B,GAAG;AAC3C,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;AACxC,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC;AACA,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;AACtD,IAAI;AACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;AACrC;AACA,IAAI;AACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;AACrC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;AACtD,IAAI;AACJ,IAAI,MAAM,OAAO,GAAG;AACpB,QAAQ,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE;AAC/B,IAAI;AACJ,IAAI,MAAM,eAAe,GAAG;AAC5B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;AAC1E,IAAI;AACJ,IAAI,MAAM,mBAAmB,GAAG;AAChC;AACA,IAAI;AACJ,IAAI,MAAM,eAAe,GAAG;AAC5B,QAAQ,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,iBAAiB,EAAE,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE;AACrH,IAAI;AACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B;AACA,IAAI;AACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;AACrC,QAAQ,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE;AAC/B,IAAI;AACJ,IAAI,MAAM,iBAAiB,CAAC,QAAQ,EAAE;AACtC,QAAQ,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE;AAChC,IAAI;AACJ,IAAI,MAAM,SAAS,CAAC,QAAQ,EAAE;AAC9B,QAAQ,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE;AACtC,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC;AACnF,IAAI;AACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B;AACA,IAAI;AACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC;AACnF,IAAI;AACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B;AACA,IAAI;AACJ,IAAI,MAAM,eAAe,CAAC,QAAQ,EAAE;AACpC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC;AACnF,IAAI;AACJ,IAAI,MAAM,aAAa,CAAC,QAAQ,EAAE;AAClC;AACA,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,oDAAoD,CAAC;AACtF,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,oDAAoD,CAAC;AACtF,IAAI;AACJ,IAAI,MAAM,eAAe,CAAC,QAAQ,EAAE;AACpC;AACA,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;AACjC;AACA,IAAI;AACJ,IAAI,MAAM,eAAe,CAAC,QAAQ,EAAE;AACpC;AACA,IAAI;AACJ;AACA,YAAY,CAAC,OAAO,GAAG;AACvB,IAAI,KAAK,EAAE,KAAK;AAChB,IAAI,QAAQ,EAAE,KAAK;AACnB,IAAI,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,uCAAuC,EAAE;AACzE,CAAC;;;;;;;;"} \ No newline at end of file diff --git a/dist/plugin.js b/dist/plugin.js index 10e684f..2a7ae65 100644 --- a/dist/plugin.js +++ b/dist/plugin.js @@ -5,6 +5,7 @@ var capacitorLevelPlay = (function (exports, core) { * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only. + * The sample apps have no native ad placement; native ads load with the default placement of the app key. * Replace them with your own ids from the LevelPlay dashboard before release. */ const LEVELPLAY_DEMO = { @@ -12,11 +13,13 @@ var capacitorLevelPlay = (function (exports, core) { appKey: '25b63cf85', rewarded: 'syz3d8ekts22q0or', interstitial: 'h3xw38h9214adgxo', + banner: '4fpetq4lhe5lsw3e', }, ios: { appKey: '8545d445', rewarded: 'qwouvdrkuwivay5q', interstitial: 'wmgt0712uuux8ju4', + banner: 'iep3rxsyp9na3rw8', }, }; @@ -27,6 +30,10 @@ var capacitorLevelPlay = (function (exports, core) { /** * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves * as "not shown" so callers can treat the web like a no-fill platform without special casing. + * + * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy + * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`, + * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`. */ class LevelPlayWeb extends core.WebPlugin { async initialize(_options) { @@ -68,6 +75,54 @@ var capacitorLevelPlay = (function (exports, core) { async validateIntegration() { /* nothing to validate */ } + async getCapabilities() { + return { banner: false, nativeAd: false, nativeAdTemplates: [], impressionData: false, adInfoChanged: false }; + } + async setSegment(_options) { + /* nothing to forward */ + } + async setDynamicUserId(_options) { + return { valid: false }; + } + async isPlacementCapped(_options) { + return { capped: false }; + } + async getReward(_options) { + return { name: '', amount: 0 }; + } + async createBanner(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async loadBanner(_options) { + /* never fills */ + } + async showBanner(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async hideBanner(_options) { + /* nothing shown */ + } + async setBannerLayout(_options) { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + async destroyBanner(_options) { + /* nothing to destroy */ + } + async loadNativeAd(_options) { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + async showNativeAd(_options) { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + async setNativeAdRect(_options) { + /* nothing shown */ + } + async hideNativeAd(_options) { + /* nothing shown */ + } + async destroyNativeAd(_options) { + /* nothing to destroy */ + } } LevelPlayWeb.NO_FILL = { shown: false, diff --git a/dist/plugin.js.map b/dist/plugin.js.map index 9ae7346..426dd5d 100644 --- a/dist/plugin.js.map +++ b/dist/plugin.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin.js","sources":["esm/demo.js","esm/index.js","esm/web.js"],"sourcesContent":["/**\n * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps\n * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and\n * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only.\n * Replace them with your own ids from the LevelPlay dashboard before release.\n */\nexport const LEVELPLAY_DEMO = {\n android: {\n appKey: '25b63cf85',\n rewarded: 'syz3d8ekts22q0or',\n interstitial: 'h3xw38h9214adgxo',\n },\n ios: {\n appKey: '8545d445',\n rewarded: 'qwouvdrkuwivay5q',\n interstitial: 'wmgt0712uuux8ju4',\n },\n};\n//# sourceMappingURL=demo.js.map","import { registerPlugin } from '@capacitor/core';\nconst LevelPlay = registerPlugin('LevelPlay', {\n web: () => import('./web').then((m) => new m.LevelPlayWeb()),\n});\nexport * from './definitions';\nexport { LEVELPLAY_DEMO } from './demo';\nexport { LevelPlay };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves\n * as \"not shown\" so callers can treat the web like a no-fill platform without special casing.\n */\nexport class LevelPlayWeb extends WebPlugin {\n async initialize(_options) {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async getSdkVersion() {\n return { sdkVersion: 'web' };\n }\n async setConsent(_options) {\n /* nothing to forward */\n }\n async setMetaData(_options) {\n /* nothing to forward */\n }\n async requestTrackingAuthorization() {\n return { status: 'unavailable' };\n }\n async getTrackingAuthorizationStatus() {\n return { status: 'unavailable' };\n }\n async loadRewarded(_options) {\n /* never fills */\n }\n async showRewarded(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async loadInterstitial(_options) {\n /* never fills */\n }\n async showInterstitial(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async isReady() {\n return { ready: false };\n }\n async launchTestSuite() {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async validateIntegration() {\n /* nothing to validate */\n }\n}\nLevelPlayWeb.NO_FILL = {\n shown: false,\n rewarded: false,\n error: { code: -1, message: 'LevelPlay is not available on the web' },\n};\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;IAAA;IACA;IACA;IACA;IACA;IACA;AACY,UAAC,cAAc,GAAG;IAC9B,IAAI,OAAO,EAAE;IACb,QAAQ,MAAM,EAAE,WAAW;IAC3B,QAAQ,QAAQ,EAAE,kBAAkB;IACpC,QAAQ,YAAY,EAAE,kBAAkB;IACxC,KAAK;IACL,IAAI,GAAG,EAAE;IACT,QAAQ,MAAM,EAAE,UAAU;IAC1B,QAAQ,QAAQ,EAAE,kBAAkB;IACpC,QAAQ,YAAY,EAAE,kBAAkB;IACxC,KAAK;IACL;;AChBK,UAAC,SAAS,GAAGA,mBAAc,CAAC,WAAW,EAAE;IAC9C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY,EAAE,CAAC;IAChE,CAAC;;ICFD;IACA;IACA;IACA;IACO,MAAM,YAAY,SAASC,cAAS,CAAC;IAC5C,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;IAC1E,IAAI;IACJ,IAAI,MAAM,aAAa,GAAG;IAC1B,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE;IACpC,IAAI;IACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B;IACA,IAAI;IACJ,IAAI,MAAM,WAAW,CAAC,QAAQ,EAAE;IAChC;IACA,IAAI;IACJ,IAAI,MAAM,4BAA4B,GAAG;IACzC,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;IACxC,IAAI;IACJ,IAAI,MAAM,8BAA8B,GAAG;IAC3C,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;IACxC,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC;IACA,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;IACtD,IAAI;IACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;IACrC;IACA,IAAI;IACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;IACrC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;IACtD,IAAI;IACJ,IAAI,MAAM,OAAO,GAAG;IACpB,QAAQ,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE;IAC/B,IAAI;IACJ,IAAI,MAAM,eAAe,GAAG;IAC5B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;IAC1E,IAAI;IACJ,IAAI,MAAM,mBAAmB,GAAG;IAChC;IACA,IAAI;IACJ;IACA,YAAY,CAAC,OAAO,GAAG;IACvB,IAAI,KAAK,EAAE,KAAK;IAChB,IAAI,QAAQ,EAAE,KAAK;IACnB,IAAI,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,uCAAuC,EAAE;IACzE,CAAC;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"plugin.js","sources":["esm/demo.js","esm/index.js","esm/web.js"],"sourcesContent":["/**\n * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps\n * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and\n * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only.\n * The sample apps have no native ad placement; native ads load with the default placement of the app key.\n * Replace them with your own ids from the LevelPlay dashboard before release.\n */\nexport const LEVELPLAY_DEMO = {\n android: {\n appKey: '25b63cf85',\n rewarded: 'syz3d8ekts22q0or',\n interstitial: 'h3xw38h9214adgxo',\n banner: '4fpetq4lhe5lsw3e',\n },\n ios: {\n appKey: '8545d445',\n rewarded: 'qwouvdrkuwivay5q',\n interstitial: 'wmgt0712uuux8ju4',\n banner: 'iep3rxsyp9na3rw8',\n },\n};\n//# sourceMappingURL=demo.js.map","import { registerPlugin } from '@capacitor/core';\nconst LevelPlay = registerPlugin('LevelPlay', {\n web: () => import('./web').then((m) => new m.LevelPlayWeb()),\n});\nexport * from './definitions';\nexport { LEVELPLAY_DEMO } from './demo';\nexport { LevelPlay };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves\n * as \"not shown\" so callers can treat the web like a no-fill platform without special casing.\n *\n * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy\n * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`,\n * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`.\n */\nexport class LevelPlayWeb extends WebPlugin {\n async initialize(_options) {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async getSdkVersion() {\n return { sdkVersion: 'web' };\n }\n async setConsent(_options) {\n /* nothing to forward */\n }\n async setMetaData(_options) {\n /* nothing to forward */\n }\n async requestTrackingAuthorization() {\n return { status: 'unavailable' };\n }\n async getTrackingAuthorizationStatus() {\n return { status: 'unavailable' };\n }\n async loadRewarded(_options) {\n /* never fills */\n }\n async showRewarded(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async loadInterstitial(_options) {\n /* never fills */\n }\n async showInterstitial(_options) {\n return Object.assign({}, LevelPlayWeb.NO_FILL);\n }\n async isReady() {\n return { ready: false };\n }\n async launchTestSuite() {\n throw this.unimplemented('LevelPlay is not available on the web.');\n }\n async validateIntegration() {\n /* nothing to validate */\n }\n async getCapabilities() {\n return { banner: false, nativeAd: false, nativeAdTemplates: [], impressionData: false, adInfoChanged: false };\n }\n async setSegment(_options) {\n /* nothing to forward */\n }\n async setDynamicUserId(_options) {\n return { valid: false };\n }\n async isPlacementCapped(_options) {\n return { capped: false };\n }\n async getReward(_options) {\n return { name: '', amount: 0 };\n }\n async createBanner(_options) {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n async loadBanner(_options) {\n /* never fills */\n }\n async showBanner(_options) {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n async hideBanner(_options) {\n /* nothing shown */\n }\n async setBannerLayout(_options) {\n throw this.unimplemented('LevelPlay banners are not available on the web.');\n }\n async destroyBanner(_options) {\n /* nothing to destroy */\n }\n async loadNativeAd(_options) {\n throw this.unimplemented('LevelPlay native ads are not available on the web.');\n }\n async showNativeAd(_options) {\n throw this.unimplemented('LevelPlay native ads are not available on the web.');\n }\n async setNativeAdRect(_options) {\n /* nothing shown */\n }\n async hideNativeAd(_options) {\n /* nothing shown */\n }\n async destroyNativeAd(_options) {\n /* nothing to destroy */\n }\n}\nLevelPlayWeb.NO_FILL = {\n shown: false,\n rewarded: false,\n error: { code: -1, message: 'LevelPlay is not available on the web' },\n};\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;IAAA;IACA;IACA;IACA;IACA;IACA;IACA;AACY,UAAC,cAAc,GAAG;IAC9B,IAAI,OAAO,EAAE;IACb,QAAQ,MAAM,EAAE,WAAW;IAC3B,QAAQ,QAAQ,EAAE,kBAAkB;IACpC,QAAQ,YAAY,EAAE,kBAAkB;IACxC,QAAQ,MAAM,EAAE,kBAAkB;IAClC,KAAK;IACL,IAAI,GAAG,EAAE;IACT,QAAQ,MAAM,EAAE,UAAU;IAC1B,QAAQ,QAAQ,EAAE,kBAAkB;IACpC,QAAQ,YAAY,EAAE,kBAAkB;IACxC,QAAQ,MAAM,EAAE,kBAAkB;IAClC,KAAK;IACL;;ACnBK,UAAC,SAAS,GAAGA,mBAAc,CAAC,WAAW,EAAE;IAC9C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY,EAAE,CAAC;IAChE,CAAC;;ICFD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACO,MAAM,YAAY,SAASC,cAAS,CAAC;IAC5C,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;IAC1E,IAAI;IACJ,IAAI,MAAM,aAAa,GAAG;IAC1B,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE;IACpC,IAAI;IACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B;IACA,IAAI;IACJ,IAAI,MAAM,WAAW,CAAC,QAAQ,EAAE;IAChC;IACA,IAAI;IACJ,IAAI,MAAM,4BAA4B,GAAG;IACzC,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;IACxC,IAAI;IACJ,IAAI,MAAM,8BAA8B,GAAG;IAC3C,QAAQ,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE;IACxC,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC;IACA,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;IACtD,IAAI;IACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;IACrC;IACA,IAAI;IACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;IACrC,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC;IACtD,IAAI;IACJ,IAAI,MAAM,OAAO,GAAG;IACpB,QAAQ,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE;IAC/B,IAAI;IACJ,IAAI,MAAM,eAAe,GAAG;IAC5B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,wCAAwC,CAAC;IAC1E,IAAI;IACJ,IAAI,MAAM,mBAAmB,GAAG;IAChC;IACA,IAAI;IACJ,IAAI,MAAM,eAAe,GAAG;IAC5B,QAAQ,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,iBAAiB,EAAE,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE;IACrH,IAAI;IACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B;IACA,IAAI;IACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;IACrC,QAAQ,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE;IAC/B,IAAI;IACJ,IAAI,MAAM,iBAAiB,CAAC,QAAQ,EAAE;IACtC,QAAQ,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE;IAChC,IAAI;IACJ,IAAI,MAAM,SAAS,CAAC,QAAQ,EAAE;IAC9B,QAAQ,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE;IACtC,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC;IACnF,IAAI;IACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B;IACA,IAAI;IACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC;IACnF,IAAI;IACJ,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;IAC/B;IACA,IAAI;IACJ,IAAI,MAAM,eAAe,CAAC,QAAQ,EAAE;IACpC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,iDAAiD,CAAC;IACnF,IAAI;IACJ,IAAI,MAAM,aAAa,CAAC,QAAQ,EAAE;IAClC;IACA,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,oDAAoD,CAAC;IACtF,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,oDAAoD,CAAC;IACtF,IAAI;IACJ,IAAI,MAAM,eAAe,CAAC,QAAQ,EAAE;IACpC;IACA,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC;IACA,IAAI;IACJ,IAAI,MAAM,eAAe,CAAC,QAAQ,EAAE;IACpC;IACA,IAAI;IACJ;IACA,YAAY,CAAC,OAAO,GAAG;IACvB,IAAI,KAAK,EAAE,KAAK;IAChB,IAAI,QAAQ,EAAE,KAAK;IACnB,IAAI,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,uCAAuC,EAAE;IACzE,CAAC;;;;;;;;;;;;"} \ No newline at end of file diff --git a/docs/design-0.3.md b/docs/design-0.3.md new file mode 100644 index 0000000..7b53a3e --- /dev/null +++ b/docs/design-0.3.md @@ -0,0 +1,590 @@ +# capacitor-levelplay 0.3.0 · API design + +Status: phase 3. `src/definitions.ts` and `src/web.ts` carry the new API; the Android bridge (phase 2, §15) and the +iOS bridge (phase 3, §16) implement all of it. The owner's answers to the open questions are recorded in §14. + +Scope (owner approved): banners, native ads (template overlay), impression-level revenue, `adInfoChanged`, placement +capping and reward lookup, segments, dynamic user id, full backwards compatibility with 0.2.x, and a Capacitor 7 +compatibility study. + +## 0. Sources and method + +Every native name below was read from the SDK binaries of **LevelPlay 9.6.1**, not only from the docs: + +- **Android**: `com.unity3d.ads-mediation:mediation-sdk:9.6.1` AAR from Maven Central, `classes.jar` listed with + `javap -public` (JDK 21). The AAR manifest declares `minSdkVersion="19"`. +- **iOS**: `IronSource.xcframework` (`CFBundleShortVersionString` 9.6.1, `MinimumOSVersion` 12.0) from the + `LevelPlay-Swift-Package` SPM checkout, `ios-arm64/IronSource.framework/Headers/*.h`. `IronSource.h` defines + `MEDIATION_SDK_VERSION = @"9.6.1"`. The framework ships no `.swiftinterface`; Swift names come from + `NS_SWIFT_NAME` annotations and the ObjC importer. +- Unity docs (behaviour, not names): `docs.unity.com/en-us/grow/levelplay/sdk/{android,ios}/banner-integration`, + `.../android/native-ads-integration`, `.../flutter/native-ads-integration`. +- Capacitor: `@capacitor/android` and `@capacitor/ios` 7.6.9 and 8.5.3 npm tarballs, diffed. + +Notation: `A:` Android (package `com.unity3d.mediation` unless a full name is given), `I:` iOS (header file name). + +## 1. Compatibility rules for 0.3.0 + +- No existing method, option, event or type is renamed or removed. `AdFormat` stays `'rewarded' | 'interstitial'` + (widening it would break exhaustive `switch` statements in 0.2.x code), so banners and native ads get their own + methods and their own event names (`banner*`, `nativeAd*`) instead of reusing `loaded`, `clicked` ... +- `AdInfo` only gains optional fields. `LevelPlayEventName` only gains members. +- Existing events keep their payloads; `adInfoChanged` and `impressionData` are new names. +- Reject codes reuse the existing string style (`INVALID_ARGUMENT`, `NO_VIEW_CONTROLLER`). + +## 2. Capabilities + +`getCapabilities(): Promise` → `{ banner, nativeAd, nativeAdTemplates, impressionData, adInfoChanged }`. + +| | Android | iOS | Web | +|---|---|---|---| +| `banner` | true | true | false | +| `nativeAd` | true | true | false | +| `nativeAdTemplates` | `['small','medium']` | `['small','medium']` | `[]` | +| `impressionData` | true | true | false | +| `adInfoChanged` | true | true | false | + +It is the honest switch the owner asked for: if a platform implementation ever has to drop a feature (for example +templates do not pass review on one OS), the flag goes `false` and the methods reject `UNSUPPORTED`, without an API +change. + +## 3. Banners + +### 3.1 TS API + +```ts +createBanner({ adUnitId, bannerId?, size?: 'BANNER'|'LARGE'|'MEDIUM_RECTANGLE'|'LEADERBOARD'|'ADAPTIVE'|'CUSTOM', + customSize?: { width, height }, adaptiveWidth?, placementName?, bidFloor?, position?: 'top'|'bottom'|'center', + offsetX?, offsetY?, respectSafeArea? }): Promise +loadBanner({ bannerId }): Promise +showBanner({ bannerId }): Promise +hideBanner({ bannerId }): Promise +setBannerLayout({ bannerId, position?, offsetX?, offsetY?, respectSafeArea? }): Promise +destroyBanner({ bannerId }): Promise +// BannerResult = { bannerId, adSize: { width, height, description?, isAdaptive? }, frame: Rect, visible } +``` + +Defaults: `bannerId = adUnitId`, `size = 'ADAPTIVE'` (`'CUSTOM'` when only `customSize` is given), `position = 'bottom'`, offsets 0, `respectSafeArea = true`. +Several banners can exist at once, keyed by `bannerId` (one ad unit may back several banners). + +Typical flow: `createBanner` → `loadBanner` → `showBanner` (immediately, or on `bannerLoaded`) → `hideBanner` during +gameplay → `showBanner` → `destroyBanner` when leaving the screen. + +### 3.2 Native mapping + +| Plugin | Android (`com.unity3d.mediation.banner`) | iOS | +|---|---|---| +| view class | `LevelPlayBannerAdView extends FrameLayout`, ctor `(Context, String adUnitId, LevelPlayBannerAdView.Config)` | `LPMBannerAdView : UIView`, `initWithAdUnitId:config:` (LPMBannerAdView.h) | +| config | `LevelPlayBannerAdView.Config.Builder().setAdSize(LevelPlayAdSize).setBidFloor(double).setPlacementName(String).build()` | `LPMBannerAdViewConfigBuilder` `set(adSize:)`, `set(bidFloor:)` (NSNumber), `set(placementName:)`, `build()` | +| `BANNER` | `LevelPlayAdSize.BANNER` | `LPMAdSize.bannerSize()` | +| `LARGE` | `LevelPlayAdSize.LARGE` | `LPMAdSize.largeSize()` | +| `MEDIUM_RECTANGLE` | `LevelPlayAdSize.MEDIUM_RECTANGLE` | `LPMAdSize.mediumRectangleSize()` | +| `LEADERBOARD` | `LevelPlayAdSize.LEADERBOARD` | `LPMAdSize.leaderBoardSize()` | +| `ADAPTIVE` | `LevelPlayAdSize.createAdaptiveAdSize(Context, Integer width)` | `LPMAdSize.createAdaptiveAdSize(withWidth: CGFloat)` (nullable: `nil` before init) | +| `CUSTOM` (Q5) | `LevelPlayAdSize.createCustomSize(int width, int height)` (dp) | `LPMAdSize.customSizeWithWidth:height:` | +| size readout | `getWidth()`, `getHeight()`, `getDescription()`, `isAdaptive()` | `width`, `height`, `sizeDescription`, `isAdaptive` | +| listener | `setBannerListener(LevelPlayBannerAdViewListener)` | `setDelegate(LPMBannerAdViewDelegate)` | +| impression data | `setImpressionDataListener(LevelPlayImpressionDataListener)` | `setImpressionDataDelegate:` | +| load | `loadAd()` (Activity context from the ctor) | `loadAdWithViewController:` (`bridge.viewController`) | +| show / hide | `setVisibility(VISIBLE/GONE)` + `resumeAutoRefresh()` / `pauseAutoRefresh()` | `isHidden` + `resumeAutoRefresh` / `pauseAutoRefresh` | +| destroy | `destroy()` then remove from parent | `destroy` then `removeFromSuperview` | + +The SDK has no show / hide API; visibility is the host view's job. Unity's docs say pause / resume only matter when a +refresh interval is set on the dashboard, and that a resumed banner completes the remaining refresh time. Android's +`IronSourceError.ERROR_BN_RELOAD_SKIP_INVISIBLE` shows the SDK itself skips refreshes of invisible banners; pausing +explicitly makes that deterministic on both platforms. + +Adaptive width units: the plugin passes CSS px. On Android 1 CSS px = 1 dp in a Capacitor WebView at default zoom, +and the `Integer` width **is dp** (§14 Q3): in the bytecode, `createAdaptiveAdSize` (`com.ironsource.g1.a`) compares +the width with the preset widths (320 / 728) and, for a `null` or negative width, falls back to +`DisplayMetrics.widthPixels / density` rounded (`com.ironsource.e5`), i.e. the screen width in dp. Checked on the emulator (Pixel 9 Pro, density 3): an +`ADAPTIVE` banner for 426 CSS px reports `adSize` 426 x 50 and its `LevelPlayBannerAdView` measures 1278 x 150 px. +On iOS 1 CSS px = 1 pt. +Both factories need a finished init (iOS returns `nil` before init, documented in LPMAdSize.h), so `createBanner` +rejects `NOT_INITIALIZED` before `initialize()` resolved. Unity's docs also say to create banners only after init +succeeded. + +### 3.3 Banner events + +| Event | Android `LevelPlayBannerAdViewListener` | iOS `LPMBannerAdViewDelegate` | +|---|---|---| +| `bannerLoaded` | `onAdLoaded(LevelPlayAdInfo)` | `didLoadAdWithAdInfo:` (required) | +| `bannerLoadFailed` | `onAdLoadFailed(LevelPlayAdError)` | `didFailToLoadAdWithAdUnitId:error:` (required) | +| `bannerDisplayed` | `onAdDisplayed` (default method) | `didDisplayAdWithAdInfo:` (optional) | +| `bannerDisplayFailed` | `onAdDisplayFailed(LevelPlayAdInfo, LevelPlayAdError)` | `didFailToDisplayAdWithAdInfo:error:` | +| `bannerClicked` | `onAdClicked` | `didClickAdWithAdInfo:` | +| `bannerExpanded` | `onAdExpanded` | `didExpandAdWithAdInfo:` | +| `bannerCollapsed` | `onAdCollapsed` | `didCollapseAdWithAdInfo:` | +| `bannerLeftApplication` | `onAdLeftApplication` | `didLeaveAppWithAdInfo:` | + +Payload: `BannerEvent { bannerId, adUnitId, adInfo?, frame? }`, plus `error` for the two failure events. All eight +callbacks exist on both platforms in 9.6.1. There is **no** `adInfoChanged` callback for banners on either platform. + +## 4. Native ads + +### 4.1 What 9.6.1 has + +- Android: `com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAd`, built with + `new LevelPlayNativeAd.Builder().withPlacementName(String).withListener(LevelPlayNativeAdListener).withActivity(Activity).build()`; + `loadAd()`, `destroyAd()`, asset getters `getTitle()`, `getAdvertiser()`, `getBody()`, `getCallToAction()`, + `getIcon()` (`NativeAdDataInterface.Image`). Views: `NativeAdLayout extends FrameLayout` with `setTitleView`, + `setAdvertiserView`, `setBodyView`, `setIconView`, `setCallToActionView`, `setMediaView(LevelPlayMediaView)`, + `registerNativeAdViews(LevelPlayNativeAd)`. Listener (`LevelPlayNativeAdListener` = `NativeAdLoadListener` + + `NativeAdInteractionListener`): `onAdLoaded(ad, AdInfo)`, `onAdLoadFailed(ad, IronSourceError)`, + `onAdImpression(ad, AdInfo)`, `onAdClicked(ad, AdInfo)`. `AdInfo` is `com.ironsource.mediationsdk.adunit.adapter.utility.AdInfo`. +- iOS: `LevelPlayNativeAd` (`initWithBuilder:`, `loadAd`, `destroyAd`, `setDelegate:`, asset properties `title`, + `advertiser`, `body`, `callToAction`, `icon` (`ISNativeAdDataImage` with `image` / `url`)), `LevelPlayNativeAdBuilder` + (`withViewController:`, `withPlacementName:`, `withDelegate:`, `build`), view `ISNativeAdView : UIView` with outlets + `adAppIcon`, `adTitleView`, `adAdvertiserView`, `adBodyView`, `adMediaView` (`LevelPlayMediaView`), + `adCallToActionView` and `registerNativeAdViews:`. Delegate `LevelPlayNativeAdDelegate` = + `ISNativeAdLoadDelegate` (`didLoad:withAdInfo:`, `didFailToLoad:withError:`) + `ISNativeAdInteractionDelegate` + (`didRecordImpression:withAdInfo:`, `didClick:withAdInfo:`), with `ISAdInfo`. + +Findings that shape the API: + +1. **No template views in the SDK on either platform.** There is no `LevelPlayNativeAdTemplate`, template type or + template layout resource in the AAR (its `res/` has only `values/`) or in the iOS headers. Unity's Flutter and + React Native wrappers ship their own XML (Android) and XIB (iOS) templates (`LevelPlayTemplateType.SMALL` / + `MEDIUM`). This plugin does the same: it owns two programmatic layouts per platform, `small` (no media view) and + `medium` (with `LevelPlayMediaView`). `nativeAdSupported` is therefore `true` on both platforms, with the + rendering being the plugin's code. +2. **Native ads have no ad unit id in 9.6.1.** Both builders take a placement name only. The API exposes + `placementName`, not `adUnitId`, and says so. +3. **One ad object per load.** Unity: "destroy the ad object and create a new one for every new load". So + `loadNativeAd` replaces the slot's previous ad. +4. **Native ad info is the old `AdInfo` / `ISAdInfo`** (auction id, network, instance, country, revenue, precision, + ab, segment, encrypted CPM; iOS adds `conversion_value`). No ad unit, ad id or placement in it. Hence a separate + `NativeAdInfo` type instead of reusing `AdInfo` (whose `adUnitId` is required). +5. **No per-ad impression-data listener for native ads** (only banners, interstitials and rewarded have + `setImpressionDataListener` / `setImpressionDataDelegate:`). See §5 for how `impressionData` still covers them. +6. Policy from Unity's guide: the ad must be marked as an ad, and the privacy / AdChoices icon belongs in the bottom + left. Both templates draw an "Ad" badge and leave the bottom-left corner free. + +### 4.2 TS API + +```ts +loadNativeAd({ nativeAdId, placementName?, template?: 'small'|'medium', style?: NativeAdTemplateStyle }): Promise +showNativeAd({ nativeAdId, rect: { x, y, width, height } }): Promise +setNativeAdRect({ nativeAdId, rect }): Promise +hideNativeAd({ nativeAdId }): Promise +destroyNativeAd({ nativeAdId }): Promise +// events: nativeAdLoaded, nativeAdLoadFailed, nativeAdImpression, nativeAdClicked (NativeAdEvent / NativeAdErrorEvent) +``` + +`style`: `backgroundColor`, `titleColor`, `bodyColor`, `callToActionBackgroundColor`, `callToActionTextColor` +(`#RRGGBB[AA]`), `cornerRadius` (CSS px), and (Q6) `titleFont`, `bodyFont`, `callToActionFont` as +`{ family?, size? }`: a system family name or a `.ttf` / `.otf` path inside the web assets (Android +`Typeface.createFromAsset(assets, "public/" + path)`, iOS `CTFontManagerRegisterFontsForURL` on the file in the +app's `public` folder), size in CSS px (dp / pt, not scaled by the system font size). Defaults are the system font. +The CTA is a native button so the SDK can register it. Android builds the templates in code (no XML resources), so +every style value applies without inflating. + +Flow: `loadNativeAd` → `nativeAdLoaded` → measure a placeholder element (`getBoundingClientRect()`) → +`showNativeAd({ rect })` → on layout change `setNativeAdRect` → `destroyNativeAd`, or `loadNativeAd` again for a new +creative. + +Mapping: build → `loadAd`; on show, inflate the template into a `NativeAdLayout` / `ISNativeAdView`, fill the +asset views from the getters, call the `set*View` setters (Android) / assign the outlets (iOS) and +`registerNativeAdViews`, then place it in the overlay (§6). `destroyNativeAd` → `destroyAd()` + remove view. + +## 5. Impression-level revenue: `impressionData` + +### 5.1 API + +`addListener('impressionData', (d: ImpressionData) => ...)`. Payload fields map 1:1 to the SDK data classes: + +| `ImpressionData` | Android `LevelPlayImpressionData` | iOS `LPMImpressionData` | +|---|---|---| +| `auctionId` | `getAuctionId()` | `auctionId` | +| `adUnitId` | `getMediationAdUnitId()` | `mediationAdUnitId` | +| `adUnitName` | `getMediationAdUnitName()` | `mediationAdUnitName` | +| `adFormat` | `getAdFormat()` | `adFormat` | +| `adNetwork` | `getAdNetwork()` | `adNetwork` | +| `instanceName` | `getInstanceName()` | `instanceName` | +| `instanceId` | `getInstanceId()` | `instanceId` | +| `country` | `getCountry()` | `country` | +| `placement` | `getPlacement()` | `placement` | +| `revenue` | `getRevenue()` (`Double`, nullable) | `revenue` (`NSNumber`) | +| `precision` | `getPrecision()` | `precision` | +| `ab` | `getAb()` | `ab` | +| `segmentName` | `getSegmentName()` | `segmentName` | +| `encryptedCPM` | `getEncryptedCPM()` | `encryptedCpm` | +| `creativeId` | `getCreativeId()` | `creativeId` | +| `conversionValue` | not in the class | `conversionValue` (`NSNumber`) | +| `allData` | `getAllData()` (`JSONObject`) | `allData` (`NSDictionary`) | + +**Not available: `lifetimeRevenue`.** It is not a property of either 9.6.1 class, not one of the Android +`IMPRESSION_DATA_KEY_*` constants (auctionId, adFormat, mediationAdUnitName, mediationAdUnitId, country, ab, +segmentName, placement, adNetwork, instanceName, instanceId, revenue, precision, encryptedCPM, creativeId), and the +string does not occur in the iOS binary. Apps that need lifetime revenue sum `revenue` themselves. If the server +sends it anyway it shows up in `allData`. Observed in phase 2 (Android, demo app key): the server does send +`allData.lifetimeRevenue` (per ad unit, cumulative in the session), so it is readable there; it stays out of the +typed fields because the SDK classes do not promise it. + +### 5.2 Registration + +9.6.1 deprecates the global listener for publishers: +- A: `LevelPlay.addImpressionDataListener` / `removeImpressionDataListener` carry `@kotlin.Deprecated("Publishers: + use setImpressionDataListener() on each LevelPlayBannerAdView, LevelPlayInterstitialAd, or LevelPlayRewardedAd ...")`. +- I: `+[LevelPlay addImpressionDataDelegate:]` is `DEPRECATED_MSG_ATTRIBUTE` with the same advice + (`setImpressionDataDelegate:` on each `LPMBannerAdView`, `LPMInterstitialAd`, `LPMRewardedAd`). +- `addImpressionLevelRevenueListener(listener, subscriberId)` is for approved third-party SDKs only (needs a + subscriber id from Unity), not for apps. + +Design (decided, Q1): the plugin attaches its own impression listener to **every** rewarded, interstitial +and banner object it creates (the holders already exist per ad unit). The JS side can add the listener at any time, +including before `initialize()`. Native ads have no per-ad listener, so on `onAdImpression` / `didRecordImpression:` the plugin +emits an `impressionData` built from the native `AdInfo` (`adFormat: 'nativead'`, no ad unit / placement / +creative fields). This avoids deprecated APIs and still covers every format. + +Queue (decided, Q2): while no JS `impressionData` listener exists, impressions are kept in a plugin-owned FIFO +queue capped at 100 (the oldest is dropped beyond that) and flushed, in order, when the first `impressionData` +listener is added (Android overrides `Plugin.addListener`; Capacitor's own `retainUntilConsumed` is not used because +its queue is unbounded). With a listener present they are sent directly. + +## 6. Overlay positioning (banners and native ads) + +### 6.1 Coordinate space + +All public geometry is in **CSS px relative to the WebView viewport** (the space of `getBoundingClientRect()` on a +non-scrolled page). Capacitor WebViews render at 1 CSS px = 1 dp (Android, default zoom / `initial-scale=1`) and +1 CSS px = 1 pt (iOS). Pages that change the viewport scale break this; documented as unsupported. + +### 6.2 Host view + +- **Android**: a plugin-owned `FrameLayout` "overlay host" added to the WebView's parent (`(ViewGroup) + bridge.getWebView().getParent()`, the Capacitor `CoordinatorLayout`) right after the WebView, so it draws above it. + It is kept equal to the WebView's bounds with an `OnLayoutChangeListener` on the WebView. The host is not clickable + and has no touch listener, so touches outside ad views fall through to the WebView below (Android dispatches to + siblings in reverse z-order until one consumes). Ad views inside it consume their own touches. +- **iOS**: a plugin-owned `UIView` subclass added to `bridge.viewController.view` above the WebView's content, frame + and `autoresizingMask` following the WebView. In Capacitor `CAPBridgeViewController.loadView` sets + `view = webView`, so that view *is* the `WKWebView`: the overlay is its last subview, above `WKScrollView`, and does + not scroll. (The WebView's superview belongs to UIKit / the presentation and a full-screen modal can reinsert the + WebView above a sibling there, so it is not used.) Its `hitTest(_:with:)` returns `nil` when the hit view is + itself, so only ad subviews receive touches. +- Full-screen ads (rewarded / interstitial / expanded banners / test suite) are presented as Activities / modal view + controllers and therefore always cover the overlay. + +### 6.3 Safe area + +`safeRect = webViewRect ∩ (window bounds − system insets)`, converted into WebView-local CSS px. + +- Android: insets from `ViewCompat.getRootWindowInsets(webView)` with + `WindowInsetsCompat.Type.systemBars() | Type.displayCutout()`. Intersecting with the WebView's on-screen rect + (`getLocationInWindow`) makes this correct in every Capacitor mode: Capacitor 7 `android.adjustMarginsForEdgeToEdge` + (margins on the WebView), Capacitor 8 `SystemBars` `insetsHandling: 'native'` (padding on the WebView parent) or + `'css'` (WebView edge to edge, insets only in CSS). Insets are re-read in the host's layout pass and via + `ViewCompat.setOnApplyWindowInsetsListener` on the host (the host returns the insets unconsumed so it never steals + them from Capacitor's own listener on the WebView). +- iOS: `overlayHost.safeAreaInsets` (same frame as the WebView), updated in `safeAreaInsetsDidChange` / + `layoutSubviews`. + +`respectSafeArea: false` uses the raw WebView rect. Native ad rects are taken literally (the page already laid them +out against `env(safe-area-inset-*)`), only clamped to the WebView rect. + +### 6.4 Placement maths (banner) + +``` +x = safe.x + (safe.width − bannerWidth) / 2 + offsetX +y = top: safe.y + offsetY + bottom: safe.y + safe.height − bannerHeight + offsetY + center: safe.y + (safe.height − bannerHeight) / 2 + offsetY +``` + +Recomputed on every host layout pass (rotation, split screen, multi-window, keyboard resizing the WebView, foldables). +Adaptive banners (decided, Q4): when the banner was created without `adaptiveWidth` and the safe-area width changes +(rotation, split screen, window resize), the plugin destroys the banner view and creates a new one with +`createAdaptiveAdSize(newWidth)` after the layout settled (debounced 250 ms), keeping `bannerId`, layout, visibility +and placement, and calls `loadAd()` again if the old view had been loaded. The new creative arrives as a normal +`bannerLoaded` with the new `frame`. A fixed `adaptiveWidth` and the presets are never recreated. + +### 6.5 WebView scroll and z-order + +Overlays are fixed to the viewport; they do not scroll with page content. Games normally have no page scroll. For +scrolling pages the app calls `setNativeAdRect` on scroll / resize (documented). Z-order inside the host: creation +order; a later `showBanner` / `showNativeAd` brings that view to the front. + +### 6.6 Lifecycle + +On `handleOnDestroy` (Android) / plugin deinit the plugin destroys every banner and native ad. On app pause the SDK +manages refresh itself; the plugin does not pause banners on `handleOnPause`. + +## 7. `adInfoChanged` + +`addListener('adInfoChanged', (e: AdEvent) => ...)`, same payload as `loaded`. Sources: A +`LevelPlayRewardedAdListener.onAdInfoChanged` / `LevelPlayInterstitialAdListener.onAdInfoChanged` (default methods); +I `LPMRewardedAdDelegate` / `LPMInterstitialAdDelegate` `didChangeAdInfo(_:)` (optional). The 0.2.x holders already +implement these as empty bodies; phase 2 only emits. Banner listener / delegate have no such callback in 9.6.1; +native ads neither. + +## 8. Placements, capping and rewards + +| Plugin | Android | iOS | +|---|---|---| +| `isPlacementCapped({ format: 'rewarded', placementName })` | `LevelPlayRewardedAd.isPlacementCapped(String)` (static) | `+[LPMRewardedAd isPlacementCapped:]` | +| `isPlacementCapped({ format: 'interstitial', ... })` | `LevelPlayInterstitialAd.isPlacementCapped(String)` (static) | `+[LPMInterstitialAd isPlacementCapped:]` | +| `getReward({ adUnitId, placementName? })` | `LevelPlayRewardedAd.getReward(String)` / `getReward()` (instance) | `-[LPMRewardedAd getRewardWithPlacementName:]` (`getReward(placementName:)`) | + +`getReward` uses the plugin's per-ad-unit `LevelPlayRewardedAd` holder (created on demand, as `loadRewarded` does). +iOS documents "an empty reward on failures (`name: ""` and `amount: 0`)"; the plugin returns the same shape on both +platforms and the web. + +Not in 9.6.1: the 7.x/8.x `IronSource.getRewardedVideoPlacementInfo` / `Placement` class (absent from +`com.ironsource.mediationsdk.IronSource` and `IronSource.h`, which now only hold demand-only and ad-revenue APIs), and +any capping API for banners or native ads. `ShowOptions.placementName` (0.1.0) already covers show-time placements. + +## 9. Segments and dynamic user id + +`setSegment(options)`: + +| Field | Android `com.unity3d.mediation.segment.LevelPlaySegment` | iOS `LPMSegment` | +|---|---|---| +| `segmentName` | `setSegmentName(String)` | `segmentName` | +| `level` | `setLevel(int)` | `level` (`int`) | +| `isPaying` | `setPaying(boolean)` | `paying` | +| `userCreationDate` (ms epoch) | `setUserCreationDate(long)` | `userCreationDate` (`NSDate`, `Date(timeIntervalSince1970: ms / 1000)`) | +| `iapTotal` | `setIapTotal(double)` | `iapTotal` | +| `customParameters` | `setCustom(String, String)` per pair | `setCustomValue:forKey:` per pair | +| apply | `LevelPlay.setSegment(LevelPlaySegment)` | `+[LevelPlay setSegment:]` | + +Custom-parameter limits read from the Android bytecode of `setCustom`: key and value must match `^[a-zA-Z0-9]*$` +and be 1-32 characters; at most 5 pairs, the oldest is silently evicted on the 6th. The plugin validates the same +rules on both platforms and rejects `INVALID_ARGUMENT` rather than dropping data silently. (The iOS header does not state the +limits; phase 2 confirms iOS behaves the same.) + +`setDynamicUserId({ userId })` → `{ valid }`: A `LevelPlay.setDynamicUserId(String): boolean`, I +`+[LevelPlay setDynamicUserId:]` returning `BOOL`. There is no `IronSource.setDynamicUserId` in 9.6.1; the LevelPlay +class is the only entry point. + +## 10. Errors + +Promise rejections (plugin codes, strings): + +| Code | When | +|---|---| +| `INVALID_ARGUMENT` | missing / empty ids, bad size or position, bad segment custom parameters, negative rect size | +| `NOT_INITIALIZED` | `createBanner`, `loadNativeAd` before `initialize()` resolved | +| `ALREADY_EXISTS` | `createBanner` with a `bannerId` in use | +| `NOT_FOUND` | `loadBanner`, `showBanner`, `setBannerLayout`, `showNativeAd`, `setNativeAdRect`, `hideNativeAd` with an unknown id (`hideBanner`, `destroy*` resolve instead) | +| `NOT_LOADED` | `showNativeAd` before `nativeAdLoaded` | +| `UNSUPPORTED` | capability is `false`, or a template not in `nativeAdTemplates` | +| `NO_VIEW_CONTROLLER` (iOS) / `NO_ACTIVITY` (Android) | no host to attach or load into | +| `UNIMPLEMENTED` | web stubs (Capacitor's `unimplemented()`), and any 0.3.0 method on a native build of phase 1 | + +Ad errors in events (`AdError { code, message }`) pass the SDK code through: A `LevelPlayAdError.getErrorCode()` / +`IronSourceError.getErrorCode()` (native), I `NSError.code`. Notable codes: 509 no fill; banner-specific Android +constants `ERROR_BN_LOAD_NO_FILL`, `ERROR_BN_UNSUPPORTED_SIZE`, `ERROR_BN_RELOAD_SKIP_INVISIBLE`; native +`ERROR_NT_LOAD_NO_FILL`, `ERROR_NT_LOAD_PLACEMENT_CAPPED`. + +## 11. Web + +`getCapabilities` all false; `setSegment` no-op; `setDynamicUserId` → `{ valid: false }`; `isPlacementCapped` → +`{ capped: false }`; `getReward` → `{ name: '', amount: 0 }`; `loadBanner`, `hideBanner`, `destroyBanner`, +`setNativeAdRect`, `hideNativeAd`, `destroyNativeAd` no-ops; `createBanner`, `showBanner`, `setBannerLayout`, +`loadNativeAd`, `showNativeAd` reject `unimplemented` (they would have to return a frame or show a view; same rule as +`initialize`). + +## 12. Capacitor 7 compatibility (applied in 0.3.0, see §17) + +Plugin-facing Java and Swift API is identical between 7.6.9 and 8.5.3 for everything this plugin uses: + +- Android: the public members of `Plugin`, `PluginCall`, `Bridge` and `JSObject` diff to zero. + `notifyListeners(String, JSObject, boolean)` exists in both. +- iOS: `CAPPluginCall` (`.swift`, `.h`) identical; `CAPBridgeProtocol` in 8 only adds deprecations (`presentVC` / + `dismissVC` → `bridge.viewController.present/dismiss`, which the plugin already uses); `CAPPlugin` in 8 adds + `handleWKWebViewURLAuthenticationChallenge` (not used). `CAPBridgedPlugin` exists in both. + +What must change to support `>=7.0.0` (phase 2 or later, not done now): + +| Item | Today (Cap 8) | Needed for Cap 7 | +|---|---|---| +| `package.json` peer | `@capacitor/core >=8.0.0` | `>=7.0.0` | +| `Package.swift` | `capacitor-swift-pm` `from: "8.0.0"` | `"7.0.0"..<"9.0.0"` (tags 7.0.0 ... 7.6.9 and 8.x exist) | +| iOS deployment target | `.iOS(.v15)`, podspec `15.0` | `.v14` / `14.0` (Cap 7 default; `Capacitor.podspec` 7 = 14.0, 8 = 15.0). LevelPlay 9.6.1 needs 12.0, so 14 is fine. SPM refuses a package whose platform is higher than the app target. | +| Android `minSdkVersion` default | 24 | 23 (Cap 7 default; LevelPlay AAR needs 19). Only the fallback; apps override from `variables.gradle`. | +| Android `compileSdk` / `targetSdk` defaults | 36 | 35 in Cap 7 projects; overridden by the app, so no code change. | +| AGP in plugin `buildscript` | `8.13.0` | Cap 7 apps use AGP 8.7.2. The plugin's `buildscript` classpath is only used by the standalone `verify:android` build, but a mismatched AGP in a subproject `buildscript` can trigger "multiple AGP versions"; phase 2 tests it in a Cap 7 app and, if needed, drops the plugin's `buildscript` classpath or keys it off `rootProject`. | +| Java | 21 | 21 (same). | +| Node / CLI | engines `>=22` | Cap 7 CLI runs on Node 20+; `engines` is advisory, can stay. | +| SPM | default in Cap 8 projects | supported in Cap 7 (CapApp-SPM since Cap 6); CocoaPods podspec unchanged. | +| LevelPlay SPM package | swift-tools 6.0 | needs Xcode 16+, which Cap 7 already requires. | + +Behavioural difference that matters for overlays: edge-to-edge handling. Cap 7 uses +`android.adjustMarginsForEdgeToEdge` (`CapConfig`, margins on `CapacitorWebView`; removed in 8). Cap 8 uses the core +`SystemBars` plugin (`insetsHandling: 'css' | 'native' | 'disable'`, padding on the WebView's parent or CSS +variables). The overlay design (§6.3) measures the WebView's real on-screen rect and intersects with window insets, so +it is correct under every combination without reading either config. + +## 13. Test plan + +Automated (CI-able): +- `bun run typecheck`, `bun run build` (docgen + rollup), `verify:ios`, `verify:android` on every change. +- Android unit tests (JUnit, no device): pure helpers for placement maths (§6.4), safe-rect intersection, size + preset parsing, segment validation, `ImpressionData` → `JSObject` mapping (constructed from a JSON fixture with + `new LevelPlayImpressionData(JSONObject)`). +- iOS: same helpers as plain Swift functions with XCTest (`swift test` cannot link the binary SDK on macOS; keep the + helpers SDK-free). + +Manual on devices (Unity demo app keys from `LEVELPLAY_DEMO` + test suite), Android 8 / 14 / 15 (edge to edge) and +iOS 15 / 18 / 26, phone and tablet, portrait and landscape: +1. Banner: every preset + adaptive; top / bottom / center with offsets; frame in `BannerResult` matches + `document.elementFromPoint` checks; notch and home indicator respected; rotate while shown; hide during gameplay + (no `bannerDisplayed` while hidden, refresh paused); two banners at once; destroy and recreate; click → `bannerClicked` + and `bannerLeftApplication`; expanded creative → `bannerExpanded` / `bannerCollapsed`. +2. Touch passthrough: game input works everywhere outside ad views, ads clickable inside; with keyboard open. +3. Native: small and medium templates at several rects; "Ad" badge and AdChoices corner; impression only once visible; + `setNativeAdRect` while shown; reload replaces the creative; destroy on screen change; no leaks across 50 loads + (Android Studio profiler / Instruments). +4. `impressionData` for rewarded, interstitial, banner, native; listener added before `initialize`; values match + `adInfo.revenue`; `conversionValue` present on iOS only. +5. `adInfoChanged` fires (needs a network that reloads; verify with test suite or logs). +6. `isPlacementCapped` with a dashboard placement capped to 1 per session; `getReward` per placement vs ad unit. +7. `setSegment` before init, segment name appears in `adInfo.segmentName` / `impressionData.segmentName`; invalid + custom parameters reject. +8. `setDynamicUserId` value reaches the S2S callback URL. +9. Backwards compatibility: the 0.2.1 README quick start and CUT BLAST's integration run unchanged. +10. Capacitor 7: a fresh Cap 7 app (SPM and CocoaPods; Android with `adjustMarginsForEdgeToEdge: 'auto'`) after the + §12 changes. + +## 14. Owner decisions (were open questions) + +- **Q1 Impression data source. Decided:** per-ad listeners (`setImpressionDataListener` / + `setImpressionDataDelegate:` on every rewarded, interstitial and banner object the plugin creates) plus native ad + impressions synthesised from the native `AdInfo` (`adFormat: 'nativead'`). The deprecated global listener is not + used. +- **Q2 Retain impressions. Decided:** yes, with a plugin-owned queue capped at 100 impressions (oldest dropped), + flushed in order on the first `addListener('impressionData')`. See §5.2. +- **Q3 Android adaptive width unit. Decided / verified:** dp, from the SDK bytecode (§3.2); confirmed on the emulator (view measured 3 px per CSS px at density 3). + CSS px are passed through unchanged. +- **Q4 Adaptive banners and rotation. Decided:** automatic. Adaptive banners without a fixed `adaptiveWidth` are + recreated and reloaded on a safe-area width change, keeping position, offsets, visibility and id. See §6.4. +- **Q5 Custom banner sizes. Decided:** supported in addition to the presets: `size: 'CUSTOM'` with + `customSize: { width, height }` (CSS px). +- **Q6 Native template styling. Decided:** colours (background, title, body, CTA background and text), corner radius, + and font family + size for title, body and CTA (`titleFont`, `bodyFont`, `callToActionFont`). See §4.2. +- **Q7 Capacitor 7. Decided:** targeted for 0.3.0. Phase 7 verifies a Cap 7 app and applies the §12 package changes; + until then the native code only uses APIs present in both Capacitor 7 and 8 (Android: `Plugin.addListener`, + `notifyListeners`, `hasListeners`, `handleOnDestroy`, `handleOnConfigurationChanged`, `bridge.getWebView()`, all + identical in 7.6.9 and 8.5.3). + +## 15. Phase 2 notes (Android implementation) + +Files (`android/src/main/java/fyi/crt/capacitor/levelplay/`): `LevelPlayPlugin` (bridge, impression queue, lifecycle), +`OverlayHost` (§6.2), `BannerManager` (§3), `NativeAdManager` + `NativeAdTemplate` + `NativeAdStyle` (§4), +`Mappers` (SDK objects to JSON), `OverlayMath` (pure geometry and validation, JVM unit tests in `android/src/test`), +`CallError` (reject codes). `res/values/strings.xml` holds the two template texts (`levelplay_native_ad_badge` "Ad", +`levelplay_native_ad_cta_fallback` "Open"), overridable by the app's own resources. + +Implementation details that the sections above leave open: + +- Every bridge call hops to the main thread; SDK listeners re-post to it. Unexpected runtime exceptions reject with + code `ERROR`. +- `createBanner` validates its arguments first (`INVALID_ARGUMENT`), then `NOT_INITIALIZED`, `ALREADY_EXISTS`, + `NO_ACTIVITY` (also when the WebView has no parent view yet). +- Overlay children are positioned with FrameLayout margins from the WebView's offset in the host + (`getLocationInWindow` of both), so the host simply fills the WebView's parent. Relayouts are posted, never run + inside a layout pass. +- A hidden banner is `View.GONE` + `pauseAutoRefresh()`; `showBanner` is `VISIBLE` + `bringToFront()` + + `resumeAutoRefresh()`. +- Banner and native listeners are per view / per ad object; callbacks from a replaced (rotation) or destroyed + object are dropped. +- `loadAd()` on a banner view is one-shot in 9.6.1: a second call only logs "Banner load already called" and the SDK + retries on its own refresh interval. Immediate retries are destroy + create + load (documented on `loadBanner`). +- A native ad template consumes touches inside its bounds (taps between asset views do not reach the page). +- Native template font files are read with `Typeface.createFromAsset(assets, "public/" + path)` and cached; a missing + file logs a warning (tag `LevelPlay`) and uses the system font. + +Emulator results (Pixel 9 Pro AVD, API 36, Capacitor 8.5.3 test app, Unity demo app key + Unity Ads adapter 5.14 / +Unity Ads 4.21 in the app): + +- Seen: init, `getCapabilities`, `setSegment` (valid, and `INVALID_ARGUMENT` for 6 pairs, a `-` in a key and a + non-integer level), `setDynamicUserId` (`valid: true`), `isPlacementCapped`, `getReward` (`Virtual Item` x 1); + adaptive / preset / `MEDIUM_RECTANGLE` / `CUSTOM` banners at top / bottom / center with offsets; hide / show / + destroy (view visibility checked with `dumpsys activity top`); `ALREADY_EXISTS`, `NOT_FOUND`; touches beside a + banner reach the page; safe area with Capacitor's default insets handling and with `insetsHandling: 'disable'` + (edge to edge: top banner at y 52 = status bar, bottom banner ends 24 px above the WebView bottom = navigation + bar; `respectSafeArea: false` gives y 0); rotation recreates a width-following adaptive banner (426 x 50 to + 900 x 50, reloaded; landscape with a display cutout: both banners at x 52, width 900, inside the safe area); a tap + on a banner fires `bannerClicked` and opens the browser without reaching the page; rewarded load / show / reward / close; queued `impressionData` (banner, rewarded) flushed on + the first listener; native ad error paths (`UNSUPPORTED`, `INVALID_ARGUMENT`, `NOT_LOADED`, `NOT_FOUND`, + `nativeAdLoadFailed` 508). +- Not seen with the public demo ids: a filled native ad (the demo app key has no native configuration: 508 "No Native + Ad configurations found"), so `nativeAdLoaded` / `nativeAdImpression` / `nativeAdClicked` and the synthesised + native `impressionData` are untested; the templates were rendered with sample assets through + `NativeAdTemplate.create` / `fill` instead. `adInfoChanged` never fired. Interstitial: load and `displayed` seen, the close could not be + driven through the ANR dialogs of the overloaded emulator. `segmentName` stayed empty in `adInfo` + (no segments on the demo dashboard). Banner expand / collapse / left-application events (Unity Ads test banners did not report them). + The emulator ran on an overloaded host (load average 30-40): system apps and the test app showed ANR dialogs + around SDK init and Unity full-screen ads; the overlay was idle at those times (no frames rendered while idle, + app CPU 2 %). + +## 16. Phase 3 notes (iOS implementation) + +Files (`ios/Sources/LevelPlayPlugin/`): `LevelPlayPlugin.swift` (bridge, holders, impression queue, overlay, +cleanup), `OverlayHost.swift` (§6.2), `BannerManager.swift` (§3), `NativeAdManager.swift` + `NativeAdTemplate.swift` + +`NativeAdStyle.swift` (§4), `Mappers.swift` (SDK objects to JSON), `OverlayMath.swift` (pure geometry and validation, +same rules as Android), `CallError.swift` (reject codes and typed option reads). + +Swift names the SDK actually imports as (the ObjC importer renames several of the §3 / §4 names): +`LPMAdSize.banner()`, `.large()`, `.mediumRectangle()`, `.leaderBoard()`, `.customSize(withWidth:height:)`, +`.createAdaptiveAdSize(withWidth:)`, `.createAdaptive()`; `LPMBannerAdView.loadAd(with:)`; +`LevelPlayNativeAd.load()` / `.destroy()`; `LevelPlayNativeAdBuilder.build()` returns an optional. Delegate methods are +declared with explicit `@objc(selector)` names so the optional callbacks are found whatever their Swift spelling. + +Behaviour matches the Android bridge (same validation order, messages, codes and payloads) except: + +- `NO_VIEW_CONTROLLER` instead of `NO_ACTIVITY`. +- `loadBanner` passes `bridge.viewController` to `loadAdWithViewController:`; the native builder gets it via + `withViewController:`. +- Booleans and numbers are told apart (`CFBoolean`), so `isPaying: 1` or `offsetX: true` reject as on Android. +- `setSegment` custom parameters are applied in key order (JS object order is not kept by the bridge). +- Native template fonts: a `.ttf` / `.otf` path is resolved against `bridge.config.appLocation` (the app's `public` + folder), registered once per process with `CTFontManagerRegisterFontsForURL` (`.process`) and used by PostScript + name; a system family is looked up by name, then by family. Missing fonts log a warning (subsystem + `fyi.crt.capacitor.levelplay`) and use the system font. Template texts `levelplay_native_ad_badge` ("Ad") and + `levelplay_native_ad_cta_fallback` ("Open") come from the app's `Localizable.strings` when present. +- The overlay logs each banner's frame (and every `showBanner`) and each shown native ad's frame at `notice` level + (subsystem `fyi.crt.capacitor.levelplay`, category `LevelPlay`). +- Cleanup runs in the plugin's `deinit` (Capacitor iOS has no `handleOnDestroy`); managers are created on first use + so `deinit` never builds them. +- The app needs the `-ObjC` linker flag (already a README requirement): without it `LevelPlay.setSegment` crashes with + `+[ISSegment createFrom:]: unrecognized selector`, a category of the static SDK binary. + +Simulator results (iPhone 17 simulator, iOS 26, Capacitor 8.5.2 Swift package, Unity demo app key, no extra +adapters, ironSource Ads filled): + +- Seen: `getCapabilities`; `setSegment` valid and `INVALID_ARGUMENT` for 6 pairs, a `-` in a key and level 1.5; + `NOT_INITIALIZED` for `createBanner` before init; init; `setDynamicUserId` (`valid: true`); `isPlacementCapped` + (and `INVALID_ARGUMENT` for format `banner`); `getReward` (`Virtual Item` x 1); adaptive banner at the bottom: + `adSize` 402 x 50, frame `0,790 402x50` in a `402x874` WebView whose safe area is `0,62 402x778` (ends 34 pt above + the bottom = home indicator); `ALREADY_EXISTS`, `NOT_FOUND`, `INVALID_ARGUMENT` for size `HUGE`; + `bannerLoadFailed` 509 then `bannerLoaded` / `bannerDisplayed` on the SDK's retry; rewarded load / show / + `displayed` / `rewarded`; `impressionData` for banner, native and rewarded queued before the first listener and + flushed in order when it was added (`allData.lifetimeRevenue` present as on Android; `conversionValue` was `nil` in + `LPMImpressionData` and `0` in `ISAdInfo` / `LPMAdInfo` with the demo key); native ad error paths (`UNSUPPORTED`, + `NOT_LOADED`); a **filled** native ad (unlike Android's demo key): `nativeAdLoaded`, `showNativeAd` in the small + template at `20,460 300x90` (icon 48 x 48, title "Demo App", "Ad" badge, body, CTA "INSTALL" 79 x 36 on the right, + the network's privacy "i" at the bottom-left corner `0,69 21x21`), `nativeAdImpression` and the synthesised + `impressionData` (`adFormat: 'nativead'`). The native `ISAdInfo` fields were all empty strings with the demo key. + The medium template and a missing-advertiser / long-text case were checked with sample assets (view hierarchy + logged: title truncated, media view filling the rest, CTA right-aligned, web-asset font applied). +- Not seen: interstitial, close of the rewarded ad, rotation (adaptive recreation), `setBannerLayout`, banner + click / expand / collapse / left-application, `nativeAdClicked`, `adInfoChanged`, Capacitor 7. Compiled only. + +## 17. Capacitor 7 verification (phase 7) + +Applied the §12 changes: peer `@capacitor/core >=7.0.0`; `Package.swift` `capacitor-swift-pm` `"7.0.0"..<"9.0.0"` and +`.iOS(.v14)`; podspec `14.0`; Android `minSdkVersion` fallback 23. The plugin's `buildscript` AGP classpath (8.13.0) +was left as is. + +Compile check with a scratch copy of `example-app/` on Capacitor 7.6.9 (`@capacitor/core`, `cli`, `android`, `ios`), +fresh `npx cap add android` and `npx cap add ios --packagemanager SPM`: + +- Android `assembleDebug`: succeeds in the Cap 7 template (AGP 8.7.2, compileSdk 35, minSdk 23, JDK 21); no + "multiple AGP versions" clash. +- iOS simulator build (`CODE_SIGNING_ALLOWED=NO`): SPM resolves `capacitor-swift-pm` 7.x with the plugin's range and + the build succeeds. The Cap 7 template's app target is iOS 14.0, which Xcode 27 rejects for any app ("supported + deployment target versions is 15.0 to 27.0"); with the app target raised to 15.0 it builds. The plugin itself only + uses iOS 14 APIs (`Logger`, ATT) but iOS 14 availability was not compiler-checked with Xcode 27. +- Not run on a device or emulator with Capacitor 7. diff --git a/docs/images/android/banners-landscape-rotated.png b/docs/images/android/banners-landscape-rotated.png new file mode 100644 index 0000000..c875ae3 Binary files /dev/null and b/docs/images/android/banners-landscape-rotated.png differ diff --git a/docs/images/android/banners-top-bottom.png b/docs/images/android/banners-top-bottom.png new file mode 100644 index 0000000..242cc22 Binary files /dev/null and b/docs/images/android/banners-top-bottom.png differ diff --git a/example-app/.gitignore b/example-app/.gitignore new file mode 100644 index 0000000..7df8b84 --- /dev/null +++ b/example-app/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +www/ +package-lock.json diff --git a/example-app/README.md b/example-app/README.md new file mode 100644 index 0000000..197abf6 --- /dev/null +++ b/example-app/README.md @@ -0,0 +1,48 @@ +# capacitor-levelplay example + +A minimal Capacitor 8 app for trying the plugin with Unity's public demo ids (`LEVELPLAY_DEMO`, test ads only). Plain +HTML and TypeScript, bundled with esbuild; the plugin comes from the parent folder (`"capacitor-levelplay": "file:.."`). + +Buttons: initialize, capabilities, segment, dynamic user id, rewarded and interstitial load / show, an adaptive banner +at the top or bottom (hide, show, destroy), native ads in the `small` or `medium` template placed over a page +placeholder, and a log panel that prints every event and each `impressionData` (format, network, revenue, precision). + +## Run + +Build the plugin once from the repository root, then the example: + +```sh +bun install && bun run build # in the repository root (plugin dist/) +cd example-app +npm install +npm run sync # tsc + esbuild into www/, then npx cap sync +npx cap run android # or: npx cap open android +npx cap run ios # or: npx cap open ios +``` + +Rebuild the plugin (`bun run build` in the root) and run `npm run sync` again after changing the plugin's TypeScript. +Native plugin code is picked up directly from `../android` and `../ios` (Gradle project / Swift package path). + +Requirements: JDK 21 and the Android SDK for Android; Xcode 26+ for iOS. + +## What is already set up + +The `android/` and `ios/` folders are committed (`npx cap add` output plus the plugin's setup steps): + +- iOS `Info.plist`: `NSUserTrackingUsageDescription`, LevelPlay's `SKAdNetworkItems` id, `NSAllowsArbitraryLoads`. +- iOS App target: `-ObjC` in **Other Linker Flags** (required by LevelPlay). +- iOS uses Swift Package Manager (`CapApp-SPM`). `@capacitor/ios` is pinned to 8.5.2 because `capacitor-swift-pm` + has no 8.5.3 tag at the time of writing (SPM fails with "no versions of 'capacitor-swift-pm' match 8.5.3"). +- Android needs nothing beyond `npx cap sync`; the plugin's manifest and Gradle file bring the SDK and permissions. + +To recreate the platforms from scratch: delete `android/` and `ios/`, run `npx cap add android` and `npx cap add ios`, +then repeat the iOS steps above (see the plugin README, "iOS setup"). + +## Notes + +- Android includes the Unity Ads mediation adapter (`app/build.gradle`): Unity's demo Android banner unit only fills + through Unity Ads, so without it banners fail with 1044 "no available ad to load". Everything else fills from + ironSource Ads. Natives may not fill on Android with the demo key (508 "No Native Ad configurations found"). +- `loadBanner` is one-shot per banner object; to retry right away, destroy and create the banner again. +- The web build (`npm run build`, open `www/index.html` through any static server) runs the plugin's web stub: + init and banners reject as unimplemented and nothing ever fills. diff --git a/example-app/android/.gitignore b/example-app/android/.gitignore new file mode 100644 index 0000000..48354a3 --- /dev/null +++ b/example-app/android/.gitignore @@ -0,0 +1,101 @@ +# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ + +# Android Profiling +*.hprof + +# Cordova plugins for Capacitor +capacitor-cordova-android-plugins + +# Copied web assets +app/src/main/assets/public + +# Generated Config files +app/src/main/assets/capacitor.config.json +app/src/main/assets/capacitor.plugins.json +app/src/main/res/xml/config.xml diff --git a/example-app/android/app/.gitignore b/example-app/android/app/.gitignore new file mode 100644 index 0000000..043df80 --- /dev/null +++ b/example-app/android/app/.gitignore @@ -0,0 +1,2 @@ +/build/* +!/build/.npmkeep diff --git a/example-app/android/app/build.gradle b/example-app/android/app/build.gradle new file mode 100644 index 0000000..9508407 --- /dev/null +++ b/example-app/android/app/build.gradle @@ -0,0 +1,57 @@ +apply plugin: 'com.android.application' + +android { + namespace = "fyi.crt.levelplay.example" + compileSdk = rootProject.ext.compileSdkVersion + defaultConfig { + applicationId "fyi.crt.levelplay.example" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + aaptOptions { + // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. + // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61 + ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' + } + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +repositories { + flatDir{ + dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs' + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" + implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" + implementation project(':capacitor-android') + // Unity Ads mediation adapter: Unity's demo Android banner unit only fills through Unity Ads + implementation 'com.unity3d.ads-mediation:unityads-adapter:5.14.0' + implementation 'com.unity3d.ads:unity-ads:4.21.0' + testImplementation "junit:junit:$junitVersion" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" + implementation project(':capacitor-cordova-android-plugins') +} + +apply from: 'capacitor.build.gradle' + +try { + def servicesJSON = file('google-services.json') + if (servicesJSON.text) { + apply plugin: 'com.google.gms.google-services' + } +} catch(Exception e) { + logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work") +} diff --git a/example-app/android/app/capacitor.build.gradle b/example-app/android/app/capacitor.build.gradle new file mode 100644 index 0000000..ab09e50 --- /dev/null +++ b/example-app/android/app/capacitor.build.gradle @@ -0,0 +1,19 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN + +android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } +} + +apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" +dependencies { + implementation project(':capacitor-levelplay') + +} + + +if (hasProperty('postBuildExtras')) { + postBuildExtras() +} diff --git a/example-app/android/app/proguard-rules.pro b/example-app/android/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/example-app/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/example-app/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/example-app/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java new file mode 100644 index 0000000..f2c2217 --- /dev/null +++ b/example-app/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import android.content.Context; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + + assertEquals("com.getcapacitor.app", appContext.getPackageName()); + } +} diff --git a/example-app/android/app/src/main/AndroidManifest.xml b/example-app/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b06ddbf --- /dev/null +++ b/example-app/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example-app/android/app/src/main/java/fyi/crt/levelplay/example/MainActivity.java b/example-app/android/app/src/main/java/fyi/crt/levelplay/example/MainActivity.java new file mode 100644 index 0000000..8094714 --- /dev/null +++ b/example-app/android/app/src/main/java/fyi/crt/levelplay/example/MainActivity.java @@ -0,0 +1,5 @@ +package fyi.crt.levelplay.example; + +import com.getcapacitor.BridgeActivity; + +public class MainActivity extends BridgeActivity {} diff --git a/example-app/android/app/src/main/res/drawable-land-hdpi/splash.png b/example-app/android/app/src/main/res/drawable-land-hdpi/splash.png new file mode 100644 index 0000000..e31573b Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-land-hdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-land-mdpi/splash.png b/example-app/android/app/src/main/res/drawable-land-mdpi/splash.png new file mode 100644 index 0000000..f7a6492 Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-land-mdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-land-xhdpi/splash.png b/example-app/android/app/src/main/res/drawable-land-xhdpi/splash.png new file mode 100644 index 0000000..8077255 Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-land-xhdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/example-app/android/app/src/main/res/drawable-land-xxhdpi/splash.png new file mode 100644 index 0000000..14c6c8f Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-land-xxhdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/example-app/android/app/src/main/res/drawable-land-xxxhdpi/splash.png new file mode 100644 index 0000000..244ca25 Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-port-hdpi/splash.png b/example-app/android/app/src/main/res/drawable-port-hdpi/splash.png new file mode 100644 index 0000000..74faaa5 Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-port-hdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-port-mdpi/splash.png b/example-app/android/app/src/main/res/drawable-port-mdpi/splash.png new file mode 100644 index 0000000..e944f4a Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-port-mdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-port-xhdpi/splash.png b/example-app/android/app/src/main/res/drawable-port-xhdpi/splash.png new file mode 100644 index 0000000..564a82f Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-port-xhdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/example-app/android/app/src/main/res/drawable-port-xxhdpi/splash.png new file mode 100644 index 0000000..bfabe68 Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-port-xxhdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/example-app/android/app/src/main/res/drawable-port-xxxhdpi/splash.png new file mode 100644 index 0000000..6929071 Binary files /dev/null and b/example-app/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differ diff --git a/example-app/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/example-app/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/example-app/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/example-app/android/app/src/main/res/drawable/ic_launcher_background.xml b/example-app/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d5fccc5 --- /dev/null +++ b/example-app/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example-app/android/app/src/main/res/drawable/splash.png b/example-app/android/app/src/main/res/drawable/splash.png new file mode 100644 index 0000000..f7a6492 Binary files /dev/null and b/example-app/android/app/src/main/res/drawable/splash.png differ diff --git a/example-app/android/app/src/main/res/layout/activity_main.xml b/example-app/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..b5ad138 --- /dev/null +++ b/example-app/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/example-app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/example-app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..036d09b --- /dev/null +++ b/example-app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/example-app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/example-app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..036d09b --- /dev/null +++ b/example-app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..c023e50 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2127973 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..b441f37 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..72905b8 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..8ed0605 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..9502e47 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..4d1e077 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..df0f158 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..853db04 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..6cdf97c Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2960cbb Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..8e3093a Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..46de6e2 Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..d2ea9ab Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..a40d73e Binary files /dev/null and b/example-app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/example-app/android/app/src/main/res/values/ic_launcher_background.xml b/example-app/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/example-app/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/example-app/android/app/src/main/res/values/strings.xml b/example-app/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..70d8143 --- /dev/null +++ b/example-app/android/app/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + LevelPlay Example + LevelPlay Example + fyi.crt.levelplay.example + fyi.crt.levelplay.example + diff --git a/example-app/android/app/src/main/res/values/styles.xml b/example-app/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..be874e5 --- /dev/null +++ b/example-app/android/app/src/main/res/values/styles.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/example-app/android/app/src/main/res/xml/file_paths.xml b/example-app/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..bd0c4d8 --- /dev/null +++ b/example-app/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/example-app/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java b/example-app/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java new file mode 100644 index 0000000..0297327 --- /dev/null +++ b/example-app/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java @@ -0,0 +1,18 @@ +package com.getcapacitor.myapp; + +import static org.junit.Assert.*; + +import org.junit.Test; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} diff --git a/example-app/android/build.gradle b/example-app/android/build.gradle new file mode 100644 index 0000000..f8f0e43 --- /dev/null +++ b/example-app/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.13.0' + classpath 'com.google.gms:google-services:4.4.4' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: "variables.gradle" + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/example-app/android/capacitor.settings.gradle b/example-app/android/capacitor.settings.gradle new file mode 100644 index 0000000..ee6419e --- /dev/null +++ b/example-app/android/capacitor.settings.gradle @@ -0,0 +1,6 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN +include ':capacitor-android' +project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor') + +include ':capacitor-levelplay' +project(':capacitor-levelplay').projectDir = new File('../../android') diff --git a/example-app/android/gradle.properties b/example-app/android/gradle.properties new file mode 100644 index 0000000..2e87c52 --- /dev/null +++ b/example-app/android/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true diff --git a/example-app/android/gradle/wrapper/gradle-wrapper.jar b/example-app/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/example-app/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/example-app/android/gradle/wrapper/gradle-wrapper.properties b/example-app/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7705927 --- /dev/null +++ b/example-app/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/example-app/android/gradlew b/example-app/android/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/example-app/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/example-app/android/gradlew.bat b/example-app/android/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/example-app/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/example-app/android/settings.gradle b/example-app/android/settings.gradle new file mode 100644 index 0000000..3b4431d --- /dev/null +++ b/example-app/android/settings.gradle @@ -0,0 +1,5 @@ +include ':app' +include ':capacitor-cordova-android-plugins' +project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/') + +apply from: 'capacitor.settings.gradle' \ No newline at end of file diff --git a/example-app/android/variables.gradle b/example-app/android/variables.gradle new file mode 100644 index 0000000..ee4ba41 --- /dev/null +++ b/example-app/android/variables.gradle @@ -0,0 +1,16 @@ +ext { + minSdkVersion = 24 + compileSdkVersion = 36 + targetSdkVersion = 36 + androidxActivityVersion = '1.11.0' + androidxAppCompatVersion = '1.7.1' + androidxCoordinatorLayoutVersion = '1.3.0' + androidxCoreVersion = '1.17.0' + androidxFragmentVersion = '1.8.9' + coreSplashScreenVersion = '1.2.0' + androidxWebkitVersion = '1.14.0' + junitVersion = '4.13.2' + androidxJunitVersion = '1.3.0' + androidxEspressoCoreVersion = '3.7.0' + cordovaAndroidVersion = '14.0.1' +} \ No newline at end of file diff --git a/example-app/capacitor.config.json b/example-app/capacitor.config.json new file mode 100644 index 0000000..89f7218 --- /dev/null +++ b/example-app/capacitor.config.json @@ -0,0 +1,5 @@ +{ + "appId": "fyi.crt.levelplay.example", + "appName": "LevelPlay Example", + "webDir": "www" +} diff --git a/example-app/index.html b/example-app/index.html new file mode 100644 index 0000000..2c11b2c --- /dev/null +++ b/example-app/index.html @@ -0,0 +1,54 @@ + + + + + + LevelPlay Example + + + +
+

capacitor-levelplay

+

Not initialized

+ +
+

SDK

+ + + + +
+ +
+

Full screen

+ + + + +
+ +
+

Banner

+ + + + + +
+ +
+

Native

+ + + +
+
+ +
+

Log

+

+      
+
+ + + diff --git a/example-app/ios/.gitignore b/example-app/ios/.gitignore new file mode 100644 index 0000000..f470299 --- /dev/null +++ b/example-app/ios/.gitignore @@ -0,0 +1,13 @@ +App/build +App/Pods +App/output +App/App/public +DerivedData +xcuserdata + +# Cordova plugins for Capacitor +capacitor-cordova-ios-plugins + +# Generated Config files +App/App/capacitor.config.json +App/App/config.xml diff --git a/example-app/ios/App/App.xcodeproj/project.pbxproj b/example-app/ios/App/App.xcodeproj/project.pbxproj new file mode 100644 index 0000000..bae79bd --- /dev/null +++ b/example-app/ios/App/App.xcodeproj/project.pbxproj @@ -0,0 +1,382 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; }; + 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; }; + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; }; + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; }; + 504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; }; + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; }; + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; }; + 50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; }; + 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = ""; }; + 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = ""; }; + 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = ""; }; + 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 504EC3011FED79650016851F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 504EC2FB1FED79650016851F = { + isa = PBXGroup; + children = ( + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */, + 504EC3061FED79650016851F /* App */, + 504EC3051FED79650016851F /* Products */, + ); + sourceTree = ""; + }; + 504EC3051FED79650016851F /* Products */ = { + isa = PBXGroup; + children = ( + 504EC3041FED79650016851F /* App.app */, + ); + name = Products; + sourceTree = ""; + }; + 504EC3061FED79650016851F /* App */ = { + isa = PBXGroup; + children = ( + 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */, + 50379B222058CBB4000EE86E /* capacitor.config.json */, + 504EC3071FED79650016851F /* AppDelegate.swift */, + 504EC30B1FED79650016851F /* Main.storyboard */, + 504EC30E1FED79650016851F /* Assets.xcassets */, + 504EC3101FED79650016851F /* LaunchScreen.storyboard */, + 504EC3131FED79650016851F /* Info.plist */, + 2FAD9762203C412B000D30F8 /* config.xml */, + 50B271D01FEDC1A000F3C39B /* public */, + ); + path = App; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 504EC3031FED79650016851F /* App */ = { + isa = PBXNativeTarget; + buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */; + buildPhases = ( + 504EC3001FED79650016851F /* Sources */, + 504EC3011FED79650016851F /* Frameworks */, + 504EC3021FED79650016851F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = App; + packageProductDependencies = ( + 4D22ABE82AF431CB00220026 /* CapApp-SPM */, + ); + productName = App; + productReference = 504EC3041FED79650016851F /* App.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 504EC2FC1FED79650016851F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 0920; + TargetAttributes = { + 504EC3031FED79650016851F = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */; + compatibilityVersion = "Xcode 8.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 504EC2FB1FED79650016851F; + packageReferences = ( + D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */, + ); + productRefGroup = 504EC3051FED79650016851F /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 504EC3031FED79650016851F /* App */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 504EC3021FED79650016851F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */, + 50B271D11FEDC1A000F3C39B /* public in Resources */, + 504EC30F1FED79650016851F /* Assets.xcassets in Resources */, + 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */, + 504EC30D1FED79650016851F /* Main.storyboard in Resources */, + 2FAD9763203C412B000D30F8 /* config.xml in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 504EC3001FED79650016851F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 504EC3081FED79650016851F /* AppDelegate.swift in Sources */, + 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 504EC30B1FED79650016851F /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC30C1FED79650016851F /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 504EC3101FED79650016851F /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 504EC3111FED79650016851F /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 504EC3141FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 504EC3151FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 504EC3171FED79650016851F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + INFOPLIST_FILE = App/Info.plist; + OTHER_LDFLAGS = "-ObjC"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; + PRODUCT_BUNDLE_IDENTIFIER = fyi.crt.levelplay.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 504EC3181FED79650016851F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + INFOPLIST_FILE = App/Info.plist; + OTHER_LDFLAGS = "-ObjC"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = fyi.crt.levelplay.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = ""; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3141FED79650016851F /* Debug */, + 504EC3151FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 504EC3171FED79650016851F /* Debug */, + 504EC3181FED79650016851F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = "CapApp-SPM"; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 4D22ABE82AF431CB00220026 /* CapApp-SPM */ = { + isa = XCSwiftPackageProductDependency; + package = D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */; + productName = "CapApp-SPM"; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 504EC2FC1FED79650016851F /* Project object */; +} diff --git a/example-app/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example-app/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example-app/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example-app/ios/App/App/AppDelegate.swift b/example-app/ios/App/App/AppDelegate.swift new file mode 100644 index 0000000..fec95ac --- /dev/null +++ b/example-app/ios/App/App/AppDelegate.swift @@ -0,0 +1,44 @@ +import UIKit +import Capacitor + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + func application(_ application: UIApplication, + configurationForConnecting connectingSceneSession: UISceneSession, + options: UIScene.ConnectionOptions) -> UISceneConfiguration { + let config = UISceneConfiguration(name: "Default Configuration", + sessionRole: connectingSceneSession.role) + config.delegateClass = SceneDelegate.self + return config + } +} diff --git a/example-app/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png b/example-app/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png new file mode 100644 index 0000000..adf6ba0 Binary files /dev/null and b/example-app/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png differ diff --git a/example-app/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/example-app/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..9b7d382 --- /dev/null +++ b/example-app/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "AppIcon-512@2x.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/example-app/ios/App/App/Assets.xcassets/Contents.json b/example-app/ios/App/App/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/example-app/ios/App/App/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/example-app/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json new file mode 100644 index 0000000..d7d96a6 --- /dev/null +++ b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "splash-2732x2732-2.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "splash-2732x2732-1.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "splash-2732x2732.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png new file mode 100644 index 0000000..33ea6c9 Binary files /dev/null and b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png differ diff --git a/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png new file mode 100644 index 0000000..33ea6c9 Binary files /dev/null and b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png differ diff --git a/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png new file mode 100644 index 0000000..33ea6c9 Binary files /dev/null and b/example-app/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png differ diff --git a/example-app/ios/App/App/Base.lproj/LaunchScreen.storyboard b/example-app/ios/App/App/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..e7ae5d7 --- /dev/null +++ b/example-app/ios/App/App/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example-app/ios/App/App/Base.lproj/Main.storyboard b/example-app/ios/App/App/Base.lproj/Main.storyboard new file mode 100644 index 0000000..b44df7b --- /dev/null +++ b/example-app/ios/App/App/Base.lproj/Main.storyboard @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/example-app/ios/App/App/Info.plist b/example-app/ios/App/App/Info.plist new file mode 100644 index 0000000..b915d1d --- /dev/null +++ b/example-app/ios/App/App/Info.plist @@ -0,0 +1,84 @@ + + + + + CAPACITOR_DEBUG + $(CAPACITOR_DEBUG) + CFBundleDevelopmentRegion + en + CFBundleDisplayName + LevelPlay Example + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + LSRequiresIPhoneOS + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + NSUserTrackingUsageDescription + Your data will be used to deliver ads that are more relevant to you. + SKAdNetworkItems + + + SKAdNetworkIdentifier + su67r6k2v3.skadnetwork + + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/example-app/ios/App/App/SceneDelegate.swift b/example-app/ios/App/App/SceneDelegate.swift new file mode 100644 index 0000000..f352e1e --- /dev/null +++ b/example-app/ios/App/App/SceneDelegate.swift @@ -0,0 +1,24 @@ +import UIKit +import Capacitor + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = scene as? UIWindowScene else { return } + + window = UIWindow(windowScene: windowScene) + window?.rootViewController = CAPBridgeViewController() + window?.makeKeyAndVisible() + + SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions) + } + + func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { + SceneDelegateProxy.shared.scene(scene, openURLContexts: URLContexts) + } + + func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { + SceneDelegateProxy.shared.scene(scene, continue: userActivity) + } +} diff --git a/example-app/ios/App/CapApp-SPM/.gitignore b/example-app/ios/App/CapApp-SPM/.gitignore new file mode 100644 index 0000000..3b29812 --- /dev/null +++ b/example-app/ios/App/CapApp-SPM/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +xcuserdata/ +DerivedData/ +.swiftpm/config/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc diff --git a/example-app/ios/App/CapApp-SPM/Package.swift b/example-app/ios/App/CapApp-SPM/Package.swift new file mode 100644 index 0000000..ae87314 --- /dev/null +++ b/example-app/ios/App/CapApp-SPM/Package.swift @@ -0,0 +1,27 @@ +// swift-tools-version: 5.9 +import PackageDescription + +// DO NOT MODIFY THIS FILE - managed by Capacitor CLI commands +let package = Package( + name: "CapApp-SPM", + platforms: [.iOS(.v15)], + products: [ + .library( + name: "CapApp-SPM", + targets: ["CapApp-SPM"]) + ], + dependencies: [ + .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "8.5.2"), + .package(name: "CapacitorLevelplay", path: "../../../..") + ], + targets: [ + .target( + name: "CapApp-SPM", + dependencies: [ + .product(name: "Capacitor", package: "capacitor-swift-pm"), + .product(name: "Cordova", package: "capacitor-swift-pm"), + .product(name: "CapacitorLevelplay", package: "CapacitorLevelplay") + ] + ) + ] +) diff --git a/example-app/ios/App/CapApp-SPM/README.md b/example-app/ios/App/CapApp-SPM/README.md new file mode 100644 index 0000000..03964db --- /dev/null +++ b/example-app/ios/App/CapApp-SPM/README.md @@ -0,0 +1,5 @@ +# CapApp-SPM + +This package is used to host SPM dependencies for your Capacitor project + +Do not modify the contents of it or there may be unintended consequences. diff --git a/example-app/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift b/example-app/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift new file mode 100644 index 0000000..945afec --- /dev/null +++ b/example-app/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift @@ -0,0 +1 @@ +public let isCapacitorApp = true diff --git a/example-app/ios/debug.xcconfig b/example-app/ios/debug.xcconfig new file mode 100644 index 0000000..53ce18d --- /dev/null +++ b/example-app/ios/debug.xcconfig @@ -0,0 +1 @@ +CAPACITOR_DEBUG = true diff --git a/example-app/package.json b/example-app/package.json new file mode 100644 index 0000000..46713cc --- /dev/null +++ b/example-app/package.json @@ -0,0 +1,21 @@ +{ + "name": "capacitor-levelplay-example", + "version": "0.3.0", + "private": true, + "description": "Minimal Capacitor app for capacitor-levelplay (Unity LevelPlay demo ids).", + "scripts": { + "build": "tsc --noEmit && rm -rf www && mkdir -p www && cp index.html style.css www/ && esbuild src/main.ts --bundle --format=esm --target=es2020 --alias:@capacitor/core=./node_modules/@capacitor/core --outfile=www/main.js", + "sync": "npm run build && cap sync" + }, + "dependencies": { + "@capacitor/android": "^8.0.0", + "@capacitor/core": "^8.0.0", + "@capacitor/ios": "8.5.2", + "capacitor-levelplay": "file:.." + }, + "devDependencies": { + "@capacitor/cli": "^8.0.0", + "esbuild": "^0.28.0", + "typescript": "^5.9.3" + } +} diff --git a/example-app/src/main.ts b/example-app/src/main.ts new file mode 100644 index 0000000..36c8abd --- /dev/null +++ b/example-app/src/main.ts @@ -0,0 +1,136 @@ +import { Capacitor } from '@capacitor/core'; +import { LEVELPLAY_DEMO, LevelPlay } from 'capacitor-levelplay'; +import type { NativeAdTemplate, Rect } from 'capacitor-levelplay'; + +// Unity's public demo ids: test ads only. Use your own ids from the LevelPlay dashboard in a real app. +const ids = Capacitor.getPlatform() === 'ios' ? LEVELPLAY_DEMO.ios : LEVELPLAY_DEMO.android; +const BANNER_ID = 'main'; +const NATIVE_ID = 'native'; + +const logEl = document.getElementById('log') as HTMLPreElement; +const statusEl = document.getElementById('status') as HTMLParagraphElement; +const slot = document.getElementById('native-slot') as HTMLDivElement; + +function log(label: string, data?: unknown): void { + const time = new Date().toISOString().slice(11, 19); + const line = data === undefined ? label : `${label} ${JSON.stringify(data)}`; + logEl.textContent = `${time} ${line}\n${logEl.textContent ?? ''}`.slice(0, 20000); +} + +function errorText(e: unknown): string { + const err = e as { code?: string; message?: string }; + return `${err.code ?? 'ERROR'}: ${err.message ?? String(e)}`; +} + +let bannerExists = false; +let nativeShown = false; + +function slotRect(): Rect { + const r = slot.getBoundingClientRect(); + return { x: r.left, y: r.top, width: r.width, height: r.height }; +} + +async function createBanner(position: 'top' | 'bottom'): Promise { + if (bannerExists) { + log('setBannerLayout', await LevelPlay.setBannerLayout({ bannerId: BANNER_ID, position })); + await LevelPlay.showBanner({ bannerId: BANNER_ID }); + return; + } + const res = await LevelPlay.createBanner({ adUnitId: ids.banner, bannerId: BANNER_ID, size: 'ADAPTIVE', position }); + bannerExists = true; + log('createBanner', res); + await LevelPlay.loadBanner({ bannerId: BANNER_ID }); // one-shot per banner object + await LevelPlay.showBanner({ bannerId: BANNER_ID }); +} + +async function loadNative(template: NativeAdTemplate): Promise { + await LevelPlay.destroyNativeAd({ nativeAdId: NATIVE_ID }); + nativeShown = false; + slot.className = template; + await LevelPlay.loadNativeAd({ + nativeAdId: NATIVE_ID, + template, + style: { cornerRadius: 8, callToActionBackgroundColor: '#2f6fed', callToActionTextColor: '#ffffff' }, + }); +} + +const actions: Record Promise> = { + init: async () => { + const res = await LevelPlay.initialize({ appKey: ids.appKey, userId: 'example-user' }); + statusEl.textContent = `LevelPlay ${res.sdkVersion} on ${Capacitor.getPlatform()}`; + return res; + }, + capabilities: () => LevelPlay.getCapabilities(), + segment: () => + LevelPlay.setSegment({ segmentName: 'example', level: 3, isPaying: false, customParameters: { source: 'demo' } }), + userId: () => LevelPlay.setDynamicUserId({ userId: `example-${Date.now()}` }), + loadRewarded: () => LevelPlay.loadRewarded({ adUnitId: ids.rewarded }), + showRewarded: () => LevelPlay.showRewarded({ adUnitId: ids.rewarded }), + loadInterstitial: () => LevelPlay.loadInterstitial({ adUnitId: ids.interstitial }), + showInterstitial: () => LevelPlay.showInterstitial({ adUnitId: ids.interstitial }), + bannerTop: () => createBanner('top'), + bannerBottom: () => createBanner('bottom'), + bannerHide: () => LevelPlay.hideBanner({ bannerId: BANNER_ID }), + bannerShow: () => LevelPlay.showBanner({ bannerId: BANNER_ID }), + bannerDestroy: async () => { + bannerExists = false; + await LevelPlay.destroyBanner({ bannerId: BANNER_ID }); + }, + nativeSmall: () => loadNative('small'), + nativeMedium: () => loadNative('medium'), + nativeDestroy: async () => { + nativeShown = false; + slot.className = ''; + await LevelPlay.destroyNativeAd({ nativeAdId: NATIVE_ID }); + }, + clear: async () => { + logEl.textContent = ''; + }, +}; + +document.addEventListener('click', (ev) => { + const action = (ev.target as HTMLElement).closest('button')?.dataset.action; + if (!action || !actions[action]) return; + actions[action]() + .then((res) => action !== 'clear' && log(`${action} ok`, res)) + .catch((e) => log(`${action} failed`, errorText(e))); +}); + +// Keep a shown native ad on its placeholder while the page scrolls or resizes. +let rectQueued = false; +function followSlot(): void { + if (!nativeShown || rectQueued) return; + rectQueued = true; + requestAnimationFrame(() => { + rectQueued = false; + LevelPlay.setNativeAdRect({ nativeAdId: NATIVE_ID, rect: slotRect() }).catch(() => undefined); + }); +} +window.addEventListener('scroll', followSlot, { passive: true }); +window.addEventListener('resize', followSlot); + +async function listen(): Promise { + // The plugin queues up to 100 impressions until the first listener is added. + await LevelPlay.addListener('impressionData', (e) => log('IMPRESSION', { format: e.adFormat, network: e.adNetwork, revenue: e.revenue, precision: e.precision })); + for (const name of ['loaded', 'loadFailed', 'displayed', 'displayFailed', 'clicked', 'closed', 'rewarded'] as const) { + await LevelPlay.addListener(name as 'loaded', (e) => log(name, e)); + } + await LevelPlay.addListener('bannerLoaded', (e) => log('bannerLoaded', e.frame)); + await LevelPlay.addListener('bannerLoadFailed', (e) => log('bannerLoadFailed', e.error)); + await LevelPlay.addListener('bannerClicked', (e) => log('bannerClicked', e.bannerId)); + await LevelPlay.addListener('nativeAdLoaded', async (e) => { + log('nativeAdLoaded', e.adInfo?.adNetwork); + try { + await LevelPlay.showNativeAd({ nativeAdId: e.nativeAdId, rect: slotRect() }); + nativeShown = true; + } catch (err) { + log('showNativeAd failed', errorText(err)); + } + }); + await LevelPlay.addListener('nativeAdLoadFailed', (e) => log('nativeAdLoadFailed', e.error)); + await LevelPlay.addListener('nativeAdImpression', (e) => log('nativeAdImpression', e.nativeAdId)); + await LevelPlay.addListener('nativeAdClicked', (e) => log('nativeAdClicked', e.nativeAdId)); +} + +listen().catch((e) => log('listeners failed', errorText(e))); +log(`platform ${Capacitor.getPlatform()}, app key ${ids.appKey}`); diff --git a/example-app/style.css b/example-app/style.css new file mode 100644 index 0000000..6bde734 --- /dev/null +++ b/example-app/style.css @@ -0,0 +1,10 @@ +:root { color-scheme: light dark; font-family: system-ui, sans-serif; } +body { margin: 0; padding: env(safe-area-inset-top) 16px calc(env(safe-area-inset-bottom) + 80px); } +h1 { font-size: 20px; } +h2 { font-size: 15px; margin: 16px 0 8px; } +button { margin: 0 6px 6px 0; padding: 10px 12px; font-size: 14px; border-radius: 8px; border: 1px solid #8888; } +#status { font-size: 13px; opacity: 0.8; } +#native-slot { height: 0; margin-top: 8px; border: 1px dashed #8888; border-radius: 8px; } +#native-slot.small { height: 90px; } +#native-slot.medium { height: 300px; } +#log { font-size: 11px; white-space: pre-wrap; word-break: break-all; max-height: 40vh; overflow: auto; } diff --git a/example-app/tsconfig.json b/example-app/tsconfig.json new file mode 100644 index 0000000..38e0c98 --- /dev/null +++ b/example-app/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2020", + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "lib": ["es2020", "dom"] + }, + "include": ["src"] +} diff --git a/ios/Sources/LevelPlayPlugin/BannerManager.swift b/ios/Sources/LevelPlayPlugin/BannerManager.swift new file mode 100644 index 0000000..5ff00a3 --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/BannerManager.swift @@ -0,0 +1,334 @@ +import IronSource +import UIKit + +protocol AdHost: AnyObject { + func hostViewController() -> UIViewController? + /// The overlay, attached on first use; nil when there is no WebView. + func overlay() -> OverlayHost? + var initialized: Bool { get } + func emit(_ event: String, _ data: [String: Any]) +} + +/// Banners (design §3, §6): `LPMBannerAdView` instances keyed by bannerId, laid out in the OverlayHost. +/// Main thread only. +final class BannerManager { + /// Owner decision Q4: adaptive banners follow safe-area width changes after the layout settled. + private static let adaptiveRecreateDelay: TimeInterval = 0.25 + + weak var host: AdHost? + private let impressionDelegate: LPMImpressionDataDelegate + private var slots: [String: Slot] = [:] + private var adaptiveCheck: DispatchWorkItem? + + init(impressionDelegate: LPMImpressionDataDelegate) { + self.impressionDelegate = impressionDelegate + } + + final class Slot { + let bannerId: String + let adUnitId: String + let size: String + let fixedAdaptiveWidth: Int? + let customWidth: Int + let customHeight: Int + let placementName: String? + let bidFloor: Double? + var position = "bottom" + var offsetX: CGFloat = 0 + var offsetY: CGFloat = 0 + var respectSafeArea = true + + var view: LPMBannerAdView! + var listener: Listener? + var adSize: LPMAdSize! + /// CSS px width the adaptive size was computed for. + var adaptiveWidthUsed = 0 + var visible = false + var loadRequested = false + var frame = CGRect.zero + var loggedFrame = CGRect.null + + init(bannerId: String, adUnitId: String, size: String, fixedAdaptiveWidth: Int?, customWidth: Int, + customHeight: Int, placementName: String?, bidFloor: Double?) { + self.bannerId = bannerId + self.adUnitId = adUnitId + self.size = size + self.fixedAdaptiveWidth = fixedAdaptiveWidth + self.customWidth = customWidth + self.customHeight = customHeight + self.placementName = placementName + self.bidFloor = bidFloor + } + } + + // MARK: - API + + func create(_ o: [String: Any]) throws -> [String: Any] { + guard let adUnitId = Args.nonEmpty(o, "adUnitId") else { throw CallError.invalid("adUnitId is required") } + let bannerId = Args.nonEmpty(o, "bannerId") ?? adUnitId + let custom = Args.object(o, "customSize") + let size = Args.string(o, "size") ?? (custom != nil ? "CUSTOM" : "ADAPTIVE") + if !OverlayMath.isBannerSize(size) { throw CallError.invalid("Unknown banner size '\(size)'") } + var cw = 0, ch = 0 + if size == "CUSTOM" { + guard let custom = custom else { throw CallError.invalid("size CUSTOM needs customSize { width, height }") } + cw = try Args.positiveInt(custom, "customSize.width", "width") + ch = try Args.positiveInt(custom, "customSize.height", "height") + } + var fixedWidth: Int? + if Args.present(o, "adaptiveWidth") { fixedWidth = try Args.positiveInt(o, "adaptiveWidth", "adaptiveWidth") } + var bidFloor: Double? + if Args.present(o, "bidFloor") { + guard let v = Args.number(o["bidFloor"]), v >= 0 else { throw CallError.invalid("bidFloor must be a number >= 0") } + bidFloor = v + } + let placement = Args.nonEmpty(o, "placementName") + + let s = Slot(bannerId: bannerId, adUnitId: adUnitId, size: size, fixedAdaptiveWidth: fixedWidth, customWidth: cw, + customHeight: ch, placementName: placement, bidFloor: bidFloor) + try applyLayout(s, o) + + guard let host = host, host.initialized else { + throw CallError("NOT_INITIALIZED", "Call initialize() and wait for it before createBanner()") + } + if slots[bannerId] != nil { throw CallError("ALREADY_EXISTS", "Banner '\(bannerId)' already exists; destroy it first") } + guard host.hostViewController() != nil else { + throw CallError("NO_VIEW_CONTROLLER", "No view controller to attach the banner to") + } + guard let overlay = host.overlay() else { + throw CallError("NO_VIEW_CONTROLLER", "The WebView is not attached to a view hierarchy") + } + try buildView(s, overlay) + slots[bannerId] = s + relayout(s, overlay) + return result(s) + } + + func load(_ bannerId: String?) throws { + let s = try require(bannerId) + guard let vc = host?.hostViewController() else { + throw CallError("NO_VIEW_CONTROLLER", "No view controller to load the banner with") + } + s.loadRequested = true + s.view.loadAd(with: vc) + } + + func show(_ bannerId: String?) throws -> [String: Any] { + let s = try require(bannerId) + s.visible = true + s.view.isHidden = false + s.view.superview?.bringSubviewToFront(s.view) + s.view.resumeAutoRefresh() + if let overlay = host?.overlay() { + relayout(s, overlay) + log(s, overlay) + } + return result(s) + } + + func hide(_ bannerId: String?) { + guard let id = bannerId, let s = slots[id] else { return } + s.visible = false + s.view.isHidden = true + s.view.pauseAutoRefresh() + levelPlayLog.notice("banner \(s.bannerId, privacy: .public) hidden") + } + + func setLayout(_ o: [String: Any]) throws -> [String: Any] { + let s = try require(Args.string(o, "bannerId")) + try applyLayout(s, o) + if let overlay = host?.overlay() { relayout(s, overlay) } + return result(s) + } + + func destroy(_ bannerId: String?) { + guard let id = bannerId, let s = slots.removeValue(forKey: id) else { return } + destroyView(s) + } + + func destroyAll() { + adaptiveCheck?.cancel() + adaptiveCheck = nil + for s in slots.values { destroyView(s) } + slots.removeAll() + } + + /// Overlay layout pass: re-place every banner and schedule the adaptive width check (Q4). + func onLayoutChanged(_ overlay: OverlayHost) { + var adaptiveChanged = false + for s in slots.values { + relayout(s, overlay) + if followsWidth(s) && currentAdaptiveWidth(s, overlay) != s.adaptiveWidthUsed { adaptiveChanged = true } + } + adaptiveCheck?.cancel() + adaptiveCheck = nil + if adaptiveChanged { + let work = DispatchWorkItem { [weak self] in self?.recreateChangedAdaptive() } + adaptiveCheck = work + DispatchQueue.main.asyncAfter(deadline: .now() + Self.adaptiveRecreateDelay, execute: work) + } + } + + // MARK: - Internals + + private func require(_ bannerId: String?) throws -> Slot { + guard let id = bannerId, !id.isEmpty else { throw CallError.invalid("bannerId is required") } + guard let s = slots[id] else { throw CallError.notFound("Banner", id) } + return s + } + + private func applyLayout(_ s: Slot, _ o: [String: Any]) throws { + if Args.present(o, "position") { + guard let p = o["position"] as? String, OverlayMath.isPosition(p) else { + throw CallError.invalid("position must be 'top', 'bottom' or 'center'") + } + s.position = p + } + if Args.present(o, "offsetX") { s.offsetX = CGFloat(try Args.finite(o, "offsetX")) } + if Args.present(o, "offsetY") { s.offsetY = CGFloat(try Args.finite(o, "offsetY")) } + if Args.present(o, "respectSafeArea") { + guard Args.isBool(o["respectSafeArea"]), let b = o["respectSafeArea"] as? Bool else { + throw CallError.invalid("respectSafeArea must be a boolean") + } + s.respectSafeArea = b + } + } + + private func followsWidth(_ s: Slot) -> Bool { + return s.size == "ADAPTIVE" && s.fixedAdaptiveWidth == nil + } + + private func area(_ s: Slot, _ overlay: OverlayHost) -> CGRect { + return s.respectSafeArea ? overlay.safeAreaCss : overlay.webViewCss + } + + private func currentAdaptiveWidth(_ s: Slot, _ overlay: OverlayHost) -> Int { + return Int(area(s, overlay).width.rounded(.down)) + } + + private func resolveSize(_ s: Slot, _ overlay: OverlayHost) -> LPMAdSize? { + switch s.size { + case "BANNER": return LPMAdSize.banner() + case "LARGE": return LPMAdSize.large() + case "MEDIUM_RECTANGLE": return LPMAdSize.mediumRectangle() + case "LEADERBOARD": return LPMAdSize.leaderBoard() + case "CUSTOM": return LPMAdSize.customSize(withWidth: s.customWidth, height: s.customHeight) + default: + // 1 CSS px = 1 pt; the SDK width is in points. + let width = s.fixedAdaptiveWidth ?? currentAdaptiveWidth(s, overlay) + s.adaptiveWidthUsed = width + return width > 0 ? LPMAdSize.createAdaptiveAdSize(withWidth: CGFloat(width)) : LPMAdSize.createAdaptive() + } + } + + private func buildView(_ s: Slot, _ overlay: OverlayHost) throws { + guard let size = resolveSize(s, overlay) else { + throw CallError("NOT_INITIALIZED", "The SDK returned no adaptive size (initialize() not finished)") + } + let builder = LPMBannerAdViewConfigBuilder().set(adSize: size) + if let floor = s.bidFloor { _ = builder.set(bidFloor: NSNumber(value: floor)) } + if let placement = s.placementName { _ = builder.set(placementName: placement) } + let view = LPMBannerAdView(adUnitId: s.adUnitId, config: builder.build()) + let listener = Listener(manager: self, slot: s, view: view) + view.setDelegate(listener) + view.setImpressionDataDelegate(impressionDelegate) + view.isHidden = !s.visible + s.view = view + s.listener = listener + s.adSize = size + overlay.add(view) + } + + private func relayout(_ s: Slot, _ overlay: OverlayHost) { + s.frame = OverlayMath.bannerFrame(area(s, overlay), width: CGFloat(s.adSize.width), height: CGFloat(s.adSize.height), + position: s.position, offsetX: s.offsetX, offsetY: s.offsetY) + overlay.place(s.view, s.frame) + if s.frame != s.loggedFrame { + s.loggedFrame = s.frame + log(s, overlay) + } + } + + private func log(_ s: Slot, _ overlay: OverlayHost) { + levelPlayLog.notice("banner \(s.bannerId, privacy: .public) frame \(Self.describe(s.view.frame), privacy: .public) in \(Self.describe(overlay.bounds), privacy: .public) safe \(Self.describe(overlay.safeAreaCss), privacy: .public) visible \(s.visible, privacy: .public)") + } + + static func describe(_ r: CGRect) -> String { + return String(format: "%.1f,%.1f %.1fx%.1f", r.minX, r.minY, r.width, r.height) + } + + private func destroyView(_ s: Slot) { + s.listener = nil + s.view.destroy() + s.view.removeFromSuperview() + } + + /// Q4: recreate adaptive banners whose safe-area width changed; keeps id, layout, visibility; reloads if loaded. + private func recreateChangedAdaptive() { + adaptiveCheck = nil + guard let overlay = host?.overlay() else { return } + let vc = host?.hostViewController() + for s in slots.values { + let width = currentAdaptiveWidth(s, overlay) + if !followsWidth(s) || width == s.adaptiveWidthUsed || width <= 0 { continue } + destroyView(s) + do { try buildView(s, overlay) } catch { continue } + relayout(s, overlay) + if s.loadRequested, let vc = vc { s.view.loadAd(with: vc) } + if !s.visible { s.view.pauseAutoRefresh() } + } + } + + private func result(_ s: Slot) -> [String: Any] { + return ["bannerId": s.bannerId, "adSize": Mappers.adSize(s.adSize), "frame": Mappers.rect(s.frame), "visible": s.visible] + } + + fileprivate func emit(_ name: String, _ slot: Slot, _ view: LPMBannerAdView, _ info: LPMAdInfo?, _ error: Error?) { + // Callbacks of a view that was replaced (Q4) or destroyed are dropped. + guard slot.view === view, slots[slot.bannerId] === slot else { return } + var o: [String: Any] = ["bannerId": slot.bannerId, "adUnitId": slot.adUnitId, "frame": Mappers.rect(slot.frame)] + if let info = info { o["adInfo"] = Mappers.adInfo(info) } + if let error = error { o["error"] = Mappers.error(error) } + host?.emit(name, o) + } + + /// One delegate per view (the SDK holds it weakly; the slot keeps it alive). + final class Listener: NSObject, LPMBannerAdViewDelegate { + private weak var manager: BannerManager? + private weak var slot: Slot? + private weak var view: LPMBannerAdView? + + init(manager: BannerManager, slot: Slot, view: LPMBannerAdView) { + self.manager = manager + self.slot = slot + self.view = view + } + + private func post(_ name: String, _ info: LPMAdInfo?, _ error: Error?) { + DispatchQueue.main.async { [weak self] in + guard let self = self, let slot = self.slot, let view = self.view else { return } + self.manager?.emit(name, slot, view, info, error) + } + } + + @objc(didLoadAdWithAdInfo:) func didLoadAd(with adInfo: LPMAdInfo) { post("bannerLoaded", adInfo, nil) } + + @objc(didFailToLoadAdWithAdUnitId:error:) func didFailToLoadAd(withAdUnitId adUnitId: String, error: Error) { + post("bannerLoadFailed", nil, error) + } + + @objc(didDisplayAdWithAdInfo:) func didDisplayAd(with adInfo: LPMAdInfo) { post("bannerDisplayed", adInfo, nil) } + + @objc(didFailToDisplayAdWithAdInfo:error:) func didFailToDisplayAd(with adInfo: LPMAdInfo, error: Error) { + post("bannerDisplayFailed", adInfo, error) + } + + @objc(didClickAdWithAdInfo:) func didClickAd(with adInfo: LPMAdInfo) { post("bannerClicked", adInfo, nil) } + + @objc(didExpandAdWithAdInfo:) func didExpandAd(with adInfo: LPMAdInfo) { post("bannerExpanded", adInfo, nil) } + + @objc(didCollapseAdWithAdInfo:) func didCollapseAd(with adInfo: LPMAdInfo) { post("bannerCollapsed", adInfo, nil) } + + @objc(didLeaveAppWithAdInfo:) func didLeaveApp(with adInfo: LPMAdInfo) { post("bannerLeftApplication", adInfo, nil) } + } +} diff --git a/ios/Sources/LevelPlayPlugin/CallError.swift b/ios/Sources/LevelPlayPlugin/CallError.swift new file mode 100644 index 0000000..005a125 --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/CallError.swift @@ -0,0 +1,65 @@ +import Foundation + +/// A promise rejection with one of the plugin's string codes (INVALID_ARGUMENT, NOT_FOUND ...). +struct CallError: Error { + let code: String + let message: String + + init(_ code: String, _ message: String) { + self.code = code + self.message = message + } + + static func invalid(_ message: String) -> CallError { + return CallError("INVALID_ARGUMENT", message) + } + + static func notFound(_ what: String, _ id: String) -> CallError { + return CallError("NOT_FOUND", "\(what) '\(id)' not found") + } +} + +/// Typed reads from a Capacitor options dictionary. JS booleans arrive as CFBoolean-backed NSNumbers and are told +/// apart from numbers, so the checks match the Android bridge (where Boolean is not a Number). +enum Args { + static func isBool(_ v: Any?) -> Bool { + guard let n = v as? NSNumber else { return false } + return CFGetTypeID(n) == CFBooleanGetTypeID() + } + + static func number(_ v: Any?) -> Double? { + guard let n = v as? NSNumber, !isBool(n) else { return nil } + return n.doubleValue + } + + static func present(_ o: [String: Any], _ key: String) -> Bool { + guard let v = o[key] else { return false } + return !(v is NSNull) + } + + static func string(_ o: [String: Any], _ key: String) -> String? { + return o[key] as? String + } + + static func nonEmpty(_ o: [String: Any], _ key: String) -> String? { + guard let s = o[key] as? String, !s.isEmpty else { return nil } + return s + } + + static func object(_ o: [String: Any], _ key: String) -> [String: Any]? { + return o[key] as? [String: Any] + } + + static func finite(_ o: [String: Any], _ key: String) throws -> Double { + guard let d = number(o[key]) else { throw CallError.invalid("\(key) must be a number") } + if !d.isFinite { throw CallError.invalid("\(key) must be finite") } + return d + } + + static func positiveInt(_ o: [String: Any], _ label: String, _ key: String) throws -> Int { + guard let d = number(o[key]), d >= 1, d.isFinite else { + throw CallError.invalid("\(label) must be a positive number") + } + return Int(d.rounded()) + } +} diff --git a/ios/Sources/LevelPlayPlugin/LevelPlayPlugin.swift b/ios/Sources/LevelPlayPlugin/LevelPlayPlugin.swift index 418bf0c..3942af5 100644 --- a/ios/Sources/LevelPlayPlugin/LevelPlayPlugin.swift +++ b/ios/Sources/LevelPlayPlugin/LevelPlayPlugin.swift @@ -3,8 +3,9 @@ import Capacitor import Foundation import IronSource -/// Capacitor bridge for the Unity LevelPlay SDK (ad-unit API: `LPMRewardedAd` / `LPMInterstitialAd`). -/// Rewarded and interstitial only. All LevelPlay calls run on the main thread. +/// Capacitor bridge for the Unity LevelPlay SDK (ad-unit API: `LPMRewardedAd` / `LPMInterstitialAd` / +/// `LPMBannerAdView`, plus `LevelPlayNativeAd`). Every SDK call and every view operation runs on the main thread; +/// plugin state is only touched there. @objc(LevelPlayPlugin) public class LevelPlayPlugin: CAPPlugin, CAPBridgedPlugin { public let identifier = "LevelPlayPlugin" @@ -22,14 +23,72 @@ public class LevelPlayPlugin: CAPPlugin, CAPBridgedPlugin { CAPPluginMethod(name: "showInterstitial", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "isReady", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "launchTestSuite", returnType: CAPPluginReturnPromise), - CAPPluginMethod(name: "validateIntegration", returnType: CAPPluginReturnPromise) + CAPPluginMethod(name: "validateIntegration", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "getCapabilities", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "setSegment", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "setDynamicUserId", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "isPlacementCapped", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "getReward", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "createBanner", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "loadBanner", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "showBanner", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "hideBanner", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "setBannerLayout", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "destroyBanner", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "loadNativeAd", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "showNativeAd", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "setNativeAdRect", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "hideNativeAd", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "destroyNativeAd", returnType: CAPPluginReturnPromise) ] + /// Impressions kept while no JS impressionData listener exists (owner decision Q2); the oldest is dropped. + static let impressionQueueCap = 100 + static let eventImpression = "impressionData" + private enum InitState { case idle, running, done } private var initState = InitState.idle private var pendingInits: [CAPPluginCall] = [] private var rewarded: [String: RewardedHolder] = [:] private var interstitials: [String: InterstitialHolder] = [:] + private var impressionQueue: [[String: Any]] = [] + private var overlayHost: OverlayHost? + /// Attached to every rewarded, interstitial and banner object (per-ad delegates, owner decision Q1). + private(set) lazy var impressionForwarder = ImpressionForwarder(plugin: self) + // Created on first use (not lazy vars: deinit must not create them while self is deallocating). + private var bannerStore: BannerManager? + private var nativeAdStore: NativeAdManager? + + private var banners: BannerManager { + if let m = bannerStore { return m } + let m = BannerManager(impressionDelegate: impressionForwarder) + m.host = self + bannerStore = m + return m + } + + private var nativeAds: NativeAdManager { + if let m = nativeAdStore { return m } + let m = NativeAdManager() + m.host = self + m.onImpression = { [weak self] data in self?.emitImpression(data) } + m.webRoot = { [weak self] in self?.bridge?.config.appLocation } + nativeAdStore = m + return m + } + + deinit { + // Plugin unload: destroy every banner and native ad on the main thread (design §6.6). + let banners = bannerStore + let nativeAds = nativeAdStore + let overlay = overlayHost + let cleanup = { + banners?.destroyAll() + nativeAds?.destroyAll() + overlay?.detach() + } + if Thread.isMainThread { cleanup() } else { DispatchQueue.main.async(execute: cleanup) } + } // MARK: - Init / settings @@ -244,18 +303,266 @@ public class LevelPlayPlugin: CAPPlugin, CAPBridgedPlugin { } static func info(_ adInfo: LPMAdInfo?) -> [String: Any] { - guard let i = adInfo else { return [:] } - var out: [String: Any] = ["adId": i.adId, "adUnitId": i.adUnitId, "adUnitName": i.adUnitName, - "adFormat": i.adFormat, "adNetwork": i.adNetwork, "instanceName": i.instanceName, - "instanceId": i.instanceId, "country": i.country, "auctionId": i.auctionId, - "precision": i.precision, "revenue": i.revenue.doubleValue] - if let placement = i.placementName { out["placementName"] = placement } - return out + return Mappers.adInfo(adInfo) } static func error(_ error: Error) -> [String: Any] { - let e = error as NSError - return ["code": e.code, "message": e.localizedDescription] + return Mappers.error(error) + } + + /// Runs on the main thread; a CallError rejects the call with its code. + private func onMain(_ call: CAPPluginCall, _ task: @escaping () throws -> Void) { + DispatchQueue.main.async { + do { + try task() + } catch let e as CallError { + call.reject(e.message, e.code) + } catch { + call.reject(error.localizedDescription, "ERROR", error) + } + } + } + + // MARK: - 0.3.0: capabilities, user + + @objc func getCapabilities(_ call: CAPPluginCall) { + call.resolve(["banner": true, "nativeAd": true, "nativeAdTemplates": ["small", "medium"], + "impressionData": true, "adInfoChanged": true]) + } + + @objc func setSegment(_ call: CAPPluginCall) { + let o = call.options as? [String: Any] ?? [:] + let segment = LPMSegment() + do { + if let name = o["segmentName"] as? String { segment.segmentName = name } + if Args.present(o, "level") { + let level = try Args.finite(o, "level") + if level != level.rounded() { throw CallError.invalid("level must be an integer") } + segment.level = Int32(clamping: Int(level)) + } + if Args.present(o, "isPaying") { + guard Args.isBool(o["isPaying"]), let paying = o["isPaying"] as? Bool else { + throw CallError.invalid("isPaying must be a boolean") + } + segment.paying = paying + } + if Args.present(o, "userCreationDate") { + let ms = try Args.finite(o, "userCreationDate") + segment.userCreationDate = Date(timeIntervalSince1970: ms / 1000) + } + if Args.present(o, "iapTotal") { segment.iapTotal = try Args.finite(o, "iapTotal") } + if Args.present(o, "customParameters") { + guard let custom = o["customParameters"] as? [String: Any] else { + throw CallError.invalid("customParameters must be an object of strings") + } + let pairs = custom.map { ($0.key, $0.value) }.sorted { $0.0 < $1.0 } + if let err = OverlayMath.customParamsError(pairs) { throw CallError.invalid(err) } + for (k, v) in pairs { segment.setCustomValue(v as? String ?? "", forKey: k) } + } + } catch let e as CallError { + call.reject(e.message, e.code) + return + } catch { + call.reject(error.localizedDescription, "ERROR", error) + return + } + DispatchQueue.main.async { + LevelPlay.setSegment(segment) + call.resolve() + } + } + + @objc func setDynamicUserId(_ call: CAPPluginCall) { + guard let userId = call.getString("userId"), !userId.isEmpty else { + call.reject("userId is required", "INVALID_ARGUMENT") + return + } + DispatchQueue.main.async { + call.resolve(["valid": LevelPlay.setDynamicUserId(userId)]) + } + } + + @objc func isPlacementCapped(_ call: CAPPluginCall) { + let format = call.getString("format") + guard format == "rewarded" || format == "interstitial" else { + call.reject("format must be 'rewarded' or 'interstitial'", "INVALID_ARGUMENT") + return + } + guard let placement = call.getString("placementName"), !placement.isEmpty else { + call.reject("placementName is required", "INVALID_ARGUMENT") + return + } + DispatchQueue.main.async { + let capped = format == "interstitial" + ? LPMInterstitialAd.isPlacementCapped(placement) + : LPMRewardedAd.isPlacementCapped(placement) + call.resolve(["capped": capped]) + } + } + + @objc func getReward(_ call: CAPPluginCall) { + guard let adUnitId = requireAdUnit(call) else { return } + let placement = call.getString("placementName") + DispatchQueue.main.async { + let ad = self.rewardedHolder(adUnitId).ad + let reward = ad.getReward(placementName: placement?.isEmpty == false ? placement : nil) + call.resolve(Mappers.reward(reward)) + } + } + + // MARK: - 0.3.0: banners + + @objc func createBanner(_ call: CAPPluginCall) { + let o = call.options as? [String: Any] ?? [:] + onMain(call) { call.resolve(try self.banners.create(o)) } + } + + @objc func loadBanner(_ call: CAPPluginCall) { + let id = call.getString("bannerId") + onMain(call) { + try self.banners.load(id) + call.resolve() + } + } + + @objc func showBanner(_ call: CAPPluginCall) { + let id = call.getString("bannerId") + onMain(call) { call.resolve(try self.banners.show(id)) } + } + + @objc func hideBanner(_ call: CAPPluginCall) { + let id = call.getString("bannerId") + onMain(call) { + self.banners.hide(id) + call.resolve() + } + } + + @objc func setBannerLayout(_ call: CAPPluginCall) { + let o = call.options as? [String: Any] ?? [:] + onMain(call) { call.resolve(try self.banners.setLayout(o)) } + } + + @objc func destroyBanner(_ call: CAPPluginCall) { + let id = call.getString("bannerId") + onMain(call) { + self.banners.destroy(id) + call.resolve() + } + } + + // MARK: - 0.3.0: native ads + + @objc func loadNativeAd(_ call: CAPPluginCall) { + let o = call.options as? [String: Any] ?? [:] + onMain(call) { + try self.nativeAds.load(o) + call.resolve() + } + } + + @objc func showNativeAd(_ call: CAPPluginCall) { + let id = call.getString("nativeAdId") + let rect = call.getObject("rect") + onMain(call) { + try self.nativeAds.show(id, rect) + call.resolve() + } + } + + @objc func setNativeAdRect(_ call: CAPPluginCall) { + let id = call.getString("nativeAdId") + let rect = call.getObject("rect") + onMain(call) { + try self.nativeAds.setRect(id, rect) + call.resolve() + } + } + + @objc func hideNativeAd(_ call: CAPPluginCall) { + let id = call.getString("nativeAdId") + onMain(call) { + try self.nativeAds.hide(id) + call.resolve() + } + } + + @objc func destroyNativeAd(_ call: CAPPluginCall) { + let id = call.getString("nativeAdId") + onMain(call) { + self.nativeAds.destroy(id) + call.resolve() + } + } + + // MARK: - Overlay + + /// Main thread. The pass-through overlay above the WebView, attached on first use (design §6.2). + func overlay() -> OverlayHost? { + if let host = overlayHost, host.superview != nil { return host } + guard let webView = bridge?.webView else { return nil } + let host = OverlayHost.attach(to: webView) { [weak self] in self?.onOverlayLayoutChanged() } + overlayHost = host + return host + } + + private func onOverlayLayoutChanged() { + guard let overlay = overlayHost else { return } + banners.onLayoutChanged(overlay) + nativeAds.onLayoutChanged(overlay) + } + + // MARK: - Impression data + + /// Main thread. Sends directly when a JS listener exists, otherwise queues (capped, oldest dropped). + func emitImpression(_ data: [String: Any]) { + if hasListeners(Self.eventImpression) { + notifyListeners(Self.eventImpression, data: data) + return + } + impressionQueue.append(data) + if impressionQueue.count > Self.impressionQueueCap { + impressionQueue.removeFirst(impressionQueue.count - Self.impressionQueueCap) + } + } + + private func flushImpressions() { + while !impressionQueue.isEmpty && hasListeners(Self.eventImpression) { + notifyListeners(Self.eventImpression, data: impressionQueue.removeFirst()) + } + } + + /// Same as CAPPlugin.addListener, then flushes impressions queued before the first impressionData listener. + override public func addListener(_ call: CAPPluginCall) { + super.addListener(call) + if call.getString("eventName") == Self.eventImpression { + DispatchQueue.main.async { self.flushImpressions() } + } + } +} + +extension LevelPlayPlugin: AdHost { + func hostViewController() -> UIViewController? { + return bridge?.viewController + } + + var initialized: Bool { + return initState == .done + } +} + +/// The plugin's per-ad impression delegate (set on every rewarded, interstitial and banner object). The SDK holds it +/// weakly; the plugin keeps it alive. +final class ImpressionForwarder: NSObject, LPMImpressionDataDelegate { + private weak var plugin: LevelPlayPlugin? + + init(plugin: LevelPlayPlugin) { + self.plugin = plugin + } + + @objc(impressionDataDidSucceed:) func impressionDataDidSucceed(_ impressionData: LPMImpressionData) { + let data = Mappers.impression(impressionData) + DispatchQueue.main.async { [weak self] in self?.plugin?.emitImpression(data) } } } @@ -278,6 +585,7 @@ final class RewardedHolder: NSObject, LPMRewardedAdDelegate { self.ad = LPMRewardedAd(adUnitId: adUnitId) super.init() ad.setDelegate(self) + ad.setImpressionDataDelegate(plugin.impressionForwarder) } func begin(_ call: CAPPluginCall) { @@ -347,7 +655,7 @@ final class RewardedHolder: NSObject, LPMRewardedAdDelegate { } } - func didChangeAdInfo(_ adInfo: LPMAdInfo) {} + func didChangeAdInfo(_ adInfo: LPMAdInfo) { plugin?.emit("adInfoChanged", base(adInfo)) } } final class InterstitialHolder: NSObject, LPMInterstitialAdDelegate { @@ -364,6 +672,7 @@ final class InterstitialHolder: NSObject, LPMInterstitialAdDelegate { self.ad = LPMInterstitialAd(adUnitId: adUnitId) super.init() ad.setDelegate(self) + ad.setImpressionDataDelegate(plugin.impressionForwarder) } func begin(_ call: CAPPluginCall) { @@ -416,5 +725,5 @@ final class InterstitialHolder: NSObject, LPMInterstitialAdDelegate { finish() } - func didChangeAdInfo(_ adInfo: LPMAdInfo) {} + func didChangeAdInfo(_ adInfo: LPMAdInfo) { plugin?.emit("adInfoChanged", base(adInfo)) } } diff --git a/ios/Sources/LevelPlayPlugin/Mappers.swift b/ios/Sources/LevelPlayPlugin/Mappers.swift new file mode 100644 index 0000000..c300bf1 --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/Mappers.swift @@ -0,0 +1,102 @@ +import Capacitor +import CoreGraphics +import Foundation +import IronSource + +/// SDK objects to the JSON shapes of src/definitions.ts. Nil SDK values are omitted. +enum Mappers { + private static func put(_ o: inout [String: Any], _ key: String, _ value: Any?) { + guard let v = value, !(v is NSNull) else { return } + o[key] = v + } + + static func adInfo(_ info: LPMAdInfo?) -> [String: Any] { + var o: [String: Any] = [:] + guard let i = info else { return o } + put(&o, "adId", i.adId as String?) + put(&o, "adUnitId", i.adUnitId as String?) + put(&o, "adUnitName", i.adUnitName as String?) + put(&o, "adFormat", i.adFormat as String?) + put(&o, "placementName", i.placementName as String?) + put(&o, "adNetwork", i.adNetwork as String?) + put(&o, "instanceName", i.instanceName as String?) + put(&o, "instanceId", i.instanceId as String?) + put(&o, "country", i.country as String?) + put(&o, "auctionId", i.auctionId as String?) + put(&o, "precision", i.precision as String?) + put(&o, "revenue", (i.revenue as NSNumber?)?.doubleValue) + put(&o, "ab", i.ab as String?) + put(&o, "segmentName", i.segmentName as String?) + put(&o, "encryptedCPM", i.encryptedCPM as String?) + put(&o, "creativeId", i.creativeId as String?) + put(&o, "conversionValue", (i.conversionValue as NSNumber?)?.doubleValue) + if let size = i.adSize as LPMAdSize? { o["adSize"] = adSize(size) } + return o + } + + static func adSize(_ s: LPMAdSize) -> [String: Any] { + var o: [String: Any] = ["width": s.width, "height": s.height, "isAdaptive": s.isAdaptive] + put(&o, "description", s.sizeDescription as String?) + return o + } + + static func impression(_ d: LPMImpressionData) -> [String: Any] { + var o: [String: Any] = [:] + put(&o, "adFormat", d.adFormat) + put(&o, "auctionId", d.auctionId) + put(&o, "adUnitId", d.mediationAdUnitId) + put(&o, "adUnitName", d.mediationAdUnitName) + put(&o, "adNetwork", d.adNetwork) + put(&o, "instanceName", d.instanceName) + put(&o, "instanceId", d.instanceId) + put(&o, "country", d.country) + put(&o, "placement", d.placement) + put(&o, "revenue", d.revenue?.doubleValue) + put(&o, "precision", d.precision) + put(&o, "ab", d.ab) + put(&o, "segmentName", d.segmentName) + put(&o, "encryptedCPM", d.encryptedCpm) + put(&o, "creativeId", d.creativeId) + put(&o, "conversionValue", d.conversionValue?.doubleValue) + if let all = d.allData { put(&o, "allData", JSTypes.coerceDictionaryToJSObject(all)) } + return o + } + + /// Native ads use the older `ISAdInfo` (no ad unit, ad id or placement). + static func nativeAdInfo(_ info: ISAdInfo?) -> [String: Any] { + var o: [String: Any] = [:] + guard let i = info else { return o } + put(&o, "auctionId", i.auction_id as String?) + put(&o, "adNetwork", i.ad_network as String?) + put(&o, "instanceName", i.instance_name as String?) + put(&o, "instanceId", i.instance_id as String?) + put(&o, "country", i.country as String?) + put(&o, "revenue", (i.revenue as NSNumber?)?.doubleValue) + put(&o, "precision", i.precision as String?) + put(&o, "ab", i.ab as String?) + put(&o, "segmentName", i.segment_name as String?) + put(&o, "encryptedCPM", i.encrypted_cpm as String?) + put(&o, "conversionValue", (i.conversion_value as NSNumber?)?.doubleValue) + return o + } + + /// impressionData synthesised from a native ad impression (no per-ad impression delegate for native ads in 9.6.1). + static func nativeImpression(_ info: ISAdInfo?) -> [String: Any] { + var o = nativeAdInfo(info) + o["adFormat"] = "nativead" + return o + } + + static func error(_ error: Error) -> [String: Any] { + let e = error as NSError + return ["code": e.code, "message": e.localizedDescription] + } + + static func reward(_ r: LPMReward?) -> [String: Any] { + return ["name": (r?.name as String?) ?? "", "amount": r?.amount ?? 0] + } + + static func rect(_ r: CGRect) -> [String: Any] { + return ["x": Double(r.minX), "y": Double(r.minY), "width": Double(r.width), "height": Double(r.height)] + } +} diff --git a/ios/Sources/LevelPlayPlugin/NativeAdManager.swift b/ios/Sources/LevelPlayPlugin/NativeAdManager.swift new file mode 100644 index 0000000..9853dd6 --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/NativeAdManager.swift @@ -0,0 +1,236 @@ +import IronSource +import UIKit + +/// Native ads (design §4): one `LevelPlayNativeAd` per load and slot, rendered into the plugin's templates and placed +/// in the OverlayHost at a WebView-local CSS rect. Main thread only. +final class NativeAdManager { + weak var host: AdHost? + /// impressionData synthesised from the native ad info (no per-ad impression delegate for native ads). + var onImpression: (([String: Any]) -> Void)? + /// The web assets folder (for template font files). + var webRoot: (() -> URL?)? + private var slots: [String: Slot] = [:] + + final class Slot { + let id: String + let placementName: String? + let template: String + let style: NativeAdStyle + var ad: LevelPlayNativeAd? + var listener: Listener? + var loaded = false + var view: ISNativeAdView? + var rect: CGRect? + var visible = false + + init(id: String, placementName: String?, template: String, style: NativeAdStyle) { + self.id = id + self.placementName = placementName + self.template = template + self.style = style + } + } + + // MARK: - API + + func load(_ o: [String: Any]) throws { + let id = try requireId(Args.string(o, "nativeAdId")) + let template = Args.string(o, "template") ?? "medium" + if template != "small" && template != "medium" { + throw CallError("UNSUPPORTED", "Template '\(template)' is not supported (small, medium)") + } + let style = try NativeAdStyle.parse(Args.object(o, "style")) + let placement = Args.nonEmpty(o, "placementName") + guard let host = host, host.initialized else { + throw CallError("NOT_INITIALIZED", "Call initialize() and wait for it before loadNativeAd()") + } + guard let vc = host.hostViewController() else { + throw CallError("NO_VIEW_CONTROLLER", "No view controller to load the native ad with") + } + + // "Destroy the ad object and create a new one for every new load" (Unity). + if let old = slots.removeValue(forKey: id) { destroySlot(old) } + + let s = Slot(id: id, placementName: placement, template: template, style: style) + let listener = Listener(manager: self, slot: s) + let builder: LevelPlayNativeAdBuilder = LevelPlayNativeAdBuilder().withViewController(vc).withDelegate(listener) + if let placement = placement { _ = builder.withPlacementName(placement) } + guard let ad = builder.build() as LevelPlayNativeAd? else { + throw CallError("ERROR", "The SDK could not create the native ad") + } + s.ad = ad + s.listener = listener + slots[id] = s + ad.load() + } + + func show(_ id: String?, _ rect: [String: Any]?) throws { + let s = try require(id) + let r = try parseRect(rect) + guard s.loaded, let ad = s.ad else { throw CallError("NOT_LOADED", "Native ad '\(s.id)' is not loaded") } + guard let overlay = host?.overlay(), host?.hostViewController() != nil else { + throw CallError("NO_VIEW_CONTROLLER", "No view controller / WebView to show the native ad in") + } + if s.view == nil { + let view = NativeAdTemplate.build(s.template, s.style, ad, webRoot: webRoot?()) + view.isHidden = true + overlay.add(view) + s.view = view + } + s.rect = r + s.visible = true + place(s, overlay) + s.view?.isHidden = false + if let view = s.view { overlay.bringSubviewToFront(view) } + logFrame(s) + } + + func setRect(_ id: String?, _ rect: [String: Any]?) throws { + let s = try require(id) + s.rect = try parseRect(rect) + if let overlay = host?.overlay(), s.view != nil { + place(s, overlay) + logFrame(s) + } + } + + func hide(_ id: String?) throws { + let s = try require(id) + s.visible = false + s.view?.isHidden = true + } + + func destroy(_ id: String?) { + guard let id = id, let s = slots.removeValue(forKey: id) else { return } + destroySlot(s) + } + + func destroyAll() { + for s in slots.values { destroySlot(s) } + slots.removeAll() + } + + func onLayoutChanged(_ overlay: OverlayHost) { + for s in slots.values where s.view != nil && s.rect != nil { place(s, overlay) } + } + + // MARK: - Internals + + private func requireId(_ id: String?) throws -> String { + guard let id = id, !id.isEmpty else { throw CallError.invalid("nativeAdId is required") } + return id + } + + private func require(_ id: String?) throws -> Slot { + let key = try requireId(id) + guard let s = slots[key] else { throw CallError.notFound("Native ad", key) } + return s + } + + private func parseRect(_ r: [String: Any]?) throws -> CGRect { + guard let r = r else { throw CallError.invalid("rect { x, y, width, height } is required") } + var out: [CGFloat] = [] + for key in ["x", "y", "width", "height"] { + guard let d = Args.number(r[key]) else { throw CallError.invalid("rect.\(key) must be a number") } + if !d.isFinite { throw CallError.invalid("rect.\(key) must be finite") } + out.append(CGFloat(d)) + } + if out[2] < 0 || out[3] < 0 { throw CallError.invalid("rect width and height must be >= 0") } + return CGRect(x: out[0], y: out[1], width: out[2], height: out[3]) + } + + /// Native rects are taken literally (the page laid them out), only clamped to the WebView (design §6.3). + private func place(_ s: Slot, _ overlay: OverlayHost) { + guard let view = s.view, let rect = s.rect else { return } + overlay.place(view, OverlayMath.intersect(rect, overlay.webViewCss)) + } + + private func logFrame(_ s: Slot) { + guard let view = s.view else { return } + view.layoutIfNeeded() + levelPlayLog.notice("nativeAd \(s.id, privacy: .public) \(s.template, privacy: .public) frame \(BannerManager.describe(view.frame), privacy: .public) visible \(s.visible, privacy: .public)") + } + + private func destroySlot(_ s: Slot) { + s.view?.removeFromSuperview() + s.view = nil + s.ad?.destroy() + s.ad = nil + s.listener = nil + s.loaded = false + } + + private func event(_ s: Slot, _ info: ISAdInfo?) -> [String: Any] { + var o: [String: Any] = ["nativeAdId": s.id] + if let p = s.placementName { o["placementName"] = p } + if let info = info { o["adInfo"] = Mappers.nativeAdInfo(info) } + return o + } + + fileprivate func current(_ slot: Slot, _ ad: LevelPlayNativeAd) -> Bool { + return slots[slot.id] === slot && slot.ad === ad + } + + fileprivate func didLoad(_ slot: Slot, _ ad: LevelPlayNativeAd, _ info: ISAdInfo?) { + guard current(slot, ad) else { return } + slot.loaded = true + host?.emit("nativeAdLoaded", event(slot, info)) + } + + fileprivate func didFail(_ slot: Slot, _ ad: LevelPlayNativeAd, _ error: Error) { + guard current(slot, ad) else { return } + // The failed ad object is destroyed; the slot stays (NOT_LOADED) until the next loadNativeAd(). + slot.ad?.destroy() + slot.ad = nil + slot.loaded = false + var o = event(slot, nil) + o["error"] = Mappers.error(error) + host?.emit("nativeAdLoadFailed", o) + } + + fileprivate func didImpression(_ slot: Slot, _ ad: LevelPlayNativeAd, _ info: ISAdInfo?) { + guard current(slot, ad) else { return } + host?.emit("nativeAdImpression", event(slot, info)) + onImpression?(Mappers.nativeImpression(info)) + } + + fileprivate func didClick(_ slot: Slot, _ ad: LevelPlayNativeAd, _ info: ISAdInfo?) { + guard current(slot, ad) else { return } + host?.emit("nativeAdClicked", event(slot, info)) + } + + /// One delegate per load (the builder holds it weakly; the slot keeps it alive). Callbacks of an ad object that + /// was replaced or destroyed are dropped. + final class Listener: NSObject, LevelPlayNativeAdDelegate { + private weak var manager: NativeAdManager? + private weak var slot: Slot? + + init(manager: NativeAdManager, slot: Slot) { + self.manager = manager + self.slot = slot + } + + private func post(_ block: @escaping (NativeAdManager, Slot) -> Void) { + DispatchQueue.main.async { [weak self] in + guard let m = self?.manager, let s = self?.slot else { return } + block(m, s) + } + } + + @objc(didLoad:withAdInfo:) func didLoad(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) { + post { $0.didLoad($1, nativeAd, adInfo) } + } + + @objc(didFailToLoad:withError:) func didFail(toLoad nativeAd: LevelPlayNativeAd, withError error: Error) { + post { $0.didFail($1, nativeAd, error) } + } + + @objc(didRecordImpression:withAdInfo:) func didRecordImpression(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) { + post { $0.didImpression($1, nativeAd, adInfo) } + } + + @objc(didClick:withAdInfo:) func didClick(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) { + post { $0.didClick($1, nativeAd, adInfo) } + } + } +} diff --git a/ios/Sources/LevelPlayPlugin/NativeAdStyle.swift b/ios/Sources/LevelPlayPlugin/NativeAdStyle.swift new file mode 100644 index 0000000..977ea26 --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/NativeAdStyle.swift @@ -0,0 +1,65 @@ +import UIKit + +/// Parsed NativeAdTemplateStyle (src/definitions.ts). Sizes are CSS px (pt). Same defaults and validation as Android. +struct NativeAdStyle { + struct Font { + var family: String? + var size: CGFloat? + } + + var backgroundColor = UIColor(white: 1, alpha: 1) + var titleColor = NativeAdStyle.rgb(0x202124) + var bodyColor = NativeAdStyle.rgb(0x5F6368) + var callToActionBackgroundColor = NativeAdStyle.rgb(0x1A73E8) + var callToActionTextColor = UIColor(white: 1, alpha: 1) + var cornerRadius: CGFloat = 0 + var titleFont = Font() + var bodyFont = Font() + var callToActionFont = Font() + + static func rgb(_ v: UInt32) -> UIColor { + return UIColor(red: CGFloat((v >> 16) & 0xFF) / 255, green: CGFloat((v >> 8) & 0xFF) / 255, + blue: CGFloat(v & 0xFF) / 255, alpha: 1) + } + + static func parse(_ o: [String: Any]?) throws -> NativeAdStyle { + var s = NativeAdStyle() + guard let o = o else { return s } + s.backgroundColor = try color(o, "backgroundColor", s.backgroundColor) + s.titleColor = try color(o, "titleColor", s.titleColor) + s.bodyColor = try color(o, "bodyColor", s.bodyColor) + s.callToActionBackgroundColor = try color(o, "callToActionBackgroundColor", s.callToActionBackgroundColor) + s.callToActionTextColor = try color(o, "callToActionTextColor", s.callToActionTextColor) + if Args.present(o, "cornerRadius") { + guard let r = Args.number(o["cornerRadius"]), r >= 0 else { throw CallError.invalid("style.cornerRadius must be >= 0") } + s.cornerRadius = CGFloat(r) + } + s.titleFont = try font(o, "titleFont") + s.bodyFont = try font(o, "bodyFont") + s.callToActionFont = try font(o, "callToActionFont") + return s + } + + private static func color(_ o: [String: Any], _ key: String, _ fallback: UIColor) throws -> UIColor { + if !Args.present(o, key) { return fallback } + guard let c = OverlayMath.parseColor(o[key] as? String) else { + throw CallError.invalid("style.\(key) must be #RRGGBB or #RRGGBBAA") + } + return UIColor(red: c.r, green: c.g, blue: c.b, alpha: c.a) + } + + private static func font(_ o: [String: Any], _ key: String) throws -> Font { + if !Args.present(o, key) { return Font() } + guard let f = o[key] as? [String: Any] else { throw CallError.invalid("style.\(key) must be an object { family?, size? }") } + var family = f["family"] as? String + if let fam = family, fam.trimmingCharacters(in: .whitespaces).isEmpty { family = nil } + var size: CGFloat? + if Args.present(f, "size") { + guard let v = Args.number(f["size"]), v > 0, v.isFinite else { + throw CallError.invalid("style.\(key).size must be a positive number") + } + size = CGFloat(v) + } + return Font(family: family, size: size) + } +} diff --git a/ios/Sources/LevelPlayPlugin/NativeAdTemplate.swift b/ios/Sources/LevelPlayPlugin/NativeAdTemplate.swift new file mode 100644 index 0000000..274d410 --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/NativeAdTemplate.swift @@ -0,0 +1,309 @@ +import CoreText +import IronSource +import UIKit + +/// The plugin's own native ad templates (the SDK ships none, design §4.1), built in code so every style value +/// applies directly. Both draw an "Ad" badge and keep the bottom-left corner free for the network's privacy / +/// AdChoices icon. Same structure as the Android templates: +/// +/// - small: [icon] [title / Ad + advertiser / body] [CTA], one row; fits rows from about 90 pt tall. +/// - medium: [icon] [title / Ad + advertiser], body, media view (fills the rest), CTA aligned right. +/// +/// Texts: `levelplay_native_ad_badge` ("Ad") and `levelplay_native_ad_cta_fallback` ("Open"), overridable in the +/// app's `Localizable.strings` (the same keys as the Android string resources). +enum NativeAdTemplate { + private static let badgeBackground = NativeAdStyle.rgb(0xFFC107) + private static let badgeText = NativeAdStyle.rgb(0x202124) + private static var assetFonts: [String: String] = [:] + + /// The template's asset views, created and styled but not filled. + struct Views { + let root: ISNativeAdView + let title: UILabel + let advertiser: UILabel + let body: UILabel + let icon: UIImageView + let cta: UIButton + let media: LevelPlayMediaView? + } + + static var badgeTitle: String { + return Bundle.main.localizedString(forKey: "levelplay_native_ad_badge", value: "Ad", table: nil) + } + + static var ctaFallback: String { + return Bundle.main.localizedString(forKey: "levelplay_native_ad_cta_fallback", value: "Open", table: nil) + } + + /// Renders a loaded ad: create, fill from the ad's assets, hand the views to the SDK and register them. + static func build(_ template: String, _ style: NativeAdStyle, _ ad: LevelPlayNativeAd, webRoot: URL?) -> ISNativeAdView { + let v = create(template, style, webRoot: webRoot) + fill(v, title: ad.title, advertiser: ad.advertiser, body: ad.body, callToAction: ad.callToAction, icon: ad.icon) + v.root.adTitleView = v.title + v.root.adAdvertiserView = v.advertiser + v.root.adBodyView = v.body + v.root.adAppIcon = v.icon + v.root.adCallToActionView = v.cta + if let media = v.media { v.root.adMediaView = media } + v.root.registerNativeAdViews(ad) + return v.root + } + + static func create(_ template: String, _ style: NativeAdStyle, webRoot: URL?) -> Views { + let medium = template == "medium" + let root = ISNativeAdView(frame: .zero) + root.accessibilityIdentifier = "LevelPlayNativeAd.\(template)" + root.backgroundColor = style.backgroundColor + root.layer.cornerRadius = style.cornerRadius + root.clipsToBounds = true + // The template consumes touches inside its bounds (UIView's default hitTest returns the root for points + // between asset views), so taps there do not reach the game. + + let icon = UIImageView() + icon.contentMode = .scaleAspectFill + icon.backgroundColor = UIColor(white: 0, alpha: 0x14 / 255.0) + icon.layer.cornerRadius = 6 + icon.clipsToBounds = true + + let title = label(style.titleColor, font(style.titleFont, 15, bold: true, webRoot: webRoot)) + title.numberOfLines = medium ? 2 : 1 + + let badge = BadgeLabel() + badge.text = badgeTitle + badge.textColor = badgeText + badge.font = font(NativeAdStyle.Font(family: style.bodyFont.family, size: 10), 10, bold: true, webRoot: webRoot) + badge.backgroundColor = badgeBackground + badge.layer.cornerRadius = 3 + badge.clipsToBounds = true + badge.setContentHuggingPriority(.defaultHigh, for: .horizontal) + badge.setContentCompressionResistancePriority(.required, for: .horizontal) + + let advertiser = label(style.bodyColor, font(style.bodyFont, 12, bold: false, webRoot: webRoot)) + advertiser.numberOfLines = 1 + + let body = label(style.bodyColor, font(style.bodyFont, 12, bold: false, webRoot: webRoot)) + body.numberOfLines = 2 + + let cta = PaddedButton(type: .custom) + cta.titleLabel?.font = font(style.callToActionFont, 13, bold: true, webRoot: webRoot) + cta.titleLabel?.lineBreakMode = .byTruncatingTail + cta.setTitleColor(style.callToActionTextColor, for: .normal) + cta.backgroundColor = style.callToActionBackgroundColor + cta.layer.cornerRadius = 6 + cta.clipsToBounds = true + cta.translatesAutoresizingMaskIntoConstraints = false + cta.heightAnchor.constraint(equalToConstant: 36).isActive = true + cta.setContentHuggingPriority(.required, for: .horizontal) + cta.setContentCompressionResistancePriority(.required, for: .horizontal) + + // Labels give way to the icon, the badge and the CTA when space is short (they truncate instead). + for l in [title, advertiser, body] { + l.setContentHuggingPriority(.defaultLow, for: .horizontal) + l.setContentCompressionResistancePriority(.defaultLow - 1, for: .horizontal) + } + + // Badge + advertiser row; the trailing filler keeps the badge at its own width when there is no advertiser. + let filler = UIView() + filler.setContentHuggingPriority(UILayoutPriority(1), for: .horizontal) + filler.setContentCompressionResistancePriority(UILayoutPriority(1), for: .horizontal) + let adRow = UIStackView(arrangedSubviews: [badge, advertiser, filler]) + adRow.axis = .horizontal + adRow.alignment = .center + adRow.spacing = 6 + + icon.translatesAutoresizingMaskIntoConstraints = false + var media: LevelPlayMediaView? + let pad: CGFloat = medium ? 10 : 8 + let content: UIStackView + if medium { + NSLayoutConstraint.activate([icon.widthAnchor.constraint(equalToConstant: 40), + icon.heightAnchor.constraint(equalToConstant: 40)]) + let texts = UIStackView(arrangedSubviews: [title, adRow]) + texts.axis = .vertical + texts.alignment = .fill + let header = UIStackView(arrangedSubviews: [icon, texts]) + header.axis = .horizontal + header.alignment = .center + header.spacing = 8 + + let m = LevelPlayMediaView(frame: .zero) + m.setContentHuggingPriority(.defaultLow - 1, for: .vertical) + m.setContentCompressionResistancePriority(.defaultLow - 1, for: .vertical) + media = m + + // CTA on the right: the bottom-left corner stays free for the AdChoices icon. + let spacer = UIView() + spacer.setContentHuggingPriority(.defaultLow - 1, for: .horizontal) + let ctaRow = UIStackView(arrangedSubviews: [spacer, cta]) + ctaRow.axis = .horizontal + + content = UIStackView(arrangedSubviews: [header, body, m, ctaRow]) + content.axis = .vertical + content.alignment = .fill + content.spacing = 8 + content.setCustomSpacing(6, after: header) + for v in [header, body, ctaRow] as [UIView] { + v.setContentHuggingPriority(.required, for: .vertical) + v.setContentCompressionResistancePriority(.required, for: .vertical) + } + } else { + NSLayoutConstraint.activate([icon.widthAnchor.constraint(equalToConstant: 48), + icon.heightAnchor.constraint(equalToConstant: 48)]) + let texts = UIStackView(arrangedSubviews: [title, adRow, body]) + texts.axis = .vertical + texts.alignment = .fill + content = UIStackView(arrangedSubviews: [icon, texts, cta]) + content.axis = .horizontal + content.alignment = .center + content.spacing = 8 + } + content.translatesAutoresizingMaskIntoConstraints = false + root.addSubview(content) + let bottom = content.bottomAnchor.constraint(lessThanOrEqualTo: root.bottomAnchor, constant: -pad) + var constraints = [ + content.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: pad), + content.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -pad), + content.topAnchor.constraint(greaterThanOrEqualTo: root.topAnchor, constant: pad), + bottom + ] + if medium { + // Fill the height; the media view takes what the texts and the CTA leave. + let fill = content.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -pad) + fill.priority = .defaultHigh + constraints += [content.topAnchor.constraint(equalTo: root.topAnchor, constant: pad).withPriority(.defaultHigh), fill] + } else { + constraints.append(content.centerYAnchor.constraint(equalTo: root.centerYAnchor)) + } + NSLayoutConstraint.activate(constraints) + + return Views(root: root, title: title, advertiser: advertiser, body: body, icon: icon, cta: cta, media: media) + } + + static func fill(_ v: Views, title: String?, advertiser: String?, body: String?, callToAction: String?, + icon: ISNativeAdDataImage?) { + setOrHide(v.title, title) + setOrHide(v.advertiser, advertiser) + setOrHide(v.body, body) + let cta = (callToAction?.isEmpty == false) ? callToAction! : ctaFallback + v.cta.setTitle(cta, for: .normal) + bindIcon(v.icon, icon) + } + + private static func label(_ color: UIColor, _ font: UIFont) -> UILabel { + let l = UILabel() + l.textColor = color + l.font = font + l.lineBreakMode = .byTruncatingTail + l.adjustsFontForContentSizeCategory = false + return l + } + + /// System family name, or a .ttf / .otf file in the web assets (Capacitor copies the web dir to `public` in the + /// app bundle). Sizes are pt (= CSS px), not scaled by Dynamic Type, like WebView text. + static func font(_ f: NativeAdStyle.Font, _ defaultSize: CGFloat, bold: Bool, webRoot: URL?) -> UIFont { + let size = f.size ?? defaultSize + let system = UIFont.systemFont(ofSize: size, weight: bold ? .bold : .regular) + guard let family = f.family else { return system } + let lower = family.lowercased() + if lower.hasSuffix(".ttf") || lower.hasSuffix(".otf") { + guard let name = assetFontName(family, webRoot: webRoot), let font = UIFont(name: name, size: size) else { + return system + } + return font + } + if let named = UIFont(name: family, size: size) { return named } + if UIFont.familyNames.contains(family) { + var desc = UIFontDescriptor(fontAttributes: [.family: family]) + if bold, let b = desc.withSymbolicTraits(.traitBold) { desc = b } + return UIFont(descriptor: desc, size: size) + } + levelPlayLog.warning("Native ad font family not found: \(family, privacy: .public); using the system font") + return system + } + + /// Registers the font file once per process (CTFontManager) and returns its PostScript name. + private static func assetFontName(_ family: String, webRoot: URL?) -> String? { + var path = family + while path.hasPrefix("/") { path.removeFirst() } + if path.hasPrefix("./") { path.removeFirst(2) } + if let cached = assetFonts[path] { return cached } + let root = webRoot ?? Bundle.main.bundleURL.appendingPathComponent("public") + let url = root.appendingPathComponent(path) + guard FileManager.default.fileExists(atPath: url.path), + let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor], + let first = descriptors.first, + let name = CTFontDescriptorCopyAttribute(first, kCTFontNameAttribute) as? String else { + levelPlayLog.warning("Native ad font not found in the web assets: \(path, privacy: .public); using the system font") + return nil + } + var error: Unmanaged? + if !CTFontManagerRegisterFontsForURL(url as CFURL, .process, &error) { + // kCTFontManagerErrorAlreadyRegistered (105) is fine; anything else falls back below if UIFont fails. + _ = error?.takeRetainedValue() + } + assetFonts[path] = name + return name + } + + private static func setOrHide(_ v: UILabel, _ text: String?) { + if let t = text, !t.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + v.text = t + v.isHidden = false + } else { + v.text = "" + v.isHidden = true + } + } + + private static func bindIcon(_ view: UIImageView, _ image: ISNativeAdDataImage?) { + guard let image = image else { + view.isHidden = true + return + } + if let img = image.image { + view.image = img + return + } + guard let url = image.url, let scheme = url.scheme, scheme.hasPrefix("http") else { + view.isHidden = true + return + } + // Some adapters only give a URL: fetch it off the main thread. + URLSession.shared.dataTask(with: url) { [weak view] data, _, _ in + let img = data.flatMap { UIImage(data: $0) } + DispatchQueue.main.async { + guard let view = view else { return } + if let img = img { view.image = img } else { view.isHidden = true } + } + }.resume() + } +} + +/// "Ad" badge: a label with 4 pt horizontal padding. +final class BadgeLabel: UILabel { + private let inset = UIEdgeInsets(top: 1, left: 4, bottom: 1, right: 4) + + override func drawText(in rect: CGRect) { + super.drawText(in: rect.inset(by: inset)) + } + + override var intrinsicContentSize: CGSize { + let s = super.intrinsicContentSize + return CGSize(width: s.width + inset.left + inset.right, height: s.height + inset.top + inset.bottom) + } +} + +/// CTA button with 12 pt horizontal padding (without the iOS 15 deprecated `contentEdgeInsets`). +final class PaddedButton: UIButton { + override var intrinsicContentSize: CGSize { + let s = super.intrinsicContentSize + return CGSize(width: s.width + 24, height: s.height) + } +} + +private extension NSLayoutConstraint { + func withPriority(_ p: UILayoutPriority) -> NSLayoutConstraint { + priority = p + return self + } +} diff --git a/ios/Sources/LevelPlayPlugin/OverlayHost.swift b/ios/Sources/LevelPlayPlugin/OverlayHost.swift new file mode 100644 index 0000000..be24469 --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/OverlayHost.swift @@ -0,0 +1,72 @@ +import UIKit +import os + +let levelPlayLog = Logger(subsystem: "fyi.crt.capacitor.levelplay", category: "LevelPlay") + +/// The plugin's pass-through overlay for banners and native ads (design §6.2). In Capacitor the bridge view +/// controller's root view is the WKWebView itself (`CAPBridgeViewController.loadView` sets `view = webView`), so the +/// overlay is added to that view, above the WebView's scroll view, filling its bounds. It therefore follows the +/// WebView's frame, safe area and modal presentations without observing anything. Its coordinate space is the +/// WebView viewport in CSS px (1 CSS px = 1 pt). +/// +/// `hitTest` returns nil for points that land on the overlay itself, so touches outside ad views reach the page. +final class OverlayHost: UIView { + /// Called on the main thread after the overlay's bounds or safe area changed (and on explicit relayouts). + var onLayoutChanged: (() -> Void)? + private var lastBounds = CGRect.null + private var lastInsets = UIEdgeInsets(top: -1, left: -1, bottom: -1, right: -1) + + static func attach(to webView: UIView, onLayoutChanged: @escaping () -> Void) -> OverlayHost { + let host = OverlayHost(frame: webView.bounds) + host.autoresizingMask = [.flexibleWidth, .flexibleHeight] + host.backgroundColor = .clear + host.isOpaque = false + host.clipsToBounds = false + host.accessibilityIdentifier = "LevelPlayOverlay" + host.onLayoutChanged = onLayoutChanged + webView.addSubview(host) + webView.bringSubviewToFront(host) + return host + } + + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + let hit = super.hitTest(point, with: event) + return hit === self ? nil : hit + } + + override func layoutSubviews() { + super.layoutSubviews() + if bounds != lastBounds || safeAreaInsets != lastInsets { + lastBounds = bounds + lastInsets = safeAreaInsets + onLayoutChanged?() + } + } + + override func safeAreaInsetsDidChange() { + super.safeAreaInsetsDidChange() + setNeedsLayout() + } + + /// The WebView viewport in CSS px. + var webViewCss: CGRect { return bounds } + + /// The viewport minus the system insets (status bar, notch, home indicator) in CSS px (design §6.3). + var safeAreaCss: CGRect { + return OverlayMath.intersect(bounds.inset(by: safeAreaInsets), bounds) + } + + func add(_ view: UIView) { + addSubview(view) + superview?.bringSubviewToFront(self) + } + + func place(_ view: UIView, _ frame: CGRect) { + if view.frame != frame { view.frame = frame } + } + + func detach() { + onLayoutChanged = nil + removeFromSuperview() + } +} diff --git a/ios/Sources/LevelPlayPlugin/OverlayMath.swift b/ios/Sources/LevelPlayPlugin/OverlayMath.swift new file mode 100644 index 0000000..5ec995c --- /dev/null +++ b/ios/Sources/LevelPlayPlugin/OverlayMath.swift @@ -0,0 +1,70 @@ +import CoreGraphics +import Foundation + +/// Pure helpers (no UIKit views, no SDK types) for overlay geometry and argument validation. Same rules as the +/// Android `OverlayMath`. +enum OverlayMath { + /// LPMSegment custom-parameter limits (read from the Android 9.6.1 bytecode, applied on both platforms). + static let maxCustomParams = 5 + static let maxCustomLength = 32 + + /// Intersection of two rects; an empty intersection has zero width / height at the clamped origin. + static func intersect(_ a: CGRect, _ b: CGRect) -> CGRect { + let l = max(a.minX, b.minX) + let t = max(a.minY, b.minY) + let r = min(a.maxX, b.maxX) + let btm = min(a.maxY, b.maxY) + return CGRect(x: l, y: t, width: max(0, r - l), height: max(0, btm - t)) + } + + /// Banner frame inside `area` (design §6.4): centred horizontally, anchored top / bottom / center. + static func bannerFrame(_ area: CGRect, width: CGFloat, height: CGFloat, position: String, + offsetX: CGFloat, offsetY: CGFloat) -> CGRect { + let x = area.minX + (area.width - width) / 2 + offsetX + let y: CGFloat + switch position { + case "top": y = area.minY + offsetY + case "center": y = area.minY + (area.height - height) / 2 + offsetY + default: y = area.minY + area.height - height + offsetY + } + return CGRect(x: x, y: y, width: width, height: height) + } + + static func isPosition(_ p: String) -> Bool { + return p == "top" || p == "bottom" || p == "center" + } + + static func isBannerSize(_ s: String) -> Bool { + return ["BANNER", "LARGE", "MEDIUM_RECTANGLE", "LEADERBOARD", "ADAPTIVE", "CUSTOM"].contains(s) + } + + /// Error message for segment custom parameters that break the SDK limits, or nil when they are fine. + static func customParamsError(_ params: [(String, Any)]) -> String? { + if params.count > maxCustomParams { + return "customParameters: at most \(maxCustomParams) pairs (got \(params.count))" + } + for (k, v) in params { + if !validToken(k) { return "customParameters: key '\(k)' must be 1-32 letters or digits" } + guard let s = v as? String else { return "customParameters: value of '\(k)' must be a string" } + if !validToken(s) { return "customParameters: value of '\(k)' must be 1-32 letters or digits" } + } + return nil + } + + private static func validToken(_ s: String) -> Bool { + guard !s.isEmpty, s.count <= maxCustomLength else { return false } + return s.unicodeScalars.allSatisfy { ($0 >= "a" && $0 <= "z") || ($0 >= "A" && $0 <= "Z") || ($0 >= "0" && $0 <= "9") } + } + + /// CSS `#RRGGBB` / `#RRGGBBAA` to RGBA components in 0...1, or nil when malformed. + static func parseColor(_ css: String?) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? { + guard let css = css, css.hasPrefix("#"), css.count == 7 || css.count == 9 else { return nil } + let hex = String(css.dropFirst()) + guard hex.allSatisfy({ $0.isHexDigit }), let v = UInt64(hex, radix: 16) else { return nil } + if hex.count == 6 { + return (CGFloat((v >> 16) & 0xFF) / 255, CGFloat((v >> 8) & 0xFF) / 255, CGFloat(v & 0xFF) / 255, 1) + } + return (CGFloat((v >> 24) & 0xFF) / 255, CGFloat((v >> 16) & 0xFF) / 255, CGFloat((v >> 8) & 0xFF) / 255, + CGFloat(v & 0xFF) / 255) + } +} diff --git a/package.json b/package.json index c6a275d..4fdee27 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "capacitor-levelplay", - "version": "0.1.0", - "description": "Capacitor 8 plugin for Unity LevelPlay (ironSource) rewarded and interstitial ads. Swift Package Manager first, ad-unit API.", + "version": "0.3.0", + "description": "Capacitor 7 and 8 plugin for Unity LevelPlay (ironSource) ads on Android and iOS: rewarded, interstitial, banner and native ads, impression-level revenue, segments, ad-unit API, Swift Package Manager first, ATT and GDPR / CCPA / COPPA consent.", "main": "dist/plugin.cjs.js", "module": "dist/esm/index.js", "types": "dist/esm/index.d.ts", @@ -11,41 +11,70 @@ "android/build.gradle", "android/proguard-rules.pro", "dist/", - "ios/Sources", + "ios/Sources/", "Package.swift", - "CapacitorLevelplay.podspec" + "CapacitorLevelplay.podspec", + "CHANGELOG.md" ], - "author": "VOX Games", + "author": "CRTkafa", "license": "MIT", + "homepage": "https://git.crt.fyi/CRT/capacitor-levelplay#readme", + "bugs": { + "url": "https://git.crt.fyi/CRT/capacitor-levelplay/issues" + }, "repository": { "type": "git", - "url": "https://git.crt.fyi/CRT/capacitor-levelplay.git" + "url": "https://git.crt.fyi/CRT/capacitor-levelplay" }, "keywords": [ "capacitor", + "capacitor-plugin", + "capacitor7", + "capacitor8", "plugin", "native", "levelplay", + "unity-levelplay", "ironsource", "unity", + "unity-ads", "ads", + "mediation", "rewarded", - "interstitial" + "rewarded-video", + "interstitial", + "banner", + "native-ads", + "impression-data", + "ilrd", + "ios", + "android", + "swift-package-manager" ], + "engines": { + "node": ">=22" + }, "scripts": { - "build": "rm -rf dist && tsc && rollup -c rollup.config.mjs", + "build": "bun run clean && bun run docgen && tsc && rollup -c rollup.config.mjs", + "clean": "rm -rf dist", + "docgen": "docgen --api LevelPlayPlugin --output-readme README.md --output-json dist/docs.json", "typecheck": "tsc --noEmit", + "test": "bun test ./test && tsc -p test", + "verify": "bun run typecheck && bun run test && bun run build && bun run verify:ios && bun run verify:android", "verify:ios": "xcodebuild build -scheme CapacitorLevelplay -destination 'generic/platform=iOS Simulator'", + "verify:android": "cd android && ./gradlew clean build test && cd ..", "verify:web": "bun run build", "prepublishOnly": "bun run build" }, "devDependencies": { + "@capacitor/android": "^8.0.0", "@capacitor/core": "^8.0.0", + "@capacitor/docgen": "^0.3.1", "rollup": "^4.53.3", "typescript": "^5.9.3" }, "peerDependencies": { - "@capacitor/core": ">=8.0.0" + "@capacitor/core": ">=7.0.0" }, "capacitor": { "ios": { diff --git a/src/definitions.ts b/src/definitions.ts index 8a9063b..b978196 100644 --- a/src/definitions.ts +++ b/src/definitions.ts @@ -1,189 +1,1762 @@ import type { PluginListenerHandle } from '@capacitor/core'; -/** Full-screen ad formats supported by this plugin. Banners and native ads are intentionally not exposed. */ +/** + * Full-screen ad formats (`loadRewarded` / `loadInterstitial` family and the `loaded` ... `rewarded` events). + * Banners and native ads have their own methods and `banner*` / `nativeAd*` events (since 0.3.0), so this union + * stays unchanged for 0.2.x code. + * + * @since 0.1.0 + */ export type AdFormat = 'rewarded' | 'interstitial'; +/** + * Options for `initialize()`. + * + * @since 0.1.0 + */ export interface InitOptions { - /** LevelPlay app key from the LevelPlay dashboard (one per platform). */ + /** + * LevelPlay app key from the LevelPlay dashboard. Android and iOS apps have different keys. + * + * @since 0.1.0 + */ appKey: string; - /** Optional user id, needed for server-to-server reward callbacks and the Ad Quality user journey. */ + /** + * Optional user id. Needed for server-to-server reward callbacks and the Ad Quality user journey. + * + * @since 0.1.0 + */ userId?: string; /** - * Enable the LevelPlay Integration Test Suite (sets the `is_test_suite=enable` meta data before init). - * Call {@link LevelPlayPlugin.launchTestSuite} after init resolves. Never ship this enabled. + * Enable the LevelPlay Integration Test Suite: sets the `is_test_suite=enable` meta data before init. + * Call `launchTestSuite()` after `initialize` resolves. Never ship this enabled. + * + * @default false + * @since 0.1.0 */ testSuite?: boolean; - /** Turn on mediated ad network debug logs (`setAdaptersDebug`). Development only. */ + /** + * Turn on debug logs of the mediated ad network adapters (`LevelPlay.setAdaptersDebug(true)`). Development only. + * + * @default false + * @since 0.1.0 + */ adaptersDebug?: boolean; /** - * Privacy flags applied right before init (LevelPlay recommends setting them before the SDK starts). - * Same as calling {@link LevelPlayPlugin.setConsent} first. + * Privacy signals applied right before init (LevelPlay recommends setting them before the SDK starts). + * Same as calling `setConsent()` first. + * + * @since 0.1.0 */ consent?: ConsentOptions; } +/** + * Result of `initialize()` and `getSdkVersion()`. + * + * @since 0.1.0 + */ export interface InitResult { - /** Native LevelPlay SDK version, for example `9.6.1`. */ + /** + * Native LevelPlay SDK version, for example `9.6.1`. `web` on the web. + * + * @since 0.1.0 + */ sdkVersion: string; } /** * Privacy signals forwarded to LevelPlay (`LevelPlayPrivacySettings` on Android, `LPMPrivacySettings` on iOS). * Omitted fields are left untouched. + * + * @since 0.1.0 */ export interface ConsentOptions { - /** GDPR: `true` when the user consented to personalised ads / data processing. */ + /** + * GDPR: `true` when the user consented to personalised ads and data processing, `false` when they did not. + * For users in the EEA, UK and Switzerland pass `false` until a consent management platform (CMP) says otherwise. + * + * @since 0.1.0 + */ gdprConsent?: boolean; - /** CCPA / US state privacy: `true` when the user opted OUT of the sale or sharing of personal data. */ + /** + * CCPA and other US state privacy laws: `true` when the user opted OUT of the sale or sharing of personal data + * ("do not sell"), `false` otherwise. + * + * @since 0.1.0 + */ ccpaDoNotSell?: boolean; - /** COPPA: `true` when the user must be treated as a child (child-directed treatment). */ + /** + * COPPA: `true` when the user must be treated as a child (child-directed treatment). + * + * @since 0.1.0 + */ coppa?: boolean; } +/** + * Options for `setMetaData()`. + * + * @since 0.1.0 + */ export interface MetaDataOptions { + /** + * Meta data key, for example `is_deviceid_optout` or a network-specific flag from Unity's docs. + * + * @since 0.1.0 + */ key: string; + /** + * Meta data value, always a string (for example `"true"`). + * + * @since 0.1.0 + */ value: string; } +/** + * Identifies one ad unit. + * + * @since 0.1.0 + */ export interface AdUnitOptions { - /** Ad unit id from the LevelPlay dashboard. */ + /** + * Ad unit id from the LevelPlay dashboard (Ad units page). Android and iOS ad units have different ids. + * + * @since 0.1.0 + */ adUnitId: string; } +/** + * Options for `showRewarded()` and `showInterstitial()`: `adUnitId` (see AdUnitOptions) plus an optional placement. + * + * @since 0.1.0 + */ export interface ShowOptions extends AdUnitOptions { - /** Optional placement name configured in the LevelPlay dashboard (capping / pacing / reward per placement). */ + /** + * Optional placement name configured in the LevelPlay dashboard (capping, pacing and reward per placement). + * Omit it to use the default placement. + * + * @since 0.1.0 + */ placementName?: string; } +/** + * Options for `isReady()`: `adUnitId` (see AdUnitOptions) plus the format. + * + * @since 0.1.0 + */ export interface IsReadyOptions extends AdUnitOptions { + /** + * Format of the ad unit. + * + * @since 0.1.0 + */ format: AdFormat; } +/** + * Result of `isReady()`. + * + * @since 0.1.0 + */ export interface IsReadyResult { + /** + * `true` when a loaded ad can be shown right now. + * + * @since 0.1.0 + */ ready: boolean; } +/** + * The reward of a rewarded ad, as configured in the LevelPlay dashboard (per ad unit or placement). + * + * @since 0.1.0 + */ export interface Reward { + /** + * Name of the reward, for example `Coins`. + * + * @since 0.1.0 + */ name: string; + /** + * Amount of the reward. + * + * @since 0.1.0 + */ amount: number; } +/** + * Error reported by the SDK (load / display failures) or by the plugin. + * + * @since 0.1.0 + */ export interface AdError { + /** + * LevelPlay error code, for example `509` (no fill). `-1` is used by the plugin for "Ad not ready" and for the web + * stub. + * + * @since 0.1.0 + */ code: number; + /** + * Human readable message. + * + * @since 0.1.0 + */ message: string; } -/** Subset of the native `LevelPlayAdInfo` / `LPMAdInfo` that is useful in JavaScript. */ +/** + * Subset of the native `LevelPlayAdInfo` (Android) / `LPMAdInfo` (iOS) that is useful in JavaScript. + * Fields the SDK does not report are omitted. + * + * @since 0.1.0 + */ export interface AdInfo { + /** + * Unique id of this ad. + * + * @since 0.1.0 + */ adId?: string; + /** + * Ad unit id. + * + * @since 0.1.0 + */ adUnitId: string; + /** + * Ad unit name from the dashboard. + * + * @since 0.1.0 + */ adUnitName?: string; + /** + * Ad format as reported by the SDK. + * + * @since 0.1.0 + */ adFormat?: string; + /** + * Placement name of the show call, when one was used. + * + * @since 0.1.0 + */ placementName?: string; + /** + * Name of the mediated network that served the ad. + * + * @since 0.1.0 + */ adNetwork?: string; + /** + * Mediation instance name. + * + * @since 0.1.0 + */ instanceName?: string; + /** + * Mediation instance id. + * + * @since 0.1.0 + */ instanceId?: string; + /** + * Country code of the impression. + * + * @since 0.1.0 + */ country?: string; + /** + * Auction id. + * + * @since 0.1.0 + */ auctionId?: string; - /** Impression revenue in USD as reported by the SDK (may be absent before display). */ + /** + * Impression revenue in USD as reported by the SDK (may be absent or 0 before display). + * + * @since 0.1.0 + */ revenue?: number; + /** + * Revenue precision as reported by the SDK. + * + * @since 0.1.0 + */ precision?: string; + /** + * A/B test group of the user (`ab`). + * + * @since 0.3.0 + */ + ab?: string; + /** + * Segment name of the user, see `setSegment()`. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * Encrypted CPM (`encryptedCPM`). + * + * @since 0.3.0 + */ + encryptedCPM?: string; + /** + * Creative id of the served ad, when the network reports one. + * + * @since 0.3.0 + */ + creativeId?: string; + /** + * iOS only: SKAdNetwork conversion value (`LPMAdInfo.conversionValue`). Android's `LevelPlayAdInfo` has no such + * field in SDK 9.6.1, so it is always absent there. + * + * @since 0.3.0 + */ + conversionValue?: number; + /** + * Size of the ad. Banners only (`LevelPlayAdInfo.getAdSize()` / `LPMAdInfo.adSize`). + * + * @since 0.3.0 + */ + adSize?: AdSizeInfo; } +/** + * A resolved ad size as reported by the SDK (`LevelPlayAdSize` / `LPMAdSize`). Width and height are in dp on Android + * and points on iOS, which equal CSS px in the WebView at the default zoom. + * + * @since 0.3.0 + */ +export interface AdSizeInfo { + /** + * Width in CSS px (dp / pt). + * + * @since 0.3.0 + */ + width: number; + /** + * Height in CSS px (dp / pt). + * + * @since 0.3.0 + */ + height: number; + /** + * SDK description of the size, for example `BANNER` or `ADAPTIVE`. + * + * @since 0.3.0 + */ + description?: string; + /** + * `true` for an adaptive size. + * + * @since 0.3.0 + */ + isAdaptive?: boolean; +} + +/** + * Result of `showRewarded()` and `showInterstitial()`, resolved after the ad + * closed or failed to display. + * + * @since 0.1.0 + */ export interface ShowResult { - /** The ad was displayed (`displayed` fired). */ + /** + * The ad was displayed (the `displayed` event fired). + * + * @since 0.1.0 + */ shown: boolean; - /** Rewarded only: the reward callback fired for this show. Grant the reward only when this is true. */ + /** + * Rewarded only: the reward callback fired for this show. Grant the reward only when this is `true`. + * Always `false` for interstitials. + * + * @since 0.1.0 + */ rewarded: boolean; + /** + * The reward, present when `rewarded` is `true`. + * + * @since 0.1.0 + */ reward?: Reward; - /** Present when the ad was not ready or failed to display. */ + /** + * Present when the ad was not ready (`code: -1`) or failed to display. + * + * @since 0.1.0 + */ error?: AdError; + /** + * Info of the displayed ad. + * + * @since 0.1.0 + */ adInfo?: AdInfo; } +/** + * Payload of the `loaded`, `displayed`, `clicked` and `closed` events. + * + * @since 0.1.0 + */ export interface AdEvent { + /** + * Format of the ad unit that fired the event. + * + * @since 0.1.0 + */ format: AdFormat; + /** + * Ad unit that fired the event. + * + * @since 0.1.0 + */ adUnitId: string; + /** + * Ad info, when the SDK provides it (not on `loadFailed`). + * + * @since 0.1.0 + */ adInfo?: AdInfo; } +/** + * Payload of the `loadFailed` and `displayFailed` events: the AdEvent fields plus `error`. + * + * @since 0.1.0 + */ export interface AdErrorEvent extends AdEvent { + /** + * What went wrong. + * + * @since 0.1.0 + */ error: AdError; } +/** + * Payload of the `rewarded` event: the AdEvent fields plus `reward`. + * + * @since 0.1.0 + */ export interface AdRewardEvent extends AdEvent { + /** + * The reward earned. + * + * @since 0.1.0 + */ reward: Reward; } +/** + * iOS App Tracking Transparency status. `unavailable` on Android, on the web and on unknown future iOS values. + * + * @since 0.1.0 + */ export type TrackingStatus = 'authorized' | 'denied' | 'restricted' | 'notDetermined' | 'unavailable'; +/** + * Result of `requestTrackingAuthorization()` and + * `getTrackingAuthorizationStatus()`. + * + * @since 0.1.0 + */ export interface TrackingResult { - /** iOS App Tracking Transparency status. Always `unavailable` on Android and web. */ + /** + * iOS App Tracking Transparency status. Always `unavailable` on Android and web. + * + * @since 0.1.0 + */ status: TrackingStatus; } +// ------------------------------------------------------------------------------------------------ 0.3.0: capabilities + +/** + * Result of `getCapabilities()`: what this platform build of the plugin can do. Check it instead of the platform + * name, so the same game code runs on Android, iOS and the web. + * + * @since 0.3.0 + */ +export interface Capabilities { + /** + * Banner ads (`createBanner()` and friends) are available. + * + * @since 0.3.0 + */ + banner: boolean; + /** + * Native ads (`loadNativeAd()` and friends) are available. + * + * @since 0.3.0 + */ + nativeAd: boolean; + /** + * Native ad templates this platform can render. Empty when `nativeAd` is `false`. + * + * @since 0.3.0 + */ + nativeAdTemplates: NativeAdTemplate[]; + /** + * The `impressionData` event is delivered. + * + * @since 0.3.0 + */ + impressionData: boolean; + /** + * The `adInfoChanged` event is delivered (rewarded and interstitial only). + * + * @since 0.3.0 + */ + adInfoChanged: boolean; +} + +// ------------------------------------------------------------------------------------------------ 0.3.0: geometry + +/** + * A rectangle in CSS px, relative to the top-left corner of the WebView viewport (the same space as + * `element.getBoundingClientRect()` without page scroll). + * + * @since 0.3.0 + */ +export interface Rect { + /** + * Left edge in CSS px. + * + * @since 0.3.0 + */ + x: number; + /** + * Top edge in CSS px. + * + * @since 0.3.0 + */ + y: number; + /** + * Width in CSS px. + * + * @since 0.3.0 + */ + width: number; + /** + * Height in CSS px. + * + * @since 0.3.0 + */ + height: number; +} + +// ------------------------------------------------------------------------------------------------ 0.3.0: banners + +/** + * Banner size presets, named after the SDK constants (`LevelPlayAdSize.BANNER` / `LPMAdSize.bannerSize()` ...). + * + * - `BANNER`: 320 x 50 + * - `LARGE`: 320 x 90 + * - `MEDIUM_RECTANGLE`: 300 x 250 + * - `LEADERBOARD`: 728 x 90 (tablets) + * - `ADAPTIVE`: `LevelPlayAdSize.createAdaptiveAdSize(context, width)` / `LPMAdSize.createAdaptiveAdSize(withWidth:)`; + * the SDK picks the height (and BANNER or LEADERBOARD as fallback) for the given width. Requires a finished + * `initialize()`. + * - `CUSTOM`: `LevelPlayAdSize.createCustomSize(width, height)` / `LPMAdSize.customSizeWithWidth:height:` with + * `customSize`. Few networks fill custom sizes; prefer a preset or `ADAPTIVE`. + * + * @since 0.3.0 + */ +export type BannerSize = 'BANNER' | 'LARGE' | 'MEDIUM_RECTANGLE' | 'LEADERBOARD' | 'ADAPTIVE' | 'CUSTOM'; + +/** + * Width and height of a `CUSTOM` banner, in CSS px (dp on Android, points on iOS). + * + * @since 0.3.0 + */ +export interface BannerCustomSize { + /** + * Width in CSS px (positive integer). + * + * @since 0.3.0 + */ + width: number; + /** + * Height in CSS px (positive integer). + * + * @since 0.3.0 + */ + height: number; +} + +/** + * Vertical anchor of a banner inside the WebView's safe area. Banners are always horizontally centred; use + * `offsetX` to move them sideways. + * + * @since 0.3.0 + */ +export type BannerPosition = 'top' | 'bottom' | 'center'; + +/** + * Identifies one banner created with `createBanner()`. + * + * @since 0.3.0 + */ +export interface BannerIdOptions { + /** + * Plugin-side banner id passed to `createBanner()` (defaults to the ad unit id there). + * + * @since 0.3.0 + */ + bannerId: string; +} + +/** + * Where a banner sits over the WebView. + * + * @since 0.3.0 + */ +export interface BannerLayoutOptions { + /** + * Vertical anchor. + * + * @default 'bottom' + * @since 0.3.0 + */ + position?: BannerPosition; + /** + * Horizontal offset from the centred position in CSS px (positive moves right). + * + * @default 0 + * @since 0.3.0 + */ + offsetX?: number; + /** + * Vertical offset from the anchored position in CSS px (positive moves down). + * + * @default 0 + * @since 0.3.0 + */ + offsetY?: number; + /** + * Keep the banner inside the safe area (status bar, notch / display cutout, home indicator, navigation bar), measured + * against the WebView's own on-screen rect. Set `false` to anchor to the raw WebView edges. + * + * @default true + * @since 0.3.0 + */ + respectSafeArea?: boolean; +} + +/** + * Options for `createBanner()`. + * + * @since 0.3.0 + */ +export interface CreateBannerOptions extends AdUnitOptions, BannerLayoutOptions { + /** + * Plugin-side id of this banner, used by every other banner method and in banner events. Lets one ad unit back + * several banners. Defaults to `adUnitId`. + * + * @since 0.3.0 + */ + bannerId?: string; + /** + * Size preset. + * + * @default 'ADAPTIVE' + * @since 0.3.0 + */ + size?: BannerSize; + /** + * `CUSTOM` only: the banner size. When `customSize` is set and `size` is omitted, `size` defaults to `CUSTOM`. + * + * @since 0.3.0 + */ + customSize?: BannerCustomSize; + /** + * `ADAPTIVE` only: width in CSS px to compute the adaptive size for. Defaults to the width of the WebView's safe + * area; in that case the plugin recreates and reloads the banner automatically when that width changes (rotation, + * split screen, window resize), keeping its id, layout and visibility. A fixed `adaptiveWidth` is never recreated. + * + * @since 0.3.0 + */ + adaptiveWidth?: number; + /** + * Placement name (reporting only for banners). Applied through the banner config before the first load. + * + * @since 0.3.0 + */ + placementName?: string; + /** + * Bid floor in USD (`LevelPlayBannerAdView.Config.Builder.setBidFloor` / `LPMBannerAdViewConfigBuilder set(bidFloor:)`). + * + * @since 0.3.0 + */ + bidFloor?: number; +} + +/** + * Options for `setBannerLayout()`: `bannerId` plus the layout fields (see BannerLayoutOptions). + * + * @since 0.3.0 + */ +export interface SetBannerLayoutOptions extends BannerIdOptions, BannerLayoutOptions {} + +/** + * Result of `createBanner()`, `showBanner()` and `setBannerLayout()`. + * + * @since 0.3.0 + */ +export interface BannerResult { + /** + * The banner id. + * + * @since 0.3.0 + */ + bannerId: string; + /** + * Requested ad size (the creative may be smaller for adaptive sizes; it is centred in this frame). + * + * @since 0.3.0 + */ + adSize: AdSizeInfo; + /** + * Where the banner frame is (or will be, while hidden) in CSS px, relative to the WebView viewport. Use it to pad + * game UI away from the banner. + * + * @since 0.3.0 + */ + frame: Rect; + /** + * The banner view is currently visible. + * + * @since 0.3.0 + */ + visible: boolean; +} + +/** + * Payload of the `banner*` events. + * + * @since 0.3.0 + */ +export interface BannerEvent { + /** + * Banner that fired the event. + * + * @since 0.3.0 + */ + bannerId: string; + /** + * Ad unit of the banner. + * + * @since 0.3.0 + */ + adUnitId: string; + /** + * Ad info, when the SDK provides it (not on `bannerLoadFailed`). + * + * @since 0.3.0 + */ + adInfo?: AdInfo; + /** + * Current frame of the banner in CSS px. + * + * @since 0.3.0 + */ + frame?: Rect; +} + +/** + * Payload of `bannerLoadFailed` and `bannerDisplayFailed`. + * + * @since 0.3.0 + */ +export interface BannerErrorEvent extends BannerEvent { + /** + * What went wrong. + * + * @since 0.3.0 + */ + error: AdError; +} + +// ------------------------------------------------------------------------------------------------ 0.3.0: native ads + +/** + * Native ad template rendered by the plugin (the LevelPlay SDK ships no template views; the plugin provides its own + * layouts, like Unity's Flutter and React Native wrappers do). + * + * - `small`: icon, title, advertiser, body, call to action; no media view. Recommended 300 x 175 or a row at least + * 90 px tall. + * - `medium`: the `small` assets plus a media view. Recommended 300 x 350. + * + * @since 0.3.0 + */ +export type NativeAdTemplate = 'small' | 'medium'; + +/** + * Optional styling of a native ad template. Colours are CSS hex strings (`#RRGGBB` or `#RRGGBBAA`). + * + * @since 0.3.0 + */ +export interface NativeAdTemplateStyle { + /** + * Template background. + * + * @since 0.3.0 + */ + backgroundColor?: string; + /** + * Title text colour. + * + * @since 0.3.0 + */ + titleColor?: string; + /** + * Body and advertiser text colour. + * + * @since 0.3.0 + */ + bodyColor?: string; + /** + * Call-to-action button background. + * + * @since 0.3.0 + */ + callToActionBackgroundColor?: string; + /** + * Call-to-action button text colour. + * + * @since 0.3.0 + */ + callToActionTextColor?: string; + /** + * Corner radius of the template in CSS px. + * + * @default 0 + * @since 0.3.0 + */ + cornerRadius?: number; + /** + * Title font. + * + * @since 0.3.0 + */ + titleFont?: NativeAdFont; + /** + * Body and advertiser font. + * + * @since 0.3.0 + */ + bodyFont?: NativeAdFont; + /** + * Call-to-action button font. + * + * @since 0.3.0 + */ + callToActionFont?: NativeAdFont; +} + +/** + * A font of a native ad template text. Omitted fields keep the template default (system font). + * + * @since 0.3.0 + */ +export interface NativeAdFont { + /** + * Font family. Either a system family name (Android: `sans-serif`, `sans-serif-medium`, `serif`, `monospace` ...; + * iOS: a `UIFont` family or PostScript name such as `Avenir Next` or `Menlo-Bold`), or the path of a `.ttf` / `.otf` + * file inside the app's web assets, relative to the web root (for example `fonts/Inter-Bold.ttf`, the same file the + * page loads with `@font-face`). Unknown families fall back to the system font. + * + * @since 0.3.0 + */ + family?: string; + /** + * Font size in CSS px (dp / pt; not scaled by the system font size setting, like text in the WebView). + * + * @since 0.3.0 + */ + size?: number; +} + +/** + * Identifies one native ad slot. + * + * @since 0.3.0 + */ +export interface NativeAdIdOptions { + /** + * Plugin-side id of the native ad slot. + * + * @since 0.3.0 + */ + nativeAdId: string; +} + +/** + * Options for `loadNativeAd()`. + * + * @since 0.3.0 + */ +export interface LoadNativeAdOptions extends NativeAdIdOptions { + /** + * Placement name. LevelPlay 9.6.1 native ads are addressed by placement only (`LevelPlayNativeAd.Builder + * .withPlacementName` / `LevelPlayNativeAdBuilder withPlacementName:`); there is no ad unit id for native ads in + * this SDK version. Omit it for the default placement. + * + * @since 0.3.0 + */ + placementName?: string; + /** + * Template used when the ad is shown. + * + * @default 'medium' + * @since 0.3.0 + */ + template?: NativeAdTemplate; + /** + * Template styling. + * + * @since 0.3.0 + */ + style?: NativeAdTemplateStyle; +} + +/** + * Options for `showNativeAd()` and `setNativeAdRect()`. + * + * @since 0.3.0 + */ +export interface NativeAdRectOptions extends NativeAdIdOptions { + /** + * Where the template goes, in CSS px relative to the WebView viewport (for example a placeholder element's + * `getBoundingClientRect()`). + * + * @since 0.3.0 + */ + rect: Rect; +} + +/** + * Ad info of a native ad (`AdInfo` on Android / `ISAdInfo` on iOS: the older ironSource info type, which has no ad + * unit, ad id or placement fields). + * + * @since 0.3.0 + */ +export interface NativeAdInfo { + /** + * Auction id. + * + * @since 0.3.0 + */ + auctionId?: string; + /** + * Mediated network that served the ad. + * + * @since 0.3.0 + */ + adNetwork?: string; + /** + * Mediation instance name. + * + * @since 0.3.0 + */ + instanceName?: string; + /** + * Mediation instance id. + * + * @since 0.3.0 + */ + instanceId?: string; + /** + * Country code. + * + * @since 0.3.0 + */ + country?: string; + /** + * Impression revenue in USD. + * + * @since 0.3.0 + */ + revenue?: number; + /** + * Revenue precision. + * + * @since 0.3.0 + */ + precision?: string; + /** + * A/B test group. + * + * @since 0.3.0 + */ + ab?: string; + /** + * Segment name. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * Encrypted CPM. + * + * @since 0.3.0 + */ + encryptedCPM?: string; + /** + * iOS only: SKAdNetwork conversion value. + * + * @since 0.3.0 + */ + conversionValue?: number; +} + +/** + * Payload of the `nativeAd*` events. + * + * @since 0.3.0 + */ +export interface NativeAdEvent { + /** + * Native ad slot that fired the event. + * + * @since 0.3.0 + */ + nativeAdId: string; + /** + * Placement passed to `loadNativeAd()`, if any. + * + * @since 0.3.0 + */ + placementName?: string; + /** + * Ad info, when the SDK provides it (not on `nativeAdLoadFailed`). + * + * @since 0.3.0 + */ + adInfo?: NativeAdInfo; +} + +/** + * Payload of `nativeAdLoadFailed`. + * + * @since 0.3.0 + */ +export interface NativeAdErrorEvent extends NativeAdEvent { + /** + * What went wrong. + * + * @since 0.3.0 + */ + error: AdError; +} + +// ------------------------------------------------------------------------------------------------ 0.3.0: revenue + +/** + * Impression-level revenue data (`LevelPlayImpressionData` on Android, `LPMImpressionData` on iOS). Every field the + * SDK 9.6.1 data class exposes is mapped; fields the SDK leaves empty are omitted. + * + * Not available in SDK 9.6.1 on either platform: `lifetimeRevenue` (removed from the impression data class). If the + * server ever sends extra keys they are still visible in `allData`. + * + * @since 0.3.0 + */ +export interface ImpressionData { + /** + * Which ad format produced the impression, as the SDK reports it (for example `Rewarded Video`, `Interstitial`, + * `Banner`, or `nativead` for impressions synthesised from native ad info). + * + * @since 0.3.0 + */ + adFormat?: string; + /** + * Auction id. + * + * @since 0.3.0 + */ + auctionId?: string; + /** + * Mediation ad unit id (`mediationAdUnitId`). + * + * @since 0.3.0 + */ + adUnitId?: string; + /** + * Mediation ad unit name (`mediationAdUnitName`). + * + * @since 0.3.0 + */ + adUnitName?: string; + /** + * Mediated network that served the ad. + * + * @since 0.3.0 + */ + adNetwork?: string; + /** + * Mediation instance name. + * + * @since 0.3.0 + */ + instanceName?: string; + /** + * Mediation instance id. + * + * @since 0.3.0 + */ + instanceId?: string; + /** + * Country code. + * + * @since 0.3.0 + */ + country?: string; + /** + * Placement name of the impression. + * + * @since 0.3.0 + */ + placement?: string; + /** + * Revenue of this impression in USD. + * + * @since 0.3.0 + */ + revenue?: number; + /** + * Revenue precision (for example `BID`, `RATE`, `ESTIMATED`). + * + * @since 0.3.0 + */ + precision?: string; + /** + * A/B test group. + * + * @since 0.3.0 + */ + ab?: string; + /** + * Segment name, see `setSegment()`. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * Encrypted CPM (`encryptedCPM` on Android, `encryptedCpm` on iOS). + * + * @since 0.3.0 + */ + encryptedCPM?: string; + /** + * Creative id. + * + * @since 0.3.0 + */ + creativeId?: string; + /** + * iOS only: SKAdNetwork conversion value. + * + * @since 0.3.0 + */ + conversionValue?: number; + /** + * The raw `allData` map of the SDK (`getAllData()` JSON on Android, `allData` dictionary on iOS). Keys and value + * types are SDK defined and may change between SDK versions. + * + * @since 0.3.0 + */ + allData?: { [key: string]: unknown }; +} + +// ------------------------------------------------------------------------------------------------ 0.3.0: placements + +/** + * Options for `isPlacementCapped()`. + * + * @since 0.3.0 + */ +export interface PlacementCappedOptions { + /** + * Format of the placement. LevelPlay 9.6.1 has capping checks for rewarded and interstitial only. + * + * @since 0.3.0 + */ + format: AdFormat; + /** + * Placement name from the LevelPlay dashboard. + * + * @since 0.3.0 + */ + placementName: string; +} + +/** + * Result of `isPlacementCapped()`. + * + * @since 0.3.0 + */ +export interface PlacementCappedResult { + /** + * `true` when the placement reached its capping or pacing limit; showing it now fails. + * + * @since 0.3.0 + */ + capped: boolean; +} + +/** + * Options for `getReward()`: `adUnitId` (see AdUnitOptions) plus an optional placement. + * + * @since 0.3.0 + */ +export interface GetRewardOptions extends AdUnitOptions { + /** + * Placement whose reward to read. Its reward takes precedence over the ad unit reward. Omit for the ad unit reward. + * + * @since 0.3.0 + */ + placementName?: string; +} + +// ------------------------------------------------------------------------------------------------ 0.3.0: user + +/** + * Options for `setSegment()` (`LevelPlaySegment` / `LPMSegment`). Omitted fields are not sent. + * + * @since 0.3.0 + */ +export interface SegmentOptions { + /** + * Segment name. + * + * @since 0.3.0 + */ + segmentName?: string; + /** + * User level (integer). + * + * @since 0.3.0 + */ + level?: number; + /** + * The user has paid in the app. + * + * @since 0.3.0 + */ + isPaying?: boolean; + /** + * When the user was created, in milliseconds since the Unix epoch (`Date.now()` style). + * + * @since 0.3.0 + */ + userCreationDate?: number; + /** + * Total in-app purchase amount of the user (USD). + * + * @since 0.3.0 + */ + iapTotal?: number; + /** + * Custom segment parameters. SDK 9.6.1 limits: at most 5 pairs; keys and values 1-32 characters, letters and digits + * only (`^[a-zA-Z0-9]*$`). The plugin rejects with `INVALID_ARGUMENT` instead of letting the SDK silently drop pairs. + * + * @since 0.3.0 + */ + customParameters?: { [key: string]: string }; +} + +/** + * Options for `setDynamicUserId()`. + * + * @since 0.3.0 + */ +export interface DynamicUserIdOptions { + /** + * Dynamic user id, forwarded in server-to-server reward callbacks. Can change during the session. + * + * @since 0.3.0 + */ + userId: string; +} + +/** + * Result of `setDynamicUserId()`. + * + * @since 0.3.0 + */ +export interface DynamicUserIdResult { + /** + * The SDK accepted the id (`LevelPlay.setDynamicUserId` returns a boolean on both platforms). + * + * @since 0.3.0 + */ + valid: boolean; +} + +/** + * Event names emitted by the plugin. + * + * @since 0.1.0 + */ +export type LevelPlayEventName = + | 'loaded' + | 'loadFailed' + | 'displayed' + | 'displayFailed' + | 'clicked' + | 'closed' + | 'rewarded' + | 'adInfoChanged' + | 'impressionData' + | 'bannerLoaded' + | 'bannerLoadFailed' + | 'bannerDisplayed' + | 'bannerDisplayFailed' + | 'bannerClicked' + | 'bannerExpanded' + | 'bannerCollapsed' + | 'bannerLeftApplication' + | 'nativeAdLoaded' + | 'nativeAdLoadFailed' + | 'nativeAdImpression' + | 'nativeAdClicked'; + +/** + * Unity LevelPlay ads (ad-unit API): rewarded, interstitial and (since 0.3.0) banner and native ads, impression-level + * revenue, segments and placement capping. + * + * @since 0.1.0 + */ export interface LevelPlayPlugin { /** - * Initialise the LevelPlay SDK. Resolves on `onInitSuccess`, rejects with the init error otherwise. - * Calling it again after a successful init resolves immediately. Load ads only after this resolves. + * Initialise the LevelPlay SDK (`LevelPlay.init`). Resolves on init success, rejects with the init error + * (code and message from the SDK) otherwise. Calling it again after a successful init resolves immediately; + * concurrent calls share one init. Load ads only after this resolves. + * + * Set consent (and on iOS ask for ATT) before calling it. + * + * On the web it rejects as unimplemented. + * + * @since 0.1.0 */ initialize(options: InitOptions): Promise; - /** Native SDK version (available before init). */ + /** + * Native LevelPlay SDK version. Works before init. + * + * @since 0.1.0 + */ getSdkVersion(): Promise; - /** Forward GDPR / CCPA / COPPA signals. Call before {@link initialize} when you can. */ + /** + * Forward GDPR / CCPA / COPPA signals to LevelPlay. Call it before `initialize()` when you + * can, and again whenever the user changes their choice. + * + * @since 0.1.0 + */ setConsent(options: ConsentOptions): Promise; - /** Raw `LevelPlay.setMetaData(key, value)` for network-specific flags. Call before init. */ + /** + * Raw `LevelPlay.setMetaData(key, value)` for SDK or network-specific flags. Call it before init. + * + * @since 0.1.0 + */ setMetaData(options: MetaDataOptions): Promise; /** - * iOS: show the App Tracking Transparency prompt (needs `NSUserTrackingUsageDescription` in Info.plist) and resolve - * with the resulting status. Call it before {@link initialize}. Android / web: resolves `unavailable`. + * iOS: show the App Tracking Transparency prompt and resolve with the resulting status. Needs + * `NSUserTrackingUsageDescription` in `Info.plist`. iOS only shows the prompt once; later calls resolve the stored + * status. Call it before `initialize()`, while the app is active. + * + * Android and web: resolves `unavailable`. + * + * @since 0.1.0 */ requestTrackingAuthorization(): Promise; - /** Current ATT status without prompting (iOS). Android / web: `unavailable`. */ + /** + * Current App Tracking Transparency status without prompting (iOS). Android and web: `unavailable`. + * + * @since 0.1.0 + */ getTrackingAuthorizationStatus(): Promise; /** - * Start loading a rewarded ad for the ad unit (the ad object is created on first use and reused). - * Resolves once the request is issued; the outcome arrives as `loaded` / `loadFailed` events. + * Start loading a rewarded ad for the ad unit. The native ad object is created on first use and reused for the + * ad unit. Resolves once the request is issued; the outcome arrives as a `loaded` or `loadFailed` event. + * Load the next ad after each show. + * + * @since 0.1.0 */ loadRewarded(options: AdUnitOptions): Promise; /** - * Show a loaded rewarded ad. Resolves after the ad closes (or failed to display) with what happened. - * Never rejects for "not ready": resolves `{ shown: false, error }` instead. + * Show a loaded rewarded ad. Resolves after the ad closed (or failed to display) with what happened. The reward + * and close callbacks can arrive in either order on some networks, so the plugin waits up to 1 second after the close + * for a late reward. Never rejects for "not ready": resolves `{ shown: false, rewarded: false, error }` instead. + * + * @since 0.1.0 */ showRewarded(options: ShowOptions): Promise; - /** Start loading an interstitial ad (see {@link loadRewarded}). */ + /** + * Start loading an interstitial ad for the ad unit. Works like `loadRewarded()`. + * + * @since 0.1.0 + */ loadInterstitial(options: AdUnitOptions): Promise; - /** Show a loaded interstitial. Resolves after it closes (or failed to display). */ + /** + * Show a loaded interstitial. Resolves after it closed (or failed to display). Never rejects for "not ready". + * + * @since 0.1.0 + */ showInterstitial(options: ShowOptions): Promise; - /** `isAdReady()` of the ad object for this ad unit (`false` when it was never loaded). */ + /** + * `isAdReady()` of the native ad object for this ad unit. `false` when the ad unit was never loaded. + * + * @since 0.1.0 + */ isReady(options: IsReadyOptions): Promise; - /** Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first. */ + /** + * Open the LevelPlay Integration Test Suite. Requires `initialize({ testSuite: true })` first. + * Development builds only. Rejects on the web. + * + * @since 0.1.0 + */ launchTestSuite(): Promise; - /** Log the LevelPlay integration helper report to the native console (development only). */ + /** + * Write the LevelPlay integration helper report to the native log (Xcode console; Android logcat tag + * `IntegrationHelper`): SDK, adapter and network SDK versions, each `VERIFIED` or not. Development only. + * + * @since 0.1.0 + */ validateIntegration(): Promise; + /** + * What this platform supports (banners, native ad templates, impression data, `adInfoChanged`). Works before init. + * Web: everything `false`. + * + * @since 0.3.0 + */ + getCapabilities(): Promise; + + /** + * Set the user segment (`LevelPlay.setSegment` with a `LevelPlaySegment` / `LPMSegment`). Call it before + * `initialize()` so the first ad requests use it; later calls apply to the following requests. Rejects with + * `INVALID_ARGUMENT` when `customParameters` break the SDK limits. Web: no-op. + * + * @since 0.3.0 + */ + setSegment(options: SegmentOptions): Promise; + + /** + * Set or change the dynamic user id used in server-to-server reward callbacks (`LevelPlay.setDynamicUserId` on + * both platforms). Set it before `showRewarded()`. Web: resolves `{ valid: false }`. + * + * @since 0.3.0 + */ + setDynamicUserId(options: DynamicUserIdOptions): Promise; + + /** + * Whether a rewarded or interstitial placement is capped right now (static + * `LevelPlayRewardedAd.isPlacementCapped` / `LevelPlayInterstitialAd.isPlacementCapped` on Android, + * `LPMRewardedAd.isPlacementCapped:` / `LPMInterstitialAd.isPlacementCapped:` on iOS). Works without a loaded ad. + * Web: `{ capped: false }`. + * + * @since 0.3.0 + */ + isPlacementCapped(options: PlacementCappedOptions): Promise; + + /** + * The reward configured for a rewarded ad unit or one of its placements (`LevelPlayRewardedAd.getReward(placement)` / + * `LPMRewardedAd getReward(placementName:)`), for "watch a video for N coins" buttons. The SDK returns + * `{ name: '', amount: 0 }` when it has no reward configuration (for example before init). Web: the same empty + * reward. + * + * @since 0.3.0 + */ + getReward(options: GetRewardOptions): Promise; + + /** + * Create a banner (`LevelPlayBannerAdView` / `LPMBannerAdView`) for the ad unit and attach it, hidden, in a + * pass-through overlay above the WebView. Requires a finished `initialize()` (`NOT_INITIALIZED` otherwise). Rejects + * with `ALREADY_EXISTS` when `bannerId` is in use; destroy it first. Does not load: call `loadBanner()`. + * Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + createBanner(options: CreateBannerOptions): Promise; + + /** + * Load the banner (`loadAd()` / `loadAdWithViewController:`). The outcome arrives as `bannerLoaded` or + * `bannerLoadFailed`; after the first load the SDK refreshes the banner on the dashboard interval. The SDK accepts + * one load per banner object: calling it again has no effect (Android logs "Banner load already called"), so to retry + * right away after `bannerLoadFailed`, destroy the banner and create it again. Web: no-op. + * + * @since 0.3.0 + */ + loadBanner(options: BannerIdOptions): Promise; + + /** + * Make the banner visible and resume auto refresh (`resumeAutoRefresh`). Can be called before the load finished; + * the creative appears when it arrives. Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + showBanner(options: BannerIdOptions): Promise; + + /** + * Hide the banner and pause auto refresh (`pauseAutoRefresh`) so hidden banners do not burn impressions. The view + * stays attached; `showBanner()` brings it back. Web: no-op. + * + * @since 0.3.0 + */ + hideBanner(options: BannerIdOptions): Promise; + + /** + * Move a banner (position, offsets, safe area). Resolves with the new frame. Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + setBannerLayout(options: SetBannerLayoutOptions): Promise; + + /** + * Remove the banner from the screen and `destroy()` it. A destroyed banner cannot be reused; create a new one. + * Resolves also for unknown ids. Web: no-op. + * + * @since 0.3.0 + */ + destroyBanner(options: BannerIdOptions): Promise; + + /** + * Load a native ad into a slot. Following the SDK rule "one native ad object per load", it destroys the slot's + * previous ad (hiding it if shown), builds a new `LevelPlayNativeAd` with the placement and loads it. The outcome + * arrives as `nativeAdLoaded` or `nativeAdLoadFailed`. Requires a finished `initialize()`. Rejects with + * `UNSUPPORTED` when `getCapabilities().nativeAd` is `false` or the template is not listed there. Web: rejects as + * unimplemented. + * + * @since 0.3.0 + */ + loadNativeAd(options: LoadNativeAdOptions): Promise; + + /** + * Render the loaded native ad into its template, register the asset views with the SDK + * (`NativeAdLayout.registerNativeAdViews` / `ISNativeAdView registerNativeAdViews:`) and place it at `rect` above the + * WebView. Rejects with `NOT_LOADED` before `nativeAdLoaded`. The impression is reported by `nativeAdImpression`. + * Web: rejects as unimplemented. + * + * @since 0.3.0 + */ + showNativeAd(options: NativeAdRectOptions): Promise; + + /** + * Move or resize a shown native ad, for example after the placeholder element moved. Web: no-op. + * + * @since 0.3.0 + */ + setNativeAdRect(options: NativeAdRectOptions): Promise; + + /** + * Hide a shown native ad (the view stays registered; `showNativeAd()` shows it again). Web: no-op. + * + * @since 0.3.0 + */ + hideNativeAd(options: NativeAdIdOptions): Promise; + + /** + * Remove the native ad view and `destroyAd()` it. Resolves also for unknown ids. Web: no-op. + * + * @since 0.3.0 + */ + destroyNativeAd(options: NativeAdIdOptions): Promise; + + /** + * An ad finished loading for the ad unit and can be shown. + * + * @since 0.1.0 + */ addListener(eventName: 'loaded', listenerFunc: (event: AdEvent) => void): Promise; + + /** + * Loading failed, for example `509` (no fill). Retry later with a backoff. + * + * @since 0.1.0 + */ addListener(eventName: 'loadFailed', listenerFunc: (event: AdErrorEvent) => void): Promise; + + /** + * The ad was displayed (impression). `adInfo.revenue` is available here. + * + * @since 0.1.0 + */ addListener(eventName: 'displayed', listenerFunc: (event: AdEvent) => void): Promise; - addListener(eventName: 'displayFailed', listenerFunc: (event: AdErrorEvent) => void): Promise; + + /** + * The ad failed to display. The pending show call resolves with the same error. + * + * @since 0.1.0 + */ + addListener( + eventName: 'displayFailed', + listenerFunc: (event: AdErrorEvent) => void, + ): Promise; + + /** + * The user clicked the ad. + * + * @since 0.1.0 + */ addListener(eventName: 'clicked', listenerFunc: (event: AdEvent) => void): Promise; + + /** + * The ad was closed and the app is back in front. + * + * @since 0.1.0 + */ addListener(eventName: 'closed', listenerFunc: (event: AdEvent) => void): Promise; + + /** + * Rewarded only: the user earned the reward. Can fire before or after `closed`. + * + * @since 0.1.0 + */ addListener(eventName: 'rewarded', listenerFunc: (event: AdRewardEvent) => void): Promise; + /** + * Rewarded and interstitial: the SDK reloaded the ad in the background and its ad info (network, revenue ...) + * changed (`onAdInfoChanged` / `didChangeAdInfo:`). Banners and native ads have no such callback in SDK 9.6.1. + * + * @since 0.3.0 + */ + addListener(eventName: 'adInfoChanged', listenerFunc: (event: AdEvent) => void): Promise; + + /** + * Impression-level revenue data for every rewarded, interstitial and banner impression (per-ad + * `setImpressionDataListener` / `setImpressionDataDelegate:`, attached by the plugin to every ad object it creates), + * plus native ad impressions synthesised from the native ad info (`adFormat: 'nativead'`, `adInfo` fields only). + * Add the listener at any time, also before `initialize()`; nothing is delivered before the first ad shows. + * + * @since 0.3.0 + */ + addListener(eventName: 'impressionData', listenerFunc: (event: ImpressionData) => void): Promise; + + /** + * A banner loaded or refreshed with a new creative. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerLoaded', listenerFunc: (event: BannerEvent) => void): Promise; + + /** + * A banner load (or refresh) failed. The SDK keeps retrying on its refresh interval. + * + * @since 0.3.0 + */ + addListener( + eventName: 'bannerLoadFailed', + listenerFunc: (event: BannerErrorEvent) => void, + ): Promise; + + /** + * A banner creative was displayed on screen (impression). + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerDisplayed', listenerFunc: (event: BannerEvent) => void): Promise; + + /** + * A banner creative failed to display. + * + * @since 0.3.0 + */ + addListener( + eventName: 'bannerDisplayFailed', + listenerFunc: (event: BannerErrorEvent) => void, + ): Promise; + + /** + * The user clicked a banner. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerClicked', listenerFunc: (event: BannerEvent) => void): Promise; + + /** + * A banner opened full screen (for example an expandable creative). Pause the game. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerExpanded', listenerFunc: (event: BannerEvent) => void): Promise; + + /** + * A banner returned to its normal size. Resume the game. + * + * @since 0.3.0 + */ + addListener(eventName: 'bannerCollapsed', listenerFunc: (event: BannerEvent) => void): Promise; + + /** + * A banner click sent the user out of the app (browser or store). + * + * @since 0.3.0 + */ + addListener( + eventName: 'bannerLeftApplication', + listenerFunc: (event: BannerEvent) => void, + ): Promise; + + /** + * A native ad loaded and can be shown with `showNativeAd()`. + * + * @since 0.3.0 + */ + addListener(eventName: 'nativeAdLoaded', listenerFunc: (event: NativeAdEvent) => void): Promise; + + /** + * A native ad failed to load. Load again later (the plugin already destroyed the failed ad object). + * + * @since 0.3.0 + */ + addListener( + eventName: 'nativeAdLoadFailed', + listenerFunc: (event: NativeAdErrorEvent) => void, + ): Promise; + + /** + * A shown native ad recorded its impression (first pixel visible). + * + * @since 0.3.0 + */ + addListener( + eventName: 'nativeAdImpression', + listenerFunc: (event: NativeAdEvent) => void, + ): Promise; + + /** + * The user clicked a native ad. + * + * @since 0.3.0 + */ + addListener(eventName: 'nativeAdClicked', listenerFunc: (event: NativeAdEvent) => void): Promise; + + /** + * Remove every listener of this plugin. + * + * @since 0.1.0 + */ removeAllListeners(): Promise; } - -/** Event names emitted by the plugin. */ -export type LevelPlayEventName = 'loaded' | 'loadFailed' | 'displayed' | 'displayFailed' | 'clicked' | 'closed' | 'rewarded'; diff --git a/src/demo.ts b/src/demo.ts index e7a5dd8..d0a467c 100644 --- a/src/demo.ts +++ b/src/demo.ts @@ -2,6 +2,7 @@ * Public demo app keys and ad unit ids from Unity's official LevelPlay sample apps * (https://github.com/ironsource-mobile/Mediation-Demo-Apps: `Android/Kotlin/.../DemoActivity.kt` and * `iOS/Swift SPM/LevelPlayDemo/DemoViewController.swift`). They serve test ads and are safe for development only. + * The sample apps have no native ad placement; native ads load with the default placement of the app key. * Replace them with your own ids from the LevelPlay dashboard before release. */ export const LEVELPLAY_DEMO = { @@ -9,10 +10,12 @@ export const LEVELPLAY_DEMO = { appKey: '25b63cf85', rewarded: 'syz3d8ekts22q0or', interstitial: 'h3xw38h9214adgxo', + banner: '4fpetq4lhe5lsw3e', }, ios: { appKey: '8545d445', rewarded: 'qwouvdrkuwivay5q', interstitial: 'wmgt0712uuux8ju4', + banner: 'iep3rxsyp9na3rw8', }, } as const; diff --git a/src/web.ts b/src/web.ts index a2ab998..fa44e2c 100644 --- a/src/web.ts +++ b/src/web.ts @@ -2,12 +2,27 @@ import { WebPlugin } from '@capacitor/core'; import type { AdUnitOptions, + BannerIdOptions, + BannerResult, + Capabilities, ConsentOptions, + CreateBannerOptions, + DynamicUserIdOptions, + DynamicUserIdResult, + GetRewardOptions, InitOptions, InitResult, IsReadyResult, LevelPlayPlugin, + LoadNativeAdOptions, MetaDataOptions, + NativeAdIdOptions, + NativeAdRectOptions, + PlacementCappedOptions, + PlacementCappedResult, + Reward, + SegmentOptions, + SetBannerLayoutOptions, ShowResult, TrackingResult, } from './definitions'; @@ -15,6 +30,10 @@ import type { /** * Web stub. LevelPlay has no web SDK: init rejects with `unimplemented`, ads are never ready and every show resolves * as "not shown" so callers can treat the web like a no-fill platform without special casing. + * + * 0.3.0: `getCapabilities()` reports nothing supported. Setters, loads of things that cannot exist, hide and destroy + * are no-ops; calls that would have to return a native view (`createBanner`, `showBanner`, `setBannerLayout`, + * `loadNativeAd`, `showNativeAd`) reject as unimplemented, like `initialize`. */ export class LevelPlayWeb extends WebPlugin implements LevelPlayPlugin { private static readonly NO_FILL: ShowResult = { @@ -74,4 +93,68 @@ export class LevelPlayWeb extends WebPlugin implements LevelPlayPlugin { async validateIntegration(): Promise { /* nothing to validate */ } + + async getCapabilities(): Promise { + return { banner: false, nativeAd: false, nativeAdTemplates: [], impressionData: false, adInfoChanged: false }; + } + + async setSegment(_options: SegmentOptions): Promise { + /* nothing to forward */ + } + + async setDynamicUserId(_options: DynamicUserIdOptions): Promise { + return { valid: false }; + } + + async isPlacementCapped(_options: PlacementCappedOptions): Promise { + return { capped: false }; + } + + async getReward(_options: GetRewardOptions): Promise { + return { name: '', amount: 0 }; + } + + async createBanner(_options: CreateBannerOptions): Promise { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + + async loadBanner(_options: BannerIdOptions): Promise { + /* never fills */ + } + + async showBanner(_options: BannerIdOptions): Promise { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + + async hideBanner(_options: BannerIdOptions): Promise { + /* nothing shown */ + } + + async setBannerLayout(_options: SetBannerLayoutOptions): Promise { + throw this.unimplemented('LevelPlay banners are not available on the web.'); + } + + async destroyBanner(_options: BannerIdOptions): Promise { + /* nothing to destroy */ + } + + async loadNativeAd(_options: LoadNativeAdOptions): Promise { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + + async showNativeAd(_options: NativeAdRectOptions): Promise { + throw this.unimplemented('LevelPlay native ads are not available on the web.'); + } + + async setNativeAdRect(_options: NativeAdRectOptions): Promise { + /* nothing shown */ + } + + async hideNativeAd(_options: NativeAdIdOptions): Promise { + /* nothing shown */ + } + + async destroyNativeAd(_options: NativeAdIdOptions): Promise { + /* nothing to destroy */ + } } diff --git a/test/bun-test.d.ts b/test/bun-test.d.ts new file mode 100644 index 0000000..f2ef1cb --- /dev/null +++ b/test/bun-test.d.ts @@ -0,0 +1,8 @@ +// Minimal typings for the parts of `bun:test` used here (keeps the repo free of @types/bun). +declare module 'bun:test' { + type Fn = () => void | Promise; + export function describe(name: string, fn: () => void): void; + export function test(name: string, fn: Fn): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + export function expect(value: unknown): any; +} diff --git a/test/demo.test.ts b/test/demo.test.ts new file mode 100644 index 0000000..1ddffcd --- /dev/null +++ b/test/demo.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, test } from 'bun:test'; + +import { LEVELPLAY_DEMO } from '../src/demo'; + +describe('LEVELPLAY_DEMO', () => { + for (const platform of ['android', 'ios'] as const) { + test(platform, () => { + const ids = LEVELPLAY_DEMO[platform]; + expect(Object.keys(ids).sort()).toEqual(['appKey', 'banner', 'interstitial', 'rewarded']); + for (const v of Object.values(ids)) expect(v).toMatch(/^[a-z0-9]{8,16}$/); + expect(new Set(Object.values(ids)).size).toBe(4); + }); + } + + test('platforms differ', () => { + expect(LEVELPLAY_DEMO.android.appKey).not.toBe(LEVELPLAY_DEMO.ios.appKey); + }); +}); diff --git a/test/index.test.ts b/test/index.test.ts new file mode 100644 index 0000000..8ec0de5 --- /dev/null +++ b/test/index.test.ts @@ -0,0 +1,13 @@ +import { expect, test } from 'bun:test'; + +import * as api from '../src/index'; + +test('public exports', () => { + expect(typeof api.LevelPlay).toBe('object'); + expect(api.LEVELPLAY_DEMO.android.appKey).toBeTruthy(); +}); + +test('web implementation is used outside native platforms', async () => { + expect(await api.LevelPlay.getSdkVersion()).toEqual({ sdkVersion: 'web' }); + expect(await api.LevelPlay.getCapabilities()).toMatchObject({ banner: false }); +}); diff --git a/test/tsconfig.json b/test/tsconfig.json new file mode 100644 index 0000000..82e6f9b --- /dev/null +++ b/test/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { "noEmit": true, "declaration": false, "sourceMap": false, "inlineSources": false, "lib": ["es2020", "dom"] }, + "files": ["bun-test.d.ts", "types.ts", "web.test.ts", "demo.test.ts", "index.test.ts"] +} diff --git a/test/types.ts b/test/types.ts new file mode 100644 index 0000000..ec0e9bc --- /dev/null +++ b/test/types.ts @@ -0,0 +1,83 @@ +// Compile-only checks of the public API (`bun run test` runs `tsc -p test`). Never executed. +import type { PluginListenerHandle } from '@capacitor/core'; + +import { LEVELPLAY_DEMO, LevelPlay } from '../src'; +import type { + AdEvent, + BannerErrorEvent, + BannerEvent, + BannerResult, + Capabilities, + CreateBannerOptions, + ImpressionData, + LevelPlayPlugin, + LoadNativeAdOptions, + NativeAdEvent, + SegmentOptions, + ShowResult, +} from '../src'; + +type Equals = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 ? true : false; +function assertType(_: T): void {} + +export async function usage(plugin: LevelPlayPlugin = LevelPlay): Promise { + const ids = LEVELPLAY_DEMO.android; + const init = await plugin.initialize({ appKey: ids.appKey, userId: 'u1', consent: { gdprConsent: true } }); + assertType>(true); + + const caps: Capabilities = await plugin.getCapabilities(); + if (caps.nativeAdTemplates.includes('medium')) { + /* typed template list */ + } + + const shown: ShowResult = await plugin.showRewarded({ adUnitId: ids.rewarded, placementName: 'Home' }); + if (shown.rewarded && shown.reward) assertType>(true); + + const banner: CreateBannerOptions = { + adUnitId: ids.banner, + bannerId: 'main', + size: 'ADAPTIVE', + position: 'bottom', + offsetY: 8, + respectSafeArea: true, + }; + const res: BannerResult = await plugin.createBanner(banner); + assertType>(true); + await plugin.loadBanner({ bannerId: res.bannerId }); + await plugin.setBannerLayout({ bannerId: 'main', position: 'top' }); + await plugin.createBanner({ adUnitId: ids.banner, size: 'CUSTOM', customSize: { width: 320, height: 60 } }); + + const native: LoadNativeAdOptions = { + nativeAdId: 'n1', + template: 'small', + style: { backgroundColor: '#fff', cornerRadius: 8, titleFont: { family: 'fonts/Inter.ttf', size: 15 } }, + }; + await plugin.loadNativeAd(native); + await plugin.showNativeAd({ nativeAdId: 'n1', rect: { x: 0, y: 0, width: 300, height: 90 } }); + + const segment: SegmentOptions = { segmentName: 'whales', level: 3, isPaying: true, customParameters: { a: 'b' } }; + await plugin.setSegment(segment); + const dyn = await plugin.setDynamicUserId({ userId: 'u2' }); + assertType>(true); + await plugin.isPlacementCapped({ format: 'interstitial', placementName: 'Level_End' }); + + const handles: PluginListenerHandle[] = [ + await plugin.addListener('impressionData', (e: ImpressionData) => void e.revenue), + await plugin.addListener('bannerLoadFailed', (e: BannerErrorEvent) => void e.error.code), + await plugin.addListener('bannerLoaded', (e: BannerEvent) => void e.frame), + await plugin.addListener('nativeAdLoaded', (e: NativeAdEvent) => void e.nativeAdId), + await plugin.addListener('adInfoChanged', (e: AdEvent) => void e.adInfo?.revenue), + ]; + for (const h of handles) await h.remove(); + + // @ts-expect-error unknown banner size + await plugin.createBanner({ adUnitId: 'x', size: 'HUGE' }); + // @ts-expect-error adUnitId is required + await plugin.createBanner({ bannerId: 'x' }); + // @ts-expect-error unknown native template + await plugin.loadNativeAd({ nativeAdId: 'n', template: 'large' }); + // @ts-expect-error banner is not a full-screen format + await plugin.isPlacementCapped({ format: 'banner', placementName: 'p' }); + // @ts-expect-error demo ids are readonly + LEVELPLAY_DEMO.ios.appKey = 'x'; +} diff --git a/test/web.test.ts b/test/web.test.ts new file mode 100644 index 0000000..bf683a9 --- /dev/null +++ b/test/web.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, test } from 'bun:test'; + +import type { LevelPlayPlugin } from '../src/definitions'; +import { LevelPlayWeb } from '../src/web'; + +const web: LevelPlayPlugin = new LevelPlayWeb(); + +async function rejection(p: Promise): Promise<{ code?: string; message?: string }> { + try { + await p; + } catch (e) { + return e as { code?: string; message?: string }; + } + throw new Error('expected a rejection'); +} + +describe('web stub: rejects as unimplemented (design §11)', () => { + const cases: [string, () => Promise][] = [ + ['initialize', () => web.initialize({ appKey: 'k' })], + ['launchTestSuite', () => web.launchTestSuite()], + ['createBanner', () => web.createBanner({ adUnitId: 'u' })], + ['showBanner', () => web.showBanner({ bannerId: 'b' })], + ['setBannerLayout', () => web.setBannerLayout({ bannerId: 'b', position: 'top' })], + ['loadNativeAd', () => web.loadNativeAd({ nativeAdId: 'n' })], + ['showNativeAd', () => web.showNativeAd({ nativeAdId: 'n', rect: { x: 0, y: 0, width: 300, height: 90 } })], + ]; + for (const [name, call] of cases) { + test(name, async () => { + const err = await rejection(call()); + expect(err.code).toBe('UNIMPLEMENTED'); + }); + } +}); + +describe('web stub: no-ops and fixed results', () => { + test('void no-ops resolve undefined', async () => { + const calls: Promise[] = [ + web.setConsent({ gdprConsent: true }), + web.setMetaData({ key: 'k', value: 'v' }), + web.loadRewarded({ adUnitId: 'u' }), + web.loadInterstitial({ adUnitId: 'u' }), + web.validateIntegration(), + web.setSegment({ level: 1 }), + web.loadBanner({ bannerId: 'b' }), + web.hideBanner({ bannerId: 'b' }), + web.destroyBanner({ bannerId: 'b' }), + web.setNativeAdRect({ nativeAdId: 'n', rect: { x: 0, y: 0, width: 1, height: 1 } }), + web.hideNativeAd({ nativeAdId: 'n' }), + web.destroyNativeAd({ nativeAdId: 'n' }), + ]; + for (const r of await Promise.all(calls)) expect(r).toBeUndefined(); + }); + + test('sdk version and tracking', async () => { + expect(await web.getSdkVersion()).toEqual({ sdkVersion: 'web' }); + expect(await web.requestTrackingAuthorization()).toEqual({ status: 'unavailable' }); + expect(await web.getTrackingAuthorizationStatus()).toEqual({ status: 'unavailable' }); + }); + + test('full-screen ads never fill', async () => { + expect(await web.isReady({ adUnitId: 'u', format: 'rewarded' })).toEqual({ ready: false }); + for (const r of [await web.showRewarded({ adUnitId: 'u' }), await web.showInterstitial({ adUnitId: 'u' })]) { + expect(r.shown).toBe(false); + expect(r.rewarded).toBe(false); + expect(r.error?.code).toBe(-1); + } + }); + + test('show results are fresh copies', async () => { + const a = await web.showRewarded({ adUnitId: 'u' }); + a.shown = true; + expect((await web.showRewarded({ adUnitId: 'u' })).shown).toBe(false); + }); + + test('capabilities all false', async () => { + expect(await web.getCapabilities()).toEqual({ + banner: false, + nativeAd: false, + nativeAdTemplates: [], + impressionData: false, + adInfoChanged: false, + }); + }); + + test('user and placement helpers', async () => { + expect(await web.setDynamicUserId({ userId: 'x' })).toEqual({ valid: false }); + expect(await web.isPlacementCapped({ format: 'rewarded', placementName: 'p' })).toEqual({ capped: false }); + expect(await web.getReward({ adUnitId: 'u' })).toEqual({ name: '', amount: 0 }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 2bf6f98..d074ff1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,6 @@ "declaration": true, "esModuleInterop": true, "inlineSources": true, - "lib": ["dom", "es2017"], "module": "esnext", "moduleResolution": "node", "noFallthroughCasesInSwitch": true,