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