@lgriffin/esi.ts 9.4.0 → 9.6.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +388 -388
  2. package/LICENSE +26 -26
  3. package/README.md +1030 -1018
  4. package/dist/EsiClient.d.ts +4 -0
  5. package/dist/EsiClient.d.ts.map +1 -1
  6. package/dist/clients/CosmeticsClient.d.ts +11 -0
  7. package/dist/clients/CosmeticsClient.d.ts.map +1 -0
  8. package/dist/clients/MercenaryClient.d.ts +19 -1
  9. package/dist/clients/MercenaryClient.d.ts.map +1 -1
  10. package/dist/clients/ParagonHubClient.d.ts +13 -0
  11. package/dist/clients/ParagonHubClient.d.ts.map +1 -0
  12. package/dist/clients/SkyhooksClient.d.ts +19 -1
  13. package/dist/clients/SkyhooksClient.d.ts.map +1 -1
  14. package/dist/core/ApiClient.d.ts.map +1 -1
  15. package/dist/core/ApiRequestHandler.d.ts.map +1 -1
  16. package/dist/core/ClientRegistry.d.ts +5 -3
  17. package/dist/core/ClientRegistry.d.ts.map +1 -1
  18. package/dist/core/cache/cacheKey.d.ts +3 -0
  19. package/dist/core/cache/cacheKey.d.ts.map +1 -0
  20. package/dist/core/endpoints/cosmeticsEndpoints.d.ts +52 -0
  21. package/dist/core/endpoints/cosmeticsEndpoints.d.ts.map +1 -0
  22. package/dist/core/endpoints/mercenaryEndpoints.d.ts +45 -0
  23. package/dist/core/endpoints/mercenaryEndpoints.d.ts.map +1 -1
  24. package/dist/core/endpoints/paragonHubEndpoints.d.ts +163 -0
  25. package/dist/core/endpoints/paragonHubEndpoints.d.ts.map +1 -0
  26. package/dist/core/endpoints/skyhookEndpoints.d.ts +64 -0
  27. package/dist/core/endpoints/skyhookEndpoints.d.ts.map +1 -1
  28. package/dist/core/requestPipeline/cachePolicy.d.ts +3 -3
  29. package/dist/core/requestPipeline/cachePolicy.d.ts.map +1 -1
  30. package/dist/core/requestPipeline/headers.d.ts.map +1 -1
  31. package/dist/core/requestPipeline/statusHandling.d.ts +2 -2
  32. package/dist/core/requestPipeline/statusHandling.d.ts.map +1 -1
  33. package/dist/errors.js.map +1 -1
  34. package/dist/errors.mjs.map +1 -1
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +497 -49
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +495 -49
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/schemas/cosmetics.d.ts +58 -0
  42. package/dist/schemas/cosmetics.d.ts.map +1 -0
  43. package/dist/schemas/index.d.ts +2 -0
  44. package/dist/schemas/index.d.ts.map +1 -1
  45. package/dist/schemas/index.js +1461 -1191
  46. package/dist/schemas/index.js.map +1 -1
  47. package/dist/schemas/index.mjs +1427 -1191
  48. package/dist/schemas/index.mjs.map +1 -1
  49. package/dist/schemas/mercenary.d.ts +54 -0
  50. package/dist/schemas/mercenary.d.ts.map +1 -1
  51. package/dist/schemas/paragon-hub.d.ts +96 -0
  52. package/dist/schemas/paragon-hub.d.ts.map +1 -0
  53. package/dist/schemas/skyhooks.d.ts +101 -0
  54. package/dist/schemas/skyhooks.d.ts.map +1 -1
  55. package/dist/sde/index.js +7 -5100
  56. package/dist/sde/index.js.map +1 -1
  57. package/dist/sde/index.mjs +12 -5134
  58. package/dist/sde/index.mjs.map +1 -1
  59. package/dist/sde/memory.d.ts +8 -0
  60. package/dist/sde/memory.d.ts.map +1 -0
  61. package/dist/sde/memory.js +1100 -0
  62. package/dist/sde/memory.js.map +1 -0
  63. package/dist/sde/memory.mjs +1064 -0
  64. package/dist/sde/memory.mjs.map +1 -0
  65. package/dist/testing/index.js.map +1 -1
  66. package/dist/testing/index.mjs.map +1 -1
  67. package/dist/types/api-responses.d.ts +2 -0
  68. package/dist/types/api-responses.d.ts.map +1 -1
  69. package/dist/types/cosmetics.d.ts +8 -0
  70. package/dist/types/cosmetics.d.ts.map +1 -0
  71. package/dist/types/mercenary.d.ts +3 -1
  72. package/dist/types/mercenary.d.ts.map +1 -1
  73. package/dist/types/paragon-hub.d.ts +8 -0
  74. package/dist/types/paragon-hub.d.ts.map +1 -0
  75. package/dist/types/skyhooks.d.ts +3 -1
  76. package/dist/types/skyhooks.d.ts.map +1 -1
  77. package/package.json +289 -282
