@super-protocol/sp-cli 0.0.8 → 0.0.10-beta

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.
Files changed (95) hide show
  1. package/README.md +200 -167
  2. package/dist/commands/account/base.d.ts +3 -4
  3. package/dist/commands/account/base.js +12 -9
  4. package/dist/commands/account/forget.d.ts +1 -1
  5. package/dist/commands/account/forget.js +66 -17
  6. package/dist/commands/account/get-sppi.js +7 -11
  7. package/dist/commands/account/info.d.ts +1 -13
  8. package/dist/commands/account/info.js +25 -45
  9. package/dist/commands/account/list.js +6 -6
  10. package/dist/commands/account/login.d.ts +10 -3
  11. package/dist/commands/account/login.js +143 -87
  12. package/dist/commands/account/switch.d.ts +3 -0
  13. package/dist/commands/account/switch.js +31 -11
  14. package/dist/commands/assets/base.d.ts +39 -0
  15. package/dist/commands/assets/base.js +217 -0
  16. package/dist/commands/assets/create.d.ts +41 -0
  17. package/dist/commands/assets/create.js +277 -0
  18. package/dist/commands/assets/delete.d.ts +14 -0
  19. package/dist/commands/assets/delete.js +69 -0
  20. package/dist/commands/assets/get.d.ts +14 -0
  21. package/dist/commands/assets/get.js +79 -0
  22. package/dist/commands/assets/list.d.ts +7 -0
  23. package/dist/commands/assets/list.js +33 -0
  24. package/dist/commands/assets/update.d.ts +44 -0
  25. package/dist/commands/assets/update.js +321 -0
  26. package/dist/commands/base.d.ts +1 -0
  27. package/dist/commands/base.js +6 -0
  28. package/dist/config/config.schema.d.ts +2 -11
  29. package/dist/config/config.schema.js +2 -7
  30. package/dist/constants.d.ts +3 -3
  31. package/dist/constants.js +3 -3
  32. package/dist/errors.d.ts +0 -2
  33. package/dist/errors.js +0 -2
  34. package/dist/hooks/prerun/auth.js +5 -9
  35. package/dist/interfaces/config-manager.interface.d.ts +3 -1
  36. package/dist/lib/container.d.ts +4 -12
  37. package/dist/lib/container.js +28 -113
  38. package/dist/lib/swarm-client/fetch-api.d.ts +7 -0
  39. package/dist/lib/swarm-client/fetch-api.js +41 -0
  40. package/dist/lib/swarm-client/fetch-timeout.client.d.ts +1 -0
  41. package/dist/lib/swarm-client/fetch-timeout.client.js +32 -0
  42. package/dist/lib/swarm-client/index.d.ts +6 -0
  43. package/dist/lib/swarm-client/index.js +31 -0
  44. package/dist/lib/swarm-client/middlewares/authorization.middleware.d.ts +2 -0
  45. package/dist/lib/swarm-client/middlewares/authorization.middleware.js +12 -0
  46. package/dist/lib/swarm-client/middlewares/index.d.ts +6 -0
  47. package/dist/lib/swarm-client/middlewares/index.js +5 -0
  48. package/dist/lib/swarm-client/middlewares/logger.middleware.d.ts +2 -0
  49. package/dist/lib/swarm-client/middlewares/logger.middleware.js +30 -0
  50. package/dist/lib/swarm-client/middlewares/request-id.middleware.d.ts +2 -0
  51. package/dist/lib/swarm-client/middlewares/request-id.middleware.js +13 -0
  52. package/dist/lib/swarm-client/types.d.ts +23 -0
  53. package/dist/lib/swarm-client/types.js +1 -0
  54. package/dist/managers/account-manager.d.ts +1 -0
  55. package/dist/managers/account-manager.js +13 -18
  56. package/dist/managers/config-file-manager.d.ts +24 -17
  57. package/dist/managers/config-file-manager.js +285 -161
  58. package/dist/managers/config-manager.d.ts +6 -6
  59. package/dist/managers/config-manager.js +8 -8
  60. package/dist/services/account.service.d.ts +42 -0
  61. package/dist/services/account.service.js +140 -0
  62. package/dist/services/asset.service.d.ts +35 -0
  63. package/dist/services/asset.service.js +120 -0
  64. package/dist/services/auth.service.d.ts +4 -6
  65. package/dist/services/auth.service.js +108 -118
  66. package/dist/utils/helper.js +2 -2
  67. package/dist/utils/progress.js +1 -0
  68. package/dist/utils/prompt.service.d.ts +8 -1
  69. package/dist/utils/prompt.service.js +33 -1
  70. package/oclif.manifest.json +479 -215
  71. package/package.json +7 -8
  72. package/dist/commands/files/download.d.ts +0 -15
  73. package/dist/commands/files/download.js +0 -63
  74. package/dist/commands/files/upload.d.ts +0 -18
  75. package/dist/commands/files/upload.js +0 -83
  76. package/dist/commands/storage/base.d.ts +0 -13
  77. package/dist/commands/storage/base.js +0 -125
  78. package/dist/commands/storage/create.d.ts +0 -11
  79. package/dist/commands/storage/create.js +0 -53
  80. package/dist/commands/storage/select.d.ts +0 -9
  81. package/dist/commands/storage/select.js +0 -38
  82. package/dist/commands/storage/show.d.ts +0 -17
  83. package/dist/commands/storage/show.js +0 -34
  84. package/dist/commands/storage/update.d.ts +0 -14
  85. package/dist/commands/storage/update.js +0 -204
  86. package/dist/commands/workflows/extend-lease.d.ts +0 -17
  87. package/dist/commands/workflows/extend-lease.js +0 -102
  88. package/dist/hooks/finally/shutdown-blockchain.d.ts +0 -3
  89. package/dist/hooks/finally/shutdown-blockchain.js +0 -8
  90. package/dist/middlewares/auth-middleware.d.ts +0 -9
  91. package/dist/middlewares/auth-middleware.js +0 -91
  92. package/dist/middlewares/cookies-middleware.d.ts +0 -8
  93. package/dist/middlewares/cookies-middleware.js +0 -80
  94. package/dist/services/storage.service.d.ts +0 -73
  95. package/dist/services/storage.service.js +0 -378
