mapricot 0.0.0-stage → 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mapricot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # Mapricot for JavaScript and TypeScript
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
+ The official JavaScript client for the [Mapricot API](https://mapricot.com/): address and place search, reverse geocoding, nearby places, routing, and IP geolocation, with 250,000 free requests every month.
4
+
5
+ ```sh
6
+ npm install mapricot
7
+ ```
8
+
9
+ It uses the built-in `fetch`, so it has no dependencies and runs in Node.js 20 and later, Deno (as `npm:mapricot`), Bun, Cloudflare Workers, and browsers. Types are included.
10
+
11
+ ## Quick start
12
+
13
+ Create a server key in the [dashboard](https://app.mapricot.com/) and set it as `MAPRICOT_KEY`:
14
+
15
+ ```sh
16
+ export MAPRICOT_KEY="mapricot_sk_…"
17
+ ```
18
+
19
+ ```js
20
+ import { Mapricot } from "mapricot";
21
+
22
+ const client = new Mapricot();
23
+
24
+ const { results } = await client.search("128 SW 3rd Ave, Portland", { limit: 1 });
25
+ console.log(results[0].label, results[0].lat, results[0].lon);
26
+ ```
27
+
28
+ Pass the key yourself with `new Mapricot({ apiKey: "mapricot_sk_…" })`. In a web page, use a browser key, which works only from the origins you allow, and keep server keys on your server.
29
+
30
+ ## Methods
31
+
32
+ Each method returns the API's JSON, typed, with the same field names as the [API reference](https://mapricot.com/api-reference/).
33
+
34
+ | Method | Endpoint |
35
+ | --- | --- |
36
+ | `client.search(q, { focus, country, limit, lang })` | [`GET /v1/search`](https://mapricot.com/docs/geocoding/#find-an-address) |
37
+ | `client.autocomplete(q, { focus, country, limit, lang })` | [`GET /v1/autocomplete`](https://mapricot.com/docs/places/#suggest-as-people-type) |
38
+ | `client.reverse(lat, lon, { limit, lang })` | [`GET /v1/reverse`](https://mapricot.com/docs/geocoding/#find-the-address-at-a-point) |
39
+ | `client.nearby(lat, lon, { category, radius, limit, lang })` | [`GET /v1/nearby`](https://mapricot.com/docs/places/#list-places-around-a-point) |
40
+ | `client.place(id, { lang })` | [`GET /v1/places/{id}`](https://mapricot.com/docs/places/#look-up-a-saved-place) |
41
+ | `client.route(waypoints, { mode })` | [`POST /v1/route`](https://mapricot.com/docs/routing/#get-a-route) |
42
+ | `client.ip(address)` | [`GET /v1/ip/{ip}`](https://mapricot.com/docs/ip-geolocation/#look-up-an-address) |
43
+ | `client.account()` | `GET /v1/account`, which checks a key and is never billed |
44
+
45
+ `focus` and each waypoint are `{ lat, lon }`. `country` and `category` take an array or a comma-separated string.
46
+
47
+ ```js
48
+ const nearby = await client.nearby(45.52, -122.68, { category: ["food:coffee_shop"], radius: 1000 });
49
+ const { routes } = await client.route([{ lat: 45.5189, lon: -122.6793 }, { lat: 45.5214, lon: -122.6828 }], { mode: "walk" });
50
+ console.log(routes[0].durationSeconds);
51
+ ```
52
+
53
+ A route's `polyline` is encoded with six decimal places. Decode it with precision 6, as [decoding a route polyline](https://mapricot.com/docs/polyline/) shows.
54
+
55
+ If your app shows results, show the credits in each response's `attribution`.
56
+
57
+ ## Errors and retries
58
+
59
+ An error response throws `MapricotError`, with the HTTP `status`, the API's error `code`, a `message`, and the `requestId`:
60
+
61
+ ```js
62
+ import { MapricotError } from "mapricot";
63
+
64
+ try {
65
+ await client.search("");
66
+ } catch (error) {
67
+ if (!(error instanceof MapricotError)) throw error;
68
+ console.log(error.status, error.code, error.message); // 400 invalid_request The service rejected the request.
69
+ }
70
+ ```
71
+
72
+ The client retries `503` responses and `429 concurrency_exceeded`, up to twice, waiting longer each time. Errors aren't billed. Set `maxRetries` and `timeout` (milliseconds) in the constructor's options to change this. The [API reference](https://mapricot.com/api-reference/#errors) lists every status.
73
+
74
+ ## Links
75
+
76
+ - [Mapricot](https://mapricot.com/)
77
+ - [Node.js docs](https://mapricot.com/docs/node/)
78
+ - [API reference](https://mapricot.com/api-reference/)
79
+ - [Pricing](https://mapricot.com/pricing/)
@@ -0,0 +1,130 @@
1
+ export interface Attribution {
2
+ source: string;
3
+ text: string;
4
+ url: string;
5
+ }
6
+ export interface Address {
7
+ houseNumber?: string;
8
+ street?: string;
9
+ postalCode?: string;
10
+ locality?: string;
11
+ region?: string;
12
+ regionCode?: string;
13
+ country?: string;
14
+ countryCode?: string;
15
+ }
16
+ export interface Place {
17
+ id: string;
18
+ type: string;
19
+ name: string;
20
+ label: string;
21
+ lat: number;
22
+ lon: number;
23
+ address?: Address;
24
+ categories?: string[];
25
+ distanceMeters?: number;
26
+ source: string;
27
+ }
28
+ export interface Places {
29
+ results: Place[];
30
+ attribution: Attribution[];
31
+ }
32
+ export interface PlaceResult {
33
+ result: Place;
34
+ attribution: Attribution[];
35
+ }
36
+ export interface Leg {
37
+ distanceMeters: number;
38
+ durationSeconds: number;
39
+ }
40
+ export interface Route {
41
+ distanceMeters: number;
42
+ durationSeconds: number;
43
+ /** Encoded polyline with six decimal places of precision. */
44
+ polyline: string;
45
+ legs: Leg[];
46
+ }
47
+ export interface Routes {
48
+ routes: Route[];
49
+ attribution?: Attribution[];
50
+ }
51
+ export interface IpLocation {
52
+ ip: string;
53
+ found: boolean;
54
+ continentCode?: string;
55
+ countryCode?: string;
56
+ countryName?: string;
57
+ regionCode?: string;
58
+ regionName?: string;
59
+ city?: string;
60
+ location?: Point;
61
+ source: string;
62
+ attributionUrl: string;
63
+ licenseUrl: string;
64
+ datasetRelease: string;
65
+ }
66
+ export interface Account {
67
+ id: string;
68
+ name: string;
69
+ status: string;
70
+ created_at: string;
71
+ }
72
+ export interface Point {
73
+ lat: number;
74
+ lon: number;
75
+ }
76
+ export interface SearchOptions {
77
+ focus?: Point;
78
+ country?: string | string[];
79
+ limit?: number;
80
+ lang?: string;
81
+ }
82
+ export interface ReverseOptions {
83
+ limit?: number;
84
+ lang?: string;
85
+ }
86
+ export interface NearbyOptions {
87
+ category?: string | string[];
88
+ radius?: number;
89
+ limit?: number;
90
+ lang?: string;
91
+ }
92
+ export interface ClientOptions {
93
+ /** Defaults to the MAPRICOT_KEY environment variable. */
94
+ apiKey?: string;
95
+ baseUrl?: string;
96
+ /** Milliseconds per attempt. */
97
+ timeout?: number;
98
+ /** Retries for 503 and for 429 with too many requests in progress. */
99
+ maxRetries?: number;
100
+ }
101
+ export declare class MapricotError extends Error {
102
+ readonly status: number;
103
+ readonly code: string;
104
+ readonly requestId: string | null;
105
+ constructor(status: number, code: string, message: string, requestId: string | null);
106
+ }
107
+ export declare class Mapricot {
108
+ #private;
109
+ constructor(options?: ClientOptions);
110
+ /** Find addresses and places matching free text. */
111
+ search(q: string, options?: SearchOptions): Promise<Places>;
112
+ /** Suggest addresses and places as someone types. */
113
+ autocomplete(q: string, options?: SearchOptions): Promise<Places>;
114
+ /** Find the address nearest a coordinate, or the area around it. */
115
+ reverse(lat: number, lon: number, options?: ReverseOptions): Promise<Places>;
116
+ /** List places around a coordinate, optionally by category. */
117
+ nearby(lat: number, lon: number, options?: NearbyOptions): Promise<Places>;
118
+ /** Look up one place by its Mapricot ID. */
119
+ place(id: string, options?: {
120
+ lang?: string;
121
+ }): Promise<PlaceResult>;
122
+ /** Find a route through 2 to 20 waypoints. */
123
+ route(waypoints: Point[], options?: {
124
+ mode?: "drive" | "walk" | "bicycle";
125
+ }): Promise<Routes>;
126
+ /** Approximate location of a public IP address. */
127
+ ip(address: string): Promise<IpLocation>;
128
+ /** The key's account. Not billed, so it checks a key for free. */
129
+ account(): Promise<Account>;
130
+ }
package/dist/index.js ADDED
@@ -0,0 +1,106 @@
1
+ export class MapricotError extends Error {
2
+ status;
3
+ code;
4
+ requestId;
5
+ constructor(status, code, message, requestId) {
6
+ super(message);
7
+ this.name = "MapricotError";
8
+ this.status = status;
9
+ this.code = code;
10
+ this.requestId = requestId;
11
+ }
12
+ }
13
+ export class Mapricot {
14
+ #apiKey;
15
+ #baseUrl;
16
+ #timeout;
17
+ #maxRetries;
18
+ constructor(options = {}) {
19
+ const apiKey = options.apiKey ?? globalThis.process?.env?.MAPRICOT_KEY;
20
+ if (!apiKey)
21
+ throw new Error("Pass apiKey or set MAPRICOT_KEY.");
22
+ this.#apiKey = apiKey;
23
+ this.#baseUrl = options.baseUrl ?? "https://api.mapricot.com";
24
+ this.#timeout = options.timeout ?? 30_000;
25
+ this.#maxRetries = options.maxRetries ?? 2;
26
+ }
27
+ /** Find addresses and places matching free text. */
28
+ search(q, options = {}) {
29
+ return this.#request("GET", "/v1/search", { q, ...options });
30
+ }
31
+ /** Suggest addresses and places as someone types. */
32
+ autocomplete(q, options = {}) {
33
+ return this.#request("GET", "/v1/autocomplete", { q, ...options });
34
+ }
35
+ /** Find the address nearest a coordinate, or the area around it. */
36
+ reverse(lat, lon, options = {}) {
37
+ return this.#request("GET", "/v1/reverse", { lat, lon, ...options });
38
+ }
39
+ /** List places around a coordinate, optionally by category. */
40
+ nearby(lat, lon, options = {}) {
41
+ return this.#request("GET", "/v1/nearby", { lat, lon, ...options });
42
+ }
43
+ /** Look up one place by its Mapricot ID. */
44
+ place(id, options = {}) {
45
+ return this.#request("GET", `/v1/places/${encodeURIComponent(id)}`, options);
46
+ }
47
+ /** Find a route through 2 to 20 waypoints. */
48
+ route(waypoints, options = {}) {
49
+ return this.#request("POST", "/v1/route", {}, { waypoints, ...options });
50
+ }
51
+ /** Approximate location of a public IP address. */
52
+ ip(address) {
53
+ return this.#request("GET", `/v1/ip/${encodeURIComponent(address)}`, {});
54
+ }
55
+ /** The key's account. Not billed, so it checks a key for free. */
56
+ account() {
57
+ return this.#request("GET", "/v1/account", {});
58
+ }
59
+ async #request(method, path, params, body) {
60
+ const url = new URL(path, this.#baseUrl);
61
+ for (const [name, value] of Object.entries(params)) {
62
+ if (value === undefined)
63
+ continue;
64
+ url.searchParams.set(name, format(value));
65
+ }
66
+ const headers = { Authorization: `Bearer ${this.#apiKey}` };
67
+ if (body)
68
+ headers["Content-Type"] = "application/json";
69
+ for (let attempt = 0;; attempt++) {
70
+ const response = await fetch(url, {
71
+ method,
72
+ headers,
73
+ body: body && JSON.stringify(body),
74
+ signal: AbortSignal.timeout(this.#timeout),
75
+ });
76
+ if (response.ok)
77
+ return (await response.json());
78
+ const error = await errorFrom(response);
79
+ if (attempt < this.#maxRetries && retryable(error)) {
80
+ await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
81
+ continue;
82
+ }
83
+ throw error;
84
+ }
85
+ }
86
+ }
87
+ function format(value) {
88
+ if (Array.isArray(value))
89
+ return value.join(",");
90
+ if (typeof value === "object")
91
+ return `${value.lat},${value.lon}`;
92
+ return String(value);
93
+ }
94
+ async function errorFrom(response) {
95
+ const requestId = response.headers.get("X-Request-Id");
96
+ try {
97
+ const { error } = await response.json();
98
+ return new MapricotError(response.status, error.code, error.message, requestId);
99
+ }
100
+ catch {
101
+ return new MapricotError(response.status, "unknown", `HTTP ${response.status}`, requestId);
102
+ }
103
+ }
104
+ function retryable(error) {
105
+ return error.status === 503 || error.code === "concurrency_exceeded";
106
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "mapricot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Official client for the Mapricot API: geocoding, places, routing, and IP geolocation.",
5
+ "keywords": [
6
+ "geocoding",
7
+ "places",
8
+ "routing",
9
+ "ip-geolocation",
10
+ "maps"
11
+ ],
12
+ "homepage": "https://mapricot.com/docs/node/",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/mapricothq/mapricot.git",
16
+ "directory": "sdks/js"
17
+ },
18
+ "bugs": "https://github.com/mapricothq/mapricot/issues",
19
+ "license": "MIT",
20
+ "type": "module",
21
+ "exports": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc",
31
+ "test": "tsc && node --test",
32
+ "prepublishOnly": "tsc"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "^7.0.2"
36
+ }
37
+ }