@blizzard-api/client 0.2.2 → 0.2.4

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/dist/index.cjs CHANGED
@@ -51,12 +51,25 @@ var BlizzardApiClient = class {
51
51
  };
52
52
  }
53
53
  axios = import_axios.default.create();
54
+ /**
55
+ * Get the request URL.
56
+ * @param resource The resource to fetch. See {@link Resource}.
57
+ * @param options Client options. See {@link ClientOptions}.
58
+ * @returns The request URL.
59
+ */
54
60
  getRequestUrl(resource, options) {
55
61
  const config = { ...this.defaults, ...options };
56
62
  const endpoint = (0, import_core.getBlizzardApi)(config.origin, config.locale);
57
63
  const backslashSeparator = resource.path.startsWith("/") ? "" : "/";
58
64
  return `${endpoint.hostname}${backslashSeparator}${resource.path}`;
59
65
  }
66
+ /**
67
+ * Get the request configuration.
68
+ * @param resource The resource to fetch. See {@link Resource}.
69
+ * @param options Client options. See {@link ClientOptions}.
70
+ * @param headers Additional headers to include in the request.
71
+ * @returns The request configuration.
72
+ */
60
73
  getRequestConfig(resource, options, headers) {
61
74
  const config = { ...this.defaults, ...options };
62
75
  const endpoint = (0, import_core.getBlizzardApi)(config.origin, config.locale);
@@ -74,6 +87,13 @@ var BlizzardApiClient = class {
74
87
  }
75
88
  };
76
89
  }
90
+ /**
91
+ * Send a request to the Blizzard API.
92
+ * @param resource The resource to fetch. See {@link Resource}.
93
+ * @param options Client options. See {@link ClientOptions}.
94
+ * @param headers Additional headers to include in the request.
95
+ * @returns The response from the Blizzard API. See {@link ResourceResponse}.
96
+ */
77
97
  async sendRequest(resource, options, headers) {
78
98
  const url = this.getRequestUrl(resource, options);
79
99
  const config = this.getRequestConfig(resource, options, headers);
@@ -86,6 +106,19 @@ var BlizzardApiClient = class {
86
106
  throw error;
87
107
  }
88
108
  }
109
+ /**
110
+ * Get an access token.
111
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
112
+ * @returns The access token. See {@link AccessToken}.
113
+ * @example
114
+ * const response = await client.getAccessToken();
115
+ * const { access_token, token_type, expires_in, sub } = response.data;
116
+ * console.log(access_token, token_type, expires_in, sub);
117
+ * // => 'access'
118
+ * // => 'bearer'
119
+ * // => 86399
120
+ * // => 'client-id'
121
+ */
89
122
  getAccessToken = async (options) => {
90
123
  const { key, secret, origin } = { ...this.defaults, ...options };
91
124
  return this.axios.post(`https://${origin}.battle.net/oauth/token`, void 0, {
@@ -101,14 +134,40 @@ var BlizzardApiClient = class {
101
134
  }
102
135
  });
103
136
  };
137
+ /**
138
+ * Set the access token.
139
+ * @param token The access token.
140
+ */
104
141
  setAccessToken = (token) => {
105
142
  this.defaults.token = token;
106
143
  };
144
+ /**
145
+ * Refresh the access token.
146
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
147
+ * @returns The access token. See {@link AccessToken}.
148
+ * @example
149
+ * const response = await client.refreshAccessToken();
150
+ * const { access_token, token_type, expires_in, sub } = response.data;
151
+ * console.log(access_token, token_type, expires_in, sub);
152
+ * // => 'access'
153
+ * // => 'bearer'
154
+ * // => 86399
155
+ * // => 'client-id'
156
+ */
107
157
  refreshAccessToken = async (options) => {
108
158
  const response = await this.getAccessToken(options);
109
159
  this.setAccessToken(response.data.access_token);
110
160
  return response;
111
161
  };
