@ad-execute-manager/ad-reward 2.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 singcl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,460 @@
1
+ # @ad-execute-manager/ad-reward
2
+
3
+ Reward ad-related classes including RewardAdFather and RewardAdNovel for ad management.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @ad-execute-manager/ad-reward
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **RewardAdFather**: Base class for reward ads with common functionality
14
+ - **RewardAdNovel**: Novel-specific reward ad implementation with enhanced features
15
+ - **AdExecuteManager**: Core ad execution management from @ad-execute-manager/core
16
+ - **TypeScript Support**: Includes TypeScript type definitions
17
+ - **Event Callbacks**: Comprehensive event callback system for ad lifecycle events
18
+ - **Error Handling**: Built-in error handling and retry mechanisms
19
+ - **Scene Support**: Scene-based ad configuration for different contexts
20
+ - **Reward Verification**: Support for reward verification and validation
21
+
22
+ ## Usage
23
+
24
+ ### RewardAdNovel
25
+
26
+ ```javascript
27
+ import { RewardAdNovel } from '@ad-execute-manager/ad-reward';
28
+
29
+ const rewardAd = RewardAdNovel.new({
30
+ sign: 'novel_reward',
31
+ preserveOnEnd: false,
32
+ needEndOnTimeout: true,
33
+ collection: {
34
+ onHalfway: (args) => {
35
+ console.log('Ad halfway:', args);
36
+ },
37
+ onShow: (args) => {
38
+ console.log('Ad shown:', args);
39
+ },
40
+ onFinish: (args) => {
41
+ console.log('Ad finished:', args);
42
+ },
43
+ onAlways: (args) => {
44
+ console.log('Ad always:', args);
45
+ },
46
+ onError: (error) => {
47
+ console.error('Ad error:', error);
48
+ }
49
+ }
50
+ });
51
+
52
+ // Initialize ad
53
+ rewardAd.initialize({
54
+ adUnitId: 'your-ad-unit-id',
55
+ retry: 3
56
+ });
57
+
58
+ // Show ad
59
+ const result = await rewardAd.addExecuteManager({
60
+ options: {
61
+ scene: 2,
62
+ timeout: 10000
63
+ }
64
+ });
65
+
66
+ console.log('Ad result:', result);
67
+ ```
68
+
69
+ ### Basic Reward Ad Usage
70
+
71
+ ```javascript
72
+ import { RewardAdNovel } from '@ad-execute-manager/ad-reward';
73
+
74
+ // Create reward ad instance
75
+ const rewardAd = RewardAdNovel.new({
76
+ sign: 'premium_content_reward',
77
+ preserveOnEnd: true,
78
+ needEndOnTimeout: true,
79
+ collection: {
80
+ onFinish: (args) => {
81
+ console.log('Reward ad finished, unlocking premium content');
82
+ // Unlock premium content logic here
83
+ unlockPremiumContent();
84
+ },
85
+ onError: (error) => {
86
+ console.error('Reward ad error:', error);
87
+ // Show error message to user
88
+ showErrorMessage('Failed to load ad. Please try again later.');
89
+ }
90
+ }
91
+ });
92
+
93
+ // Initialize ad
94
+ rewardAd.initialize({ adUnitId: 'your-ad-unit-id', retry: 3 });
95
+
96
+ // Function to unlock premium content
97
+ function unlockPremiumContent() {
98
+ // Logic to unlock premium content
99
+ console.log('Premium content unlocked!');
100
+ }
101
+
102
+ // Function to show error message
103
+ function showErrorMessage(message) {
104
+ // Logic to show error message
105
+ console.log('Error:', message);
106
+ }
107
+
108
+ // Show reward ad to unlock premium content
109
+ async function showRewardAdForPremium() {
110
+ try {
111
+ const result = await rewardAd.addExecuteManager({
112
+ options: {
113
+ scene: 2,
114
+ timeout: 15000
115
+ }
116
+ });
117
+ console.log('Reward ad result:', result);
118
+ } catch (error) {
119
+ console.error('Reward ad execution error:', error);
120
+ }
121
+ }
122
+
123
+ // Usage
124
+ // showRewardAdForPremium();
125
+ ```
126
+
127
+ ### Ad Instance Management
128
+
129
+ ```javascript
130
+ import { RewardAdNovel } from '@ad-execute-manager/ad-reward';
131
+
132
+ // Create ad instance
133
+ const rewardAd = RewardAdNovel.new({ sign: 'reward' });
134
+
135
+ // Initialize ad
136
+ rewardAd.initialize({ adUnitId: 'your-ad-unit-id', retry: 3 });
137
+
138
+ // Function to show ad based on user action
139
+ async function showAdBasedOnAction(action) {
140
+ try {
141
+ switch (action) {
142
+ case 'unlock_premium':
143
+ return await rewardAd.addExecuteManager({
144
+ options: {
145
+ scene: 2,
146
+ timeout: 15000
147
+ }
148
+ });
149
+ case 'get_coins':
150
+ return await rewardAd.addExecuteManager({
151
+ options: {
152
+ scene: 3,
153
+ timeout: 10000
154
+ }
155
+ });
156
+ case 'continue_game':
157
+ return await rewardAd.addExecuteManager({
158
+ options: {
159
+ scene: 4,
160
+ timeout: 8000
161
+ }
162
+ });
163
+ default:
164
+ throw new Error('Invalid ad action');
165
+ }
166
+ } catch (error) {
167
+ console.error('Ad error:', error);
168
+ return { success: false, error: error.message };
169
+ }
170
+ }
171
+
172
+ // Usage examples
173
+ // showAdBasedOnAction('unlock_premium');
174
+ // showAdBasedOnAction('get_coins');
175
+ // showAdBasedOnAction('continue_game');
176
+ ```
177
+
178
+ ## API
179
+
180
+ ### RewardAdFather
181
+
182
+ Base class for reward ads with common functionality.
183
+
184
+ ### RewardAdNovel
185
+
186
+ ```typescript
187
+ class RewardAdNovel extends RewardAdFather {
188
+ /**
189
+ * Builds and returns an instance of RewardAdNovel
190
+ * @param args Construction arguments
191
+ * @returns Instance of RewardAdNovel
192
+ */
193
+ static build(args: IConstructArgs): RewardAdNovel;
194
+
195
+ /**
196
+ * Gets the singleton instance of RewardAdNovel
197
+ * @returns Singleton instance of RewardAdNovel
198
+ */
199
+ static getInstance(): RewardAdNovel;
200
+
201
+ /**
202
+ * Creates a new instance of RewardAdNovel
203
+ * @param args Construction arguments
204
+ * @returns New instance of RewardAdNovel
205
+ */
206
+ static new(args: IConstructArgs): RewardAdNovel;
207
+
208
+ /**
209
+ * Initializes the ad with configuration
210
+ * @param params Ad configuration parameters
211
+ * @param callback Optional callback function
212
+ * @returns Current instance for method chaining
213
+ */
214
+ initialize(params: IRewordAdConfig, callback?: (v: IRewardedVideoAd) => void): this;
215
+
216
+ /**
217
+ * Adds execute manager and runs the ad
218
+ * @param ctx Context object with options
219
+ * @returns Promise with ad execution result
220
+ */
221
+ addExecuteManager(ctx: any): Promise<any>;
222
+
223
+ /**
224
+ * Clears the ad instance
225
+ */
226
+ clear(): void;
227
+
228
+ /**
229
+ * Shifts the ad instance
230
+ */
231
+ shift(): void;
232
+ }
233
+ ```
234
+
235
+ ## Configuration
236
+
237
+ ### Construction Arguments
238
+
239
+ When creating an ad instance, you can pass the following configuration options:
240
+
241
+ - **sign**: Unique identifier for the ad instance
242
+ - **preserveOnEnd**: Whether to preserve the instance after ad ends
243
+ - **needEndOnTimeout**: Whether to end the ad on timeout
244
+ - **collection**: Event collection object with callback functions
245
+ - **onHalfway**: Called when ad reaches halfway point
246
+ - **onShow**: Called when ad is shown
247
+ - **onFinish**: Called when ad finishes
248
+ - **onAlways**: Called always after ad operation
249
+ - **onError**: Called when ad encounters error
250
+
251
+ ### Initialize Parameters
252
+
253
+ When initializing an ad, you can pass the following parameters:
254
+
255
+ - **adUnitId**: Unique identifier for the ad unit
256
+ - **retry**: Number of retry attempts on ad error
257
+
258
+ ## Examples
259
+
260
+ ### Example 1: Premium Content Unlock
261
+
262
+ ```javascript
263
+ import { RewardAdNovel } from '@ad-execute-manager/ad-reward';
264
+
265
+ // Create reward ad instance for premium content
266
+ const premiumContentAd = RewardAdNovel.new({
267
+ sign: 'premium_content_reward',
268
+ preserveOnEnd: true,
269
+ needEndOnTimeout: true,
270
+ collection: {
271
+ onShow: () => {
272
+ console.log('Premium content reward ad shown');
273
+ // Track reward ad show event
274
+ },
275
+ onFinish: (args) => {
276
+ console.log('Premium content reward ad finished');
277
+ // Unlock premium content
278
+ unlockPremiumContent();
279
+ },
280
+ onError: (error) => {
281
+ console.error('Premium content reward ad error:', error);
282
+ // Show error message to user
283
+ showError('Failed to load reward ad. Please try again later.');
284
+ }
285
+ }
286
+ });
287
+
288
+ // Initialize ad
289
+ premiumContentAd.initialize({
290
+ adUnitId: 'your-ad-unit-id',
291
+ retry: 3
292
+ });
293
+
294
+ // Function to unlock premium content
295
+ function unlockPremiumContent() {
296
+ console.log('Unlocking premium content...');
297
+ // Premium content unlock logic here
298
+ // For example: unlock chapters, remove ads, give bonus content
299
+ }
300
+
301
+ // Function to show error message
302
+ function showError(message) {
303
+ console.error('Error:', message);
304
+ // Error message display logic here
305
+ }
306
+
307
+ // Show reward ad to unlock premium content
308
+ async function unlockPremiumWithAd() {
309
+ console.log('Showing reward ad to unlock premium content...');
310
+ try {
311
+ await premiumContentAd.addExecuteManager({
312
+ options: {
313
+ scene: 2, // Premium content unlock scene
314
+ timeout: 15000
315
+ }
316
+ });
317
+ } catch (error) {
318
+ console.error('Error showing premium content reward ad:', error);
319
+ showError('Failed to load reward ad. Please try again later.');
320
+ }
321
+ }
322
+ ```
323
+
324
+ ### Example 2: In-Game Currency Reward
325
+
326
+ ```javascript
327
+ import { RewardAdNovel } from '@ad-execute-manager/ad-reward';
328
+
329
+ // Create reward ad instance for in-game currency
330
+ const currencyAd = RewardAdNovel.new({
331
+ sign: 'game_currency_reward',
332
+ preserveOnEnd: true,
333
+ needEndOnTimeout: true,
334
+ collection: {
335
+ onShow: () => {
336
+ console.log('In-game currency reward ad shown');
337
+ // Track currency reward ad show event
338
+ },
339
+ onFinish: (args) => {
340
+ console.log('In-game currency reward ad finished');
341
+ // Give player in-game currency
342
+ giveCurrency(100); // Give 100 coins
343
+ },
344
+ onError: (error) => {
345
+ console.error('In-game currency reward ad error:', error);
346
+ // Show error message to player
347
+ showGameError('Failed to load reward ad. Please try again later.');
348
+ }
349
+ }
350
+ });
351
+
352
+ // Initialize ad
353
+ currencyAd.initialize({
354
+ adUnitId: 'your-ad-unit-id',
355
+ retry: 2
356
+ });
357
+
358
+ // Function to give in-game currency
359
+ function giveCurrency(amount) {
360
+ console.log(`Giving ${amount} coins to player...`);
361
+ // In-game currency award logic here
362
+ // For example: update player balance, show reward animation
363
+ }
364
+
365
+ // Function to show game error message
366
+ function showGameError(message) {
367
+ console.error('Game error:', message);
368
+ // Game error message display logic here
369
+ }
370
+
371
+ // Show reward ad to get in-game currency
372
+ async function getCurrencyWithAd() {
373
+ console.log('Showing reward ad to get in-game currency...');
374
+ try {
375
+ await currencyAd.addExecuteManager({
376
+ options: {
377
+ scene: 3, // In-game currency reward scene
378
+ timeout: 10000
379
+ }
380
+ });
381
+ } catch (error) {
382
+ console.error('Error showing currency reward ad:', error);
383
+ showGameError('Failed to load reward ad. Please try again later.');
384
+ }
385
+ }
386
+ ```
387
+
388
+ ### Example 3: Continue Game After Defeat
389
+
390
+ ```javascript
391
+ import { RewardAdNovel } from '@ad-execute-manager/ad-reward';
392
+
393
+ // Create reward ad instance for continue game
394
+ const continueGameAd = RewardAdNovel.new({
395
+ sign: 'continue_game_reward',
396
+ preserveOnEnd: false,
397
+ needEndOnTimeout: true,
398
+ collection: {
399
+ onShow: () => {
400
+ console.log('Continue game reward ad shown');
401
+ // Track continue game reward ad show event
402
+ },
403
+ onFinish: (args) => {
404
+ console.log('Continue game reward ad finished');
405
+ // Continue game from where player left off
406
+ continueGame();
407
+ },
408
+ onError: (error) => {
409
+ console.error('Continue game reward ad error:', error);
410
+ // Show error message and go to game over
411
+ showGameOver();
412
+ }
413
+ }
414
+ });
415
+
416
+ // Initialize ad
417
+ continueGameAd.initialize({
418
+ adUnitId: 'your-ad-unit-id',
419
+ retry: 1
420
+ });
421
+
422
+ // Function to continue game
423
+ function continueGame() {
424
+ console.log('Continuing game...');
425
+ // Game continuation logic here
426
+ // For example: restore player position, health, game state
427
+ }
428
+
429
+ // Function to show game over
430
+ function showGameOver() {
431
+ console.log('Showing game over screen...');
432
+ // Game over screen logic here
433
+ }
434
+
435
+ // Show reward ad to continue game
436
+ async function continueGameWithAd() {
437
+ console.log('Showing reward ad to continue game...');
438
+ try {
439
+ await continueGameAd.addExecuteManager({
440
+ options: {
441
+ scene: 4, // Continue game scene
442
+ timeout: 8000
443
+ }
444
+ });
445
+ } catch (error) {
446
+ console.error('Error showing continue game reward ad:', error);
447
+ showGameOver();
448
+ }
449
+ }
450
+ ```
451
+
452
+ ## Dependencies
453
+
454
+ - **@ad-execute-manager/core**: Core ad execution management
455
+ - **@ad-execute-manager/logger**: Logging utility
456
+ - **@ad-execute-manager/serializable-error**: Serializable error implementation
457
+
458
+ ## License
459
+
460
+ MIT
@@ -0,0 +1,181 @@
1
+ export default RewardAdFather;
2
+ export type IRewordAdConfig = import("./typings/ad.js").IRewordAdConfig;
3
+ export type CallbackCollection = import("./typings/ad.js").CallbackCollection;
4
+ export type RecoveredInfo = import("./typings/ad.js").RecoveredInfo;
5
+ export type IConstructArgs = import("./typings/ad.js").IConstructArgs;
6
+ export type RewardedVideoAd = import("./typings/create-rewarded-video-ad.js").RewardedVideoAd;
7
+ export type IRewardedVideoAd = {
8
+ /**
9
+ * 显示激励视频广告
10
+ */
11
+ show: () => Promise<void>;
12
+ };
13
+ /**
14
+ * @typedef IRewardedVideoAd
15
+ * @property {() => Promise.<void>} show 显示激励视频广告
16
+ */
17
+ declare class RewardAdFather {
18
+ /** @type {IRewordAdConfig | null} */
19
+ static args: IRewordAdConfig | null;
20
+ /**
21
+ * @param {IRewordAdConfig} args
22
+ */
23
+ static buildArgs(args: IRewordAdConfig): void;
24
+ /**
25
+ * 使用管理器执行广告
26
+ * @param {Object} adInstance 广告实例
27
+ * @param {Object} ctx 上下文对象,用于传递数据和状态
28
+ * @param {Object} ctx.options 广告执行选项
29
+ * @param {Object} ctx.collection 回调集合
30
+ * @returns {Promise} 广告执行结果的Promise
31
+ */
32
+ static executeWithManager(adInstance: any, ctx: {
33
+ options: any;
34
+ collection: any;
35
+ }): Promise<any>;
36
+ /**
37
+ * @param {IConstructArgs} args
38
+ */
39
+ constructor(args: IConstructArgs);
40
+ /** @private */
41
+ /** @type {Logger} */
42
+ _logger: Logger;
43
+ _adTimeoutTime: number;
44
+ _initSign: string;
45
+ _preserveOnEnd: boolean;
46
+ /**
47
+ * 激励视频实例
48
+ * @type {RewardedVideoAd | null}
49
+ */
50
+ _rewardAd: RewardedVideoAd | null;
51
+ /**
52
+ * 激励视频实例
53
+ * @type {RewardedVideoAd | null}
54
+ */
55
+ __ad__: RewardedVideoAd | null;
56
+ _ttErrorMsgs: string[];
57
+ _ttErrorCodes: number[];
58
+ __bindAdErrorForeverHandler: any;
59
+ _adConfig: {};
60
+ /**
61
+ * 初始化
62
+ * 子类可以选择覆盖此方法,或使用默认实现
63
+ * @param {IRewordAdConfig} params
64
+ * @param {(v: IRewardedVideoAd) => void} [callback] 初始化成功回调
65
+ * @returns {this} 当前实例
66
+ */
67
+ initialize(params: IRewordAdConfig, callback?: (v: IRewardedVideoAd) => void): this;
68
+ initialized(): boolean;
69
+ /**
70
+ * 激励视频展示失败时始终执行的一个方法
71
+ * @private
72
+ * @param {{errMsg: string; errCode: number}} e 错误信息
73
+ */
74
+ private __adErrorForeverHandler;
75
+ /**
76
+ * 激励视频展示失败时始终执行的一个方法
77
+ * @abstract 激励视频展示失败时始终执行的一个方法,子类需要用到时实现此方法
78
+ * @param {{errMsg: string; errCode: number}} _e 错误信息
79
+ * @returns
80
+ */
81
+ adErrorForeverHandler(_e: {
82
+ errMsg: string;
83
+ errCode: number;
84
+ }): any;
85
+ /**
86
+ * 执行广告展示
87
+ * @abstract
88
+ * @param {Object} [ctx] 上下文对象,用于传递数据和状态
89
+ * @param {IRewordAdConfig} [ctx.options] 广告执行选项
90
+ * @param {CallbackCollection} [ctx.collection] 回调集合
91
+ * @param {RecoveredInfo} [ctx.recovered] 恢复重试信息
92
+ * @param {Function} next 执行下一个任务的回调函数,在洋葱模型中手动调用以继续执行流程
93
+ * @returns {Promise<unknown>} 广告执行结果的Promise
94
+ * @throws {Error} 子类必须实现此方法
95
+ */
96
+ ad(ctx?: {
97
+ options?: IRewordAdConfig;
98
+ collection?: CallbackCollection;
99
+ recovered?: RecoveredInfo;
100
+ }, next?: Function): Promise<unknown>;
101
+ /**
102
+ * 确保广告按顺序执行
103
+ * @param {Object} [ctx] 上下文对象,用于传递数据和状态
104
+ * @param {IRewordAdConfig} [ctx.options] 广告执行选项
105
+ * @param {CallbackCollection} [ctx.collection] 回调集合
106
+ * @returns {Promise.<unknown>} 广告执行结果的Promise
107
+ */
108
+ addExecuteManager(ctx?: {
109
+ options?: IRewordAdConfig;
110
+ collection?: CallbackCollection;
111
+ }): Promise<unknown>;
112
+ destroy(): void;
113
+ /**
114
+ * 清理广告实例
115
+ * @abstract 清理广告实例,子类必须实现此方法
116
+ */
117
+ clear(): void;
118
+ /**
119
+ * 任务执行完成后始终执行的一个方法
120
+ * @abstract 任务执行完成后始终执行的一个方法,子类需要用到时实现此方法
121
+ * @param {object} [_args] 执行结果信息
122
+ * @param {number} [_args.scene] 场景信息
123
+ * @param {string} _args.id 任务id
124
+ * @param {object} [_args.apiError] 广告api错误信息
125
+ * @param {number} [_args.adTypeR] 广告类型 1 激励视频 2插屏广告
126
+ * @param {object} _args.recovered 后台恢复重试
127
+ * @param {boolean} [_args.recovered.retry] 后台恢复预估是否重试
128
+ * @param {number} [_args.recovered.count] 后台恢复预估重试次数
129
+ * @param {string} [_args.recovered.message] 后台恢复预估重试原因
130
+ */
131
+ record(_args?: {
132
+ scene?: number;
133
+ id: string;
134
+ apiError?: object;
135
+ adTypeR?: number;
136
+ recovered: {
137
+ retry?: boolean;
138
+ count?: number;
139
+ message?: string;
140
+ };
141
+ }): this;
142
+ /**
143
+ *
144
+ * @param {({isEnded: boolean, count: number}) => void} callback
145
+ */
146
+ onClose(callback: ({ isEnded: boolean, count: number }: any) => void): void;
147
+ /**
148
+ *
149
+ * @param {({isEnded: boolean, count: number}) => void} callback
150
+ */
151
+ offClose(callback: ({ isEnded: boolean, count: number }: any) => void): void;
152
+ /**
153
+ * show
154
+ * @returns { Promise.<void>}
155
+ * @params {{errMsg: string; errCode: number}} err
156
+ */
157
+ show(): Promise<void>;
158
+ /**
159
+ * load
160
+ * @returns { Promise.<void>}
161
+ */
162
+ load(): Promise<void>;
163
+ /**
164
+ *
165
+ * @param {({errMsg: string; errCode: number}) => void} callback
166
+ */
167
+ onError(callback: any): void;
168
+ /**
169
+ *
170
+ * @param {({errMsg: string; errCode: number}) => void} callback
171
+ */
172
+ offError(callback: any): void;
173
+ onLoad(callback: any): void;
174
+ offLoad(callback: any): void;
175
+ /**
176
+ * 站位方法,没有任何左右
177
+ * @returns
178
+ */
179
+ placeholder(): any;
180
+ }
181
+ import { Logger } from '@ad-execute-manager/logger';