@blizzard-api/client 1.0.10 → 2.0.0

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/README.md CHANGED
@@ -4,14 +4,11 @@ This package provides a client that is meant to be used together with one or mor
4
4
 
5
5
  Currently available packages are:
6
6
 
7
- - `@blizzard-api/d3`
8
- - `@blizzard-api/wow`
9
7
  - `@blizzard-api/classic-wow`
10
-
11
- Planned packages are:
12
-
8
+ - `@blizzard-api/d3`
13
9
  - `@blizzard-api/hs`
14
10
  - `@blizzard-api/sc2`
11
+ - `@blizzard-api/wow`
15
12
 
16
13
  ## Installation
17
14
 
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { setTimeout } from 'timers';
2
- import { stringify } from 'querystring';
1
+ import { setTimeout } from 'node:timers';
2
+ import { stringify } from 'node:querystring';
3
3
  import { getBlizzardApi } from '@blizzard-api/core';
4
4
  import axios, { isAxiosError, AxiosError } from 'axios';
5
5
 
package/package.json CHANGED
@@ -1,25 +1,21 @@
1
1
  {
2
2
  "name": "@blizzard-api/client",
3
- "version": "1.0.10",
3
+ "version": "2.0.0",
4
4
  "license": "MIT",
5
5
  "author": "Putro",
6
6
  "description": "A node.js axios client to integrate with the blizzard battle.net api.",
7
7
  "repository": "https://github.com/Pewtro/blizzard-api/tree/main/packages/client",
8
8
  "type": "module",
9
9
  "engines": {
10
- "node": "^18.18 || ^20.9 || ^21.1 || ^22"
10
+ "node": "^18.18 || >=20.9"
11
11
  },
12
- "main": "./dist/index.cjs",
13
12
  "module": "./dist/index.js",
14
13
  "types": "./dist/index.d.ts",
15
14
  "exports": {
16
15
  "import": {
16
+ "@blizzard-api/client-local": "./src/index.ts",
17
17
  "types": "./dist/index.d.ts",
18
18
  "default": "./dist/index.js"
19
- },
20
- "require": {
21
- "types": "./dist/index.d.cts",
22
- "default": "./dist/index.cjs"
23
19
  }
24
20
  },
25
21
  "files": [
@@ -47,14 +43,15 @@
47
43
  "axios": "1.7.7"
48
44
  },
49
45
  "peerDependencies": {
50
- "@blizzard-api/core": "1.2.1"
46
+ "@blizzard-api/core": "2.0.0"
51
47
  },
52
48
  "devDependencies": {
53
- "@blizzard-api/classic-wow": "1.1.6",
54
- "@blizzard-api/core": "1.2.1",
55
- "@blizzard-api/d3": "0.1.5",
56
- "@blizzard-api/sc2": "0.1.0",
57
- "@blizzard-api/wow": "1.2.1"
49
+ "@blizzard-api/classic-wow": "2.0.0",
50
+ "@blizzard-api/core": "2.0.0",
51
+ "@blizzard-api/d3": "1.0.0",
52
+ "@blizzard-api/hs": "1.0.0",
53
+ "@blizzard-api/sc2": "1.0.0",
54
+ "@blizzard-api/wow": "2.0.0"
58
55
  },
59
56
  "scripts": {
60
57
  "build": "tsup",
package/dist/index.cjs DELETED
@@ -1,207 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var timers = require('timers');
6
- var querystring = require('querystring');
7
- var core = require('@blizzard-api/core');
8
- var axios = require('axios');
9
-
10
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
-
12
- var axios__default = /*#__PURE__*/_interopDefault(axios);
13
-
14
- // src/client/create-client.ts
15
- var BlizzardApiClient = class {
16
- axios = axios__default.default.create();
17
- defaults;
18
- /**
19
- * Get an access token.
20
- * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
21
- * @returns The access token. See {@link AccessToken}.
22
- * @example
23
- * const response = await client.getAccessToken();
24
- * const { access_token, token_type, expires_in, sub } = response.data;
25
- * console.log(access_token, token_type, expires_in, sub);
26
- * // => 'access'
27
- * // => 'bearer'
28
- * // => 86399
29
- * // => 'client-id'
30
- */
31
- getAccessToken = async (options) => {
32
- const { key, origin, secret } = { ...this.defaults, ...options };
33
- return this.axios.post(`https://${origin}.battle.net/oauth/token`, void 0, {
34
- auth: {
35
- password: secret,
36
- username: key
37
- },
38
- headers: {
39
- "Content-Type": "application/json"
40
- },
41
- params: {
42
- grant_type: "client_credentials"
43
- }
44
- });
45
- };
46
- /**
47
- * Refresh the access token.
48
- * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
49
- * @returns The access token. See {@link AccessToken}.
50
- * @example
51
- * const response = await client.refreshAccessToken();
52
- * const { access_token, token_type, expires_in, sub } = response.data;
53
- * console.log(access_token, token_type, expires_in, sub);
54
- * // => 'access'
55
- * // => 'bearer'
56
- * // => 86399
57
- * // => 'client-id'
58
- */
59
- refreshAccessToken = async (options) => {
60
- const response = await this.getAccessToken(options);
61
- this.setAccessToken(response.data.access_token);
62
- return response;
63
- };
64
- /**
65
- * Set the access token.
66
- * @param token The access token.
67
- */
68
- setAccessToken = (token) => {
69
- this.defaults.token = token;
70
- };
71
- /**
72
- * Validate an access token.
73
- * @param options The validate access token arguments. See {@link ValidateAccessTokenArguments}.
74
- * @returns The response from the Blizzard API. See {@link ValidateAccessTokenResponse}.
75
- * @example
76
- * const response = await client.validateAccessToken({ token: 'access' });
77
- * console.log(response.data.client_id);
78
- * // => 'client-id'
79
- */
80
- validateAccessToken = async (options) => {
81
- const { origin, token } = { ...this.defaults, ...options };
82
- if (!token) {
83
- throw new Error("No token has been set previously or been passed to the validateAccessToken method.");
84
- }
85
- return await this.axios.post(
86
- `https://${origin}.battle.net/oauth/check_token`,
87
- querystring.stringify({ token }),
88
- {
89
- headers: {
90
- "Content-Type": "application/x-www-form-urlencoded"
91
- }
92
- }
93
- );
94
- };
95
- constructor(options) {
96
- const { locale, origin } = core.getBlizzardApi(options.origin, options.locale);
97
- this.defaults = {
98
- key: options.key,
99
- locale,
100
- origin,
101
- secret: options.secret,
102
- token: options.token
103
- };
104
- }
105
- /**
106
- * Get the request configuration.
107
- * @param resource The resource to fetch. See {@link Resource}.
108
- * @param options Client options. See {@link ClientOptions}.
109
- * @param headers Additional headers to include in the request.
110
- * @returns The request configuration.
111
- */
112
- getRequestConfig(resource, options, headers) {
113
- const config = { ...this.defaults, ...options };
114
- const endpoint = core.getBlizzardApi(config.origin, config.locale);
115
- const namespace = resource.namespace ? { "Battlenet-Namespace": `${resource.namespace}-${endpoint.origin}` } : void 0;
116
- return {
117
- headers: {
118
- ...headers,
119
- ...namespace,
120
- Authorization: `Bearer ${config.token}`,
121
- "Content-Type": "application/json"
122
- },
123
- params: {
124
- locale: endpoint.locale,
125
- ...resource.parameters
126
- }
127
- };
128
- }
129
- /**
130
- * Get the request URL.
131
- * @param resource The resource to fetch. See {@link Resource}.
132
- * @param options Client options. See {@link ClientOptions}.
133
- * @returns The request URL.
134
- */
135
- getRequestUrl(resource, options) {
136
- const config = { ...this.defaults, ...options };
137
- const endpoint = core.getBlizzardApi(config.origin, config.locale);
138
- const backslashSeparator = resource.path.startsWith("/") ? "" : "/";
139
- return `${endpoint.hostname}${backslashSeparator}${resource.path}`;
140
- }
141
- /**
142
- * Send a request to the Blizzard API.
143
- * @param resource The resource to fetch. See {@link Resource}.
144
- * @param options Client options. See {@link ClientOptions}.
145
- * @param headers Additional headers to include in the request.
146
- * @returns The response from the Blizzard API. See {@link ResourceResponse}.
147
- */
148
- async sendRequest(resource, options, headers) {
149
- const url = this.getRequestUrl(resource, options);
150
- const config = this.getRequestConfig(resource, options, headers);
151
- try {
152
- return await this.axios.get(url, config);
153
- } catch (error) {
154
- if (axios.isAxiosError(error)) {
155
- throw new axios.AxiosError(error.message, error.code);
156
- }
157
- throw error;
158
- }
159
- }
160
- };
161
-
162
- // src/client/create-client.ts
163
- var getTokenExpiration = (expiresIn) => expiresIn * 1e3 - 6e4;
164
- var createBlizzardApiClient = async (options, onTokenRefresh = true) => {
165
- const { key, secret, token } = options;
166
- if (!key) {
167
- throw new Error(`Client missing 'key' parameter`);
168
- }
169
- if (!secret) {
170
- throw new Error(`Client missing 'secret' parameter`);
171
- }
172
- const client = new BlizzardApiClient(options);
173
- const refreshToken = async () => {
174
- const response = await client.getAccessToken();
175
- client.setAccessToken(response.data.access_token);
176
- if (typeof onTokenRefresh === "function") {
177
- onTokenRefresh?.(response.data);
178
- }
179
- const timeout = timers.setTimeout(() => void refreshToken(), getTokenExpiration(response.data.expires_in));
180
- timeout.unref();
181
- };
182
- if (!onTokenRefresh) {
183
- return client;
184
- }
185
- if (token) {
186
- try {
187
- const validatedToken = await client.validateAccessToken({ token });
188
- const expiry = getTokenExpiration(validatedToken.data.exp);
189
- if (expiry - Date.now() < 6e4) {
190
- await refreshToken();
191
- } else {
192
- const timeout = timers.setTimeout(() => void refreshToken(), expiry - Date.now());
193
- timeout.unref();
194
- }
195
- } catch {
196
- await refreshToken();
197
- }
198
- } else {
199
- await refreshToken();
200
- }
201
- return client;
202
- };
203
-
204
- exports.createBlizzardApiClient = createBlizzardApiClient;
205
- exports.default = createBlizzardApiClient;
206
- //# sourceMappingURL=index.cjs.map
207
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/client/client.ts","../src/client/create-client.ts"],"names":["axios","stringify","getBlizzardApi","isAxiosError","AxiosError","setTimeout"],"mappings":";;;;;;;;;;;;;;AA4BO,IAAM,oBAAN,MAAsD;AAAA,EACnD,KAAA,GAAQA,uBAAM,MAAO,EAAA,CAAA;AAAA,EAEtB,QAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBA,cAAA,GAAiB,OAAO,OAA+E,KAAA;AAC5G,IAAM,MAAA,EAAE,GAAK,EAAA,MAAA,EAAQ,MAAO,EAAA,GAAI,EAAE,GAAG,IAAA,CAAK,QAAU,EAAA,GAAG,OAAQ,EAAA,CAAA;AAC/D,IAAA,OAAO,KAAK,KAAM,CAAA,IAAA,CAAkB,CAAW,QAAA,EAAA,MAAM,2BAA2B,KAAW,CAAA,EAAA;AAAA,MACzF,IAAM,EAAA;AAAA,QACJ,QAAU,EAAA,MAAA;AAAA,QACV,QAAU,EAAA,GAAA;AAAA,OACZ;AAAA,MACA,OAAS,EAAA;AAAA,QACP,cAAgB,EAAA,kBAAA;AAAA,OACl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A;AAEzE,QAAA,OAAA,CAAQ,KAAM,EAAA,CAAA;AAAA,OAChB;AAAA,KACM,CAAA,MAAA;AAEN,MAAA,MAAM,YAAa,EAAA,CAAA;AAAA,KACrB;AAAA,GACK,MAAA;AAEL,IAAA,MAAM,YAAa,EAAA,CAAA;AAAA,GACrB;AAEA,EAAO,OAAA,MAAA,CAAA;AACT","file":"index.cjs","sourcesContent":["import { stringify } from 'node:querystring';\r\nimport { getBlizzardApi } from '@blizzard-api/core';\r\nimport type { Locales, Origins, Resource, ResourceResponse } from '@blizzard-api/core';\r\nimport type { AxiosResponse } from 'axios';\r\nimport axios, { AxiosError, isAxiosError } from 'axios';\r\nimport type {\r\n AccessToken,\r\n AccessTokenRequestArguments,\r\n ClientOptions,\r\n IBlizzardApiClient,\r\n ValidateAccessTokenArguments,\r\n ValidateAccessTokenResponse,\r\n} from './types';\r\n\r\n/**\r\n * A Blizzard API client.\r\n * @implements IBlizzardApiClient\r\n * @class\r\n * @classdesc A client to interact with the Blizzard API.\r\n * @example\r\n * const client = new BlizzardApiClient({\r\n * key: 'client',\r\n * secret: 'secret',\r\n * origin: 'eu',\r\n * locale: 'en_GB',\r\n * token: 'access'\r\n * });\r\n */\r\nexport class BlizzardApiClient implements IBlizzardApiClient {\r\n private axios = axios.create();\r\n\r\n public defaults: {\r\n key: string;\r\n locale: Locales;\r\n origin: Origins;\r\n secret: string;\r\n token?: string;\r\n };\r\n\r\n /**\r\n * Get an access token.\r\n * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.\r\n * @returns The access token. See {@link AccessToken}.\r\n * @example\r\n * const response = await client.getAccessToken();\r\n * const { access_token, token_type, expires_in, sub } = response.data;\r\n * console.log(access_token, token_type, expires_in, sub);\r\n * // => 'access'\r\n * // => 'bearer'\r\n * // => 86399\r\n * // => 'client-id'\r\n */\r\n public getAccessToken = async (options?: AccessTokenRequestArguments): Promise<AxiosResponse<AccessToken>> => {\r\n const { key, origin, secret } = { ...this.defaults, ...options };\r\n return this.axios.post<AccessToken>(`https://${origin}.battle.net/oauth/token`, undefined, {\r\n auth: {\r\n password: secret,\r\n username: key,\r\n },\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n params: {\r\n grant_type: 'client_credentials',\r\n },\r\n });\r\n };\r\n\r\n /**\r\n * Refresh the access token.\r\n * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.\r\n * @returns The access token. See {@link AccessToken}.\r\n * @example\r\n * const response = await client.refreshAccessToken();\r\n * const { access_token, token_type, expires_in, sub } = response.data;\r\n * console.log(access_token, token_type, expires_in, sub);\r\n * // => 'access'\r\n * // => 'bearer'\r\n * // => 86399\r\n * // => 'client-id'\r\n */\r\n public refreshAccessToken = async (options?: AccessTokenRequestArguments): Promise<AxiosResponse<AccessToken>> => {\r\n const response = await this.getAccessToken(options);\r\n this.setAccessToken(response.data.access_token);\r\n return response;\r\n };\r\n\r\n /**\r\n * Set the access token.\r\n * @param token The access token.\r\n */\r\n public setAccessToken = (token: string): void => {\r\n this.defaults.token = token;\r\n };\r\n\r\n /**\r\n * Validate an access token.\r\n * @param options The validate access token arguments. See {@link ValidateAccessTokenArguments}.\r\n * @returns The response from the Blizzard API. See {@link ValidateAccessTokenResponse}.\r\n * @example\r\n * const response = await client.validateAccessToken({ token: 'access' });\r\n * console.log(response.data.client_id);\r\n * // => 'client-id'\r\n */\r\n public validateAccessToken = async (\r\n options?: ValidateAccessTokenArguments,\r\n ): Promise<AxiosResponse<ValidateAccessTokenResponse>> => {\r\n const { origin, token } = { ...this.defaults, ...options };\r\n\r\n if (!token) {\r\n throw new Error('No token has been set previously or been passed to the validateAccessToken method.');\r\n }\r\n\r\n return await this.axios.post<ValidateAccessTokenResponse>(\r\n `https://${origin}.battle.net/oauth/check_token`,\r\n stringify({ token }),\r\n {\r\n headers: {\r\n 'Content-Type': 'application/x-www-form-urlencoded',\r\n },\r\n },\r\n );\r\n };\r\n\r\n constructor(options: ClientOptions) {\r\n const { locale, origin } = getBlizzardApi(options.origin, options.locale);\r\n this.defaults = {\r\n key: options.key,\r\n locale: locale,\r\n origin: origin,\r\n secret: options.secret,\r\n token: options.token,\r\n };\r\n }\r\n\r\n /**\r\n * Get the request configuration.\r\n * @param resource The resource to fetch. See {@link Resource}.\r\n * @param options Client options. See {@link ClientOptions}.\r\n * @param headers Additional headers to include in the request.\r\n * @returns The request configuration.\r\n */\r\n public getRequestConfig<T, Protected extends boolean = false>(\r\n resource: Resource<T, object, Protected>,\r\n options?: Partial<ClientOptions>,\r\n headers?: Record<string, string>,\r\n ) {\r\n const config = { ...this.defaults, ...options };\r\n const endpoint = getBlizzardApi(config.origin, config.locale);\r\n\r\n const namespace = resource.namespace\r\n ? { 'Battlenet-Namespace': `${resource.namespace}-${endpoint.origin}` }\r\n : undefined;\r\n\r\n return {\r\n headers: {\r\n ...headers,\r\n ...namespace,\r\n Authorization: `Bearer ${config.token}`,\r\n 'Content-Type': 'application/json',\r\n },\r\n params: {\r\n locale: endpoint.locale,\r\n ...resource.parameters,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Get the request URL.\r\n * @param resource The resource to fetch. See {@link Resource}.\r\n * @param options Client options. See {@link ClientOptions}.\r\n * @returns The request URL.\r\n */\r\n public getRequestUrl<T, Protected extends boolean = false>(\r\n resource: Resource<T, object, Protected>,\r\n options?: Partial<ClientOptions>,\r\n ) {\r\n const config = { ...this.defaults, ...options };\r\n const endpoint = getBlizzardApi(config.origin, config.locale);\r\n\r\n const backslashSeparator = resource.path.startsWith('/') ? '' : '/';\r\n\r\n return `${endpoint.hostname}${backslashSeparator}${resource.path}`;\r\n }\r\n\r\n /**\r\n * Send a request to the Blizzard API.\r\n * @param resource The resource to fetch. See {@link Resource}.\r\n * @param options Client options. See {@link ClientOptions}.\r\n * @param headers Additional headers to include in the request.\r\n * @returns The response from the Blizzard API. See {@link ResourceResponse}.\r\n */\r\n public async sendRequest<T, Protected extends boolean = false>(\r\n resource: Resource<T, object, Protected>,\r\n options?: Partial<ClientOptions>,\r\n headers?: Record<string, string>,\r\n ): ResourceResponse<AxiosResponse<T>> {\r\n const url = this.getRequestUrl(resource, options);\r\n const config = this.getRequestConfig(resource, options, headers);\r\n\r\n try {\r\n return await this.axios.get<T>(url, config);\r\n } catch (error) {\r\n if (isAxiosError(error)) {\r\n throw new AxiosError(error.message, error.code);\r\n }\r\n throw error;\r\n }\r\n }\r\n}\r\n","//We have to explicitly import setTimeout because of https://github.com/electron/electron/issues/21162#issuecomment-554792447\r\nimport { setTimeout } from 'node:timers';\r\nimport { BlizzardApiClient } from './client';\r\nimport type { AccessToken, ClientOptions } from './types';\r\n\r\nconst getTokenExpiration = (expiresIn: number) => expiresIn * 1000 - 60_000;\r\n\r\n/**\r\n * Create a new Blizzard API client.\r\n * @param options Client options, see {@link ClientOptions} & https://develop.battle.net/documentation/guides/getting-started\r\n * @param onTokenRefresh Callback function to handle token refresh. If set to `true`, the client will automatically refresh the token. If set to `false`, the client will not refresh the token. If set to a function, the function will be called with the new token.\r\n * @returns A new Blizzard API client.\r\n */\r\nexport const createBlizzardApiClient = async (\r\n options: ClientOptions,\r\n onTokenRefresh: ((token: AccessToken) => void) | boolean = true,\r\n): Promise<BlizzardApiClient> => {\r\n const { key, secret, token } = options;\r\n if (!key) {\r\n throw new Error(`Client missing 'key' parameter`);\r\n }\r\n if (!secret) {\r\n throw new Error(`Client missing 'secret' parameter`);\r\n }\r\n\r\n const client = new BlizzardApiClient(options);\r\n\r\n const refreshToken = async () => {\r\n const response = await client.getAccessToken();\r\n\r\n client.setAccessToken(response.data.access_token);\r\n\r\n if (typeof onTokenRefresh === 'function') {\r\n onTokenRefresh?.(response.data);\r\n }\r\n\r\n //Schedule a refresh of the token\r\n const timeout = setTimeout(() => void refreshToken(), getTokenExpiration(response.data.expires_in));\r\n timeout.unref();\r\n };\r\n\r\n //If tokenRefresh is false, return the client without refreshing the token\r\n if (!onTokenRefresh) {\r\n return client;\r\n }\r\n\r\n if (token) {\r\n try {\r\n //If token is set, validate the token\r\n const validatedToken = await client.validateAccessToken({ token });\r\n const expiry = getTokenExpiration(validatedToken.data.exp);\r\n //If token is expiring in less than 60 seconds, refresh the token\r\n if (expiry - Date.now() < 60_000) {\r\n await refreshToken();\r\n } else {\r\n //If token is not expiring, schedule a refresh\r\n const timeout = setTimeout(() => void refreshToken(), expiry - Date.now());\r\n //Unref the timeout so the process can exit\r\n timeout.unref();\r\n }\r\n } catch {\r\n //If token is invalid, refresh the token\r\n await refreshToken();\r\n }\r\n } else {\r\n //If token is not set, refresh the token\r\n await refreshToken();\r\n }\r\n\r\n return client;\r\n};\r\n"]}
package/dist/index.d.cts DELETED
@@ -1,238 +0,0 @@
1
- import { Origins, Locales, Resource, ResourceResponse } from '@blizzard-api/core';
2
- import { AxiosResponse } from 'axios';
3
-
4
- /**
5
- * An access token response from the Blizzard API.
6
- * @see https://develop.battle.net/documentation/guides/using-oauth
7
- * @see https://develop.battle.net/documentation/guides/using-oauth/client-credentials-flow¨
8
- * @interface AccessToken
9
- * @property access_token The access token.
10
- * @property token_type The type of token.
11
- * @property expires_in The time in seconds until the token expires.
12
- * @property sub The subject (unique user identifier) of the token.
13
- * @example
14
- * const response: AccessToken = {
15
- * access_token: 'access-token',
16
- * token_type: 'bearer',
17
- * expires_in: 86399,
18
- * sub: 'client-id',
19
- * };
20
- */
21
- interface AccessToken {
22
- access_token: string;
23
- expires_in: number;
24
- sub?: string;
25
- token_type: 'bearer';
26
- }
27
- /**
28
- * An access token request.
29
- * @see https://develop.battle.net/documentation/guides/using-oauth/client-credentials-flow
30
- * @interface AccessTokenRequestArguments
31
- * @property origin The region to request the access token from.
32
- * @property key The client ID.
33
- * @property secret The client secret.
34
- * @example
35
- * const request: AccessTokenRequestArguments = {
36
- * origin: 'eu',
37
- * key: 'client',
38
- * secret: 'secret'
39
- * };
40
- */
41
- interface AccessTokenRequestArguments {
42
- key?: string;
43
- origin?: Origins;
44
- secret?: string;
45
- }
46
- /**
47
- * Validate an access token.
48
- * @see https://develop.battle.net/documentation/guides/using-oauth/client-credentials-flow
49
- * @interface ValidateAccessTokenArguments
50
- * @property origin The region to validate the access token from.
51
- * @property token The access token to validate.
52
- * @example
53
- * const request: ValidateAccessTokenArguments = {
54
- * origin: 'eu',
55
- * token: 'access'
56
- * };
57
- */
58
- interface ValidateAccessTokenArguments {
59
- origin?: Origins;
60
- token?: string;
61
- }
62
- /**
63
- * A response from validating an access token.
64
- * @see https://develop.battle.net/documentation/guides/using-oauth/client-credentials-flow
65
- * @interface ValidateAccessTokenResponse
66
- * @property scope The scope of the token.
67
- * @property account_authorities The account authorities.
68
- * @property exp The expiration time of the token.
69
- * @property client_authorities The client authorities.
70
- * @property authorities The authorities.
71
- * @property client_id The client ID.
72
- * @example
73
- * const response: ValidateAccessTokenResponse = {
74
- * scope: ['wow.profile'],
75
- * account_authorities: [],
76
- * exp: 1617000000,
77
- * client_authorities: [],
78
- * authorities: ['wow.profile'],
79
- * client_id: 'client'
80
- * };
81
- */
82
- interface ValidateAccessTokenResponse {
83
- account_authorities: Array<unknown>;
84
- authorities: Array<string>;
85
- client_authorities: Array<unknown>;
86
- client_id: string;
87
- exp: number;
88
- scope: Array<string>;
89
- }
90
- /**
91
- * A client configuration object.
92
- * @interface ClientOptions
93
- * @property key The client ID.
94
- * @property secret The client secret.
95
- * @property origin The region of the Blizzard API.
96
- * @property locale The locale of the Blizzard API.
97
- * @property token The access token.
98
- * @example
99
- * const options: ClientOptions = {
100
- * key: 'client',
101
- * secret: 'secret',
102
- * origin: 'eu',
103
- * locale: 'en_GB',
104
- * token: 'access'
105
- * };
106
- */
107
- interface ClientOptions {
108
- key: string;
109
- locale?: Locales;
110
- origin: Origins;
111
- secret: string;
112
- token?: string;
113
- }
114
- /**
115
- * A Blizzard API client.
116
- * @interface IBlizzardApiClient
117
- * @property getAccessToken Get an access token.
118
- * @property setAccessToken Set an access token.
119
- * @property refreshAccessToken Refresh an access token.
120
- * @property validateAccessToken Validate an access token.
121
- */
122
- interface IBlizzardApiClient {
123
- getAccessToken: (options: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
124
- refreshAccessToken: (options: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
125
- setAccessToken: (token: string) => void;
126
- validateAccessToken: (options: ValidateAccessTokenArguments) => Promise<AxiosResponse<ValidateAccessTokenResponse>>;
127
- }
128
-
129
- /**
130
- * A Blizzard API client.
131
- * @implements IBlizzardApiClient
132
- * @class
133
- * @classdesc A client to interact with the Blizzard API.
134
- * @example
135
- * const client = new BlizzardApiClient({
136
- * key: 'client',
137
- * secret: 'secret',
138
- * origin: 'eu',
139
- * locale: 'en_GB',
140
- * token: 'access'
141
- * });
142
- */
143
- declare class BlizzardApiClient implements IBlizzardApiClient {
144
- private axios;
145
- defaults: {
146
- key: string;
147
- locale: Locales;
148
- origin: Origins;
149
- secret: string;
150
- token?: string;
151
- };
152
- /**
153
- * Get an access token.
154
- * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
155
- * @returns The access token. See {@link AccessToken}.
156
- * @example
157
- * const response = await client.getAccessToken();
158
- * const { access_token, token_type, expires_in, sub } = response.data;
159
- * console.log(access_token, token_type, expires_in, sub);
160
- * // => 'access'
161
- * // => 'bearer'
162
- * // => 86399
163
- * // => 'client-id'
164
- */
165
- getAccessToken: (options?: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
166
- /**
167
- * Refresh the access token.
168
- * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
169
- * @returns The access token. See {@link AccessToken}.
170
- * @example
171
- * const response = await client.refreshAccessToken();
172
- * const { access_token, token_type, expires_in, sub } = response.data;
173
- * console.log(access_token, token_type, expires_in, sub);
174
- * // => 'access'
175
- * // => 'bearer'
176
- * // => 86399
177
- * // => 'client-id'
178
- */
179
- refreshAccessToken: (options?: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
180
- /**
181
- * Set the access token.
182
- * @param token The access token.
183
- */
184
- setAccessToken: (token: string) => void;
185
- /**
186
- * Validate an access token.
187
- * @param options The validate access token arguments. See {@link ValidateAccessTokenArguments}.
188
- * @returns The response from the Blizzard API. See {@link ValidateAccessTokenResponse}.
189
- * @example
190
- * const response = await client.validateAccessToken({ token: 'access' });
191
- * console.log(response.data.client_id);
192
- * // => 'client-id'
193
- */
194
- validateAccessToken: (options?: ValidateAccessTokenArguments) => Promise<AxiosResponse<ValidateAccessTokenResponse>>;
195
- constructor(options: ClientOptions);
196
- /**
197
- * Get the request configuration.
198
- * @param resource The resource to fetch. See {@link Resource}.
199
- * @param options Client options. See {@link ClientOptions}.
200
- * @param headers Additional headers to include in the request.
201
- * @returns The request configuration.
202
- */
203
- getRequestConfig<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>, headers?: Record<string, string>): {
204
- headers: {
205
- Authorization: string;
206
- 'Content-Type': string;
207
- 'Battlenet-Namespace'?: string | undefined;
208
- };
209
- params: {
210
- locale: "de_DE" | "en_GB" | "en_US" | "es_ES" | "es_MX" | "fr_FR" | "it_IT" | "ko_KR" | "multi" | "pt_BR" | "pt_PT" | "ru_RU" | "zh_CN" | "zh_TW";
211
- };
212
- };
213
- /**
214
- * Get the request URL.
215
- * @param resource The resource to fetch. See {@link Resource}.
216
- * @param options Client options. See {@link ClientOptions}.
217
- * @returns The request URL.
218
- */
219
- getRequestUrl<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>): string;
220
- /**
221
- * Send a request to the Blizzard API.
222
- * @param resource The resource to fetch. See {@link Resource}.
223
- * @param options Client options. See {@link ClientOptions}.
224
- * @param headers Additional headers to include in the request.
225
- * @returns The response from the Blizzard API. See {@link ResourceResponse}.
226
- */
227
- sendRequest<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>, headers?: Record<string, string>): ResourceResponse<AxiosResponse<T>>;
228
- }
229
-
230
- /**
231
- * Create a new Blizzard API client.
232
- * @param options Client options, see {@link ClientOptions} & https://develop.battle.net/documentation/guides/getting-started
233
- * @param onTokenRefresh Callback function to handle token refresh. If set to `true`, the client will automatically refresh the token. If set to `false`, the client will not refresh the token. If set to a function, the function will be called with the new token.
234
- * @returns A new Blizzard API client.
235
- */
236
- declare const createBlizzardApiClient: (options: ClientOptions, onTokenRefresh?: ((token: AccessToken) => void) | boolean) => Promise<BlizzardApiClient>;
237
-
238
- export { type AccessToken, type AccessTokenRequestArguments, type ClientOptions, type IBlizzardApiClient, type ValidateAccessTokenArguments, type ValidateAccessTokenResponse, createBlizzardApiClient, createBlizzardApiClient as default };