162
+ /**
163
+ * Validate an access token.
164
+ * @param options The validate access token arguments. See {@link ValidateAccessTokenArguments}.
165
+ * @returns The response from the Blizzard API. See {@link ValidateAccessTokenResponse}.
166
+ * @example
167
+ * const response = await client.validateAccessToken({ token: 'access' });
168
+ * console.log(response.data.client_id);
169
+ * // => 'client-id'
170
+ */
112
171
  validateAccessToken = async (options) => {
113
172
  const { origin, token } = { ...this.defaults, ...options };
114
173
  if (!token) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client/client.ts","../src/client/create-client.ts"],"sourcesContent":["export { createBlizzardApiClient } from './client/create-client';\r\nexport * from './client/types';\r\n","import { stringify } from 'node:querystring';\r\nimport { getBlizzardApi } from '@blizzard-api/core';\r\nimport type { Origins, Locales, ResourceResponse, Resource } 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\nexport class BlizzardApiClient implements IBlizzardApiClient {\r\n public defaults: {\r\n key: string;\r\n secret: string;\r\n origin: Origins;\r\n locale: Locales;\r\n token?: string;\r\n };\r\n\r\n constructor(options: ClientOptions) {\r\n const { origin, locale } = getBlizzardApi(options.origin, options.locale);\r\n this.defaults = {\r\n key: options.key,\r\n secret: options.secret,\r\n token: options.token,\r\n origin: origin,\r\n locale: locale,\r\n };\r\n }\r\n\r\n private axios = axios.create();\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 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 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${config.token}`,\r\n },\r\n params: {\r\n locale: endpoint.locale,\r\n ...resource.parameters,\r\n },\r\n };\r\n }\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 public getAccessToken = async (options?: AccessTokenRequestArguments): Promise<AxiosResponse<AccessToken>> => {\r\n const { key, secret, origin } = { ...this.defaults, ...options };\r\n return this.axios.post<AccessToken>(`https://${origin}.battle.net/oauth/token`, undefined, {\r\n params: {\r\n grant_type: 'client_credentials',\r\n },\r\n auth: {\r\n username: key,\r\n password: secret,\r\n },\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n });\r\n };\r\n\r\n public setAccessToken = (token: string): void => {\r\n this.defaults.token = token;\r\n };\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 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","import { BlizzardApiClient } from './client';\r\nimport type { AccessToken, ClientOptions } from './types';\r\n\r\nconst getTokenExpiration = (expiresIn: number) => expiresIn * 1000 - 60_000;\r\n\r\nexport const createBlizzardApiClient = async (\r\n /**\r\n * Client options.\r\n * @see ClientOptions\r\n * @see https://develop.battle.net/documentation/guides/getting-started\r\n */\r\n options: ClientOptions,\r\n /**\r\n * Callback function to handle token refresh.\r\n *\r\n * If set to `true`, the client will automatically refresh the token.\r\n *\r\n * If set to `false`, the client will not refresh the token.\r\n *\r\n * If set to a function, the function will be called with the new token.\r\n */\r\n onTokenRefresh: boolean | ((token: AccessToken) => void) = 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAA0B;AAC1B,kBAA+B;AAG/B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M,IAAI;AAC/B,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,gCAAgC;AAAA,EAClD;AACA,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAEA,QAAM,SAAS,IAAI,kBAAkB,OAAO;AAE5C,QAAM,eAAe,YAAY;AAC/B,UAAM,WAAW,MAAM,OAAO,eAAe;AAE7C,WAAO,eAAe,SAAS,KAAK,YAAY;AAEhD,QAAI,OAAO,mBAAmB,YAAY;AACxC,uBAAiB,SAAS,IAAI;AAAA,IAChC;AAGA,UAAM,UAAU,WAAW,MAAM,KAAK,aAAa,GAAG,mBAAmB,SAAS,KAAK,UAAU,CAAC;AAClG,YAAQ,MAAM;AAAA,EAChB;AAGA,MAAI,CAAC,gBAAgB;AACnB,WAAO;AAAA,EACT;AAEA,MAAI,OAAO;AACT,QAAI;AAEF,YAAM,iBAAiB,MAAM,OAAO,oBAAoB,EAAE,MAAM,CAAC;AACjE,YAAM,SAAS,mBAAmB,eAAe,KAAK,GAAG;AAEzD,UAAI,SAAS,KAAK,IAAI,IAAI,KAAQ;AAChC,cAAM,aAAa;AAAA,MACrB,OAAO;AAEL,cAAM,UAAU,WAAW,MAAM,KAAK,aAAa,GAAG,SAAS,KAAK,IAAI,CAAC;AAEzE,gBAAQ,MAAM;AAAA,MAChB;AAAA,IACF,QAAQ;AAEN,YAAM,aAAa;AAAA,IACrB;AAAA,EACF,OAAO;AAEL,UAAM,aAAa;AAAA,EACrB;AAEA,SAAO;AACT;","names":["axios"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client/client.ts","../src/client/create-client.ts"],"sourcesContent":["export { createBlizzardApiClient } from './client/create-client';\r\nexport * from './client/types';\r\n","import { stringify } from 'node:querystring';\r\nimport { getBlizzardApi } from '@blizzard-api/core';\r\nimport type { Origins, Locales, ResourceResponse, Resource } 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 public defaults: {\r\n key: string;\r\n secret: string;\r\n origin: Origins;\r\n locale: Locales;\r\n token?: string;\r\n };\r\n\r\n constructor(options: ClientOptions) {\r\n const { origin, locale } = getBlizzardApi(options.origin, options.locale);\r\n this.defaults = {\r\n key: options.key,\r\n secret: options.secret,\r\n token: options.token,\r\n origin: origin,\r\n locale: locale,\r\n };\r\n }\r\n\r\n private axios = axios.create();\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 * 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 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${config.token}`,\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 * 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 /**\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, secret, origin } = { ...this.defaults, ...options };\r\n return this.axios.post<AccessToken>(`https://${origin}.battle.net/oauth/token`, undefined, {\r\n params: {\r\n grant_type: 'client_credentials',\r\n },\r\n auth: {\r\n username: key,\r\n password: secret,\r\n },\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n });\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 * 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 * 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","import { 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: boolean | ((token: AccessToken) => void) = 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAA0B;AAC1B,kBAA+B;AAG/B,mBAAgD;AAwBzC,I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;AAEL,UAAM,aAAa;AAAA,EACrB;AAEA,SAAO;AACT;","names":["axios"]}
package/dist/index.d.cts CHANGED
@@ -1,21 +1,84 @@
1
1
  import { Origins, Locales, Resource, ResourceResponse } from '@blizzard-api/core';
2
2
  import { AxiosResponse } from 'axios';
3
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
+ */
4
21
  interface AccessToken {
5
22
  access_token: string;
6
23
  token_type: 'bearer';
7
24
  expires_in: number;
8
25
  sub?: string;
9
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
+ */
10
41
  interface AccessTokenRequestArguments {
11
42
  origin?: Origins;
12
43
  key?: string;
13
44
  secret?: string;
14
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
+ */
15
58
  interface ValidateAccessTokenArguments {
16
59
  origin?: Origins;
17
60
  token?: string;
18
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
+ */
19
82
  interface ValidateAccessTokenResponse {
20
83
  scope: Array<string>;
21
84
  account_authorities: Array<unknown>;
@@ -24,6 +87,23 @@ interface ValidateAccessTokenResponse {
24
87
  authorities: Array<string>;
25
88
  client_id: string;
26
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
+ */
27
107
  interface ClientOptions {
28
108
  key: string;
29
109
  secret: string;
@@ -31,6 +111,14 @@ interface ClientOptions {
31
111
  locale?: Locales;
32
112
  token?: string;
33
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
+ */
34
122
  interface IBlizzardApiClient {
35
123
  getAccessToken: (options: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
36
124
  setAccessToken: (token: string) => void;
@@ -38,6 +126,20 @@ interface IBlizzardApiClient {
38
126
  validateAccessToken: (options: ValidateAccessTokenArguments) => Promise<AxiosResponse<ValidateAccessTokenResponse>>;
39
127
  }
40
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
+ */
41
143
  declare class BlizzardApiClient implements IBlizzardApiClient {
42
144
  defaults: {
43
145
  key: string;
@@ -48,7 +150,20 @@ declare class BlizzardApiClient implements IBlizzardApiClient {
48
150
  };
49
151
  constructor(options: ClientOptions);
50
152
  private axios;
153
+ /**
154
+ * Get the request URL.
155
+ * @param resource The resource to fetch. See {@link Resource}.
156
+ * @param options Client options. See {@link ClientOptions}.
157
+ * @returns The request URL.
158
+ */
51
159
  getRequestUrl<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>): string;
160
+ /**
161
+ * Get the request configuration.
162
+ * @param resource The resource to fetch. See {@link Resource}.
163
+ * @param options Client options. See {@link ClientOptions}.
164
+ * @param headers Additional headers to include in the request.
165
+ * @returns The request configuration.
166
+ */
52
167
  getRequestConfig<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>, headers?: Record<string, string>): {
53
168
  headers: {
54
169
  'Content-Type': string;
@@ -59,13 +174,65 @@ declare class BlizzardApiClient implements IBlizzardApiClient {
59
174
  locale: "en_US" | "es_MX" | "pt_BR" | "en_GB" | "es_ES" | "fr_FR" | "ru_RU" | "de_DE" | "pt_PT" | "it_IT" | "ko_KR" | "zh_TW" | "multi";
60
175
  };
61
176
  };
177
+ /**
178
+ * Send a request to the Blizzard API.
179
+ * @param resource The resource to fetch. See {@link Resource}.
180
+ * @param options Client options. See {@link ClientOptions}.
181
+ * @param headers Additional headers to include in the request.
182
+ * @returns The response from the Blizzard API. See {@link ResourceResponse}.
183
+ */
62
184
  sendRequest<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>, headers?: Record<string, string>): ResourceResponse<AxiosResponse<T>>;
185
+ /**
186
+ * Get an access token.
187
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
188
+ * @returns The access token. See {@link AccessToken}.
189
+ * @example
190
+ * const response = await client.getAccessToken();
191
+ * const { access_token, token_type, expires_in, sub } = response.data;
192
+ * console.log(access_token, token_type, expires_in, sub);
193
+ * // => 'access'
194
+ * // => 'bearer'
195
+ * // => 86399
196
+ * // => 'client-id'
197
+ */
63
198
  getAccessToken: (options?: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
199
+ /**
200
+ * Set the access token.
201
+ * @param token The access token.
202
+ */
64
203
  setAccessToken: (token: string) => void;
204
+ /**
205
+ * Refresh the access token.
206
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
207
+ * @returns The access token. See {@link AccessToken}.
208
+ * @example
209
+ * const response = await client.refreshAccessToken();
210
+ * const { access_token, token_type, expires_in, sub } = response.data;
211
+ * console.log(access_token, token_type, expires_in, sub);
212
+ * // => 'access'
213
+ * // => 'bearer'
214
+ * // => 86399
215
+ * // => 'client-id'
216
+ */
65
217
  refreshAccessToken: (options?: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
218
+ /**
219
+ * Validate an access token.
220
+ * @param options The validate access token arguments. See {@link ValidateAccessTokenArguments}.
221
+ * @returns The response from the Blizzard API. See {@link ValidateAccessTokenResponse}.
222
+ * @example
223
+ * const response = await client.validateAccessToken({ token: 'access' });
224
+ * console.log(response.data.client_id);
225
+ * // => 'client-id'
226
+ */
66
227
  validateAccessToken: (options?: ValidateAccessTokenArguments) => Promise<AxiosResponse<ValidateAccessTokenResponse>>;
67
228
  }
68
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
+ */
69
236
  declare const createBlizzardApiClient: (options: ClientOptions, onTokenRefresh?: boolean | ((token: AccessToken) => void)) => Promise<BlizzardApiClient>;
70
237
 
71
238
  export { type AccessToken, type AccessTokenRequestArguments, type ClientOptions, type IBlizzardApiClient, type ValidateAccessTokenArguments, type ValidateAccessTokenResponse, createBlizzardApiClient };
package/dist/index.d.ts CHANGED
@@ -1,21 +1,84 @@
1
1
  import { Origins, Locales, Resource, ResourceResponse } from '@blizzard-api/core';
2
2
  import { AxiosResponse } from 'axios';
3
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
+ */
4
21
  interface AccessToken {
5
22
  access_token: string;
6
23
  token_type: 'bearer';
7
24
  expires_in: number;
8
25
  sub?: string;
9
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
+ */
10
41
  interface AccessTokenRequestArguments {
11
42
  origin?: Origins;
12
43
  key?: string;
13
44
  secret?: string;
14
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
+ */
15
58
  interface ValidateAccessTokenArguments {
16
59
  origin?: Origins;
17
60
  token?: string;
18
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
+ */
19
82
  interface ValidateAccessTokenResponse {
20
83
  scope: Array<string>;
21
84
  account_authorities: Array<unknown>;
@@ -24,6 +87,23 @@ interface ValidateAccessTokenResponse {
24
87
  authorities: Array<string>;
25
88
  client_id: string;
26
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
+ */
27
107
  interface ClientOptions {
28
108
  key: string;
29
109
  secret: string;
@@ -31,6 +111,14 @@ interface ClientOptions {
31
111
  locale?: Locales;
32
112
  token?: string;
33
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
+ */
34
122
  interface IBlizzardApiClient {
35
123
  getAccessToken: (options: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
36
124
  setAccessToken: (token: string) => void;
@@ -38,6 +126,20 @@ interface IBlizzardApiClient {
38
126
  validateAccessToken: (options: ValidateAccessTokenArguments) => Promise<AxiosResponse<ValidateAccessTokenResponse>>;
39
127
  }
40
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
+ */
41
143
  declare class BlizzardApiClient implements IBlizzardApiClient {
42
144
  defaults: {
43
145
  key: string;
@@ -48,7 +150,20 @@ declare class BlizzardApiClient implements IBlizzardApiClient {
48
150
  };
49
151
  constructor(options: ClientOptions);
50
152
  private axios;
153
+ /**
154
+ * Get the request URL.
155
+ * @param resource The resource to fetch. See {@link Resource}.
156
+ * @param options Client options. See {@link ClientOptions}.
157
+ * @returns The request URL.
158
+ */
51
159
  getRequestUrl<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>): string;
160
+ /**
161
+ * Get the request configuration.
162
+ * @param resource The resource to fetch. See {@link Resource}.
163
+ * @param options Client options. See {@link ClientOptions}.
164
+ * @param headers Additional headers to include in the request.
165
+ * @returns The request configuration.
166
+ */
52
167
  getRequestConfig<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>, headers?: Record<string, string>): {
53
168
  headers: {
54
169
  'Content-Type': string;
@@ -59,13 +174,65 @@ declare class BlizzardApiClient implements IBlizzardApiClient {
59
174
  locale: "en_US" | "es_MX" | "pt_BR" | "en_GB" | "es_ES" | "fr_FR" | "ru_RU" | "de_DE" | "pt_PT" | "it_IT" | "ko_KR" | "zh_TW" | "multi";
60
175
  };
61
176
  };
177
+ /**
178
+ * Send a request to the Blizzard API.
179
+ * @param resource The resource to fetch. See {@link Resource}.
180
+ * @param options Client options. See {@link ClientOptions}.
181
+ * @param headers Additional headers to include in the request.
182
+ * @returns The response from the Blizzard API. See {@link ResourceResponse}.
183
+ */
62
184
  sendRequest<T, Protected extends boolean = false>(resource: Resource<T, object, Protected>, options?: Partial<ClientOptions>, headers?: Record<string, string>): ResourceResponse<AxiosResponse<T>>;
185
+ /**
186
+ * Get an access token.
187
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
188
+ * @returns The access token. See {@link AccessToken}.
189
+ * @example
190
+ * const response = await client.getAccessToken();
191
+ * const { access_token, token_type, expires_in, sub } = response.data;
192
+ * console.log(access_token, token_type, expires_in, sub);
193
+ * // => 'access'
194
+ * // => 'bearer'
195
+ * // => 86399
196
+ * // => 'client-id'
197
+ */
63
198
  getAccessToken: (options?: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
199
+ /**
200
+ * Set the access token.
201
+ * @param token The access token.
202
+ */
64
203
  setAccessToken: (token: string) => void;
204
+ /**
205
+ * Refresh the access token.
206
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
207
+ * @returns The access token. See {@link AccessToken}.
208
+ * @example
209
+ * const response = await client.refreshAccessToken();
210
+ * const { access_token, token_type, expires_in, sub } = response.data;
211
+ * console.log(access_token, token_type, expires_in, sub);
212
+ * // => 'access'
213
+ * // => 'bearer'
214
+ * // => 86399
215
+ * // => 'client-id'
216
+ */
65
217
  refreshAccessToken: (options?: AccessTokenRequestArguments) => Promise<AxiosResponse<AccessToken>>;
218
+ /**
219
+ * Validate an access token.
220
+ * @param options The validate access token arguments. See {@link ValidateAccessTokenArguments}.
221
+ * @returns The response from the Blizzard API. See {@link ValidateAccessTokenResponse}.
222
+ * @example
223
+ * const response = await client.validateAccessToken({ token: 'access' });
224
+ * console.log(response.data.client_id);
225
+ * // => 'client-id'
226
+ */
66
227
  validateAccessToken: (options?: ValidateAccessTokenArguments) => Promise<AxiosResponse<ValidateAccessTokenResponse>>;
67
228
  }
68
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
+ */
69
236
  declare const createBlizzardApiClient: (options: ClientOptions, onTokenRefresh?: boolean | ((token: AccessToken) => void)) => Promise<BlizzardApiClient>;
70
237
 
71
238
  export { type AccessToken, type AccessTokenRequestArguments, type ClientOptions, type IBlizzardApiClient, type ValidateAccessTokenArguments, type ValidateAccessTokenResponse, createBlizzardApiClient };
package/dist/index.js CHANGED
@@ -15,12 +15,25 @@ var BlizzardApiClient = class {
15
15
  };
16
16
  }
17
17
  axios = axios.create();
18
+ /**
19
+ * Get the request URL.
20
+ * @param resource The resource to fetch. See {@link Resource}.
21
+ * @param options Client options. See {@link ClientOptions}.
22
+ * @returns The request URL.
23
+ */
18
24
  getRequestUrl(resource, options) {
19
25
  const config = { ...this.defaults, ...options };
20
26
  const endpoint = getBlizzardApi(config.origin, config.locale);
21
27
  const backslashSeparator = resource.path.startsWith("/") ? "" : "/";
22
28
  return `${endpoint.hostname}${backslashSeparator}${resource.path}`;
23
29
  }
30
+ /**
31
+ * Get the request configuration.
32
+ * @param resource The resource to fetch. See {@link Resource}.
33
+ * @param options Client options. See {@link ClientOptions}.
34
+ * @param headers Additional headers to include in the request.
35
+ * @returns The request configuration.
36
+ */
24
37
  getRequestConfig(resource, options, headers) {
25
38
  const config = { ...this.defaults, ...options };
26
39
  const endpoint = getBlizzardApi(config.origin, config.locale);
@@ -38,6 +51,13 @@ var BlizzardApiClient = class {
38
51
  }
39
52
  };
40
53
  }
54
+ /**
55
+ * Send a request to the Blizzard API.
56
+ * @param resource The resource to fetch. See {@link Resource}.
57
+ * @param options Client options. See {@link ClientOptions}.
58
+ * @param headers Additional headers to include in the request.
59
+ * @returns The response from the Blizzard API. See {@link ResourceResponse}.
60
+ */
41
61
  async sendRequest(resource, options, headers) {
42
62
  const url = this.getRequestUrl(resource, options);
43
63
  const config = this.getRequestConfig(resource, options, headers);
@@ -50,6 +70,19 @@ var BlizzardApiClient = class {
50
70
  throw error;
51
71
  }
52
72
  }
73
+ /**
74
+ * Get an access token.
75
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
76
+ * @returns The access token. See {@link AccessToken}.
77
+ * @example
78
+ * const response = await client.getAccessToken();
79
+ * const { access_token, token_type, expires_in, sub } = response.data;
80
+ * console.log(access_token, token_type, expires_in, sub);
81
+ * // => 'access'
82
+ * // => 'bearer'
83
+ * // => 86399
84
+ * // => 'client-id'
85
+ */
53
86
  getAccessToken = async (options) => {
54
87
  const { key, secret, origin } = { ...this.defaults, ...options };
55
88
  return this.axios.post(`https://${origin}.battle.net/oauth/token`, void 0, {
@@ -65,14 +98,40 @@ var BlizzardApiClient = class {
65
98
  }
66
99
  });
67
100
  };
101
+ /**
102
+ * Set the access token.
103
+ * @param token The access token.
104
+ */
68
105
  setAccessToken = (token) => {
69
106
  this.defaults.token = token;
70
107
  };
108
+ /**
109
+ * Refresh the access token.
110
+ * @param options The access token request arguments. See {@link AccessTokenRequestArguments}.
111
+ * @returns The access token. See {@link AccessToken}.
112
+ * @example
113
+ * const response = await client.refreshAccessToken();
114
+ * const { access_token, token_type, expires_in, sub } = response.data;
115
+ * console.log(access_token, token_type, expires_in, sub);
116
+ * // => 'access'
117
+ * // => 'bearer'
118
+ * // => 86399
119
+ * // => 'client-id'
120
+ */
71
121
  refreshAccessToken = async (options) => {
72
122
  const response = await this.getAccessToken(options);
73
123
  this.setAccessToken(response.data.access_token);
74
124
  return response;
75
125
  };
126
+ /**
127
+ * Validate an access token.
128
+ * @param options The validate access token arguments. See {@link ValidateAccessTokenArguments}.
129
+ * @returns The response from the Blizzard API. See {@link ValidateAccessTokenResponse}.
130
+ * @example
131
+ * const response = await client.validateAccessToken({ token: 'access' });
132
+ * console.log(response.data.client_id);
133
+ * // => 'client-id'
134
+ */
76
135
  validateAccessToken = async (options) => {
77
136
  const { origin, token } = { ...this.defaults, ...options };
78
137
  if (!token) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/client.ts","../src/client/create-client.ts"],"sourcesContent":["import { stringify } from 'node:querystring';\r\nimport { getBlizzardApi } from '@blizzard-api/core';\r\nimport type { Origins, Locales, ResourceResponse, Resource } 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\nexport class BlizzardApiClient implements IBlizzardApiClient {\r\n public defaults: {\r\n key: string;\r\n secret: string;\r\n origin: Origins;\r\n locale: Locales;\r\n token?: string;\r\n };\r\n\r\n constructor(options: ClientOptions) {\r\n const { origin, locale } = getBlizzardApi(options.origin, options.locale);\r\n this.defaults = {\r\n key: options.key,\r\n secret: options.secret,\r\n token: options.token,\r\n origin: origin,\r\n locale: locale,\r\n };\r\n }\r\n\r\n private axios = axios.create();\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 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 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${config.token}`,\r\n },\r\n params: {\r\n locale: endpoint.locale,\r\n ...resource.parameters,\r\n },\r\n };\r\n }\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 public getAccessToken = async (options?: AccessTokenRequestArguments): Promise<AxiosResponse<AccessToken>> => {\r\n const { key, secret, origin } = { ...this.defaults, ...options };\r\n return this.axios.post<AccessToken>(`https://${origin}.battle.net/oauth/token`, undefined, {\r\n params: {\r\n grant_type: 'client_credentials',\r\n },\r\n auth: {\r\n username: key,\r\n password: secret,\r\n },\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n });\r\n };\r\n\r\n public setAccessToken = (token: string): void => {\r\n this.defaults.token = token;\r\n };\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 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","import { BlizzardApiClient } from './client';\r\nimport type { AccessToken, ClientOptions } from './types';\r\n\r\nconst getTokenExpiration = (expiresIn: number) => expiresIn * 1000 - 60_000;\r\n\r\nexport const createBlizzardApiClient = async (\r\n /**\r\n * Client options.\r\n * @see ClientOptions\r\n * @see https://develop.battle.net/documentation/guides/getting-started\r\n */\r\n options: ClientOptions,\r\n /**\r\n * Callback function to handle token refresh.\r\n *\r\n * If set to `true`, the client will automatically refresh the token.\r\n *\r\n * If set to `false`, the client will not refresh the token.\r\n *\r\n * If set to a function, the function will be called with the new token.\r\n */\r\n onTokenRefresh: boolean | ((token: AccessToken) => void) = 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"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAG/B,OAAO,SAAS,YAAY,oBAAoB;AAUzC,IAAM,oBAAN,MAAsD;AAAA,EACpD;AAAA,EAQP,YAAY,SAAwB;AAClC,UAAM,EAAE,QAAQ,OAAO,IAAI,eAAe,QAAQ,QAAQ,QAAQ,MAAM;AACxE,SAAK,WAAW;AAAA,MACd,KAAK,QAAQ;AAAA,MACb,QAAQ,QAAQ;AAAA,MAChB,OAAO,QAAQ;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,QAAQ,MAAM,OAAO;AAAA,EAEtB,cACL,UACA,SACA;AACA,UAAM,SAAS,EAAE,GAAG,KAAK,UAAU,GAAG,QAAQ;AAC9C,UAAM,WAAW,eAAe,OAAO,QAAQ,OAAO,MAAM;AAE5D,UAAM,qBAAqB,SAAS,KAAK,WAAW,GAAG,IAAI,KAAK;AAEhE,WAAO,GAAG,SAAS,QAAQ,GAAG,kBAAkB,GAAG,SAAS,IAAI;AAAA,EAClE;AAAA,EAEO,iBACL,UACA,SACA,SACA;AACA,UAAM,SAAS,EAAE,GAAG,KAAK,UAAU,GAAG,QAAQ;AAC9C,UAAM,WAAW,eAAe,OAAO,QAAQ,OAAO,MAAM;AAE5D,UAAM,YAAY,SAAS,YACvB,EAAE,uBAAuB,GAAG,SAAS,SAAS,IAAI,SAAS,MAAM,GAAG,IACp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AAA,MAChB;AAAA,IACF,QAAQ;AAEN,YAAM,aAAa;AAAA,IACrB;AAAA,EACF,OAAO;AAEL,UAAM,aAAa;AAAA,EACrB;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/client/client.ts","../src/client/create-client.ts"],"sourcesContent":["import { stringify } from 'node:querystring';\r\nimport { getBlizzardApi } from '@blizzard-api/core';\r\nimport type { Origins, Locales, ResourceResponse, Resource } 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 public defaults: {\r\n key: string;\r\n secret: string;\r\n origin: Origins;\r\n locale: Locales;\r\n token?: string;\r\n };\r\n\r\n constructor(options: ClientOptions) {\r\n const { origin, locale } = getBlizzardApi(options.origin, options.locale);\r\n this.defaults = {\r\n key: options.key,\r\n secret: options.secret,\r\n token: options.token,\r\n origin: origin,\r\n locale: locale,\r\n };\r\n }\r\n\r\n private axios = axios.create();\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 * 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 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${config.token}`,\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 * 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 /**\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, secret, origin } = { ...this.defaults, ...options };\r\n return this.axios.post<AccessToken>(`https://${origin}.battle.net/oauth/token`, undefined, {\r\n params: {\r\n grant_type: 'client_credentials',\r\n },\r\n auth: {\r\n username: key,\r\n password: secret,\r\n },\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n });\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 * 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 * 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","import { 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: boolean | ((token: AccessToken) => void) = 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"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAG/B,OAAO,SAAS,YAAY,oBAAoB;AAwBzC,IAAM,oBAAN,MAAsD;AAAA,EACpD;AAAA,EAQP,YAAY,SAAwB;AAClC,UAAM,EAAE,QAAQ,OAAO,IAAI,eAAe,QAAQ,QAAQ,QAAQ,MAAM;AACxE,SAAK,WAAW;AAAA,MACd,KAAK,QAAQ;AAAA,MACb,QAAQ,QAAQ;AAAA,MAChB,OAAO,QAAQ;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,QAAQ,MAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQtB,cACL,UACA,SACA;AACA,UAAM,SAAS,EAAE,GAAG,KAAK,UAAU,GAAG,QAAQ;AAC9C,UAAM,WAAW,eAAe,OAAO,QAAQ,OAAO,MAAM;AAE5D,UAAM,qBAAqB,SAAS,KAAK,WAAW,GAAG,IAAI,KAAK;AAEhE,WAAO,GAAG,SAAS,QAAQ,GAAG,kBAAkB,GAAG,SAAS,IAAI;AAAA,EAClE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,iBACL,UACA,SACA,SACA;AACA,UAAM,SAAS,EAAE,GAAG,KAAK,UAAU,GAAG,QAAQ;AAC9C,UAAM,WAAW,eAAe,OAAO,QAAQ,OAAO,MAAM;AAE5D,UAAM,YAAY,SAAS,YACvB,EAAE,uBAAuB,GAAG,SAAS,SAAS,IAAI,SAAS,MAAM,GAAG,IACpE;AAEJ,WAAO;AAAA,MACL,SAAS;AAAA,QACP,GAAG;AAA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;AACjE,YAAM,SAAS,mBAAmB,eAAe,KAAK,GAAG;AAEzD,UAAI,SAAS,KAAK,IAAI,IAAI,KAAQ;AAChC,cAAM,aAAa;AAAA,MACrB,OAAO;AAEL,cAAM,UAAU,WAAW,MAAM,KAAK,aAAa,GAAG,SAAS,KAAK,IAAI,CAAC;AAEzE,gBAAQ,MAAM;AAAA,MAChB;AAAA,IACF,QAAQ;AAEN,YAAM,aAAa;AAAA,IACrB;AAAA,EACF,OAAO;AAEL,UAAM,aAAa;AAAA,EACrB;AAEA,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@blizzard-api/client",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
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/tree/main/packages/client",
8
8
  "type": "module",
9
9
  "engines": {
10
- "node": ">=18 <19 || >=20"
10
+ "node": "^18.18 || ^20.9 || ^21.1 || ^22"
11
11
  },
12
12
  "main": "./dist/index.js",
13
13
  "exports": {
@@ -47,15 +47,16 @@
47
47
  "axios": "1.6.8"
48
48
  },
49
49
  "peerDependencies": {
50
- "@blizzard-api/core": "0.1.0"
50
+ "@blizzard-api/core": "0.1.2"
51
51
  },
52
52
  "devDependencies": {
53
- "@blizzard-api/core": "0.1.0",
54
- "@blizzard-api/wow": "0.2.2"
53
+ "@blizzard-api/classic-wow": "0.1.0",
54
+ "@blizzard-api/core": "0.1.2",
55
+ "@blizzard-api/wow": "0.2.4"
55
56
  },
56
57
  "scripts": {
57
58
  "build": "tsup",
58
- "debv": "tsup --watch",
59
+ "dev": "tsup --watch",
59
60
  "test": "vitest run",
60
61
  "test:coverage": "pnpm test -- --coverage",
61
62
  "test:watch": "vitest watch"