@internetdata/internetdata 2.8.1 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,13 +1,21 @@
1
1
  import type { Writable } from 'node:stream';
2
2
  import type { Client } from './generated/client/index.js';
3
+ import type { Entitlement } from './generated/types.gen.js';
4
+ import { InternetDataError } from './errors.js';
3
5
  import { OauthApi } from './oauth.js';
4
- import type { Database, DatabaseFormat, DatabaseMetadata, DbChecksums, Download } from './types.js';
6
+ import type { AsnResult, Database, DatabaseFormat, DatabaseMetadata, DbChecksums, DomainResult, Download, Result } from './types.js';
5
7
  /**
6
8
  * Where `download` puts the bytes: a path to write, or a stream you opened
7
9
  * yourself and will close yourself.
8
10
  */
9
11
  export type DownloadDestination = string | Writable;
10
- export declare const DEFAULT_BASE_URL = "https://internetdata.io";
12
+ export declare const DEFAULT_BASE_URL = "https://api.internetdata.io";
13
+ export interface CacheOptions {
14
+ /** Maximum number of addresses held. Default 10000. */
15
+ max?: number;
16
+ /** How long an answer stays fresh, in milliseconds. Default 1 hour. */
17
+ ttlMs?: number;
18
+ }
11
19
  export interface DownloadsOptions {
12
20
  /** How many attempts to return, newest first. The API clamps this to 200. */
13
21
  limit?: number;
@@ -42,12 +50,24 @@ export interface DownloadOptions {
42
50
  }
43
51
  export interface Options {
44
52
  /**
45
- * Your API key, carrying the `db.download` scope. Omit it to send no
46
- * `Authorization` header at all, which is what a dataset offered without a
47
- * license would be read with.
53
+ * Your API key. Without one a lookup is on Unlimited, the free plan, limited
54
+ * per address per minute, and no `Authorization` header is sent at all. The
55
+ * database calls need a key carrying the `db.download` scope. A batch needs
56
+ * a key on a paid plan.
48
57
  */
49
58
  apiKey?: string;
59
+ /**
60
+ * Default `https://api.internetdata.io`. The `oauth` calls go to the apex
61
+ * this names: `api.` dropped, and `api-<env>.` read as `<env>.`.
62
+ */
50
63
  baseUrl?: string;
64
+ /** Pass `false` to disable caching. */
65
+ cache?: CacheOptions | false;
66
+ /**
67
+ * Concurrent batch requests - chunks of up to 1000 addresses - during a
68
+ * batch, a whole number from 1. Default 8.
69
+ */
70
+ concurrency?: number;
51
71
  /** Retry attempts for a transient failure, a whole number from 0. Default 2. */
52
72
  retries?: number;
53
73
  /**
@@ -62,20 +82,36 @@ export interface Options {
62
82
  /** Override the HTTP implementation, mostly for tests. */
63
83
  fetch?: typeof globalThis.fetch;
64
84
  }
85
+ /** Per-call overrides for a single lookup. Anything omitted falls back to the client's setting. */
86
+ export interface LookupOptions {
87
+ /** Retry attempts for a transient failure, a whole number from 0. */
88
+ retries?: number;
89
+ /** How long one attempt may take before it is abandoned, in milliseconds. */
90
+ timeoutMs?: number;
91
+ }
92
+ /** Per-call overrides for one batch. Anything omitted falls back to the client's setting. */
93
+ export interface BatchOptions extends LookupOptions {
94
+ /** Concurrent batch requests for THIS batch only. */
95
+ concurrency?: number;
96
+ }
65
97
  /**
66
98
  * A client for the InternetData API.
67
99
  *
68
- * Everything the API answers is scoped to the organization the key belongs to,
69
- * including which databases are listed at all, so one client speaks for exactly
70
- * one organization and nothing it learns may be reused for another key.
100
+ * The cache is per instance, so an answer is never shared between two clients
101
+ * holding different API keys and therefore entitled to different fields.
71
102
  *
72
- * The key is optional, and an absent one sends no `Authorization` header rather
73
- * than an empty one. `oauth` needs none. Every database published today is
74
- * licensed, so a keyless `database` call is answered `401` for now; it exists
75
- * because what the API serves without a license is a product decision, not the
76
- * client's to refuse.
103
+ * Everything the database calls answer is scoped to the organization the key
104
+ * belongs to, including which databases are listed at all, so one client speaks
105
+ * for exactly one organization and nothing it learns may be reused for another
106
+ * key. The key is optional, and an absent one sends no `Authorization` header
107
+ * rather than an empty one. `oauth` needs none.
77
108
  */
78
109
  export declare class InternetData {
110
+ private readonly client;
111
+ private readonly cache;
112
+ private readonly limit;
113
+ private readonly retries;
114
+ private readonly timeoutMs;
79
115
  /** The database catalog, downloads and their history. */
80
116
  readonly database: DatabaseApi;
81
117
  /**
@@ -84,6 +120,107 @@ export declare class InternetData {
84
120
  */
85
121
  readonly oauth: OauthApi;
86
122
  constructor(options?: Options);
123
+ /**
124
+ * Whether an address is private, loopback, link-local, documentation,
125
+ * multicast or otherwise not routable, including the IPv6 equivalents and
126
+ * the 6to4 and Teredo ranges.
127
+ *
128
+ * These are the addresses `lookup` answers locally. Exposed here so the
129
+ * check is reachable from the client you already hold; the same function is
130
+ * also importable on its own.
131
+ */
132
+ isBogon(ip: string): boolean;
133
+ /**
134
+ * What every database says about one address.
135
+ *
136
+ * A bogon is answered locally and never reaches the network. Everything
137
+ * else is served, then cached for this instance. Calls that miss the cache
138
+ * while a request for their address is in flight, a batch's included, await
139
+ * that request rather than sending their own, and take its answer, sent
140
+ * under the options of the call that led it. An IPv4-mapped address
141
+ * (`::ffff:8.8.8.8`) is the IPv4 address it carries: judged, sent and cached
142
+ * as that, so the answer names `8.8.8.8`. Anything that is not an IP address
143
+ * is refused as `bad_request` before it is sent: an AS is `lookupAsn`'s, and
144
+ * a domain `lookupDomain`'s.
145
+ */
146
+ lookup(ip: string, options?: LookupOptions): Promise<Result>;
147
+ private serve;
148
+ /**
149
+ * What the databases say about the address this client is calling from.
150
+ *
151
+ * The same answer `lookup` would give for that address, at the same cost
152
+ * against your allowance. The address is the one our edge observed, so a
153
+ * call made through a proxy or a VPN reports the exit it left through -
154
+ * usually the point of asking.
155
+ *
156
+ * Deliberately NOT cached. The cache is keyed by address, and which
157
+ * address this is IS the question: a machine that moves between networks
158
+ * would otherwise be told where it used to be.
159
+ */
160
+ myIp(options?: LookupOptions): Promise<Result>;
161
+ /**
162
+ * What InternetData knows about one autonomous system, by its number: its
163
+ * registration on every plan, and on a paid one its ASN Whois record and
164
+ * every prefix it announces.
165
+ *
166
+ * Sent as given and not cached. The API refuses a number it cannot read as
167
+ * `bad_request`.
168
+ */
169
+ lookupAsn(asn: number, options?: LookupOptions): Promise<AsnResult>;
170
+ /**
171
+ * What InternetData knows about one domain: on every plan whether it is
172
+ * registered and which DNS record types it has, and on a paid one the
173
+ * records themselves, its organization's IP ranges and whether it is a
174
+ * disposable email domain.
175
+ *
176
+ * Sent as given and not cached. The API refuses a name it cannot read as
177
+ * `bad_request`.
178
+ */
179
+ lookupDomain(domain: string, options?: LookupOptions): Promise<DomainResult>;
180
+ /**
181
+ * What this client's key is entitled to, and how much of it has been used.
182
+ *
183
+ * Named for what it answers rather than `me`, which sits one letter from
184
+ * `myIp` and means something quite different: one is which address you are
185
+ * calling FROM, the other is what the key you are calling WITH may spend.
186
+ *
187
+ * Unlike a lookup there is no useful unauthenticated answer, so a client
188
+ * built without a key gets an unauthorized error rather than a partial one.
189
+ *
190
+ * Usage counts against the ALLOWANCE WINDOW - on a paid plan the
191
+ * anniversary of the subscription, not the calendar month and not the
192
+ * billing period, and on the free plan the UTC day - and it is the same
193
+ * number a lookup is gated on. It can lag by a few seconds, because
194
+ * requests are counted in memory and flushed in aggregate.
195
+ *
196
+ * Deliberately NOT cached: the whole point is what has been spent, and a
197
+ * cached answer is a wrong one within seconds of the next request.
198
+ */
199
+ myEntitlement(options?: LookupOptions): Promise<Entitlement>;
200
+ /**
201
+ * Look many addresses up in as few requests as possible.
202
+ *
203
+ * Bogons are answered locally and cached answers are reused, and an address
204
+ * with a request already in flight, a lookup's or another batch's, awaits
205
+ * that request; everything else goes to the batch endpoint in chunks of up
206
+ * to 1000 addresses, with at most `concurrency` chunks in flight, and a
207
+ * lookup arriving meanwhile awaits this batch's answer for its address.
208
+ * Keyed by address rather than positional, so duplicates in the input
209
+ * collapse to a single entry and the caller never has to line two lists up.
210
+ * An address that fails carries its error as its value, so one bad entry
211
+ * cannot lose the rest of the answers: the API reports a per-entry failure
212
+ * with the status the single lookup would have answered, and a chunk that
213
+ * fails as a whole marks every address in it. A per-call `concurrency` that
214
+ * is not a whole number from 1 is refused as `bad_request` before anything
215
+ * is sent. An IPv4-mapped address is looked up as the IPv4 address it
216
+ * carries, and its answer keyed as you passed it. The batch endpoint needs
217
+ * a paid plan: without a key every address in a request of two or more
218
+ * carries an `unauthorized` error, and a free-plan key's request of two or
219
+ * more a `bad_request` (HTTP 402). A request of one address is answered as
220
+ * its lookup would be.
221
+ */
222
+ lookupBatch(ips: Iterable<string>, options?: BatchOptions): Promise<Map<string, Result | InternetDataError>>;
223
+ private lookupChunk;
87
224
  }
88
225
  /** The licensed database downloads. Access is granted by contract, not self-serve. */
89
226
  export declare class DatabaseApi {
package/dist/client.js CHANGED
@@ -1,29 +1,42 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import pLimit from 'p-limit';
1
3
  import { createClient, createConfig } from './generated/client/index.js';
2
- import { databaseChecksumV2, databaseMetadataV2, downloadDatabaseV2 as downloadRedirect, listDatabases, listDownloads, } from './generated/sdk.gen.js';
3
- import { errorFromResponse, InternetDataError } from './errors.js';
4
+ import { databaseChecksumV2, databaseMetadataV2, downloadDatabaseV2 as downloadRedirect, listDatabases, listDownloads, lookupAsn, lookupBatch, lookupDomain, lookupIp, lookupMyIp, myEntitlement, } from './generated/sdk.gen.js';
5
+ import { bogonResult, isAddress, isBogon, unmapped } from './bogon.js';
6
+ import { errorFromEntry, errorFromResponse, InternetDataError } from './errors.js';
4
7
  import { OauthApi } from './oauth.js';
5
- import { isChecksumsResponse, isDatabaseList, isDatabaseMetadata, isDownloadList, } from './shapes.js';
6
- import { checkTimeout, deadline, readable, unwrap, withRetry } from './transport.js';
7
- import { DATABASE_FORMATS } from './types.js';
8
- export const DEFAULT_BASE_URL = 'https://internetdata.io';
8
+ import { isAsnLookup, isBatch, isBatchError, isChecksumsResponse, isDatabaseList, isDatabaseMetadata, isDomainLookup, isDownloadList, isEntitlement, isLookup, } from './shapes.js';
9
+ import { asError, checkConcurrency, checkRetries, checkTimeout, deadline, readable, unwrap, withRetry, } from './transport.js';
10
+ import { DATABASE_FORMATS, toAsnResult, toDomainResult, toResult } from './types.js';
11
+ export const DEFAULT_BASE_URL = 'https://api.internetdata.io';
9
12
  // Matches the other SDKs, whose HTTP clients default to 30s. Node's global
10
13
  // fetch has no whole-request limit of its own, so without this a hung API holds
11
14
  // a caller until undici's 300s headers timeout.
12
15
  const DEFAULT_TIMEOUT_MS = 30_000;
16
+ // The most addresses POST /batch takes in one call; a larger batch is sent in
17
+ // chunks of this size.
18
+ const BATCH_MAX = 1000;
13
19
  /**
14
20
  * A client for the InternetData API.
15
21
  *
16
- * Everything the API answers is scoped to the organization the key belongs to,
17
- * including which databases are listed at all, so one client speaks for exactly
18
- * one organization and nothing it learns may be reused for another key.
22
+ * The cache is per instance, so an answer is never shared between two clients
23
+ * holding different API keys and therefore entitled to different fields.
19
24
  *
20
- * The key is optional, and an absent one sends no `Authorization` header rather
21
- * than an empty one. `oauth` needs none. Every database published today is
22
- * licensed, so a keyless `database` call is answered `401` for now; it exists
23
- * because what the API serves without a license is a product decision, not the
24
- * client's to refuse.
25
+ * Everything the database calls answer is scoped to the organization the key
26
+ * belongs to, including which databases are listed at all, so one client speaks
27
+ * for exactly one organization and nothing it learns may be reused for another
28
+ * key. The key is optional, and an absent one sends no `Authorization` header
29
+ * rather than an empty one. `oauth` needs none.
25
30
  */
26
31
  export class InternetData {
32
+ client;
33
+ // Keyed by address. The context is how a call sends the request when the
34
+ // address has none in flight: `fetch()` runs it synchronously, so a batch
35
+ // knows which addresses it leads before it builds a chunk.
36
+ cache;
37
+ limit;
38
+ retries;
39
+ timeoutMs;
27
40
  /** The database catalog, downloads and their history. */
28
41
  database;
29
42
  /**
@@ -37,18 +50,320 @@ export class InternetData {
37
50
  // the same implementation a test substituted.
38
51
  const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
39
52
  const apiKey = checkApiKey(options.apiKey);
40
- const client = createClient(createConfig({
41
- // Every path appended starts with a slash, and a second one is another
42
- // path, which the API answers with a redirect.
43
- baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ''),
53
+ // Every path appended starts with a slash, and a second one is another
54
+ // path, which the API answers with a redirect.
55
+ const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
56
+ this.client = createClient(createConfig({
57
+ baseUrl: baseUrl,
44
58
  ...(apiKey === undefined ? {} : { auth: bearerOnly(apiKey) }),
45
59
  fetch: fetchImpl,
46
60
  }));
47
- const retries = checkRetries(options.retries ?? 2);
48
- const timeoutMs = checkTimeout(options.timeoutMs) ?? DEFAULT_TIMEOUT_MS;
49
- this.database = new DatabaseApi(client, retries, timeoutMs, fetchImpl);
50
- this.oauth = new OauthApi(client, retries, timeoutMs);
61
+ this.cache = options.cache === false ? null : new LRUCache({
62
+ max: options.cache?.max ?? 10_000,
63
+ ttl: options.cache?.ttlMs ?? 60 * 60 * 1000,
64
+ // Concurrent misses for one address share one request: every
65
+ // `fetch()` while it is in flight gets the same promise, and a
66
+ // failure rejects them all and is cached for none.
67
+ fetchMethod: (_ip, _stale, { context }) => context(),
68
+ // An eviction must not fail the callers awaiting a request.
69
+ ignoreFetchAbort: true,
70
+ });
71
+ this.limit = pLimit(checkConcurrency(options.concurrency) ?? 8);
72
+ this.retries = checkRetries(options.retries) ?? 2;
73
+ this.timeoutMs = checkTimeout(options.timeoutMs) ?? DEFAULT_TIMEOUT_MS;
74
+ this.database = new DatabaseApi(this.client, this.retries, this.timeoutMs, fetchImpl);
75
+ // The authorization server is the apex, not the API host, and its
76
+ // requests carry no credential at all.
77
+ const authServer = createClient(createConfig({ baseUrl: apexOf(baseUrl), fetch: fetchImpl }));
78
+ this.oauth = new OauthApi(authServer, this.retries, this.timeoutMs);
79
+ }
80
+ /**
81
+ * Whether an address is private, loopback, link-local, documentation,
82
+ * multicast or otherwise not routable, including the IPv6 equivalents and
83
+ * the 6to4 and Teredo ranges.
84
+ *
85
+ * These are the addresses `lookup` answers locally. Exposed here so the
86
+ * check is reachable from the client you already hold; the same function is
87
+ * also importable on its own.
88
+ */
89
+ isBogon(ip) {
90
+ return isBogon(ip);
91
+ }
92
+ /**
93
+ * What every database says about one address.
94
+ *
95
+ * A bogon is answered locally and never reaches the network. Everything
96
+ * else is served, then cached for this instance. Calls that miss the cache
97
+ * while a request for their address is in flight, a batch's included, await
98
+ * that request rather than sending their own, and take its answer, sent
99
+ * under the options of the call that led it. An IPv4-mapped address
100
+ * (`::ffff:8.8.8.8`) is the IPv4 address it carries: judged, sent and cached
101
+ * as that, so the answer names `8.8.8.8`. Anything that is not an IP address
102
+ * is refused as `bad_request` before it is sent: an AS is `lookupAsn`'s, and
103
+ * a domain `lookupDomain`'s.
104
+ */
105
+ async lookup(ip, options = {}) {
106
+ // First, or a bogon and a cached address would answer any value.
107
+ checkTimeout(options.timeoutMs);
108
+ checkRetries(options.retries);
109
+ // The API answers an AS or a domain at this path too, in a shape this
110
+ // call cannot read, so one sent here failed as three retried server errors.
111
+ if (typeof ip !== 'string' || !isAddress(unmapped(ip))) {
112
+ throw new InternetDataError('bad_request', `'${String(ip)}' is not an IP address: `
113
+ + 'look up an AS with lookupAsn, and a domain with lookupDomain');
114
+ }
115
+ const addr = unmapped(ip);
116
+ if (isBogon(addr)) {
117
+ return bogonResult(addr);
118
+ }
119
+ if (this.cache === null) {
120
+ return this.serve(addr, options);
121
+ }
122
+ return (await this.cache.fetch(addr, { context: () => this.serve(addr, options) }));
123
+ }
124
+ async serve(ip, options) {
125
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
126
+ return withRetry(options.retries ?? this.retries, async () => {
127
+ const res = await deadline(timeoutMs, (signal) => lookupIp({
128
+ client: this.client, path: { ip: ip }, signal: signal,
129
+ }));
130
+ return toResult(readable(res, isLookup));
131
+ });
132
+ }
133
+ /**
134
+ * What the databases say about the address this client is calling from.
135
+ *
136
+ * The same answer `lookup` would give for that address, at the same cost
137
+ * against your allowance. The address is the one our edge observed, so a
138
+ * call made through a proxy or a VPN reports the exit it left through -
139
+ * usually the point of asking.
140
+ *
141
+ * Deliberately NOT cached. The cache is keyed by address, and which
142
+ * address this is IS the question: a machine that moves between networks
143
+ * would otherwise be told where it used to be.
144
+ */
145
+ async myIp(options = {}) {
146
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
147
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
148
+ const res = await deadline(timeoutMs, (signal) => lookupMyIp({
149
+ client: this.client, signal: signal,
150
+ }));
151
+ return toResult(readable(res, isLookup));
152
+ });
153
+ }
154
+ /**
155
+ * What InternetData knows about one autonomous system, by its number: its
156
+ * registration on every plan, and on a paid one its ASN Whois record and
157
+ * every prefix it announces.
158
+ *
159
+ * Sent as given and not cached. The API refuses a number it cannot read as
160
+ * `bad_request`.
161
+ */
162
+ async lookupAsn(asn, options = {}) {
163
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
164
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
165
+ const res = await deadline(timeoutMs, (signal) => lookupAsn({
166
+ client: this.client, path: { asn: String(asn) }, signal: signal,
167
+ }));
168
+ return toAsnResult(readable(res, isAsnLookup));
169
+ });
170
+ }
171
+ /**
172
+ * What InternetData knows about one domain: on every plan whether it is
173
+ * registered and which DNS record types it has, and on a paid one the
174
+ * records themselves, its organization's IP ranges and whether it is a
175
+ * disposable email domain.
176
+ *
177
+ * Sent as given and not cached. The API refuses a name it cannot read as
178
+ * `bad_request`.
179
+ */
180
+ async lookupDomain(domain, options = {}) {
181
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
182
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
183
+ const res = await deadline(timeoutMs, (signal) => lookupDomain({
184
+ client: this.client, path: { domain: domain }, signal: signal,
185
+ }));
186
+ return toDomainResult(readable(res, isDomainLookup));
187
+ });
188
+ }
189
+ /**
190
+ * What this client's key is entitled to, and how much of it has been used.
191
+ *
192
+ * Named for what it answers rather than `me`, which sits one letter from
193
+ * `myIp` and means something quite different: one is which address you are
194
+ * calling FROM, the other is what the key you are calling WITH may spend.
195
+ *
196
+ * Unlike a lookup there is no useful unauthenticated answer, so a client
197
+ * built without a key gets an unauthorized error rather than a partial one.
198
+ *
199
+ * Usage counts against the ALLOWANCE WINDOW - on a paid plan the
200
+ * anniversary of the subscription, not the calendar month and not the
201
+ * billing period, and on the free plan the UTC day - and it is the same
202
+ * number a lookup is gated on. It can lag by a few seconds, because
203
+ * requests are counted in memory and flushed in aggregate.
204
+ *
205
+ * Deliberately NOT cached: the whole point is what has been spent, and a
206
+ * cached answer is a wrong one within seconds of the next request.
207
+ */
208
+ async myEntitlement(options = {}) {
209
+ const timeoutMs = checkTimeout(options.timeoutMs) ?? this.timeoutMs;
210
+ return withRetry(checkRetries(options.retries) ?? this.retries, async () => {
211
+ const res = await deadline(timeoutMs, (signal) => myEntitlement({
212
+ client: this.client, signal: signal,
213
+ }));
214
+ return readable(res, isEntitlement);
215
+ });
51
216
  }
