-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
949 lines (860 loc) · 25.2 KB
/
index.js
File metadata and controls
949 lines (860 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
/*
* Copyright 2013-2026 Erudika. https://erudika.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For issues and patches go to: https://github.com/erudika
*/
/* eslint-disable padding-line-between-statements */
/* eslint-disable max-params */
/* eslint-disable function-call-argument-newline */
/* eslint-disable spaced-comment */
/* eslint-disable capitalized-comments */
/* eslint complexity: ["error", 21] */
/* eslint indent: ["error", "tab"] */
/* eslint object-curly-spacing: ["error", "always"] */
/* global console, process, Buffer */
import { readFileSync, statSync, writeFileSync } from 'node:fs';
import { basename, relative, resolve } from 'node:path';
import { URL } from 'node:url';
import { TextEncoder } from 'node:util';
import input from '@inquirer/input';
import password from '@inquirer/password';
import chalk from 'chalk';
import { globbySync } from 'globby';
import { Parser } from 'htmlparser2';
import jsonwebtoken from 'jsonwebtoken';
import { lookup } from 'mime-types';
import { Pager, ParaClient, ParaObject } from 'para-client-js';
import striptags from 'striptags';
import apiClient from 'superagent';
const encoder = new TextEncoder('utf-8');
const { cyan, red, yellow, green } = chalk;
const { sign } = jsonwebtoken;
const MAX_FILE_SIZE = 350 * 1024;
var defaultConfig = { accessKey: '', secretKey: '', endpoint: 'https://paraio.com' };
const _defaultConfig = defaultConfig;
export { _defaultConfig as defaultConfig };
export async function setup(config) {
try {
const accessKey = await input({
message: 'Para Access Key:',
default: config.get('accessKey') || 'app:para'
});
const secretKey = await password({
message: 'Para Secret Key:',
mask: '*'
});
const endpoint = await input({
message: 'Para Endpoint:',
default: defaultConfig.endpoint
});
var access = (accessKey || config.get('accessKey') || 'app:para').trim();
var secret = (secretKey || config.get('secretKey')).trim();
var endpointValue = (endpoint || defaultConfig.endpoint).trim();
newJWT(access, secret, endpointValue, config);
ping(config);
if (access === 'app:para') {
listApps(config, {}, access, async () => {
// if none, ask to create one
const shouldCreate = await input({
message: 'Would you like to create a new Para app? [Y/n]',
default: 'Y'
});
const Yn = shouldCreate.trim();
if ('' === Yn || 'y' === Yn.toLowerCase()) {
const appname = await input({
message: 'App name:'
});
newApp(['', appname], config, {});
}
});
}
} catch (error) {
if (error.name === 'ExitPromptError') {
console.log('\nSetup cancelled.');
} else {
throw error;
}
}
}
export function createAll(input, config, flags = {}) {
if (!input[1]) {
fail('No files specified.');
return;
}
const pc = getClient(config, flags);
var files = globbySync(input[1], { realpath: true });
var totalSize = 0;
var totalObjects = 0;
var batches = [[]];
var batchId = 0;
var batchSize = 0;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var stats = statSync(file);
var filePath = relative(flags.cwd || '.', file);
var fileType = lookup(file) || 'text/plain';
var fileBody = '';
var id;
if (!stats?.isFile()) {
console.error(red('✖'), yellow(file), 'is not a file.');
continue;
}
if (fileType.match(/text\/.*/)) {
totalObjects++;
totalSize += stats.size;
batchSize += stats.size;
fileBody = readFile(file);
var json = {};
if (fileType === 'text/html') {
json = parseHTML(fileBody);
} else {
json = { text: striptags(fileBody).replace(/[\s]+/gi, ' ') };
}
if (flags.sanitize) {
json.text = json.text.replace(/[^0-9\p{L}]+/giu, ' ').replace(/[\s]+/gi, ' ');
}
id = i === 0 && flags.id ? flags.id : json.url || filePath;
var textEncoded = encoder.encode(json.text);
//batchSize += textEncoded.length;
if (textEncoded.length > MAX_FILE_SIZE) {
console.log(red('!'), yellow('File is larger than', MAX_FILE_SIZE / 1024, 'KB - splitting into chunks...'));
sendFileChunk(1, textEncoded, json, id, flags, 0, MAX_FILE_SIZE, pc);
} else {
if (batchSize > MAX_FILE_SIZE) {
batchId++;
batches[batchId] = [];
console.log(yellow('*'), 'Batch', yellow(batchId), 'is', Math.round(batchSize / 1024), 'KB.');
batchSize = 0;
}
addObjectsToBatch(batches[batchId], json, id, flags);
console.log(green('✔'), 'Creating', yellow(id));
}
} else if (fileType === 'application/json') {
totalObjects++;
id = i === 0 && flags.id ? flags.id : filePath;
totalSize += stats.size;
batchSize += stats.size;
if (batchSize > MAX_FILE_SIZE) {
batchId++;
batches[batchId] = [];
console.log(yellow('*'), 'Batch', yellow(batchId), 'is', Math.round(batchSize / 1024), 'KB.');
batchSize = 0;
}
addObjectsToBatch(batches[batchId], JSON.parse(readFile(file)), id, flags);
console.log(green('✔'), 'Creating', yellow(id));
} else {
console.error(red('✖'), 'Skipping', yellow(file), "- isn't JSON, HTML nor text.");
}
}
for (var k = 0; k < batches.length; k++) {
var objectsList = batches[k];
if (objectsList.length > 0) {
pc.createAll(objectsList)
.then((data) => {
console.log(green('✔'), 'Created', data.length, 'objects.');
})
.catch((err) => {
fail('Failed to create documents:', err);
});
}
}
console.log(green('✔'), 'Created', totalObjects, 'objects with a total size of', Math.round(totalSize / 1024), 'KB.');
}
export function readAll(config, flags = {}) {
const pc = getClient(config, flags);
if (flags.id) {
var readIds = flags.id;
if (!Array.isArray(readIds)) {
readIds = [readIds];
}
pc.readAll(readIds)
.then((data) => {
console.log(JSON.stringify(data, null, 2));
})
.catch((err) => {
fail('Failed to read object:', err);
});
} else {
fail('Must specify object id(s).');
}
}
export function updateAll(input, config, flags = {}) {
if (!input[1]) {
fail('No files specified.');
return;
}
const pc = getClient(config, flags);
var files = globbySync(input[1], { realpath: true });
var updateList = [];
for (var i = 0; i < files.length; i++) {
var file = files[i];
var stats = statSync(file);
var fileType = lookup(file) || 'text/plain';
var defaultId = relative(flags.cwd || '.', file);
if (fileType !== 'application/json') {
console.error(red('✖'), yellow(file), 'skipped because it is not a JSON file');
continue;
}
if (!stats?.isFile()) {
console.error(red('✖'), yellow(file), 'is not a file.');
continue;
}
var fileJSON = JSON.parse(readFile(file));
var id = fileJSON.id || defaultId;
addObjectsToBatch(updateList, fileJSON, id, flags);
console.log(green('✔'), 'Updating', yellow(id));
}
pc.updateAll(updateList)
.then(() => {
console.log(green('✔'), 'Updated', updateList.length, 'files.');
})
.catch((err) => {
fail('Failed to read object:', err);
});
}
export function deleteAll(input, config, flags = {}) {
const pc = getClient(config, flags);
if (flags.id || input[1]) {
var deleteIds = globbySync(input[1] || ' ', { realpath: true });
if (deleteIds.length === 0) {
deleteIds = Array.isArray(flags.id) ? flags.id : [String(flags.id)];
}
for (var i = 0; i < deleteIds.length; i++) {
deleteIds[i] = basename(String(deleteIds[i]));
}
pc.deleteAll(deleteIds)
.then(() => {
console.log(green('✔'), 'Deleted objects "', deleteIds, '" from Para.');
})
.catch((err) => {
fail('Failed to delete objects:', err);
});
} else {
fail('No files specified.');
}
}
export function newKeys(config, flags = {}) {
const pc = getClient(config, flags);
pc.newKeys()
.then((keys) => {
config.set('secretKey', keys.secretKey);
console.log(green('✔'), 'New JWT generated and saved in', yellow(config.path));
})
.catch((err) => {
fail('Failed to generate new secret key:', err);
});
}
export function newJWT(accessKey, secretKey, endpoint, config, flags) {
if (!accessKey || accessKey.length < 3 || !secretKey || secretKey.length < 6) {
fail('Invalid credentials.');
return;
}
var now = Math.round(Date.now() / 1000);
var sClaim = JSON.stringify({
exp: now + 7 * 24 * 60 * 60,
iat: now,
nbf: now - 5, // allow for 5 seconds time difference in clocks
appid: accessKey
});
var selectedApp = config.get('selectedApp');
if (selectedApp?.secretKey) {
selectedApp.accessKey = accessKey;
selectedApp.secretKey = secretKey;
config.set('selectedApp', selectedApp);
} else {
config.set('accessKey', accessKey);
config.set('secretKey', secretKey);
}
config.set('endpoint', endpoint || config.get('endpoint'));
config.set('jwt', sign(sClaim, secretKey, { algorithm: 'HS256' }));
if (flags?.print) {
console.log(yellow(config.get('jwt')));
} else {
console.log(green('✔'), 'New JWT generated and saved in', yellow(config.path));
}
}
export function newApp(input, config, flags = {}) {
if (!input[1]) {
fail('App name not specified.');
return;
}
const pc = getClient(config, flags);
var appid = input[1];
var req = pc.invokeGet(`_setup/${appid}`, { name: flags.name || appid, shared: flags.shared || false });
pc.getEntity(req)
.then((resp) => {
if (resp?.secretKey) {
console.log(green('✔'), 'App created:');
console.log(JSON.stringify(resp, null, 2));
} else {
console.log(green('✔'), yellow(`App "${appid}" already exists.`));
}
})
.catch((err) => {
fail('Failed to create app:', err);
});
}
export async function deleteApp(inputArgs, config, flags = {}) {
if (!inputArgs[1]) {
fail('App id not specified.');
return;
}
const pc = getClient(config, flags);
var appid = inputArgs[1];
if (appid.indexOf('app:') < 0) {
appid = `app:${appid}`;
}
try {
const confirm = await input({
message: `${red.bold(`Are you sure you want to delete ${appid}? ALL DATA FOR THAT APP WILL BE LOST! `)}yes/No`
});
if (confirm === 'yes') {
pc.invokeDelete(`apps/${appid}`, {})
.then((resp) => {
if (resp?.ok) {
console.log(green('✔'), `App ${red.bold(appid)} was deleted!`);
} else {
console.log(green('✔'), yellow(`App "${appid}" could not be deleted.`));
}
})
.catch((err) => {
fail('Failed to delete app:', err);
});
}
} catch (error) {
if (error.name === 'ExitPromptError') {
console.log('\nDelete cancelled.');
} else {
throw error;
}
}
}
export function ping(config, flags = {}) {
const pc = getClient(config, flags);
pc.me()
.then((mee) => {
pc.getServerVersion()
.then((ver) => {
console.log(
green('✔'),
`Connected to Para server ${cyan.bold(`v${ver}`)}`,
`on ${cyan(pc.endpoint)}. Authenticated as:`,
cyan(`${mee.type} ${mee.name} (${mee.id})`)
);
})
.catch(() => {
fail('Connection failed. Run "para-cli setup" or check the configuration file', yellow(config.path));
process.exit(1);
});
})
.catch(() => {
fail('Connection failed. Run "para-cli setup" or check the configuration file', yellow(config.path));
process.exit(1);
});
}
export function me(config, flags = {}) {
const pc = getClient(config, flags);
pc.me()
.then((mee) => {
console.log(JSON.stringify(mee, null, 2));
})
.catch(() => {
fail('Connection failed. Server might be down. Check the configuration file', yellow(config.path));
});
}
export function types(config, flags = {}) {
const pc = getClient(config, flags);
const _types = pc
.getEntity(pc.invokeGet('_types'))
.then((data) => {
console.log(JSON.stringify(data, null, 2));
})
.catch(() => {
fail('Connection failed. Server might be down. Check the configuration file', yellow(config.path));
});
}
export function exportData(config, flags = {}) {
const pc = getClient(config, flags);
pc.invokeGet('/_export')
.then((data) => {
try {
var filename = data.headers['content-disposition'] || 'export.zip';
var filesize = Math.round(((data.headers['content-length'] || 0) / 1000000) * 100) / 100;
filename = filename.substring(filename.lastIndexOf('=') + 1);
writeFileSync(filename, data.body);
console.log(green('✔'), yellow(`Exported ${filesize}MB of data to file ${filename}`));
} catch (e) {
console.error(e);
}
})
.catch(() => {
fail('Connection failed. Server might be down. Check the configuration file', yellow(config.path));
});
}
export function importData(input, config, flags = {}) {
if (!input[1]) {
fail('No file to import.');
return;
}
const pc = getClient(config, flags);
if (!config.get('jwt')) {
newJWT(config.get('accessKey'), config.get('secretKey'), config.get('endpoint'), config);
}
var headers = {
'User-Agent': 'Para CLI tool',
'Content-Type': 'application/zip',
Authorization: `Bearer ${config.get('jwt')}`
};
try {
apiClient
.put(`${pc.endpoint}/v1/_import`)
.set(headers)
.send(readFileSync(resolve(input[1])))
.then((res) => {
console.log(green('✔'), `${yellow(`Imported ${res.body.count} object into app "${res.body.appid}`)}"`);
})
.catch((e) => {
fail(`Import request failed. ${e}`);
});
} catch (e) {
fail(`Import request failed: ${e}`);
}
}
function promiseWhile(results, fn) {
return new Promise((resolve, _reject) => {
function loop() {
return Promise.resolve(fn()).then((result) => {
if (result && result.length > 0) {
result.forEach((res) => {
results.push(res);
});
return loop();
}
resolve();
});
}
loop();
});
}
export function search(input, config, flags = {}) {
const pc = getClient(config, flags);
var p = new Pager(flags.page, flags.sort, flags.desc, flags.limit);
if (flags.lastKey) {
p.lastKey = flags.lastKey;
}
if (flags.page && flags.page === 'all') {
var results = [];
p.sortby = '_docid';
p.page = 1;
promiseWhile(results, () => pc.findQuery(getType(flags.type), String(input[1]) || '', p))
.then(() => {
console.log(JSON.stringify(results, null, 2));
})
.catch((err) => {
fail('Search failed.', err);
});
} else {
pc.findQuery(getType(flags.type), String(input[1]) || '', p)
.then((resp) => {
console.log(JSON.stringify(resp, null, 2));
})
.catch((err) => {
fail('Search failed.', err);
});
}
}
export function appSettings(config, flags = {}) {
const pc = getClient(config, flags);
pc.appSettings()
.then((settings) => {
console.log(JSON.stringify(settings, null, 2));
})
.catch(() => {
fail('Connection failed. Check the configuration file', yellow(config.path));
});
}
export function rebuildIndex(config, flags = {}) {
const pc = getClient(config, flags);
pc.rebuildIndex(flags.destinationIndex)
.then((response) => {
console.log(JSON.stringify(response, null, 2));
})
.catch((err) => {
fail('Reindex failed.', err);
});
}
export function listApps(config, flags, parentAccessKey, failureCallback) {
var pc = getClient(config, flags);
var selectedEndpoint = getSelectedEndpoint(config, flags);
var p = new Pager();
var results = [];
p.sortby = '_docid';
p.page = 1;
promiseWhile(results, () => pc.findQuery('app', '*', p))
.then(() => {
var apps = results.map((app) => app.appIdentifier.trim());
if (apps.length) {
console.log(
'Found',
p.count,
`apps on ${cyan(selectedEndpoint.endpoint)}:\n`,
yellow('[') + green(apps.join(yellow('] ['))) + yellow(']')
);
console.log(
'\nTyping',
cyan('para-cli select'),
green(apps[0]),
'will switch to that app. \nCurrent app:',
green(parentAccessKey)
);
process.exit(0);
} else {
failureCallback();
}
})
.catch((_err) => {
failureCallback();
});
}
export function selectApp(input, config, flags) {
var selectedEndpoint = getSelectedEndpoint(config, flags);
var accessKey = selectedEndpoint.accessKey;
var secretKey = selectedEndpoint.secretKey;
if (accessKey === 'app:para' && secretKey) {
var selectedApp = `app:${(input[1] || 'para').trim()}`;
if (selectedApp === 'app:para') {
config.set('selectedApp', selectedEndpoint);
console.log(green('✔'), 'Selected', green(selectedApp), 'as the current app.');
return;
}
var now = Math.round(Date.now() / 1000);
var jwt = sign(
JSON.stringify({
iat: now,
exp: now + 10,
nbf: now - 5, // allow for 5 seconds time difference in clocks
appid: accessKey,
getCredentials: selectedApp
}),
secretKey,
{ algorithm: 'HS256' }
);
var paraClient = getClient(config, flags);
paraClient.setAccessToken(jwt);
paraClient
.me(jwt)
.then((data) => {
if (data?.credentials) {
config.set('selectedApp', data.credentials);
console.log(green('✔'), 'Selected', green(selectedApp), 'as the current app.');
} else {
fail(`That did not work -${red(input[1])} try updating Para to the latest version.`);
}
})
.catch((_err) => {
fail(`App ${red(input[1])} not found!`);
});
} else {
fail('This command only works when Para CLI is configured to use the keys for the root app.');
}
}
export function listEndpoints(config, flags, failureCallback) {
var accessKey = flags.accessKey || process.env.PARA_ACCESS_KEY || config.get('accessKey');
var secretKey = flags.secretKey || process.env.PARA_SECRET_KEY || config.get('secretKey');
var endpoint = flags.endpoint || process.env.PARA_ENDPOINT || config.get('endpoint');
var endpoints = config.get('endpoints') || [];
var list = [{ endpoint: endpoint, accessKey: accessKey, secretKey: secretKey }].concat(endpoints);
if (list.length === 0) {
failureCallback();
return [];
}
for (var i = 0; i < list.length; i++) {
var ep = list[i];
var selected = (config.get('selectedEndpoint') || 0) === i;
var rootAppConfigured = ep.accessKey === 'app:para' && ep.secretKey.length > 10;
console.log(
yellow(selected ? ' ➤' : ' ', `${i + 1}. `) + cyan(ep.endpoint),
rootAppConfigured ? green('✔ root app configured') : red('root app not configured')
);
}
return list;
}
export async function addEndpoint(config) {
try {
const endpoint = await input({
message: 'Para Endpoint:'
});
if (!isValidUrl(endpoint)) {
fail('Endpoint must be a valid URL.');
return;
}
const secretKey = await password({
message: 'Para Secret Key (for root app app:para):',
mask: '*'
});
var endpoints = config.get('endpoints') || [];
var existing = false;
for (var i = 0; i < endpoints.length; i++) {
var ep = endpoints[i];
if (ep.endpoint === endpoint) {
ep.secretKey = secretKey;
existing = true;
}
}
if (!existing) {
endpoints.push({ accessKey: 'app:para', secretKey: secretKey, endpoint: endpoint });
}
config.set('endpoints', endpoints);
ping(config);
} catch (error) {
if (error.name === 'ExitPromptError') {
console.log('\nAdd endpoint cancelled.');
} else {
throw error;
}
}
}
export async function removeEndpoint(config, flags) {
var list = listEndpoints(config, flags, () => {
console.log('No endpoints found.');
});
try {
const index = await input({
message: 'Type the number of the Para endpoint to remove:'
});
var selectedEndpoint = 0;
if (!Number.isNaN(index) && index <= list.length && index >= 1) {
selectedEndpoint = index - 1;
}
var url = list[selectedEndpoint].endpoint;
if (selectedEndpoint === 0) {
config.set('accessKey', 'app:para');
config.set('secretKey', '');
config.set('endpoint', defaultConfig.endpoint);
} else {
if (selectedEndpoint === config.get('selectedEndpoint')) {
config.delete('selectedEndpoint');
config.delete('selectedApp');
}
list.splice(selectedEndpoint, 1);
list.shift();
config.set('endpoints', list);
}
console.log(`Removed endpoint: ${cyan(url)}`);
} catch (error) {
if (error.name === 'ExitPromptError') {
console.log('\nRemove endpoint cancelled.');
} else {
throw error;
}
}
}
export async function selectEndpoint(config, flags) {
var list = listEndpoints(config, flags, () => {
console.log('No endpoints found.');
});
try {
const index = await input({
message: 'Type the number of the Para endpoint to select:'
});
var selectedEndpoint = 0;
if (!Number.isNaN(index) && index <= list.length && index >= 1) {
selectedEndpoint = index - 1;
}
config.delete('selectedApp');
config.set('selectedEndpoint', selectedEndpoint);
console.log(`Selected endpoint: ${cyan(list[selectedEndpoint].endpoint)}`);
} catch (error) {
if (error.name === 'ExitPromptError') {
console.log('\nSelect endpoint cancelled.');
} else {
throw error;
}
}
}
export function parseEndpoint(endpoint) {
try {
var url = new URL(endpoint);
if (url.pathname !== '/') {
var x = { endpoint: `${url.protocol}//${url.host}`, apiPath: `${url.pathname.replace(/\/*$/, '')}/v1/` };
return x;
}
} catch (e) {
fail(`Invalid Para endpoint: ${endpoint}`, e);
}
return { endpoint: endpoint };
}
function getSelectedEndpoint(config, flags) {
var accessKey = flags.accessKey || process.env.PARA_ACCESS_KEY || config.get('accessKey');
var secretKey = flags.secretKey || process.env.PARA_SECRET_KEY || config.get('secretKey');
var endpoint = flags.endpoint || process.env.PARA_ENDPOINT || config.get('endpoint');
var endpoints = [{ endpoint: endpoint, accessKey: accessKey, secretKey: secretKey }].concat(
config.get('endpoints') || []
);
try {
return endpoints[config.get('selectedEndpoint') || 0];
} catch (_e) {
config.delete('selectedEndpoint');
return endpoints[0];
}
}
function getClient(config, flags = {}) {
var selectedEndpoint = getSelectedEndpoint(config, flags);
return new ParaClient(
selectedEndpoint.accessKey,
selectedEndpoint.secretKey,
parseEndpoint(selectedEndpoint.endpoint)
);
}
function sendFileChunk(chunkId, textEncoded, json, id, flags, start, end, pc, decoder) {
if (start > 0 && textEncoded[start] !== 32) {
for (var i = 0; i < 100 && start - i >= 0; i++) {
if (textEncoded[start - i] === 32) {
start = start - i + 1;
break;
}
}
}
if (end >= textEncoded.length) {
end = textEncoded.length;
}
if (textEncoded[end] !== 32) {
for (var j = 0; j < 100 && end - j >= 0; j++) {
if (textEncoded[end - j] === 32) {
end -= j;
break;
}
}
}
if (typeof decoder === 'undefined') {
decoder = new TextDecoder();
}
var chunk = textEncoded.slice(start, end);
var text = decoder.decode(chunk);
var obj = getParaObject(Object.assign({}, json, { text: text }), `${id}_chunk${chunkId}`, flags);
if (text && text.trim().length > 0) {
obj.chunkid = chunkId;
pc.create(obj)
.then(() => {
console.log(
green('✔'),
'Created object chunk',
yellow(chunkId),
'with size',
Math.round(chunk.length / 1024),
'KB.'
);
if (end < textEncoded.length) {
sendFileChunk(
++chunkId,
textEncoded,
json,
id,
flags,
start + MAX_FILE_SIZE,
end + MAX_FILE_SIZE,
pc,
decoder
);
}
})
.catch((err) => {
fail('Failed to create chunk:', err);
});
}
}
function addObjectsToBatch(list, json, id, flags) {
var objects = Array.isArray(json) ? json : [json];
for (var i = 0; i < objects.length; i++) {
list.push(getParaObject(objects[i], id, flags));
}
return objects;
}
function getParaObject(json, id, flags) {
var pobj = new ParaObject();
if (flags?.type) {
pobj.setType(getType(flags.type));
}
id = String(id);
if (flags && flags.encodeId === 'false') {
pobj.setId(id);
} else {
pobj.setId(Buffer.from(id || '').toString('base64'));
}
pobj.setName(id);
pobj.setFields(json);
return pobj;
}
function getType(type) {
if (type && type.trim().length > 0) {
return type.replace(/[^\w\s]/giu, ' ').replace(/[\s]+/gi, '-');
}
return null;
}
function parseHTML(file) {
var title = null;
var url = null;
var text = '';
var inScript = false;
var inAnchor = false;
var parser = new Parser(
{
onopentag: (tag, attribs) => {
if (tag === 'meta' && attribs.property === 'og:title') {
title = attribs.content;
}
if (tag === 'meta' && attribs.property === 'og:url') {
url = attribs.content;
}
inScript = tag === 'script';
inAnchor = tag === 'a' && attribs.href && !attribs.href.match(/^http/i);
},
ontext: (txt) => {
if (!inScript && !inAnchor) {
text += ` ${txt}`;
}
},
onclosetag: () => {
inScript = false;
inAnchor = false;
}
},
{ decodeEntities: true }
);
parser.write(file);
parser.end();
return {
name: title,
url: url,
text: (text || ' ').replace(/[\s]+/gi, ' ')
};
}
function isValidUrl(url) {
try {
new URL(url);
return true;
} catch (_err) {
return false;
}
}
function readFile(filePath) {
return readFileSync(filePath, { encoding: 'utf8' });
}
function fail(msg, err) {
var errMsg = err?.response?.body?.message ? err.response.body.message : err || '';
var code = err?.response?.status ? `(${err.response.status} ${err.response.res.statusMessage})` : '';
console.error(red('✖'), msg || 'Forgive me, I have failed you!', red(errMsg), red(code));
process.exitCode = 1;
}