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