217
+ /**
218
+ * Look many addresses up in as few requests as possible.
219
+ *
220
+ * Bogons are answered locally and cached answers are reused, and an address
221
+ * with a request already in flight, a lookup's or another batch's, awaits
222
+ * that request; everything else goes to the batch endpoint in chunks of up
223
+ * to 1000 addresses, with at most `concurrency` chunks in flight, and a
224
+ * lookup arriving meanwhile awaits this batch's answer for its address.
225
+ * Keyed by address rather than positional, so duplicates in the input
226
+ * collapse to a single entry and the caller never has to line two lists up.
227
+ * An address that fails carries its error as its value, so one bad entry
228
+ * cannot lose the rest of the answers: the API reports a per-entry failure
229
+ * with the status the single lookup would have answered, and a chunk that
230
+ * fails as a whole marks every address in it. A per-call `concurrency` that
231
+ * is not a whole number from 1 is refused as `bad_request` before anything
232
+ * is sent. An IPv4-mapped address is looked up as the IPv4 address it
233
+ * carries, and its answer keyed as you passed it. The batch endpoint needs
234
+ * a paid plan: without a key every address in a request of two or more
235
+ * carries an `unauthorized` error, and a free-plan key's request of two or
236
+ * more a `bad_request` (HTTP 402). A request of one address is answered as
237
+ * its lookup would be.
238
+ */
239
+ async lookupBatch(ips, options = {}) {
240
+ const concurrency = checkConcurrency(options.concurrency);
241
+ checkTimeout(options.timeoutMs);
242
+ checkRetries(options.retries);
243
+ const asked = [...new Set(ips)];
244
+ const unique = [...new Set(asked.map(unmapped))];
245
+ const out = new Map();
246
+ const pending = [];
247
+ // Every address that is neither a bogon nor cached goes through
248
+ // `fetch()` in one synchronous pass: one with a request in flight joins
249
+ // it, and for the rest `fetchMethod` runs at once, which is how this
250
+ // batch learns the addresses it leads before building any chunk.
251
+ const shared = [];
252
+ const led = new Map();
253
+ for (const ip of unique) {
254
+ if (isBogon(ip)) {
255
+ out.set(ip, bogonResult(ip));
256
+ continue;
257
+ }
258
+ const hit = this.cache?.get(ip);
259
+ if (hit !== undefined) {
260
+ out.set(ip, hit);
261
+ continue;
262
+ }
263
+ if (this.cache === null) {
264
+ pending.push(ip);
265
+ continue;
266
+ }
267
+ shared.push([ip, this.cache.fetch(ip, {
268
+ context: () => {
269
+ const landing = Promise.withResolvers();
270
+ led.set(ip, landing);
271
+ pending.push(ip);
272
+ return landing.promise;
273
+ },
274
+ })]);
275
+ }
276
+ // A per-call concurrency gets its own limiter; without one the call
277
+ // would share the instance's budget and silently ignore the override.
278
+ const limit = concurrency === undefined ? this.limit : pLimit(concurrency);
279
+ const chunks = [];
280
+ for (let i = 0; i < pending.length; i += BATCH_MAX) {
281
+ chunks.push(pending.slice(i, i + BATCH_MAX));
282
+ }
283
+ await Promise.all([
284
+ ...chunks.map((chunk) => limit(async () => {
285
+ for (const [ip, answer] of await this.lookupChunk(chunk, options)) {
286
+ const landing = led.get(ip);
287
+ if (landing === undefined) {
288
+ out.set(ip, answer);
289
+ }
290
+ else if (answer instanceof InternetDataError) {
291
+ landing.reject(answer);
292
+ }
293
+ else {
294
+ landing.resolve(answer);
295
+ }
296
+ }
297
+ })),
298
+ ...shared.map(async ([ip, answer]) => {
299
+ try {
300
+ out.set(ip, (await answer));
301
+ }
302
+ catch (err) {
303
+ out.set(ip, asError(err));
304
+ }
305
+ }),
306
+ ]);
307
+ // Reinstated in input order, under the addresses as passed: chunks
308
+ // settle in completion order, and a caller iterating the map should see
309
+ // what they passed in.
310
+ return new Map(asked.map((ip) => [ip, out.get(unmapped(ip))]));
311
+ }
312
+ // One POST /batch, mapped back onto the addresses it was asked about. A
313
+ // chunk-level failure - the call refused, the transport failing, the
314
+ // retries exhausted - becomes every address's error, exactly as it would
315
+ // have been had each been looked up alone.
316
+ async lookupChunk(chunk, options) {
317
+ const out = new Map();
318
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
319
+ let body;
320
+ try {
321
+ body = await withRetry(options.retries ?? this.retries, async () => {
322
+ const res = await deadline(timeoutMs, (signal) => lookupBatch({
323
+ client: this.client, body: { ips: chunk }, signal: signal,
324
+ }));
325
+ return readable(res, isBatch);
326
+ });
327
+ }
328
+ catch (err) {
329
+ const failure = asError(err);
330
+ for (const ip of chunk) {
331
+ out.set(ip, failure);
332
+ }
333
+ return out;
334
+ }
335
+ // An entry is judged alone: one the client cannot read is that address's
336
+ // error, and the rest of the chunk keeps its answers. Each map is read by
337
+ // its own keys alone, so `__proto__`, `constructor` and `toString` never
338
+ // read the object's prototype as a served answer.
339
+ for (const ip of chunk) {
340
+ const served = Object.hasOwn(body.results, ip) ? body.results[ip] : undefined;
341
+ if (served !== undefined) {
342
+ // Cached by the `fetch()` this batch leads it through.
343
+ out.set(ip, isLookup(served) ? toResult(served) : unreadableEntry(ip));
344
+ continue;
345
+ }
346
+ const failed = Object.hasOwn(body.errors, ip) ? body.errors[ip] : undefined;
347
+ if (failed !== undefined) {
348
+ out.set(ip, isBatchError(failed) ? errorFromEntry(failed) : unreadableEntry(ip));
349
+ continue;
350
+ }
351
+ out.set(ip, new InternetDataError('server_error', `the batch answer did not include ${ip}`, 200));
352
+ }
353
+ return out;
354
+ }
355
+ }
356
+ /**
357
+ * The host the `oauth` calls go to: the apex, since the authorization server is
358
+ * mounted there and not on the API host. `https://api.internetdata.io` is
359
+ * `https://internetdata.io` and `https://api-<env>.internetdata.io` is
360
+ * `https://<env>.internetdata.io`; any other base URL is used as given.
361
+ */
362
+ function apexOf(baseUrl) {
363
+ return baseUrl.replace(/^(https?:\/\/)api(?:-([^./:@]+))?\./i, (_, scheme, env) => (env === undefined ? scheme : `${scheme}${env}.`));
364
+ }
365
+ function unreadableEntry(ip) {
366
+ return new InternetDataError('server_error', `unreadable batch answer for ${ip}, status 200`, 200);
52
367
  }
