clashofclans.js 1.5.4 → 2.0.0-dev.2c5b083

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +2 -1
  3. package/README.md +39 -110
  4. package/dist/client/Client.d.ts +177 -0
  5. package/dist/client/Client.js +237 -0
  6. package/dist/client/EventManager.d.ts +86 -0
  7. package/dist/client/EventManager.js +279 -0
  8. package/dist/index.d.ts +9 -0
  9. package/dist/index.js +21 -0
  10. package/dist/rest/HTTPError.d.ts +24 -0
  11. package/dist/rest/HTTPError.js +42 -0
  12. package/dist/rest/RESTManager.d.ts +56 -0
  13. package/dist/rest/RESTManager.js +123 -0
  14. package/dist/rest/RequestHandler.d.ts +162 -0
  15. package/dist/rest/RequestHandler.js +198 -0
  16. package/dist/rest/Throttler.d.ts +31 -0
  17. package/dist/rest/Throttler.js +86 -0
  18. package/dist/struct/Achievement.d.ts +25 -0
  19. package/dist/struct/Achievement.js +28 -0
  20. package/dist/struct/Badge.d.ts +16 -0
  21. package/dist/struct/Badge.js +27 -0
  22. package/dist/struct/ChatLanguage.d.ts +11 -0
  23. package/dist/struct/ChatLanguage.js +12 -0
  24. package/dist/struct/Clan.d.ts +64 -0
  25. package/dist/struct/Clan.js +44 -0
  26. package/dist/struct/ClanMember.d.ts +32 -0
  27. package/dist/struct/ClanMember.js +28 -0
  28. package/dist/struct/ClanWar.d.ts +137 -0
  29. package/dist/struct/ClanWar.js +198 -0
  30. package/dist/struct/ClanWarLeagueGroup.d.ts +63 -0
  31. package/dist/struct/ClanWarLeagueGroup.js +85 -0
  32. package/dist/struct/ClanWarLog.d.ts +54 -0
  33. package/dist/struct/ClanWarLog.js +46 -0
  34. package/dist/struct/Icon.d.ts +16 -0
  35. package/dist/struct/Icon.js +27 -0
  36. package/dist/struct/Label.d.ts +12 -0
  37. package/dist/struct/Label.js +13 -0
  38. package/dist/struct/League.d.ts +14 -0
  39. package/dist/struct/League.js +18 -0
  40. package/dist/struct/LegendStatistics.d.ts +18 -0
  41. package/dist/struct/LegendStatistics.js +17 -0
  42. package/dist/struct/Location.d.ts +15 -0
  43. package/dist/struct/Location.js +14 -0
  44. package/dist/struct/Player.d.ts +78 -0
  45. package/dist/struct/Player.js +72 -0
  46. package/dist/struct/PlayerClan.d.ts +19 -0
  47. package/dist/struct/PlayerClan.js +19 -0
  48. package/dist/struct/Ranking.d.ts +58 -0
  49. package/dist/struct/Ranking.js +50 -0
  50. package/dist/struct/Season.d.ts +19 -0
  51. package/dist/struct/Season.js +21 -0
  52. package/dist/struct/Unit.d.ts +68 -0
  53. package/dist/struct/Unit.js +90 -0
  54. package/dist/struct/WarLeague.d.ts +11 -0
  55. package/dist/struct/WarLeague.js +16 -0
  56. package/dist/struct/index.d.ts +19 -0
  57. package/dist/struct/index.js +31 -0
  58. package/dist/types/index.d.ts +350 -0
  59. package/dist/types/index.js +2 -0
  60. package/dist/util/Constants.d.ts +41 -0
  61. package/dist/util/Constants.js +122 -0
  62. package/dist/util/Util.d.ts +18 -0
  63. package/dist/util/Util.js +53 -0
  64. package/dist/util/raw.json +1 -0
  65. package/package.json +109 -36
  66. package/src/index.d.ts +0 -811
  67. package/src/index.js +0 -5
  68. package/src/struct/Client.js +0 -481
  69. package/src/util/Extension.js +0 -130
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
+
5
+ ## 2.0.0 (2021-11-26)
6
+
7
+ This new version is a complete TypeScript rewrite to convert everything from plain (literal JSON) objects to class (constructor) objects and support a lot more features.
8
+
9
+ ### Features
10
+
11
+ - API Date Parser and Request Retries ([#26](https://github.com/clashperk/clashofclans.js/issues/26)) ([94585f3](https://github.com/clashperk/clashofclans.js/commit/94585f3a84a7175b2d07872f9eb9e42372b95e12))
12
+ - EventManager and Custom Events ([#37](https://github.com/clashperk/clashofclans.js/issues/37)) ([5027ae6](https://github.com/clashperk/clashofclans.js/commit/5027ae663a8e07175e17384c7e5706f4a1a7afb4))
13
+ - Email Password Login ([#31](https://github.com/clashperk/clashofclans.js/issues/31)) ([4153cd3](https://github.com/clashperk/clashofclans.js/commit/4153cd37ea0e1c71550b9e892105b84d5a407e23))
14
+ - QueueThrottler and BatchThrottler ([#34](https://github.com/clashperk/clashofclans.js/issues/34)) ([3a8f051](https://github.com/clashperk/clashofclans.js/commit/3a8f051552e93b98f89bc7d524acdecddf242718))
15
+ - Override Request Options ([#36](https://github.com/clashperk/clashofclans.js/issues/36)) ([42d7fdd](https://github.com/clashperk/clashofclans.js/commit/42d7fdd36262cc46f23b731f8cffb9daea19d3b0))
16
+ - Internal Caching Options ([#53](https://github.com/clashperk/clashofclans.js/issues/53)) ([984451d](https://github.com/clashperk/clashofclans.js/commit/30ea3240c11866008d0dae514468c0fdbb34ffd0))
17
+ - Raw Data for Player Units ([#65](https://github.com/clashperk/clashofclans.js/pull/65)) ([aa1696](https://github.com/clashperk/clashofclans.js/commit/aa1696243d96d4fed0250b4282c60522a6482343))
package/LICENSE CHANGED
@@ -1,6 +1,7 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2020 - 2021 ClashPerk
3
+ Copyright (c) 2020 - 2021 csuvajit
4
+ Copyright (c) 2020 - 2021 TheLearneer
4
5
 
5
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
7
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -4,136 +4,65 @@
4
4
 
5
5
  ### JavaScript library for interacting with the Clash of Clans API
6
6
 
7
- [![ESLint](https://github.com/clashperk/clashofclans.js/actions/workflows/node.js.yml/badge.svg)](https://github.com/clashperk/clashofclans.js/actions/workflows/node.js.yml)
8
- [![Docs](https://github.com/clashperk/clashofclans.js/actions/workflows/docs.yml/badge.svg)](https://github.com/clashperk/clashofclans.js/actions/workflows/docs.yml)
7
+ [![ESLint](https://github.com/clashperk/clashofclans.js/actions/workflows/eslint.yml/badge.svg)](https://github.com/clashperk/clashofclans.js/actions/workflows/node.js.yml)
9
8
  [![Logo](https://img.shields.io/npm/v/clashofclans.js.svg?maxAge=3600)](https://www.npmjs.com/package/clashofclans.js)
10
9
 
11
10
  </div>
12
11
 
13
12
  ### Installation
14
- - **`npm i clashofclans.js`**
15
- - **Node.js v14.0.0 or newer is required.**
13
+
14
+ - **`npm i clashofclans.js`**
15
+ - **Node.js v14 or newer is required.**
16
16
 
17
17
  ### Links
18
18
 
19
- - [Documentation](https://clashofclans.js.org/api/)
20
- - [Clash of Clans Developer Website](https://developer.clashofclans.com/)
21
- - [Clash of Clans API Community Discord](https://discord.gg/Eaja7gJ)
19
+ - [Documentation](https://clashofclans.js.org/docs/)
20
+ - [Clash of Clans Developer Website](https://developer.clashofclans.com/)
21
+ - [Clash of Clans API Community Discord](https://discord.gg/Eaja7gJ)
22
22
 
23
- ### Example
23
+ ### Examples
24
24
 
25
25
  ```js
26
26
  const { Client } = require('clashofclans.js');
27
- const client = new Client({ keys: ['API_KEY'] });
28
-
29
- (async function() {
30
- const data = await client.locations('#8QU8J9LP', { limit: 1 });
31
- console.log(data);
32
- })();
33
- ```
34
-
35
- ### Response
36
-
37
- ```json
38
- {
39
- "items": [
40
- {
41
- "id": 32000000,
42
- "name": "Europe",
43
- "isCountry": false
44
- }
45
- ],
46
- "paging": {},
47
- "statusCode": 200,
48
- "ok": true,
49
- "maxAge": 600000
50
- }
51
- ```
52
-
53
- ### What is **`maxAge`**?
54
-
55
- The `maxAge` ([Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)) is the maximum amount of time in milliseconds (converted) which shows how long until a fresh data is available.
56
-
57
- ### Validation
27
+ const client = new Client();
58
28
 
59
- It's recommended to see if a data is available before performing operations or reading data from it.
60
- You can check this with `data.ok` property.
29
+ (async function () {
30
+ await client.login({ email: 'developer@email.com', password: '***' });
61
31
 
62
- ```js
63
- (async function() {
64
- const data = await client.clan('#WRONG_TAG');
65
- console.log(data);
66
- if (!data.ok) return; // Invalid Tag
32
+ const clan = await client.getClan('#2PP');
33
+ console.log(`${clan.name} (${clan.tag})`);
67
34
  })();
68
35
  ```
69
36
 
70
- ```json
71
- {
72
- "reason": "notFound",
73
- "statusCode": 404,
74
- "ok": false,
75
- "maxAge": 600000
76
- }
77
- ```
78
-
79
- ### Status Codes
80
- - **200:** Successful Response.
81
- - **400:** Client provided incorrect parameters for the request.
82
- - **403:** Access denied, either because of missing/incorrect credentials or used API token does not grant access to the requested resource.
83
- - **404:** Resource was not found.
84
- - **429:** Request was throttled, because amount of requests was above the threshold defined for the used API token.
85
- - **500:** Unknown error happened when handling the request.
86
- - **503:** Service is temporarily unavailable because of maintenance.
87
- - **504:** Request Timeout.
88
-
89
- ## Methods
90
-
91
- | Methods | Description |
92
- | --------------------------------------------------------------------- | --------------------------------- |
93
- | [init(options)](https://clashofclans.js.org/api#Client#init) | Initialize Extension class and create keys |
94
- | [parseTag(tag)](https://clashofclans.js.org/api#Client#parseTag) | Parse a clan or player Tag |
95
- | [clans([options])](https://clashofclans.js.org/api#Client#clans) | Search clans |
96
- | [clan(clanTag)](https://clashofclans.js.org/api#Client#clan) | Get clan information |
97
- | [clanMembers(clanTag, [options])](https://clashofclans.js.org/api#Client#clanMembers) | List clan members |
98
- | [detailedClanMembers(members)](https://clashofclans.js.org/api#Client#detailedClanMembers) | Detailed clan members |
99
- | [clanWarLog(clanTag, [options])](https://clashofclans.js.org/api#Client#clanWarLog) | Retrieve clan's clan war log |
100
- | [currentClanWar(clanTag, [options])](https://clashofclans.js.org/api#Client#currentClanWar) | Information about clan's current clan war |
101
- | [clanWarLeague(clanTag)](https://clashofclans.js.org/api#Client#clanWarLeague) | Information about clan's current clan war league group |
102
- | [clanWarLeagueWar(warTag)](https://clashofclans.js.org/api#Client#clanWarLeagueWar) | Information about individual clan war league war |
103
- | [player(playerTag)](https://clashofclans.js.org/api#Client#player) | Get player information |
104
- | [verifyPlayerToken(playerTag, token)](https://clashofclans.js.org/api#Client#verifyPlayerToken) | Verify player API token |
105
- | [leagues([options])](https://clashofclans.js.org/api#Client#leagues) | List Leagues |
106
- | [league(leagueId)](https://clashofclans.js.org/api#Client#league) | Get league information |
107
- | [leagueSeason(leagueId, [options])](https://clashofclans.js.org/api#Client#leagueSeason) | Get league seasons |
108
- | [leagueRanking(leagueId, seasonId, [options])](https://clashofclans.js.org/api#Client#leagueRanking) | Get league season rankings |
109
- | [warLeagues([options])](https://clashofclans.js.org/api#Client#warLeagues) | List war leagues |
110
- | [warLeague(leagueId)](https://clashofclans.js.org/api#Client#warLeague) | Get war league information |
111
- | [locations([options])](https://clashofclans.js.org/api#Client#locations) | List locations |
112
- | [location(locationId)](https://clashofclans.js.org/api#Client#location) | Get information about specific location |
113
- | [clanRanks(locationId, [options])](https://clashofclans.js.org/api#Client#clanRanks) | Get clan rankings for a specific location |
114
- | [playerRanks(locationId, [options])](https://clashofclans.js.org/api#Client#playerRanks) | Get player rankings for a specific location |
115
- | [versusClanRanks(locationId, [options])](https://clashofclans.js.org/api#Client#versusClanRanks) | Get clan versus rankings for a specific location |
116
- | [versusPlayerRanks(locationId, [options])](https://clashofclans.js.org/api#Client#versusPlayerRanks) | Get player versus rankings for a specific location |
117
- | [clanLabels([options])](https://clashofclans.js.org/api#Client#clanLabels) | List clan labels |
118
- | [playerLabels([options])](https://clashofclans.js.org/api#Client#playerLabels) | List player labels |
119
- | [goldPassSeason()](https://clashofclans.js.org/api#Client#goldPassSeason) | Get information about the current gold pass season |
120
-
121
- ### Create API Token
122
-
123
- This method is for creating API keys for the external IP the code is running on. Therefore no static IP is required and always ready to be deployed on Serverless platform like Heroku.
37
+ ### Custom Event
124
38
 
125
39
  ```js
126
- const { Client } = require('clashofclans.js');
127
- const client = new Client();
128
-
129
- (async () => {
130
- await client.init({ email: '', password: '' });
131
- // you would have to run the `init` method just for once.
132
-
133
- const data = await client.clan('#2PP');
134
- console.log(data);
40
+ const { Client, BatchThrottler } = require('clashofclans.js');
41
+ const client = new Client({
42
+ cache: true,
43
+ retryLimit: 1,
44
+ restRequestTimeout: 5000,
45
+ throttler: new BatchThrottler(20)
46
+ });
47
+
48
+ client.events.addClans(['#8QU8J9LP', '#8P2QG08P']);
49
+ client.events.setClanEvent({
50
+ name: 'clanDescriptionChange',
51
+ filter: (oldClan, newClan) => {
52
+ return oldClan.description !== newClan.description;
53
+ }
54
+ });
55
+
56
+ client.on('clanDescriptionChange', (oldClan, newClan) => {
57
+ console.log(oldClan.description, newClan.description);
58
+ });
59
+
60
+ (async function () {
61
+ await client.login({ email: 'developer@email.com', password: '***' });
62
+ await client.events.init();
135
63
  })();
136
64
  ```
137
65
 
138
66
  ### Disclaimer
139
- > This content is not affiliated with, endorsed, sponsored, or specifically approved by Supercell and Supercell is not responsible for it. For more information see [Supercell’s Fan Content Policy](https://supercell.com/en/fan-content-policy/).
67
+
68
+ > This content is not affiliated with, endorsed, sponsored, or specifically approved by Supercell and Supercell is not responsible for it. For more information see [Supercell's Fan Content Policy](https://supercell.com/en/fan-content-policy/).
@@ -0,0 +1,177 @@
1
+ /// <reference types="node" />
2
+ import { ClanSearchOptions, SearchOptions, ClientOptions, InitOptions, OverrideOptions } from '../rest/RequestHandler';
3
+ import { EVENTS, CWL_ROUNDS } from '../util/Constants';
4
+ import { RESTManager } from '../rest/RESTManager';
5
+ import { EventManager } from './EventManager';
6
+ import { EventEmitter } from 'events';
7
+ import { Util } from '../util/Util';
8
+ import { Clan, ClanMember, ClanWar, ClanWarLog, League, Location, Player, WarLeague, RankedClan, RankedPlayer, Label, GoldPassSeason, ClanWarLeagueGroup } from '../struct';
9
+ /**
10
+ * Represents Clash of Clans API Client.
11
+ * ```js
12
+ * const { Client } = require('clashofclans.js');
13
+ * const client = new Client({ keys: ['***'] });
14
+ * ```
15
+ */
16
+ export declare class Client extends EventEmitter {
17
+ /** Event Manager for the client. */
18
+ readonly events: EventManager;
19
+ /** REST Handler of the client. */
20
+ readonly rest: RESTManager;
21
+ constructor(options?: ClientOptions);
22
+ /** Contains various general-purpose utility methods. */
23
+ get util(): typeof Util;
24
+ /** Whether the API is in maintenance break. */
25
+ get inMaintenance(): boolean;
26
+ /**
27
+ * Initialize the client to create keys.
28
+ * @example
29
+ * ```
30
+ * const client = new Client();
31
+ * client.login({ email: 'developer@email.com', password: '***' });
32
+ * ```
33
+ */
34
+ login(options: InitOptions): Promise<string[]>;
35
+ /** Set Clash of Clans API keys. */
36
+ setKeys(keys: string[]): this;
37
+ /** Search all clans by name and/or filtering the results using various criteria. */
38
+ getClans(options: ClanSearchOptions): Promise<Clan[]>;
39
+ /** Get information about a clan. */
40
+ getClan(clanTag: string, options?: OverrideOptions): Promise<Clan>;
41
+ /** Get list of clan members. */
42
+ getClanMembers(clanTag: string, options?: SearchOptions): Promise<ClanMember[]>;
43
+ /** Get clan war log. */
44
+ getClanWarLog(clanTag: string, options?: SearchOptions): Promise<ClanWarLog[]>;
45
+ /** Get info about currently running war (normal or friendly) in the clan. */
46
+ getClanWar(clanTag: string, options?: OverrideOptions): Promise<ClanWar>;
47
+ /**
48
+ * Get info about currently running war in the clan.
49
+ * @example
50
+ * ```ts
51
+ * await client.getCurrentWar('#8QU8J9LP');
52
+ * ```
53
+ * @example
54
+ * ```ts
55
+ * await client.getCurrentWar({ clanTag: '#8QU8J9LP', round: 'PREVIOUS_ROUND' });
56
+ * ```
57
+ */
58
+ getCurrentWar(clanTag: string | {
59
+ clanTag: string;
60
+ round?: keyof typeof CWL_ROUNDS;
61
+ }, options?: OverrideOptions): Promise<ClanWar | null>;
62
+ /**
63
+ * Get info about currently running CWL round.
64
+ * @example
65
+ * ```ts
66
+ * await client.getLeagueWar('#8QU8J9LP');
67
+ * ```
68
+ * @example
69
+ * ```ts
70
+ * await client.getLeagueWar({ clanTag: '#8QU8J9LP', round: 'PREVIOUS_ROUND' });
71
+ * ```
72
+ */
73
+ getLeagueWar(clanTag: string | {
74
+ clanTag: string;
75
+ round?: keyof typeof CWL_ROUNDS;
76
+ }, options?: OverrideOptions): Promise<ClanWar | null>;
77
+ private _getCurrentLeagueWars;
78
+ private _getClanWars;
79
+ /** Get information about clan war league. */
80
+ getClanWarLeagueGroup(clanTag: string, options?: OverrideOptions): Promise<ClanWarLeagueGroup>;
81
+ /** Get info about a CWL round by WarTag. */
82
+ getClanWarLeagueRound(warTag: string | {
83
+ warTag: string;
84
+ clanTag?: string;
85
+ }, options?: OverrideOptions): Promise<ClanWar>;
86
+ /** Get information about a player by tag. */
87
+ getPlayer(playerTag: string, options?: OverrideOptions): Promise<Player>;
88
+ /** Verify Player API token that can be found from the Game settings. */
89
+ verifyPlayerToken(playerTag: string, token: string, options?: OverrideOptions): Promise<boolean>;
90
+ /** Get list of Leagues. */
91
+ getLeagues(options?: SearchOptions): Promise<League[]>;
92
+ /** Get Legend League season Ids. */
93
+ getLeagueSeasons(options?: SearchOptions): Promise<string[]>;
94
+ /** Get Legend League season rankings by season Id. */
95
+ getSeasonRankings(seasonId: string, options?: SearchOptions): Promise<RankedPlayer[]>;
96
+ /** Get list of Clan War Leagues. */
97
+ getWarLeagues(options?: SearchOptions): Promise<WarLeague[]>;
98
+ /** Get list of Locations. */
99
+ getLocations(options?: SearchOptions): Promise<Location[]>;
100
+ /** Get clan rankings for a specific location. */
101
+ getClanRanks(locationId: number | 'global', options?: SearchOptions): Promise<RankedClan[]>;
102
+ /** Get player rankings for a specific location. */
103
+ getPlayerRanks(locationId: number | 'global', options?: SearchOptions): Promise<RankedPlayer[]>;
104
+ /** Get clan versus rankings for a specific location. */
105
+ getVersusClanRanks(locationId: number | 'global', options?: SearchOptions): Promise<RankedClan[]>;
106
+ /** Get player versus rankings for a specific location. */
107
+ getVersusPlayerRanks(locationId: number | 'global', options?: SearchOptions): Promise<RankedPlayer[]>;
108
+ /** Get list of clan labels. */
109
+ getClanLabels(options?: SearchOptions): Promise<Label[]>;
110
+ /** Get list of player labels. */
111
+ getPlayerLabels(options?: SearchOptions): Promise<Label[]>;
112
+ /** Get info about gold pass season. */
113
+ getGoldPassSeason(options?: OverrideOptions): Promise<GoldPassSeason>;
114
+ /**
115
+ * Emits when a new season starts.
116
+ *
117
+ * **Parameters**
118
+ *
119
+ * | Name | Type | Description |
120
+ * | :--: | :------: | :-------------------: |
121
+ * | `id` | `string` | Id of the new season. |
122
+ * @public
123
+ * @event
124
+ */
125
+ private static newSeasonStart;
126
+ /**
127
+ * Emits when maintenance break starts in the API.
128
+ * @public
129
+ * @event
130
+ */
131
+ private static maintenanceStart;
132
+ /**
133
+ * Emits when maintenance break ends in the API.
134
+ *
135
+ * **Parameters**
136
+ *
137
+ * | Name | Type | Description |
138
+ * | :--------: | :------: | :------------------------------------------------: |
139
+ * | `duration` | `number` | Duration of the maintenance break in milliseconds. |
140
+ * @public
141
+ * @event
142
+ */
143
+ private static maintenanceEnd;
144
+ /** @internal */
145
+ on<K extends keyof ClientEvents>(event: K, listeners: (...args: ClientEvents[K]) => void): this;
146
+ /** @internal */
147
+ on<S extends keyof CustomEvents>(event: Exclude<S, keyof ClientEvents>, listeners: (...args: CustomEvents[S]) => void): this;
148
+ /** @internal */ on<S extends string | symbol>(event: Exclude<S, keyof ClientEvents>, listeners: (...args: any[]) => void): this;
149
+ /** @internal */
150
+ once<K extends keyof ClientEvents>(event: K, listeners: (...args: ClientEvents[K]) => void): this;
151
+ /** @internal */
152
+ once<S extends keyof CustomEvents>(event: Exclude<S, keyof ClientEvents>, listeners: (...args: CustomEvents[S]) => void): this;
153
+ /** @internal */ once<S extends string | symbol>(event: Exclude<S, keyof ClientEvents>, listeners: (...args: any[]) => void): this;
154
+ /** @internal */
155
+ emit<K extends keyof ClientEvents>(event: K, ...args: ClientEvents[K]): boolean;
156
+ /** @internal */
157
+ emit<S extends keyof CustomEvents>(event: Exclude<S, keyof ClientEvents>, ...args: CustomEvents[S]): this;
158
+ /** @internal */ emit<S extends string | symbol>(event: Exclude<S, keyof ClientEvents>, ...args: any[]): boolean;
159
+ }
160
+ interface ClientEvents {
161
+ [EVENTS.NEW_SEASON_START]: [id: string];
162
+ [EVENTS.MAINTENANCE_START]: [];
163
+ [EVENTS.MAINTENANCE_END]: [duration: number];
164
+ [EVENTS.CLAN_LOOP_START]: [];
165
+ [EVENTS.CLAN_LOOP_END]: [];
166
+ [EVENTS.PLAYER_LOOP_START]: [];
167
+ [EVENTS.PLAYER_LOOP_END]: [];
168
+ [EVENTS.WAR_LOOP_START]: [];
169
+ [EVENTS.WAR_LOOP_END]: [];
170
+ [EVENTS.ERROR]: [error: unknown];
171
+ }
172
+ interface CustomEvents {
173
+ [key: `clan${string}`]: [oldClan: Clan, newClan: Clan];
174
+ [key: `war${string}`]: [oldWar: ClanWar, newWar: ClanWar];
175
+ [key: `player${string}`]: [oldPlayer: Player, newPlayer: Player];
176
+ }
177
+ export {};
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Client = void 0;
4
+ const Constants_1 = require("../util/Constants");
5
+ const HTTPError_1 = require("../rest/HTTPError");
6
+ const RESTManager_1 = require("../rest/RESTManager");
7
+ const EventManager_1 = require("./EventManager");
8
+ const events_1 = require("events");
9
+ const Util_1 = require("../util/Util");
10
+ const struct_1 = require("../struct");
11
+ /**
12
+ * Represents Clash of Clans API Client.
13
+ * ```js
14
+ * const { Client } = require('clashofclans.js');
15
+ * const client = new Client({ keys: ['***'] });
16
+ * ```
17
+ */
18
+ class Client extends events_1.EventEmitter {
19
+ constructor(options) {
20
+ super();
21
+ this.rest = new RESTManager_1.RESTManager(options);
22
+ this.events = new EventManager_1.EventManager(this);
23
+ }
24
+ /** Contains various general-purpose utility methods. */
25
+ get util() {
26
+ return Util_1.Util;
27
+ }
28
+ /** Whether the API is in maintenance break. */
29
+ get inMaintenance() {
30
+ // @ts-expect-error
31
+ return this.events._inMaintenance;
32
+ }
33
+ /**
34
+ * Initialize the client to create keys.
35
+ * @example
36
+ * ```
37
+ * const client = new Client();
38
+ * client.login({ email: 'developer@email.com', password: '***' });
39
+ * ```
40
+ */
41
+ login(options) {
42
+ return this.rest.handler.init(options);
43
+ }
44
+ /** Set Clash of Clans API keys. */
45
+ setKeys(keys) {
46
+ this.rest.handler.setKeys(keys);
47
+ return this;
48
+ }
49
+ /** Search all clans by name and/or filtering the results using various criteria. */
50
+ async getClans(options) {
51
+ const { data } = await this.rest.getClans(options);
52
+ // @ts-expect-error
53
+ return data.items.map((clan) => new struct_1.Clan(this, clan));
54
+ }
55
+ /** Get information about a clan. */
56
+ async getClan(clanTag, options) {
57
+ const { data } = await this.rest.getClan(clanTag, options);
58
+ return new struct_1.Clan(this, data);
59
+ }
60
+ /** Get list of clan members. */
61
+ async getClanMembers(clanTag, options) {
62
+ const { data } = await this.rest.getClanMembers(clanTag, options);
63
+ return data.items.map((entry) => new struct_1.ClanMember(this, entry));
64
+ }
65
+ /** Get clan war log. */
66
+ async getClanWarLog(clanTag, options) {
67
+ const { data } = await this.rest.getClanWarLog(clanTag, options);
68
+ return data.items.map((entry) => new struct_1.ClanWarLog(this, entry));
69
+ }
70
+ /** Get info about currently running war (normal or friendly) in the clan. */
71
+ async getClanWar(clanTag, options) {
72
+ const { data, maxAge, path, status } = await this.rest.getCurrentWar(clanTag, options);
73
+ if (data.state === 'notInWar') {
74
+ throw new HTTPError_1.HTTPError(HTTPError_1.NotInWarError, status, path, maxAge);
75
+ }
76
+ return new struct_1.ClanWar(this, data, { clanTag, maxAge });
77
+ }
78
+ /**
79
+ * Get info about currently running war in the clan.
80
+ * @example
81
+ * ```ts
82
+ * await client.getCurrentWar('#8QU8J9LP');
83
+ * ```
84
+ * @example
85
+ * ```ts
86
+ * await client.getCurrentWar({ clanTag: '#8QU8J9LP', round: 'PREVIOUS_ROUND' });
87
+ * ```
88
+ */
89
+ async getCurrentWar(clanTag, options) {
90
+ const args = typeof clanTag === 'string' ? { clanTag } : { clanTag: clanTag.clanTag, round: clanTag.round };
91
+ try {
92
+ return await this.getClanWar(args.clanTag, options);
93
+ }
94
+ catch (e) {
95
+ if (e instanceof HTTPError_1.HTTPError && [200, 403].includes(e.status)) {
96
+ return this.getLeagueWar({ clanTag: args.clanTag, round: args.round }, options);
97
+ }
98
+ throw e;
99
+ }
100
+ }
101
+ /**
102
+ * Get info about currently running CWL round.
103
+ * @example
104
+ * ```ts
105
+ * await client.getLeagueWar('#8QU8J9LP');
106
+ * ```
107
+ * @example
108
+ * ```ts
109
+ * await client.getLeagueWar({ clanTag: '#8QU8J9LP', round: 'PREVIOUS_ROUND' });
110
+ * ```
111
+ */
112
+ async getLeagueWar(clanTag, options) {
113
+ const args = typeof clanTag === 'string' ? { clanTag } : { clanTag: clanTag.clanTag, round: clanTag.round };
114
+ const state = (args.round && Constants_1.CWL_ROUNDS[args.round]) ?? 'inWar'; // eslint-disable-line
115
+ const data = await this.getClanWarLeagueGroup(args.clanTag, options);
116
+ const rounds = data.rounds.filter((round) => !round.warTags.includes('#0'));
117
+ if (!rounds.length)
118
+ return null;
119
+ const num = state === 'preparation' ? -1 : state === 'warEnded' ? -3 : -2;
120
+ const warTags = rounds
121
+ .slice(num)
122
+ .map((round) => round.warTags)
123
+ .flat()
124
+ .reverse();
125
+ const wars = await this.util.allSettled(warTags.map((warTag) => this.getClanWarLeagueRound({ warTag, clanTag: args.clanTag }, { ...options, ignoreRateLimit: true })));
126
+ if (args.round && args.round in Constants_1.CWL_ROUNDS) {
127
+ return wars.find((war) => war.state === state) ?? null;
128
+ }
129
+ return wars.find((war) => war.state === state) ?? wars.at(0) ?? null;
130
+ }
131
+ async _getCurrentLeagueWars(clanTag, options) {
132
+ const data = await this.getClanWarLeagueGroup(clanTag, options);
133
+ // @ts-expect-error
134
+ return data._getCurrentWars(clanTag, options);
135
+ }
136
+ async _getClanWars(clanTag, options) {
137
+ const date = new Date().getUTCDate();
138
+ if (!(date >= 1 && date <= 10)) {
139
+ return [await this.getClanWar(clanTag, options)];
140
+ }
141
+ try {
142
+ return this._getCurrentLeagueWars(clanTag, options);
143
+ }
144
+ catch (e) {
145
+ if (e instanceof HTTPError_1.HTTPError && [404].includes(e.status)) {
146
+ return [await this.getClanWar(clanTag, options)];
147
+ }
148
+ throw e;
149
+ }
150
+ }
151
+ /** Get information about clan war league. */
152
+ async getClanWarLeagueGroup(clanTag, options) {
153
+ const { data } = await this.rest.getClanWarLeagueGroup(clanTag, options);
154
+ return new struct_1.ClanWarLeagueGroup(this, data);
155
+ }
156
+ /** Get info about a CWL round by WarTag. */
157
+ async getClanWarLeagueRound(warTag, options) {
158
+ const args = typeof warTag === 'string' ? { warTag } : { warTag: warTag.warTag, clanTag: warTag.clanTag };
159
+ const { data, maxAge, status, path } = await this.rest.getClanWarLeagueRound(args.warTag, options);
160
+ if (data.state === 'notInWar') {
161
+ throw new HTTPError_1.HTTPError(HTTPError_1.NotInWarError, status, path, maxAge);
162
+ }
163
+ return new struct_1.ClanWar(this, data, { warTag: args.warTag, clanTag: args.clanTag, maxAge });
164
+ }
165
+ /** Get information about a player by tag. */
166
+ async getPlayer(playerTag, options) {
167
+ const { data } = await this.rest.getPlayer(playerTag, options);
168
+ return new struct_1.Player(this, data);
169
+ }
170
+ /** Verify Player API token that can be found from the Game settings. */
171
+ async verifyPlayerToken(playerTag, token, options) {
172
+ const { data } = await this.rest.verifyPlayerToken(playerTag, token, options);
173
+ return data.status === 'ok';
174
+ }
175
+ /** Get list of Leagues. */
176
+ async getLeagues(options) {
177
+ const { data } = await this.rest.getLeagues(options);
178
+ return data.items.map((entry) => new struct_1.League(entry));
179
+ }
180
+ /** Get Legend League season Ids. */
181
+ async getLeagueSeasons(options) {
182
+ const { data } = await this.rest.getLeagueSeasons(Constants_1.LEGEND_LEAGUE_ID, options);
183
+ return data.items.map((league) => league.id);
184
+ }
185
+ /** Get Legend League season rankings by season Id. */
186
+ async getSeasonRankings(seasonId, options) {
187
+ const { data } = await this.rest.getSeasonRankings(Constants_1.LEGEND_LEAGUE_ID, seasonId, options);
188
+ // @ts-expect-error
189
+ return data.items.map((entry) => new struct_1.RankedPlayer(entry));
190
+ }
191
+ /** Get list of Clan War Leagues. */
192
+ async getWarLeagues(options) {
193
+ const { data } = await this.rest.getWarLeagues(options);
194
+ return data.items.map((entry) => new struct_1.WarLeague(entry));
195
+ }
196
+ /** Get list of Locations. */
197
+ async getLocations(options) {
198
+ const { data } = await this.rest.getLocations(options);
199
+ return data.items.map((entry) => new struct_1.Location(entry));
200
+ }
201
+ /** Get clan rankings for a specific location. */
202
+ async getClanRanks(locationId, options) {
203
+ const { data } = await this.rest.getClanRanks(locationId, options);
204
+ return data.items.map((entry) => new struct_1.RankedClan(entry));
205
+ }
206
+ /** Get player rankings for a specific location. */
207
+ async getPlayerRanks(locationId, options) {
208
+ const { data } = await this.rest.getPlayerRanks(locationId, options);
209
+ return data.items.map((entry) => new struct_1.RankedPlayer(this, entry));
210
+ }
211
+ /** Get clan versus rankings for a specific location. */
212
+ async getVersusClanRanks(locationId, options) {
213
+ const { data } = await this.rest.getVersusClanRanks(locationId, options);
214
+ return data.items.map((entry) => new struct_1.RankedClan(entry));
215
+ }
216
+ /** Get player versus rankings for a specific location. */
217
+ async getVersusPlayerRanks(locationId, options) {
218
+ const { data } = await this.rest.getVersusPlayerRanks(locationId, options);
219
+ return data.items.map((entry) => new struct_1.RankedPlayer(this, entry));
220
+ }
221
+ /** Get list of clan labels. */
222
+ async getClanLabels(options) {
223
+ const { data } = await this.rest.getClanLabels(options);
224
+ return data.items.map((entry) => new struct_1.Label(entry));
225
+ }
226
+ /** Get list of player labels. */
227
+ async getPlayerLabels(options) {
228
+ const { data } = await this.rest.getPlayerLabels(options);
229
+ return data.items.map((entry) => new struct_1.Label(entry));
230
+ }
231
+ /** Get info about gold pass season. */
232
+ async getGoldPassSeason(options) {
233
+ const { data } = await this.rest.getGoldPassSeason(options);
234
+ return new struct_1.GoldPassSeason(data);
235
+ }
236
+ }
237
+ exports.Client = Client;