ani-client 1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gonzyui
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,178 @@
1
+ # ani-client
2
+
3
+ > A simple, typed client to fetch anime, manga, character, staff and user data from [AniList](https://anilist.co).
4
+
5
+ Works in **Node.js ≥ 18**, **Bun**, **Deno** and modern **browsers** — anywhere the `fetch` API is available.
6
+ Ships ESM + CJS bundles with full **TypeScript** declarations.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ # npm
12
+ npm install ani-client
13
+
14
+ # pnpm
15
+ pnpm add ani-client
16
+
17
+ # yarn
18
+ yarn add ani-client
19
+ ```
20
+
21
+ ## Quick start
22
+
23
+ ```ts
24
+ import { AniListClient, MediaType } from "ani-client";
25
+
26
+ const client = new AniListClient();
27
+
28
+ // Get an anime by ID
29
+ const cowboyBebop = await client.getMedia(1);
30
+ console.log(cowboyBebop.title.romaji); // "Cowboy Bebop"
31
+
32
+ // Search for anime
33
+ const results = await client.searchMedia({
34
+ query: "Naruto",
35
+ type: MediaType.ANIME,
36
+ perPage: 5,
37
+ });
38
+ console.log(results.results.map((m) => m.title.english));
39
+
40
+ // Trending anime
41
+ const trending = await client.getTrending(MediaType.ANIME);
42
+ console.log(trending.results[0].title.romaji);
43
+ ```
44
+
45
+ ### CommonJS
46
+
47
+ ```js
48
+ const { AniListClient } = require("ani-client");
49
+
50
+ const client = new AniListClient();
51
+ client.getMedia(1).then((anime) => console.log(anime.title.romaji));
52
+ ```
53
+
54
+ ## API
55
+
56
+ ### `new AniListClient(options?)`
57
+
58
+ | Option | Type | Default | Description |
59
+ | ----------- | -------- | -------------------------------- | ---------------------------------- |
60
+ | `token` | `string` | — | AniList OAuth bearer token |
61
+ | `apiUrl` | `string` | `https://graphql.anilist.co` | Custom API endpoint |
62
+ | `cache` | `object` | `{ ttl: 86400000, maxSize: 500, enabled: true }` | Cache configuration |
63
+ | `rateLimit` | `object` | `{ maxRequests: 85, windowMs: 60000, maxRetries: 3, enabled: true }` | Rate limiter configuration |
64
+
65
+ ### Media
66
+
67
+ | Method | Description |
68
+ | ----------------------------------- | ------------------------------------ |
69
+ | `getMedia(id: number)` | Fetch a single anime / manga by ID |
70
+ | `searchMedia(options?)` | Search & filter anime / manga |
71
+ | `getTrending(type?, page?, perPage?)` | Get currently trending entries |
72
+
73
+ ### Characters
74
+
75
+ | Method | Description |
76
+ | ----------------------------------- | ------------------------------------ |
77
+ | `getCharacter(id: number)` | Fetch a character by ID |
78
+ | `searchCharacters(options?)` | Search characters by name |
79
+
80
+ ### Staff
81
+
82
+ | Method | Description |
83
+ | ----------------------------------- | ------------------------------------ |
84
+ | `getStaff(id: number)` | Fetch a staff member by ID |
85
+ | `searchStaff(options?)` | Search for staff members |
86
+
87
+ ### Users
88
+
89
+ | Method | Description |
90
+ | ----------------------------------- | ------------------------------------ |
91
+ | `getUser(id: number)` | Fetch a user by ID |
92
+ | `getUserByName(name: string)` | Fetch a user by username |
93
+
94
+ ### Raw queries
95
+
96
+ | Method | Description |
97
+ | ----------------------------------- | ------------------------------------ |
98
+ | `raw<T>(query, variables?)` | Execute any GraphQL query |
99
+
100
+ ### Cache management
101
+
102
+ | Method / Property | Description |
103
+ | ----------------------------------- | ------------------------------------ |
104
+ | `clearCache()` | Clear the entire response cache |
105
+ | `cacheSize` | Number of entries currently cached |
106
+
107
+ ## Caching
108
+
109
+ All responses are cached in-memory by default (**24 hours TTL**, max 500 entries). Configure it per-client:
110
+
111
+ ```ts
112
+ const client = new AniListClient({
113
+ cache: {
114
+ ttl: 1000 * 60 * 60, // 1 hour
115
+ maxSize: 200, // keep at most 200 entries
116
+ enabled: true, // set to false to disable
117
+ },
118
+ });
119
+
120
+ // Manual cache control
121
+ client.clearCache();
122
+ console.log(client.cacheSize); // 0
123
+ ```
124
+
125
+ ## Rate limiting
126
+
127
+ The client automatically respects AniList's rate limit (90 req/min) with a conservative default of **85 req/min**. If you hit a `429 Too Many Requests`, it retries automatically (up to 3 times with backoff).
128
+
129
+ ```ts
130
+ const client = new AniListClient({
131
+ rateLimit: {
132
+ maxRequests: 60, // be extra conservative
133
+ windowMs: 60_000, // 1 minute window
134
+ maxRetries: 5, // retry up to 5 times on 429
135
+ retryDelayMs: 3000, // wait 3s between retries
136
+ enabled: true, // set to false to disable
137
+ },
138
+ });
139
+ ```
140
+
141
+ ## Error handling
142
+
143
+ All API errors throw an `AniListError` with:
144
+
145
+ - `message` — Human-readable error message
146
+ - `status` — HTTP status code
147
+ - `errors` — Raw error array from the API
148
+
149
+ ```ts
150
+ import { AniListClient, AniListError } from "ani-client";
151
+
152
+ try {
153
+ await client.getMedia(999999999);
154
+ } catch (err) {
155
+ if (err instanceof AniListError) {
156
+ console.error(err.message, err.status);
157
+ }
158
+ }
159
+ ```
160
+
161
+ ## Types
162
+
163
+ All types are exported and documented:
164
+
165
+ ```ts
166
+ import type {
167
+ Media,
168
+ Character,
169
+ Staff,
170
+ User,
171
+ PagedResult,
172
+ SearchMediaOptions,
173
+ } from "ani-client";
174
+ ```
175
+
176
+ ## License
177
+
178
+ [MIT](LICENSE) © gonzyui
@@ -0,0 +1,461 @@
1
+ declare enum MediaType {
2
+ ANIME = "ANIME",
3
+ MANGA = "MANGA"
4
+ }
5
+ declare enum MediaFormat {
6
+ TV = "TV",
7
+ TV_SHORT = "TV_SHORT",
8
+ MOVIE = "MOVIE",
9
+ SPECIAL = "SPECIAL",
10
+ OVA = "OVA",
11
+ ONA = "ONA",
12
+ MUSIC = "MUSIC",
13
+ MANGA = "MANGA",
14
+ NOVEL = "NOVEL",
15
+ ONE_SHOT = "ONE_SHOT"
16
+ }
17
+ declare enum MediaStatus {
18
+ FINISHED = "FINISHED",
19
+ RELEASING = "RELEASING",
20
+ NOT_YET_RELEASED = "NOT_YET_RELEASED",
21
+ CANCELLED = "CANCELLED",
22
+ HIATUS = "HIATUS"
23
+ }
24
+ declare enum MediaSeason {
25
+ WINTER = "WINTER",
26
+ SPRING = "SPRING",
27
+ SUMMER = "SUMMER",
28
+ FALL = "FALL"
29
+ }
30
+ declare enum MediaSort {
31
+ ID = "ID",
32
+ TITLE_ROMAJI = "TITLE_ROMAJI",
33
+ TITLE_ENGLISH = "TITLE_ENGLISH",
34
+ TITLE_NATIVE = "TITLE_NATIVE",
35
+ TYPE = "TYPE",
36
+ FORMAT = "FORMAT",
37
+ START_DATE = "START_DATE",
38
+ END_DATE = "END_DATE",
39
+ SCORE = "SCORE",
40
+ POPULARITY = "POPULARITY",
41
+ TRENDING = "TRENDING",
42
+ EPISODES = "EPISODES",
43
+ DURATION = "DURATION",
44
+ STATUS = "STATUS",
45
+ FAVOURITES = "FAVOURITES",
46
+ UPDATED_AT = "UPDATED_AT",
47
+ SEARCH_MATCH = "SEARCH_MATCH"
48
+ }
49
+ declare enum CharacterSort {
50
+ ID = "ID",
51
+ ROLE = "ROLE",
52
+ SEARCH_MATCH = "SEARCH_MATCH",
53
+ FAVOURITES = "FAVOURITES"
54
+ }
55
+ interface MediaTitle {
56
+ romaji: string | null;
57
+ english: string | null;
58
+ native: string | null;
59
+ userPreferred: string | null;
60
+ }
61
+ interface MediaCoverImage {
62
+ extraLarge: string | null;
63
+ large: string | null;
64
+ medium: string | null;
65
+ color: string | null;
66
+ }
67
+ interface FuzzyDate {
68
+ year: number | null;
69
+ month: number | null;
70
+ day: number | null;
71
+ }
72
+ interface MediaTrailer {
73
+ id: string | null;
74
+ site: string | null;
75
+ thumbnail: string | null;
76
+ }
77
+ interface MediaTag {
78
+ id: number;
79
+ name: string;
80
+ description: string | null;
81
+ category: string | null;
82
+ rank: number | null;
83
+ isMediaSpoiler: boolean | null;
84
+ }
85
+ interface Studio {
86
+ id: number;
87
+ name: string;
88
+ isAnimationStudio: boolean;
89
+ siteUrl: string | null;
90
+ }
91
+ interface StudioConnection {
92
+ nodes: Studio[];
93
+ }
94
+ interface CharacterName {
95
+ first: string | null;
96
+ middle: string | null;
97
+ last: string | null;
98
+ full: string | null;
99
+ native: string | null;
100
+ alternative: string[];
101
+ }
102
+ interface CharacterImage {
103
+ large: string | null;
104
+ medium: string | null;
105
+ }
106
+ interface Media {
107
+ id: number;
108
+ idMal: number | null;
109
+ title: MediaTitle;
110
+ type: MediaType;
111
+ format: MediaFormat | null;
112
+ status: MediaStatus | null;
113
+ description: string | null;
114
+ startDate: FuzzyDate | null;
115
+ endDate: FuzzyDate | null;
116
+ season: MediaSeason | null;
117
+ seasonYear: number | null;
118
+ episodes: number | null;
119
+ duration: number | null;
120
+ chapters: number | null;
121
+ volumes: number | null;
122
+ countryOfOrigin: string | null;
123
+ isLicensed: boolean | null;
124
+ source: string | null;
125
+ hashtag: string | null;
126
+ trailer: MediaTrailer | null;
127
+ coverImage: MediaCoverImage;
128
+ bannerImage: string | null;
129
+ genres: string[];
130
+ synonyms: string[];
131
+ averageScore: number | null;
132
+ meanScore: number | null;
133
+ popularity: number | null;
134
+ favourites: number | null;
135
+ trending: number | null;
136
+ tags: MediaTag[];
137
+ studios: StudioConnection;
138
+ isAdult: boolean | null;
139
+ siteUrl: string | null;
140
+ }
141
+ interface Character {
142
+ id: number;
143
+ name: CharacterName;
144
+ image: CharacterImage;
145
+ description: string | null;
146
+ gender: string | null;
147
+ dateOfBirth: FuzzyDate | null;
148
+ age: string | null;
149
+ bloodType: string | null;
150
+ favourites: number | null;
151
+ siteUrl: string | null;
152
+ media: {
153
+ nodes: Pick<Media, "id" | "title" | "type" | "coverImage" | "siteUrl">[];
154
+ } | null;
155
+ }
156
+ interface StaffName {
157
+ first: string | null;
158
+ middle: string | null;
159
+ last: string | null;
160
+ full: string | null;
161
+ native: string | null;
162
+ }
163
+ interface StaffImage {
164
+ large: string | null;
165
+ medium: string | null;
166
+ }
167
+ interface Staff {
168
+ id: number;
169
+ name: StaffName;
170
+ language: string | null;
171
+ image: StaffImage;
172
+ description: string | null;
173
+ primaryOccupations: string[];
174
+ gender: string | null;
175
+ dateOfBirth: FuzzyDate | null;
176
+ dateOfDeath: FuzzyDate | null;
177
+ age: number | null;
178
+ yearsActive: number[];
179
+ homeTown: string | null;
180
+ bloodType: string | null;
181
+ favourites: number | null;
182
+ siteUrl: string | null;
183
+ }
184
+ interface UserAvatar {
185
+ large: string | null;
186
+ medium: string | null;
187
+ }
188
+ interface UserStatistics {
189
+ count: number;
190
+ meanScore: number;
191
+ minutesWatched: number;
192
+ episodesWatched: number;
193
+ chaptersRead: number;
194
+ volumesRead: number;
195
+ }
196
+ interface User {
197
+ id: number;
198
+ name: string;
199
+ about: string | null;
200
+ avatar: UserAvatar;
201
+ bannerImage: string | null;
202
+ isFollowing: boolean | null;
203
+ isFollower: boolean | null;
204
+ donatorTier: number | null;
205
+ donatorBadge: string | null;
206
+ createdAt: number | null;
207
+ siteUrl: string | null;
208
+ statistics: {
209
+ anime: UserStatistics;
210
+ manga: UserStatistics;
211
+ } | null;
212
+ }
213
+ interface PageInfo {
214
+ total: number | null;
215
+ perPage: number | null;
216
+ currentPage: number | null;
217
+ lastPage: number | null;
218
+ hasNextPage: boolean | null;
219
+ }
220
+ interface SearchMediaOptions {
221
+ query?: string;
222
+ type?: MediaType;
223
+ format?: MediaFormat;
224
+ status?: MediaStatus;
225
+ season?: MediaSeason;
226
+ seasonYear?: number;
227
+ genre?: string;
228
+ tag?: string;
229
+ isAdult?: boolean;
230
+ sort?: MediaSort[];
231
+ page?: number;
232
+ perPage?: number;
233
+ }
234
+ interface SearchCharacterOptions {
235
+ query?: string;
236
+ sort?: CharacterSort[];
237
+ page?: number;
238
+ perPage?: number;
239
+ }
240
+ interface SearchStaffOptions {
241
+ query?: string;
242
+ page?: number;
243
+ perPage?: number;
244
+ }
245
+ interface PagedResult<T> {
246
+ pageInfo: PageInfo;
247
+ results: T[];
248
+ }
249
+ interface AniListClientOptions {
250
+ /** Optional AniList OAuth token for authenticated requests */
251
+ token?: string;
252
+ /** Custom API endpoint (defaults to https://graphql.anilist.co) */
253
+ apiUrl?: string;
254
+ /** Cache configuration (enabled by default, 24h TTL) */
255
+ cache?: {
256
+ /** Time-to-live in milliseconds (default: 86 400 000 = 24h) */
257
+ ttl?: number;
258
+ /** Maximum number of cached entries (default: 500, 0 = unlimited) */
259
+ maxSize?: number;
260
+ /** Set to false to disable caching entirely */
261
+ enabled?: boolean;
262
+ };
263
+ /** Rate limiter configuration (enabled by default, 85 req/min) */
264
+ rateLimit?: {
265
+ /** Max requests per window (default: 85) */
266
+ maxRequests?: number;
267
+ /** Window size in ms (default: 60 000) */
268
+ windowMs?: number;
269
+ /** Max retries on 429 (default: 3) */
270
+ maxRetries?: number;
271
+ /** Retry delay in ms when Retry-After header is absent (default: 2000) */
272
+ retryDelayMs?: number;
273
+ /** Set to false to disable rate limiting entirely */
274
+ enabled?: boolean;
275
+ };
276
+ }
277
+
278
+ /**
279
+ * Lightweight AniList GraphQL client with built-in caching and rate limiting.
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * import { AniListClient } from "ani-client";
284
+ *
285
+ * const client = new AniListClient();
286
+ * const anime = await client.getMedia(1); // Cowboy Bebop
287
+ * console.log(anime.title.romaji);
288
+ *
289
+ * // Custom cache & rate limit options
290
+ * const client2 = new AniListClient({
291
+ * cache: { ttl: 1000 * 60 * 60 }, // 1 hour cache
292
+ * rateLimit: { maxRequests: 60 },
293
+ * });
294
+ * ```
295
+ */
296
+ declare class AniListClient {
297
+ private readonly apiUrl;
298
+ private readonly headers;
299
+ private readonly cache;
300
+ private readonly rateLimiter;
301
+ constructor(options?: AniListClientOptions);
302
+ /**
303
+ * @internal
304
+ */
305
+ private request;
306
+ /**
307
+ * Fetch a single media entry by its AniList ID.
308
+ *
309
+ * @param id - The AniList media ID
310
+ * @returns The media object
311
+ */
312
+ getMedia(id: number): Promise<Media>;
313
+ /**
314
+ * Search for anime or manga.
315
+ *
316
+ * @param options - Search / filter parameters
317
+ * @returns Paginated results with matching media
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * const results = await client.searchMedia({
322
+ * query: "Naruto",
323
+ * type: MediaType.ANIME,
324
+ * perPage: 5,
325
+ * });
326
+ * ```
327
+ */
328
+ searchMedia(options?: SearchMediaOptions): Promise<PagedResult<Media>>;
329
+ /**
330
+ * Get currently trending anime or manga.
331
+ *
332
+ * @param type - `MediaType.ANIME` or `MediaType.MANGA` (defaults to ANIME)
333
+ * @param page - Page number (default 1)
334
+ * @param perPage - Results per page (default 20, max 50)
335
+ */
336
+ getTrending(type?: MediaType, page?: number, perPage?: number): Promise<PagedResult<Media>>;
337
+ /**
338
+ * Fetch a character by AniList ID.
339
+ */
340
+ getCharacter(id: number): Promise<Character>;
341
+ /**
342
+ * Search for characters by name.
343
+ */
344
+ searchCharacters(options?: SearchCharacterOptions): Promise<PagedResult<Character>>;
345
+ /**
346
+ * Fetch a staff member by AniList ID.
347
+ */
348
+ getStaff(id: number): Promise<Staff>;
349
+ /**
350
+ * Search for staff (voice actors, directors, etc.).
351
+ */
352
+ searchStaff(options?: SearchStaffOptions): Promise<PagedResult<Staff>>;
353
+ /**
354
+ * Fetch a user by AniList ID.
355
+ */
356
+ getUser(id: number): Promise<User>;
357
+ /**
358
+ * Fetch a user by username.
359
+ */
360
+ getUserByName(name: string): Promise<User>;
361
+ /**
362
+ * Execute an arbitrary GraphQL query against the AniList API.
363
+ * Useful for advanced use-cases not covered by the built-in methods.
364
+ *
365
+ * @param query - A valid GraphQL query string
366
+ * @param variables - Optional variables object
367
+ */
368
+ raw<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T>;
369
+ /**
370
+ * Clear the entire response cache.
371
+ */
372
+ clearCache(): void;
373
+ /**
374
+ * Number of entries currently in the cache.
375
+ */
376
+ get cacheSize(): number;
377
+ }
378
+
379
+ /**
380
+ * Custom error class for AniList API errors.
381
+ */
382
+ declare class AniListError extends Error {
383
+ /** HTTP status code returned by the API */
384
+ readonly status: number;
385
+ /** Raw error body from the API response */
386
+ readonly errors: unknown[];
387
+ constructor(message: string, status: number, errors?: unknown[]);
388
+ }
389
+
390
+ /**
391
+ * Simple in-memory cache with configurable TTL.
392
+ * Used internally by AniListClient to avoid redundant API calls.
393
+ */
394
+ interface CacheOptions {
395
+ /** Time-to-live in milliseconds (default: 24 hours) */
396
+ ttl?: number;
397
+ /** Maximum number of entries to keep (default: 500, 0 = unlimited) */
398
+ maxSize?: number;
399
+ /** Disable caching entirely (default: false) */
400
+ enabled?: boolean;
401
+ }
402
+ declare class MemoryCache {
403
+ private readonly ttl;
404
+ private readonly maxSize;
405
+ private readonly enabled;
406
+ private readonly store;
407
+ constructor(options?: CacheOptions);
408
+ /** Build a deterministic cache key from a query + variables pair. */
409
+ static key(query: string, variables: Record<string, unknown>): string;
410
+ /** Retrieve a cached value, or `undefined` if missing / expired. */
411
+ get<T>(key: string): T | undefined;
412
+ /** Store a value in the cache. */
413
+ set<T>(key: string, data: T): void;
414
+ /** Remove a specific entry. */
415
+ delete(key: string): boolean;
416
+ /** Clear the entire cache. */
417
+ clear(): void;
418
+ /** Number of entries currently stored. */
419
+ get size(): number;
420
+ }
421
+
422
+ /**
423
+ * Rate limiter with automatic retry for AniList API.
424
+ *
425
+ * AniList allows 90 requests per minute.
426
+ * When a 429 (Too Many Requests) is received, the client
427
+ * waits for the Retry-After header and retries automatically.
428
+ */
429
+ interface RateLimitOptions {
430
+ /** Max requests per window (default: 85, conservative under AniList's 90/min) */
431
+ maxRequests?: number;
432
+ /** Window size in milliseconds (default: 60 000 = 1 minute) */
433
+ windowMs?: number;
434
+ /** Max number of retries on 429 responses (default: 3) */
435
+ maxRetries?: number;
436
+ /** Default retry delay in ms when Retry-After header is missing (default: 2000) */
437
+ retryDelayMs?: number;
438
+ /** Disable rate limiting entirely (default: false) */
439
+ enabled?: boolean;
440
+ }
441
+ declare class RateLimiter {
442
+ private readonly maxRequests;
443
+ private readonly windowMs;
444
+ private readonly maxRetries;
445
+ private readonly retryDelayMs;
446
+ private readonly enabled;
447
+ /** @internal */
448
+ private timestamps;
449
+ constructor(options?: RateLimitOptions);
450
+ /**
451
+ * Wait until it's safe to make a request (respects rate limit window).
452
+ */
453
+ acquire(): Promise<void>;
454
+ /**
455
+ * Execute a fetch with automatic retry on 429 responses.
456
+ */
457
+ fetchWithRetry(url: string, init: RequestInit): Promise<Response>;
458
+ private sleep;
459
+ }
460
+
461
+ export { AniListClient, type AniListClientOptions, AniListError, type CacheOptions, type Character, type CharacterImage, type CharacterName, CharacterSort, type FuzzyDate, type Media, type MediaCoverImage, MediaFormat, MediaSeason, MediaSort, MediaStatus, type MediaTag, type MediaTitle, type MediaTrailer, MediaType, MemoryCache, type PageInfo, type PagedResult, type RateLimitOptions, RateLimiter, type SearchCharacterOptions, type SearchMediaOptions, type SearchStaffOptions, type Staff, type StaffImage, type StaffName, type Studio, type StudioConnection, type User, type UserAvatar, type UserStatistics };