53
368
  /** The licensed database downloads. Access is granted by contract, not self-serve. */
54
369
  export class DatabaseApi {
@@ -258,10 +573,11 @@ function checkBuild(build) {
258
573
  * The key without the blanks around it, and no key at all for blanks alone,
259
574
  * which went out as `Authorization: Bearer` (2.5.1, measured 2026-10-10). A
260
575
  * control character inside it is refused here: fetch refuses such a header, so
261
- * every call failed as a retried `network` error with nothing sent.
576
+ * every call failed as a retried `network` error with nothing sent. `null` is no
577
+ * key.
262
578
  */
263
579
  function checkApiKey(apiKey) {
264
- if (apiKey === undefined) {
580
+ if (apiKey === undefined || apiKey === null) {
265
581
  return undefined;
266
582
  }
267
583
  if (typeof apiKey !== 'string') {
@@ -278,18 +594,6 @@ function checkApiKey(apiKey) {
278
594
  }
279
595
  return key === '' ? undefined : key;
280
596
  }
281
- /**
282
- * A retry count p-retry can run, refused where it is set: through 2.7.3 a negative,
283
- * NaN or non-number failed every call with p-retry's own TypeError as a `network`
284
- * error, and a fraction ended a failing call as one too (measured 2026-10-23).
285
- * `Infinity` is p-retry's own unbounded count.
286
- */
287
- function checkRetries(retries) {
288
- if (typeof retries === 'number' && (Number.isInteger(retries) || retries === Infinity) && retries >= 0) {
289
- return retries;
290
- }
291
- throw new InternetDataError('bad_request', `retries must be a whole number from 0, got ${String(retries)}`);
292
- }
293
597
  /**
294
598
  * Sends the key in the `Authorization` header and nowhere else.
295
599
  *