@super-protocol/sp-cli 0.0.2-beta.2 → 0.0.2-beta.5

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.
@@ -1,8 +1,9 @@
1
+ import { EncryptionWithIV, Resource, RuntimeInputInfo } from '@super-protocol/dto-js';
1
2
  import { AddStorageDto, ProviderClient, StorageResponseDto, UpdateStorageDto } from '@super-protocol/provider-client';
2
3
  import pino from 'pino';
3
4
  export declare class StorageError extends Error {
4
5
  }
5
- export declare class StoragesEmptyError extends StorageError {
6
+ export declare class StoragesUndefinedError extends StorageError {
6
7
  }
7
8
  export declare class StorageCreateError extends StorageError {
8
9
  }
@@ -10,12 +11,40 @@ export declare class StorageUpdateError extends StorageError {
10
11
  }
11
12
  export declare class StorageGetError extends StorageError {
12
13
  }
14
+ type IUploadParams = {
15
+ localPath: string;
16
+ maximumConcurrent?: number;
17
+ metadataPath?: string;
18
+ outputPath?: string;
19
+ remotePath?: string;
20
+ sync?: boolean;
21
+ withEncryption: boolean;
22
+ };
23
+ type IDownloadParams = {
24
+ downloadPath: string;
25
+ maximumConcurrent?: number;
26
+ resourcePath: string;
27
+ };
28
+ export type ResourceFile = Partial<Pick<RuntimeInputInfo, 'args' | 'hardwareContext' | 'hash' | 'signatureKeyHash'>> & {
29
+ encryption?: EncryptionWithIV;
30
+ resource: Resource;
31
+ };
32
+ type ProgressCb = (arg: {
33
+ current: number;
34
+ key: string;
35
+ total: number;
36
+ }) => void;
37
+ export declare const generateExternalId: () => string;
13
38
  export declare class StorageService {
14
39
  private readonly providerClient;
15
40
  private readonly logger;
16
41
  constructor(providerClient: ProviderClient, logger: pino.BaseLogger);
17
42
  createStorage(storage: AddStorageDto): Promise<StorageResponseDto>;
18
- getCentralizedStorage(): Promise<{
43
+ download(params: IDownloadParams, progressCb: ProgressCb): Promise<void>;
44
+ getCentralizedStorage(): Promise<StorageResponseDto>;
45
+ getCurrentStorage(): Promise<StorageResponseDto>;
46
+ hasStorage(): Promise<boolean>;
47
+ initCentralizedStorage(): Promise<{
19
48
  bucket: string;
20
49
  createdAt: string;
21
50
  id: string;
@@ -26,22 +55,17 @@ export declare class StorageService {
26
55
  storjCredentials?: import("@super-protocol/provider-client").components["schemas"]["StorJCredentialsResponseDto"];
27
56
  updatedAt: string;
28
57
  userId: string;
29
- } | undefined>;
30
- getCurrentStorage(): Promise<StorageResponseDto>;
31
- hasStorage(): Promise<boolean>;
32
- initStorage(): Promise<{
33
- bucket: string;
58
+ }>;
59
+ requestStorages(): Promise<StorageResponseDto[]>;
60
+ saveStorage(selectedStorage: string): Promise<{
61
+ activeStorageId: string;
34
62
  createdAt: string;
63
+ decentralizedStorageId?: string;
35
64
  id: string;
36
- isCentralized: boolean;
37
- prefix: string;
38
- s3Credentials?: import("@super-protocol/provider-client").components["schemas"]["S3CredentialsResponseDto"];
39
- storageType: import("@super-protocol/provider-client").components["schemas"]["StorageType"];
40
- storjCredentials?: import("@super-protocol/provider-client").components["schemas"]["StorJCredentialsResponseDto"];
41
65
  updatedAt: string;
42
66
  userId: string;
43
67
  }>;
44
- requestStorages(): Promise<StorageResponseDto[]>;
45
- saveStorage(selectedStorage: string): Promise<void>;
46
68
  updateStorage(id: string, storage: UpdateStorageDto): Promise<StorageResponseDto>;
69
+ upload(params: IUploadParams, progressCb: ProgressCb): Promise<void>;
47
70
  }
71
+ export {};
@@ -1,7 +1,23 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { StorageType, } from '@super-protocol/dto-js';
8
+ import { ResourceType, } from '@super-protocol/provider-client';
9
+ import { download, upload } from '@super-protocol/sp-files-addon';
10
+ import * as fs from 'node:fs/promises';
11
+ import { basename, dirname, join } from 'node:path';
12
+ import { Value } from 'typebox/value';
13
+ import { Retryable } from 'typescript-retry-decorator';
14
+ import { storageResourceSchema } from '../config/resource.schema.js';
15
+ import { S3_ENDPOINT } from '../constants.js';
1
16
  import { ProviderClientError } from '../errors.js';
17
+ import { preparePath, readJsonFile } from '../utils/helper.js';
2
18
  export class StorageError extends Error {
3
19
  }
4
- export class StoragesEmptyError extends StorageError {
20
+ export class StoragesUndefinedError extends StorageError {
5
21
  }
6
22
  export class StorageCreateError extends StorageError {
7
23
  }
@@ -9,6 +25,7 @@ export class StorageUpdateError extends StorageError {
9
25
  }
10
26
  export class StorageGetError extends StorageError {
11
27
  }
28
+ export const generateExternalId = () => Array.from({ length: 16 }).map(() => Math.floor(Math.random() * 16).toString(16)).join('');
12
29
  export class StorageService {
13
30
  providerClient;
14
31
  logger;
@@ -39,9 +56,43 @@ export class StorageService {
39
56
  throw error_;
40
57
  }
41
58
  }
59
+ async download(params, progressCb) {
60
+ const resourceFile = await readJsonFile({ path: params.resourcePath });
61
+ if (!Value.Check(storageResourceSchema, resourceFile)) {
62
+ throw new StorageError('Invalid resource file format, please verify resource.json against the schema.');
63
+ }
64
+ const { resource } = resourceFile;
65
+ if (resource.type !== ResourceType.StorageProvider) {
66
+ throw new StorageError(`Resource type ${resource.type} is not supported, use StorageProvider type for this command`);
67
+ }
68
+ let localPath = preparePath(params.downloadPath);
69
+ if (resource.filepath) {
70
+ localPath = join(localPath, resource.filepath);
71
+ }
72
+ await download(resource, localPath, {
73
+ encryption: resourceFile.encryption,
74
+ progressCallback: progressCb,
75
+ threads: params.maximumConcurrent,
76
+ });
77
+ }
42
78
  async getCentralizedStorage() {
43
- const storages = await this.requestStorages();
44
- return storages.find(storage => storage.isCentralized);
79
+ try {
80
+ const storages = await this.requestStorages();
81
+ const centralized = storages.find(storage => storage.isCentralized);
82
+ if (!centralized) {
83
+ const storage = await this.initCentralizedStorage();
84
+ return storage;
85
+ }
86
+ return centralized;
87
+ }
88
+ catch (error) {
89
+ this.logger.error({ err: error }, 'Error getting centralized storage');
90
+ if (error instanceof StoragesUndefinedError) {
91
+ const storage = await this.initCentralizedStorage();
92
+ return storage;
93
+ }
94
+ throw error;
95
+ }
45
96
  }
46
97
  async getCurrentStorage() {
47
98
  try {
@@ -67,11 +118,6 @@ export class StorageService {
67
118
  try {
68
119
  const { data, error } = await this.providerClient.GET('/api/user-settings');
69
120
  if (error && error.statusCode === 404) {
70
- const storage = await this.getCentralizedStorage();
71
- if (storage) {
72
- await this.saveStorage(storage.id);
73
- return true;
74
- }
75
121
  return false;
76
122
  }
77
123
  if (error) {
@@ -89,7 +135,7 @@ export class StorageService {
89
135
  throw error_;
90
136
  }
91
137
  }
92
- async initStorage() {
138
+ async initCentralizedStorage() {
93
139
  this.logger.info('Requesting storage initialization');
94
140
  try {
95
141
  const result = await this.providerClient.POST('/api/storages/centralized');
@@ -120,9 +166,9 @@ export class StorageService {
120
166
  this.logger.error({ err: result.error }, 'Failed to fetch storages');
121
167
  throw new StorageError(result.error.message);
122
168
  }
123
- if (!data || !data?.length) {
124
- this.logger.warn('Storages list is empty');
125
- throw new StoragesEmptyError('Storages is empty please create or import first one');
169
+ if (data === undefined) {
170
+ this.logger.warn('Storages list response is wrong');
171
+ throw new StoragesUndefinedError('Storages is empty please create or import first one');
126
172
  }
127
173
  this.logger.debug({ count: data.length }, 'Received storages list');
128
174
  return data;
@@ -142,9 +188,10 @@ export class StorageService {
142
188
  },
143
189
  });
144
190
  if (error) {
145
- throw new StorageError(`User settings request error ${error?.message}`);
191
+ throw new StorageError(`User settings request error ${error.message}`);
146
192
  }
147
193
  this.logger.info({ selectedStorage: data?.activeStorageId }, 'Selected storage saved successfully');
194
+ return data;
148
195
  }
149
196
  catch (error) {
150
197
  this.logger.error({ err: error }, 'Failed to save selected storage');
@@ -161,7 +208,7 @@ export class StorageService {
161
208
  });
162
209
  if (error) {
163
210
  this.logger.error({ err: error, storageId: id }, 'Failed to update storage');
164
- throw new StorageUpdateError(error?.message);
211
+ throw new StorageUpdateError(error.message);
165
212
  }
166
213
  if (!data) {
167
214
  this.logger.error({ storageId: id }, 'Provider returned empty storage update response');
@@ -176,4 +223,86 @@ export class StorageService {
176
223
  throw error_;
177
224
  }
178
225
  }
226
+ async upload(params, progressCb) {
227
+ const storage = await this.getCurrentStorage();
228
+ const remotePath = `${params.remotePath || generateExternalId()}`;
229
+ const resourceFilePath = preparePath(params.outputPath || '');
230
+ try {
231
+ await fs.stat(resourceFilePath);
232
+ throw new Error('Output file for resource file already exists');
233
+ }
234
+ catch (error) {
235
+ if (error instanceof Error && 'code' in error && error.code !== 'ENOENT') {
236
+ throw error;
237
+ }
238
+ }
239
+ let metadata = {};
240
+ if (params.metadataPath) {
241
+ metadata = await readJsonFile({ path: preparePath(params.metadataPath) });
242
+ }
243
+ const writeCredentials = storage.storageType === StorageType.StorJ
244
+ ? {
245
+ bucket: storage.bucket,
246
+ prefix: join(storage.prefix, remotePath),
247
+ token: storage.storjCredentials.writeAccessToken,
248
+ }
249
+ : {
250
+ accessKeyId: storage.s3Credentials.writeAccessKeyId,
251
+ bucket: storage.bucket,
252
+ endpoint: S3_ENDPOINT,
253
+ prefix: join(storage.prefix, remotePath),
254
+ secretKey: storage.s3Credentials.writeSecretAccessKey,
255
+ };
256
+ const readCredentials = storage.storageType === StorageType.StorJ
257
+ ? {
258
+ bucket: storage.bucket,
259
+ prefix: join(storage.prefix, remotePath),
260
+ token: storage.storjCredentials.readAccessToken,
261
+ }
262
+ : {
263
+ accessKeyId: storage.s3Credentials.readAccessKeyId,
264
+ bucket: storage.bucket,
265
+ endpoint: S3_ENDPOINT,
266
+ prefix: join(storage.prefix, remotePath),
267
+ secretKey: storage.s3Credentials.readSecretAccessKey,
268
+ };
269
+ const info = await fs.stat(params.localPath);
270
+ let { localPath } = params;
271
+ let sourcePath;
272
+ if (info.isFile()) {
273
+ sourcePath = basename(localPath);
274
+ localPath = dirname(localPath);
275
+ }
276
+ try {
277
+ const uploadResult = await upload(localPath, {
278
+ credentials: writeCredentials,
279
+ filepath: '',
280
+ storageType: storage.storageType,
281
+ type: ResourceType.StorageProvider,
282
+ }, {
283
+ encryption: params.withEncryption,
284
+ progressCallback: progressCb,
285
+ sourcePath,
286
+ sync: params.sync,
287
+ threads: params.maximumConcurrent,
288
+ });
289
+ uploadResult.resource.storageType = storage.storageType;
290
+ uploadResult.resource.credentials = readCredentials;
291
+ const result = {
292
+ ...metadata,
293
+ ...uploadResult,
294
+ };
295
+ await fs.writeFile(resourceFilePath, JSON.stringify(result, null, 2));
296
+ this.logger.info(`Resource file was created in ${resourceFilePath}`);
297
+ }
298
+ catch (error) {
299
+ this.logger.error({ err: error }, 'Somethong went wrong with upload');
300
+ console.log(error);
301
+ const error_ = error instanceof StorageError ? error : new ProviderClientError('Request failed please try again later');
302
+ throw error_;
303
+ }
304
+ }
179
305
  }
306
+ __decorate([
307
+ Retryable({ maxAttempts: 3, value: [StoragesUndefinedError, StorageCreateError, ProviderClientError] })
308
+ ], StorageService.prototype, "getCentralizedStorage", null);
@@ -1 +1,6 @@
1
1
  export declare const getConfigName: (name: string) => string;
2
+ export declare const preparePath: (rawPath: string) => string;
3
+ export type ReadJsonFileParams = {
4
+ path: string;
5
+ };
6
+ export declare const readJsonFile: <T>(params: ReadJsonFileParams) => Promise<T>;
@@ -1 +1,23 @@
1
+ import { existsSync } from 'node:fs';
2
+ import * as fs from 'node:fs/promises';
3
+ import path from 'node:path';
1
4
  export const getConfigName = (name) => name.toLowerCase().replaceAll(/[^a-z0-9]+/g, '-') + '.config.json';
5
+ export const preparePath = (rawPath) => {
6
+ if (path.isAbsolute(rawPath))
7
+ return rawPath;
8
+ return path.join(process.cwd(), rawPath);
9
+ };
10
+ export const readJsonFile = async (params) => {
11
+ if (!existsSync(params.path)) {
12
+ throw new Error(`File could not be found in ${params.path}`);
13
+ }
14
+ const jsonString = await fs.readFile(params.path, 'utf8');
15
+ let parsedValue;
16
+ try {
17
+ parsedValue = JSON.parse(jsonString);
18
+ }
19
+ catch {
20
+ throw new Error(`Invalid JSON format of file ${params.path}`);
21
+ }
22
+ return parsedValue;
23
+ };
@@ -0,0 +1,8 @@
1
+ export declare const createProgressPrinter: ({ action, done, start, }: {
2
+ action: string;
3
+ done?: string;
4
+ start: string;
5
+ }) => {
6
+ advance(key: string, num: number, message: string): void;
7
+ finish: () => void;
8
+ };
@@ -0,0 +1,27 @@
1
+ import * as p from '@clack/prompts';
2
+ export const createProgressPrinter = ({ action, done = 'completed', start, }) => {
3
+ const progressBars = {};
4
+ let lastKey = '';
5
+ const getProgress = (key) => {
6
+ if (key in progressBars) {
7
+ lastKey = key;
8
+ return progressBars[key];
9
+ }
10
+ if (lastKey in progressBars) {
11
+ const progressBar = progressBars[lastKey];
12
+ progressBar.stop(`${action} ${lastKey} ${done}`);
13
+ }
14
+ const progressBar = p.progress({ size: 100, style: 'block' });
15
+ progressBar.start(`${start} ${key}`);
16
+ progressBars[key] = progressBar;
17
+ return progressBar;
18
+ };
19
+ const finish = () => progressBars[lastKey].stop(`${action} ${lastKey} ${done}`);
20
+ return {
21
+ advance(key, num, message) {
22
+ const progress = getProgress(key);
23
+ progress.advance(num, message);
24
+ },
25
+ finish,
26
+ };
27
+ };
@@ -74,7 +74,9 @@
74
74
  ]
75
75
  },
76
76
  "auth:login": {
77
- "aliases": [],
77
+ "aliases": [
78
+ "login"
79
+ ],
78
80
  "args": {},
79
81
  "description": "Authorization",
80
82
  "examples": [
@@ -473,6 +475,161 @@
473
475
  "use.js"
474
476
  ]
475
477
  },
478
+ "files:download": {
479
+ "aliases": [],
480
+ "args": {
481
+ "resourceFile": {
482
+ "description": "Path to a resource file",
483
+ "name": "resourceFile",
484
+ "required": true
485
+ },
486
+ "localDirectory": {
487
+ "description": "Path to save downloaded file",
488
+ "name": "localDirectory",
489
+ "required": true
490
+ }
491
+ },
492
+ "description": "describe the command here",
493
+ "examples": [
494
+ "<%= config.bin %> <%= command.id %> ./resource.json ./pathToDownload "
495
+ ],
496
+ "flags": {
497
+ "json": {
498
+ "description": "Format output as json.",
499
+ "helpGroup": "GLOBAL",
500
+ "name": "json",
501
+ "allowNo": false,
502
+ "type": "boolean"
503
+ },
504
+ "config": {
505
+ "helpGroup": "GLOBAL",
506
+ "name": "config",
507
+ "required": false,
508
+ "summary": "Specify config file.",
509
+ "hasDynamicHelp": false,
510
+ "multiple": false,
511
+ "type": "option"
512
+ },
513
+ "maximum-concurrent": {
514
+ "description": "Maximum concurrent pieces to upload at once per transfer",
515
+ "name": "maximum-concurrent",
516
+ "default": 1,
517
+ "hasDynamicHelp": false,
518
+ "multiple": false,
519
+ "type": "option"
520
+ }
521
+ },
522
+ "hasDynamicHelp": false,
523
+ "hiddenAliases": [],
524
+ "id": "files:download",
525
+ "pluginAlias": "@super-protocol/sp-cli",
526
+ "pluginName": "@super-protocol/sp-cli",
527
+ "pluginType": "core",
528
+ "strict": true,
529
+ "enableJsonFlag": true,
530
+ "help": "Download and decrypt a file from the remote storage to <localPath> using resource file <resourcePath>",
531
+ "isESM": true,
532
+ "relativePath": [
533
+ "dist",
534
+ "commands",
535
+ "files",
536
+ "download.js"
537
+ ]
538
+ },
539
+ "files:upload": {
540
+ "aliases": [],
541
+ "args": {
542
+ "path": {
543
+ "description": "file or directory to upload",
544
+ "name": "path",
545
+ "required": true
546
+ }
547
+ },
548
+ "description": "describe the command here",
549
+ "examples": [
550
+ "<%= config.bin %> <%= command.id %> ./file.txt"
551
+ ],
552
+ "flags": {
553
+ "json": {
554
+ "description": "Format output as json.",
555
+ "helpGroup": "GLOBAL",
556
+ "name": "json",
557
+ "allowNo": false,
558
+ "type": "boolean"
559
+ },
560
+ "config": {
561
+ "helpGroup": "GLOBAL",
562
+ "name": "config",
563
+ "required": false,
564
+ "summary": "Specify config file.",
565
+ "hasDynamicHelp": false,
566
+ "multiple": false,
567
+ "type": "option"
568
+ },
569
+ "filename": {
570
+ "description": "The name of the resulting file/directory in the storage",
571
+ "name": "filename",
572
+ "required": false,
573
+ "hasDynamicHelp": false,
574
+ "multiple": false,
575
+ "type": "option"
576
+ },
577
+ "maximum-concurrent": {
578
+ "description": "Maximum concurrent pieces to upload at once per transfer",
579
+ "name": "maximum-concurrent",
580
+ "default": 1,
581
+ "hasDynamicHelp": false,
582
+ "multiple": false,
583
+ "type": "option"
584
+ },
585
+ "metadata": {
586
+ "description": "Path to a metadata file for adding fields to the resource file",
587
+ "name": "metadata",
588
+ "required": false,
589
+ "hasDynamicHelp": false,
590
+ "multiple": false,
591
+ "type": "option"
592
+ },
593
+ "output": {
594
+ "description": "Path to save resource file that is used to access the uploaded file",
595
+ "name": "output",
596
+ "required": false,
597
+ "default": "resource.json",
598
+ "hasDynamicHelp": false,
599
+ "multiple": false,
600
+ "type": "option"
601
+ },
602
+ "skip-encryption": {
603
+ "description": "Skip file encryption before upload",
604
+ "name": "skip-encryption",
605
+ "required": false,
606
+ "allowNo": false,
607
+ "type": "boolean"
608
+ },
609
+ "sync": {
610
+ "description": "Sync mode: delete files in target that don't exist in source",
611
+ "name": "sync",
612
+ "required": false,
613
+ "allowNo": false,
614
+ "type": "boolean"
615
+ }
616
+ },
617
+ "hasDynamicHelp": false,
618
+ "hiddenAliases": [],
619
+ "id": "files:upload",
620
+ "pluginAlias": "@super-protocol/sp-cli",
621
+ "pluginName": "@super-protocol/sp-cli",
622
+ "pluginType": "core",
623
+ "strict": true,
624
+ "enableJsonFlag": true,
625
+ "isESM": true,
626
+ "relativePath": [
627
+ "dist",
628
+ "commands",
629
+ "files",
630
+ "upload.js"
631
+ ]
632
+ },
476
633
  "storage:base": {
477
634
  "aliases": [],
478
635
  "args": {},
@@ -679,5 +836,5 @@
679
836
  ]
680
837
  }
681
838
  },
682
- "version": "0.0.2-beta.2"
839
+ "version": "0.0.2-beta.5"
683
840
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@super-protocol/sp-cli",
3
3
  "description": "SuperProtocol Command line interface",
4
- "version": "0.0.2-beta.2",
4
+ "version": "0.0.2-beta.5",
5
5
  "author": "SuperProtocol",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -13,19 +13,21 @@
13
13
  },
14
14
  "bugs": "https://github.com/Super-Protocol/sp-cli/issues",
15
15
  "dependencies": {
16
- "@clack/prompts": "^0.11.0",
16
+ "@clack/prompts": "^1.0.0-alpha.6",
17
17
  "@oclif/core": "^4.7.2",
18
+ "@oclif/plugin-autocomplete": "^3.2.39",
18
19
  "@oclif/plugin-help": "^6.2.33",
19
- "@oclif/plugin-plugins": "^5.4.50",
20
20
  "@oclif/plugin-warn-if-update-available": "^3.1.50",
21
21
  "@sinclair/typebox": "^0.33.22",
22
- "@super-protocol/provider-client": "^0.1.7",
23
- "@super-protocol/sp-files-addon": "^0.12.5",
22
+ "@super-protocol/dto-js": "^1.3.0",
23
+ "@super-protocol/provider-client": "^0.1.8",
24
+ "@super-protocol/sp-files-addon": "^0.12.7",
24
25
  "cookie": "^1.0.2",
25
26
  "jsonwebtoken": "^9.0.2",
26
27
  "pino": "^9.14.0",
27
28
  "pino-pretty": "^13.1.2",
28
29
  "tough-cookie": "^6.0.0",
30
+ "typebox": "^1.0.55",
29
31
  "typescript-retry-decorator": "^2.4.2",
30
32
  "viem": "^2.38.3"
31
33
  },
@@ -66,8 +68,7 @@
66
68
  "oclif": {
67
69
  "bin": "sp",
68
70
  "binAliases": [
69
- "spcli",
70
- "sp-cli"
71
+ "spcli"
71
72
  ],
72
73
  "dirname": "sp",
73
74
  "commands": {
@@ -81,7 +82,6 @@
81
82
  },
82
83
  "plugins": [
83
84
  "@oclif/plugin-help",
84
- "@oclif/plugin-plugins",
85
85
  "@oclif/plugin-warn-if-update-available"
86
86
  ],
87
87
  "warn-if-update-available": {