@osm-editor-kit/key-value-db-client 0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tobias Jordans
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 ADDED
@@ -0,0 +1,25 @@
1
+ # @osm-editor-kit/key-value-db-client
2
+
3
+ Typed, dependency-free `fetch` client for [key-value-db](https://github.com/FixMyBerlin/key-value-db), a shared key-value API for OpenStreetMap-authenticated apps.
4
+
5
+ ```ts
6
+ import { createKvClient } from '@osm-editor-kit/key-value-db-client'
7
+
8
+ const kv = createKvClient<MyData>({
9
+ baseUrl: 'https://key-value-store.fixmycity.workers.dev',
10
+ project: 'my-project',
11
+ apiKey: 'kv_…', // public project key
12
+ getOsmToken: () => osmAccessToken ?? null,
13
+ })
14
+
15
+ await kv.put('way/1', { note: 'hi' }, ['tag-a'])
16
+ const { items } = await kv.list({ tags: ['tag-a'] })
17
+ ```
18
+
19
+ Methods: `list`, `get`, `put` (with `ifMatch`), `remove`, `batch`, `tags`, `me`, `removeMine` ("delete my data" in this project), and `forget` (drops the server-side token cache). Errors are thrown as `KvError` with `status` and `code`. Response envelopes are checked; your `data` is not.
20
+
21
+ API reference: [docs/API.md](https://github.com/FixMyBerlin/key-value-db/blob/main/docs/API.md).
22
+
23
+ ## License
24
+
25
+ This package is [MIT](LICENSE). The key-value-db server in the same repo is AGPL-3.0.
@@ -0,0 +1,8 @@
1
+ import type { KvErrorCode } from './types.js';
2
+ export declare class KvError extends Error {
3
+ readonly status: number;
4
+ readonly code: KvErrorCode;
5
+ readonly details?: unknown;
6
+ constructor(status: number, code: KvErrorCode, message: string, details?: unknown);
7
+ }
8
+ export declare function kvErrorFromResponse(response: Response): Promise<KvError>;
package/dist/errors.js ADDED
@@ -0,0 +1,53 @@
1
+ const KV_ERROR_CODES = new Set([
2
+ 'invalid_project_key',
3
+ 'origin_not_allowed',
4
+ 'unauthenticated',
5
+ 'forbidden_user',
6
+ 'not_found',
7
+ 'validation_failed',
8
+ 'payload_too_large',
9
+ 'version_conflict',
10
+ 'rate_limited',
11
+ 'osm_unavailable',
12
+ 'internal',
13
+ ]);
14
+ export class KvError extends Error {
15
+ status;
16
+ code;
17
+ details;
18
+ constructor(status, code, message, details) {
19
+ super(message);
20
+ this.status = status;
21
+ this.code = code;
22
+ this.details = details;
23
+ this.name = 'KvError';
24
+ }
25
+ }
26
+ function asKvErrorCode(code) {
27
+ if (typeof code === 'string' && KV_ERROR_CODES.has(code)) {
28
+ return code;
29
+ }
30
+ return 'internal';
31
+ }
32
+ export async function kvErrorFromResponse(response) {
33
+ let code = 'internal';
34
+ let message = response.statusText || 'Request failed';
35
+ let details;
36
+ try {
37
+ const body = await response.json();
38
+ if (body !== null && typeof body === 'object' && 'error' in body) {
39
+ const err = body.error;
40
+ if (err !== null && typeof err === 'object') {
41
+ const envelope = err;
42
+ code = asKvErrorCode(envelope.code);
43
+ if (typeof envelope.message === 'string')
44
+ message = envelope.message;
45
+ details = envelope.details;
46
+ }
47
+ }
48
+ }
49
+ catch {
50
+ // Non-JSON error bodies still become a KvError with status.
51
+ }
52
+ return new KvError(response.status, code, message, details);
53
+ }
@@ -0,0 +1,5 @@
1
+ import { KvError } from './errors.js';
2
+ import type { KvClient, KvClientOptions } from './types.js';
3
+ export type { KvBatchResult, KvClient, KvClientOptions, KvEntry, KvErrorCode, KvListResult, KvUser, } from './types.js';
4
+ export { KvError };
5
+ export declare function createKvClient<T = unknown>(options: KvClientOptions): KvClient<T>;
package/dist/index.js ADDED
@@ -0,0 +1,138 @@
1
+ import { kvErrorFromResponse, KvError } from './errors.js';
2
+ import { assertBatch, assertDeleted, assertEntry, assertList, assertMe, assertTags, } from './validate.js';
3
+ export { KvError };
4
+ function trimTrailingSlashes(baseUrl) {
5
+ return baseUrl.replace(/\/+$/, '');
6
+ }
7
+ function projectUrl(baseUrl, project, ...segments) {
8
+ const parts = [
9
+ trimTrailingSlashes(baseUrl),
10
+ 'v1',
11
+ 'projects',
12
+ encodeURIComponent(project),
13
+ ...segments,
14
+ ];
15
+ return parts.join('/');
16
+ }
17
+ async function requestHeaders(apiKey, getOsmToken, extra) {
18
+ const headers = new Headers(extra);
19
+ headers.set('X-Api-Key', apiKey);
20
+ const token = await getOsmToken();
21
+ if (token != null) {
22
+ headers.set('Authorization', `Bearer ${token}`);
23
+ }
24
+ return headers;
25
+ }
26
+ async function parseJson(response, check) {
27
+ if (!response.ok) {
28
+ throw await kvErrorFromResponse(response);
29
+ }
30
+ const body = await response.json();
31
+ check(body);
32
+ return body;
33
+ }
34
+ async function parseEmpty(response) {
35
+ if (!response.ok) {
36
+ throw await kvErrorFromResponse(response);
37
+ }
38
+ }
39
+ export function createKvClient(options) {
40
+ const { apiKey, getOsmToken, project } = options;
41
+ const baseUrl = options.baseUrl;
42
+ const entriesCollection = () => projectUrl(baseUrl, project, 'entries');
43
+ const entryUrl = (id) => projectUrl(baseUrl, project, 'entries', encodeURIComponent(id));
44
+ const tagsUrl = () => projectUrl(baseUrl, project, 'tags');
45
+ const meUrl = () => projectUrl(baseUrl, project, 'me');
46
+ const batchUrl = () => projectUrl(baseUrl, project, 'batch');
47
+ return {
48
+ async list(params) {
49
+ const query = new URLSearchParams();
50
+ for (const tag of params?.tags ?? []) {
51
+ query.append('tag', tag);
52
+ }
53
+ if (params?.match !== undefined) {
54
+ query.set('match', params.match);
55
+ }
56
+ if (params?.updatedSince !== undefined) {
57
+ query.set('updated_since', params.updatedSince);
58
+ }
59
+ if (params?.limit !== undefined) {
60
+ query.set('limit', String(params.limit));
61
+ }
62
+ if (params?.cursor !== undefined) {
63
+ query.set('cursor', params.cursor);
64
+ }
65
+ const qs = query.toString();
66
+ const url = qs ? `${entriesCollection()}?${qs}` : entriesCollection();
67
+ const response = await fetch(url, {
68
+ method: 'GET',
69
+ headers: await requestHeaders(apiKey, getOsmToken),
70
+ });
71
+ return parseJson(response, assertList);
72
+ },
73
+ async get(id) {
74
+ const response = await fetch(entryUrl(id), {
75
+ method: 'GET',
76
+ headers: await requestHeaders(apiKey, getOsmToken),
77
+ });
78
+ return parseJson(response, assertEntry);
79
+ },
80
+ async put(id, data, tags = [], opts) {
81
+ const headers = await requestHeaders(apiKey, getOsmToken, {
82
+ 'Content-Type': 'application/json',
83
+ });
84
+ if (opts?.ifMatch !== undefined) {
85
+ headers.set('If-Match', opts.ifMatch);
86
+ }
87
+ const response = await fetch(entryUrl(id), {
88
+ method: 'PUT',
89
+ headers,
90
+ body: JSON.stringify({ data, tags }),
91
+ });
92
+ return parseJson(response, assertEntry);
93
+ },
94
+ async remove(id) {
95
+ const response = await fetch(entryUrl(id), {
96
+ method: 'DELETE',
97
+ headers: await requestHeaders(apiKey, getOsmToken),
98
+ });
99
+ await parseEmpty(response);
100
+ },
101
+ async tags() {
102
+ const response = await fetch(tagsUrl(), {
103
+ method: 'GET',
104
+ headers: await requestHeaders(apiKey, getOsmToken),
105
+ });
106
+ return parseJson(response, assertTags);
107
+ },
108
+ async batch(ops) {
109
+ const response = await fetch(batchUrl(), {
110
+ method: 'POST',
111
+ headers: await requestHeaders(apiKey, getOsmToken, { 'Content-Type': 'application/json' }),
112
+ body: JSON.stringify({ put: ops.put ?? [], delete: ops.delete ?? [] }),
113
+ });
114
+ return parseJson(response, assertBatch);
115
+ },
116
+ async removeMine() {
117
+ const response = await fetch(`${meUrl()}/entries`, {
118
+ method: 'DELETE',
119
+ headers: await requestHeaders(apiKey, getOsmToken),
120
+ });
121
+ return parseJson(response, assertDeleted);
122
+ },
123
+ async me() {
124
+ const response = await fetch(meUrl(), {
125
+ method: 'GET',
126
+ headers: await requestHeaders(apiKey, getOsmToken),
127
+ });
128
+ return parseJson(response, assertMe);
129
+ },
130
+ async forget() {
131
+ const response = await fetch(meUrl(), {
132
+ method: 'DELETE',
133
+ headers: await requestHeaders(apiKey, getOsmToken),
134
+ });
135
+ await parseEmpty(response);
136
+ },
137
+ };
138
+ }
@@ -0,0 +1,69 @@
1
+ export type KvErrorCode = 'invalid_project_key' | 'origin_not_allowed' | 'unauthenticated' | 'forbidden_user' | 'not_found' | 'validation_failed' | 'payload_too_large' | 'version_conflict' | 'rate_limited' | 'osm_unavailable' | 'internal';
2
+ export type KvUser = {
3
+ osm_uid: number;
4
+ display_name: string;
5
+ };
6
+ export type KvEntry<T> = {
7
+ id: string;
8
+ data: T;
9
+ tags: string[];
10
+ version: number;
11
+ created_at: string;
12
+ updated_at: string;
13
+ created_by: KvUser;
14
+ updated_by: KvUser;
15
+ /** ISO time the entry expires (projects with entry_ttl_s); null or absent = never. */
16
+ expires_at?: string | null;
17
+ };
18
+ export type KvListResult<T> = {
19
+ items: Array<KvEntry<T>>;
20
+ next_cursor: string | null;
21
+ };
22
+ export type KvClientOptions = {
23
+ baseUrl: string;
24
+ project: string;
25
+ apiKey: string;
26
+ getOsmToken: () => string | null | Promise<string | null>;
27
+ };
28
+ export type KvClient<T> = {
29
+ list(params?: {
30
+ tags?: string[];
31
+ match?: 'all' | 'any';
32
+ updatedSince?: string;
33
+ limit?: number;
34
+ cursor?: string;
35
+ }): Promise<KvListResult<T>>;
36
+ get(id: string): Promise<KvEntry<T>>;
37
+ put(id: string, data: T, tags?: string[], opts?: {
38
+ ifMatch?: string;
39
+ }): Promise<KvEntry<T>>;
40
+ remove(id: string): Promise<void>;
41
+ tags(): Promise<{
42
+ tags: Array<{
43
+ tag: string;
44
+ count: number;
45
+ }>;
46
+ }>;
47
+ /** Up to 25 puts and 50 deletes in one atomic call. Deleting an absent id is not an error. */
48
+ batch(ops: {
49
+ put?: Array<{
50
+ id: string;
51
+ data: T;
52
+ tags?: string[];
53
+ }>;
54
+ delete?: string[];
55
+ }): Promise<KvBatchResult<T>>;
56
+ me(): Promise<{
57
+ user: KvUser;
58
+ can_write: boolean;
59
+ }>;
60
+ /** "Delete my data" for this project: removes every entry the user created here. */
61
+ removeMine(): Promise<{
62
+ deleted: number;
63
+ }>;
64
+ forget(): Promise<void>;
65
+ };
66
+ export type KvBatchResult<T> = {
67
+ put: Array<KvEntry<T>>;
68
+ deleted: number;
69
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { KvBatchResult, KvEntry, KvListResult, KvUser } from './types.js';
2
+ export declare function assertEntry<T>(v: unknown): asserts v is KvEntry<T>;
3
+ export declare function assertList<T>(v: unknown): asserts v is KvListResult<T>;
4
+ export declare function assertBatch<T>(v: unknown): asserts v is KvBatchResult<T>;
5
+ export declare function assertTags(v: unknown): asserts v is {
6
+ tags: Array<{
7
+ tag: string;
8
+ count: number;
9
+ }>;
10
+ };
11
+ export declare function assertMe(v: unknown): asserts v is {
12
+ user: KvUser;
13
+ can_write: boolean;
14
+ };
15
+ export declare function assertDeleted(v: unknown): asserts v is {
16
+ deleted: number;
17
+ };
@@ -0,0 +1,57 @@
1
+ import { KvError } from './errors.js';
2
+ // Small hand-written checks for the response envelopes, so the client stays
3
+ // dependency-free. `data` is not checked: each app validates its own payload.
4
+ const isObject = (v) => typeof v === 'object' && v !== null;
5
+ function invalid(what) {
6
+ return new KvError(200, 'internal', `Unexpected response from the KV API: ${what}`);
7
+ }
8
+ function assertUser(v, what) {
9
+ if (!isObject(v) || typeof v.osm_uid !== 'number' || typeof v.display_name !== 'string') {
10
+ throw invalid(what);
11
+ }
12
+ }
13
+ export function assertEntry(v) {
14
+ if (!isObject(v) ||
15
+ typeof v.id !== 'string' ||
16
+ !('data' in v) ||
17
+ !Array.isArray(v.tags) ||
18
+ !v.tags.every((t) => typeof t === 'string') ||
19
+ typeof v.version !== 'number' ||
20
+ typeof v.created_at !== 'string' ||
21
+ typeof v.updated_at !== 'string' ||
22
+ (v.expires_at !== undefined && v.expires_at !== null && typeof v.expires_at !== 'string')) {
23
+ throw invalid('entry');
24
+ }
25
+ assertUser(v.created_by, 'entry.created_by');
26
+ assertUser(v.updated_by, 'entry.updated_by');
27
+ }
28
+ export function assertList(v) {
29
+ if (!isObject(v) || !Array.isArray(v.items))
30
+ throw invalid('list');
31
+ if (v.next_cursor !== null && typeof v.next_cursor !== 'string')
32
+ throw invalid('list.next_cursor');
33
+ for (const item of v.items)
34
+ assertEntry(item);
35
+ }
36
+ export function assertBatch(v) {
37
+ if (!isObject(v) || !Array.isArray(v.put) || typeof v.deleted !== 'number')
38
+ throw invalid('batch');
39
+ for (const item of v.put)
40
+ assertEntry(item);
41
+ }
42
+ export function assertTags(v) {
43
+ if (!isObject(v) ||
44
+ !Array.isArray(v.tags) ||
45
+ !v.tags.every((t) => isObject(t) && typeof t.tag === 'string' && typeof t.count === 'number')) {
46
+ throw invalid('tags');
47
+ }
48
+ }
49
+ export function assertMe(v) {
50
+ if (!isObject(v) || typeof v.can_write !== 'boolean')
51
+ throw invalid('me');
52
+ assertUser(v.user, 'me.user');
53
+ }
54
+ export function assertDeleted(v) {
55
+ if (!isObject(v) || typeof v.deleted !== 'number')
56
+ throw invalid('deleted');
57
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@osm-editor-kit/key-value-db-client",
3
+ "version": "0.0.0",
4
+ "description": "Typed, dependency-free fetch client for key-value-db: a shared key-value API for OpenStreetMap-authenticated apps (Cloudflare Workers + D1).",
5
+ "keywords": [
6
+ "client",
7
+ "cloudflare",
8
+ "d1",
9
+ "key-value",
10
+ "openstreetmap",
11
+ "osm"
12
+ ],
13
+ "homepage": "https://github.com/FixMyBerlin/key-value-db/tree/main/packages/kv-client#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/FixMyBerlin/key-value-db/issues"
16
+ },
17
+ "license": "MIT",
18
+ "author": "Tobias Jordans",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/FixMyBerlin/key-value-db.git",
22
+ "directory": "packages/kv-client"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "source": "./src/index.ts",
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "provenance": true
40
+ },
41
+ "scripts": {
42
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
43
+ "check-exports": "attw --pack . --ignore-rules cjs-resolves-to-esm no-resolution --profile node16",
44
+ "prepublishOnly": "bun run build",
45
+ "type-check": "tsc --noEmit -p tsconfig.json",
46
+ "test-run": "vitest run --passWithNoTests"
47
+ },
48
+ "devDependencies": {
49
+ "@types/bun": "^1.3.0",
50
+ "vitest": "^4.1.0"
51
+ },
52
+ "engines": {
53
+ "node": ">=18"
54
+ }
55
+ }