package/README.md CHANGED
@@ -1,1018 +1,1030 @@
1
- # ESI.ts
2
-
3
- [![npm version](https://badge.fury.io/js/%40lgriffin%2Fesi.ts.svg)](https://badge.fury.io/js/%40lgriffin%2Fesi.ts)
4
- [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
5
- [![TypeScript](https://img.shields.io/badge/TypeScript-6.0%2B-blue)](https://www.typescriptlang.org/)
6
- [![CI/CD Pipeline](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml/badge.svg)](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml)
7
- [![Coverage](https://img.shields.io/badge/coverage-90%25%2B-brightgreen)](https://github.com/lgriffin/ESI.ts)
8
- [![npm downloads](https://img.shields.io/npm/dm/%40lgriffin/esi.ts)](https://www.npmjs.com/package/@lgriffin/esi.ts)
9
- [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/lgriffin/ESI.ts/badge)](https://scorecard.dev/viewer/?uri=github.com/lgriffin/ESI.ts)
10
-
11
- A production-grade TypeScript client for the [EVE Online ESI API](https://esi.evetech.net/), built on the **OpenAPI 3.1 spec**, with runtime validation, intelligent caching, and full endpoint coverage.
12
-
13
- **v9.1.0** — Expanded test pyramid (schema rejection, domain fuzz, benchmark, type tests), updated documentation and examples, fuzz test date handling fix.
14
-
15
- **223 endpoint definitions — 194 from the public ESI OpenAPI spec, plus 29 for newer EVE features (Equinox sovereignty, orbital skyhooks, mercenary dens, access lists, freelance jobs, military campaigns, corporation projects). All 221 exercisable endpoints validated against live Tranquility on 2026-08-14.**
16
-
17
- ## Why ESI.ts vs. OpenAPI-Generated Clients?
18
-
19
- Tools like `openapi-typescript` or `openapi-generator` can produce a typed client from the ESI OpenAPI spec in minutes. They're a reasonable starting point — but they stop at type generation. ESI.ts is a purpose-built SDK that handles the problems you hit _after_ the types compile.
20
-
21
- ### What generators give you
22
-
23
- - TypeScript interfaces from the OpenAPI spec
24
- - Basic request/response typing
25
- - A thin HTTP wrapper
26
-
27
- ### What ESI.ts gives you on top of that
28
-
29
- | Capability | openapi-typescript | ESI.ts |
30
- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
31
- | **Runtime response validation** | None — types are erased at compile time. If CCP changes a field, you get silent data corruption. | Every GET response is validated at runtime via [Zod](https://zod.dev/) schemas — all 173 GET endpoints have schemas. Schema mismatches throw `EsiValidationError` immediately. |
32
- | **Intelligent caching** | None — you build your own. | Three-tier: spec-aware TTL (zero HTTP calls within ESI's `x-cached-seconds` window), ETag conditional GETs, stale-on-error fallback on 5xx. Write operations auto-invalidate related GET caches. |
33
- | **Rate limiting** | None — you build your own. | 36 per-group token buckets extracted from the ESI spec at build time. Market requests can't starve wallet requests. Optional per-user bucketing for multi-character apps. |
34
- | **Pagination** | Manual — you write the page loop. | Automatic offset pagination, cursor-based pagination (Equinox-era endpoints), and streaming `AsyncGenerator` pagination for memory-efficient processing of large datasets. |
35
- | **Retry & resilience** | None. | Exponential backoff with jitter, circuit breaker (closed/open/half-open), automatic 401 token refresh with concurrent coalescing. |
36
- | **Wire format correctness** | Generates from spec, but ESI's spec has inconsistencies (query params documented as body, missing required fields). | Every endpoint tested against live ESI. Wire format bugs (query params vs. body, field naming) are caught and fixed — see the contacts and UI endpoint fixes in v6.1.0. |
37
- | **Batch operations** | None. | `batch()` with bounded concurrency for GET fan-out, `batchPost()` with auto-chunking for large POST payloads. |
38
- | **Domain knowledge** | None — generic HTTP client. | 37 domain clients with typed methods, JSDoc documentation, and input validation (e.g., fleet wing/squad names are capped at 10 characters before hitting the API). |
39
- | **Streaming pagination** | None. | 21 domain clients with 73+ `stream*` methods via `AsyncGenerator` — process large datasets page-by-page without loading everything into memory. |
40
- | **Testing** | Whatever you write. | 143 test suites, 4,182 tests across 9 tiers including property-based fuzzing (fast-check), mutation testing (Stryker), deep contract tests against live OpenAPI spec, and consumer type tests (tsd). 46 runnable example scripts. |
41
-
42
- ### The real problem with generated clients
43
-
44
- The ESI OpenAPI spec is not a perfect source of truth. During live endpoint validation against the OpenAPI 3.1 spec, we discovered:
45
-
46
- - `addContacts`, `editContacts`, and 4 UI endpoints document parameters as request body when ESI actually expects query parameters
47
- - `deleteCharacterContacts` expects comma-separated contact IDs as a query param, not a JSON body
48
- - Fleet wing/squad names have a 10-character limit not documented in the spec
49
- - The `updateMailMetadata` endpoint uses the field name `read`, not `is_read`
50
-
51
- A generated client faithfully reproduces these spec bugs. ESI.ts fixes them.
52
-
53
- ## Installation
54
-
55
- ```bash
56
- npm install @lgriffin/esi.ts
57
- ```
58
-
59
- ### Building from Source
60
-
61
- ```bash
62
- git clone https://github.com/lgriffin/ESI.ts.git
63
- cd ESI.ts
64
- npm install # installs dependencies and compiles (via the prepare script)
65
- ```
66
-
67
- If you've already installed and just need to recompile:
68
-
69
- ```bash
70
- npm run build
71
- ```
72
-
73
- Verify everything works:
74
-
75
- ```bash
76
- npm run example:status # quick smoke test — checks ESI is reachable
77
- npm test # run the full test suite (143 suites, 4,182 tests)
78
- ```
79
-
80
- ## Sub-path Exports
81
-
82
- ESI.ts provides sub-path exports for targeted imports, reducing bundle size when you only need specific parts of the library:
83
-
84
- ```typescript
85
- // Zod schemas for runtime validation
86
- import { MarketOrderSchema } from '@lgriffin/esi.ts/schemas';
87
-
88
- // Error classes and type guards
89
- import { EsiError, isCircuitOpen } from '@lgriffin/esi.ts/errors';
90
-
91
- // Test utilities
92
- import { TestDataFactory } from '@lgriffin/esi.ts/testing';
93
- ```
94
-
95
- ## Static Data Export (SDE) Module
96
-
97
- ESI.ts includes a standalone module for querying CCP's EVE Online Static Data Export — 102 YAML files loaded into in-memory Maps with 109 typed interfaces, Zod validation, and ~97 query methods. No database, no external services.
98
-
99
- ```typescript
100
- import { SdeDataProvider } from '@lgriffin/esi.ts/sde';
101
-
102
- const sde = SdeDataProvider.fromDirectory('./sde-data');
103
-
104
- const tritanium = sde.getType(34);
105
- console.log(tritanium?.name); // "Tritanium"
106
-
107
- const jita = sde.getSolarSystem(30000142);
108
- const minerals = sde.getTypesByGroup(18);
109
- const caldari = sde.getFaction(500001);
110
-
111
- sde.close();
112
- ```
113
-
114
- Download SDE data with: `npx ts-node scripts/sde-ingest.ts --output sde-data`
115
-
116
- | Document | Description |
117
- | -------------------------------------------------- | --------------------------------------------------------------------------------------------- |
118
- | [SDE README](src/sde/README.md) | Module overview, quick start, full API reference (~97 methods), entity coverage table |
119
- | [Architecture](src/sde/docs/ARCHITECTURE.md) | C4 diagrams (context, container, component), data flow sequence, ER diagram, design decisions |
120
- | [Usage Guide](src/sde/docs/USAGE.md) | Provider patterns, query examples, error handling |
121
- | [Developer Guide](src/sde/docs/DEVELOPER_GUIDE.md) | Project structure, new entity checklist, field normalization, testing patterns |
122
- | [API Contracts](src/sde/docs/API_CONTRACTS.md) | Complete method reference for all IStaticDataProvider methods |
123
-
124
- ## Quick Start
125
-
126
- ```typescript
127
- import { EsiClient } from '@lgriffin/esi.ts';
128
-
129
- const client = new EsiClient();
130
-
131
- // Public data — no auth required
132
- const alliances = await client.alliance.getAlliances();
133
- const character = await client.characters.getCharacterPublicInfo(1689391488);
134
- const system = await client.universe.getSystemById(30000142);
135
- const prices = await client.market.getMarketPrices();
136
-
137
- // Authenticated data — token read from ESI_ACCESS_TOKEN env var
138
- const authedClient = new EsiClient();
139
- const assets = await authedClient.assets.getCharacterAssets(characterId);
140
- const wallet = await authedClient.wallet.getCharacterWallet(characterId);
141
-
142
- // Clean up when done
143
- await client.shutdown();
144
- ```
145
-
146
- ## Configuration
147
-
148
- ```typescript
149
- const client = new EsiClient({
150
- clientId: 'my-app', // User-Agent identifier (default: 'esi-client')
151
- accessToken: 'your-token', // EVE SSO token for authenticated endpoints
152
- baseUrl: 'https://esi.evetech.net', // ESI base URL (default)
153
- onTokenRefresh: async () => newToken, // Auto-refresh on 401 (optional)
154
- language: 'en', // Accept-Language header: en, de, fr, ja, ru, zh, ko, es (default: none)
155
- timeout: 30000, // Request timeout in ms (default: 30000)
156
- retryConfig: {
157
- maxRetries: 3, // Max retry attempts for transient errors (default: 3)
158
- baseDelayMs: 1000, // Initial backoff delay (default: 1000)
159
- maxDelayMs: 30000, // Maximum backoff delay (default: 30000)
160
- retryMutations: false, // Retry POST/PUT/DELETE (default: false, GET only)
161
- },
162
- enableETagCache: true, // ETag caching (default: true)
163
- etagCacheConfig: {
164
- maxEntries: 1000, // Max cached responses (default: 1000)
165
- defaultTtl: 300000, // Fallback TTL in ms (default: 5 min)
166
- cleanupInterval: 60000, // Expired entry cleanup interval (default: 1 min)
167
- },
168
- validateResponse: true, // Runtime Zod validation of ESI responses (default: true)
169
- validateRequest: false, // Opt-in request body Zod validation for POST/PUT/DELETE (default: false)
170
- retryStrategy: customRetryStrategy, // Injectable IRetryStrategy (default: built-in exponential backoff)
171
- circuitBreakerConfig: {
172
- keyStrategy: 'resolved', // CB keying: 'resolved' (per-URL) or 'template' (per-route) (default: 'resolved')
173
- cleanupIntervalMs: 300000, // Automatic stale circuit cleanup interval (default: 5 min)
174
- },
175
- });
176
- ```
177
-
178
- Retry is enabled by default (`maxRetries: 3`). Transient errors (502, 503, 504, timeout, rate limit) are retried with exponential backoff and jitter. The circuit breaker is respected — requests are not retried when the circuit is open. Set `maxRetries: 0` to disable retry.
179
-
180
- The access token can be updated at runtime:
181
-
182
- ```typescript
183
- client.setAccessToken('new-token');
184
- ```
185
-
186
- ## Authentication
187
-
188
- Many ESI endpoints require an EVE SSO access token. There are three ways to provide one:
189
-
190
- ### 1. Environment variable (recommended)
191
-
192
- Set `ESI_ACCESS_TOKEN` in your environment or a `.env` file. The client reads it automatically — no token in source code.
193
-
194
- ```bash
195
- # Copy the example and fill in your token
196
- cp .env.example .env
197
- ```
198
-
199
- ```env
200
- ESI_ACCESS_TOKEN=your-eve-sso-access-token
201
- ESI_CLIENT_ID=my-app-name
202
- ```
203
-
204
- If you use a `.env` loader like [dotenv](https://www.npmjs.com/package/dotenv), load it before creating the client:
205
-
206
- ```typescript
207
- import 'dotenv/config';
208
- import { EsiClient } from '@lgriffin/esi.ts';
209
-
210
- const client = new EsiClient();
211
- // Token is picked up from process.env.ESI_ACCESS_TOKEN
212
- ```
213
-
214
- ### 2. Constructor parameter
215
-
216
- Pass the token directly (useful for apps that manage tokens themselves):
217
-
218
- ```typescript
219
- const client = new EsiClient({ accessToken: token });
220
- ```
221
-
222
- ### 3. Runtime update
223
-
224
- Set or refresh the token after construction:
225
-
226
- ```typescript
227
- client.setAccessToken(newToken);
228
- ```
229
-
230
- ### Getting an EVE SSO token
231
-
232
- 1. Register an application at [EVE Developers](https://developers.eveonline.com/)
233
- 2. Set a callback URL and select the ESI scopes your app needs
234
- 3. Implement the [OAuth2 flow](https://docs.esi.evetech.net/docs/sso/) to obtain an access token
235
- 4. Access tokens expire — use the refresh token to get new ones
236
-
237
- ### Automatic Token Refresh
238
-
239
- EVE SSO access tokens expire after 20 minutes. Instead of manually tracking expiry, you can provide a refresh callback — the client will automatically call it on 401, update the token, and retry the request:
240
-
241
- ```typescript
242
- const client = new EsiClient({
243
- accessToken: initialToken,
244
- onTokenRefresh: async () => {
245
- const response = await fetch('https://login.eveonline.com/v2/oauth/token', {
246
- method: 'POST',
247
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
248
- body: new URLSearchParams({
249
- grant_type: 'refresh_token',
250
- refresh_token: myRefreshToken,
251
- client_id: myClientId,
252
- }),
253
- });
254
- const { access_token } = await response.json();
255
- return access_token;
256
- },
257
- });
258
-
259
- // Requests now auto-refresh on 401 — no manual token management needed
260
- const location = await client.location.getCharacterLocation(characterId);
261
- ```
262
-
263
- The token provider can also be set or changed at runtime:
264
-
265
- ```typescript
266
- client.setTokenProvider(myRefreshFunction);
267
- client.setTokenProvider(undefined); // disable auto-refresh
268
- ```
269
-
270
- Key behaviors:
271
-
272
- - Only retries **once** per request — if the refreshed token also gets a 401, the error is thrown
273
- - **Concurrent coalescing** — if multiple requests hit 401 simultaneously, only one refresh call is made
274
- - If the refresh callback throws (e.g., refresh token revoked), a `TOKEN_REFRESH_FAILED` error is raised
275
- - Without a token provider, 401 errors throw immediately as before
276
-
277
- ### Environment variables reference
278
-
279
- | Variable | Description | Default |
280
- | ------------------ | -------------------------------------------- | ------------------------- |
281
- | `ESI_ACCESS_TOKEN` | EVE SSO access token | none |
282
- | `ESI_CLIENT_ID` | User-Agent identifier | `esi-client` |
283
- | `ESI_BASE_URL` | ESI API base URL | `https://esi.evetech.net` |
284
- | `ESI_LOG_LEVEL` | Log level (`error`, `warn`, `info`, `debug`) | `warn` |
285
-
286
- ## Available APIs
287
-
288
- All clients are accessed as properties on the `EsiClient` instance. Authenticated endpoints require an access token.
289
-
290
- | Client | Property | Auth | Examples |
291
- | ------------------ | ---------------------------- | ---- | -------------------------------------------------------------------------------- |
292
- | Alliance | `client.alliance` | Some | `getAlliances()`, `getAllianceById(id)` |
293
- | Assets | `client.assets` | Yes | `getCharacterAssets(id)` |
294
- | Calendar | `client.calendar` | Yes | `getCalendarEvents(id)` |
295
- | Characters | `client.characters` | Some | `getCharacterPublicInfo(id)`, `getCharacterPortrait(id)` |
296
- | Clones | `client.clones` | Yes | `getCharacterClones(id)` |
297
- | Contacts | `client.contacts` | Yes | `getCharacterContacts(id)`, `postCharacterContacts(id, standing, contactIds)` |
298
- | Contracts | `client.contracts` | Yes | `getCharacterContracts(id)` |
299
- | Corp Projects | `client.corporationProjects` | Yes | `getCorporationProjects(corpId)`, `getCorporationProject(corpId, projectId)` |
300
- | Corporations | `client.corporations` | Some | `getCorporationInfo(id)`, `getCorporationMembers(id)` |
301
- | Dogma | `client.dogma` | No | `getDogmaAttributes()`, `getDynamicItemInfo(typeId, itemId)` |
302
- | Factions | `client.factions` | Some | `getFactionWarStats()` |
303
- | Fittings | `client.fittings` | Yes | `getFittings(id)`, `createFitting(id, body)` |
304
- | Fleets | `client.fleets` | Yes | `getFleetInformation(id)`, `getFleetMembers(id)` |
305
- | Incursions | `client.incursions` | No | `getIncursions()` |
306
- | Industry | `client.industry` | Some | `getCharacterIndustryJobs(id)` |
307
- | Insurance | `client.insurance` | No | `getInsurancePrices()` |
308
- | Killmails | `client.killmails` | Some | `getKillmail(id, hash)` |
309
- | Location | `client.location` | Yes | `getCharacterLocation(id)` |
310
- | Loyalty | `client.loyalty` | Yes | `getCharacterLoyaltyPoints(id)` |
311
- | Mail | `client.mail` | Yes | `getCharacterMail(id)`, `sendMail(id, body)` |
312
- | Market | `client.market` | Some | `getMarketPrices()`, `getMarketOrders(regionId)` |
313
- | Military Campaigns | `client.militaryCampaigns` | Some | `getMilitaryCampaigns()`, `getMilitaryCampaignById(id)` |
314
- | PI | `client.pi` | Yes | `getCharacterPlanets(id)` |
315
- | Route | `client.route` | No | `getRoute(origin, destination)` |
316
- | Search | `client.search` | Some | `search(characterId, query)` |
317
- | Skills | `client.skills` | Yes | `getCharacterSkills(id)` |
318
- | Sovereignty | `client.sovereignty` | No | `getSovereigntySystems()`, `getSovereigntyMap()` |
319
- | Skyhooks | `client.skyhooks` | No | `getSovereigntyHubs()`, `getRaidableSkyhooks()` |
320
- | Mercenary | `client.mercenary` | No | `getMercenaryDens()`, `getMercenaryTacticalOperations()` |
321
- | Access Lists | `client.accessLists` | Yes | `getAccessList(id)` |
322
- | Status | `client.status` | No | `getStatus()` |
323
- | UI | `client.ui` | Yes | `setAutopilotWaypoint(destId, addToBeginning, clear)`, `openNewMailWindow(body)` |
324
- | Universe | `client.universe` | Some | `getSystemById(id)`, `getTypeById(id)` |
325
- | Wallet | `client.wallet` | Yes | `getCharacterWallet(id)` |
326
- | Wars | `client.wars` | No | `getWars()`, `getWarById(id)` |
327
- | Freelance Jobs | `client.freelanceJobs` | Some | `getFreelanceJobs()`, `getFreelanceJobById(id)` |
328
- | Meta | `client.meta` | No | `getOpenApiJson()`, `getOpenApiYaml()` |
329
-
330
- ## Runtime Response Validation
331
-
332
- ESI.ts validates API responses at runtime using [Zod](https://zod.dev/) schemas. All GET endpoints have schemas — these are the endpoints that return data your application consumes, where a silent shape change from CCP would cause bugs. POST/PUT/DELETE mutations typically return `204 No Content` (no body to validate) or simple confirmation values, so schemas are omitted where there is nothing meaningful to validate.
333
-
334
- Validation is **on by default**. Extra fields from ESI are preserved via `z.looseObject()` passthrough mode, so new fields added by CCP won't break your application — they flow through to your code untouched.
335
-
336
- ```typescript
337
- import {
338
- EsiClient,
339
- EsiValidationError,
340
- isValidationError,
341
- schemas,
342
- } from '@lgriffin/esi.ts';
343
-
344
- const client = new EsiClient();
345
-
346
- // Validation happens automatically on every request
347
- const character = await client.characters.getCharacterPublicInfo(12345);
348
-
349
- // Disable validation globally if needed
350
- const rawClient = new EsiClient({ validateResponse: false });
351
-
352
- // Use schemas directly for your own validation
353
- const result = schemas.CharacterInfoSchema.safeParse(someData);
354
- if (result.success) {
355
- console.log(result.data.name);
356
- }
357
- ```
358
-
359
- ### Request Body Validation
360
-
361
- For POST/PUT/DELETE endpoints, opt-in request body validation ensures outgoing payloads match the endpoint's `requestSchema` before the request is sent:
362
-
363
- ```typescript
364
- // Opt-in request body validation for POST/PUT/DELETE
365
- const client = new EsiClient({ validateRequest: true });
366
-
367
- // Throws EsiValidationError if the request body doesn't match the endpoint's requestSchema
368
- await client.mail.sendMail(characterId, {
369
- recipients: [{ recipient_id: 12345, recipient_type: 'character' }],
370
- subject: 'Hello',
371
- body: 'Message body',
372
- });
373
- ```
374
-
375
- See [guides/RUNTIME-VALIDATION.md](guides/RUNTIME-VALIDATION.md) for the full guide on schemas, error handling, and extending schemas.
376
-
377
- ## Caching
378
-
379
- ETag caching is enabled by default. The client automatically:
380
-
381
- 1. Stores ETag and response data on GET requests
382
- 2. Sends `If-None-Match` on subsequent requests
383
- 3. Returns cached data on `304 Not Modified`
384
- 4. Parses `Cache-Control: max-age` from ESI for per-endpoint TTL
385
- 5. Serves stale cached data when ESI returns 5xx errors
386
- 6. Invalidates related GET caches when POST/PUT/DELETE requests are made
387
-
388
- ```typescript
389
- // Cache stats
390
- const stats = client.getCacheStats();
391
- console.log(`${stats.totalEntries}/${stats.maxEntries} entries cached`);
392
-
393
- // Manual cache operations
394
- client.clearCache();
395
- client.updateCacheConfig({ maxEntries: 2000 });
396
-
397
- // Disable caching entirely
398
- const uncachedClient = new EsiClient({ enableETagCache: false });
399
- ```
400
-
401
- ### Spec-Aware Cache TTLs
402
-
403
- The library reads `x-cache-age` from the ESI OpenAPI spec (126 of 195 endpoints). Within the TTL window, repeated GET requests return cached data with **zero HTTP calls** — not even a conditional GET.
404
-
405
- This layers on top of ETag caching in three tiers:
406
-
407
- 1. **Spec TTL** — data can't have changed yet, return cached data immediately
408
- 2. **ETag conditional GET** — data might have changed, send `If-None-Match` to check
409
- 3. **Full request** — no cache entry, fetch fresh data
410
-
411
- ```typescript
412
- const client = new EsiClient();
413
-
414
- // First call — fetches from ESI
415
- const alliances = await client.alliance.getAlliances();
416
-
417
- // Second call within the next 3600s — returns cached data, zero HTTP calls
418
- const same = await client.alliance.getAlliances();
419
- ```
420
-
421
- ## Batch Requests
422
-
423
- Fetch data for multiple IDs with bounded concurrency using `batch()`, or chunk large POST payloads with `batchPost()`:
424
-
425
- ```typescript
426
- import { EsiClient } from '@lgriffin/esi.ts';
427
-
428
- const client = new EsiClient();
429
-
430
- // Fetch 500 type details with at most 10 concurrent requests
431
- const result = await client.batch(
432
- typeIds,
433
- (id) => client.universe.getTypeById(id),
434
- {
435
- concurrency: 10,
436
- onProgress: (done, total) => console.log(`${done}/${total}`),
437
- },
438
- );
439
-
440
- // result.results: Map<number, T> — successful responses
441
- // result.errors: Map<number, Error> — failed requests
442
- console.log(`${result.results.size} succeeded, ${result.errors.size} failed`);
443
- ```
444
-
445
- For POST endpoints that accept arrays (e.g., `postUniverseNames` with a 1000-ID limit), `batchPost` auto-chunks and concatenates:
446
-
447
- ```typescript
448
- const allNames = await client.batchPost(
449
- largeIdArray,
450
- (chunk) => client.universe.postUniverseNames(chunk),
451
- 1000, // chunk size
452
- );
453
- ```
454
-
455
- ## Streaming Pagination
456
-
457
- For large paginated endpoints (market orders, contracts, assets), streaming yields one page at a time via `AsyncGenerator` instead of eagerly fetching all pages into memory:
458
-
459
- ```typescript
460
- import { EsiClient } from '@lgriffin/esi.ts';
461
-
462
- const client = new EsiClient();
463
-
464
- // Stream all market orders in The Forge, page by page
465
- for await (const page of client.market.streamMarketOrders(10000002)) {
466
- console.log(
467
- `Page ${page.page}/${page.totalPages}: ${page.data.length} orders`,
468
- );
469
-
470
- // Process each order as it arrives
471
- for (const order of page.data) {
472
- if (order.is_buy_order && order.price > 1_000_000) {
473
- console.log(`High-value buy: ${order.type_id} @ ${order.price} ISK`);
474
- }
475
- }
476
-
477
- // Early termination — stops fetching remaining pages
478
- if (page.page >= 3) break;
479
- }
480
- ```
481
-
482
- 21 domain clients expose 73+ streaming methods. `BaseEsiClient.streamEndpoint()` is also public as an escape hatch for any paginated endpoint not yet wrapped with a convenience method.
483
-
484
- Available streaming methods (representative selection):
485
-
486
- - **MarketClient** — `streamMarketOrders`, `streamMarketTypes`, `streamCharacterOrderHistory`, `streamCorporationOrders`, `streamCorporationOrderHistory`, `streamMarketOrdersInStructure`
487
- - **CorporationsClient** — `streamCorporationMembers`, `streamCorporationStructures`, `streamCorporationBlueprints`, + 14 more
488
- - **CharacterClient** — `streamCharacterBlueprints`, `streamCharacterNotifications`, `streamCharacterStandings`, + 5 more
489
- - **ContractsClient** — `streamPublicContracts`, `streamCharacterContracts`, `streamCorporationContracts`
490
- - **WalletClient** — `streamCharacterWalletJournal`, `streamCorporationWalletJournal`, `streamCharacterWalletTransactions`
491
- - **IndustryClient** — `streamCorporationIndustryJobs`, `streamCorporationMiningObservers`, + 6 more
492
- - **ContactsClient** — `streamAllianceContacts`, `streamCharacterContacts`, `streamCorporationContacts`, + 3 more
493
- - **AssetsClient** — `streamCharacterAssets`, `streamCorporationAssets`
494
- - **KillmailsClient** — `streamCharacterRecentKillmails`, `streamCorporationRecentKillmails`
495
- - **MailClient** — `streamCharacterMail`, `streamCharacterMailLabels`
496
- - **FleetsClient** — `streamFleetMembers`, `streamFleetWings`
497
- - **CalendarClient** — `streamCalendarEvents`
498
- - **FittingsClient** — `streamCharacterFittings`
499
- - **SkillsClient** — `streamCharacterSkillQueue`
500
- - **LoyaltyClient** — `streamCorporationLoyaltyStoreOffers`
501
- - **BookmarksClient** — `streamCharacterBookmarks`, `streamCorporationBookmarks`
502
- - **ClonesClient** — `streamCharacterImplants`
503
- - **PIClient** — `streamCharacterPlanets`
504
- - **WarsClient** — `streamWars`
505
- - **FactionWarfareClient** — `streamFactionWarfareStats`
506
- - **AllianceClient** — `streamAllianceCorporations`
507
-
508
- Try it: `npm run example:streaming`
509
-
510
- ## Cursor-based Pagination
511
-
512
- Newer ESI routes (Freelance Jobs, and future routes) use cursor-based pagination with opaque `before`/`after` tokens in the response body. See the [ESI blog post](https://developers.eveonline.com/blog/changing-pagination-turning-a-new-page) for background.
513
-
514
- ```typescript
515
- import { EsiClient, fetchAllCursorPages } from '@lgriffin/esi.ts';
516
-
517
- const client = new EsiClient();
518
-
519
- // Fetch first page — returns { cursor: { before, after }, freelance_jobs: [...] }
520
- const page = await client.freelanceJobs.getFreelanceJobs();
521
- console.log(page.freelance_jobs); // job records
522
- console.log(page.cursor.after); // opaque token for next page
523
-
524
- // Fetch next page using the cursor
525
- const nextPage = await client.freelanceJobs.getFreelanceJobs(
526
- undefined,
527
- page.cursor.after,
528
- );
529
-
530
- // Auto-fetch all pages in one call
531
- const allJobs = await fetchAllCursorPages(
532
- (before, after) => client.freelanceJobs.getFreelanceJobs(before, after),
533
- (response) => response.freelance_jobs,
534
- (response) => response.cursor,
535
- );
536
-
537
- // Authenticated endpoints — character/corporation freelance jobs
538
- const authedClient = new EsiClient({ accessToken: 'your-token' });
539
- const myJobs =
540
- await authedClient.freelanceJobs.getCharacterFreelanceJobs(characterId);
541
- const corpJobs =
542
- await authedClient.freelanceJobs.getCorporationFreelanceJobs(corporationId);
543
- ```
544
-
545
- **Polling for changes** — cursor tokens persist across sessions, so you can save the last `after` token and poll later to get only records that changed:
546
-
547
- ```typescript
548
- // After initial scan, save the final cursor
549
- let savedCursor = lastPage.cursor.after;
550
-
551
- // Later: check for updates (hours, days, or weeks later)
552
- const updates = await client.freelanceJobs.getFreelanceJobs(
553
- undefined,
554
- savedCursor,
555
- );
556
- if (updates.freelance_jobs.length > 0) {
557
- // Process changed records — duplicates are expected for modified records
558
- savedCursor = updates.cursor.after;
559
- }
560
- ```
561
-
562
- Key points:
563
-
564
- - Cursor tokens are **opaque strings** — never parse or validate them
565
- - An **empty result array** signals the end of the dataset (not a short page)
566
- - **Duplicates across pages** are expected when records are modified between requests
567
- - Existing offset-based routes (`getMarketOrders`, etc.) are unchanged
568
-
569
- ## Generated Types
570
-
571
- The library includes TypeScript interfaces generated directly from the ESI OpenAPI 3.1 spec, available as the `EsiSpec` namespace. These are guaranteed to match the live spec and complement the hand-written types:
572
-
573
- ```typescript
574
- import { EsiSpec } from '@lgriffin/esi.ts';
575
-
576
- // Generated type — uses OpenAPI schema names (v7.0.0+)
577
- const order: EsiSpec.MarketsRegionIdOrdersGet = {
578
- order_id: 123,
579
- type_id: 34,
580
- price: 5.5,
581
- volume_remain: 1000,
582
- volume_total: 5000,
583
- is_buy_order: false,
584
- // ...
585
- };
586
- ```
587
-
588
- To regenerate types from the latest ESI spec:
589
-
590
- ```bash
591
- npm run generate:types # fetches OpenAPI spec, generates 161 interfaces + cache TTL map + rate limit groups + scope map
592
- npm run validate:esi # reports type drift between hand-written and generated types
593
- ```
594
-
595
- ## ESI Scopes
596
-
597
- The library includes a generated scope-to-endpoint mapping extracted from the ESI OpenAPI spec. Use it to check which OAuth scopes an endpoint requires before making a request:
598
-
599
- ```typescript
600
- import { esiEndpointScopes, EsiScope } from '@lgriffin/esi.ts';
601
-
602
- // Look up scopes for a specific endpoint
603
- const walletScopes = esiEndpointScopes['GET:characters/{character_id}/wallet'];
604
- // → ['esi-wallet.read_character_wallet.v1']
605
-
606
- // Check if an endpoint requires auth
607
- const isPublic = !esiEndpointScopes['GET:universe/types/{type_id}'];
608
- // → true (public endpoint, no scopes needed)
609
-
610
- // Type-safe scope values
611
- const scope: EsiScope = 'esi-assets.read_assets.v1';
612
- ```
613
-
614
- ## Error Handling
615
-
616
- API errors throw `EsiError` with `statusCode`, `message`, and `url` properties:
617
-
618
- ```typescript
619
- import {
620
- EsiError,
621
- TimeoutError,
622
- EsiValidationError,
623
- isTimeout,
624
- isRetryable,
625
- isValidationError,
626
- isCircuitOpen,
627
- } from '@lgriffin/esi.ts';
628
-
629
- try {
630
- const alliance = await client.alliance.getAllianceById(99999999);
631
- console.log('Alliance:', alliance.name);
632
- } catch (err) {
633
- if (isCircuitOpen(err)) {
634
- console.log('Circuit breaker is open — endpoint temporarily unavailable');
635
- } else if (isValidationError(err)) {
636
- console.log('Response validation failed:', err.validationError);
637
- } else if (isTimeout(err)) {
638
- console.log(`Request timed out after ${err.timeoutMs}ms`);
639
- } else if (err instanceof EsiError) {
640
- console.log(`ESI error ${err.statusCode}: ${err.message}`);
641
- console.log(`Retryable: ${err.retryable}`);
642
- }
643
- }
644
- ```
645
-
646
- - **204 No Content** — returns `undefined` (valid for DELETE/POST actions)
647
- - **304 Not Modified** — handled internally, returns cached data
648
- - **4xx/5xx** — throws `EsiError`
649
- - **5xx with cache** — returns stale cached data instead of throwing
650
- - **Timeout** — throws `TimeoutError` (extends `EsiError` with `statusCode: 0` and `timeoutMs`)
651
- - **Retryable errors** — `EsiError.retryable` returns `true` for 502, 503, 504, 420, 429, and timeouts
652
- - **Validation errors** — throws `EsiValidationError` (extends `EsiError`) when response data doesn't match the expected Zod schema
653
-
654
- ## Response Metadata
655
-
656
- Use `withMetadata()` to get response headers, cache status, rate limit info, and timing alongside the data:
657
-
658
- ```typescript
659
- const metaClient = client.alliance.withMetadata();
660
- const result = await metaClient.getAllianceById(99000001);
661
-
662
- console.log(result.data.name); // "Goonswarm Federation"
663
- console.log(result.meta.fromCache); // true if served from cache
664
- console.log(result.meta.cacheHitType); // 'spec-ttl' | 'etag-304' | 'stale-on-error'
665
- console.log(result.meta.responseTimeMs); // milliseconds
666
- console.log(result.meta.rateLimit); // { remaining, limit, used, group }
667
- console.log(result.meta.requestId); // ESI request ID for debugging
668
- ```
669
-
670
- The `meta` object includes:
671
-
672
- | Field | Type | Description |
673
- | ---------------- | ------------------------ | ------------------------------------------------- |
674
- | `headers` | `Record<string, string>` | Raw response headers |
675
- | `fromCache` | `boolean` | Whether data was served from cache |
676
- | `stale` | `boolean` | Whether cached data is stale (5xx fallback) |
677
- | `cacheHitType` | `string?` | `'spec-ttl'`, `'etag-304'`, or `'stale-on-error'` |
678
- | `rateLimit` | `RateLimitMeta?` | Rate limit status from ESI headers |
679
- | `responseTimeMs` | `number?` | Request duration in milliseconds |
680
- | `requestId` | `string?` | ESI request ID |
681
- | `warning` | `object?` | ESI deprecation warning |
682
-
683
- ## Rate Limiting
684
-
685
- ESI.ts automatically manages rate limiting using ESI's per-group token bucket system. The 36 rate limit groups from the ESI OpenAPI spec are extracted at build time, so each group (e.g., `market-order`, `char-notification`) gets its own independent bucket. A burst of market requests won't starve unrelated endpoints.
686
-
687
- Rate limiting works out of the box with no configuration. For multi-character applications, enable per-user bucketing:
688
-
689
- ```typescript
690
- import { EsiClient } from '@lgriffin/esi.ts';
691
-
692
- const client = new EsiClient({
693
- rateLimiterConfig: {
694
- userKeyExtractor: (headers) => headers['authorization'] ?? 'anon',
695
- },
696
- });
697
- ```
698
-
699
- Monitor rate limit status per group:
700
-
701
- ```typescript
702
- const limiter = client.getRateLimiter();
703
-
704
- // Worst-case across all groups (backward-compatible)
705
- const status = limiter.getStatus();
706
- console.log(status.remaining, status.limit, status.group);
707
-
708
- // Specific group
709
- const marketStatus = limiter.getGroupStatus('market-order');
710
- console.log(marketStatus?.remaining); // tokens remaining in this group
711
-
712
- // All active groups
713
- const all = limiter.getAllGroupStatuses();
714
- for (const [group, info] of all) {
715
- console.log(`${group}: ${info.remaining}/${info.limit}`);
716
- }
717
-
718
- // Check if a specific group is blocked
719
- console.log(limiter.isBlocked('char-notification')); // true if 429'd
720
- ```
721
-
722
- ## Lightweight Clients
723
-
724
- All three client creation patterns (`EsiClient`, `CustomEsiClient`, `EsiApiFactory`) now get identical middleware defaults (cache, request deduplication, rate limiter) thanks to `configureApiClient()`. Previously `CustomEsiClient` and `EsiApiFactory` only configured the rate limiter.
725
-
726
- If you only need a subset of APIs, use `CustomEsiClient` or `EsiClientBuilder` to load only what you need:
727
-
728
- ```typescript
729
- import { EsiClientBuilder } from '@lgriffin/esi.ts';
730
-
731
- const client = new EsiClientBuilder()
732
- .addClients(['market', 'universe', 'characters'])
733
- .withClientId('my-trading-bot')
734
- .withAccessToken('your-token')
735
- .build();
736
-
737
- const prices = await client.market?.getMarketPrices();
738
- const system = await client.universe?.getSystemById(30000142);
739
- ```
740
-
741
- Or create standalone single-API clients:
742
-
743
- ```typescript
744
- import { EsiApiFactory } from '@lgriffin/esi.ts';
745
-
746
- const marketClient = EsiApiFactory.createMarketClient({
747
- clientId: 'price-checker',
748
- });
749
- const prices = await marketClient.getMarketPrices();
750
- ```
751
-
752
- ## Endpoint Coverage
753
-
754
- All 223 endpoint definitions have been validated against live Tranquility using the **OpenAPI 3.1 spec** — 194 from the public ESI spec plus 29 for newer EVE features. 221 endpoints are exercisable (2 mercenary den endpoints await CCP deployment). Full output is captured in [`openapi.output.md`](openapi.output.md).
755
-
756
- | Category | Endpoints | Method |
757
- | --------------------------- | --------- | -------------------------------------------------- |
758
- | Public GETs | 78 | 46 runnable example scripts with captured output |
759
- | Authenticated GETs | 72 | Example scripts + live testing with EVE SSO tokens |
760
- | Contacts (POST/PUT/DELETE) | 3 | Live create/edit/delete lifecycle |
761
- | Fittings (POST/DELETE) | 2 | Live create/delete lifecycle |
762
- | Mail (POST/PUT/DELETE) | 5 | Live send/label/metadata/delete lifecycle |
763
- | UI (POST) | 5 | Live testing with EVE client running |
764
- | Calendar (PUT) | 1 | Live RSVP to event |
765
- | Fleet (GET/POST/PUT/DELETE) | 14 | Live fleet with fleet commander + squad members |
766
- | Assets POST | 3 | Live asset location/name queries |
767
- | CSPA (POST) | 1 | Live charge cost calculation |
768
- | Dogma dynamic (GET) | 1 | Live mutaplasmid (Abyssal) item query |
769
- | Universe POST helpers | 3 | Live name resolution and affiliation |
770
- | Freelance Jobs (GET) | 4 | Live queries (graceful 404 for no active jobs) |
771
-
772
- ## Examples
773
-
774
- 46 runnable examples are in the `examples/` directory.
775
-
776
- ### Public Endpoints (no auth needed)
777
-
778
- ```bash
779
- npm run example:status # Server status — quickest smoke test
780
- npm run example:character # Character public info, portrait, corporation
781
- npm run example:universe # Solar system, constellation, region, station
782
- npm run example:market # Average prices + Tritanium price history
783
- npm run example:alliance # Alliance info + member corporations
784
- npm run example:route # Jita-to-Amarr route with system names
785
- npm run example:wars # Recent wars with aggressor/defender details
786
- npm run example:sovereignty # Nullsec sovereignty map + active campaigns
787
- npm run example:industry # Industry facilities, cost indices, insurance
788
- npm run example:incursions # Active incursions + faction warfare stats
789
- npm run example:dogma # Item type details + dogma attributes
790
- npm run example:contracts # Public region contracts + auction bids/items
791
- npm run example:rate-limiting # Rate limiter & pagination demonstration
792
- npm run example:cursor-pagination # Freelance Jobs with cursor pagination
793
- npm run example:streaming # Streaming pagination for large datasets
794
- npm run example:token-refresh # Automatic token refresh on 401
795
- npm run example:universe-encyclopedia # Ancestries, bloodlines, races, celestials
796
- npm run example:dogma-meta-sov # Dogma effects, sovereignty, meta endpoint
797
- npm run example:faction-details # Faction warfare leaderboards and stats
798
- ```
799
-
800
- ### Authenticated Endpoints (require ESI_ACCESS_TOKEN)
801
-
802
- ```bash
803
- npm run example # Full character profile assembly
804
- npm run example:wallet # Wallet balance, journal, transactions
805
- npm run example:skills # Trained skills, queue, attributes
806
- npm run example:assets # Asset inventory with bulk name lookup
807
- npm run example:killmails # Recent killmails + full details
808
- npm run example:fleet # Fleet info, members, wing/squad structure
809
- npm run example:mail # Inbox headers, labels, mailing lists
810
- npm run example:location # Current system, online status, ship
811
- npm run example:fittings # Saved fittings + clone state + implants
812
- npm run example:contacts # Contact list with standings + labels
813
- npm run example:character-details # Blueprints, roles, standings, medals
814
- npm run example:corporation-details # Corp members, divisions, structures
815
- npm run example:calendar-search # Calendar events + character search
816
- npm run example:loyalty-pi # Loyalty points + planetary interaction
817
- npm run example:industry-mining # Industry jobs + mining ledger
818
- npm run example:market-orders # Character/corp market orders
819
- npm run example:corp-contracts-wallet # Corp contracts, contacts, wallets
820
- ```
821
-
822
- ### Write Operations (require specific scopes + caution)
823
-
824
- ```bash
825
- npm run example:write-ops # Contacts, fittings, mail, UI lifecycle tests
826
- npm run example:universe-posts # Name resolution + character affiliation (public)
827
- npm run example:freelance-jobs # Freelance job queries
828
- ```
829
-
830
- ### Parallel Requests
831
-
832
- ```typescript
833
- const [character, portrait, corp] = await Promise.all([
834
- client.characters.getCharacterPublicInfo(characterId),
835
- client.characters.getCharacterPortrait(characterId),
836
- client.corporations.getCorporationInfo(corporationId),
837
- ]);
838
-
839
- console.log(`${character.name} [${corp.ticker}]`);
840
- ```
841
-
842
- ### Market Analysis
843
-
844
- ```typescript
845
- const [orders, history] = await Promise.all([
846
- client.market.getMarketOrders(regionId),
847
- client.market.getMarketHistory(regionId, typeId),
848
- ]);
849
-
850
- const buyOrders = orders.filter((o) => o.is_buy_order);
851
- const sellOrders = orders.filter((o) => !o.is_buy_order);
852
-
853
- console.log(`Best buy: ${Math.max(...buyOrders.map((o) => o.price))}`);
854
- console.log(`Best sell: ${Math.min(...sellOrders.map((o) => o.price))}`);
855
- ```
856
-
857
- ## Resource Management
858
-
859
- Always call `shutdown()` when you're done to clean up cache timers:
860
-
861
- ```typescript
862
- const client = new EsiClient();
863
- try {
864
- const status = await client.status.getStatus();
865
- console.log(status.server_version);
866
- } finally {
867
- await client.shutdown();
868
- }
869
- ```
870
-
871
- ## Testing
872
-
873
- ESI.ts has a comprehensive multi-tier testing strategy with 139 suites and 4,104 tests:
874
-
875
- | Tier | Tests | Purpose |
876
- | -------------------------- | ---------------- | ------------------------------------------------------------------ |
877
- | **TDD unit tests** | 100 files | Every client method, endpoint path, query param, and body format |
878
- | **BDD scenario tests** | 41 feature files | Behavioral specifications in Gherkin (Given/When/Then) |
879
- | **Mocked integration** | Full suite | Cross-layer request flow with jest-fetch-mock |
880
- | **Live smoke tests** | 46 examples | Every endpoint against live Tranquility |
881
- | **ESI spec contract** | 15 tests | Endpoint definitions validated against live OpenAPI spec |
882
- | **Deep contract tests** | 8 categories | Path params, query params, body, auth, schemas, pagination vs spec |
883
- | **Property-based fuzzing** | 601 tests | fast-check fuzzing of validation, URL construction, Zod schemas |
884
- | **Mutation testing** | Stryker | Validates test suite kills code mutants |
885
- | **Type-level tests** | tsd | Consumer API type correctness via tsd |
886
- | **Gated auth tests** | 33 tests | Authenticated endpoints with real tokens |
887
- | **Construction parity** | Per-surface | Verifies all client surfaces get identical middleware defaults |
888
- | **Spec-alignment** | Type assertions | Ensures hand-written types align with generated OpenAPI types |
889
-
890
- ```bash
891
- npm test # Unit + BDD tests (143 suites, 4,182 tests)
892
- npm run coverage # Tests with coverage report (thresholds enforced)
893
- npm run bdd # BDD scenario tests only
894
- npm run contract # Contract tests (skipped without ESI_LIVE_TESTS=true)
895
- npm run fuzz # Property-based fuzz tests (601 tests)
896
- npm run mutation # Mutation testing (Stryker)
897
- npm run benchmark # Performance benchmark tests
898
- npm run test:types # tsd consumer type tests
899
- ```
900
-
901
- Coverage: statements 98.47%, branches 90.10%, functions 97.54%, lines 98.59%. Thresholds enforced in CI: branches 80%, functions 75%, lines 90%, statements 90%.
902
-
903
- See [guides/TESTING.md](guides/TESTING.md) for the full testing guide, and [guides/ARCHITECTURE.md](guides/ARCHITECTURE.md) for architecture diagrams.
904
-
905
- ## Development
906
-
907
- ### Prerequisites
908
-
909
- - Node.js 18+
910
- - npm
911
-
912
- ### Code Quality Tools
913
-
914
- The project uses a comprehensive suite of static analysis and code quality tools:
915
-
916
- | Tool | Purpose | Command |
917
- | ------------------------------------------------------------------------------------ | ------------------------------------------------------- | ------------------------------ |
918
- | [ESLint](https://eslint.org/) | Linting with TypeScript, security, and code smell rules | `npm run lint` |
919
- | [Prettier](https://prettier.io/) | Code formatting | `npm run format:check` |
920
- | [knip](https://knip.dev/) | Dead code and unused export detection | `npm run knip` |
921
- | [eslint-plugin-security](https://github.com/eslint-community/eslint-plugin-security) | Security anti-pattern detection | Integrated into `npm run lint` |
922
- | [eslint-plugin-sonarjs](https://github.com/SonarSource/eslint-plugin-sonarjs) | Cognitive complexity and code smell detection | Integrated into `npm run lint` |
923
- | [husky](https://typicode.github.io/husky/) | Git pre-commit hooks | Automatic on commit |
924
- | [lint-staged](https://github.com/lint-staged/lint-staged) | Run linters on staged files only | Automatic on commit |
925
- | [Redocly CLI](https://redocly.com/docs/cli/) | OpenAPI spec validation and linting | `npm run validate:spec` |
926
-
927
- ### Available Scripts
928
-
929
- ```bash
930
- # Development
931
- npm run build # Compile TypeScript
932
- npm run lint # Run ESLint
933
- npm run lint:fix # Run ESLint with auto-fix
934
- npm run format # Format code with Prettier
935
- npm run format:check # Check formatting without modifying
936
-
937
- # Testing
938
- npm test # Unit tests (143 suites, 4,182 tests)
939
- npm run test:all # Unit + BDD + integration + fuzz + type tests
940
- npm run coverage # Tests with coverage report (thresholds enforced)
941
- npm run bdd # BDD scenario tests
942
- npm run contract:live # Deep contract tests against live ESI spec
943
- npm run fuzz # Property-based fuzz tests (fast-check)
944
- npm run mutation # Mutation testing (Stryker)
945
- npm run benchmark # Performance benchmark tests
946
- npm run test:types # Consumer type tests (tsd)
947
- npm run mock:esi # Start Prism mock ESI server on port 4010
948
-
949
- # Static Analysis
950
- npm run knip # Detect dead code and unused exports
951
- npm run validate:esi # Validate endpoints against live ESI OpenAPI spec
952
- npm run validate:spec # Lint ESI OpenAPI spec with Redocly (structural + best practices)
953
- npm run validate:auth-scopes # Auth/scope cross-validation
954
- npm run schema:drift # Schema drift detection (hand-written vs OpenAPI spec)
955
- npm run validate # Run all checks: lint, format, build, coverage, knip
956
- npm run generate:types # Regenerate TypeScript interfaces from ESI OpenAPI spec
957
- npm run generate:endpoints # Regenerate endpoint definitions from ESI OpenAPI spec
958
- npm run generate:all # Run all generators (types + endpoints + OKF)
959
- npm run generate:okf # Generate OKF knowledge bundle from ESI OpenAPI spec
960
-
961
- # Documentation
962
- npm run docs # Generate TypeDoc API documentation
963
- npm run docs:serve # Serve docs locally on port 8080
964
- ```
965
-
966
- ### ESI Endpoint Validation
967
-
968
- To verify that the codebase endpoint definitions match the live ESI OpenAPI spec:
969
-
970
- ```bash
971
- npm run validate:esi
972
- ```
973
-
974
- This fetches the ESI OpenAPI spec and reports:
975
-
976
- - Endpoints in the codebase that are no longer in the ESI spec
977
- - Endpoints in the ESI spec that the codebase doesn't cover
978
- - HTTP method mismatches between codebase and spec
979
-
980
- ### Pre-commit Hooks
981
-
982
- The project uses husky with lint-staged to run ESLint and Prettier on staged files before each commit. This is set up automatically when you run `npm install`.
983
-
984
- ### CI/CD
985
-
986
- Every pull request runs the full validation suite:
987
-
988
- - ESLint (with security and sonarjs plugins)
989
- - Prettier formatting check
990
- - TypeScript compilation
991
- - Generated types staleness check (regenerates from live ESI OpenAPI spec and verifies no diff)
992
- - Unit tests across Node.js 18, 20, and 22
993
- - BDD scenario tests
994
- - Coverage threshold enforcement (branches: 80%, functions: 75%, lines: 90%, statements: 90%)
995
- - Auth/scopes cross-validation
996
- - Spec-alignment type assertions
997
- - Schema drift detection
998
- - Mutation testing (Stryker)
999
- - Dead code detection via knip
1000
- - npm security audit
1001
-
1002
- See [.github/workflows/README.md](.github/workflows/README.md) for full workflow details.
1003
-
1004
- ## Contributing
1005
-
1006
- 1. Fork the repository
1007
- 2. Create a feature branch
1008
- 3. Write tests for your changes
1009
- 4. Run `npm run validate` to check everything passes
1010
- 5. Open a Pull Request
1011
-
1012
- ## License
1013
-
1014
- GPL-3.0-or-later - see the [LICENSE](LICENSE) file for details.
1015
-
1016
- ---
1017
-
1018
- **o7**
1
+ # ESI.ts
2
+
3
+ [![npm version](https://badge.fury.io/js/%40lgriffin%2Fesi.ts.svg)](https://badge.fury.io/js/%40lgriffin%2Fesi.ts)
4
+ [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-6.0%2B-blue)](https://www.typescriptlang.org/)
6
+ [![CI/CD Pipeline](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml/badge.svg)](https://github.com/lgriffin/ESI.ts/actions/workflows/ci.yml)
7
+ [![Coverage](https://img.shields.io/badge/coverage-90%25%2B-brightgreen)](https://github.com/lgriffin/ESI.ts)
8
+ [![npm downloads](https://img.shields.io/npm/dm/%40lgriffin/esi.ts)](https://www.npmjs.com/package/@lgriffin/esi.ts)
9
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/lgriffin/ESI.ts/badge)](https://scorecard.dev/viewer/?uri=github.com/lgriffin/ESI.ts)
10
+
11
+ A production-grade TypeScript client for the [EVE Online ESI API](https://esi.evetech.net/), built on the **OpenAPI 3.1 spec**, with runtime validation, intelligent caching, and full endpoint coverage.
12
+
13
+ **v9.5.2** — Supply chain security hardening: all GitHub Actions pinned by SHA, npm publish with SLSA provenance attestations, least-privilege workflow permissions, script injection prevention, and ETag cache cross-tenant isolation.
14
+
15
+ **v9.5.0** — Adds 12 new ESI endpoints: CosmeticsClient (SKINR licenses, components, design lookup), ParagonHubClient (marketplace listings with cursor pagination), plus detail endpoints for Mercenary Dens, Tactical Operations, Skyhooks, and Sovereignty Hubs.
16
+
17
+ **235 endpoint definitions — 206 from the public ESI OpenAPI spec, plus 29 for newer EVE features (Equinox sovereignty, orbital skyhooks, mercenary dens, access lists, freelance jobs, military campaigns, corporation projects, SKINR cosmetics, Paragon Hub marketplace). All exercisable endpoints validated against live Tranquility.**
18
+
19
+ ## Why ESI.ts vs. OpenAPI-Generated Clients?
20
+
21
+ Tools like `openapi-typescript` or `openapi-generator` can produce a typed client from the ESI OpenAPI spec in minutes. They're a reasonable starting point — but they stop at type generation. ESI.ts is a purpose-built SDK that handles the problems you hit _after_ the types compile.
22
+
23
+ ### What generators give you
24
+
25
+ - TypeScript interfaces from the OpenAPI spec
26
+ - Basic request/response typing
27
+ - A thin HTTP wrapper
28
+
29
+ ### What ESI.ts gives you on top of that
30
+
31
+ | Capability | openapi-typescript | ESI.ts |
32
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
33
+ | **Runtime response validation** | None — types are erased at compile time. If CCP changes a field, you get silent data corruption. | Every GET response is validated at runtime via [Zod](https://zod.dev/) schemas — all 200 GET endpoints have schemas. Schema mismatches throw `EsiValidationError` immediately. |
34
+ | **Intelligent caching** | None — you build your own. | Three-tier: spec-aware TTL (zero HTTP calls within ESI's `x-cached-seconds` window), ETag conditional GETs, stale-on-error fallback on 5xx. Write operations auto-invalidate related GET caches. |
35
+ | **Rate limiting** | None — you build your own. | 36 per-group token buckets extracted from the ESI spec at build time. Market requests can't starve wallet requests. Optional per-user bucketing for multi-character apps. |
36
+ | **Pagination** | Manual — you write the page loop. | Automatic offset pagination, cursor-based pagination (Equinox-era endpoints), and streaming `AsyncGenerator` pagination for memory-efficient processing of large datasets. |
37
+ | **Retry & resilience** | None. | Exponential backoff with jitter, circuit breaker (closed/open/half-open), automatic 401 token refresh with concurrent coalescing. |
38
+ | **Wire format correctness** | Generates from spec, but ESI's spec has inconsistencies (query params documented as body, missing required fields). | Every endpoint tested against live ESI. Wire format bugs (query params vs. body, field naming) are caught and fixed — see the contacts and UI endpoint fixes in v6.1.0. |
39
+ | **Batch operations** | None. | `batch()` with bounded concurrency for GET fan-out, `batchPost()` with auto-chunking for large POST payloads. |
40
+ | **Domain knowledge** | None — generic HTTP client. | 39 domain clients with typed methods, JSDoc documentation, and input validation (e.g., fleet wing/squad names are capped at 10 characters before hitting the API). |
41
+ | **Streaming pagination** | None. | 21 domain clients with 73+ `stream*` methods via `AsyncGenerator` — process large datasets page-by-page without loading everything into memory. |
42
+ | **Testing** | Whatever you write. | 167 test suites, 4,730 tests across 9 tiers including property-based fuzzing (fast-check), mutation testing (Stryker), deep contract tests against live OpenAPI spec, and consumer type tests (tsd). 52 runnable example scripts. |
43
+
44
+ ### The real problem with generated clients
45
+
46
+ The ESI OpenAPI spec is not a perfect source of truth. During live endpoint validation against the OpenAPI 3.1 spec, we discovered:
47
+
48
+ - `addContacts`, `editContacts`, and 4 UI endpoints document parameters as request body when ESI actually expects query parameters
49
+ - `deleteCharacterContacts` expects comma-separated contact IDs as a query param, not a JSON body
50
+ - Fleet wing/squad names have a 10-character limit not documented in the spec
51
+ - The `updateMailMetadata` endpoint uses the field name `read`, not `is_read`
52
+
53
+ A generated client faithfully reproduces these spec bugs. ESI.ts fixes them.
54
+
55
+ ## Installation
56
+
57
+ ```bash
58
+ npm install @lgriffin/esi.ts
59
+ ```
60
+
61
+ ### Building from Source
62
+
63
+ ```bash
64
+ git clone https://github.com/lgriffin/ESI.ts.git
65
+ cd ESI.ts
66
+ npm install # installs dependencies and compiles (via the prepare script)
67
+ ```
68
+
69
+ If you've already installed and just need to recompile:
70
+
71
+ ```bash
72
+ npm run build
73
+ ```
74
+
75
+ Verify everything works:
76
+
77
+ ```bash
78
+ npm run example:status # quick smoke test — checks ESI is reachable
79
+ npm test # run the full test suite (167 suites, 4,730 tests)
80
+ ```
81
+
82
+ ## Sub-path Exports
83
+
84
+ ESI.ts provides sub-path exports for targeted imports, reducing bundle size when you only need specific parts of the library:
85
+
86
+ ```typescript
87
+ // Zod schemas for runtime validation
88
+ import { MarketOrderSchema } from '@lgriffin/esi.ts/schemas';
89
+
90
+ // Error classes and type guards
91
+ import { EsiError, isCircuitOpen } from '@lgriffin/esi.ts/errors';
92
+
93
+ // Test utilities
94
+ import { TestDataFactory } from '@lgriffin/esi.ts/testing';
95
+ ```
96
+
97
+ ## Static Data Export (SDE) Module
98
+
99
+ ESI.ts includes a standalone module for querying CCP's EVE Online Static Data Export — 102 YAML files loaded into in-memory Maps with 109 typed interfaces, Zod validation, and ~97 query methods. No database, no external services.
100
+
101
+ ```typescript
102
+ import { SdeDataProvider } from '@lgriffin/esi.ts/sde';
103
+
104
+ const sde = SdeDataProvider.fromDirectory('./sde-data');
105
+
106
+ const tritanium = sde.getType(34);
107
+ console.log(tritanium?.name); // "Tritanium"
108
+
109
+ const jita = sde.getSolarSystem(30000142);
110
+ const minerals = sde.getTypesByGroup(18);
111
+ const caldari = sde.getFaction(500001);
112
+
113
+ sde.close();
114
+ ```
115
+
116
+ Download SDE data with: `npx ts-node scripts/sde-ingest.ts --output sde-data`
117
+
118
+ | Document | Description |
119
+ | -------------------------------------------------- | --------------------------------------------------------------------------------------------- |
120
+ | [SDE README](src/sde/README.md) | Module overview, quick start, full API reference (~97 methods), entity coverage table |
121
+ | [Architecture](src/sde/docs/ARCHITECTURE.md) | C4 diagrams (context, container, component), data flow sequence, ER diagram, design decisions |
122
+ | [Usage Guide](src/sde/docs/USAGE.md) | Provider patterns, query examples, error handling |
123
+ | [Developer Guide](src/sde/docs/DEVELOPER_GUIDE.md) | Project structure, new entity checklist, field normalization, testing patterns |
124
+ | [API Contracts](src/sde/docs/API_CONTRACTS.md) | Complete method reference for all IStaticDataProvider methods |
125
+
126
+ ## Quick Start
127
+
128
+ ```typescript
129
+ import { EsiClient } from '@lgriffin/esi.ts';
130
+
131
+ const client = new EsiClient();
132
+
133
+ // Public data — no auth required
134
+ const alliances = await client.alliance.getAlliances();
135
+ const character = await client.characters.getCharacterPublicInfo(1689391488);
136
+ const system = await client.universe.getSystemById(30000142);
137
+ const prices = await client.market.getMarketPrices();
138
+
139
+ // Authenticated data — token read from ESI_ACCESS_TOKEN env var
140
+ const authedClient = new EsiClient();
141
+ const assets = await authedClient.assets.getCharacterAssets(characterId);
142
+ const wallet = await authedClient.wallet.getCharacterWallet(characterId);
143
+
144
+ // Clean up when done
145
+ await client.shutdown();
146
+ ```
147
+
148
+ ## Configuration
149
+
150
+ ```typescript
151
+ const client = new EsiClient({
152
+ clientId: 'my-app', // User-Agent identifier (default: 'esi-client')
153
+ accessToken: 'your-token', // EVE SSO token for authenticated endpoints
154
+ baseUrl: 'https://esi.evetech.net', // ESI base URL (default)
155
+ onTokenRefresh: async () => newToken, // Auto-refresh on 401 (optional)
156
+ language: 'en', // Accept-Language header: en, de, fr, ja, ru, zh, ko, es (default: none)
157
+ timeout: 30000, // Request timeout in ms (default: 30000)
158
+ retryConfig: {
159
+ maxRetries: 3, // Max retry attempts for transient errors (default: 3)
160
+ baseDelayMs: 1000, // Initial backoff delay (default: 1000)
161
+ maxDelayMs: 30000, // Maximum backoff delay (default: 30000)
162
+ retryMutations: false, // Retry POST/PUT/DELETE (default: false, GET only)
163
+ },
164
+ enableETagCache: true, // ETag caching (default: true)
165
+ etagCacheConfig: {
166
+ maxEntries: 1000, // Max cached responses (default: 1000)
167
+ defaultTtl: 300000, // Fallback TTL in ms (default: 5 min)
168
+ cleanupInterval: 60000, // Expired entry cleanup interval (default: 1 min)
169
+ },
170
+ validateResponse: true, // Runtime Zod validation of ESI responses (default: true)
171
+ validateRequest: false, // Opt-in request body Zod validation for POST/PUT/DELETE (default: false)
172
+ retryStrategy: customRetryStrategy, // Injectable IRetryStrategy (default: built-in exponential backoff)
173
+ circuitBreakerConfig: {
174
+ keyStrategy: 'resolved', // CB keying: 'resolved' (per-URL) or 'template' (per-route) (default: 'resolved')
175
+ cleanupIntervalMs: 300000, // Automatic stale circuit cleanup interval (default: 5 min)
176
+ },
177
+ });
178
+ ```
179
+
180
+ Retry is enabled by default (`maxRetries: 3`). Transient errors (502, 503, 504, timeout, rate limit) are retried with exponential backoff and jitter. The circuit breaker is respected — requests are not retried when the circuit is open. Set `maxRetries: 0` to disable retry.
181
+
182
+ The access token can be updated at runtime:
183
+
184
+ ```typescript
185
+ client.setAccessToken('new-token');
186
+ ```
187
+
188
+ ## Authentication
189
+
190
+ Many ESI endpoints require an EVE SSO access token. There are three ways to provide one:
191
+
192
+ ### 1. Environment variable (recommended)
193
+
194
+ Set `ESI_ACCESS_TOKEN` in your environment or a `.env` file. The client reads it automatically — no token in source code.
195
+
196
+ ```bash
197
+ # Copy the example and fill in your token
198
+ cp .env.example .env
199
+ ```
200
+
201
+ ```env
202
+ ESI_ACCESS_TOKEN=your-eve-sso-access-token
203
+ ESI_CLIENT_ID=my-app-name
204
+ ```
205
+
206
+ If you use a `.env` loader like [dotenv](https://www.npmjs.com/package/dotenv), load it before creating the client:
207
+
208
+ ```typescript
209
+ import 'dotenv/config';
210
+ import { EsiClient } from '@lgriffin/esi.ts';
211
+
212
+ const client = new EsiClient();
213
+ // Token is picked up from process.env.ESI_ACCESS_TOKEN
214
+ ```
215
+
216
+ ### 2. Constructor parameter
217
+
218
+ Pass the token directly (useful for apps that manage tokens themselves):
219
+
220
+ ```typescript
221
+ const client = new EsiClient({ accessToken: token });
222
+ ```
223
+
224
+ ### 3. Runtime update
225
+
226
+ Set or refresh the token after construction:
227
+
228
+ ```typescript
229
+ client.setAccessToken(newToken);
230
+ ```
231
+
232
+ ### Getting an EVE SSO token
233
+
234
+ 1. Register an application at [EVE Developers](https://developers.eveonline.com/)
235
+ 2. Set a callback URL and select the ESI scopes your app needs
236
+ 3. Implement the [OAuth2 flow](https://docs.esi.evetech.net/docs/sso/) to obtain an access token
237
+ 4. Access tokens expire — use the refresh token to get new ones
238
+
239
+ ### Automatic Token Refresh
240
+
241
+ EVE SSO access tokens expire after 20 minutes. Instead of manually tracking expiry, you can provide a refresh callback — the client will automatically call it on 401, update the token, and retry the request:
242
+
243
+ ```typescript
244
+ const client = new EsiClient({
245
+ accessToken: initialToken,
246
+ onTokenRefresh: async () => {
247
+ const response = await fetch('https://login.eveonline.com/v2/oauth/token', {
248
+ method: 'POST',
249
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
250
+ body: new URLSearchParams({
251
+ grant_type: 'refresh_token',
252
+ refresh_token: myRefreshToken,
253
+ client_id: myClientId,
254
+ }),
255
+ });
256
+ const { access_token } = await response.json();
257
+ return access_token;
258
+ },
259
+ });
260
+
261
+ // Requests now auto-refresh on 401 — no manual token management needed
262
+ const location = await client.location.getCharacterLocation(characterId);
263
+ ```
264
+
265
+ The token provider can also be set or changed at runtime:
266
+
267
+ ```typescript
268
+ client.setTokenProvider(myRefreshFunction);
269
+ client.setTokenProvider(undefined); // disable auto-refresh
270
+ ```
271
+
272
+ Key behaviors:
273
+
274
+ - Only retries **once** per request — if the refreshed token also gets a 401, the error is thrown
275
+ - **Concurrent coalescing** — if multiple requests hit 401 simultaneously, only one refresh call is made
276
+ - If the refresh callback throws (e.g., refresh token revoked), a `TOKEN_REFRESH_FAILED` error is raised
277
+ - Without a token provider, 401 errors throw immediately as before
278
+
279
+ ### Environment variables reference
280
+
281
+ | Variable | Description | Default |
282
+ | ------------------ | -------------------------------------------- | ------------------------- |
283
+ | `ESI_ACCESS_TOKEN` | EVE SSO access token | none |
284
+ | `ESI_CLIENT_ID` | User-Agent identifier | `esi-client` |
285
+ | `ESI_BASE_URL` | ESI API base URL | `https://esi.evetech.net` |
286
+ | `ESI_LOG_LEVEL` | Log level (`error`, `warn`, `info`, `debug`) | `warn` |
287
+
288
+ ## Available APIs
289
+
290
+ All clients are accessed as properties on the `EsiClient` instance. Authenticated endpoints require an access token.
291
+
292
+ | Client | Property | Auth | Examples |
293
+ | ------------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------- |
294
+ | Alliance | `client.alliance` | Some | `getAlliances()`, `getAllianceById(id)` |
295
+ | Assets | `client.assets` | Yes | `getCharacterAssets(id)` |
296
+ | Calendar | `client.calendar` | Yes | `getCalendarEvents(id)` |
297
+ | Characters | `client.characters` | Some | `getCharacterPublicInfo(id)`, `getCharacterPortrait(id)` |
298
+ | Clones | `client.clones` | Yes | `getCharacterClones(id)` |
299
+ | Contacts | `client.contacts` | Yes | `getCharacterContacts(id)`, `postCharacterContacts(id, standing, contactIds)` |
300
+ | Contracts | `client.contracts` | Yes | `getCharacterContracts(id)` |
301
+ | Corp Projects | `client.corporationProjects` | Yes | `getCorporationProjects(corpId)`, `getCorporationProject(corpId, projectId)` |
302
+ | Corporations | `client.corporations` | Some | `getCorporationInfo(id)`, `getCorporationMembers(id)` |
303
+ | Dogma | `client.dogma` | No | `getDogmaAttributes()`, `getDynamicItemInfo(typeId, itemId)` |
304
+ | Factions | `client.factions` | Some | `getFactionWarStats()` |
305
+ | Fittings | `client.fittings` | Yes | `getFittings(id)`, `createFitting(id, body)` |
306
+ | Fleets | `client.fleets` | Yes | `getFleetInformation(id)`, `getFleetMembers(id)` |
307
+ | Incursions | `client.incursions` | No | `getIncursions()` |
308
+ | Industry | `client.industry` | Some | `getCharacterIndustryJobs(id)` |
309
+ | Insurance | `client.insurance` | No | `getInsurancePrices()` |
310
+ | Killmails | `client.killmails` | Some | `getKillmail(id, hash)` |
311
+ | Location | `client.location` | Yes | `getCharacterLocation(id)` |
312
+ | Loyalty | `client.loyalty` | Yes | `getCharacterLoyaltyPoints(id)` |
313
+ | Mail | `client.mail` | Yes | `getCharacterMail(id)`, `sendMail(id, body)` |
314
+ | Market | `client.market` | Some | `getMarketPrices()`, `getMarketOrders(regionId)` |
315
+ | Military Campaigns | `client.militaryCampaigns` | Some | `getMilitaryCampaigns()`, `getMilitaryCampaignById(id)` |
316
+ | PI | `client.pi` | Yes | `getCharacterPlanets(id)` |
317
+ | Route | `client.route` | No | `getRoute(origin, destination)` |
318
+ | Search | `client.search` | Some | `search(characterId, query)` |
319
+ | Skills | `client.skills` | Yes | `getCharacterSkills(id)` |
320
+ | Sovereignty | `client.sovereignty` | No | `getSovereigntySystems()`, `getSovereigntyMap()` |
321
+ | Skyhooks | `client.skyhooks` | Some | `getSovereigntyHubs(corpId)`, `getSkyhookDetail(corpId, id)`, `getRaidableSkyhooks()` |
322
+ | Mercenary | `client.mercenary` | Yes | `getMercenaryDens(charId)`, `getMercenaryDenDetail(charId, denId)` |
323
+ | Cosmetics | `client.cosmetics` | Some | `getSkinr(id)`, `getCharacterSkinr(charId)`, `getCharacterSkinrComponents(charId)` |
324
+ | Paragon Hub | `client.paragonHub` | Some | `getPublicListings()`, `getCharacterListings(charId)`, `getAllianceListings(id)` |
325
+ | Access Lists | `client.accessLists` | Yes | `getAccessList(id)` |
326
+ | Status | `client.status` | No | `getStatus()` |
327
+ | UI | `client.ui` | Yes | `setAutopilotWaypoint(destId, addToBeginning, clear)`, `openNewMailWindow(body)` |
328
+ | Universe | `client.universe` | Some | `getSystemById(id)`, `getTypeById(id)` |
329
+ | Wallet | `client.wallet` | Yes | `getCharacterWallet(id)` |
330
+ | Wars | `client.wars` | No | `getWars()`, `getWarById(id)` |
331
+ | Freelance Jobs | `client.freelanceJobs` | Some | `getFreelanceJobs()`, `getFreelanceJobById(id)` |
332
+ | Meta | `client.meta` | No | `getOpenApiJson()`, `getOpenApiYaml()` |
333
+
334
+ ## Runtime Response Validation
335
+
336
+ ESI.ts validates API responses at runtime using [Zod](https://zod.dev/) schemas. All GET endpoints have schemas — these are the endpoints that return data your application consumes, where a silent shape change from CCP would cause bugs. POST/PUT/DELETE mutations typically return `204 No Content` (no body to validate) or simple confirmation values, so schemas are omitted where there is nothing meaningful to validate.
337
+
338
+ Validation is **on by default**. Extra fields from ESI are preserved via `z.looseObject()` passthrough mode, so new fields added by CCP won't break your application — they flow through to your code untouched.
339
+
340
+ ```typescript
341
+ import {
342
+ EsiClient,
343
+ EsiValidationError,
344
+ isValidationError,
345
+ schemas,
346
+ } from '@lgriffin/esi.ts';
347
+
348
+ const client = new EsiClient();
349
+
350
+ // Validation happens automatically on every request
351
+ const character = await client.characters.getCharacterPublicInfo(12345);
352
+
353
+ // Disable validation globally if needed
354
+ const rawClient = new EsiClient({ validateResponse: false });
355
+
356
+ // Use schemas directly for your own validation
357
+ const result = schemas.CharacterInfoSchema.safeParse(someData);
358
+ if (result.success) {
359
+ console.log(result.data.name);
360
+ }
361
+ ```
362
+
363
+ ### Request Body Validation
364
+
365
+ For POST/PUT/DELETE endpoints, opt-in request body validation ensures outgoing payloads match the endpoint's `requestSchema` before the request is sent:
366
+
367
+ ```typescript
368
+ // Opt-in request body validation for POST/PUT/DELETE
369
+ const client = new EsiClient({ validateRequest: true });
370
+
371
+ // Throws EsiValidationError if the request body doesn't match the endpoint's requestSchema
372
+ await client.mail.sendMail(characterId, {
373
+ recipients: [{ recipient_id: 12345, recipient_type: 'character' }],
374
+ subject: 'Hello',
375
+ body: 'Message body',
376
+ });
377
+ ```
378
+
379
+ See [guides/RUNTIME-VALIDATION.md](guides/RUNTIME-VALIDATION.md) for the full guide on schemas, error handling, and extending schemas.
380
+
381
+ ## Caching
382
+
383
+ ETag caching is enabled by default. The client automatically:
384
+
385
+ 1. Stores ETag and response data on GET requests
386
+ 2. Sends `If-None-Match` on subsequent requests
387
+ 3. Returns cached data on `304 Not Modified`
388
+ 4. Parses `Cache-Control: max-age` from ESI for per-endpoint TTL
389
+ 5. Serves stale cached data when ESI returns 5xx errors
390
+ 6. Invalidates related GET caches when POST/PUT/DELETE requests are made
391
+
392
+ ```typescript
393
+ // Cache stats
394
+ const stats = client.getCacheStats();
395
+ console.log(`${stats.totalEntries}/${stats.maxEntries} entries cached`);
396
+
397
+ // Manual cache operations
398
+ client.clearCache();
399
+ client.updateCacheConfig({ maxEntries: 2000 });
400
+
401
+ // Disable caching entirely
402
+ const uncachedClient = new EsiClient({ enableETagCache: false });
403
+ ```
404
+
405
+ ### Spec-Aware Cache TTLs
406
+
407
+ The library reads `x-cache-age` from the ESI OpenAPI spec (126 of 195 endpoints). Within the TTL window, repeated GET requests return cached data with **zero HTTP calls** — not even a conditional GET.
408
+
409
+ This layers on top of ETag caching in three tiers:
410
+
411
+ 1. **Spec TTL** — data can't have changed yet, return cached data immediately
412
+ 2. **ETag conditional GET** — data might have changed, send `If-None-Match` to check
413
+ 3. **Full request** — no cache entry, fetch fresh data
414
+
415
+ ```typescript
416
+ const client = new EsiClient();
417
+
418
+ // First call — fetches from ESI
419
+ const alliances = await client.alliance.getAlliances();
420
+
421
+ // Second call within the next 3600s — returns cached data, zero HTTP calls
422
+ const same = await client.alliance.getAlliances();
423
+ ```
424
+
425
+ ## Batch Requests
426
+
427
+ Fetch data for multiple IDs with bounded concurrency using `batch()`, or chunk large POST payloads with `batchPost()`:
428
+
429
+ ```typescript
430
+ import { EsiClient } from '@lgriffin/esi.ts';
431
+
432
+ const client = new EsiClient();
433
+
434
+ // Fetch 500 type details with at most 10 concurrent requests
435
+ const result = await client.batch(
436
+ typeIds,
437
+ (id) => client.universe.getTypeById(id),
438
+ {
439
+ concurrency: 10,
440
+ onProgress: (done, total) => console.log(`${done}/${total}`),
441
+ },
442
+ );
443
+
444
+ // result.results: Map<number, T> — successful responses
445
+ // result.errors: Map<number, Error> — failed requests
446
+ console.log(`${result.results.size} succeeded, ${result.errors.size} failed`);
447
+ ```
448
+
449
+ For POST endpoints that accept arrays (e.g., `postUniverseNames` with a 1000-ID limit), `batchPost` auto-chunks and concatenates:
450
+
451
+ ```typescript
452
+ const allNames = await client.batchPost(
453
+ largeIdArray,
454
+ (chunk) => client.universe.postUniverseNames(chunk),
455
+ 1000, // chunk size
456
+ );
457
+ ```
458
+
459
+ ## Streaming Pagination
460
+
461
+ For large paginated endpoints (market orders, contracts, assets), streaming yields one page at a time via `AsyncGenerator` instead of eagerly fetching all pages into memory:
462
+
463
+ ```typescript
464
+ import { EsiClient } from '@lgriffin/esi.ts';
465
+
466
+ const client = new EsiClient();
467
+
468
+ // Stream all market orders in The Forge, page by page
469
+ for await (const page of client.market.streamMarketOrders(10000002)) {
470
+ console.log(
471
+ `Page ${page.page}/${page.totalPages}: ${page.data.length} orders`,
472
+ );
473
+
474
+ // Process each order as it arrives
475
+ for (const order of page.data) {
476
+ if (order.is_buy_order && order.price > 1_000_000) {
477
+ console.log(`High-value buy: ${order.type_id} @ ${order.price} ISK`);
478
+ }
479
+ }
480
+
481
+ // Early termination — stops fetching remaining pages
482
+ if (page.page >= 3) break;
483
+ }
484
+ ```
485
+
486
+ 21 domain clients expose 73+ streaming methods. `BaseEsiClient.streamEndpoint()` is also public as an escape hatch for any paginated endpoint not yet wrapped with a convenience method.
487
+
488
+ Available streaming methods (representative selection):
489
+
490
+ - **MarketClient** — `streamMarketOrders`, `streamMarketTypes`, `streamCharacterOrderHistory`, `streamCorporationOrders`, `streamCorporationOrderHistory`, `streamMarketOrdersInStructure`
491
+ - **CorporationsClient** — `streamCorporationMembers`, `streamCorporationStructures`, `streamCorporationBlueprints`, + 14 more
492
+ - **CharacterClient** — `streamCharacterBlueprints`, `streamCharacterNotifications`, `streamCharacterStandings`, + 5 more
493
+ - **ContractsClient** — `streamPublicContracts`, `streamCharacterContracts`, `streamCorporationContracts`
494
+ - **WalletClient** — `streamCharacterWalletJournal`, `streamCorporationWalletJournal`, `streamCharacterWalletTransactions`
495
+ - **IndustryClient** — `streamCorporationIndustryJobs`, `streamCorporationMiningObservers`, + 6 more
496
+ - **ContactsClient** — `streamAllianceContacts`, `streamCharacterContacts`, `streamCorporationContacts`, + 3 more
497
+ - **AssetsClient** — `streamCharacterAssets`, `streamCorporationAssets`
498
+ - **KillmailsClient** — `streamCharacterRecentKillmails`, `streamCorporationRecentKillmails`
499
+ - **MailClient** — `streamCharacterMail`, `streamCharacterMailLabels`
500
+ - **FleetsClient** — `streamFleetMembers`, `streamFleetWings`
501
+ - **CalendarClient** — `streamCalendarEvents`
502
+ - **FittingsClient** — `streamCharacterFittings`
503
+ - **SkillsClient** — `streamCharacterSkillQueue`
504
+ - **LoyaltyClient** — `streamCorporationLoyaltyStoreOffers`
505
+ - **BookmarksClient** — `streamCharacterBookmarks`, `streamCorporationBookmarks`
506
+ - **ClonesClient** — `streamCharacterImplants`
507
+ - **PIClient** — `streamCharacterPlanets`
508
+ - **WarsClient** — `streamWars`
509
+ - **FactionWarfareClient** — `streamFactionWarfareStats`
510
+ - **AllianceClient** — `streamAllianceCorporations`
511
+
512
+ Try it: `npm run example:streaming`
513
+
514
+ ## Cursor-based Pagination
515
+
516
+ Newer ESI routes (Freelance Jobs, and future routes) use cursor-based pagination with opaque `before`/`after` tokens in the response body. See the [ESI blog post](https://developers.eveonline.com/blog/changing-pagination-turning-a-new-page) for background.
517
+
518
+ ```typescript
519
+ import { EsiClient, fetchAllCursorPages } from '@lgriffin/esi.ts';
520
+
521
+ const client = new EsiClient();
522
+
523
+ // Fetch first page — returns { cursor: { before, after }, freelance_jobs: [...] }
524
+ const page = await client.freelanceJobs.getFreelanceJobs();
525
+ console.log(page.freelance_jobs); // job records
526
+ console.log(page.cursor.after); // opaque token for next page
527
+
528
+ // Fetch next page using the cursor
529
+ const nextPage = await client.freelanceJobs.getFreelanceJobs(
530
+ undefined,
531
+ page.cursor.after,
532
+ );
533
+
534
+ // Auto-fetch all pages in one call
535
+ const allJobs = await fetchAllCursorPages(
536
+ (before, after) => client.freelanceJobs.getFreelanceJobs(before, after),
537
+ (response) => response.freelance_jobs,
538
+ (response) => response.cursor,
539
+ );
540
+
541
+ // Authenticated endpoints — character/corporation freelance jobs
542
+ const authedClient = new EsiClient({ accessToken: 'your-token' });
543
+ const myJobs =
544
+ await authedClient.freelanceJobs.getCharacterFreelanceJobs(characterId);
545
+ const corpJobs =
546
+ await authedClient.freelanceJobs.getCorporationFreelanceJobs(corporationId);
547
+ ```
548
+
549
+ **Polling for changes** — cursor tokens persist across sessions, so you can save the last `after` token and poll later to get only records that changed:
550
+
551
+ ```typescript
552
+ // After initial scan, save the final cursor
553
+ let savedCursor = lastPage.cursor.after;
554
+
555
+ // Later: check for updates (hours, days, or weeks later)
556
+ const updates = await client.freelanceJobs.getFreelanceJobs(
557
+ undefined,
558
+ savedCursor,
559
+ );
560
+ if (updates.freelance_jobs.length > 0) {
561
+ // Process changed records — duplicates are expected for modified records
562
+ savedCursor = updates.cursor.after;
563
+ }
564
+ ```
565
+
566
+ Key points:
567
+
568
+ - Cursor tokens are **opaque strings** — never parse or validate them
569
+ - An **empty result array** signals the end of the dataset (not a short page)
570
+ - **Duplicates across pages** are expected when records are modified between requests
571
+ - Existing offset-based routes (`getMarketOrders`, etc.) are unchanged
572
+
573
+ ## Generated Types
574
+
575
+ The library includes TypeScript interfaces generated directly from the ESI OpenAPI 3.1 spec, available as the `EsiSpec` namespace. These are guaranteed to match the live spec and complement the hand-written types:
576
+
577
+ ```typescript
578
+ import { EsiSpec } from '@lgriffin/esi.ts';
579
+
580
+ // Generated type — uses OpenAPI schema names (v7.0.0+)
581
+ const order: EsiSpec.MarketsRegionIdOrdersGet = {
582
+ order_id: 123,
583
+ type_id: 34,
584
+ price: 5.5,
585
+ volume_remain: 1000,
586
+ volume_total: 5000,
587
+ is_buy_order: false,
588
+ // ...
589
+ };
590
+ ```
591
+
592
+ To regenerate types from the latest ESI spec:
593
+
594
+ ```bash
595
+ npm run generate:types # fetches OpenAPI spec, generates 161 interfaces + cache TTL map + rate limit groups + scope map
596
+ npm run validate:esi # reports type drift between hand-written and generated types
597
+ ```
598
+
599
+ ## ESI Scopes
600
+
601
+ The library includes a generated scope-to-endpoint mapping extracted from the ESI OpenAPI spec. Use it to check which OAuth scopes an endpoint requires before making a request:
602
+
603
+ ```typescript
604
+ import { esiEndpointScopes, EsiScope } from '@lgriffin/esi.ts';
605
+
606
+ // Look up scopes for a specific endpoint
607
+ const walletScopes = esiEndpointScopes['GET:characters/{character_id}/wallet'];
608
+ // → ['esi-wallet.read_character_wallet.v1']
609
+
610
+ // Check if an endpoint requires auth
611
+ const isPublic = !esiEndpointScopes['GET:universe/types/{type_id}'];
612
+ // → true (public endpoint, no scopes needed)
613
+
614
+ // Type-safe scope values
615
+ const scope: EsiScope = 'esi-assets.read_assets.v1';
616
+ ```
617
+
618
+ ## Error Handling
619
+
620
+ API errors throw `EsiError` with `statusCode`, `message`, and `url` properties:
621
+
622
+ ```typescript
623
+ import {
624
+ EsiError,
625
+ TimeoutError,
626
+ EsiValidationError,
627
+ isTimeout,
628
+ isRetryable,
629
+ isValidationError,
630
+ isCircuitOpen,
631
+ } from '@lgriffin/esi.ts';
632
+
633
+ try {
634
+ const alliance = await client.alliance.getAllianceById(99999999);
635
+ console.log('Alliance:', alliance.name);
636
+ } catch (err) {
637
+ if (isCircuitOpen(err)) {
638
+ console.log('Circuit breaker is open — endpoint temporarily unavailable');
639
+ } else if (isValidationError(err)) {
640
+ console.log('Response validation failed:', err.validationError);
641
+ } else if (isTimeout(err)) {
642
+ console.log(`Request timed out after ${err.timeoutMs}ms`);
643
+ } else if (err instanceof EsiError) {
644
+ console.log(`ESI error ${err.statusCode}: ${err.message}`);
645
+ console.log(`Retryable: ${err.retryable}`);
646
+ }
647
+ }
648
+ ```
649
+
650
+ - **204 No Content** — returns `undefined` (valid for DELETE/POST actions)
651
+ - **304 Not Modified** — handled internally, returns cached data
652
+ - **4xx/5xx** — throws `EsiError`
653
+ - **5xx with cache** — returns stale cached data instead of throwing
654
+ - **Timeout** — throws `TimeoutError` (extends `EsiError` with `statusCode: 0` and `timeoutMs`)
655
+ - **Retryable errors** — `EsiError.retryable` returns `true` for 502, 503, 504, 420, 429, and timeouts
656
+ - **Validation errors** — throws `EsiValidationError` (extends `EsiError`) when response data doesn't match the expected Zod schema
657
+
658
+ ## Response Metadata
659
+
660
+ Use `withMetadata()` to get response headers, cache status, rate limit info, and timing alongside the data:
661
+
662
+ ```typescript
663
+ const metaClient = client.alliance.withMetadata();
664
+ const result = await metaClient.getAllianceById(99000001);
665
+
666
+ console.log(result.data.name); // "Goonswarm Federation"
667
+ console.log(result.meta.fromCache); // true if served from cache
668
+ console.log(result.meta.cacheHitType); // 'spec-ttl' | 'etag-304' | 'stale-on-error'
669
+ console.log(result.meta.responseTimeMs); // milliseconds
670
+ console.log(result.meta.rateLimit); // { remaining, limit, used, group }
671
+ console.log(result.meta.requestId); // ESI request ID for debugging
672
+ ```
673
+
674
+ The `meta` object includes:
675
+
676
+ | Field | Type | Description |
677
+ | ---------------- | ------------------------ | ------------------------------------------------- |
678
+ | `headers` | `Record<string, string>` | Raw response headers |
679
+ | `fromCache` | `boolean` | Whether data was served from cache |
680
+ | `stale` | `boolean` | Whether cached data is stale (5xx fallback) |
681
+ | `cacheHitType` | `string?` | `'spec-ttl'`, `'etag-304'`, or `'stale-on-error'` |
682
+ | `rateLimit` | `RateLimitMeta?` | Rate limit status from ESI headers |
683
+ | `responseTimeMs` | `number?` | Request duration in milliseconds |
684
+ | `requestId` | `string?` | ESI request ID |
685
+ | `warning` | `object?` | ESI deprecation warning |
686
+
687
+ ## Rate Limiting
688
+
689
+ ESI.ts automatically manages rate limiting using ESI's per-group token bucket system. The 36 rate limit groups from the ESI OpenAPI spec are extracted at build time, so each group (e.g., `market-order`, `char-notification`) gets its own independent bucket. A burst of market requests won't starve unrelated endpoints.
690
+
691
+ Rate limiting works out of the box with no configuration. For multi-character applications, enable per-user bucketing:
692
+
693
+ ```typescript
694
+ import { EsiClient } from '@lgriffin/esi.ts';
695
+
696
+ const client = new EsiClient({
697
+ rateLimiterConfig: {
698
+ userKeyExtractor: (headers) => headers['authorization'] ?? 'anon',
699
+ },
700
+ });
701
+ ```
702
+
703
+ Monitor rate limit status per group:
704
+
705
+ ```typescript
706
+ const limiter = client.getRateLimiter();
707
+
708
+ // Worst-case across all groups (backward-compatible)
709
+ const status = limiter.getStatus();
710
+ console.log(status.remaining, status.limit, status.group);
711
+
712
+ // Specific group
713
+ const marketStatus = limiter.getGroupStatus('market-order');
714
+ console.log(marketStatus?.remaining); // tokens remaining in this group
715
+
716
+ // All active groups
717
+ const all = limiter.getAllGroupStatuses();
718
+ for (const [group, info] of all) {
719
+ console.log(`${group}: ${info.remaining}/${info.limit}`);
720
+ }
721
+
722
+ // Check if a specific group is blocked
723
+ console.log(limiter.isBlocked('char-notification')); // true if 429'd
724
+ ```
725
+
726
+ ## Lightweight Clients
727
+
728
+ All three client creation patterns (`EsiClient`, `CustomEsiClient`, `EsiApiFactory`) now get identical middleware defaults (cache, request deduplication, rate limiter) thanks to `configureApiClient()`. Previously `CustomEsiClient` and `EsiApiFactory` only configured the rate limiter.
729
+
730
+ If you only need a subset of APIs, use `CustomEsiClient` or `EsiClientBuilder` to load only what you need:
731
+
732
+ ```typescript
733
+ import { EsiClientBuilder } from '@lgriffin/esi.ts';
734
+
735
+ const client = new EsiClientBuilder()
736
+ .addClients(['market', 'universe', 'characters'])
737
+ .withClientId('my-trading-bot')
738
+ .withAccessToken('your-token')
739
+ .build();
740
+
741
+ const prices = await client.market?.getMarketPrices();
742
+ const system = await client.universe?.getSystemById(30000142);
743
+ ```
744
+
745
+ Or create standalone single-API clients:
746
+
747
+ ```typescript
748
+ import { EsiApiFactory } from '@lgriffin/esi.ts';
749
+
750
+ const marketClient = EsiApiFactory.createMarketClient({
751
+ clientId: 'price-checker',
752
+ });
753
+ const prices = await marketClient.getMarketPrices();
754
+ ```
755
+
756
+ ## Endpoint Coverage
757
+
758
+ All 235 endpoint definitions have been validated against live Tranquility using the **OpenAPI 3.1 spec** — 206 from the public ESI spec plus 29 for newer EVE features. Full output is captured in [`openapi.output.md`](openapi.output.md).
759
+
760
+ | Category | Endpoints | Method |
761
+ | --------------------------- | --------- | -------------------------------------------------- |
762
+ | Public GETs | 86 | 52 runnable example scripts with captured output |
763
+ | Authenticated GETs | 114 | Example scripts + live testing with EVE SSO tokens |
764
+ | Contacts (POST/PUT/DELETE) | 3 | Live create/edit/delete lifecycle |
765
+ | Fittings (POST/DELETE) | 2 | Live create/delete lifecycle |
766
+ | Mail (POST/PUT/DELETE) | 5 | Live send/label/metadata/delete lifecycle |
767
+ | UI (POST) | 5 | Live testing with EVE client running |
768
+ | Calendar (PUT) | 1 | Live RSVP to event |
769
+ | Fleet (GET/POST/PUT/DELETE) | 14 | Live fleet with fleet commander + squad members |
770
+ | Assets POST | 3 | Live asset location/name queries |
771
+ | CSPA (POST) | 1 | Live charge cost calculation |
772
+ | Dogma dynamic (GET) | 1 | Live mutaplasmid (Abyssal) item query |
773
+ | Universe POST helpers | 3 | Live name resolution and affiliation |
774
+ | Freelance Jobs (GET) | 4 | Live queries (graceful 404 for no active jobs) |
775
+
776
+ ## Examples
777
+
778
+ 52 runnable examples are in the `examples/` directory.
779
+
780
+ ### Public Endpoints (no auth needed)
781
+
782
+ ```bash
783
+ npm run example:status # Server status — quickest smoke test
784
+ npm run example:character # Character public info, portrait, corporation
785
+ npm run example:universe # Solar system, constellation, region, station
786
+ npm run example:market # Average prices + Tritanium price history
787
+ npm run example:alliance # Alliance info + member corporations
788
+ npm run example:route # Jita-to-Amarr route with system names
789
+ npm run example:wars # Recent wars with aggressor/defender details
790
+ npm run example:sovereignty # Nullsec sovereignty map + active campaigns
791
+ npm run example:industry # Industry facilities, cost indices, insurance
792
+ npm run example:incursions # Active incursions + faction warfare stats
793
+ npm run example:dogma # Item type details + dogma attributes
794
+ npm run example:contracts # Public region contracts + auction bids/items
795
+ npm run example:rate-limiting # Rate limiter & pagination demonstration
796
+ npm run example:cursor-pagination # Freelance Jobs with cursor pagination
797
+ npm run example:streaming # Streaming pagination for large datasets
798
+ npm run example:token-refresh # Automatic token refresh on 401
799
+ npm run example:universe-encyclopedia # Ancestries, bloodlines, races, celestials
800
+ npm run example:dogma-meta-sov # Dogma effects, sovereignty, meta endpoint
801
+ npm run example:faction-details # Faction warfare leaderboards and stats
802
+ ```
803
+
804
+ ### Authenticated Endpoints (require ESI_ACCESS_TOKEN)
805
+
806
+ ```bash
807
+ npm run example # Full character profile assembly
808
+ npm run example:wallet # Wallet balance, journal, transactions
809
+ npm run example:skills # Trained skills, queue, attributes
810
+ npm run example:assets # Asset inventory with bulk name lookup
811
+ npm run example:killmails # Recent killmails + full details
812
+ npm run example:fleet # Fleet info, members, wing/squad structure
813
+ npm run example:mail # Inbox headers, labels, mailing lists
814
+ npm run example:location # Current system, online status, ship
815
+ npm run example:fittings # Saved fittings + clone state + implants
816
+ npm run example:contacts # Contact list with standings + labels
817
+ npm run example:character-details # Blueprints, roles, standings, medals
818
+ npm run example:corporation-details # Corp members, divisions, structures
819
+ npm run example:calendar-search # Calendar events + character search
820
+ npm run example:loyalty-pi # Loyalty points + planetary interaction
821
+ npm run example:industry-mining # Industry jobs + mining ledger
822
+ npm run example:market-orders # Character/corp market orders
823
+ npm run example:corp-contracts-wallet # Corp contracts, contacts, wallets
824
+ ```
825
+
826
+ ### Write Operations (require specific scopes + caution)
827
+
828
+ ```bash
829
+ npm run example:write-ops # Contacts, fittings, mail, UI lifecycle tests
830
+ npm run example:universe-posts # Name resolution + character affiliation (public)
831
+ npm run example:freelance-jobs # Freelance job queries
832
+ ```
833
+
834
+ ### Parallel Requests
835
+
836
+ ```typescript
837
+ const [character, portrait, corp] = await Promise.all([
838
+ client.characters.getCharacterPublicInfo(characterId),
839
+ client.characters.getCharacterPortrait(characterId),
840
+ client.corporations.getCorporationInfo(corporationId),
841
+ ]);
842
+
843
+ console.log(`${character.name} [${corp.ticker}]`);
844
+ ```
845
+
846
+ ### Market Analysis
847
+
848
+ ```typescript
849
+ const [orders, history] = await Promise.all([
850
+ client.market.getMarketOrders(regionId),
851
+ client.market.getMarketHistory(regionId, typeId),
852
+ ]);
853
+
854
+ const buyOrders = orders.filter((o) => o.is_buy_order);
855
+ const sellOrders = orders.filter((o) => !o.is_buy_order);
856
+
857
+ console.log(`Best buy: ${Math.max(...buyOrders.map((o) => o.price))}`);
858
+ console.log(`Best sell: ${Math.min(...sellOrders.map((o) => o.price))}`);
859
+ ```
860
+
861
+ ## Resource Management
862
+
863
+ Always call `shutdown()` when you're done to clean up cache timers:
864
+
865
+ ```typescript
866
+ const client = new EsiClient();
867
+ try {
868
+ const status = await client.status.getStatus();
869
+ console.log(status.server_version);
870
+ } finally {
871
+ await client.shutdown();
872
+ }
873
+ ```
874
+
875
+ ## Testing
876
+
877
+ ESI.ts has a comprehensive multi-tier testing strategy with 139 suites and 4,104 tests:
878
+
879
+ | Tier | Tests | Purpose |
880
+ | -------------------------- | ---------------- | ------------------------------------------------------------------ |
881
+ | **TDD unit tests** | 100 files | Every client method, endpoint path, query param, and body format |
882
+ | **BDD scenario tests** | 41 feature files | Behavioral specifications in Gherkin (Given/When/Then) |
883
+ | **Mocked integration** | Full suite | Cross-layer request flow with jest-fetch-mock |
884
+ | **Live smoke tests** | 46 examples | Every endpoint against live Tranquility |
885
+ | **ESI spec contract** | 15 tests | Endpoint definitions validated against live OpenAPI spec |
886
+ | **Deep contract tests** | 8 categories | Path params, query params, body, auth, schemas, pagination vs spec |
887
+ | **Property-based fuzzing** | 601 tests | fast-check fuzzing of validation, URL construction, Zod schemas |
888
+ | **Mutation testing** | Stryker | Validates test suite kills code mutants |
889
+ | **Type-level tests** | tsd | Consumer API type correctness via tsd |
890
+ | **Gated auth tests** | 33 tests | Authenticated endpoints with real tokens |
891
+ | **Construction parity** | Per-surface | Verifies all client surfaces get identical middleware defaults |
892
+ | **Spec-alignment** | Type assertions | Ensures hand-written types align with generated OpenAPI types |
893
+
894
+ ```bash
895
+ npm test # Unit + BDD tests (167 suites, 4,730 tests)
896
+ npm run coverage # Tests with coverage report (thresholds enforced)
897
+ npm run bdd # BDD scenario tests only
898
+ npm run contract # Contract tests (skipped without ESI_LIVE_TESTS=true)
899
+ npm run fuzz # Property-based fuzz tests (601 tests)
900
+ npm run mutation # Mutation testing (Stryker)
901
+ npm run benchmark # Performance benchmark tests
902
+ npm run test:types # tsd consumer type tests
903
+ ```
904
+
905
+ Coverage: statements 98.47%, branches 90.10%, functions 97.54%, lines 98.59%. Thresholds enforced in CI: branches 80%, functions 75%, lines 90%, statements 90%.
906
+
907
+ See [guides/TESTING.md](guides/TESTING.md) for the full testing guide, and [guides/ARCHITECTURE.md](guides/ARCHITECTURE.md) for architecture diagrams.
908
+
909
+ ## Development
910
+
911
+ ### Prerequisites
912
+
913
+ - Node.js 18+
914
+ - npm
915
+
916
+ ### Code Quality Tools
917
+
918
+ The project uses a comprehensive suite of static analysis and code quality tools:
919
+
920
+ | Tool | Purpose | Command |
921
+ | ------------------------------------------------------------------------------------ | ------------------------------------------------------- | ------------------------------ |
922
+ | [ESLint](https://eslint.org/) | Linting with TypeScript, security, and code smell rules | `npm run lint` |
923
+ | [Prettier](https://prettier.io/) | Code formatting | `npm run format:check` |
924
+ | [knip](https://knip.dev/) | Dead code and unused export detection | `npm run knip` |
925
+ | [eslint-plugin-security](https://github.com/eslint-community/eslint-plugin-security) | Security anti-pattern detection | Integrated into `npm run lint` |
926
+ | [eslint-plugin-sonarjs](https://github.com/SonarSource/eslint-plugin-sonarjs) | Cognitive complexity and code smell detection | Integrated into `npm run lint` |
927
+ | [husky](https://typicode.github.io/husky/) | Git pre-commit hooks | Automatic on commit |
928
+ | [lint-staged](https://github.com/lint-staged/lint-staged) | Run linters on staged files only | Automatic on commit |
929
+ | [Redocly CLI](https://redocly.com/docs/cli/) | OpenAPI spec validation and linting | `npm run validate:spec` |
930
+
931
+ ### Available Scripts
932
+
933
+ ```bash
934
+ # Development
935
+ npm run build # Compile TypeScript
936
+ npm run lint # Run ESLint
937
+ npm run lint:fix # Run ESLint with auto-fix
938
+ npm run format # Format code with Prettier
939
+ npm run format:check # Check formatting without modifying
940
+
941
+ # Testing
942
+ npm test # Unit tests (167 suites, 4,730 tests)
943
+ npm run test:all # Unit + BDD + integration + fuzz + type tests
944
+ npm run coverage # Tests with coverage report (thresholds enforced)
945
+ npm run bdd # BDD scenario tests
946
+ npm run contract:live # Deep contract tests against live ESI spec
947
+ npm run fuzz # Property-based fuzz tests (fast-check)
948
+ npm run mutation # Mutation testing (Stryker)
949
+ npm run benchmark # Performance benchmark tests
950
+ npm run test:types # Consumer type tests (tsd)
951
+ npm run mock:esi # Start Prism mock ESI server on port 4010
952
+
953
+ # Static Analysis
954
+ npm run knip # Detect dead code and unused exports
955
+ npm run validate:esi # Validate endpoints against live ESI OpenAPI spec
956
+ npm run validate:spec # Lint ESI OpenAPI spec with Redocly (structural + best practices)
957
+ npm run validate:auth-scopes # Auth/scope cross-validation
958
+ npm run schema:drift # Schema drift detection (hand-written vs OpenAPI spec)
959
+ npm run validate # Run all checks: lint, format, build, coverage, knip
960
+ npm run generate:types # Regenerate TypeScript interfaces from ESI OpenAPI spec
961
+ npm run generate:endpoints # Regenerate endpoint definitions from ESI OpenAPI spec
962
+ npm run generate:all # Run all generators (types + endpoints + OKF)
963
+ npm run generate:okf # Generate OKF knowledge bundle from ESI OpenAPI spec
964
+
965
+ # Documentation
966
+ npm run docs # Generate TypeDoc API documentation
967
+ npm run docs:serve # Serve docs locally on port 8080
968
+ ```
969
+
970
+ ### ESI Endpoint Validation
971
+
972
+ To verify that the codebase endpoint definitions match the live ESI OpenAPI spec:
973
+
974
+ ```bash
975
+ npm run validate:esi
976
+ ```
977
+
978
+ This fetches the ESI OpenAPI spec and reports:
979
+
980
+ - Endpoints in the codebase that are no longer in the ESI spec
981
+ - Endpoints in the ESI spec that the codebase doesn't cover
982
+ - HTTP method mismatches between codebase and spec
983
+
984
+ ### Pre-commit Hooks
985
+
986
+ The project uses husky with lint-staged to run ESLint and Prettier on staged files before each commit. This is set up automatically when you run `npm install`.
987
+
988
+ ### CI/CD
989
+
990
+ Every pull request runs the full validation suite:
991
+
992
+ - ESLint (with security and sonarjs plugins)
993
+ - Prettier formatting check
994
+ - TypeScript compilation
995
+ - Generated types staleness check (regenerates from live ESI OpenAPI spec and verifies no diff)
996
+ - Unit tests across Node.js 18, 20, and 22
997
+ - BDD scenario tests
998
+ - Coverage threshold enforcement (branches: 80%, functions: 75%, lines: 90%, statements: 90%)
999
+ - Auth/scopes cross-validation
1000
+ - Spec-alignment type assertions
1001
+ - Schema drift detection
1002
+ - Mutation testing (Stryker)
1003
+ - Dead code detection via knip
1004
+ - npm security audit
1005
+
1006
+ **Supply chain security:**
1007
+
1008
+ - All GitHub Actions pinned by SHA hash (not mutable tags) to prevent supply chain attacks
1009
+ - Least-privilege `permissions:` on all workflows and jobs
1010
+ - Script injection prevention (user-controlled inputs passed via `env:`, never interpolated in `run:`)
1011
+ - npm publish with `--provenance` for SLSA attestations (verifiable build origin)
1012
+ - OpenSSF Scorecard runs weekly via the `scorecard.yml` workflow
1013
+
1014
+ See [.github/workflows/README.md](.github/workflows/README.md) for full workflow details.
1015
+
1016
+ ## Contributing
1017
+
1018
+ 1. Fork the repository
1019
+ 2. Create a feature branch
1020
+ 3. Write tests for your changes
1021
+ 4. Run `npm run validate` to check everything passes
1022
+ 5. Open a Pull Request
1023
+
1024
+ ## License
1025
+
1026
+ GPL-3.0-or-later - see the [LICENSE](LICENSE) file for details.
1027
+
1028
+ ---
1029
+
1030
+ **o7**