@@ -1,204 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { Flags } from '@oclif/core';
4
- import { StorageType, } from '@super-protocol/provider-client';
5
- import { StoragesUndefinedError } from '../../services/storage.service.js';
6
- import { promptService } from '../../utils/prompt.service.js';
7
- import { BaseStorageCommand } from './base.js';
8
- export default class StorageUpdate extends BaseStorageCommand {
9
- static description = 'Update the configuration of an existing storage.';
10
- static examples = [
11
- '<%= config.bin %> storage update --id=2de3e3a4-0000-1111-2222-333344445555 --fromFile ./storage-update.json',
12
- '<%= config.bin %> storage update --id=2de3e3a4-0000-1111-2222-333344445555',
13
- ];
14
- static flags = {
15
- fromFile: Flags.string({
16
- char: 'f',
17
- description: 'Path to a JSON file that contains UpdateStorageDto payload.',
18
- }),
19
- id: Flags.string({
20
- char: 'i',
21
- description: 'Storage ID to update',
22
- }),
23
- };
24
- async run() {
25
- const { flags } = await this.parse(StorageUpdate);
26
- try {
27
- const shouldRequestStorages = !flags.fromFile || !flags.id;
28
- const storages = shouldRequestStorages
29
- ? await this.storageService.requestStorages()
30
- : undefined;
31
- let storageId = flags.id;
32
- if (!storageId) {
33
- const options = (storages || [])
34
- .filter((cp) => !cp.isCentralized)
35
- .map((storage) => ({
36
- label: `${storage.id} (${storage.storageType}) ${storage.bucket}/${storage.prefix} `,
37
- value: storage.id,
38
- }));
39
- if (!options || options.length === 0) {
40
- throw new StoragesUndefinedError('No storages available to update');
41
- }
42
- storageId = await promptService.select({
43
- message: 'Select storage to update',
44
- options,
45
- });
46
- }
47
- if (!storageId) {
48
- this.error('Storage ID is required');
49
- }
50
- const storageToUpdate = storages?.find((storage) => storage.id === storageId);
51
- if (flags.id && storages && !storageToUpdate) {
52
- this.error(`Storage with ID ${storageId} not found`);
53
- }
54
- const updatePayload = flags.fromFile
55
- ? await this.loadStorageFromFile(flags.fromFile)
56
- : await this.promptStorageUpdate(storageToUpdate);
57
- await this.storageService.updateStorage(storageId, updatePayload);
58
- this.log(`Storage updated: ${storageId}`);
59
- }
60
- catch (error) {
61
- if (error instanceof StoragesUndefinedError) {
62
- this.error('No storages available. Run "sp storage create" first.');
63
- }
64
- else {
65
- this.error(error instanceof Error ? error.message : String(error));
66
- }
67
- }
68
- }
69
- ensureNonEmptyString(value, fieldName) {
70
- if (typeof value !== 'string' || !value.trim()) {
71
- this.error(`${fieldName} must be a non-empty string`);
72
- }
73
- return value.trim();
74
- }
75
- ensureUpdatePayload(payload) {
76
- if (!payload || typeof payload !== 'object') {
77
- this.error('Storage update definition must be an object');
78
- }
79
- const updateFields = [
80
- 'bucket',
81
- 'prefix',
82
- 'storageType',
83
- 's3Credentials',
84
- 'storjCredentials',
85
- ];
86
- const hasUpdates = updateFields.some((key) => payload[key] !== undefined);
87
- if (!hasUpdates) {
88
- this.error('Update payload must include at least one property');
89
- }
90
- if (payload.storageType && !Object.values(StorageType).includes(payload.storageType)) {
91
- this.error(`Unsupported storage type: ${payload.storageType}`);
92
- }
93
- if (payload.s3Credentials) {
94
- const { readAccessKeyId, readSecretAccessKey, region, writeAccessKeyId, writeSecretAccessKey, } = payload.s3Credentials;
95
- if (!readAccessKeyId ||
96
- !readSecretAccessKey ||
97
- !region ||
98
- !writeAccessKeyId ||
99
- !writeSecretAccessKey) {
100
- this.error('S3 credentials must include readAccessKeyId, readSecretAccessKey, region, writeAccessKeyId and writeSecretAccessKey');
101
- }
102
- }
103
- if (payload.storjCredentials) {
104
- const { readAccessToken, writeAccessToken } = payload.storjCredentials;
105
- if (!readAccessToken || !writeAccessToken) {
106
- this.error('StorJ credentials must include readAccessToken and writeAccessToken');
107
- }
108
- }
109
- const sanitized = {};
110
- if (payload.bucket !== undefined) {
111
- sanitized.bucket = this.ensureNonEmptyString(payload.bucket, 'Bucket');
112
- }
113
- if (payload.prefix !== undefined) {
114
- sanitized.prefix = this.ensureNonEmptyString(payload.prefix, 'Prefix');
115
- }
116
- if (payload.storageType) {
117
- sanitized.storageType = payload.storageType;
118
- }
119
- if (payload.s3Credentials) {
120
- sanitized.s3Credentials = {
121
- readAccessKeyId: this.ensureNonEmptyString(payload.s3Credentials.readAccessKeyId, 'S3 credential "readAccessKeyId"'),
122
- readSecretAccessKey: this.ensureNonEmptyString(payload.s3Credentials.readSecretAccessKey, 'S3 credential "readSecretAccessKey"'),
123
- region: this.ensureNonEmptyString(payload.s3Credentials.region, 'S3 credential "region"'),
124
- writeAccessKeyId: this.ensureNonEmptyString(payload.s3Credentials.writeAccessKeyId, 'S3 credential "writeAccessKeyId"'),
125
- writeSecretAccessKey: this.ensureNonEmptyString(payload.s3Credentials.writeSecretAccessKey, 'S3 credential "writeSecretAccessKey"'),
126
- };
127
- }
128
- if (payload.storjCredentials) {
129
- sanitized.storjCredentials = {
130
- readAccessToken: this.ensureNonEmptyString(payload.storjCredentials.readAccessToken, 'StorJ credential "readAccessToken"'),
131
- writeAccessToken: this.ensureNonEmptyString(payload.storjCredentials.writeAccessToken, 'StorJ credential "writeAccessToken"'),
132
- };
133
- }
134
- return sanitized;
135
- }
136
- async loadStorageFromFile(filePath) {
137
- const absolutePath = path.isAbsolute(filePath)
138
- ? filePath
139
- : path.join(this.currentDir, filePath);
140
- try {
141
- const fileContent = await fs.readFile(absolutePath, 'utf8');
142
- const parsed = JSON.parse(fileContent);
143
- return this.ensureUpdatePayload(parsed);
144
- }
145
- catch (error) {
146
- this.error(`Failed to load storage update definition: ${error instanceof Error ? error.message : String(error)}`);
147
- }
148
- }
149
- async promptStorageUpdate(existingStorage) {
150
- const payload = {};
151
- const bucket = (await promptService.text({
152
- defaultValue: existingStorage?.bucket ?? '',
153
- message: 'Bucket name (leave empty to keep current)',
154
- })).trim();
155
- if (bucket) {
156
- payload.bucket = bucket;
157
- }
158
- const prefix = (await promptService.text({
159
- defaultValue: existingStorage?.prefix ?? '',
160
- message: 'Prefix (leave empty to keep current)',
161
- })).trim();
162
- if (prefix) {
163
- payload.prefix = prefix;
164
- }
165
- let newStorageType;
166
- const shouldChangeType = await promptService.confirm({
167
- initialValue: false,
168
- message: existingStorage
169
- ? `Change storage type? (current: ${existingStorage.storageType})`
170
- : 'Change storage type?',
171
- });
172
- if (shouldChangeType) {
173
- newStorageType = await promptService.select({
174
- message: 'Select new storage type',
175
- options: [
176
- { label: 'Amazon S3', value: StorageType.S3 },
177
- { label: 'StorJ', value: StorageType.StorJ },
178
- ],
179
- });
180
- payload.storageType = newStorageType;
181
- }
182
- const effectiveType = newStorageType ?? existingStorage?.storageType;
183
- const credentialsRequired = Boolean(newStorageType);
184
- if (effectiveType) {
185
- const updateCredentials = credentialsRequired ||
186
- (await promptService.confirm({
187
- initialValue: false,
188
- message: `Update ${effectiveType} credentials?`,
189
- }));
190
- if (updateCredentials) {
191
- if (effectiveType === StorageType.S3) {
192
- payload.s3Credentials = await this.promptS3Credentials();
193
- }
194
- else {
195
- payload.storjCredentials = await this.promptStorJCredentials();
196
- }
197
- }
198
- }
199
- if (Object.keys(payload).length === 0) {
200
- this.error('No changes provided');
201
- }
202
- return this.ensureUpdatePayload(payload);
203
- }
204
- }
@@ -1,17 +0,0 @@
1
- import { type SelectOptions } from '../../utils/prompt.service.js';
2
- import { BaseCommand } from '../base.js';
3
- export default class WorkflowsExtendLease extends BaseCommand<typeof WorkflowsExtendLease> {
4
- static args: {
5
- orderId: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
6
- };
7
- static description: string;
8
- static examples: string[];
9
- static flags: {
10
- minutes: import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
- sppi: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
- yes: import("@oclif/core/interfaces").BooleanFlag<boolean>;
13
- };
14
- init(): Promise<void>;
15
- run(): Promise<void>;
16
- protected selectPrompt<Value>(options: SelectOptions<Value>): Promise<Value>;
17
- }
@@ -1,102 +0,0 @@
1
- import { Args, Flags } from '@oclif/core';
2
- import { Orders } from '@super-protocol/sdk-js';
3
- import { formatEther, parseEther } from 'viem/utils';
4
- import { promptService } from '../../utils/prompt.service.js';
5
- import { BaseCommand } from '../base.js';
6
- export default class WorkflowsExtendLease extends BaseCommand {
7
- static args = {
8
- orderId: Args.string({ description: 'Order ID', required: true }),
9
- };
10
- static description = 'Replenish deposit for a workflow to extend its lease time';
11
- static examples = [
12
- '<%= config.bin %> <%= command.id %> <orderId> --sppi 1.5',
13
- '<%= config.bin %> <%= command.id %> <orderId> --minutes 120',
14
- '<%= config.bin %> <%= command.id %> <orderId> --sppi 2 --yes',
15
- ];
16
- static flags = {
17
- minutes: Flags.integer({
18
- description: 'Time to extend order in minutes (automatically calculates tokens)',
19
- }),
20
- sppi: Flags.string({
21
- description: 'SPPI token amount to add to the order',
22
- }),
23
- yes: Flags.boolean({
24
- char: 'y',
25
- default: false,
26
- description: 'Skip confirmation prompt',
27
- }),
28
- };
29
- async init() {
30
- await super.init();
31
- await this.container
32
- .initConfigManager()
33
- .initAccountManager()
34
- .initBlockchainConnector()
35
- .initProviderClient({ enableAuth: true })
36
- .build();
37
- }
38
- async run() {
39
- const { args, flags } = await this.parse(WorkflowsExtendLease);
40
- const { providerClient } = this.container;
41
- try {
42
- this.logger.info(`Checking order ${args.orderId}`);
43
- // Get actual per-hour price from blockchain
44
- const amountPerHour = await Orders.calculateWorkflowPerHourPrice(args.orderId);
45
- let tokenAmount;
46
- let minutes;
47
- if (flags.minutes) {
48
- // Calculate token amount from minutes
49
- tokenAmount = (BigInt(amountPerHour) * BigInt(flags.minutes)) / 60n;
50
- minutes = flags.minutes;
51
- }
52
- else if (flags.sppi) {
53
- // Use provided SPPI amount
54
- tokenAmount = parseEther(flags.sppi);
55
- minutes = Number((tokenAmount * 60n) / BigInt(amountPerHour));
56
- }
57
- else {
58
- this.error('Please provide either --sppi or --minutes flag to specify the replenishment amount');
59
- return;
60
- }
61
- // Confirmation prompt
62
- const confirmed = this.flags.yes ||
63
- (await this.selectPrompt({
64
- message: `Deposit will be replenished by ${formatEther(tokenAmount)} SPPI. Order time is extended by ${minutes} minutes. Confirm?`,
65
- options: [
66
- { label: 'Yes', value: true },
67
- { label: 'No', value: false },
68
- ],
69
- }));
70
- if (!confirmed) {
71
- this.logger.info('Operation cancelled by user');
72
- return;
73
- }
74
- // Call API to replenish deposit
75
- const { data, error } = await providerClient.POST('/api/workflows/{orderId}/replenish', {
76
- body: {
77
- amount: tokenAmount.toString(),
78
- },
79
- params: {
80
- path: {
81
- orderId: args.orderId,
82
- },
83
- },
84
- });
85
- if (error) {
86
- this.logger.error({ error }, `Order ${args.orderId} was not replenished`);
87
- this.error(`Failed to replenish deposit: ${error.message || 'Unknown error'}`);
88
- return;
89
- }
90
- this.logger.info({ data }, 'Deposit replenished successfully');
91
- this.log('Deposit replenished successfully');
92
- }
93
- catch (error) {
94
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
95
- this.logger.error({ error }, `Order ${args.orderId} was not replenished`);
96
- this.error(`Order ${args.orderId} was not replenished: ${errorMessage}`);
97
- }
98
- }
99
- async selectPrompt(options) {
100
- return promptService.select(options);
101
- }
102
- }
@@ -1,3 +0,0 @@
1
- import type { Hook } from '@oclif/core';
2
- declare const hook: Hook<'finally'>;
3
- export default hook;
@@ -1,8 +0,0 @@
1
- import { BlockchainConnector } from '@super-protocol/sdk-js';
2
- const hook = async () => {
3
- const connector = BlockchainConnector.getInstance();
4
- if (connector.isInitialized()) {
5
- connector.shutdown();
6
- }
7
- };
8
- export default hook;
@@ -1,9 +0,0 @@
1
- import type { MiddlewareFn, ProviderClient } from '@super-protocol/provider-client';
2
- import type pino from 'pino';
3
- import type { Auth } from '../config/config.schema.js';
4
- interface CredentialsStorage {
5
- getCredentials(): Promise<Auth | undefined>;
6
- setCredentials(auth: Auth): void;
7
- }
8
- export declare function createAuthMiddleware(configManager: CredentialsStorage, providerClient: ProviderClient, logger: pino.BaseLogger): Promise<ReturnType<MiddlewareFn>>;
9
- export {};
@@ -1,91 +0,0 @@
1
- import { decode } from 'jsonwebtoken';
2
- import { REFRESH_TOKEN_URI } from '../constants.js';
3
- import { AuthorizationRequiredError } from '../errors.js';
4
- function isAccessKeyExpired(accessKey) {
5
- try {
6
- const payload = decode(accessKey);
7
- if (!payload || typeof payload.exp !== 'number') {
8
- return true;
9
- }
10
- const now = Math.floor(Date.now() / 1000);
11
- return now >= payload.exp;
12
- }
13
- catch {
14
- return true;
15
- }
16
- }
17
- export async function createAuthMiddleware(configManager, providerClient, logger) {
18
- let auth;
19
- let refreshPromise;
20
- const performRefresh = async () => {
21
- if (!auth) {
22
- return undefined;
23
- }
24
- logger.info('Performed refresh token');
25
- let refreshResult;
26
- try {
27
- refreshResult = await providerClient.POST(REFRESH_TOKEN_URI);
28
- }
29
- catch (error) {
30
- logger.error({ err: error }, 'failure refresh token');
31
- const message = error instanceof Error ? error.message : 'Unknown error';
32
- throw new AuthorizationRequiredError(`Unable to reach provider API: ${message}`);
33
- }
34
- const { data, error: refreshError } = refreshResult;
35
- if (refreshError) {
36
- logger.error({ refreshError }, 'Failure refresh response');
37
- throw new AuthorizationRequiredError(`Unable to refresh access key: ${JSON.stringify(refreshError)}`);
38
- }
39
- if (!data || !data.accessToken) {
40
- logger.error({ response: data }, 'Server returned incorrect response');
41
- throw new AuthorizationRequiredError('Provider returned an unexpected refresh response.');
42
- }
43
- const updatedAuth = {
44
- accessKey: data.accessToken,
45
- };
46
- await setCredentials(updatedAuth);
47
- return updatedAuth.accessKey;
48
- };
49
- const refreshAccessKey = async () => {
50
- if (!auth) {
51
- return undefined;
52
- }
53
- if (!refreshPromise) {
54
- refreshPromise = performRefresh().finally(() => {
55
- refreshPromise = undefined;
56
- });
57
- }
58
- return refreshPromise;
59
- };
60
- const ensureAccessKey = async (forceRefresh = false) => {
61
- if (!auth) {
62
- return undefined;
63
- }
64
- const { accessKey } = auth;
65
- if (!forceRefresh && accessKey && !isAccessKeyExpired(accessKey)) {
66
- return accessKey;
67
- }
68
- return refreshAccessKey();
69
- };
70
- const setCredentials = async (newAuth) => {
71
- auth = newAuth;
72
- await configManager.setCredentials(newAuth);
73
- };
74
- auth = await configManager.getCredentials();
75
- if (!auth) {
76
- throw new AuthorizationRequiredError('Authorization not found please login first');
77
- }
78
- const middleware = {
79
- async onRequest({ request }) {
80
- if (request.url.endsWith(REFRESH_TOKEN_URI)) {
81
- return request;
82
- }
83
- const accessToken = await ensureAccessKey();
84
- if (accessToken) {
85
- request.headers.set('Authorization', `Bearer ${accessToken}`);
86
- }
87
- return request;
88
- },
89
- };
90
- return middleware;
91
- }
@@ -1,8 +0,0 @@
1
- import type { MiddlewareFn } from '@super-protocol/provider-client';
2
- import type pino from 'pino';
3
- interface CookiesStorage {
4
- getCookies(): Promise<unknown>;
5
- setCookies(cookies: unknown): Promise<void>;
6
- }
7
- export declare const createCookieMiddleware: (configManager: CookiesStorage, logger: pino.BaseLogger, baseUrl: string) => Promise<ReturnType<MiddlewareFn>>;
8
- export {};
@@ -1,80 +0,0 @@
1
- import { CookieJar } from 'tough-cookie';
2
- const extractSetCookieHeaders = (response) => {
3
- const cookiesFromGetter = response.headers.getSetCookie?.();
4
- if (cookiesFromGetter && cookiesFromGetter.length > 0) {
5
- return cookiesFromGetter;
6
- }
7
- // For capability to nodejs < 20
8
- const headersWithRaw = response.headers;
9
- const raw = headersWithRaw.raw?.();
10
- const headerList = raw?.['set-cookie'];
11
- if (headerList && headerList.length > 0) {
12
- return headerList;
13
- }
14
- const headerValue = response.headers.get('set-cookie');
15
- return headerValue ? [headerValue] : [];
16
- };
17
- export const createCookieMiddleware = async (configManager, logger, baseUrl) => {
18
- let cookieJar = new CookieJar();
19
- const loadCookieJar = async () => {
20
- try {
21
- const stored = await configManager.getCookies();
22
- if (stored && typeof stored === 'object') {
23
- cookieJar = CookieJar.fromJSON(stored);
24
- return;
25
- }
26
- }
27
- catch (error) {
28
- logger.warn({ err: error }, 'Failed to load cookies from config');
29
- }
30
- cookieJar = new CookieJar();
31
- };
32
- const persistCookieJar = async () => {
33
- try {
34
- const serialized = cookieJar.toJSON();
35
- await configManager.setCookies(serialized);
36
- }
37
- catch (error) {
38
- logger.warn({ err: error }, 'Failed to persist cookies');
39
- }
40
- };
41
- await loadCookieJar();
42
- return {
43
- async onRequest({ request }) {
44
- const requestUrl = request.url ?? baseUrl;
45
- try {
46
- const cookieHeader = await cookieJar.getCookieString(requestUrl);
47
- if (cookieHeader) {
48
- request.headers.set('Cookie', cookieHeader);
49
- }
50
- }
51
- catch (error) {
52
- logger.warn({ err: error, requestUrl }, 'Failed to attach cookies to request');
53
- }
54
- },
55
- async onResponse({ response }) {
56
- const rawCookies = extractSetCookieHeaders(response);
57
- if (rawCookies.length === 0) {
58
- return response;
59
- }
60
- const targetUrl = response.url || baseUrl;
61
- const updates = await Promise.all(rawCookies.map(async (rawCookie) => {
62
- try {
63
- const storedCookie = await cookieJar.setCookie(rawCookie, targetUrl);
64
- if (storedCookie) {
65
- logger.debug({ cookie: storedCookie.key }, 'Updated cookie from response');
66
- }
67
- return true;
68
- }
69
- catch (error) {
70
- logger.warn({ err: error, rawCookie }, 'Failed to store cookie from response');
71
- return false;
72
- }
73
- }));
74
- if (updates.some(Boolean)) {
75
- await persistCookieJar();
76
- }
77
- return response;
78
- },
79
- };
80
- };
@@ -1,73 +0,0 @@
1
- import { type EncryptionWithIV, type Resource, type RuntimeInputInfo } from '@super-protocol/dto-js';
2
- import { type AddStorageDto, type ProviderClient, type StorageResponseDto, type UpdateStorageDto } from '@super-protocol/provider-client';
3
- import type pino from 'pino';
4
- export declare class StorageError extends Error {
5
- }
6
- export declare class StoragesUndefinedError extends StorageError {
7
- }
8
- export declare class StorageCreateError extends StorageError {
9
- }
10
- export declare class StorageUpdateError extends StorageError {
11
- }
12
- export declare class StorageGetError extends StorageError {
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;
38
- export declare class StorageService {
39
- private readonly providerClient;
40
- private readonly logger;
41
- constructor(providerClient: ProviderClient, logger: pino.BaseLogger);
42
- createStorage(storage: AddStorageDto): Promise<StorageResponseDto>;
43
- download(params: IDownloadParams, progressCb: ProgressCb): Promise<void>;
44
- getCentralizedStorage(): Promise<StorageResponseDto>;
45
- getCurrentStorage(): Promise<StorageResponseDto>;
46
- getLabel(storage: StorageResponseDto): string;
47
- hasStorage(): Promise<boolean>;
48
- initCentralizedStorage(): Promise<{
49
- bucket: string;
50
- createdAt: string;
51
- id: string;
52
- isCentralized: boolean;
53
- prefix: string;
54
- s3Credentials?: import("@super-protocol/provider-client").components["schemas"]["S3CredentialsResponseDto"];
55
- storageType: import("@super-protocol/provider-client").components["schemas"]["StorageType"];
56
- storjCredentials?: import("@super-protocol/provider-client").components["schemas"]["StorJCredentialsResponseDto"];
57
- updatedAt: string;
58
- userId: string;
59
- }>;
60
- requestStorages(): Promise<StorageResponseDto[]>;
61
- saveStorage(selectedStorage: string): Promise<{
62
- activeStorageId: string;
63
- createdAt: string;
64
- decentralizedStorageId?: string;
65
- id: string;
66
- updatedAt: string;
67
- userId: string;
68
- } | undefined>;
69
- updateStorage(id: string, storage: UpdateStorageDto): Promise<StorageResponseDto>;
70
- upload(params: IUploadParams, progressCb: ProgressCb): Promise<void>;
71
- private getStorageCredentials;
72
- }
73
- export {};