@rediads/react-native-ads 0.0.0-stage → 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ import ExpoModulesCore
2
+ import RediadsDisplay
3
+
4
+ /// Options of `start`, from `RediadsAds.start` in src/RediadsAds.ts.
5
+ struct StartOptions: Record {
6
+ @Field var accountId: String = ""
7
+ @Field var serverUrl: String = RediadsAds.defaultServerURL
8
+ @Field var testMode: Bool = false
9
+ @Field var debugLogging: Bool = false
10
+ @Field var childDirected: Bool = false
11
+ @Field var appStoreId: String?
12
+ }
13
+
14
+ /// Starts the Rediads SDK, hosts its banners as React Native views and runs interstitial and rewarded
15
+ /// ads by the ID JavaScript gives them (src/RediadsFullScreenAd.ts). Everything that touches the SDK
16
+ /// runs on the main queue, where the SDK also calls back.
17
+ public class RediadsAdsModule: Module {
18
+ /// Interstitials and rewarded ads by ID. Main queue only.
19
+ private var ads: [Int: NSObject] = [:]
20
+
21
+ public func definition() -> ModuleDefinition {
22
+ Name("RediadsAds")
23
+
24
+ Constant("sdkVersion") {
25
+ RediadsAds.sdkVersion
26
+ }
27
+
28
+ Events("onFullScreenAdEvent")
29
+
30
+ AsyncFunction("start") { (options: StartOptions, promise: Promise) in
31
+ RediadsAds.testMode = options.testMode
32
+ RediadsAds.debugLogging = options.debugLogging
33
+ RediadsAds.childDirected = options.childDirected
34
+ if let appStoreId = options.appStoreId {
35
+ RediadsAds.appStoreID = appStoreId
36
+ }
37
+ // The SDK sends the IDFA only if the user has allowed tracking (App Tracking Transparency).
38
+ // Whether to ask is the app's choice, made outside this package.
39
+ RediadsAds.start(accountId: options.accountId, serverURL: options.serverUrl) { error in
40
+ promise.resolve(error?.localizedDescription)
41
+ }
42
+ }.runOnQueue(.main)
43
+
44
+ AsyncFunction("setChildDirected") { (value: Bool) in
45
+ RediadsAds.childDirected = value
46
+ }.runOnQueue(.main)
47
+
48
+ AsyncFunction("loadInterstitial") { (adId: Int, placement: String, format: String, promise: Promise) in
49
+ let ad = RediadsInterstitial(placement: placement, format: Self.format(format))
50
+ ad.onEvent = self.forward(adId)
51
+ self.ads[adId] = ad
52
+ ad.load { error in
53
+ promise.resolve(error?.localizedDescription)
54
+ }
55
+ }.runOnQueue(.main)
56
+
57
+ AsyncFunction("loadRewarded") {
58
+ (adId: Int, placement: String, rewardType: String, rewardAmount: Int, format: String,
59
+ displaySeconds: Int, promise: Promise) in
60
+ let ad = RediadsRewarded(
61
+ placement: placement,
62
+ reward: RediadsReward(type: rewardType, amount: rewardAmount),
63
+ format: Self.format(format),
64
+ displaySeconds: displaySeconds > 0 ? displaySeconds : RediadsRewarded.defaultDisplaySeconds
65
+ )
66
+ ad.onEvent = self.forward(adId)
67
+ self.ads[adId] = ad
68
+ ad.load { error in
69
+ promise.resolve(error?.localizedDescription)
70
+ }
71
+ }.runOnQueue(.main)
72
+
73
+ AsyncFunction("isReady") { (adId: Int) -> Bool in
74
+ switch self.ads[adId] {
75
+ case let ad as RediadsInterstitial: return ad.isReady
76
+ case let ad as RediadsRewarded: return ad.isReady
77
+ default: return false
78
+ }
79
+ }.runOnQueue(.main)
80
+
81
+ AsyncFunction("show") { (adId: Int) in
82
+ guard let ad = self.ads[adId] else { return }
83
+ // The top view controller, above any modal React Native has presented.
84
+ guard let host = self.appContext?.utilities?.currentViewController() else {
85
+ let placement = (ad as? RediadsInterstitial)?.placement ?? (ad as? RediadsRewarded)?.placement ?? ""
86
+ self.sendEvent("onFullScreenAdEvent", [
87
+ "adId": adId, "type": "failed", "placement": placement,
88
+ "error": "There is no view controller to show the ad from.",
89
+ ])
90
+ return
91
+ }
92
+ if let ad = ad as? RediadsInterstitial {
93
+ ad.show(from: host)
94
+ } else if let ad = ad as? RediadsRewarded {
95
+ ad.show(from: host)
96
+ }
97
+ }.runOnQueue(.main)
98
+
99
+ AsyncFunction("destroy") { (adId: Int) in
100
+ self.ads[adId] = nil
101
+ }.runOnQueue(.main)
102
+
103
+ View(RediadsBannerSlot.self) {
104
+ Events("onAdEvent")
105
+
106
+ Prop("placement") { (view: RediadsBannerSlot, placement: String) in
107
+ view.placement = placement
108
+ }
109
+
110
+ Prop("size") { (view: RediadsBannerSlot, size: String) in
111
+ view.size = size
112
+ }
113
+
114
+ Prop("format") { (view: RediadsBannerSlot, format: String) in
115
+ view.format = format
116
+ }
117
+
118
+ OnViewDidUpdateProps { (view: RediadsBannerSlot) in
119
+ view.loadIfReady()
120
+ }
121
+ }
122
+ }
123
+
124
+ /// Sends an ad's events to JavaScript under its ID.
125
+ private func forward(_ adId: Int) -> (RediadsAdEvent) -> Void {
126
+ return { [weak self] event in
127
+ var payload: [String: Any?] = [
128
+ "adId": adId,
129
+ "type": Self.name(of: event.type),
130
+ "placement": event.placement,
131
+ ]
132
+ if let error = event.error { payload["error"] = error.localizedDescription }
133
+ if let reward = event.reward {
134
+ payload["rewardType"] = reward.type
135
+ payload["rewardAmount"] = reward.amount
136
+ }
137
+ self?.sendEvent("onFullScreenAdEvent", payload)
138
+ }
139
+ }
140
+
141
+ /// The JavaScript format names: display, video, displayAndVideo.
142
+ static func format(_ name: String) -> RediadsAdFormat {
143
+ switch name {
144
+ case "video": return .video
145
+ case "displayAndVideo": return .displayAndVideo
146
+ default: return .display
147
+ }
148
+ }
149
+
150
+ static func name(of type: RediadsAdEventType) -> String {
151
+ switch type {
152
+ case .loaded: return "loaded"
153
+ case .displayed: return "displayed"
154
+ case .failed: return "failed"
155
+ case .clicked: return "clicked"
156
+ case .presented: return "presented"
157
+ case .dismissed: return "dismissed"
158
+ case .leftApplication: return "leftApplication"
159
+ case .rewarded: return "rewarded"
160
+ @unknown default: return "unknown"
161
+ }
162
+ }
163
+ }
164
+
165
+ /// One banner slot. The banner is made once React has set the props and is kept for the life of the
166
+ /// view (JavaScript gives the view a new key when they change); the SDK refreshes it while on screen.
167
+ final class RediadsBannerSlot: ExpoView {
168
+ let onAdEvent = EventDispatcher()
169
+ var placement = ""
170
+ var size = "320x50"
171
+ var format = "display"
172
+ private var banner: RediadsBannerView?
173
+
174
+ func loadIfReady() {
175
+ guard banner == nil, !placement.isEmpty else { return }
176
+ let adSize =
177
+ size == "300x250" ? RediadsBannerView.mediumRectangle300x250 : RediadsBannerView.banner320x50
178
+ let banner = RediadsBannerView(
179
+ placement: placement, size: adSize, format: RediadsAdsModule.format(format))
180
+ banner.onEvent = { [weak self] event in
181
+ var payload: [String: Any] = [
182
+ "type": RediadsAdsModule.name(of: event.type),
183
+ "placement": event.placement,
184
+ ]
185
+ if let error = event.error { payload["error"] = error.localizedDescription }
186
+ self?.onAdEvent(payload)
187
+ }
188
+ banner.frame = CGRect(origin: .zero, size: adSize)
189
+ addSubview(banner)
190
+ self.banner = banner
191
+ banner.load()
192
+ }
193
+
194
+ override func layoutSubviews() {
195
+ super.layoutSubviews()
196
+ banner?.center = CGPoint(x: bounds.midX, y: bounds.midY)
197
+ }
198
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@rediads/react-native-ads",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.1",
4
+ "description": "Banner, interstitial and rewarded ads from the Rediads SDK for React Native apps on iOS and Android.",
5
+ "main": "build/index.js",
6
+ "types": "build/index.d.ts",
7
+ "files": [
8
+ "build/**/*.js",
9
+ "build/**/*.d.ts",
10
+ "ios/*.podspec",
11
+ "ios/*.swift",
12
+ "android/build.gradle",
13
+ "android/src/main/",
14
+ "plugin/",
15
+ "app.plugin.js",
16
+ "expo-module.config.json",
17
+ "README.md",
18
+ "LICENSE",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "scripts": {
22
+ "build": "node internal/module_scripts/build.js",
23
+ "clean": "node internal/module_scripts/clean.js",
24
+ "lint": "eslint src/ plugin/ app.plugin.js",
25
+ "prepare": "node internal/module_scripts/prepare.js"
26
+ },
27
+ "keywords": [
28
+ "react-native",
29
+ "expo",
30
+ "ads",
31
+ "advertising",
32
+ "rediads",
33
+ "prebid"
34
+ ],
35
+ "author": "Rediads (https://rediads.com)",
36
+ "license": "Apache-2.0",
37
+ "homepage": "https://rediads.com",
38
+ "devDependencies": {
39
+ "@types/react": "~19.3.0",
40
+ "eslint": "~9.39.4",
41
+ "eslint-config-universe": "^16.1.2",
42
+ "expo": "^58.0.21",
43
+ "prettier": "^3.0.0",
44
+ "react": "19.3.0",
45
+ "react-native": "0.88.1",
46
+ "typescript": "~6.0.3"
47
+ },
48
+ "peerDependencies": {
49
+ "expo": ">=58.0.0",
50
+ "react": "*",
51
+ "react-native": "*"
52
+ }
53
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Expo config plugin of @rediads/react-native-ads. It runs during `npx expo prebuild` (and
3
+ * `expo run:ios|android`, EAS Build) and points the generated projects at the native Rediads SDKs.
4
+ *
5
+ * plugins: ['@rediads/react-native-ads']
6
+ *
7
+ * With no options (apps):
8
+ * - iOS: the Rediads SDK pods are binaries in Rediads' pod list, github.com/rediads-hq/rediads-ios.
9
+ * The plugin adds it to the Podfile as a `source`, followed by CocoaPods' own (cdn.cocoapods.org):
10
+ * once a Podfile names a source, CocoaPods uses only the named ones.
11
+ * - Android: nothing to do. The SDK is on Maven Central, which Expo's android/build.gradle has.
12
+ *
13
+ * Options, for developing the SDKs themselves (local builds instead of the published ones):
14
+ *
15
+ * plugins: [
16
+ * ['@rediads/react-native-ads', {
17
+ * // A checkout of rediads-ios-sdk: the folder with RediadsDisplay.podspec. Give the AdMob and
18
+ * // GAM plugins the same path.
19
+ * iosSdkPath: '../rediads-ios-sdk',
20
+ * // The Android SDK's Maven folder (`./gradlew publishAllPublicationsToRediadsLocalRepository`
21
+ * // in rediads-android-sdk writes it), or the URL of a Maven repository that has
22
+ * // com.rediads:rediads-display.
23
+ * androidMavenRepo: '../rediads-android-sdk/build/rediads-maven',
24
+ * }],
25
+ * ]
26
+ *
27
+ * Relative paths are from the app's folder (the one with app.json). The local SDKs must have the
28
+ * versions the packages ask for (the podspecs and android/build.gradle).
29
+ *
30
+ * iOS with iosSdkPath: the pods go to the app's own target only (the first `target ... do` with
31
+ * `use_expo_modules!`), not to app extensions, which can't use the SDK (it uses UIApplication.shared).
32
+ * Android with androidMavenRepo: the folder goes to `allprojects.repositories` in android/build.gradle.
33
+ */
34
+ const { createRunOncePlugin, withPodfile, withProjectBuildGradle } = require('expo/config-plugins');
35
+ const fs = require('fs');
36
+ const path = require('path');
37
+ const { pathToFileURL } = require('url');
38
+
39
+ const pkg = require('../package.json');
40
+
41
+ const PODS = ['RediadsEngine', 'RediadsCore', 'RediadsDisplay', 'RediadsOM'];
42
+ const TAG = '@rediads/react-native-ads';
43
+ /** The Podfile block with the pod sources; the AdMob and GAM plugins add the same block. */
44
+ const SOURCES_TAG = '@rediads/react-native-ads-pod-sources';
45
+ /** Rediads' pod list first, then CocoaPods' own, which has everything else. */
46
+ const POD_SOURCES = [
47
+ { url: 'https://github.com/rediads-hq/rediads-ios.git', pattern: /^\s*source\s+['"]https:\/\/github\.com\/rediads-hq\/rediads-ios(\.git)?['"]/m },
48
+ { url: 'https://cdn.cocoapods.org/', pattern: /^\s*source\s+['"]https:\/\/cdn\.cocoapods\.org\/?['"]/m },
49
+ ];
50
+
51
+ function escapeRegExp(text) {
52
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
53
+ }
54
+
55
+ /** Removes the block an earlier prebuild added, so a changed path replaces it. */
56
+ function removeBlock(contents, comment, tag = TAG) {
57
+ const begin = escapeRegExp(`${comment} @generated begin ${tag}`);
58
+ const end = escapeRegExp(`${comment} @generated end ${tag}`);
59
+ // Exact tags (a space follows the tag): '@rediads/react-native-ads-admob' blocks must not match.
60
+ return contents.replace(new RegExp(`[ \\t]*${begin} [\\s\\S]*?${end}\\n`), '');
61
+ }
62
+
63
+ function block(comment, indent, lines, note, tag = TAG) {
64
+ return [
65
+ `${indent}${comment} @generated begin ${tag} - ${note}`,
66
+ ...lines.map((line) => `${indent}${line}`),
67
+ `${indent}${comment} @generated end ${tag}`,
68
+ '',
69
+ ].join('\n');
70
+ }
71
+
72
+ /**
73
+ * Adds Rediads' pod list and CocoaPods' own as Podfile sources, before `platform :ios` (or the
74
+ * first target). Sources the Podfile already names are left alone; running it again changes nothing.
75
+ */
76
+ function addSources(podfile) {
77
+ const contents = removeBlock(podfile, '#', SOURCES_TAG);
78
+ const missing = POD_SOURCES.filter(({ pattern }) => !pattern.test(contents));
79
+ if (missing.length === 0) return contents;
80
+ const anchor = /^platform :ios\b/m.test(contents) ? /^platform :ios\b/m : /^target '/m;
81
+ if (!anchor.test(contents)) {
82
+ throw new Error(
83
+ `${TAG}: could not find \`platform :ios\` or a target in ios/Podfile, so the Rediads pod sources could not be added.`
84
+ );
85
+ }
86
+ const lines = missing.map(({ url }) => `source '${url}'`);
87
+ const text = block('#', '', lines, "Rediads' pod list, then CocoaPods' own", SOURCES_TAG);
88
+ return contents.replace(anchor, (found) => `${text}${found}`);
89
+ }
90
+
91
+ function addPods(podfile, sdkPath) {
92
+ const contents = removeBlock(podfile, '#');
93
+ // The app's own target; extension targets (widgets, notification services) come after it.
94
+ const anchor = /^target '[^']+' do\n([ \t]*)use_expo_modules![^\n]*\n/m;
95
+ const match = contents.match(anchor);
96
+ if (!match) {
97
+ throw new Error(
98
+ `${TAG}: could not find the app target's \`use_expo_modules!\` in ios/Podfile, so the Rediads pods could not be added.`
99
+ );
100
+ }
101
+ const lines = PODS.map((name) => `pod '${name}', :path => ${JSON.stringify(sdkPath)}`);
102
+ const text = block('#', match[1], lines, 'Rediads SDK pods from a local checkout');
103
+ return contents.replace(anchor, (found) => `${found}${text}`);
104
+ }
105
+
106
+ function addMavenRepo(buildGradle, url) {
107
+ const contents = removeBlock(buildGradle, '//');
108
+ const anchor = /allprojects\s*\{\s*\n[ \t]*repositories\s*\{[^\n]*\n/;
109
+ if (!anchor.test(contents)) {
110
+ throw new Error(
111
+ `${TAG}: could not find \`allprojects { repositories { ... } }\` in android/build.gradle, so the Rediads Maven repository could not be added.`
112
+ );
113
+ }
114
+ const text = block('//', ' ', [`maven { url '${url}' }`], 'Rediads SDK from a local Maven folder');
115
+ return contents.replace(anchor, (found) => `${found}${text}`);
116
+ }
117
+
118
+ function iosSdkFolder(projectRoot, option) {
119
+ const folder = path.resolve(projectRoot, option);
120
+ if (!fs.existsSync(path.join(folder, 'RediadsDisplay.podspec'))) {
121
+ throw new Error(`${TAG}: iosSdkPath ${folder} has no RediadsDisplay.podspec.`);
122
+ }
123
+ return folder;
124
+ }
125
+
126
+ function mavenUrl(projectRoot, option) {
127
+ if (/^(https?|file):/.test(option)) return option;
128
+ const folder = path.resolve(projectRoot, option);
129
+ if (!fs.existsSync(path.join(folder, 'com', 'rediads', 'rediads-display'))) {
130
+ throw new Error(
131
+ `${TAG}: androidMavenRepo ${folder} has no com/rediads/rediads-display. Build it with ./gradlew publishAllPublicationsToRediadsLocalRepository in rediads-android-sdk.`
132
+ );
133
+ }
134
+ return pathToFileURL(folder).href;
135
+ }
136
+
137
+ /**
138
+ * @param {import('expo/config').ExpoConfig} config
139
+ * @param {{ iosSdkPath?: string, androidMavenRepo?: string } | undefined} options
140
+ */
141
+ function withRediadsAds(config, options = {}) {
142
+ const { iosSdkPath, androidMavenRepo } = options ?? {};
143
+
144
+ config = withPodfile(config, (config) => {
145
+ const contents = config.modResults.contents;
146
+ if (iosSdkPath) {
147
+ // Local pods; the pod sources aren't needed (and Rediads' list may not have this version yet).
148
+ const folder = iosSdkFolder(config.modRequest.projectRoot, iosSdkPath);
149
+ config.modResults.contents = addPods(removeBlock(contents, '#', SOURCES_TAG), folder);
150
+ } else {
151
+ // Published pods; drop local pods an earlier prebuild added.
152
+ config.modResults.contents = addSources(removeBlock(contents, '#'));
153
+ }
154
+ return config;
155
+ });
156
+
157
+ if (androidMavenRepo) {
158
+ config = withProjectBuildGradle(config, (config) => {
159
+ if (config.modResults.language !== 'groovy') {
160
+ throw new Error(`${TAG}: android/build.gradle.kts is not supported yet; add the Maven repository by hand.`);
161
+ }
162
+ const url = mavenUrl(config.modRequest.projectRoot, androidMavenRepo);
163
+ config.modResults.contents = addMavenRepo(config.modResults.contents, url);
164
+ return config;
165
+ });
166
+ }
167
+
168
+ return config;
169
+ }
170
+
171
+ module.exports = createRunOncePlugin(withRediadsAds, pkg.name, pkg.version);
172
+ module.exports.addPods = addPods;
173
+ module.exports.addSources = addSources;
174
+ module.exports.addMavenRepo = addMavenRepo;