scryfall-api 3.2.5 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2021-2022 Mario Menéndez
3
+ Copyright (c) 2021-2024 MarioMH
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,42 +1,93 @@
1
- # scryfall-api
1
+ ![banner.png](.idea%2Fbanner.png)
2
2
 
3
- [![npm](https://img.shields.io/npm/v/scryfall-api?style=flat-square)](https://www.npmjs.com/package/scryfall-api)
4
- [![GitHub issues](https://img.shields.io/github/issues/mariomh8/scryfall-api?style=flat-square)](https://github.com/MarioMH8/scryfall-api)
3
+ <h1 align="center">
4
+ scryfall-api
5
+ </h1>
5
6
 
6
- A Javascript library for [Scryfall](https://scryfall.com/docs/api) written in Typescript.
7
+ <p align="center">
8
+ A Javascript library for <a href='https://scryfall.com/docs/api' target='_blank'>scryfall.com</a> written in Typescript.
9
+ </p>
7
10
 
8
- As of [August 6th, 2022](./CHANGELOG.md), almost all features described in
9
- the [Scryfall documentation](https://scryfall.com/docs/api) are supported. If you see something that isn't supported,
10
- make an issue! See [support readme](./SUPPORT.md).
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/scryfall-api" rel="nofollow">
13
+ <img src="https://camo.githubusercontent.com/a172c58fbefc7103cb230b872119a85914a463f32958ea9e4e1f3ad9d7e1a100/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f762f7363727966616c6c2d6170693f7374796c653d666c61742d737175617265" alt="npm" data-canonical-src="https://img.shields.io/npm/v/scryfall-api?style=flat-square" style="max-width: 100%;">
14
+ </a>
15
+ <a href="https://github.com/MarioMH8/scryfall-api">
16
+ <img src="https://camo.githubusercontent.com/93378eea577b6b00f04b1fbfa5dc6871778ff3f6b4de76833a6211d35770f6c4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f6d6172696f6d68382f7363727966616c6c2d6170693f7374796c653d666c61742d737175617265" alt="GitHub issues" data-canonical-src="https://img.shields.io/github/issues/mariomh8/scryfall-api?style=flat-square" style="max-width: 100%;">
17
+ </a>
18
+ </p>
19
+
20
+ ## Table of Contents
21
+
22
+ - [Installation](#installation)
23
+ - [Documentation](#documentation)
24
+ - [Contributing](#contributing)
11
25
 
12
26
  ## Installation
13
27
 
14
- ```bat
15
- npm install scryfall-api
28
+ ```bash
29
+ npm install --save scryfall-api
30
+ ```
31
+
32
+ **Using bun**
33
+
34
+ ```bash
35
+ bun add scryfall-api
16
36
  ```
17
37
 
18
38
  ## Documentation
19
39
 
20
- Link to [documentation.](./DOCUMENTATION.md)
40
+ In the documentation below, requiring the package is assumed.
41
+
42
+ ```js
43
+ import scryfall from 'scryfall-api';
44
+ ```
45
+
46
+
47
+ **With CommonJS**
48
+
49
+ ```js
50
+ const scryfall = require('scryfall-api');
51
+ ```
52
+
53
+ **If you only need Cards**
54
+
55
+ ```js
56
+ import { Cards } from 'scryfall-api';
57
+ ```
58
+
59
+ Link to [full documentation.](./DOCUMENTATION.md)
21
60
 
22
61
  ## Contributing
23
62
 
63
+ This project uses [Bun](https://bun.sh) as a runtime, test runner and bundler.
64
+
24
65
  Thanks for wanting to help out! Here's the setup you'll have to do:
25
66
 
26
- ```bat
67
+ Clone the project
68
+
69
+ ```bash
27
70
  git clone git@github.com:MarioMH8/scryfall-api.git
71
+ ```
72
+
73
+ Go to the project directory
74
+
75
+ ```bash
28
76
  cd scryfall-api
29
- yarn install
30
77
  ```
31
78
 
32
- You can now make changes to the repository.
79
+ Install dependencies
80
+
81
+ ```bash
82
+ bun install
83
+ ```
33
84
 
34
- To compile:
85
+ Compile the project
35
86
 
36
- ```bat
37
- yarn build
87
+ ```bash
88
+ bun run build
38
89
  ```
39
90
 
40
91
  ## MIT License
41
92
 
42
- [Copyright 2021-2022 Mario Menéndez](./LICENSE)
93
+ [Copyright 2021-2024 MarioMH](./LICENSE)
@@ -0,0 +1,488 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/scryfall-api.ts
21
+ var scryfall_api_exports = {};
22
+ __export(scryfall_api_exports, {
23
+ CardIdentifierBuilder: () => card_identifier_default,
24
+ Cards: () => card_default,
25
+ Catalogs: () => catalog_default,
26
+ InvalidScryfallArgumentError: () => InvalidScryfallArgumentError,
27
+ MagicPageResult: () => MagicPageResult,
28
+ Rulings: () => ruling_default,
29
+ ScryfallError: () => ScryfallError,
30
+ Sets: () => set_default,
31
+ SymbologyApi: () => symbology_default,
32
+ UnknownScryfallError: () => UnknownScryfallError
33
+ });
34
+ module.exports = __toCommonJS(scryfall_api_exports);
35
+
36
+ // src/error/invalid.error.ts
37
+ var InvalidScryfallArgumentError = class extends Error {
38
+ };
39
+
40
+ // src/error/scryfall.error.ts
41
+ var ScryfallError = class extends Error {
42
+ constructor(code, details, status, type, warnings) {
43
+ super(details);
44
+ this.code = code;
45
+ this.status = status;
46
+ this.type = type;
47
+ this.warnings = warnings;
48
+ }
49
+ };
50
+
51
+ // src/error/unknown.error.ts
52
+ var UnknownScryfallError = class extends Error {
53
+ };
54
+
55
+ // src/fetcher/debounce.fetcher.ts
56
+ var lastQuery = 100;
57
+ var rateLimit = 100;
58
+ async function sleep(ms = 0) {
59
+ return new Promise((resolve) => {
60
+ setTimeout(resolve, ms);
61
+ });
62
+ }
63
+ async function debounce() {
64
+ const now = Date.now();
65
+ const timeSinceLastQuery = now - lastQuery;
66
+ if (timeSinceLastQuery >= rateLimit) {
67
+ lastQuery = now;
68
+ } else {
69
+ const timeUntilNextQuery = rateLimit - timeSinceLastQuery;
70
+ lastQuery += timeUntilNextQuery;
71
+ await sleep(timeUntilNextQuery);
72
+ }
73
+ }
74
+ function createDebounceFetcher(fetcher2 = fetch) {
75
+ return async function debounceFetcher(...args) {
76
+ await debounce();
77
+ return fetcher2(...args);
78
+ };
79
+ }
80
+
81
+ // src/fetcher/page.result.ts
82
+ var MagicPageResult = class {
83
+ constructor(apiPath, query) {
84
+ this.apiPath = apiPath;
85
+ this.query = query;
86
+ this.#hasMore = true;
87
+ this.#count = 0;
88
+ }
89
+ #count;
90
+ #hasMore;
91
+ get count() {
92
+ return this.#count;
93
+ }
94
+ get hasMore() {
95
+ return this.#hasMore;
96
+ }
97
+ async all() {
98
+ const r = [];
99
+ while (this.#hasMore) {
100
+ const result = await this.next();
101
+ r.push(...result);
102
+ }
103
+ return r;
104
+ }
105
+ async get(limit) {
106
+ const r = [];
107
+ while (this.#hasMore) {
108
+ const result = await this.next();
109
+ r.push(...result);
110
+ if (r.length === limit) {
111
+ return r;
112
+ }
113
+ if (r.length > limit) {
114
+ return r.slice(0, limit);
115
+ }
116
+ }
117
+ return r;
118
+ }
119
+ async next() {
120
+ const results = await fetcher(this.apiPath, this.query);
121
+ this.#hasMore = results?.has_more ?? false;
122
+ this.#count = Number.parseInt(`${results?.total_cards ?? 0}`, 10);
123
+ if (this.#hasMore) {
124
+ this.setNextPage();
125
+ }
126
+ return results?.data ?? [];
127
+ }
128
+ async page(page) {
129
+ this.query.page = page;
130
+ return this.next();
131
+ }
132
+ setNextPage() {
133
+ this.query.page += 1;
134
+ }
135
+ };
136
+
137
+ // src/fetcher/retry.fetcher.ts
138
+ var defaultCanRetry = async (response) => {
139
+ const object = await response.json();
140
+ const status = "status" in object ? Number(object.status) : void 0;
141
+ if (status && status >= 500) {
142
+ return true;
143
+ }
144
+ const code = "code" in object && typeof object.code === "string" ? object.code : void 0;
145
+ return code !== "not_found" && code !== "bad_request";
146
+ };
147
+ function createRetryFetcher({ maxAttempts = 3, canRetry = defaultCanRetry } = {}, fetcher2 = fetch) {
148
+ let retries = 0;
149
+ return async function retryFetcher(...args) {
150
+ retries++;
151
+ const response = await fetcher2(...args);
152
+ if (response.ok) {
153
+ return response;
154
+ }
155
+ const object = await response.json();
156
+ const code = "code" in object && typeof object.code === "string" ? object.code : void 0;
157
+ const status = "status" in object ? Number(object.status) : void 0;
158
+ const details = "details" in object && typeof object.details === "string" ? object.details : void 0;
159
+ const type = "type" in object && typeof object.type === "string" ? object.type : void 0;
160
+ const warnings = "warnings" in object && Array.isArray(object.warnings) ? object.warnings : void 0;
161
+ if (retries >= maxAttempts) {
162
+ if (code && details && status) {
163
+ throw new ScryfallError(code, details, status, type, warnings);
164
+ }
165
+ throw new UnknownScryfallError(`Request failed with status ${response.status}`);
166
+ }
167
+ if (canRetry(response)) {
168
+ return retryFetcher(...args);
169
+ }
170
+ if (code && details && status) {
171
+ throw new ScryfallError(code, details, status, type, warnings);
172
+ }
173
+ throw new UnknownScryfallError(`Request failed with status ${response.status}`);
174
+ };
175
+ }
176
+
177
+ // src/fetcher/index.ts
178
+ var simpleFetcher = createDebounceFetcher(createRetryFetcher());
179
+ var endpoint = "https://api.scryfall.com";
180
+ var DATE_REGEXP = /^\d{4}-\d{2}-\d{2}?$/;
181
+ var dateParser = (_key, value) => {
182
+ if (typeof value === "string") {
183
+ if (DATE_REGEXP.test(value)) {
184
+ return new Date(value);
185
+ }
186
+ }
187
+ return value;
188
+ };
189
+ async function fetcher(apiPath, params, body) {
190
+ let path = "";
191
+ if (typeof apiPath === "number" || typeof apiPath === "string") {
192
+ path = apiPath;
193
+ } else if (apiPath) {
194
+ path = apiPath.join("/");
195
+ }
196
+ const url = new URL(`${endpoint}/${path}`);
197
+ if (params) {
198
+ Object.entries(params).forEach(([key, value]) => {
199
+ if (value !== void 0) {
200
+ url.searchParams.append(key, `${value}`);
201
+ }
202
+ });
203
+ }
204
+ try {
205
+ const init = {
206
+ method: body ? "POST" : "GET"
207
+ };
208
+ if (body) {
209
+ init.body = JSON.stringify(body);
210
+ init.headers = {
211
+ "Content-Type": "application/json"
212
+ };
213
+ }
214
+ const response = await simpleFetcher(url, init);
215
+ const content = await response.text();
216
+ return JSON.parse(content, dateParser);
217
+ } catch (e) {
218
+ if (e instanceof ScryfallError) {
219
+ if (e.warnings) {
220
+ console.warn(e.warnings);
221
+ }
222
+ if (e.code === "not_found" || e.code === "bad_request") {
223
+ return void 0;
224
+ }
225
+ }
226
+ throw e;
227
+ }
228
+ }
229
+
230
+ // src/api/card/card.api.ts
231
+ var CardApi = class {
232
+ /*
233
+ * Returns up to 20 full English card names that could be autocompletions of the given string parameter.
234
+ * @param {string} name
235
+ * The string to search for
236
+ * @returns {Promise<string[]>}
237
+ * A list of up to 20 full English card names.
238
+ */
239
+ async autoCompleteName(name) {
240
+ const result = await fetcher("cards/autocomplete", {
241
+ q: name
242
+ });
243
+ return result?.data ?? [];
244
+ }
245
+ /*
246
+ * Returns a single card with the given Magic: The Gathering Arena ID.
247
+ * @param {number} id
248
+ * The Magic: The Gathering Arena ID of the card to retrieve.
249
+ * @returns {Promise<Card | undefined>}
250
+ * Returns a single card or undefined if no card is found.
251
+ */
252
+ async byArenaId(id) {
253
+ return fetcher(["cards/arena", id]);
254
+ }
255
+ /*
256
+ * Returns a single card with the given Scryfall ID.
257
+ * @param {number} id
258
+ * The Scryfall ID.
259
+ * @returns {Promise<Card | undefined>}
260
+ * Returns a single card or undefined if no card is found.
261
+ */
262
+ async byId(id) {
263
+ return fetcher(["cards", id]);
264
+ }
265
+ async byMtgoId(id) {
266
+ return fetcher(["cards/mtgo", id]);
267
+ }
268
+ async byMultiverseId(id) {
269
+ return fetcher(["cards/multiverse", id]);
270
+ }
271
+ async byName(name, set2, fuzzy = false) {
272
+ let f = fuzzy;
273
+ let s = set2;
274
+ if (typeof set2 === "boolean") {
275
+ f = set2;
276
+ s = void 0;
277
+ }
278
+ return fetcher("cards/named", {
279
+ [f ? "fuzzy" : "exact"]: name,
280
+ set: s
281
+ });
282
+ }
283
+ async bySet(setCode, collectorNumber, lang) {
284
+ const path = ["cards", setCode, collectorNumber];
285
+ if (lang) {
286
+ path.push(lang);
287
+ }
288
+ return fetcher(path);
289
+ }
290
+ async byTcgPlayerId(id) {
291
+ return fetcher(["cards/tcgplayer", id]);
292
+ }
293
+ async collection(...identifiers) {
294
+ const cards2 = [];
295
+ for (let i = 0; i < identifiers.length; i += 75) {
296
+ const collectionSection = { identifiers: identifiers.slice(i, i + 75) };
297
+ const result = await fetcher(
298
+ "cards/collection",
299
+ void 0,
300
+ collectionSection
301
+ );
302
+ cards2.push(...result?.data ?? []);
303
+ }
304
+ return cards2;
305
+ }
306
+ async random() {
307
+ return fetcher("cards/random");
308
+ }
309
+ search(query, options) {
310
+ return new MagicPageResult("cards/search", {
311
+ q: query,
312
+ ...typeof options === "number" ? { page: options } : { ...options, page: options?.page ?? 1 }
313
+ });
314
+ }
315
+ };
316
+ var cards = new CardApi();
317
+ var card_api_default = cards;
318
+
319
+ // src/api/card/index.ts
320
+ var card_default = card_api_default;
321
+
322
+ // src/api/card-identifier/card-identifier.api.ts
323
+ var CardIdentifierApi = class {
324
+ static byId(id) {
325
+ return { id };
326
+ }
327
+ static byIllustrationId(id) {
328
+ return { illustration_id: id };
329
+ }
330
+ static byMtgoId(id) {
331
+ return { mtgo_id: id };
332
+ }
333
+ static byMultiverseId(id) {
334
+ return { multiverse_id: id };
335
+ }
336
+ static byName(name, set2) {
337
+ if (set2) {
338
+ return { name, set: set2 };
339
+ }
340
+ return { name };
341
+ }
342
+ static byOracleId(id) {
343
+ return { oracle_id: id };
344
+ }
345
+ static bySet(set2, collectorNumber) {
346
+ return { collector_number: `${collectorNumber}`, set: set2 };
347
+ }
348
+ };
349
+
350
+ // src/api/card-identifier/index.ts
351
+ var card_identifier_default = CardIdentifierApi;
352
+
353
+ // src/api/catalog/catalog.api.ts
354
+ var CatalogApi = class {
355
+ async artifactTypes() {
356
+ return (await fetcher("catalog/artifact-types"))?.data ?? [];
357
+ }
358
+ async artistNames() {
359
+ return (await fetcher("catalog/artist-names"))?.data ?? [];
360
+ }
361
+ async cardNames() {
362
+ return (await fetcher("catalog/card-names"))?.data ?? [];
363
+ }
364
+ async creatureTypes() {
365
+ return (await fetcher("catalog/creature-types"))?.data ?? [];
366
+ }
367
+ async enchantmentTypes() {
368
+ return (await fetcher("catalog/enchantment-types"))?.data ?? [];
369
+ }
370
+ async landTypes() {
371
+ return (await fetcher("catalog/land-types"))?.data ?? [];
372
+ }
373
+ async loyalties() {
374
+ return (await fetcher("catalog/loyalties"))?.data ?? [];
375
+ }
376
+ async planeswalkerTypes() {
377
+ return (await fetcher("catalog/planeswalker-types"))?.data ?? [];
378
+ }
379
+ async powers() {
380
+ return (await fetcher("catalog/powers"))?.data ?? [];
381
+ }
382
+ async spellTypes() {
383
+ return (await fetcher("catalog/spell-types"))?.data ?? [];
384
+ }
385
+ async toughnesses() {
386
+ return (await fetcher("catalog/toughnesses"))?.data ?? [];
387
+ }
388
+ async watermarks() {
389
+ return (await fetcher("catalog/watermarks"))?.data ?? [];
390
+ }
391
+ async wordBank() {
392
+ return (await fetcher("catalog/word-bank"))?.data ?? [];
393
+ }
394
+ };
395
+ var catalog = new CatalogApi();
396
+ var catalog_api_default = catalog;
397
+
398
+ // src/api/catalog/index.ts
399
+ var catalog_default = catalog_api_default;
400
+
401
+ // src/api/ruling/ruling.api.ts
402
+ var RulingApi = class {
403
+ async byArenaId(id) {
404
+ return (await fetcher(["cards/arena", id, "rulings"]))?.data ?? [];
405
+ }
406
+ async byId(id) {
407
+ return (await fetcher(["cards", id, "rulings"]))?.data ?? [];
408
+ }
409
+ async byMtgoId(id) {
410
+ return (await fetcher(["cards/mtgo", id, "rulings"]))?.data ?? [];
411
+ }
412
+ async byMultiverseId(id) {
413
+ return (await fetcher(["cards/multiverse", id, "rulings"]))?.data ?? [];
414
+ }
415
+ async bySet(setCode, collectorNumber) {
416
+ return (await fetcher(["cards", setCode, `${collectorNumber}`, "rulings"]))?.data ?? [];
417
+ }
418
+ };
419
+ var rulings = new RulingApi();
420
+ var ruling_api_default = rulings;
421
+
422
+ // src/api/ruling/index.ts
423
+ var ruling_default = ruling_api_default;
424
+
425
+ // src/api/set/set.api.ts
426
+ var SetApi = class {
427
+ async all() {
428
+ const result = await fetcher("sets");
429
+ return result?.data ?? [];
430
+ }
431
+ async byCode(code) {
432
+ return await fetcher(["sets", code]);
433
+ }
434
+ async byId(id) {
435
+ return fetcher(["sets", id]);
436
+ }
437
+ async byTcgPlayerId(id) {
438
+ return fetcher(["sets/tcgplayer", id]);
439
+ }
440
+ };
441
+ var set = new SetApi();
442
+ var set_api_default = set;
443
+
444
+ // src/api/set/index.ts
445
+ var set_default = set_api_default;
446
+
447
+ // src/api/symbology/symbology.api.ts
448
+ var SymbologyApi = class {
449
+ async all() {
450
+ const list = await fetcher("symbology");
451
+ return list?.data ?? [];
452
+ }
453
+ async parseMana(shorthand) {
454
+ if (!shorthand || typeof shorthand !== "string") {
455
+ throw new InvalidScryfallArgumentError("shorthand must be a string");
456
+ }
457
+ const cost = await fetcher("symbology/parse-mana", {
458
+ cost: shorthand
459
+ });
460
+ return cost ?? {
461
+ cost: "",
462
+ colors: [],
463
+ cmc: 0,
464
+ colorless: false,
465
+ monocolored: false,
466
+ multicolored: false,
467
+ object: "mana_cost"
468
+ };
469
+ }
470
+ };
471
+ var symbology = new SymbologyApi();
472
+ var symbology_api_default = symbology;
473
+
474
+ // src/api/symbology/index.ts
475
+ var symbology_default = symbology_api_default;
476
+ // Annotate the CommonJS export names for ESM import in node:
477
+ 0 && (module.exports = {
478
+ CardIdentifierBuilder,
479
+ Cards,
480
+ Catalogs,
481
+ InvalidScryfallArgumentError,
482
+ MagicPageResult,
483
+ Rulings,
484
+ ScryfallError,
485
+ Sets,
486
+ SymbologyApi,
487
+ UnknownScryfallError
488
+ });