dserver-client 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/CHANGELOG.md ADDED
@@ -0,0 +1,56 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+
9
+ ## [0.1.0] - 2026-11-30
10
+
11
+ First release on npm.
12
+
13
+ ### Added
14
+
15
+ - `DServerClient` for dserver's REST API, with a JWT token (`setToken()`):
16
+ - Search: `searchDatasets()` with free text and filters (creators, base
17
+ URIs, UUIDs, tags, uploaders), pagination and sorting; the
18
+ `X-Pagination` header is parsed into `{ total, page, per_page, pages }`
19
+ (`parsePaginationHeader()`), also in flask-smorest's format.
20
+ - Datasets: `getManifest()`, `getReadme()`, `setReadme()`,
21
+ `getDatasetsByUuid()`.
22
+ - Tags and annotations: `getTags()`, `setTags()`, `addTag()`,
23
+ `removeTag()`, `getAnnotations()`, `setAnnotations()`,
24
+ `setAnnotation()`, `deleteAnnotation()`.
25
+ - Users and administration: `getMe()`, `getMySummary()`,
26
+ `getUserSummary()`, `getCurrentUser()`, `listUsers()`, `getUser()`,
27
+ `createUser()`, `updateUser()` (e.g. the display name),
28
+ `updateUserAdmin()`, `deleteUser()`; base URIs and search/register
29
+ permissions (`listBaseURIs()`, `createBaseURI()`, `deleteBaseURI()`,
30
+ `grantSearchPermission()`, `revokeSearchPermission()`,
31
+ `grantRegisterPermission()`, `revokeRegisterPermission()`).
32
+ - Server: `getServerVersions()`, `checkHealth()`.
33
+ - Dependency graphs (dserver dependency graph plugin):
34
+ `getDependencyGraph()` returns every dataset of the graph (all pages),
35
+ each with `derived_from`, using the server's dependency keys unless
36
+ custom keys are given.
37
+ - Signed URLs (dserver signed URL plugin): `getDatasetSignedUrls()`,
38
+ `getItemSignedUrl()`, downloads of items, manifest, admin metadata,
39
+ README, overlays and annotations, and `createDataset()` to upload a
40
+ dataset (`getUploadUrls()`, `signalUploadComplete()`), with progress
41
+ callbacks and cancellation via `AbortController`.
42
+ - Typed errors: `DServerError`, `AuthenticationError` (401),
43
+ `AuthorizationError` (403), `NotFoundError` (404).
44
+ - TypeScript type definitions for requests and responses, among them
45
+ `uploaded_by`/`uploaded_at` of datasets.
46
+ - Utilities: `generateIdentifier()` (dtool item identifiers, SHA-1),
47
+ `generateUUID()`, `encodeUri()`, expiry helpers, `formatBytes()`,
48
+ `withRetry()`, `chunk()`, `parallelLimit()`.
49
+ - Vue 3 composables in the separate entry point `dserver-client/vue`:
50
+ `useDServerClient()`, `useDatasetDownload()`, `useDatasetUpload()`. Vue is
51
+ an optional peer dependency; the client itself works without it.
52
+ - ES module and CommonJS builds with type declarations, for browsers and
53
+ Node.js 20 or later. Built with tsdown; TypeScript 7 does the type checking
54
+ (tools that need TypeScript's JavaScript API use TypeScript 6 through
55
+ `@typescript/typescript6`).
56
+ - Publishing to npm from GitHub releases, with provenance.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 livMatS
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,347 @@
1
- # Temporary Holding Version
1
+ # dserver-client
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
+ TypeScript/JavaScript client for [dserver](https://github.com/jic-dtool/dservercore),
4
+ the REST API for the metadata of [dtool](https://github.com/jic-dtool/dtool)
5
+ datasets. It is used by the dserver web interface,
6
+ [dserver-webapp](https://github.com/jic-dtool/dserver-webapp).
7
+
8
+ ## Features
9
+
10
+ - **Search and browse datasets**: search with free text and filters,
11
+ manifests, READMEs, server versions, user summaries
12
+ - **Edit metadata**: tags, annotations, READMEs
13
+ - **Administration**: users, base URIs, search and register permissions
14
+ - **Dependency graphs** (dserver dependency graph plugin)
15
+ - **Download and upload datasets** through signed URLs (dserver signed URL
16
+ plugin), without credentials for the storage backend, with progress
17
+ callbacks and cancellation via `AbortController`
18
+ - **TypeScript-first** with full type definitions; ES module and CommonJS
19
+ - **Browser and Node.js** (20 or later), uses the native `fetch`
20
+ - **Vue 3 composables** in the separate entry point `dserver-client/vue`
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install dserver-client
26
+ ```
27
+
28
+ Vue is an optional peer dependency, needed only for `dserver-client/vue`.
29
+
30
+ ## Searching and Editing Metadata
31
+
32
+ ```typescript
33
+ import { DServerClient } from 'dserver-client';
34
+
35
+ const client = new DServerClient({ baseUrl: 'https://dserver.example.com', token });
36
+
37
+ const { data, pagination } = await client.searchDatasets(
38
+ { free_text: 'topography', tags: ['raw'] },
39
+ { page: 1, page_size: 10, sort: '-frozen_at' },
40
+ );
41
+ for (const dataset of data) console.log(dataset.uri, dataset.name);
42
+
43
+ await client.addTag(data[0].uri, 'reviewed');
44
+ await client.setAnnotation(data[0].uri, 'project', 'demo');
45
+ const graph = await client.getDependencyGraph(data[0].uuid);
46
+ ```
47
+
48
+ Further methods cover READMEs and manifests (`getReadme`, `setReadme`,
49
+ `getManifest`), tags and annotations (`getTags`, `setTags`, `removeTag`,
50
+ `getAnnotations`, `setAnnotations`, `deleteAnnotation`), the current user
51
+ (`getMe`, `getMySummary`), administration (`listUsers`, `createUser`,
52
+ `updateUser`, `listBaseURIs`, `grantSearchPermission`, ...) and the server
53
+ (`getServerVersions`, `checkHealth`). See the type definitions for details.
54
+
55
+ ## Quick Start
56
+
57
+ ### Reading a Dataset
58
+
59
+ ```typescript
60
+ import { DServerClient } from 'dserver-client';
61
+
62
+ // Initialize client with your dserver URL and JWT token
63
+ const client = new DServerClient({
64
+ baseUrl: 'http://localhost:5000',
65
+ token: 'your-jwt-token'
66
+ });
67
+
68
+ // Get signed URLs for a dataset
69
+ const urls = await client.getDatasetSignedUrls('s3://bucket/dataset-uuid');
70
+
71
+ // Download the manifest
72
+ const manifest = await client.downloadManifest(urls);
73
+ console.log('Items:', Object.keys(manifest.items).length);
74
+
75
+ // Download a specific item
76
+ const itemId = Object.keys(manifest.items)[0];
77
+ const content = await client.downloadItem(urls, itemId, {
78
+ onProgress: (loaded, total) => {
79
+ console.log(`Progress: ${Math.round(loaded/total*100)}%`);
80
+ }
81
+ });
82
+
83
+ // Content is an ArrayBuffer - convert as needed
84
+ const text = new TextDecoder().decode(content);
85
+ ```
86
+
87
+ ### Uploading a Dataset
88
+
89
+ ```typescript
90
+ import { DServerClient } from 'dserver-client';
91
+
92
+ const client = new DServerClient({
93
+ baseUrl: 'http://localhost:5000',
94
+ token: 'your-jwt-token'
95
+ });
96
+
97
+ // Prepare files to upload
98
+ const files = [
99
+ {
100
+ relpath: 'data/experiment1.csv',
101
+ content: 'id,value\n1,100\n2,200',
102
+ contentType: 'text/csv'
103
+ },
104
+ {
105
+ relpath: 'data/experiment2.csv',
106
+ content: await fetch('/local/file.csv').then(r => r.blob())
107
+ }
108
+ ];
109
+
110
+ // Create and upload the dataset
111
+ const result = await client.createDataset(
112
+ 's3://my-bucket',
113
+ 'my-experiment-data',
114
+ files,
115
+ {
116
+ readme: '---\ndescription: Experiment results\nauthor: Jane Doe\n',
117
+ onProgress: (uploaded, total, currentFile) => {
118
+ console.log(`Uploading ${currentFile}: ${Math.round(uploaded/total*100)}%`);
119
+ }
120
+ }
121
+ );
122
+
123
+ console.log('Dataset created:', result.uri);
124
+ ```
125
+
126
+ ## API Reference
127
+
128
+ ### `DServerClient`
129
+
130
+ The main client class for interacting with dserver.
131
+
132
+ #### Constructor
133
+
134
+ ```typescript
135
+ const client = new DServerClient({
136
+ baseUrl: string, // dserver URL (e.g., "http://localhost:5000")
137
+ token?: string, // JWT authentication token
138
+ fetch?: typeof fetch // Optional custom fetch implementation
139
+ });
140
+ ```
141
+
142
+ #### Methods
143
+
144
+ ##### `getDatasetSignedUrls(uri: string): Promise<DatasetSignedURLsResponse>`
145
+
146
+ Get signed URLs for reading all components of a dataset.
147
+
148
+ ```typescript
149
+ const urls = await client.getDatasetSignedUrls('s3://bucket/uuid');
150
+ // urls.manifest_url, urls.readme_url, urls.item_urls, etc.
151
+ ```
152
+
153
+ ##### `getItemSignedUrl(uri: string, identifier: string): Promise<ItemSignedURLResponse>`
154
+
155
+ Get a signed URL for a single item (more efficient for single-item access).
156
+
157
+ ```typescript
158
+ const itemUrl = await client.getItemSignedUrl('s3://bucket/uuid', 'abc123...');
159
+ ```
160
+
161
+ ##### `downloadItem(urls, identifier, options?): Promise<ArrayBuffer>`
162
+
163
+ Download an item using the signed URLs.
164
+
165
+ ```typescript
166
+ const content = await client.downloadItem(urls, identifier, {
167
+ onProgress: (loaded, total) => console.log(`${loaded}/${total}`),
168
+ signal: abortController.signal
169
+ });
170
+ ```
171
+
172
+ ##### `downloadManifest(urls): Promise<Manifest>`
173
+
174
+ Download and parse the dataset manifest.
175
+
176
+ ##### `downloadAdminMetadata(urls): Promise<AdminMetadata>`
177
+
178
+ Download and parse the admin metadata.
179
+
180
+ ##### `downloadReadme(urls): Promise<string>`
181
+
182
+ Download the README as a string.
183
+
184
+ ##### `createDataset(baseUri, name, files, options?): Promise<UploadCompleteResponse>`
185
+
186
+ Create and upload a new dataset.
187
+
188
+ ```typescript
189
+ const result = await client.createDataset(
190
+ 's3://bucket',
191
+ 'my-dataset',
192
+ [
193
+ { relpath: 'file.txt', content: 'Hello World' }
194
+ ],
195
+ {
196
+ readme: '---\ndescription: My dataset\n',
197
+ onProgress: (uploaded, total, file) => { ... }
198
+ }
199
+ );
200
+ ```
201
+
202
+ ### Types
203
+
204
+ #### `DatasetSignedURLsResponse`
205
+
206
+ ```typescript
207
+ interface DatasetSignedURLsResponse {
208
+ uri: string;
209
+ expiry_seconds: number;
210
+ expiry_timestamp: string;
211
+ admin_metadata_url: string;
212
+ manifest_url: string;
213
+ readme_url: string;
214
+ item_urls: Record<string, string>;
215
+ overlay_urls: Record<string, string>;
216
+ annotation_urls: Record<string, string>;
217
+ tags: string[];
218
+ }
219
+ ```
220
+
221
+ #### `FileToUpload`
222
+
223
+ ```typescript
224
+ interface FileToUpload {
225
+ relpath: string; // Path within dataset
226
+ content: Blob | ArrayBuffer | string; // File content
227
+ contentType?: string; // MIME type
228
+ }
229
+ ```
230
+
231
+ #### `UploadOptions`
232
+
233
+ ```typescript
234
+ interface UploadOptions {
235
+ onProgress?: (loaded: number, total: number, item?: string) => void;
236
+ signal?: AbortSignal;
237
+ readme?: string;
238
+ annotations?: Record<string, unknown>;
239
+ tags?: string[];
240
+ }
241
+ ```
242
+
243
+ ### Utilities
244
+
245
+ The package exports several utility functions:
246
+
247
+ ```typescript
248
+ import {
249
+ generateIdentifier, // Generate SHA-1 identifier from relpath
250
+ generateUUID, // Generate UUID v4
251
+ encodeUri, // URL-encode a URI
252
+ isExpired, // Check if signed URL has expired
253
+ timeUntilExpiry, // Seconds until expiry
254
+ formatBytes, // Human-readable byte size
255
+ withRetry, // Retry with exponential backoff
256
+ parallelLimit // Run promises with concurrency limit
257
+ } from 'dserver-client';
258
+ ```
259
+
260
+ ## Error Handling
261
+
262
+ The client throws typed errors for different failure cases:
263
+
264
+ ```typescript
265
+ import {
266
+ DServerError,
267
+ AuthenticationError,
268
+ AuthorizationError,
269
+ NotFoundError
270
+ } from 'dserver-client';
271
+
272
+ try {
273
+ await client.getDatasetSignedUrls('s3://bucket/uuid');
274
+ } catch (error) {
275
+ if (error instanceof AuthenticationError) {
276
+ // Token is invalid or expired
277
+ console.log('Please log in again');
278
+ } else if (error instanceof AuthorizationError) {
279
+ // User doesn't have permission
280
+ console.log('Access denied');
281
+ } else if (error instanceof NotFoundError) {
282
+ // Dataset doesn't exist
283
+ console.log('Dataset not found');
284
+ } else if (error instanceof DServerError) {
285
+ // Other API error
286
+ console.log('Error:', error.message, error.status);
287
+ }
288
+ }
289
+ ```
290
+
291
+ ## Cancellation
292
+
293
+ Use `AbortController` to cancel long-running operations:
294
+
295
+ ```typescript
296
+ const controller = new AbortController();
297
+
298
+ // Start download
299
+ const downloadPromise = client.downloadItem(urls, identifier, {
300
+ signal: controller.signal
301
+ });
302
+
303
+ // Cancel after 5 seconds
304
+ setTimeout(() => controller.abort(), 5000);
305
+
306
+ try {
307
+ await downloadPromise;
308
+ } catch (error) {
309
+ if (error.name === 'AbortError') {
310
+ console.log('Download cancelled');
311
+ }
312
+ }
313
+ ```
314
+
315
+ ## Vue.js Integration
316
+
317
+ Vue 3 composables with reactive state (loading, errors, progress):
318
+
319
+ ```typescript
320
+ import { useDServerClient, useDatasetDownload, useDatasetUpload } from 'dserver-client/vue';
321
+
322
+ const { client } = useDServerClient({ baseUrl: 'https://dserver.example.com', token });
323
+ const { loadDataset, manifest, progress } = useDatasetDownload(client);
324
+ const { uploadDataset, progressPercent } = useDatasetUpload(client);
325
+ ```
326
+
327
+ ## Browser Support
328
+
329
+ The client uses standard Web APIs:
330
+ - `fetch` - for HTTP requests
331
+ - `crypto.subtle` - for SHA-1 identifier generation
332
+ - `TextEncoder`/`TextDecoder` - for string encoding
333
+
334
+ Supported in all modern browsers (Chrome 63+, Firefox 57+, Safari 11.1+, Edge 79+).
335
+
336
+ Node.js 20 or later.
337
+
338
+ ## Releasing
339
+
340
+ 1. Update the version in `package.json` and the changelog, merge to `main`.
341
+ 2. Publish a GitHub release with the version as tag (e.g. `0.1.0`). The
342
+ `publish` workflow tests the package and publishes it to npm with
343
+ provenance, authenticated by npm trusted publishing.
344
+
345
+ ## License
346
+
347
+ MIT