@covia/covia-sdk 1.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/dist/index.mjs ADDED
@@ -0,0 +1,463 @@
1
+ import { Resolver } from 'did-resolver';
2
+ import { getResolver } from 'web-did-resolver';
3
+
4
+ // src/types.ts
5
+ var RunStatus = /* @__PURE__ */ ((RunStatus2) => {
6
+ RunStatus2["COMPLETE"] = "COMPLETE";
7
+ RunStatus2["FAILED"] = "FAILED";
8
+ RunStatus2["PENDING"] = "PENDING";
9
+ RunStatus2["STARTED"] = "STARTED";
10
+ RunStatus2["CANCELLED"] = "CANCELLED";
11
+ RunStatus2["TIMEOUT"] = "TIMEOUT";
12
+ RunStatus2["REJECTED"] = "REJECTED";
13
+ RunStatus2["INPUT_REQUIRED"] = "INPUT_REQUIRED";
14
+ RunStatus2["AUTH_REQUIRED"] = "AUTH_REQUIRED";
15
+ RunStatus2["PAUSED"] = "PAUSED";
16
+ return RunStatus2;
17
+ })(RunStatus || {});
18
+ var CoviaError = class extends Error {
19
+ constructor(message, code = null) {
20
+ super(message);
21
+ this.name = "CoviaError";
22
+ this.code = code;
23
+ this.message = message;
24
+ }
25
+ };
26
+
27
+ // src/Credentials.ts
28
+ var CredentialsHTTP = class {
29
+ constructor(venueId, apiKey, userId) {
30
+ this.venueId = venueId;
31
+ this.apiKey = apiKey;
32
+ this.userId = userId;
33
+ }
34
+ };
35
+
36
+ // src/Utils.ts
37
+ function fetchWithError(url, options) {
38
+ return fetch(url, options).then((response) => {
39
+ if (!response.ok) {
40
+ throw new CoviaError(`Request failed! status: ${response.status}`);
41
+ }
42
+ return response.json();
43
+ }).catch((error) => {
44
+ throw error instanceof CoviaError ? error : new CoviaError(`Request failed: ${error.message}`);
45
+ });
46
+ }
47
+ function fetchStreamWithError(url, options) {
48
+ return fetch(url, options).then((response) => {
49
+ if (!response.ok) {
50
+ throw new CoviaError(`Request failed! status: ${response.status}`);
51
+ }
52
+ return response;
53
+ }).catch((error) => {
54
+ throw error instanceof CoviaError ? error : new CoviaError(`Request failed: ${error.message}`);
55
+ });
56
+ }
57
+ function isJobComplete(jobStatus) {
58
+ if (jobStatus == null)
59
+ return false;
60
+ return jobStatus == "COMPLETE" /* COMPLETE */ ? true : false;
61
+ }
62
+ function isJobPaused(jobStatus) {
63
+ if (jobStatus == null)
64
+ return false;
65
+ return jobStatus == "PAUSED" /* PAUSED */ ? true : false;
66
+ }
67
+ function isJobFinished(jobStatus) {
68
+ if (jobStatus == null)
69
+ return false;
70
+ if (jobStatus == "COMPLETE" /* COMPLETE */) return true;
71
+ if (jobStatus == "FAILED" /* FAILED */) return true;
72
+ if (jobStatus == "REJECTED" /* REJECTED */) return true;
73
+ if (jobStatus == "CANCELLED" /* CANCELLED */) return true;
74
+ return false;
75
+ }
76
+ function getParsedAssetId(assetId) {
77
+ if (assetId.startsWith("did:web")) {
78
+ const parts = assetId.split("/");
79
+ return parts[parts.length - 1];
80
+ }
81
+ return assetId;
82
+ }
83
+ function getAssetIdFromPath(assetHex, assetPath) {
84
+ const venueDid = decodeURIComponent(assetPath.split("/")[4]);
85
+ return venueDid + "/a/" + assetHex;
86
+ }
87
+ function getAssetIdFromVenueId(assetHex, venueId) {
88
+ return venueId + "/a/" + assetHex;
89
+ }
90
+
91
+ // src/Asset.ts
92
+ var cache = /* @__PURE__ */ new Map();
93
+ var Asset = class {
94
+ constructor(id, venue, metadata = {}) {
95
+ this.id = id;
96
+ this.venue = venue;
97
+ this.metadata = metadata;
98
+ }
99
+ /**
100
+ * Get asset metadata
101
+ * @returns {Promise<AssetMetadata>}
102
+ */
103
+ async getMetadata() {
104
+ if (cache.has(this.id)) {
105
+ return Promise.resolve(cache.get(this.id));
106
+ } else {
107
+ const data = this.venue.getMetadata(this.id);
108
+ if (data) {
109
+ cache.set(this.id, data);
110
+ }
111
+ return data;
112
+ }
113
+ }
114
+ /**
115
+ * Read stream from asset
116
+ * @param reader - ReadableStreamDefaultReader
117
+ */
118
+ async readStream(reader) {
119
+ return this.readStream(reader);
120
+ }
121
+ /**
122
+ * Upload content to asset
123
+ * @param content - Content to upload
124
+ * @returns {Promise<ReadableStream<Uint8Array> | null>}
125
+ */
126
+ uploadContent(content) {
127
+ return this.venue.uploadContent(this.id, content);
128
+ }
129
+ /**
130
+ * Get asset content
131
+ * @returns {Promise<ReadableStream<Uint8Array> | null>}
132
+ */
133
+ getContent() {
134
+ return this.venue.getContent(this.id);
135
+ }
136
+ /**
137
+ * Get the URL for downloading asset content
138
+ * @returns {string} The URL for downloading the asset content
139
+ */
140
+ getContentURL() {
141
+ return `${this.venue.baseUrl}/api/v1/assets/${this.id}/content`;
142
+ }
143
+ /**
144
+ * Execute the operation
145
+ * @param input - Operation input parameters
146
+ * @returns {Promise<any>}
147
+ */
148
+ run(input) {
149
+ return this.venue.run(this.id, input);
150
+ }
151
+ /**
152
+ * Execute the operation
153
+ * @param input - Operation input parameters
154
+ * @returns {Promise<any>}
155
+ */
156
+ invoke(input) {
157
+ return this.venue.invoke(this.id, input);
158
+ }
159
+ };
160
+
161
+ // src/Operation.ts
162
+ var Operation = class extends Asset {
163
+ constructor(id, venue, metadata = {}) {
164
+ super(id, venue, metadata);
165
+ }
166
+ // Operation-specific methods can be added here
167
+ // For now, it inherits all functionality from Asset
168
+ };
169
+
170
+ // src/DataAsset.ts
171
+ var DataAsset = class extends Asset {
172
+ constructor(id, venue, metadata = {}) {
173
+ super(id, venue, metadata);
174
+ }
175
+ // DataAsset-specific methods can be added here
176
+ // For now, it inherits all functionality from Asset
177
+ };
178
+
179
+ // src/Job.ts
180
+ var Job = class {
181
+ constructor(id, venue, metadata) {
182
+ this.id = id;
183
+ this.venue = venue;
184
+ this.metadata = metadata;
185
+ }
186
+ /**
187
+ * Cancels the execution of the job
188
+ * @returns {Promise<number>}
189
+ */
190
+ async cancelJob() {
191
+ return this.venue.cancelJob(this.id);
192
+ }
193
+ /**
194
+ * Delete the job
195
+ * @returns {Promise<number>}
196
+ */
197
+ async deleteJob() {
198
+ return this.venue.deleteJob(this.id);
199
+ }
200
+ };
201
+
202
+ // src/Venue.ts
203
+ var webResolver = getResolver();
204
+ var resolver = new Resolver(webResolver);
205
+ var cache2 = /* @__PURE__ */ new Map();
206
+ var Venue = class _Venue {
207
+ constructor(options = {}) {
208
+ this.baseUrl = options.baseUrl || "";
209
+ this.venueId = options.venueId || "";
210
+ this.credentials = options.credentials || new CredentialsHTTP(this.venueId, "", "");
211
+ this.metadata = {
212
+ name: options.name || "default",
213
+ description: options.description || ""
214
+ };
215
+ }
216
+ /**
217
+ * Static method to connect to a venue
218
+ * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
219
+ * @param credentials - Optional credentials for venue authentication
220
+ * @returns {Promise<Venue>} A new Venue instance configured appropriately
221
+ */
222
+ static async connect(venueId, credentials) {
223
+ if (venueId instanceof _Venue) {
224
+ return new _Venue({
225
+ baseUrl: venueId.baseUrl,
226
+ venueId: venueId.venueId,
227
+ name: venueId.metadata.name,
228
+ credentials
229
+ });
230
+ }
231
+ if (typeof venueId === "string") {
232
+ let baseUrl;
233
+ if (venueId.startsWith("http:") || venueId.startsWith("https:")) {
234
+ baseUrl = venueId;
235
+ if (baseUrl.endsWith("/"))
236
+ baseUrl = baseUrl.substring(0, baseUrl.length - 1);
237
+ } else if (venueId.startsWith("did:web:")) {
238
+ const didDoc = await resolver.resolve(venueId);
239
+ if (!didDoc.didDocument) {
240
+ throw new CoviaError("Invalid DID document");
241
+ }
242
+ const endpoint = didDoc.didDocument.service?.find((service) => service.type === "Covia.API.v1")?.serviceEndpoint;
243
+ if (!endpoint) {
244
+ throw new CoviaError("No endpoint found for DID");
245
+ }
246
+ baseUrl = endpoint.toString().replace(/\/api\/v1/, "");
247
+ } else {
248
+ baseUrl = `https://${venueId}`;
249
+ }
250
+ const data = await fetchWithError(baseUrl + "/api/v1/status");
251
+ return new _Venue({
252
+ baseUrl,
253
+ venueId: data.did,
254
+ name: data.name,
255
+ credentials
256
+ });
257
+ }
258
+ throw new CoviaError("Invalid venue ID parameter. Must be a string (URL/DNS) or Venue instance.");
259
+ }
260
+ /**
261
+ * Create a new asset
262
+ * @param assetData - Asset configuration
263
+ * @returns {Promise<Asset>}
264
+ */
265
+ async createAsset(assetData) {
266
+ return fetchWithError(`${this.baseUrl}/api/v1/assets/`, {
267
+ method: "POST",
268
+ headers: this.setCredentialsInHeader(),
269
+ body: JSON.stringify(assetData)
270
+ }).then((response) => {
271
+ return this.getAsset(response);
272
+ });
273
+ }
274
+ /**
275
+ * Read stream from asset
276
+ * @param reader - ReadableStreamDefaultReader
277
+ */
278
+ async readStream(reader) {
279
+ while (true) {
280
+ const { done, value } = await reader.read();
281
+ if (done) {
282
+ break;
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * Get asset by ID
288
+ * @param assetId - Asset identifier
289
+ * @returns {Promise<Asset>} Returns either an Operation or DataAsset based on the asset's metadata
290
+ */
291
+ async getAsset(assetId) {
292
+ if (cache2.has(assetId)) {
293
+ const cachedData = cache2.get(assetId);
294
+ if (cachedData.metadata?.operation) {
295
+ return new Operation(assetId, this, cachedData);
296
+ } else {
297
+ return new DataAsset(assetId, this, cachedData);
298
+ }
299
+ } else {
300
+ return fetchWithError(`${this.baseUrl}/api/v1/assets/${assetId}`).then((data) => {
301
+ cache2.set(assetId, data);
302
+ if (data.metadata?.operation) {
303
+ return new Operation(assetId, this, data);
304
+ } else {
305
+ return new DataAsset(assetId, this, data);
306
+ }
307
+ });
308
+ }
309
+ }
310
+ /**
311
+ * Get all assets
312
+ * @returns {Promise<Asset[]>}
313
+ */
314
+ getAssets() {
315
+ return fetchWithError(`${this.baseUrl}/api/v1/assets/`).then((assetIds) => {
316
+ const assetPromises = assetIds.items.map((assetId) => this.getAsset(assetId));
317
+ return Promise.all(assetPromises);
318
+ });
319
+ }
320
+ /**
321
+ * Get all jobs
322
+ * @returns {Promise<string[]>}
323
+ */
324
+ async getJobs() {
325
+ return fetchWithError(`${this.baseUrl}/api/v1/jobs`);
326
+ }
327
+ /**
328
+ * Get job by ID
329
+ * @param jobId - Job identifier
330
+ * @returns {Promise<Job>}
331
+ */
332
+ async getJob(jobId) {
333
+ return fetchWithError(`${this.baseUrl}/api/v1/jobs/${jobId}`).then((data) => {
334
+ return new Job(jobId, this, data);
335
+ });
336
+ }
337
+ /**
338
+ * Cancel job by ID
339
+ * @param jobId - Job identifier
340
+ * @returns {Promise<number>}
341
+ */
342
+ async cancelJob(jobId) {
343
+ return fetchStreamWithError(`${this.baseUrl}/api/v1/jobs/${jobId}/cancel`, { method: "PUT" }).then((response) => {
344
+ return response.status;
345
+ });
346
+ }
347
+ /**
348
+ * Delete job by ID
349
+ * @param jobId - Job identifier
350
+ * @returns {Promise<number>}
351
+ */
352
+ async deleteJob(jobId) {
353
+ return fetchStreamWithError(`${this.baseUrl}/api/v1/jobs/${jobId}/delete`, { method: "PUT" }).then((response) => {
354
+ return response.status;
355
+ });
356
+ }
357
+ /**
358
+ * Get the DID (Decentralized Identifier) for this venue
359
+ * @returns {string} DID in the format did:web:domain
360
+ */
361
+ getStats() {
362
+ return fetchWithError(`${this.baseUrl}/api/v1/status`);
363
+ }
364
+ /**
365
+ * Get asset metadata
366
+ * @returns {Promise<AssetMetadata>}
367
+ */
368
+ async getMetadata(assetId) {
369
+ return await fetchWithError(`${this.baseUrl}/api/v1/assets/${assetId}`);
370
+ }
371
+ /**
372
+ * Upload content to asset
373
+ * @param content - Content to upload
374
+ * @returns {Promise<ReadableStream<Uint8Array> | null>}
375
+ */
376
+ async uploadContent(assetId, content) {
377
+ const response = await fetchStreamWithError(`${this.baseUrl}/api/v1/assets/${assetId}/content`, {
378
+ method: "PUT",
379
+ headers: this.setCredentialsInHeader(),
380
+ body: content
381
+ });
382
+ return response.body;
383
+ }
384
+ /**
385
+ * Get asset content
386
+ * @returns {Promise<ReadableStream<Uint8Array> | null>}
387
+ */
388
+ async getContent(assetId) {
389
+ const response = await fetchStreamWithError(`${this.baseUrl}/api/v1/assets/${assetId}/content`);
390
+ return response.body;
391
+ }
392
+ /**
393
+ * Execute the operation
394
+ * @param input - Operation input parameters
395
+ * @returns {Promise<any>}
396
+ */
397
+ async run(assetId, input) {
398
+ const payload = {
399
+ operation: assetId,
400
+ input
401
+ };
402
+ try {
403
+ const response = await fetchWithError(`${this.baseUrl}/api/v1/invoke/`, {
404
+ method: "POST",
405
+ headers: this.setCredentialsInHeader(),
406
+ body: JSON.stringify(payload)
407
+ });
408
+ return response?.output;
409
+ } catch (error) {
410
+ throw error;
411
+ }
412
+ }
413
+ /**
414
+ * Execute the operation
415
+ * @param input - Operation input parameters
416
+ * @returns {Promise<Job>}
417
+ */
418
+ async invoke(assetId, input) {
419
+ const payload = {
420
+ operation: assetId,
421
+ input
422
+ };
423
+ try {
424
+ const response = await fetchWithError(`${this.baseUrl}/api/v1/invoke/`, {
425
+ method: "POST",
426
+ headers: this.setCredentialsInHeader(),
427
+ body: JSON.stringify(payload)
428
+ });
429
+ return new Job(response?.id, this, response);
430
+ } catch (error) {
431
+ throw error;
432
+ }
433
+ }
434
+ setCredentialsInHeader() {
435
+ if (this.credentials.userId && this.credentials.userId != "") {
436
+ return {
437
+ "Content-Type": "application/json",
438
+ "X-Covia-User": this.credentials.userId
439
+ };
440
+ } else {
441
+ return { "Content-Type": "application/json" };
442
+ }
443
+ }
444
+ };
445
+
446
+ // src/Grid.ts
447
+ var cache3 = /* @__PURE__ */ new Map();
448
+ var Grid = class {
449
+ /**
450
+ * Static method to connect to a venue
451
+ * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
452
+ * @returns {Promise<Venue>} A new Venue instance configured appropriately
453
+ */
454
+ static async connect(venueId, credentials) {
455
+ if (cache3.has(venueId))
456
+ return Promise.resolve(cache3.get(venueId));
457
+ const connectedVenue = await Venue.connect(venueId, credentials);
458
+ cache3.set(venueId, connectedVenue);
459
+ return Promise.resolve(connectedVenue);
460
+ }
461
+ };
462
+
463
+ export { Asset, CoviaError, CredentialsHTTP, DataAsset, Grid, Job, Operation, RunStatus, Venue, fetchStreamWithError, fetchWithError, getAssetIdFromPath, getAssetIdFromVenueId, getParsedAssetId, isJobComplete, isJobFinished, isJobPaused };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@covia/covia-sdk",
3
+ "version": "1.0.0",
4
+ "description": "Typescript library for covia-ai",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "require": "./dist/index.js",
12
+ "import": "./dist/index.mjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
20
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
21
+ "lint": "eslint src --ext .ts",
22
+ "test": "jest",
23
+ "prepublishOnly": "npm run build && npm test",
24
+ "prepare": "npm run build"
25
+ },
26
+ "keywords": [
27
+ "covia",
28
+ "grid",
29
+ "api",
30
+ "typescript",
31
+ "data-assets",
32
+ "operations"
33
+ ],
34
+ "author": "Covia AI",
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/covia-ai/covia-sdk.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/covia-ai/covia-sdk/issues"
42
+ },
43
+ "homepage": "https://github.com/covia-ai/covia-sdk#readme",
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "devDependencies": {
48
+ "@types/jest": "^30.0.0",
49
+ "@types/node": "^20.0.0",
50
+ "dotenv": "^17.2.3",
51
+ "jest": "^30.2.0",
52
+ "ts-jest": "^29.4.6",
53
+ "tsup": "^8.0.0",
54
+ "typescript": "^5.3.0"
55
+ },
56
+ "engines": {
57
+ "node": ">=18"
58
+ },
59
+ "dependencies": {
60
+ "did-resolver": "^4.1.0",
61
+ "web-did-resolver": "^2.0.32"
62
+ }
63
+ }