-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1199 lines (1035 loc) · 36 KB
/
Copy pathcli.js
File metadata and controls
executable file
·1199 lines (1035 loc) · 36 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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Web Ledgers CLI
* Interactive command-line interface for Web Ledgers
*/
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const inquirer = require('inquirer');
const { Command } = require('commander');
const ora = require('ora');
const Table = require('cli-table3');
const figlet = require('figlet');
const { version } = require('./package.json');
// Import our Web Ledgers library
const {
WebLedger,
Entry,
createLedger,
loadLedger,
validateLedgerData,
generateLedgerId
} = require('./index.js');
const program = new Command();
// Default paths following RFC 5785 well-known URI conventions
const DEFAULT_LEDGER_PATH = '.well-known/webledgers/webledgers.json';
// CLI Configuration
program
.name('webledgers')
.description('Web Ledgers CLI - Manage URI-to-balance mappings')
.version(version);
/**
* Display the welcome banner
*/
function displayBanner () {
console.log(chalk.cyan(figlet.textSync('Web Ledgers', { horizontalLayout: 'fitted' })));
console.log(chalk.gray(`URI-to-Balance Mapping System v${version}`));
console.log(chalk.gray(`Default location: ${DEFAULT_LEDGER_PATH}\n`));
}
/**
* Pretty print a ledger in table format
*/
function displayLedger (ledger, currency = null) {
const targetCurrency = currency || ledger.defaultCurrency;
// Metadata table
const metaTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')],
colWidths: [20, 50]
});
metaTable.push(
['Name', ledger.name || chalk.gray('(unnamed)')],
['Description', ledger.description || chalk.gray('(no description)')],
['ID', ledger.id || chalk.gray('(no id)')],
['Default Currency', chalk.yellow(ledger.defaultCurrency)],
['Created', new Date(ledger.created * 1000).toLocaleString()],
['Updated', new Date(ledger.updated * 1000).toLocaleString()],
['Entries', chalk.green(ledger.getEntryCount())],
['Total (' + targetCurrency + ')', chalk.green(ledger.getTotalBalance(targetCurrency))]
);
console.log(chalk.cyan('\n📊 Ledger Information:'));
console.log(metaTable.toString());
// Entries table
if (ledger.entries.length > 0) {
const entriesTable = new Table({
head: [chalk.cyan('URI'), chalk.cyan('Amount'), chalk.cyan('Currency')],
colWidths: [50, 15, 15]
});
ledger.entries.forEach(entry => {
if (typeof entry.amount === 'string') {
entriesTable.push([
entry.url,
chalk.green(entry.amount),
chalk.yellow(ledger.defaultCurrency)
]);
} else if (Array.isArray(entry.amount)) {
entry.amount.forEach((currencyEntry, index) => {
entriesTable.push([
index === 0 ? entry.url : '',
chalk.green(currencyEntry.value),
chalk.yellow(currencyEntry.currency)
]);
});
}
});
console.log(chalk.cyan('\n💰 Entries:'));
console.log(entriesTable.toString());
} else {
console.log(chalk.yellow('\n📭 No entries in this ledger'));
}
}
/**
* Save ledger to file with pretty formatting
*/
function saveLedger (ledger, filename) {
const spinner = ora(`Saving ledger to ${filename}`).start();
try {
// Create directory structure if it doesn't exist
const dir = path.dirname(filename);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const jsonData = ledger.toJSON(true);
fs.writeFileSync(filename, jsonData, 'utf8');
spinner.succeed(chalk.green(`Ledger saved to ${filename}`));
} catch (error) {
spinner.fail(chalk.red(`Failed to save ledger: ${error.message}`));
process.exit(1);
}
}
/**
* Load ledger from file
*/
function loadLedgerFromFile (filename) {
const spinner = ora(`Loading ledger from ${filename}`).start();
try {
if (!fs.existsSync(filename)) {
spinner.fail(chalk.red(`File not found: ${filename}`));
process.exit(1);
}
const data = fs.readFileSync(filename, 'utf8');
// Handle empty file - create new ledger with defaults
if (!data || data.trim() === '') {
spinner.info(chalk.yellow(`Empty file found, creating new ledger`));
const ledger = createLedger({
name: 'Web Ledger',
defaultCurrency: 'btc',
id: `urn:ledger:${generateLedgerId()}`
});
return ledger;
}
const ledger = loadLedger(JSON.parse(data));
spinner.succeed(chalk.green(`Ledger loaded from ${filename}`));
return ledger;
} catch (error) {
spinner.fail(chalk.red(`Failed to load ledger: ${error.message}`));
process.exit(1);
}
}
/**
* Interactive ledger creation wizard
*/
async function createLedgerWizard () {
console.log(chalk.cyan('\n🧙♂️ Ledger Creation Wizard\n'));
const answers = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: chalk.yellow('What is the name of your ledger?'),
validate: input => input.length > 0 || 'Name is required'
},
{
type: 'input',
name: 'description',
message: chalk.yellow('Provide a description (optional):')
},
{
type: 'list',
name: 'defaultCurrency',
message: chalk.yellow('Choose default currency:'),
choices: [
{ name: '₿ Bitcoin (btc)', value: 'btc' },
{ name: '₿ Bitcoin (satoshi)', value: 'satoshi' },
{ name: '💵 US Dollar (USD)', value: 'USD' },
{ name: '💶 Euro (EUR)', value: 'EUR' },
{ name: '🏆 Points', value: 'points' },
{ name: '⭐ Reputation', value: 'reputation-points' },
{ name: '🌱 Carbon Credits (tCO2e)', value: 'tCO2e' },
{ name: '🎓 Credits', value: 'credit-hours' },
{ name: '🔧 Custom...', value: 'custom' }
]
},
{
type: 'input',
name: 'customCurrency',
message: chalk.yellow('Enter custom currency name:'),
when: answers => answers.defaultCurrency === 'custom',
validate: input => input.length > 0 || 'Currency name is required'
},
{
type: 'confirm',
name: 'generateId',
message: chalk.yellow('Generate a unique ID for this ledger?'),
default: true
}
]);
const currency = answers.defaultCurrency === 'custom' ? answers.customCurrency : answers.defaultCurrency;
const ledger = createLedger({
name: answers.name,
description: answers.description || undefined,
defaultCurrency: currency,
id: answers.generateId ? `urn:ledger:${generateLedgerId()}` : undefined
});
console.log(chalk.green('\n✅ Ledger created successfully!'));
return ledger;
}
/**
* Interactive entry addition wizard
*/
async function addEntryWizard (ledger) {
console.log(chalk.cyan('\n➕ Add Entry Wizard\n'));
const answers = await inquirer.prompt([
{
type: 'input',
name: 'url',
message: chalk.yellow('Enter the URI:'),
validate: input => {
if (!input.length) return 'URI is required';
try {
return ledger.isValidURI(input) || 'Invalid URI format';
} catch {
return 'Invalid URI format';
}
}
},
{
type: 'list',
name: 'amountType',
message: chalk.yellow('How do you want to specify the amount?'),
choices: [
{ name: `Simple amount in ${ledger.defaultCurrency}`, value: 'simple' },
{ name: 'Multi-currency amount', value: 'multi' }
]
},
{
type: 'input',
name: 'simpleAmount',
message: chalk.yellow(`Enter amount in ${ledger.defaultCurrency}:`),
when: answers => answers.amountType === 'simple',
validate: input => /^\d+$/.test(input) || 'Amount must be a positive integer'
}
]);
let amount;
if (answers.amountType === 'simple') {
amount = answers.simpleAmount;
} else {
// Multi-currency wizard
const currencies = [];
let addMore = true;
while (addMore) {
const currencyAnswer = await inquirer.prompt([
{
type: 'input',
name: 'currency',
message: chalk.yellow(`Currency ${currencies.length + 1} - Enter currency code:`),
validate: input => input.length > 0 || 'Currency code is required'
},
{
type: 'input',
name: 'value',
message: chalk.yellow('Enter amount:'),
validate: input => /^\d+(\.\d+)?$/.test(input) || 'Amount must be a positive number'
}
]);
currencies.push({
currency: currencyAnswer.currency,
value: currencyAnswer.value
});
const continueAnswer = await inquirer.prompt([
{
type: 'confirm',
name: 'continue',
message: chalk.yellow('Add another currency?'),
default: false
}
]);
addMore = continueAnswer.continue;
}
amount = currencies;
}
try {
const entry = ledger.addEntry(answers.url, amount);
console.log(chalk.green('\n✅ Entry added successfully!'));
// Show the added entry
const entryTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')]
});
entryTable.push(
['URI', entry.url],
['Amount', typeof entry.amount === 'string' ? entry.amount : JSON.stringify(entry.amount, null, 2)]
);
console.log(entryTable.toString());
return entry;
} catch (error) {
console.log(chalk.red(`\n❌ Failed to add entry: ${error.message}`));
}
}
/**
* Interactive wizard for depositing to balance
*/
async function depositWizard (ledger) {
console.log(chalk.cyan('\n💰 Deposit Wizard\n'));
const answers = await inquirer.prompt([
{
type: 'input',
name: 'url',
message: chalk.yellow('Enter the URI:'),
validate: input => {
if (!input.length) return 'URI is required';
try {
return ledger.isValidURI(input) || 'Invalid URI format';
} catch {
return 'Invalid URI format';
}
}
},
{
type: 'input',
name: 'amount',
message: chalk.yellow('Enter the deposit amount:'),
validate: input => /^\d+(\.\d+)?$/.test(input) || 'Amount must be a positive number'
},
{
type: 'input',
name: 'currency',
message: chalk.yellow(`Enter currency (leave empty for default: ${ledger.defaultCurrency}):`),
default: ''
}
]);
const currency = answers.currency.trim() || null;
try {
const entry = ledger.deposit(answers.url, answers.amount, currency);
console.log(chalk.green('\n✅ Deposit successful!'));
// Show the updated entry
const entryTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')]
});
entryTable.push(
['URI', entry.url],
['Amount', typeof entry.amount === 'string' ? entry.amount : JSON.stringify(entry.amount, null, 2)]
);
console.log(entryTable.toString());
return entry;
} catch (error) {
console.log(chalk.red(`\n❌ Failed to deposit: ${error.message}`));
throw error;
}
}
/**
* Interactive wizard for withdrawing from balance
*/
async function withdrawWizard (ledger) {
console.log(chalk.cyan('\n💸 Withdraw Wizard\n'));
const answers = await inquirer.prompt([
{
type: 'input',
name: 'url',
message: chalk.yellow('Enter the URI:'),
validate: input => {
if (!input.length) return 'URI is required';
try {
return ledger.isValidURI(input) || 'Invalid URI format';
} catch {
return 'Invalid URI format';
}
}
},
{
type: 'input',
name: 'amount',
message: chalk.yellow('Enter the withdrawal amount:'),
validate: input => /^\d+(\.\d+)?$/.test(input) || 'Amount must be a positive number'
},
{
type: 'input',
name: 'currency',
message: chalk.yellow(`Enter currency (leave empty for default: ${ledger.defaultCurrency}):`),
default: ''
}
]);
const currency = answers.currency.trim() || null;
try {
const entry = ledger.withdraw(answers.url, answers.amount, currency);
console.log(chalk.green('\n✅ Withdrawal successful!'));
// Show the updated entry
const entryTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')]
});
entryTable.push(
['URI', entry.url],
['Amount', typeof entry.amount === 'string' ? entry.amount : JSON.stringify(entry.amount, null, 2)]
);
console.log(entryTable.toString());
return entry;
} catch (error) {
console.log(chalk.red(`\n❌ Failed to withdraw: ${error.message}`));
throw error;
}
}
/**
* Interactive wizard for setting balance
*/
async function setBalanceWizard (ledger) {
console.log(chalk.cyan('\n⚖️ Set Balance Wizard\n'));
const answers = await inquirer.prompt([
{
type: 'input',
name: 'url',
message: chalk.yellow('Enter the URI:'),
validate: input => {
if (!input.length) return 'URI is required';
try {
return ledger.isValidURI(input) || 'Invalid URI format';
} catch {
return 'Invalid URI format';
}
}
},
{
type: 'input',
name: 'amount',
message: chalk.yellow('Enter the amount:'),
validate: input => /^\d+(\.\d+)?$/.test(input) || 'Amount must be a positive number'
},
{
type: 'input',
name: 'currency',
message: chalk.yellow(`Enter currency (leave empty for default: ${ledger.defaultCurrency}):`),
default: ''
}
]);
const currency = answers.currency.trim() || null;
try {
const entry = ledger.setBalance(answers.url, answers.amount, currency);
console.log(chalk.green('\n✅ Balance set successfully!'));
// Show the updated entry
const entryTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')]
});
entryTable.push(
['URI', entry.url],
['Amount', typeof entry.amount === 'string' ? entry.amount : JSON.stringify(entry.amount, null, 2)]
);
console.log(entryTable.toString());
return entry;
} catch (error) {
console.log(chalk.red(`\n❌ Failed to set balance: ${error.message}`));
throw error;
}
}
/**
* Interactive balance query wizard
*/
async function queryBalanceWizard (ledger) {
console.log(chalk.cyan('\n🔍 Balance Query Wizard\n'));
const uris = ledger.entries.map(entry => entry.url);
if (uris.length === 0) {
console.log(chalk.yellow('No entries in this ledger to query.'));
return;
}
const answers = await inquirer.prompt([
{
type: 'list',
name: 'url',
message: chalk.yellow('Select URI to query:'),
choices: uris
},
{
type: 'input',
name: 'currency',
message: chalk.yellow(`Currency (default: ${ledger.defaultCurrency}):`),
default: ledger.defaultCurrency
}
]);
const balance = ledger.getBalance(answers.url, answers.currency);
if (balance !== null) {
console.log(chalk.green(`\n💰 Balance: ${balance} ${answers.currency}`));
} else {
console.log(chalk.red(`\n❌ No balance found for ${answers.currency}`));
}
}
/**
* Validation display with colors
*/
function displayValidation (validation) {
if (validation.isValid) {
console.log(chalk.green('\n✅ Ledger is valid!'));
} else {
console.log(chalk.red('\n❌ Ledger validation failed:'));
validation.errors.forEach(error => {
console.log(chalk.red(` • ${error}`));
});
}
// Display warnings if any
if (validation.warnings && validation.warnings.length > 0) {
console.log(chalk.yellow('\n⚠️ Warnings:'));
validation.warnings.forEach(warning => {
console.log(chalk.yellow(` • ${warning}`));
});
}
}
// CLI Commands
program
.command('create')
.description('Create a new ledger (interactive wizard)')
.option('-o, --output <file>', `output file (default: ${DEFAULT_LEDGER_PATH})`)
.action(async (options) => {
displayBanner();
const ledger = await createLedgerWizard();
const filename = options.output || DEFAULT_LEDGER_PATH;
saveLedger(ledger, filename);
console.log(chalk.cyan('\nLedger preview:'));
displayLedger(ledger);
});
program
.command('add')
.description('Add entries to an existing ledger')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.action(async (options) => {
displayBanner();
const filename = options.file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
let addMore = true;
while (addMore) {
await addEntryWizard(ledger);
const continueAnswer = await inquirer.prompt([
{
type: 'confirm',
name: 'continue',
message: chalk.yellow('Add another entry?'),
default: false
}
]);
addMore = continueAnswer.continue;
}
saveLedger(ledger, filename);
console.log(chalk.cyan('\nUpdated ledger:'));
displayLedger(ledger);
});
program
.command('deposit [uri] [amount] [currency]')
.description('Deposit (increment) balance for a specific URI')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('-u, --uri <uri>', 'URI to deposit to')
.option('-a, --amount <amount>', 'deposit amount')
.option('-c, --currency <currency>', 'currency (optional, uses ledger default if not specified)')
.action(async (uri, amount, currency, options) => {
displayBanner();
const filename = options.file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
// Use command line arguments if provided, otherwise use options, otherwise interactive
const targetUri = uri || options.uri;
const targetAmount = amount || options.amount;
const targetCurrency = currency || options.currency || null;
if (targetUri && targetAmount) {
// Non-interactive mode
try {
// Normalize URI (auto-prefix bare names with urn:local:)
const normalizedUri = ledger.normalizeURI(targetUri);
if (!/^\d+(\.\d+)?$/.test(targetAmount)) {
console.log(chalk.red('❌ Amount must be a positive number'));
process.exit(1);
}
const entry = ledger.deposit(normalizedUri, targetAmount, targetCurrency);
console.log(chalk.green(`✅ Deposited ${targetAmount} ${targetCurrency || ledger.defaultCurrency} to ${normalizedUri}`));
// Show the updated entry
const entryTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')]
});
entryTable.push(
['URI', entry.url],
['Amount', typeof entry.amount === 'string' ? entry.amount : JSON.stringify(entry.amount, null, 2)]
);
console.log(entryTable.toString());
} catch (error) {
console.log(chalk.red(`❌ Error: ${error.message}`));
process.exit(1);
}
} else {
// Interactive mode
await depositWizard(ledger);
}
saveLedger(ledger, filename);
console.log(chalk.cyan('\nUpdated ledger:'));
displayLedger(ledger);
});
program
.command('withdraw [uri] [amount] [currency]')
.description('Withdraw (decrement) balance for a specific URI')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('-u, --uri <uri>', 'URI to withdraw from')
.option('-a, --amount <amount>', 'withdrawal amount')
.option('-c, --currency <currency>', 'currency (optional, uses ledger default if not specified)')
.action(async (uri, amount, currency, options) => {
displayBanner();
const filename = options.file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
// Use command line arguments if provided, otherwise use options, otherwise interactive
const targetUri = uri || options.uri;
const targetAmount = amount || options.amount;
const targetCurrency = currency || options.currency || null;
if (targetUri && targetAmount) {
// Non-interactive mode
try {
// Normalize URI (auto-prefix bare names with urn:local:)
const normalizedUri = ledger.normalizeURI(targetUri);
if (!/^\d+(\.\d+)?$/.test(targetAmount)) {
console.log(chalk.red('❌ Amount must be a positive number'));
process.exit(1);
}
const entry = ledger.withdraw(normalizedUri, targetAmount, targetCurrency);
console.log(chalk.green(`✅ Withdrew ${targetAmount} ${targetCurrency || ledger.defaultCurrency} from ${normalizedUri}`));
// Show the updated entry
const entryTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')]
});
entryTable.push(
['URI', entry.url],
['Amount', typeof entry.amount === 'string' ? entry.amount : JSON.stringify(entry.amount, null, 2)]
);
console.log(entryTable.toString());
} catch (error) {
console.log(chalk.red(`❌ Error: ${error.message}`));
process.exit(1);
}
} else {
// Interactive mode
await withdrawWizard(ledger);
}
saveLedger(ledger, filename);
console.log(chalk.cyan('\nUpdated ledger:'));
displayLedger(ledger);
});
program
.command('set-balance [uri] [amount] [currency]')
.description('Set balance for a specific URI')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('-u, --uri <uri>', 'URI to set balance for')
.option('-a, --amount <amount>', 'balance amount')
.option('-c, --currency <currency>', 'currency (optional, uses ledger default if not specified)')
.action(async (uri, amount, currency, options) => {
displayBanner();
const filename = options.file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
// Use command line arguments if provided, otherwise use options, otherwise interactive
const targetUri = uri || options.uri;
const targetAmount = amount || options.amount;
const targetCurrency = currency || options.currency || null;
if (targetUri && targetAmount) {
// Non-interactive mode
try {
// Normalize URI (auto-prefix bare names with urn:local:)
const normalizedUri = ledger.normalizeURI(targetUri);
if (!/^\d+(\.\d+)?$/.test(targetAmount)) {
console.log(chalk.red('❌ Amount must be a positive number'));
process.exit(1);
}
const entry = ledger.setBalance(normalizedUri, targetAmount, targetCurrency);
console.log(chalk.green(`✅ Set balance for ${normalizedUri} to ${targetAmount} ${targetCurrency || ledger.defaultCurrency}`));
// Show the updated entry
const entryTable = new Table({
head: [chalk.cyan('Property'), chalk.cyan('Value')]
});
entryTable.push(
['URI', entry.url],
['Amount', typeof entry.amount === 'string' ? entry.amount : JSON.stringify(entry.amount, null, 2)]
);
console.log(entryTable.toString());
} catch (error) {
console.log(chalk.red(`❌ Error: ${error.message}`));
process.exit(1);
}
} else {
// Interactive mode
await setBalanceWizard(ledger);
}
saveLedger(ledger, filename);
console.log(chalk.cyan('\nUpdated ledger:'));
displayLedger(ledger);
});
program
.command('show [file]')
.description('Display ledger contents')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('-c, --currency <currency>', 'currency to display totals for')
.action((file, options) => {
displayBanner();
const filename = options.file || file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
displayLedger(ledger, options.currency);
});
program
.command('query')
.description('Query balance for specific URI (interactive)')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.action(async (options) => {
displayBanner();
const filename = options.file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
await queryBalanceWizard(ledger);
});
program
.command('balance [file]')
.description('Display all balances in the ledger')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('-c, --currency <currency>', 'filter by specific currency (shows all if not specified)')
.action((file, options) => {
const filename = options.file || file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
if (ledger.entries.length === 0) {
console.log(chalk.yellow('📭 No entries in this ledger'));
return;
}
// Create balances table
const balancesTable = new Table({
head: [chalk.cyan('URI'), chalk.cyan('Amount'), chalk.cyan('Currency')],
colWidths: [50, 15, 15]
});
let hasResults = false;
ledger.entries.forEach(entry => {
if (typeof entry.amount === 'string') {
// Simple amount in default currency
if (!options.currency || options.currency === ledger.defaultCurrency) {
balancesTable.push([
entry.url,
chalk.green(entry.amount),
chalk.yellow(ledger.defaultCurrency)
]);
hasResults = true;
}
} else if (Array.isArray(entry.amount)) {
// Multi-currency amounts
entry.amount.forEach((currencyEntry, index) => {
if (!options.currency || options.currency === currencyEntry.currency) {
balancesTable.push([
index === 0 ? entry.url : '', // Only show URI on first row
chalk.green(currencyEntry.value),
chalk.yellow(currencyEntry.currency)
]);
hasResults = true;
}
});
}
});
if (!hasResults) {
console.log(chalk.yellow(`No balances found for currency: ${options.currency}`));
return;
}
console.log(chalk.cyan('\n💰 All Balances:'));
console.log(balancesTable.toString());
// Show totals by currency
const currencies = new Set();
ledger.entries.forEach(entry => {
if (typeof entry.amount === 'string') {
currencies.add(ledger.defaultCurrency);
} else if (Array.isArray(entry.amount)) {
entry.amount.forEach(curr => currencies.add(curr.currency));
}
});
if (currencies.size > 1 || !options.currency) {
const totalTable = new Table({
head: [chalk.cyan('Currency'), chalk.cyan('Total')]
});
currencies.forEach(currency => {
if (!options.currency || options.currency === currency) {
const total = ledger.getTotalBalance(currency);
if (total !== '0') {
totalTable.push([
chalk.yellow(currency),
chalk.green(total)
]);
}
}
});
if (totalTable.length > 0) {
console.log(chalk.cyan('\n🧮 Totals:'));
console.log(totalTable.toString());
}
}
});
program
.command('validate [file]')
.description('Validate ledger structure and data')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.action((file, options) => {
displayBanner();
const filename = options.file || file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
const validation = ledger.validate();
displayValidation(validation);
if (!validation.isValid) {
process.exit(1);
}
});
program
.command('total [file]')
.description('Calculate total balance for currency (shows all currencies if none specified)')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('-c, --currency <currency>', 'currency (shows all currencies if not specified)')
.action((file, options) => {
const filename = options.file || file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
if (options.currency) {
// Show specific currency total
const total = ledger.getTotalBalance(options.currency);
console.log(chalk.green(`💰 ${total} ${options.currency}`));
} else {
// Show all currencies
const currencies = new Set([ledger.defaultCurrency]);
ledger.entries.forEach(entry => {
if (Array.isArray(entry.amount)) {
entry.amount.forEach(curr => currencies.add(curr.currency));
}
});
const totalTable = new Table({
head: [chalk.cyan('Currency'), chalk.cyan('Total')]
});
currencies.forEach(currency => {
const total = ledger.getTotalBalance(currency);
if (total !== '0') { // Only show currencies with non-zero balances
totalTable.push([
chalk.yellow(currency),
chalk.green(total)
]);
}
});
if (totalTable.length > 0) {
console.log(chalk.cyan('\n🧮 Total Balances:'));
console.log(totalTable.toString());
} else {
console.log(chalk.yellow('No balances found in this ledger.'));
}
}
});
program
.command('merge')
.description('Merge two ledgers')
.option('-a, --first <file>', `first ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.requiredOption('-b, --second <file>', 'second ledger file')
.option('-o, --output <file>', `output merged ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('-s, --strategy <strategy>', 'conflict strategy: replace|add|skip', 'replace')
.action((options) => {
displayBanner();
const spinner = ora('Merging ledgers').start();
try {
const firstFile = options.first || DEFAULT_LEDGER_PATH;
const outputFile = options.output || DEFAULT_LEDGER_PATH;
const ledger1 = loadLedgerFromFile(firstFile);
const ledger2 = loadLedgerFromFile(options.second);
ledger1.merge(ledger2, options.strategy);
spinner.succeed('Ledgers merged successfully');
saveLedger(ledger1, outputFile);
console.log(chalk.cyan('\nMerged ledger:'));
displayLedger(ledger1);
} catch (error) {
spinner.fail(`Merge failed: ${error.message}`);
process.exit(1);
}
});
program
.command('search')
.description('Search entries by criteria (interactive if no criteria specified)')
.option('-f, --file <file>', `ledger file (default: ${DEFAULT_LEDGER_PATH})`)
.option('--url <pattern>', 'URL pattern to search for')
.option('--min-amount <amount>', 'minimum amount')
.option('--max-amount <amount>', 'maximum amount')
.option('-c, --currency <currency>', 'currency for amount filters')
.action(async (options) => {
displayBanner();
const filename = options.file || DEFAULT_LEDGER_PATH;
const ledger = loadLedgerFromFile(filename);
let criteria = {};
if (options.url) criteria.url = options.url;
if (options.minAmount) criteria.minAmount = options.minAmount;
if (options.maxAmount) criteria.maxAmount = options.maxAmount;
if (options.currency) criteria.currency = options.currency;