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 +16 -0
- package/README.md +207 -2
- package/dist/cjs/addresses.d.ts +28 -0
- package/dist/cjs/addresses.js +64 -0
- package/dist/cjs/browser.d.ts +39 -0
- package/dist/cjs/browser.js +54 -0
- package/dist/cjs/client.d.ts +146 -0
- package/dist/cjs/client.js +188 -0
- package/dist/cjs/errors.d.ts +73 -0
- package/dist/cjs/errors.js +111 -0
- package/dist/cjs/generated.d.ts +546 -0
- package/dist/cjs/generated.js +63 -0
- package/dist/cjs/http.d.ts +62 -0
- package/dist/cjs/http.js +173 -0
- package/dist/cjs/index.d.ts +24 -0
- package/dist/cjs/index.js +54 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/page.d.ts +20 -0
- package/dist/cjs/page.js +39 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +24 -0
- package/dist/esm/addresses.d.ts +28 -0
- package/dist/esm/addresses.js +47 -0
- package/dist/esm/browser.d.ts +39 -0
- package/dist/esm/browser.js +33 -0
- package/dist/esm/client.d.ts +146 -0
- package/dist/esm/client.js +169 -0
- package/dist/esm/errors.d.ts +73 -0
- package/dist/esm/errors.js +92 -0
- package/dist/esm/generated.d.ts +546 -0
- package/dist/esm/generated.js +42 -0
- package/dist/esm/http.d.ts +62 -0
- package/dist/esm/http.js +161 -0
- package/dist/esm/index.d.ts +24 -0
- package/dist/esm/index.js +37 -0
- package/dist/esm/page.d.ts +20 -0
- package/dist/esm/page.js +17 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/package.json +80 -4
package/dist/cjs/http.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
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 http_exports = {};
|
|
20
|
+
__export(http_exports, {
|
|
21
|
+
Transport: () => Transport,
|
|
22
|
+
rateLimitOf: () => rateLimitOf
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(http_exports);
|
|
25
|
+
var import_generated = require("./generated.js");
|
|
26
|
+
var import_errors = require("./errors.js");
|
|
27
|
+
const RETRY_STATUS = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
28
|
+
const RETRY_POST = /* @__PURE__ */ new Set([429, 503]);
|
|
29
|
+
function retryAfterOf(h) {
|
|
30
|
+
const v = h.get("retry-after");
|
|
31
|
+
if (v === null)
|
|
32
|
+
return null;
|
|
33
|
+
const n = Number(v);
|
|
34
|
+
if (Number.isFinite(n))
|
|
35
|
+
return Math.max(0, n);
|
|
36
|
+
const at = Date.parse(v);
|
|
37
|
+
return Number.isNaN(at) ? null : Math.max(0, (at - Date.now()) / 1e3);
|
|
38
|
+
}
|
|
39
|
+
const intOf = (v) => v == null || v === "" || !Number.isFinite(Number(v)) ? null : Number(v);
|
|
40
|
+
function rateLimitOf(h) {
|
|
41
|
+
const structured = h.get("ratelimit");
|
|
42
|
+
const m = structured?.match(/^\s*"([^"]+)"\s*;(.*)$/);
|
|
43
|
+
const item = (s, k) => s?.match(new RegExp(`(?:^|;)\\s*${k}=(\\d+)`))?.[1];
|
|
44
|
+
const policy = m?.[1] ?? null;
|
|
45
|
+
const q = policy ? h.get("ratelimit-policy")?.split(",").find((p) => p.trim().startsWith(`"${policy}"`)) : void 0;
|
|
46
|
+
const r = {
|
|
47
|
+
policy,
|
|
48
|
+
limit: intOf(h.get("ratelimit-limit")) ?? intOf(item(q, "q")),
|
|
49
|
+
remaining: intOf(h.get("ratelimit-remaining")) ?? intOf(item(m?.[2], "r")),
|
|
50
|
+
reset: intOf(h.get("ratelimit-reset")) ?? intOf(item(m?.[2], "t"))
|
|
51
|
+
};
|
|
52
|
+
return r.policy === null && r.limit === null && r.remaining === null && r.reset === null ? null : r;
|
|
53
|
+
}
|
|
54
|
+
function sleep(ms, signal) {
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
if (signal?.aborted)
|
|
57
|
+
return reject(signal.reason);
|
|
58
|
+
const t = setTimeout(done, ms);
|
|
59
|
+
function done() {
|
|
60
|
+
signal?.removeEventListener("abort", stop);
|
|
61
|
+
resolve();
|
|
62
|
+
}
|
|
63
|
+
function stop() {
|
|
64
|
+
clearTimeout(t);
|
|
65
|
+
reject(signal?.reason);
|
|
66
|
+
}
|
|
67
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const backoff = (attempt) => Math.min(8e3, 500 * 2 ** attempt) * (0.5 + Math.random() / 2);
|
|
71
|
+
class Transport {
|
|
72
|
+
config;
|
|
73
|
+
constructor(config) {
|
|
74
|
+
this.config = config;
|
|
75
|
+
}
|
|
76
|
+
/** The URL for an operation: path parameters encoded into the path, then the query it takes. */
|
|
77
|
+
url(id, call) {
|
|
78
|
+
const op = import_generated.OPERATIONS[id];
|
|
79
|
+
const path = op.path.replace(/\{(\w+)\}/g, (_, k) => {
|
|
80
|
+
const v = String(call.path?.[k] ?? "").trim();
|
|
81
|
+
if (!v)
|
|
82
|
+
throw new TypeError(`${id} needs a ${k}`);
|
|
83
|
+
return encodeURIComponent(v);
|
|
84
|
+
});
|
|
85
|
+
const q = new URLSearchParams();
|
|
86
|
+
for (const [k, v] of Object.entries(call.query ?? {})) {
|
|
87
|
+
if (v === void 0 || v === null)
|
|
88
|
+
continue;
|
|
89
|
+
if (!op.query.includes(k))
|
|
90
|
+
throw new TypeError(`${id} takes no "${k}" parameter (it takes: ${op.query.join(", ") || "none"})`);
|
|
91
|
+
q.set(k, String(v));
|
|
92
|
+
}
|
|
93
|
+
if (this.config.key && this.config.keyInQuery)
|
|
94
|
+
q.set("key", this.config.key);
|
|
95
|
+
const s = q.toString();
|
|
96
|
+
return `${this.config.baseUrl}${path}${s ? `?${s}` : ""}`;
|
|
97
|
+
}
|
|
98
|
+
/** Make the call, retrying 429s, 5xx answers, timeouts and dropped connections with backoff (a POST: 429 and 503
|
|
99
|
+
* only). No wait is longer than maxRetryDelay: a longer Retry-After is thrown at once. */
|
|
100
|
+
async request(id, call = {}, options = {}) {
|
|
101
|
+
const url = this.url(id, call);
|
|
102
|
+
const headers = { accept: "application/json", ...this.config.headers };
|
|
103
|
+
if (this.config.key && !this.config.keyInQuery)
|
|
104
|
+
headers["x-api-key"] = this.config.key;
|
|
105
|
+
if (call.body !== void 0)
|
|
106
|
+
headers["content-type"] = "application/json";
|
|
107
|
+
const method = import_generated.OPERATIONS[id].method;
|
|
108
|
+
const init = { method, headers, redirect: "error", body: call.body === void 0 ? void 0 : JSON.stringify(call.body) };
|
|
109
|
+
const retries = options.maxRetries ?? this.config.maxRetries;
|
|
110
|
+
for (let attempt = 0; ; attempt++) {
|
|
111
|
+
let wait;
|
|
112
|
+
try {
|
|
113
|
+
const { response, text } = await this.attempt(url, init, options);
|
|
114
|
+
if (response.ok) {
|
|
115
|
+
let json;
|
|
116
|
+
try {
|
|
117
|
+
json = JSON.parse(text);
|
|
118
|
+
} catch {
|
|
119
|
+
throw new import_errors.APIError(response.status, { detail: "The answer was not JSON." }, response.headers, null);
|
|
120
|
+
}
|
|
121
|
+
return { data: json.data, meta: json.meta, status: response.status, requestId: response.headers.get("x-request-id"), rateLimit: rateLimitOf(response.headers) };
|
|
122
|
+
}
|
|
123
|
+
let problem = null;
|
|
124
|
+
try {
|
|
125
|
+
problem = JSON.parse(text);
|
|
126
|
+
} catch {
|
|
127
|
+
problem = null;
|
|
128
|
+
}
|
|
129
|
+
const after = retryAfterOf(response.headers);
|
|
130
|
+
const error = (0, import_errors.errorFor)(response.status, problem, response.headers, after);
|
|
131
|
+
if (!(method === "POST" ? RETRY_POST : RETRY_STATUS).has(response.status) || attempt >= retries)
|
|
132
|
+
throw error;
|
|
133
|
+
const limit = rateLimitOf(response.headers);
|
|
134
|
+
const advised = after ?? (response.status === 429 && limit?.remaining === 0 ? limit.reset : null);
|
|
135
|
+
if (advised !== null && advised * 1e3 > this.config.maxRetryDelay)
|
|
136
|
+
throw error;
|
|
137
|
+
wait = advised !== null ? advised * 1e3 : Math.min(backoff(attempt), this.config.maxRetryDelay);
|
|
138
|
+
} catch (e) {
|
|
139
|
+
if (e instanceof import_errors.APIError || options.signal?.aborted)
|
|
140
|
+
throw e;
|
|
141
|
+
if (!(e instanceof import_errors.APIConnectionError) || method === "POST" || attempt >= retries)
|
|
142
|
+
throw e;
|
|
143
|
+
wait = Math.min(backoff(attempt), this.config.maxRetryDelay);
|
|
144
|
+
}
|
|
145
|
+
await sleep(wait, options.signal);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** One attempt within the timeout: the response and its body. */
|
|
149
|
+
async attempt(url, init, options) {
|
|
150
|
+
const timeout = options.timeout ?? this.config.timeout;
|
|
151
|
+
const ctl = new AbortController();
|
|
152
|
+
const timer = setTimeout(() => ctl.abort(new import_errors.APITimeoutError(`No answer within ${timeout} ms`)), timeout);
|
|
153
|
+
const outer = options.signal;
|
|
154
|
+
const relay = () => ctl.abort(outer?.reason);
|
|
155
|
+
if (outer?.aborted)
|
|
156
|
+
relay();
|
|
157
|
+
else
|
|
158
|
+
outer?.addEventListener("abort", relay, { once: true });
|
|
159
|
+
try {
|
|
160
|
+
const response = await this.config.fetch(url, { ...init, signal: ctl.signal });
|
|
161
|
+
return { response, text: await response.text() };
|
|
162
|
+
} catch (e) {
|
|
163
|
+
if (ctl.signal.reason instanceof import_errors.APITimeoutError)
|
|
164
|
+
throw ctl.signal.reason;
|
|
165
|
+
if (outer?.aborted)
|
|
166
|
+
throw outer.reason;
|
|
167
|
+
throw new import_errors.APIConnectionError(`Could not reach the ClearPostcode API: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
168
|
+
} finally {
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
outer?.removeEventListener("abort", relay);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ClearPostcode: UK postcode data (lookup, validation, autocomplete, nearest, reverse geocoding, distance, districts,
|
|
3
|
+
* sectors, areas and places) and Address lookup (Royal Mail PAF, early access). No dependencies.
|
|
4
|
+
* Docs: https://clearpostcode.co.uk/developers/docs
|
|
5
|
+
*/
|
|
6
|
+
import { Client, type ClientOptions } from "./client.js";
|
|
7
|
+
import { VERSION } from "./version.js";
|
|
8
|
+
/**
|
|
9
|
+
* The client for servers, scripts and edge functions. The key comes from `key`, else the CLEAR_POSTCODE_KEY
|
|
10
|
+
* environment variable; with neither, calls run keyless (rate-limited per network). `key: null` forces keyless.
|
|
11
|
+
*/
|
|
12
|
+
export declare class ClearPostcode extends Client {
|
|
13
|
+
constructor(options?: ClientOptions);
|
|
14
|
+
}
|
|
15
|
+
export default ClearPostcode;
|
|
16
|
+
export { VERSION };
|
|
17
|
+
export * from "./errors.js";
|
|
18
|
+
export type * from "./generated.js";
|
|
19
|
+
export { BASE_URL } from "./generated.js";
|
|
20
|
+
export type { ClientOptions, PostcodeRecord, PostcodeField, PostcodeWith, BulkLookupItem, BulkResult, ReversePoint, Postcodes, Outcodes, Sectors, Areas, Places, Account } from "./client.js";
|
|
21
|
+
export { BULK_POSTCODES, BULK_POINTS } from "./client.js";
|
|
22
|
+
export type { Addresses, AddressSuggestParams } from "./addresses.js";
|
|
23
|
+
export type { Page } from "./page.js";
|
|
24
|
+
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 index_exports = {};
|
|
21
|
+
__export(index_exports, {
|
|
22
|
+
BASE_URL: () => import_generated.BASE_URL,
|
|
23
|
+
BULK_POINTS: () => import_client2.BULK_POINTS,
|
|
24
|
+
BULK_POSTCODES: () => import_client2.BULK_POSTCODES,
|
|
25
|
+
ClearPostcode: () => ClearPostcode,
|
|
26
|
+
VERSION: () => import_version.VERSION,
|
|
27
|
+
default: () => index_default
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(index_exports);
|
|
30
|
+
var import_client = require("./client.js");
|
|
31
|
+
var import_errors = require("./errors.js");
|
|
32
|
+
var import_version = require("./version.js");
|
|
33
|
+
__reExport(index_exports, require("./errors.js"), module.exports);
|
|
34
|
+
var import_generated = require("./generated.js");
|
|
35
|
+
var import_client2 = require("./client.js");
|
|
36
|
+
const g = globalThis;
|
|
37
|
+
function runtime() {
|
|
38
|
+
const v = g.process?.versions;
|
|
39
|
+
if (v?.bun)
|
|
40
|
+
return `bun/${v.bun}`;
|
|
41
|
+
if (g.Deno?.version?.deno)
|
|
42
|
+
return `deno/${g.Deno.version.deno}`;
|
|
43
|
+
return v?.node ? `node/${v.node}` : "js";
|
|
44
|
+
}
|
|
45
|
+
class ClearPostcode extends import_client.Client {
|
|
46
|
+
constructor(options = {}) {
|
|
47
|
+
const key = (options.key === void 0 ? g.process?.env?.CLEAR_POSTCODE_KEY : options.key) || null;
|
|
48
|
+
const inBrowser = typeof g.document !== "undefined" || /^Mozilla\//.test(g.navigator?.userAgent ?? "");
|
|
49
|
+
if (inBrowser && key?.startsWith("cp_live_"))
|
|
50
|
+
throw new import_errors.ClearPostcodeError("Secret keys (cp_live_) stay on your server. In a browser, use a publishable key (cp_pub_) locked to your domain, with clearpostcode/browser.");
|
|
51
|
+
super((0, import_client.transportConfig)(options, key, { keyInQuery: false, headers: inBrowser ? {} : { "user-agent": `clearpostcode-js/${import_version.VERSION} ${runtime()}` } }));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
var index_default = ClearPostcode;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "type": "commonjs" }
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { OperationTypes } from "./generated.js";
|
|
2
|
+
import type { Call, RequestOptions, Result, Transport } from "./http.js";
|
|
3
|
+
/** One page of a list. `next()` fetches the page after it (null after the last). */
|
|
4
|
+
export interface Page<T, M> extends Result<T[], M> {
|
|
5
|
+
/** meta.next_cursor: pass it as `cursor` for the next page; null on the last page. */
|
|
6
|
+
readonly nextCursor: string | null;
|
|
7
|
+
readonly hasMore: boolean;
|
|
8
|
+
next(options?: RequestOptions): Promise<Page<T, M> | null>;
|
|
9
|
+
}
|
|
10
|
+
type Paged = {
|
|
11
|
+
[K in keyof OperationTypes]: OperationTypes[K]["meta"] extends {
|
|
12
|
+
next_cursor?: string | null;
|
|
13
|
+
} ? (OperationTypes[K]["data"] extends unknown[] ? K : never) : never;
|
|
14
|
+
}[keyof OperationTypes];
|
|
15
|
+
type Item<I extends Paged> = OperationTypes[I]["data"][number];
|
|
16
|
+
/** A page of a cursor-paged operation; `cursorParam` names the query parameter the cursor goes back in. */
|
|
17
|
+
export declare function pageOf<I extends Paged>(t: Transport, id: I, call: Call, cursorParam: string, cursor: string | null, options: RequestOptions): Promise<Page<Item<I>, OperationTypes[I]["meta"]>>;
|
|
18
|
+
/** Every item of a list, following the cursor page after page. Nothing is fetched until the first item is read. */
|
|
19
|
+
export declare function every<T, M>(first: () => Promise<Page<T, M>>): AsyncGenerator<T>;
|
|
20
|
+
export {};
|
package/dist/cjs/page.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
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 page_exports = {};
|
|
20
|
+
__export(page_exports, {
|
|
21
|
+
every: () => every,
|
|
22
|
+
pageOf: () => pageOf
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(page_exports);
|
|
25
|
+
async function pageOf(t, id, call, cursorParam, cursor, options) {
|
|
26
|
+
const r = await t.request(id, cursor ? { ...call, query: { ...call.query, [cursorParam]: cursor } } : call, options);
|
|
27
|
+
const nextCursor = r.meta.next_cursor ?? null;
|
|
28
|
+
return {
|
|
29
|
+
...r,
|
|
30
|
+
data: r.data,
|
|
31
|
+
nextCursor,
|
|
32
|
+
hasMore: nextCursor !== null,
|
|
33
|
+
next: (o = options) => nextCursor === null ? Promise.resolve(null) : pageOf(t, id, call, cursorParam, nextCursor, o)
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
async function* every(first) {
|
|
37
|
+
for (let page = await first(); page; page = await page.next())
|
|
38
|
+
yield* page.data;
|
|
39
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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 version_exports = {};
|
|
20
|
+
__export(version_exports, {
|
|
21
|
+
VERSION: () => VERSION
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(version_exports);
|
|
24
|
+
const VERSION = "2.0.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,47 @@
|
|
|
1
|
+
import { Transport } from "./http.js";
|
|
2
|
+
import { pageOf, every } from "./page.js";
|
|
3
|
+
/**
|
|
4
|
+
* Address lookup (Royal Mail PAF, early access), behind one adapter: each SDK call names its operation and parameters
|
|
5
|
+
* here and nowhere else, so a change to an address route is one edit. A key is always needed, and the business it
|
|
6
|
+
* serves must have Address lookup switched on in the dashboard; otherwise the API answers 403
|
|
7
|
+
* address_lookup_not_enabled (a PermissionDeniedError).
|
|
8
|
+
*/
|
|
9
|
+
const ROUTES = {
|
|
10
|
+
byPostcode: { op: "addressesByPostcode", postcode: "postcode", cursor: "cursor" },
|
|
11
|
+
suggest: { op: "addressSuggest", q: "q", container: "container", limit: "limit" },
|
|
12
|
+
retrieve: { op: "addressRetrieve", id: "id" },
|
|
13
|
+
byUdprn: { op: "addressByUdprn", udprn: "udprn" },
|
|
14
|
+
};
|
|
15
|
+
export class Addresses {
|
|
16
|
+
#t;
|
|
17
|
+
constructor(transport) {
|
|
18
|
+
this.#t = transport;
|
|
19
|
+
}
|
|
20
|
+
/** One page of the addresses at a postcode, in delivery order (up to 100 a page; 1 address credit a page). */
|
|
21
|
+
byPostcode(postcode, params = {}, options = {}) {
|
|
22
|
+
const r = ROUTES.byPostcode;
|
|
23
|
+
return pageOf(this.#t, r.op, { query: { [r.postcode]: postcode } }, r.cursor, params.cursor ?? null, options);
|
|
24
|
+
}
|
|
25
|
+
/** Every address at a postcode, page after page. */
|
|
26
|
+
allByPostcode(postcode, options = {}) {
|
|
27
|
+
return every(() => this.byPostcode(postcode, {}, options));
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Suggestions as the customer types (free): kind "address" is one address (resolve its id with retrieve()), kind
|
|
31
|
+
* "container" is a postcode, street or building holding `count` addresses (pass its id as `container`).
|
|
32
|
+
*/
|
|
33
|
+
suggest(q, params = {}, options = {}) {
|
|
34
|
+
const r = ROUTES.suggest;
|
|
35
|
+
return this.#t.request(r.op, { query: { [r.q]: q || undefined, [r.container]: params.container, [r.limit]: params.limit } }, options);
|
|
36
|
+
}
|
|
37
|
+
/** The full address for an address suggestion's id (1 address credit). */
|
|
38
|
+
retrieve(id, options = {}) {
|
|
39
|
+
const r = ROUTES.retrieve;
|
|
40
|
+
return this.#t.request(r.op, { path: { [r.id]: id } }, options);
|
|
41
|
+
}
|
|
42
|
+
/** The full address for a UDPRN, Royal Mail's number for one delivery point (1 address credit). */
|
|
43
|
+
byUdprn(udprn, options = {}) {
|
|
44
|
+
const r = ROUTES.byUdprn;
|
|
45
|
+
return this.#t.request(r.op, { path: { [r.udprn]: String(udprn) } }, options);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -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,33 @@
|
|
|
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 { Client, transportConfig } from "./client.js";
|
|
7
|
+
import { ClearPostcodeError } from "./errors.js";
|
|
8
|
+
/** The browser client. Throws ClearPostcodeError for anything but a publishable key, before any call. */
|
|
9
|
+
export class ClearPostcode {
|
|
10
|
+
postcodes;
|
|
11
|
+
outcodes;
|
|
12
|
+
sectors;
|
|
13
|
+
areas;
|
|
14
|
+
places;
|
|
15
|
+
addresses;
|
|
16
|
+
constructor(options = {}) {
|
|
17
|
+
const key = options.key || null;
|
|
18
|
+
if (key && !key.startsWith("cp_pub_")) {
|
|
19
|
+
throw new 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.");
|
|
20
|
+
}
|
|
21
|
+
const c = new Client(transportConfig(options, key, { keyInQuery: true, headers: {} }));
|
|
22
|
+
this.postcodes = c.postcodes;
|
|
23
|
+
this.outcodes = c.outcodes;
|
|
24
|
+
this.sectors = c.sectors;
|
|
25
|
+
this.areas = c.areas;
|
|
26
|
+
this.places = c.places;
|
|
27
|
+
this.addresses = c.addresses;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export default ClearPostcode;
|
|
31
|
+
export { VERSION } from "./version.js";
|
|
32
|
+
export * from "./errors.js";
|
|
33
|
+
export { BASE_URL } from "./generated.js";
|
|
@@ -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
|
+
}
|