clearpostcode 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ClearPostcode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,208 @@
1
- # Temporary Holding Version
1
+ # clearpostcode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Every UK postcode, answered in milliseconds: look up, validate and autocomplete postcodes, with the council, ward,
4
+ constituency, coordinates, police force, NHS area and deprivation decile behind each one. Find the nearest postcodes,
5
+ reverse geocode a point, measure distances, list a district, search places, and look up full Royal Mail addresses.
6
+
7
+ - **Typed end to end:** every answer and every error is typed, generated from the API's OpenAPI document.
8
+ - **Built for production:** automatic retries with backoff that honour `Retry-After` and the rate-limit headers,
9
+ timeouts, cancellation, cursor pagination and bulk calls of any size.
10
+ - **Runs anywhere:** Node 20+, Bun, Deno, Cloudflare Workers and browsers. ESM and CommonJS. No dependencies.
11
+ - **Free to start:** 10,000 postcode lookups a month on a free key, no card, and many calls work with no key at all.
12
+
13
+ Two products, one key: **Postcode data** (every UK postcode and its areas, from open data) and **Address lookup**
14
+ (every address at a postcode, from Royal Mail PAF).
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install clearpostcode
20
+ ```
21
+
22
+ ## Quickstart
23
+
24
+ Runs as printed, with or without a key. The client reads your key from `CLEAR_POSTCODE_KEY` when it is set; without
25
+ one, calls run on the free keyless allowance.
26
+
27
+ ```js
28
+ import { ClearPostcode } from "clearpostcode";
29
+
30
+ const cp = new ClearPostcode();
31
+
32
+ const { data } = await cp.postcodes.lookup("SW1A 1AA");
33
+ console.log(data.local_authority?.name, data.constituency?.name);
34
+ // Westminster Cities of London and Westminster
35
+
36
+ const { data: check } = await cp.postcodes.validate("m1 1ae");
37
+ console.log(check.valid, check.postcode); // true M1 1AE
38
+
39
+ const { data: suggestions } = await cp.postcodes.autocomplete("SW1A 1");
40
+ console.log(suggestions.length > 0); // true
41
+ ```
42
+
43
+ Get a free key in under a minute at [clearpostcode.co.uk/developers](https://clearpostcode.co.uk/developers#key).
44
+ Secret keys (`cp_live_`) are for servers; publishable keys (`cp_pub_`) are locked to your domains and safe in a
45
+ browser.
46
+
47
+ ```sh
48
+ export CLEAR_POSTCODE_KEY=cp_live_...
49
+ ```
50
+
51
+ ## What you can call
52
+
53
+ | Call | What it answers |
54
+ |---|---|
55
+ | `postcodes.lookup(postcode, { fields })` | The full record: status, coordinates, council, ward, constituency and every other area |
56
+ | `postcodes.validate(postcode)` | Is the format valid, is it in the current edition, is it live |
57
+ | `postcodes.autocomplete(q, { limit })` | Postcodes (or districts) that start with what was typed. Free |
58
+ | `postcodes.nearest(postcode, { radius, limit })` | Live postcodes nearest a postcode, with distances |
59
+ | `postcodes.reverse({ latitude, longitude, radius, limit })` | Live postcodes nearest a point |
60
+ | `postcodes.distance(from, to)` | Kilometres, miles and the bearing between two postcodes |
61
+ | `postcodes.bulk(postcodes, { fields })` | Any number of postcodes, sent 100 a call. Secret key |
62
+ | `postcodes.bulkReverse(points)` | Nearest postcodes for any number of points, 20 a call. Secret key |
63
+ | `outcodes.get(outcode)` | A district: counts, sectors, centre, councils, wards, places |
64
+ | `outcodes.postcodes(outcode)` / `outcodes.allPostcodes(outcode)` | Every live postcode in a district, by page or all of them. Secret key |
65
+ | `sectors.get(sector)` · `areas.get(area)` | A sector or an area |
66
+ | `places.search(q)` | Cities, towns, villages and neighbourhoods by name |
67
+ | `account.usage()` | Your plan, allowance, lookups used and reset date. Secret key |
68
+ | `addresses.suggest`, `retrieve`, `byPostcode`, `allByPostcode`, `byUdprn` | Address lookup (below) |
69
+
70
+ Every call answers a `Result`: `data` and `meta` as the API sends them, plus `status`, `requestId` and `rateLimit`
71
+ (`policy`, `limit`, `remaining`, `reset`). API parameters come first, then request options (`signal`, `timeout`,
72
+ `maxRetries`): `cp.postcodes.nearest("SW1A 1AA", { limit: 5 }, { timeout: 2_000 })`. Every field is documented at
73
+ [clearpostcode.co.uk/developers/docs](https://clearpostcode.co.uk/developers/docs).
74
+
75
+ Ask only for the fields you need, and the types follow:
76
+
77
+ ```js
78
+ import { ClearPostcode } from "clearpostcode";
79
+
80
+ const cp = new ClearPostcode();
81
+ const { data } = await cp.postcodes.lookup("EH1 1YZ", { fields: ["location", "ward"] });
82
+ console.log(data.postcode, data.ward?.name, data.location.latitude); // EH1 1YZ City Centre 55.950328
83
+ ```
84
+
85
+ ## Errors
86
+
87
+ Every error is a `ClearPostcodeError`. When the API answers with an error, you get an `APIError` subclass carrying
88
+ the problem's `code`, `detail`, `status` and the `requestId` to quote to support:
89
+
90
+ ```js
91
+ import { ClearPostcode, NotFoundError } from "clearpostcode";
92
+
93
+ const cp = new ClearPostcode();
94
+ try {
95
+ await cp.postcodes.lookup("SW1A 9ZZ");
96
+ } catch (err) {
97
+ if (!(err instanceof NotFoundError)) throw err;
98
+ console.log(err.code); // postcode_not_found
99
+ }
100
+ ```
101
+
102
+ | Class | Status | Codes |
103
+ |---|---|---|
104
+ | `BadRequestError` | 400, 413 | `invalid_postcode`, `unknown_parameter`, `bad_request`, `secret_key_in_url`, `body_too_large` |
105
+ | `AuthenticationError` | 401 | `invalid_key`, `key_required` |
106
+ | `QuotaExceededError` | 402 | `quota_exceeded`, `address_credits_exhausted` |
107
+ | `PermissionDeniedError` | 403 | `origin_not_allowed`, `publishable_key_not_allowed`, `secret_key_in_browser`, `address_lookup_not_enabled` |
108
+ | `NotFoundError` | 404 | `postcode_not_found`, `not_covered`, `not_found` |
109
+ | `UnprocessableEntityError` | 422 | `no_position` |
110
+ | `RateLimitError` | 429 | `rate_limited`, `daily_cap_reached`, `suggestions_capped` |
111
+ | `InternalServerError` | 5xx | `server_error`, `service_unavailable` |
112
+ | `APIConnectionError`, `APITimeoutError` | | The API could not be reached, or did not answer in time |
113
+
114
+ ## Retries, timeouts and cancellation
115
+
116
+ 429s, 5xx answers, timeouts and dropped connections are retried twice by default, with exponential backoff and
117
+ jitter. A `Retry-After` from the API is honoured exactly, and a 429 without one waits for the `RateLimit` reset. A
118
+ wait longer than `maxRetryDelay` (a key's daily cap until midnight, say) is thrown to you at once, with `retryAfter`
119
+ in seconds.
120
+
121
+ ```js
122
+ import { ClearPostcode } from "clearpostcode";
123
+
124
+ const cp = new ClearPostcode({ timeout: 5_000, maxRetries: 3 });
125
+ const { data, rateLimit } = await cp.postcodes.validate("SW1A 1AA", { signal: AbortSignal.timeout(8_000) });
126
+ console.log(data.valid, rateLimit !== null); // true true
127
+ ```
128
+
129
+ ## Pages and bulk calls
130
+
131
+ ```js secret
132
+ import { ClearPostcode } from "clearpostcode";
133
+
134
+ const cp = new ClearPostcode(); // a secret key in CLEAR_POSTCODE_KEY
135
+
136
+ let count = 0;
137
+ for await (const pc of cp.outcodes.allPostcodes("SW1A")) count++;
138
+ console.log(count > 100); // true: every live postcode in SW1A, page after page
139
+
140
+ const { data, meta } = await cp.postcodes.bulk(["SW1A 1AA", "M1 1AE", "EH1 1YZ"], { fields: ["local_authority"] });
141
+ console.log(meta?.found, data[1]?.result?.local_authority?.name); // 3 Manchester
142
+ ```
143
+
144
+ Bulk calls take lists of any length: the client sends 100 postcodes (or 20 points) a call, one after another, and
145
+ joins the answers in the order you sent them. If a chunk fails part-way (the month's lookups run out, say), the error
146
+ carries `partial`: everything the chunks before it answered, so nothing you paid for is lost. Bulk calls are retried
147
+ only on answers that say nothing was billed (429 and 503).
148
+
149
+ ## In the browser
150
+
151
+ `clearpostcode/browser` takes a publishable key (or none), refuses a secret key before any call, sends the key in the
152
+ URL so there is no CORS preflight, and offers only the calls a browser may make.
153
+
154
+ ```js
155
+ import { ClearPostcode } from "clearpostcode/browser";
156
+
157
+ const cp = new ClearPostcode(); // or { key: "cp_pub_..." }: your publishable key, locked to your domain
158
+ const { data } = await cp.postcodes.autocomplete("M1 1");
159
+ console.log(data.length > 0); // true
160
+ ```
161
+
162
+ ## Address lookup
163
+
164
+ Full UK address lookup on Royal Mail's Postcode Address File: the customer types a postcode or the start of an
165
+ address, picks it from the list, and you save a clean Royal Mail address. It is in early access and switches on per
166
+ account: once the business your key serves has Address lookup switched on in your
167
+ [dashboard](https://clearpostcode.co.uk/dashboard#address-lookup), every call below answers. Until then they answer
168
+ `PermissionDeniedError` with code `address_lookup_not_enabled`. Join at
169
+ [clearpostcode.co.uk/address-lookup](https://clearpostcode.co.uk/address-lookup).
170
+
171
+ ```js secret
172
+ import { ClearPostcode } from "clearpostcode";
173
+
174
+ const cp = new ClearPostcode();
175
+
176
+ // Suggestions are free (within a daily allowance per business). Kind "container" lists what it holds.
177
+ const { data: found } = await cp.addresses.suggest("2 high street porthmore");
178
+ const first = found[0];
179
+ const pick = first?.kind === "container" ? (await cp.addresses.suggest("", { container: first.id })).data[0] : first;
180
+
181
+ // Resolving an address costs one address credit.
182
+ if (pick?.kind === "address") {
183
+ const { data: address } = await cp.addresses.retrieve(pick.id);
184
+ console.log(address.line_1, address.post_town, address.postcode);
185
+ }
186
+
187
+ // Every address at a postcode, 100 a page.
188
+ for await (const a of cp.addresses.allByPostcode("AB10 1AA")) console.log(a.udprn, a.line_1);
189
+ ```
190
+
191
+ ## CommonJS
192
+
193
+ ```js cjs
194
+ const { ClearPostcode } = require("clearpostcode");
195
+
196
+ new ClearPostcode().postcodes.lookup("M1 1AE").then(({ data }) => console.log(data.local_authority?.name)); // Manchester
197
+ ```
198
+
199
+ ## Plans
200
+
201
+ Free: 10,000 postcode lookups a month, no card. Not-found answers, autocomplete and address suggestions cost nothing.
202
+ More lookups and Address lookup: [clearpostcode.co.uk/pricing](https://clearpostcode.co.uk/pricing). What's new:
203
+ [CHANGELOG](https://github.com/clearpostcode/postcode-api/blob/main/CHANGELOG.md).
204
+
205
+ ## Licence
206
+
207
+ MIT. Postcode data: Contains OS data © Crown copyright and database right; Royal Mail data © Royal Mail copyright and
208
+ database right; Office for National Statistics data licensed under the Open Government Licence v3.0.
@@ -0,0 +1,28 @@
1
+ import type { Address, AddressMeta, AddressSuggestion } from "./generated.js";
2
+ import { type RequestOptions, type Result, Transport } from "./http.js";
3
+ import { type Page } from "./page.js";
4
+ export interface AddressSuggestParams {
5
+ /** A container suggestion's id: list the addresses (or smaller containers) it holds. */
6
+ container?: string;
7
+ /** How many suggestions (1 to 100, default 10). */
8
+ limit?: number;
9
+ }
10
+ export declare class Addresses {
11
+ #private;
12
+ constructor(transport: Transport);
13
+ /** One page of the addresses at a postcode, in delivery order (up to 100 a page; 1 address credit a page). */
14
+ byPostcode(postcode: string, params?: {
15
+ cursor?: string;
16
+ }, options?: RequestOptions): Promise<Page<Address, AddressMeta>>;
17
+ /** Every address at a postcode, page after page. */
18
+ allByPostcode(postcode: string, options?: RequestOptions): AsyncGenerator<Address>;
19
+ /**
20
+ * Suggestions as the customer types (free): kind "address" is one address (resolve its id with retrieve()), kind
21
+ * "container" is a postcode, street or building holding `count` addresses (pass its id as `container`).
22
+ */
23
+ suggest(q: string, params?: AddressSuggestParams, options?: RequestOptions): Promise<Result<AddressSuggestion[], AddressMeta>>;
24
+ /** The full address for an address suggestion's id (1 address credit). */
25
+ retrieve(id: string, options?: RequestOptions): Promise<Result<Address, AddressMeta>>;
26
+ /** The full address for a UDPRN, Royal Mail's number for one delivery point (1 address credit). */
27
+ byUdprn(udprn: string | number, options?: RequestOptions): Promise<Result<Address, AddressMeta>>;
28
+ }
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var addresses_exports = {};
20
+ __export(addresses_exports, {
21
+ Addresses: () => Addresses
22
+ });
23
+ module.exports = __toCommonJS(addresses_exports);
24
+ var import_http = require("./http.js");
25
+ var import_page = require("./page.js");
26
+ const ROUTES = {
27
+ byPostcode: { op: "addressesByPostcode", postcode: "postcode", cursor: "cursor" },
28
+ suggest: { op: "addressSuggest", q: "q", container: "container", limit: "limit" },
29
+ retrieve: { op: "addressRetrieve", id: "id" },
30
+ byUdprn: { op: "addressByUdprn", udprn: "udprn" }
31
+ };
32
+ class Addresses {
33
+ #t;
34
+ constructor(transport) {
35
+ this.#t = transport;
36
+ }
37
+ /** One page of the addresses at a postcode, in delivery order (up to 100 a page; 1 address credit a page). */
38
+ byPostcode(postcode, params = {}, options = {}) {
39
+ const r = ROUTES.byPostcode;
40
+ return (0, import_page.pageOf)(this.#t, r.op, { query: { [r.postcode]: postcode } }, r.cursor, params.cursor ?? null, options);
41
+ }
42
+ /** Every address at a postcode, page after page. */
43
+ allByPostcode(postcode, options = {}) {
44
+ return (0, import_page.every)(() => this.byPostcode(postcode, {}, options));
45
+ }
46
+ /**
47
+ * Suggestions as the customer types (free): kind "address" is one address (resolve its id with retrieve()), kind
48
+ * "container" is a postcode, street or building holding `count` addresses (pass its id as `container`).
49
+ */
50
+ suggest(q, params = {}, options = {}) {
51
+ const r = ROUTES.suggest;
52
+ return this.#t.request(r.op, { query: { [r.q]: q || void 0, [r.container]: params.container, [r.limit]: params.limit } }, options);
53
+ }
54
+ /** The full address for an address suggestion's id (1 address credit). */
55
+ retrieve(id, options = {}) {
56
+ const r = ROUTES.retrieve;
57
+ return this.#t.request(r.op, { path: { [r.id]: id } }, options);
58
+ }
59
+ /** The full address for a UDPRN, Royal Mail's number for one delivery point (1 address credit). */
60
+ byUdprn(udprn, options = {}) {
61
+ const r = ROUTES.byUdprn;
62
+ return this.#t.request(r.op, { path: { [r.udprn]: String(udprn) } }, options);
63
+ }
64
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * ClearPostcode for web pages: the same client, for publishable keys (cp_pub_, locked to your domains) or no key.
3
+ * It refuses a secret key before any call, sends the key as ?key= (no CORS preflight) and offers only the calls a
4
+ * browser may make. Docs: https://clearpostcode.co.uk/developers/docs
5
+ */
6
+ import { type ClientOptions, type Postcodes, type Outcodes, type Sectors, type Areas, type Places } from "./client.js";
7
+ import type { Addresses } from "./addresses.js";
8
+ export interface BrowserClientOptions extends Omit<ClientOptions, "key"> {
9
+ /** A publishable key (cp_pub_). Optional: postcode lookups, validation and autocomplete also work without one. */
10
+ key?: string | null;
11
+ }
12
+ /** The calls a publishable key or a keyless browser may make (bulk calls, every postcode in a district and usage
13
+ * need a secret key, so they stay on servers). */
14
+ export interface BrowserClient {
15
+ readonly postcodes: Omit<Postcodes, "bulk" | "bulkReverse">;
16
+ readonly outcodes: Pick<Outcodes, "get">;
17
+ readonly sectors: Sectors;
18
+ readonly areas: Areas;
19
+ readonly places: Places;
20
+ readonly addresses: Addresses;
21
+ }
22
+ /** The browser client. Throws ClearPostcodeError for anything but a publishable key, before any call. */
23
+ export declare class ClearPostcode implements BrowserClient {
24
+ readonly postcodes: BrowserClient["postcodes"];
25
+ readonly outcodes: BrowserClient["outcodes"];
26
+ readonly sectors: Sectors;
27
+ readonly areas: Areas;
28
+ readonly places: Places;
29
+ readonly addresses: Addresses;
30
+ constructor(options?: BrowserClientOptions);
31
+ }
32
+ export default ClearPostcode;
33
+ export { VERSION } from "./version.js";
34
+ export * from "./errors.js";
35
+ export type * from "./generated.js";
36
+ export { BASE_URL } from "./generated.js";
37
+ export type { PostcodeRecord, PostcodeField, PostcodeWith, Postcodes, Outcodes, Sectors, Areas, Places } from "./client.js";
38
+ export type { Addresses, AddressSuggestParams } from "./addresses.js";
39
+ export type { RateLimit, RequestOptions, Result } from "./http.js";
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var browser_exports = {};
21
+ __export(browser_exports, {
22
+ BASE_URL: () => import_generated.BASE_URL,
23
+ ClearPostcode: () => ClearPostcode,
24
+ VERSION: () => import_version.VERSION,
25
+ default: () => browser_default
26
+ });
27
+ module.exports = __toCommonJS(browser_exports);
28
+ var import_client = require("./client.js");
29
+ var import_errors = require("./errors.js");
30
+ var import_version = require("./version.js");
31
+ __reExport(browser_exports, require("./errors.js"), module.exports);
32
+ var import_generated = require("./generated.js");
33
+ class ClearPostcode {
34
+ postcodes;
35
+ outcodes;
36
+ sectors;
37
+ areas;
38
+ places;
39
+ addresses;
40
+ constructor(options = {}) {
41
+ const key = options.key || null;
42
+ if (key && !key.startsWith("cp_pub_")) {
43
+ throw new import_errors.ClearPostcodeError(key.startsWith("cp_live_") ? "Secret keys (cp_live_) stay on your server. In a browser, use a publishable key (cp_pub_) locked to your domain." : "Browser keys start cp_pub_. Copy your publishable key from your dashboard.");
44
+ }
45
+ const c = new import_client.Client((0, import_client.transportConfig)(options, key, { keyInQuery: true, headers: {} }));
46
+ this.postcodes = c.postcodes;
47
+ this.outcodes = c.outcodes;
48
+ this.sectors = c.sectors;
49
+ this.areas = c.areas;
50
+ this.places = c.places;
51
+ this.addresses = c.addresses;
52
+ }
53
+ }
54
+ var browser_default = ClearPostcode;
@@ -0,0 +1,146 @@
1
+ import { type Area, type BulkItem, type Distance, type District, type Meta, type Near, type OutcodePostcode, type Place, type Postcode, type ReverseItem, type Sector, type Suggestion, type Usage, type Validation } from "./generated.js";
2
+ import { type RateLimit, type RequestOptions, type Result, Transport, type TransportConfig } from "./http.js";
3
+ import { type Page } from "./page.js";
4
+ import { Addresses } from "./addresses.js";
5
+ /** Options for a client. */
6
+ export interface ClientOptions {
7
+ /** Your key: cp_live_ (secret, servers) or cp_pub_ (publishable, browsers). Postcode lookups, validation,
8
+ * autocomplete and more also work without one, on the free keyless allowance. */
9
+ key?: string | null;
10
+ /** The API's base URL (default https://api.clearpostcode.co.uk/v1). */
11
+ baseUrl?: string;
12
+ /** Milliseconds to wait for each attempt (default 10,000). */
13
+ timeout?: number;
14
+ /** Retries after a 429, a 5xx, a timeout or a dropped connection (default 2). */
15
+ maxRetries?: number;
16
+ /** The longest Retry-After the client waits out, in milliseconds (default 60,000); a longer one is thrown at once. */
17
+ maxRetryDelay?: number;
18
+ /** A fetch to use instead of the global one. */
19
+ fetch?: typeof fetch;
20
+ }
21
+ /** A full postcode record: every field, as a lookup without `fields` answers. */
22
+ export type PostcodeRecord = Required<Postcode>;
23
+ /** A field to ask for with `fields` (postcode and status always come back). */
24
+ export type PostcodeField = Exclude<keyof Postcode, "postcode" | "status">;
25
+ /** The record a lookup with `fields` answers. */
26
+ export type PostcodeWith<F extends PostcodeField> = Pick<PostcodeRecord, F | "postcode" | "status">;
27
+ /** A bulk lookup's item, its record trimmed to the fields asked for. */
28
+ export type BulkLookupItem<R> = Omit<BulkItem, "result"> & {
29
+ result: R | null;
30
+ };
31
+ /** A point for reverse geocoding. */
32
+ export interface ReversePoint {
33
+ latitude: number;
34
+ longitude: number;
35
+ /** Search radius in metres (default 500). */
36
+ radius?: number;
37
+ /** How many postcodes for this point (1 to 10, default 1). */
38
+ limit?: number;
39
+ }
40
+ /** A bulk call's answer, sent in chunks the API takes (100 postcodes, 20 points) and joined in the order sent. */
41
+ export interface BulkResult<T> {
42
+ readonly data: T[];
43
+ /** The last chunk's meta, with `sent` and `found` added up over every chunk. Null for an empty list. A chunk that
44
+ * fails throws its error with `partial` holding what the chunks before it answered. */
45
+ readonly meta: Meta | null;
46
+ /** One id per chunk. */
47
+ readonly requestIds: (string | null)[];
48
+ readonly rateLimit: RateLimit | null;
49
+ }
50
+ export declare const BULK_POSTCODES = 100;
51
+ export declare const BULK_POINTS = 20;
52
+ /** Postcodes: lookup, validation, nearest, reverse geocoding, bulk, autocomplete and distance. */
53
+ export declare class Postcodes {
54
+ #private;
55
+ constructor(transport: Transport);
56
+ /** Everything about one postcode (1 lookup when found; not found is free). `fields` trims the record. */
57
+ lookup(postcode: string, params?: {
58
+ fields?: undefined;
59
+ }, options?: RequestOptions): Promise<Result<PostcodeRecord, Meta>>;
60
+ lookup<F extends PostcodeField>(postcode: string, params: {
61
+ fields: readonly F[];
62
+ }, options?: RequestOptions): Promise<Result<PostcodeWith<F>, Meta>>;
63
+ /** Is the format valid, is it in the current edition, is it live? Never throws for a wrong postcode. */
64
+ validate(postcode: string, options?: RequestOptions): Promise<Result<Validation, Meta>>;
65
+ /** Live postcodes nearest this one, nearest first. */
66
+ nearest(postcode: string, params?: {
67
+ radius?: number;
68
+ limit?: number;
69
+ }, options?: RequestOptions): Promise<Result<Near[], Meta>>;
70
+ /** Live postcodes nearest a point (reverse geocoding), out to 20 km. */
71
+ reverse(point: ReversePoint, options?: RequestOptions): Promise<Result<Near[], Meta>>;
72
+ /** Any number of postcodes, sent 100 a call, in the order given. Needs a secret key. */
73
+ bulk(postcodes: readonly string[], params?: {
74
+ fields?: undefined;
75
+ }, options?: RequestOptions): Promise<BulkResult<BulkLookupItem<PostcodeRecord>>>;
76
+ bulk<F extends PostcodeField>(postcodes: readonly string[], params: {
77
+ fields: readonly F[];
78
+ }, options?: RequestOptions): Promise<BulkResult<BulkLookupItem<PostcodeWith<F>>>>;
79
+ /** Nearest postcodes for any number of points, sent 20 a call. Needs a secret key. */
80
+ bulkReverse(points: readonly ReversePoint[], options?: RequestOptions): Promise<BulkResult<ReverseItem>>;
81
+ /** Postcodes (or districts, for 1 to 4 characters) that start with what has been typed. Free. */
82
+ autocomplete(q: string, params?: {
83
+ limit?: number;
84
+ }, options?: RequestOptions): Promise<Result<Suggestion[], Meta>>;
85
+ /** Straight-line distance between two postcodes, in kilometres and miles, with the bearing. */
86
+ distance(from: string, to: string, options?: RequestOptions): Promise<Result<Distance, Meta>>;
87
+ }
88
+ /** Postcode districts (outward codes such as SW1A). */
89
+ export declare class Outcodes {
90
+ #private;
91
+ constructor(transport: Transport);
92
+ /** One district: counts, sectors, centre, councils, wards, constituencies and places. */
93
+ get(outcode: string, options?: RequestOptions): Promise<Result<District, Meta>>;
94
+ /** One page of the district's live postcodes (1 lookup a page). Needs a secret key. */
95
+ postcodes(outcode: string, params?: {
96
+ cursor?: string;
97
+ limit?: number;
98
+ }, options?: RequestOptions): Promise<Page<OutcodePostcode, Meta>>;
99
+ /** Every live postcode in the district, page after page. Needs a secret key. */
100
+ allPostcodes(outcode: string, params?: {
101
+ limit?: number;
102
+ }, options?: RequestOptions): AsyncGenerator<OutcodePostcode>;
103
+ }
104
+ /** Postcode sectors (such as SW1A 1). */
105
+ export declare class Sectors {
106
+ #private;
107
+ constructor(transport: Transport);
108
+ /** One sector: its live postcodes with coordinates, centre, councils and wards. */
109
+ get(sector: string, options?: RequestOptions): Promise<Result<Sector, Meta>>;
110
+ }
111
+ /** Postcode areas (the letters, such as SW). */
112
+ export declare class Areas {
113
+ #private;
114
+ constructor(transport: Transport);
115
+ /** One area: its name, counts and every district in it. */
116
+ get(area: string, options?: RequestOptions): Promise<Result<Area, Meta>>;
117
+ }
118
+ /** Places by name (OS Open Names). */
119
+ export declare class Places {
120
+ #private;
121
+ constructor(transport: Transport);
122
+ /** Cities, towns, villages and neighbourhoods whose name starts with `q`; accents optional. */
123
+ search(q: string, params?: {
124
+ limit?: number;
125
+ }, options?: RequestOptions): Promise<Result<Place[], Meta>>;
126
+ }
127
+ /** Your account. */
128
+ export declare class Account {
129
+ #private;
130
+ constructor(transport: Transport);
131
+ /** Your plan, this period's allowance, lookups used, credits and when it resets. Free. Needs a secret key. */
132
+ usage(options?: RequestOptions): Promise<Result<Usage, Meta>>;
133
+ }
134
+ /** Defaults every client shares. */
135
+ export declare function transportConfig(options: ClientOptions, key: string | null, extra: Pick<TransportConfig, "headers" | "keyInQuery">): TransportConfig;
136
+ /** The resources every client carries. */
137
+ export declare class Client {
138
+ readonly postcodes: Postcodes;
139
+ readonly outcodes: Outcodes;
140
+ readonly sectors: Sectors;
141
+ readonly areas: Areas;
142
+ readonly places: Places;
143
+ readonly account: Account;
144
+ readonly addresses: Addresses;
145
+ constructor(config: TransportConfig);
146
+ }