@freeticket/cli 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +36 -15
  2. package/dist/index.js +1921 -688
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,12 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/index.ts
4
- import { Command } from "commander";
5
-
6
3
  // package.json
7
4
  var package_default = {
8
5
  name: "@freeticket/cli",
9
- version: "0.8.0",
6
+ version: "0.10.0",
10
7
  description: "Official FreeTicket CLI \u2014 consumes the B2B REST API for events, sales, tickets, memberships, venues, staff, and reports.",
11
8
  keywords: [
12
9
  "freeticket",
@@ -69,13 +66,134 @@ var package_default = {
69
66
  }
70
67
  };
71
68
 
69
+ // src/lib/banner.ts
70
+ import { Chalk } from "chalk";
71
+ var YELLOW = "#FFD500";
72
+ var c = new Chalk({ level: 3 });
73
+ var ART = String.raw`
74
+ ___ ___ ___ ___ _____ ___ ___ _ _____ _____
75
+ | __| _ \ __| __|_ _|_ _/ __| |/ / __|_ _|
76
+ | _|| / _|| _| | | | | (__| ' <| _| | |
77
+ |_| |_|_\___|___| |_| |___\___|_|\_\___| |_|
78
+ `;
79
+ function banner() {
80
+ return [
81
+ c.hex(YELLOW)(ART),
82
+ c.hex(YELLOW)(" \u25CF ") + c.hex(YELLOW).bold("FreeTicket") + c.hex(YELLOW)(" \u2014 events, tickets, and sales from your terminal"),
83
+ ""
84
+ ].join("\n");
85
+ }
86
+
87
+ // src/lib/update-check.ts
88
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
89
+ import { homedir } from "os";
90
+ import { dirname, join } from "path";
91
+ import chalk from "chalk";
92
+ var CACHE_PATH = join(homedir(), ".freeticket", "update-check.json");
93
+ var REGISTRY = "https://registry.npmjs.org/@freeticket/cli/latest";
94
+ var ONE_DAY = 24 * 60 * 60 * 1e3;
95
+ var FETCH_TIMEOUT = 1500;
96
+ async function notifyUpdate(current) {
97
+ if (!process.stderr.isTTY || process.env.FT_NO_UPDATE_CHECK || process.env.CI) {
98
+ return;
99
+ }
100
+ try {
101
+ const latest = await getLatest();
102
+ if (latest && isNewer(latest, current)) {
103
+ process.stderr.write(
104
+ `
105
+ ${chalk.yellow(`\u26A0 Update available: @freeticket/cli ${current} \u2192 ${latest}`)}
106
+ ${chalk.dim(" npm i -g @freeticket/cli@latest \xB7 or use npx @freeticket/cli@latest")}
107
+
108
+ `
109
+ );
110
+ }
111
+ } catch {
112
+ }
113
+ }
114
+ async function getLatest() {
115
+ const cached = readCache();
116
+ if (cached && Date.now() - cached.at < ONE_DAY) return cached.latest;
117
+ const res = await fetch(REGISTRY, {
118
+ signal: AbortSignal.timeout(FETCH_TIMEOUT),
119
+ headers: { Accept: "application/vnd.npm.install-v1+json" }
120
+ });
121
+ if (!res.ok) throw new Error(`registry ${res.status}`);
122
+ const latest = (await res.json()).version ?? null;
123
+ if (latest) writeCache({ at: Date.now(), latest });
124
+ return latest;
125
+ }
126
+ function readCache() {
127
+ if (!existsSync(CACHE_PATH)) return null;
128
+ try {
129
+ return JSON.parse(readFileSync(CACHE_PATH, "utf8"));
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+ function writeCache(v) {
135
+ try {
136
+ mkdirSync(dirname(CACHE_PATH), { recursive: true });
137
+ writeFileSync(CACHE_PATH, JSON.stringify(v));
138
+ } catch {
139
+ }
140
+ }
141
+ function isNewer(a, b) {
142
+ const parse = (v) => {
143
+ const [maj, min, pat] = (v.replace(/^v/, "").split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0);
144
+ return [maj ?? 0, min ?? 0, pat ?? 0];
145
+ };
146
+ const [aM, aN, aP] = parse(a);
147
+ const [bM, bN, bP] = parse(b);
148
+ return aM > bM || aM === bM && (aN > bN || aN === bN && aP > bP);
149
+ }
150
+
151
+ // src/program.ts
152
+ import { Command } from "commander";
153
+
72
154
  // src/client/client.gen.ts
73
155
  import { createClient, createConfig } from "@hey-api/client-fetch";
74
156
  var client = createClient(createConfig({
75
- baseUrl: "http://localhost:3000/api/v1"
157
+ baseUrl: "https://admin.appfreeticket.com/api/v1"
76
158
  }));
77
159
 
78
160
  // src/client/sdk.gen.ts
161
+ var getEventsIdDates = (options) => {
162
+ return (options.client ?? client).get({
163
+ security: [
164
+ {
165
+ name: "Authorization",
166
+ type: "apiKey"
167
+ },
168
+ {
169
+ name: "x-api-key",
170
+ type: "apiKey"
171
+ }
172
+ ],
173
+ url: "/events/{id}/dates",
174
+ ...options
175
+ });
176
+ };
177
+ var postEventsIdDates = (options) => {
178
+ return (options.client ?? client).post({
179
+ security: [
180
+ {
181
+ name: "Authorization",
182
+ type: "apiKey"
183
+ },
184
+ {
185
+ name: "x-api-key",
186
+ type: "apiKey"
187
+ }
188
+ ],
189
+ url: "/events/{id}/dates",
190
+ ...options,
191
+ headers: {
192
+ "Content-Type": "application/json",
193
+ ...options?.headers
194
+ }
195
+ });
196
+ };
79
197
  var postAuthDeviceCode = (options) => {
80
198
  return (options?.client ?? client).post({
81
199
  url: "/auth/device/code",
@@ -98,6 +216,10 @@ var getMe = (options) => {
98
216
  {
99
217
  name: "Authorization",
100
218
  type: "apiKey"
219
+ },
220
+ {
221
+ name: "x-api-key",
222
+ type: "apiKey"
101
223
  }
102
224
  ],
103
225
  url: "/me",
@@ -110,6 +232,10 @@ var getEvents = (options) => {
110
232
  {
111
233
  name: "Authorization",
112
234
  type: "apiKey"
235
+ },
236
+ {
237
+ name: "x-api-key",
238
+ type: "apiKey"
113
239
  }
114
240
  ],
115
241
  url: "/events",
@@ -122,6 +248,10 @@ var postEvents = (options) => {
122
248
  {
123
249
  name: "Authorization",
124
250
  type: "apiKey"
251
+ },
252
+ {
253
+ name: "x-api-key",
254
+ type: "apiKey"
125
255
  }
126
256
  ],
127
257
  url: "/events",
@@ -138,6 +268,10 @@ var deleteEventsId = (options) => {
138
268
  {
139
269
  name: "Authorization",
140
270
  type: "apiKey"
271
+ },
272
+ {
273
+ name: "x-api-key",
274
+ type: "apiKey"
141
275
  }
142
276
  ],
143
277
  url: "/events/{id}",
@@ -150,6 +284,10 @@ var getEventsId = (options) => {
150
284
  {
151
285
  name: "Authorization",
152
286
  type: "apiKey"
287
+ },
288
+ {
289
+ name: "x-api-key",
290
+ type: "apiKey"
153
291
  }
154
292
  ],
155
293
  url: "/events/{id}",
@@ -162,6 +300,10 @@ var patchEventsId = (options) => {
162
300
  {
163
301
  name: "Authorization",
164
302
  type: "apiKey"
303
+ },
304
+ {
305
+ name: "x-api-key",
306
+ type: "apiKey"
165
307
  }
166
308
  ],
167
309
  url: "/events/{id}",
@@ -178,46 +320,26 @@ var postEventsIdPublish = (options) => {
178
320
  {
179
321
  name: "Authorization",
180
322
  type: "apiKey"
181
- }
182
- ],
183
- url: "/events/{id}/publish",
184
- ...options
185
- });
186
- };
187
- var getEventsIdDates = (options) => {
188
- return (options.client ?? client).get({
189
- security: [
323
+ },
190
324
  {
191
- name: "Authorization",
325
+ name: "x-api-key",
192
326
  type: "apiKey"
193
327
  }
194
328
  ],
195
- url: "/events/{id}/dates",
329
+ url: "/events/{id}/publish",
196
330
  ...options
197
331
  });
198
332
  };
199
- var postEventsIdDates = (options) => {
200
- return (options.client ?? client).post({
201
- security: [
202
- {
203
- name: "Authorization",
204
- type: "apiKey"
205
- }
206
- ],
207
- url: "/events/{id}/dates",
208
- ...options,
209
- headers: {
210
- "Content-Type": "application/json",
211
- ...options?.headers
212
- }
213
- });
214
- };
215
333
  var deleteEventsIdDatesDateId = (options) => {
216
334
  return (options.client ?? client).delete({
217
335
  security: [
218
336
  {
219
337
  name: "Authorization",
220
338
  type: "apiKey"
339
+ },
340
+ {
341
+ name: "x-api-key",
342
+ type: "apiKey"
221
343
  }
222
344
  ],
223
345
  url: "/events/{id}/dates/{dateId}",
@@ -230,6 +352,10 @@ var patchEventsIdDatesDateId = (options) => {
230
352
  {
231
353
  name: "Authorization",
232
354
  type: "apiKey"
355
+ },
356
+ {
357
+ name: "x-api-key",
358
+ type: "apiKey"
233
359
  }
234
360
  ],
235
361
  url: "/events/{id}/dates/{dateId}",
@@ -246,6 +372,10 @@ var getTicketTypes = (options) => {
246
372
  {
247
373
  name: "Authorization",
248
374
  type: "apiKey"
375
+ },
376
+ {
377
+ name: "x-api-key",
378
+ type: "apiKey"
249
379
  }
250
380
  ],
251
381
  url: "/ticket-types",
@@ -258,6 +388,10 @@ var postTicketTypes = (options) => {
258
388
  {
259
389
  name: "Authorization",
260
390
  type: "apiKey"
391
+ },
392
+ {
393
+ name: "x-api-key",
394
+ type: "apiKey"
261
395
  }
262
396
  ],
263
397
  url: "/ticket-types",
@@ -274,6 +408,10 @@ var deleteTicketTypesId = (options) => {
274
408
  {
275
409
  name: "Authorization",
276
410
  type: "apiKey"
411
+ },
412
+ {
413
+ name: "x-api-key",
414
+ type: "apiKey"
277
415
  }
278
416
  ],
279
417
  url: "/ticket-types/{id}",
@@ -286,6 +424,10 @@ var getTicketTypesId = (options) => {
286
424
  {
287
425
  name: "Authorization",
288
426
  type: "apiKey"
427
+ },
428
+ {
429
+ name: "x-api-key",
430
+ type: "apiKey"
289
431
  }
290
432
  ],
291
433
  url: "/ticket-types/{id}",
@@ -298,6 +440,10 @@ var patchTicketTypesId = (options) => {
298
440
  {
299
441
  name: "Authorization",
300
442
  type: "apiKey"
443
+ },
444
+ {
445
+ name: "x-api-key",
446
+ type: "apiKey"
301
447
  }
302
448
  ],
303
449
  url: "/ticket-types/{id}",
@@ -314,6 +460,10 @@ var getSales = (options) => {
314
460
  {
315
461
  name: "Authorization",
316
462
  type: "apiKey"
463
+ },
464
+ {
465
+ name: "x-api-key",
466
+ type: "apiKey"
317
467
  }
318
468
  ],
319
469
  url: "/sales",
@@ -326,6 +476,10 @@ var postSales = (options) => {
326
476
  {
327
477
  name: "Authorization",
328
478
  type: "apiKey"
479
+ },
480
+ {
481
+ name: "x-api-key",
482
+ type: "apiKey"
329
483
  }
330
484
  ],
331
485
  url: "/sales",
@@ -342,6 +496,10 @@ var getSalesId = (options) => {
342
496
  {
343
497
  name: "Authorization",
344
498
  type: "apiKey"
499
+ },
500
+ {
501
+ name: "x-api-key",
502
+ type: "apiKey"
345
503
  }
346
504
  ],
347
505
  url: "/sales/{id}",
@@ -354,10 +512,18 @@ var postSalesIdCancel = (options) => {
354
512
  {
355
513
  name: "Authorization",
356
514
  type: "apiKey"
515
+ },
516
+ {
517
+ name: "x-api-key",
518
+ type: "apiKey"
357
519
  }
358
520
  ],
359
521
  url: "/sales/{id}/cancel",
360
- ...options
522
+ ...options,
523
+ headers: {
524
+ "Content-Type": "application/json",
525
+ ...options?.headers
526
+ }
361
527
  });
362
528
  };
363
529
  var postSalesIdRefund = (options) => {
@@ -366,10 +532,18 @@ var postSalesIdRefund = (options) => {
366
532
  {
367
533
  name: "Authorization",
368
534
  type: "apiKey"
535
+ },
536
+ {
537
+ name: "x-api-key",
538
+ type: "apiKey"
369
539
  }
370
540
  ],
371
541
  url: "/sales/{id}/refund",
372
- ...options
542
+ ...options,
543
+ headers: {
544
+ "Content-Type": "application/json",
545
+ ...options?.headers
546
+ }
373
547
  });
374
548
  };
375
549
  var getMembershipPlans = (options) => {
@@ -378,6 +552,10 @@ var getMembershipPlans = (options) => {
378
552
  {
379
553
  name: "Authorization",
380
554
  type: "apiKey"
555
+ },
556
+ {
557
+ name: "x-api-key",
558
+ type: "apiKey"
381
559
  }
382
560
  ],
383
561
  url: "/membership-plans",
@@ -390,6 +568,10 @@ var postMembershipPlans = (options) => {
390
568
  {
391
569
  name: "Authorization",
392
570
  type: "apiKey"
571
+ },
572
+ {
573
+ name: "x-api-key",
574
+ type: "apiKey"
393
575
  }
394
576
  ],
395
577
  url: "/membership-plans",
@@ -406,6 +588,10 @@ var deleteMembershipPlansId = (options) => {
406
588
  {
407
589
  name: "Authorization",
408
590
  type: "apiKey"
591
+ },
592
+ {
593
+ name: "x-api-key",
594
+ type: "apiKey"
409
595
  }
410
596
  ],
411
597
  url: "/membership-plans/{id}",
@@ -418,6 +604,10 @@ var getMembershipPlansId = (options) => {
418
604
  {
419
605
  name: "Authorization",
420
606
  type: "apiKey"
607
+ },
608
+ {
609
+ name: "x-api-key",
610
+ type: "apiKey"
421
611
  }
422
612
  ],
423
613
  url: "/membership-plans/{id}",
@@ -430,6 +620,10 @@ var patchMembershipPlansId = (options) => {
430
620
  {
431
621
  name: "Authorization",
432
622
  type: "apiKey"
623
+ },
624
+ {
625
+ name: "x-api-key",
626
+ type: "apiKey"
433
627
  }
434
628
  ],
435
629
  url: "/membership-plans/{id}",
@@ -446,6 +640,10 @@ var getVenues = (options) => {
446
640
  {
447
641
  name: "Authorization",
448
642
  type: "apiKey"
643
+ },
644
+ {
645
+ name: "x-api-key",
646
+ type: "apiKey"
449
647
  }
450
648
  ],
451
649
  url: "/venues",
@@ -458,6 +656,10 @@ var postVenues = (options) => {
458
656
  {
459
657
  name: "Authorization",
460
658
  type: "apiKey"
659
+ },
660
+ {
661
+ name: "x-api-key",
662
+ type: "apiKey"
461
663
  }
462
664
  ],
463
665
  url: "/venues",
@@ -474,6 +676,10 @@ var deleteVenuesId = (options) => {
474
676
  {
475
677
  name: "Authorization",
476
678
  type: "apiKey"
679
+ },
680
+ {
681
+ name: "x-api-key",
682
+ type: "apiKey"
477
683
  }
478
684
  ],
479
685
  url: "/venues/{id}",
@@ -486,6 +692,10 @@ var getVenuesId = (options) => {
486
692
  {
487
693
  name: "Authorization",
488
694
  type: "apiKey"
695
+ },
696
+ {
697
+ name: "x-api-key",
698
+ type: "apiKey"
489
699
  }
490
700
  ],
491
701
  url: "/venues/{id}",
@@ -498,6 +708,10 @@ var patchVenuesId = (options) => {
498
708
  {
499
709
  name: "Authorization",
500
710
  type: "apiKey"
711
+ },
712
+ {
713
+ name: "x-api-key",
714
+ type: "apiKey"
501
715
  }
502
716
  ],
503
717
  url: "/venues/{id}",
@@ -514,6 +728,10 @@ var getStaff = (options) => {
514
728
  {
515
729
  name: "Authorization",
516
730
  type: "apiKey"
731
+ },
732
+ {
733
+ name: "x-api-key",
734
+ type: "apiKey"
517
735
  }
518
736
  ],
519
737
  url: "/staff",
@@ -526,6 +744,10 @@ var postStaff = (options) => {
526
744
  {
527
745
  name: "Authorization",
528
746
  type: "apiKey"
747
+ },
748
+ {
749
+ name: "x-api-key",
750
+ type: "apiKey"
529
751
  }
530
752
  ],
531
753
  url: "/staff",
@@ -542,6 +764,10 @@ var patchStaffIdRole = (options) => {
542
764
  {
543
765
  name: "Authorization",
544
766
  type: "apiKey"
767
+ },
768
+ {
769
+ name: "x-api-key",
770
+ type: "apiKey"
545
771
  }
546
772
  ],
547
773
  url: "/staff/{id}/role",
@@ -558,6 +784,10 @@ var getReportsSummary = (options) => {
558
784
  {
559
785
  name: "Authorization",
560
786
  type: "apiKey"
787
+ },
788
+ {
789
+ name: "x-api-key",
790
+ type: "apiKey"
561
791
  }
562
792
  ],
563
793
  url: "/reports/summary",
@@ -570,6 +800,10 @@ var getReportsInventory = (options) => {
570
800
  {
571
801
  name: "Authorization",
572
802
  type: "apiKey"
803
+ },
804
+ {
805
+ name: "x-api-key",
806
+ type: "apiKey"
573
807
  }
574
808
  ],
575
809
  url: "/reports/inventory",
@@ -582,8 +816,12 @@ var getReportsReconciliation = (options) => {
582
816
  {
583
817
  name: "Authorization",
584
818
  type: "apiKey"
585
- }
586
- ],
819
+ },
820
+ {
821
+ name: "x-api-key",
822
+ type: "apiKey"
823
+ }
824
+ ],
587
825
  url: "/reports/reconciliation",
588
826
  ...options
589
827
  });
@@ -594,6 +832,10 @@ var getReportsExportsReconciliation = (options) => {
594
832
  {
595
833
  name: "Authorization",
596
834
  type: "apiKey"
835
+ },
836
+ {
837
+ name: "x-api-key",
838
+ type: "apiKey"
597
839
  }
598
840
  ],
599
841
  url: "/reports/exports/reconciliation",
@@ -606,6 +848,10 @@ var getReportsExportsAttendees = (options) => {
606
848
  {
607
849
  name: "Authorization",
608
850
  type: "apiKey"
851
+ },
852
+ {
853
+ name: "x-api-key",
854
+ type: "apiKey"
609
855
  }
610
856
  ],
611
857
  url: "/reports/exports/attendees",
@@ -618,6 +864,10 @@ var getReportsExportsBuyers = (options) => {
618
864
  {
619
865
  name: "Authorization",
620
866
  type: "apiKey"
867
+ },
868
+ {
869
+ name: "x-api-key",
870
+ type: "apiKey"
621
871
  }
622
872
  ],
623
873
  url: "/reports/exports/buyers",
@@ -630,6 +880,10 @@ var getReportsExportsSubscribers = (options) => {
630
880
  {
631
881
  name: "Authorization",
632
882
  type: "apiKey"
883
+ },
884
+ {
885
+ name: "x-api-key",
886
+ type: "apiKey"
633
887
  }
634
888
  ],
635
889
  url: "/reports/exports/subscribers",
@@ -642,6 +896,10 @@ var getReportsByEvent = (options) => {
642
896
  {
643
897
  name: "Authorization",
644
898
  type: "apiKey"
899
+ },
900
+ {
901
+ name: "x-api-key",
902
+ type: "apiKey"
645
903
  }
646
904
  ],
647
905
  url: "/reports/by-event",
@@ -654,18 +912,58 @@ var getReportsTimeseries = (options) => {
654
912
  {
655
913
  name: "Authorization",
656
914
  type: "apiKey"
915
+ },
916
+ {
917
+ name: "x-api-key",
918
+ type: "apiKey"
657
919
  }
658
920
  ],
659
921
  url: "/reports/timeseries",
660
922
  ...options
661
923
  });
662
924
  };
925
+ var getReportsFinancials = (options) => {
926
+ return (options?.client ?? client).get({
927
+ security: [
928
+ {
929
+ name: "Authorization",
930
+ type: "apiKey"
931
+ },
932
+ {
933
+ name: "x-api-key",
934
+ type: "apiKey"
935
+ }
936
+ ],
937
+ url: "/reports/financials",
938
+ ...options
939
+ });
940
+ };
941
+ var getSettlements = (options) => {
942
+ return (options?.client ?? client).get({
943
+ security: [
944
+ {
945
+ name: "Authorization",
946
+ type: "apiKey"
947
+ },
948
+ {
949
+ name: "x-api-key",
950
+ type: "apiKey"
951
+ }
952
+ ],
953
+ url: "/settlements",
954
+ ...options
955
+ });
956
+ };
663
957
  var getDiscounts = (options) => {
664
958
  return (options?.client ?? client).get({
665
959
  security: [
666
960
  {
667
961
  name: "Authorization",
668
962
  type: "apiKey"
963
+ },
964
+ {
965
+ name: "x-api-key",
966
+ type: "apiKey"
669
967
  }
670
968
  ],
671
969
  url: "/discounts",
@@ -678,6 +976,10 @@ var postDiscounts = (options) => {
678
976
  {
679
977
  name: "Authorization",
680
978
  type: "apiKey"
979
+ },
980
+ {
981
+ name: "x-api-key",
982
+ type: "apiKey"
681
983
  }
682
984
  ],
683
985
  url: "/discounts",
@@ -694,6 +996,10 @@ var deleteDiscountsId = (options) => {
694
996
  {
695
997
  name: "Authorization",
696
998
  type: "apiKey"
999
+ },
1000
+ {
1001
+ name: "x-api-key",
1002
+ type: "apiKey"
697
1003
  }
698
1004
  ],
699
1005
  url: "/discounts/{id}",
@@ -706,6 +1012,10 @@ var patchDiscountsId = (options) => {
706
1012
  {
707
1013
  name: "Authorization",
708
1014
  type: "apiKey"
1015
+ },
1016
+ {
1017
+ name: "x-api-key",
1018
+ type: "apiKey"
709
1019
  }
710
1020
  ],
711
1021
  url: "/discounts/{id}",
@@ -722,6 +1032,10 @@ var getWebhooks = (options) => {
722
1032
  {
723
1033
  name: "Authorization",
724
1034
  type: "apiKey"
1035
+ },
1036
+ {
1037
+ name: "x-api-key",
1038
+ type: "apiKey"
725
1039
  }
726
1040
  ],
727
1041
  url: "/webhooks",
@@ -734,6 +1048,10 @@ var postWebhooks = (options) => {
734
1048
  {
735
1049
  name: "Authorization",
736
1050
  type: "apiKey"
1051
+ },
1052
+ {
1053
+ name: "x-api-key",
1054
+ type: "apiKey"
737
1055
  }
738
1056
  ],
739
1057
  url: "/webhooks",
@@ -750,6 +1068,10 @@ var deleteWebhooksId = (options) => {
750
1068
  {
751
1069
  name: "Authorization",
752
1070
  type: "apiKey"
1071
+ },
1072
+ {
1073
+ name: "x-api-key",
1074
+ type: "apiKey"
753
1075
  }
754
1076
  ],
755
1077
  url: "/webhooks/{id}",
@@ -762,6 +1084,10 @@ var getMembershipPlansIdSubscribers = (options) => {
762
1084
  {
763
1085
  name: "Authorization",
764
1086
  type: "apiKey"
1087
+ },
1088
+ {
1089
+ name: "x-api-key",
1090
+ type: "apiKey"
765
1091
  }
766
1092
  ],
767
1093
  url: "/membership-plans/{id}/subscribers",
@@ -774,6 +1100,10 @@ var postSubscriptionsIdCancel = (options) => {
774
1100
  {
775
1101
  name: "Authorization",
776
1102
  type: "apiKey"
1103
+ },
1104
+ {
1105
+ name: "x-api-key",
1106
+ type: "apiKey"
777
1107
  }
778
1108
  ],
779
1109
  url: "/subscriptions/{id}/cancel",
@@ -786,18 +1116,42 @@ var getSalesIdTickets = (options) => {
786
1116
  {
787
1117
  name: "Authorization",
788
1118
  type: "apiKey"
1119
+ },
1120
+ {
1121
+ name: "x-api-key",
1122
+ type: "apiKey"
789
1123
  }
790
1124
  ],
791
1125
  url: "/sales/{id}/tickets",
792
1126
  ...options
793
1127
  });
794
1128
  };
1129
+ var postTicketsTicketCodeResend = (options) => {
1130
+ return (options.client ?? client).post({
1131
+ security: [
1132
+ {
1133
+ name: "Authorization",
1134
+ type: "apiKey"
1135
+ },
1136
+ {
1137
+ name: "x-api-key",
1138
+ type: "apiKey"
1139
+ }
1140
+ ],
1141
+ url: "/tickets/{ticketCode}/resend",
1142
+ ...options
1143
+ });
1144
+ };
795
1145
  var postTicketsTicketCodeCheckin = (options) => {
796
1146
  return (options.client ?? client).post({
797
1147
  security: [
798
1148
  {
799
1149
  name: "Authorization",
800
1150
  type: "apiKey"
1151
+ },
1152
+ {
1153
+ name: "x-api-key",
1154
+ type: "apiKey"
801
1155
  }
802
1156
  ],
803
1157
  url: "/tickets/{ticketCode}/checkin",
@@ -810,6 +1164,10 @@ var getTicketsTicketCodeAccess = (options) => {
810
1164
  {
811
1165
  name: "Authorization",
812
1166
  type: "apiKey"
1167
+ },
1168
+ {
1169
+ name: "x-api-key",
1170
+ type: "apiKey"
813
1171
  }
814
1172
  ],
815
1173
  url: "/tickets/{ticketCode}/access",
@@ -822,6 +1180,10 @@ var getApiKeys = (options) => {
822
1180
  {
823
1181
  name: "Authorization",
824
1182
  type: "apiKey"
1183
+ },
1184
+ {
1185
+ name: "x-api-key",
1186
+ type: "apiKey"
825
1187
  }
826
1188
  ],
827
1189
  url: "/api-keys",
@@ -834,6 +1196,10 @@ var postApiKeys = (options) => {
834
1196
  {
835
1197
  name: "Authorization",
836
1198
  type: "apiKey"
1199
+ },
1200
+ {
1201
+ name: "x-api-key",
1202
+ type: "apiKey"
837
1203
  }
838
1204
  ],
839
1205
  url: "/api-keys",
@@ -850,187 +1216,93 @@ var deleteApiKeysId = (options) => {
850
1216
  {
851
1217
  name: "Authorization",
852
1218
  type: "apiKey"
853
- }
854
- ],
855
- url: "/api-keys/{id}",
856
- ...options
857
- });
858
- };
859
- var postTicketsTicketCodeResend = (options) => {
860
- return (options.client ?? client).post({
861
- security: [
1219
+ },
862
1220
  {
863
- name: "Authorization",
1221
+ name: "x-api-key",
864
1222
  type: "apiKey"
865
1223
  }
866
1224
  ],
867
- url: "/tickets/{ticketCode}/resend",
1225
+ url: "/api-keys/{id}",
868
1226
  ...options
869
1227
  });
870
1228
  };
871
-
872
- // src/commands/admin.ts
873
- import chalk2 from "chalk";
874
-
875
- // src/admin-client/client.gen.ts
876
- import { createClient as createClient2, createConfig as createConfig2 } from "@hey-api/client-fetch";
877
- var client2 = createClient2(createConfig2({
878
- baseUrl: "https://admin.appfreeticket.com/api/admin"
879
- }));
880
-
881
- // src/admin-client/sdk.gen.ts
882
- var getMe2 = (options) => {
883
- return (options?.client ?? client2).get({
1229
+ var getContentVideos = (options) => {
1230
+ return (options?.client ?? client).get({
884
1231
  security: [
885
1232
  {
886
- in: "cookie",
887
- name: "better-auth.session_token",
1233
+ name: "Authorization",
888
1234
  type: "apiKey"
889
- }
890
- ],
891
- url: "/me",
892
- ...options
893
- });
894
- };
895
- var getWorkspaces = (options) => {
896
- return (options?.client ?? client2).get({
897
- security: [
1235
+ },
898
1236
  {
899
- in: "cookie",
900
- name: "better-auth.session_token",
1237
+ name: "x-api-key",
901
1238
  type: "apiKey"
902
1239
  }
903
1240
  ],
904
- url: "/workspaces",
1241
+ url: "/content/videos",
905
1242
  ...options
906
1243
  });
907
1244
  };
908
- var postWorkspaces = (options) => {
909
- return (options.client ?? client2).post({
1245
+ var getContentPosts = (options) => {
1246
+ return (options?.client ?? client).get({
910
1247
  security: [
911
1248
  {
912
- in: "cookie",
913
- name: "better-auth.session_token",
1249
+ name: "Authorization",
914
1250
  type: "apiKey"
915
- }
916
- ],
917
- url: "/workspaces",
918
- ...options,
919
- headers: {
920
- "Content-Type": "application/json",
921
- ...options?.headers
922
- }
923
- });
924
- };
925
- var getWorkspacesId = (options) => {
926
- return (options.client ?? client2).get({
927
- security: [
1251
+ },
928
1252
  {
929
- in: "cookie",
930
- name: "better-auth.session_token",
1253
+ name: "x-api-key",
931
1254
  type: "apiKey"
932
1255
  }
933
1256
  ],
934
- url: "/workspaces/{id}",
1257
+ url: "/content/posts",
935
1258
  ...options
936
1259
  });
937
1260
  };
938
- var patchWorkspacesId = (options) => {
939
- return (options.client ?? client2).patch({
940
- security: [
941
- {
942
- in: "cookie",
943
- name: "better-auth.session_token",
944
- type: "apiKey"
945
- }
946
- ],
947
- url: "/workspaces/{id}",
948
- ...options,
949
- headers: {
950
- "Content-Type": "application/json",
951
- ...options?.headers
952
- }
953
- });
954
- };
955
- var postWorkspacesIdSuspend = (options) => {
956
- return (options.client ?? client2).post({
1261
+ var getContentLives = (options) => {
1262
+ return (options?.client ?? client).get({
957
1263
  security: [
958
1264
  {
959
- in: "cookie",
960
- name: "better-auth.session_token",
1265
+ name: "Authorization",
961
1266
  type: "apiKey"
962
- }
963
- ],
964
- url: "/workspaces/{id}/suspend",
965
- ...options
966
- });
967
- };
968
- var postWorkspacesIdRestore = (options) => {
969
- return (options.client ?? client2).post({
970
- security: [
1267
+ },
971
1268
  {
972
- in: "cookie",
973
- name: "better-auth.session_token",
1269
+ name: "x-api-key",
974
1270
  type: "apiKey"
975
1271
  }
976
1272
  ],
977
- url: "/workspaces/{id}/restore",
1273
+ url: "/content/lives",
978
1274
  ...options
979
1275
  });
980
1276
  };
981
- var getUsers = (options) => {
982
- return (options?.client ?? client2).get({
1277
+ var getContentLivesId = (options) => {
1278
+ return (options.client ?? client).get({
983
1279
  security: [
984
1280
  {
985
- in: "cookie",
986
- name: "better-auth.session_token",
1281
+ name: "Authorization",
987
1282
  type: "apiKey"
988
- }
989
- ],
990
- url: "/users",
991
- ...options
992
- });
993
- };
994
- var getUsersId = (options) => {
995
- return (options.client ?? client2).get({
996
- security: [
1283
+ },
997
1284
  {
998
- in: "cookie",
999
- name: "better-auth.session_token",
1285
+ name: "x-api-key",
1000
1286
  type: "apiKey"
1001
1287
  }
1002
1288
  ],
1003
- url: "/users/{id}",
1289
+ url: "/content/lives/{id}",
1004
1290
  ...options
1005
1291
  });
1006
1292
  };
1007
- var patchUsersId = (options) => {
1008
- return (options.client ?? client2).patch({
1293
+ var postContentPlaybackToken = (options) => {
1294
+ return (options.client ?? client).post({
1009
1295
  security: [
1010
1296
  {
1011
- in: "cookie",
1012
- name: "better-auth.session_token",
1297
+ name: "Authorization",
1013
1298
  type: "apiKey"
1014
- }
1015
- ],
1016
- url: "/users/{id}",
1017
- ...options,
1018
- headers: {
1019
- "Content-Type": "application/json",
1020
- ...options?.headers
1021
- }
1022
- });
1023
- };
1024
- var postImpersonate = (options) => {
1025
- return (options.client ?? client2).post({
1026
- security: [
1299
+ },
1027
1300
  {
1028
- in: "cookie",
1029
- name: "better-auth.session_token",
1301
+ name: "x-api-key",
1030
1302
  type: "apiKey"
1031
1303
  }
1032
1304
  ],
1033
- url: "/impersonate",
1305
+ url: "/content/playback-token",
1034
1306
  ...options,
1035
1307
  headers: {
1036
1308
  "Content-Type": "application/json",
@@ -1038,12 +1310,887 @@ var postImpersonate = (options) => {
1038
1310
  }
1039
1311
  });
1040
1312
  };
1041
- var postImpersonateStop = (options) => {
1042
- return (options?.client ?? client2).post({
1043
- security: [
1044
- {
1045
- in: "cookie",
1046
- name: "better-auth.session_token",
1313
+
1314
+ // src/commands/account.ts
1315
+ import chalk4 from "chalk";
1316
+
1317
+ // src/admin-client/client.gen.ts
1318
+ import { createClient as createClient2, createConfig as createConfig2 } from "@hey-api/client-fetch";
1319
+ var client2 = createClient2(createConfig2({
1320
+ baseUrl: "https://admin.appfreeticket.com/api/admin"
1321
+ }));
1322
+
1323
+ // src/lib/config.ts
1324
+ import {
1325
+ chmodSync,
1326
+ existsSync as existsSync2,
1327
+ mkdirSync as mkdirSync2,
1328
+ readFileSync as readFileSync2,
1329
+ renameSync,
1330
+ writeFileSync as writeFileSync2
1331
+ } from "fs";
1332
+ import { homedir as homedir2 } from "os";
1333
+ import { dirname as dirname2, join as join2 } from "path";
1334
+ var CONFIG_DIR = join2(homedir2(), ".freeticket");
1335
+ var CONFIG_PATH = join2(CONFIG_DIR, "config.json");
1336
+ var DEFAULT_API_URL = "https://admin.appfreeticket.com";
1337
+ var LEGACY_ACCOUNT = "default";
1338
+ var ENV_ACCOUNT = "FT_API_KEY";
1339
+ var ConfigError = class extends Error {
1340
+ };
1341
+ function readFile() {
1342
+ if (!existsSync2(CONFIG_PATH)) return {};
1343
+ let parsed;
1344
+ try {
1345
+ parsed = JSON.parse(readFileSync2(CONFIG_PATH, "utf8"));
1346
+ } catch (err) {
1347
+ throw new ConfigError(
1348
+ `${CONFIG_PATH} is not valid JSON (${err.message}). Fix it, or move it away and run \`ft login\` again.`
1349
+ );
1350
+ }
1351
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
1352
+ throw new ConfigError(`${CONFIG_PATH} does not hold a JSON object.`);
1353
+ return migrate(parsed);
1354
+ }
1355
+ function migrate(file) {
1356
+ const { apiKey, ...rest } = file;
1357
+ if (!apiKey) return rest;
1358
+ const accounts = { ...rest.accounts };
1359
+ accounts[LEGACY_ACCOUNT] ??= {
1360
+ apiKey,
1361
+ ...rest.workspaceId ? { workspaceId: rest.workspaceId } : {}
1362
+ };
1363
+ return { ...rest, accounts };
1364
+ }
1365
+ function loginTarget(file, email, accountFlag2) {
1366
+ if (accountFlag2) return { name: accountFlag2 };
1367
+ const accounts = file.accounts ?? {};
1368
+ const same = Object.entries(accounts).find(
1369
+ ([, a]) => email !== void 0 && a.email === email
1370
+ );
1371
+ if (same) return { name: same[0] };
1372
+ const name = email ?? LEGACY_ACCOUNT;
1373
+ const names = Object.keys(accounts);
1374
+ if (names.length === 1 && names[0] === LEGACY_ACCOUNT && !accounts[LEGACY_ACCOUNT]?.email)
1375
+ return { name, replaces: LEGACY_ACCOUNT };
1376
+ return { name };
1377
+ }
1378
+ function resolveAccounts(file, env, accountFlag2) {
1379
+ const apiUrl = (a) => env.FT_API_URL ?? a?.apiUrl ?? file.apiUrl ?? DEFAULT_API_URL;
1380
+ if (env.FT_API_KEY) {
1381
+ if (accountFlag2)
1382
+ throw new Error(
1383
+ "FT_API_KEY overrides --account; unset it to use stored accounts."
1384
+ );
1385
+ return [
1386
+ {
1387
+ name: ENV_ACCOUNT,
1388
+ apiUrl: apiUrl(),
1389
+ apiKey: env.FT_API_KEY,
1390
+ // Same as before accounts existed: a workspace pinned in the file
1391
+ // still applies to the env key.
1392
+ workspaceId: env.FT_WORKSPACE_ID ?? file.workspaceId
1393
+ }
1394
+ ];
1395
+ }
1396
+ const accounts = file.accounts ?? {};
1397
+ const resolve = ([name, a]) => ({
1398
+ name,
1399
+ apiUrl: apiUrl(a),
1400
+ apiKey: a.apiKey,
1401
+ workspaceId: env.FT_WORKSPACE_ID ?? a.workspaceId
1402
+ });
1403
+ const pick2 = accountFlag2 ?? file.activeAccount;
1404
+ if (pick2 !== void 0) {
1405
+ const picked = accounts[pick2];
1406
+ if (!picked) {
1407
+ const names = Object.keys(accounts).join(", ");
1408
+ throw new Error(
1409
+ `No account named "${pick2}". Stored: ${names || "(none)"}`
1410
+ );
1411
+ }
1412
+ return [resolve([pick2, picked])];
1413
+ }
1414
+ return Object.entries(accounts).map(resolve);
1415
+ }
1416
+ function effectiveAccounts(accountFlag2) {
1417
+ return resolveAccounts(readFile(), process.env, accountFlag2);
1418
+ }
1419
+ function readConfig() {
1420
+ return readFile();
1421
+ }
1422
+ function loadConfig() {
1423
+ const file = readFile();
1424
+ let accounts = [];
1425
+ try {
1426
+ accounts = resolveAccounts(file, process.env);
1427
+ } catch {
1428
+ }
1429
+ const only = accounts.length === 1 ? accounts[0] : void 0;
1430
+ return {
1431
+ apiUrl: process.env.FT_API_URL ?? only?.apiUrl ?? file.apiUrl ?? DEFAULT_API_URL,
1432
+ apiKey: only?.apiKey,
1433
+ workspaceId: process.env.FT_WORKSPACE_ID ?? only?.workspaceId,
1434
+ adminSession: process.env.FT_ADMIN_SESSION ?? file.adminSession
1435
+ };
1436
+ }
1437
+ function saveConfig(patch) {
1438
+ const next = { ...readFile(), ...patch };
1439
+ mkdirSync2(dirname2(CONFIG_PATH), { recursive: true });
1440
+ const tmp = `${CONFIG_PATH}.${process.pid}.tmp`;
1441
+ writeFileSync2(tmp, `${JSON.stringify(next, null, 2)}
1442
+ `, { mode: 384 });
1443
+ chmodSync(tmp, 384);
1444
+ renameSync(tmp, CONFIG_PATH);
1445
+ }
1446
+ function saveAccount(name, account, replaces) {
1447
+ const file = readFile();
1448
+ const accounts = { ...file.accounts };
1449
+ if (replaces && replaces !== name) delete accounts[replaces];
1450
+ if (account) accounts[name] = account;
1451
+ else delete accounts[name];
1452
+ let activeAccount = file.activeAccount;
1453
+ if (replaces && activeAccount === replaces) activeAccount = name;
1454
+ if (!account && activeAccount === name) activeAccount = void 0;
1455
+ saveConfig({ accounts, activeAccount });
1456
+ }
1457
+
1458
+ // src/lib/api.ts
1459
+ var accountFlag;
1460
+ function setAccountFlag(name) {
1461
+ accountFlag = name;
1462
+ }
1463
+ function accountsInScope() {
1464
+ try {
1465
+ return effectiveAccounts(accountFlag);
1466
+ } catch (err) {
1467
+ const message = err.message;
1468
+ fail(
1469
+ message,
1470
+ message.startsWith("No account named") ? "See them with `ft account list`; `ft account clear` unpins." : void 0
1471
+ );
1472
+ }
1473
+ }
1474
+ function resolveAccount() {
1475
+ const accounts = accountsInScope();
1476
+ if (accounts.length === 0) {
1477
+ fail(
1478
+ "Not logged in. Run `ft login` to sign in through your browser.",
1479
+ "CI / headless only: set FT_API_KEY (or `ft login --key`) with a backend-issued token."
1480
+ );
1481
+ }
1482
+ if (accounts.length > 1) {
1483
+ fail(
1484
+ `Several accounts are stored (${accounts.map((a) => a.name).join(", ")}) and this command needs exactly one.`,
1485
+ "Pick one with --account <name>, or pin it with `ft account use <name>`."
1486
+ );
1487
+ }
1488
+ return accounts[0];
1489
+ }
1490
+ function configureClient(workspaceOverride, account = resolveAccount()) {
1491
+ const workspaceId = workspaceOverride ?? account.workspaceId;
1492
+ client.setConfig({
1493
+ baseUrl: `${account.apiUrl.replace(/\/$/, "")}/api/v1`,
1494
+ headers: {
1495
+ Authorization: `Bearer ${account.apiKey}`,
1496
+ ...workspaceId ? { "X-Workspace-Id": workspaceId } : {}
1497
+ }
1498
+ });
1499
+ }
1500
+ function configureAdminClient() {
1501
+ const cfg = loadConfig();
1502
+ if (!cfg.adminSession) {
1503
+ fail(
1504
+ "No superadmin session. Export FT_ADMIN_SESSION with a SUPER_ADMIN better-auth session token.",
1505
+ "Log in to the admin panel in your browser and copy the `better-auth.session_token` cookie."
1506
+ );
1507
+ }
1508
+ client2.setConfig({
1509
+ baseUrl: `${cfg.apiUrl.replace(/\/$/, "")}/api/admin`,
1510
+ headers: {
1511
+ Cookie: `better-auth.session_token=${cfg.adminSession}`
1512
+ }
1513
+ });
1514
+ }
1515
+ async function signedDownload(path) {
1516
+ const cfg = client.getConfig();
1517
+ const res = await fetch(`${cfg.baseUrl}${path}`, {
1518
+ redirect: "manual",
1519
+ headers: cfg.headers
1520
+ });
1521
+ const url = res.headers.get("location");
1522
+ if (!url)
1523
+ fail(
1524
+ `The API did not return a signed URL (HTTP ${res.status}).`,
1525
+ res.status === 404 ? "The settlement has no document yet, or it belongs to another workspace." : void 0
1526
+ );
1527
+ return { url, expiresInMinutes: 5 };
1528
+ }
1529
+ function unwrap(res) {
1530
+ if (res.data !== void 0) return res.data;
1531
+ const status = res.response?.status;
1532
+ const err = res.error?.error;
1533
+ if (err) {
1534
+ const lines = [
1535
+ `Error ${status ?? ""} [${err.code ?? "?"}]: ${err.message ?? "unknown failure"}`.trim()
1536
+ ];
1537
+ for (const d of err.details ?? [])
1538
+ lines.push(` \xB7 ${d.path ?? ""}: ${d.message ?? ""}`.trimEnd());
1539
+ fail(lines.join("\n"), hintFor(status));
1540
+ }
1541
+ fail(
1542
+ `The API responded with ${status ?? "an error"} without a readable body.`
1543
+ );
1544
+ }
1545
+ function describeError(res) {
1546
+ const status = res.response?.status;
1547
+ const err = res.error?.error;
1548
+ if (!err) return `HTTP ${status ?? "error"}`;
1549
+ return `${status ?? ""} ${err.code ?? "?"}: ${err.message ?? "unknown failure"}`.trim();
1550
+ }
1551
+ function hintFor(status) {
1552
+ switch (status) {
1553
+ case 401:
1554
+ return "Your session is invalid, revoked, or expired. Run `ft login`.";
1555
+ case 403:
1556
+ return "Your role or workspace does not allow this action.";
1557
+ case 404:
1558
+ return "The resource does not exist or belongs to another workspace.";
1559
+ case 422:
1560
+ return "Validation failed. Fix the fields listed above and retry.";
1561
+ case 429:
1562
+ return "Rate limit reached. Wait and retry with backoff - this one is worth retrying.";
1563
+ case 500:
1564
+ return "Server error. Retry once; if it persists, report it.";
1565
+ case 501:
1566
+ return "The backend has not implemented this operation yet.";
1567
+ case 503:
1568
+ return "The service is temporarily unavailable. Retry with backoff.";
1569
+ }
1570
+ }
1571
+ function fail(message, hint) {
1572
+ console.error(message);
1573
+ if (hint) console.error(`
1574
+ ${hint}`);
1575
+ process.exit(1);
1576
+ }
1577
+ function expandTargets(perAccount, workspaceFlag) {
1578
+ const seen = /* @__PURE__ */ new Set();
1579
+ const out = [];
1580
+ for (const { account, workspaces } of perAccount) {
1581
+ const only = workspaceFlag ?? account.workspaceId;
1582
+ for (const w of workspaces) {
1583
+ if (w.sections !== null && w.sections.length === 0) continue;
1584
+ if (only && w.id !== only) continue;
1585
+ if (seen.has(w.id)) continue;
1586
+ seen.add(w.id);
1587
+ out.push({ id: w.id, name: w.name, account });
1588
+ }
1589
+ }
1590
+ return out;
1591
+ }
1592
+ async function listTargets(override) {
1593
+ const accounts = accountsInScope();
1594
+ if (accounts.length <= 1) {
1595
+ const account = resolveAccount();
1596
+ if (!override && !account.workspaceId) {
1597
+ configureClient(void 0, account);
1598
+ const res = await getMe({});
1599
+ const targets2 = expandTargets([
1600
+ { account, workspaces: res.data?.data.workspaces ?? [] }
1601
+ ]);
1602
+ if (targets2.length > 1) return targets2;
1603
+ }
1604
+ configureClient(override, account);
1605
+ return null;
1606
+ }
1607
+ const perAccount = [];
1608
+ const errors = [];
1609
+ for (const account of accounts) {
1610
+ configureClient(void 0, account);
1611
+ const res = await getMe({});
1612
+ if (!res.data) {
1613
+ errors.push(`account ${account.name}: ${describeError(res)}`);
1614
+ continue;
1615
+ }
1616
+ perAccount.push({ account, workspaces: res.data.data.workspaces });
1617
+ }
1618
+ failIfNoneAnswered(perAccount.length, errors);
1619
+ const targets = expandTargets(perAccount, override);
1620
+ if (override && targets.length === 0) {
1621
+ fail(
1622
+ `No stored account reaches workspace ${override}.`,
1623
+ "See what each one reaches with `ft workspace list`."
1624
+ );
1625
+ }
1626
+ const [only] = targets;
1627
+ if (only && targets.length === 1) {
1628
+ configureClient(only.id, only.account);
1629
+ return null;
1630
+ }
1631
+ return targets;
1632
+ }
1633
+ function failIfNoneAnswered(answered, errors) {
1634
+ if (answered === 0 && errors.length > 0)
1635
+ fail(
1636
+ `No account could be read:
1637
+ ${errors.map((e) => ` \xB7 ${e}`).join("\n")}`,
1638
+ "Run `ft login` again for the expired ones, or remove them with `ft account remove <name>`."
1639
+ );
1640
+ for (const e of errors) console.error(`(${e})`);
1641
+ }
1642
+ function spansAccounts(targets) {
1643
+ return new Set(targets.map((t) => t.account.name)).size > 1;
1644
+ }
1645
+ function tagRow(ws, row, withAccount) {
1646
+ return {
1647
+ ...withAccount ? { account: ws.account.name } : {},
1648
+ workspaceId: ws.id,
1649
+ workspaceName: ws.name,
1650
+ ...row
1651
+ };
1652
+ }
1653
+ function splitLimit(limit, targets) {
1654
+ if (!Number.isFinite(limit) || limit <= 0 || targets <= 1) return limit;
1655
+ return Math.max(1, Math.ceil(limit / targets));
1656
+ }
1657
+
1658
+ // src/lib/output.ts
1659
+ import chalk2 from "chalk";
1660
+ import Table from "cli-table3";
1661
+ function print(data, opts = {}) {
1662
+ if (opts.json) {
1663
+ const out = opts.columnsExplicit && opts.columns && Array.isArray(data) ? data.map(
1664
+ (row) => pick(row, opts.columns)
1665
+ ) : data;
1666
+ process.stdout.write(`${JSON.stringify(out, null, 2)}
1667
+ `);
1668
+ return;
1669
+ }
1670
+ if (Array.isArray(data) && data.every(isPlainRow)) {
1671
+ if (data.length === 0) {
1672
+ console.log(chalk2.dim("(no results)"));
1673
+ return;
1674
+ }
1675
+ const cols = opts.columns ?? Object.keys(data[0]);
1676
+ const table = new Table({ head: cols.map((c2) => chalk2.hex("#07C2BA")(c2)) });
1677
+ for (const row of data) {
1678
+ table.push(cols.map((c2) => fmt(row[c2])));
1679
+ }
1680
+ console.log(table.toString());
1681
+ return;
1682
+ }
1683
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
1684
+ `);
1685
+ }
1686
+ function csvEsc(v) {
1687
+ if (v === null || v === void 0) return "";
1688
+ const s = typeof v === "object" ? JSON.stringify(v) : String(v);
1689
+ return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
1690
+ }
1691
+ function toCsv(rows, columns) {
1692
+ if (!Array.isArray(rows) || rows.length === 0) {
1693
+ return columns?.length ? columns.map(csvEsc).join(",") : "";
1694
+ }
1695
+ const cols = columns ?? Object.keys(rows[0]);
1696
+ const head = cols.map(csvEsc).join(",");
1697
+ const body = rows.map(
1698
+ (r) => cols.map((c2) => csvEsc(r[c2])).join(",")
1699
+ );
1700
+ return [head, ...body].join("\n");
1701
+ }
1702
+ function resolveColumns(opts, fallback) {
1703
+ if (opts.full) return void 0;
1704
+ if (opts.columns) {
1705
+ return opts.columns.split(",").map((c2) => c2.trim()).filter(Boolean);
1706
+ }
1707
+ return fallback;
1708
+ }
1709
+ function printNextCursor(page) {
1710
+ if (page?.nextCursor) {
1711
+ console.error(chalk2.dim(`
1712
+ More results: --cursor ${page.nextCursor}`));
1713
+ }
1714
+ }
1715
+ function isPlainRow(v) {
1716
+ return v !== null && typeof v === "object" && !Array.isArray(v);
1717
+ }
1718
+ function fmt(v) {
1719
+ if (v === null || v === void 0) return chalk2.dim("\u2014");
1720
+ if (typeof v === "object") return JSON.stringify(v);
1721
+ return String(v);
1722
+ }
1723
+ function pick(row, columns) {
1724
+ const out = {};
1725
+ for (const c2 of columns) if (c2 in row) out[c2] = row[c2];
1726
+ return out;
1727
+ }
1728
+ function printEmptyScope(workspaceFlag) {
1729
+ const workspaceId = workspaceFlag ?? loadConfig().workspaceId;
1730
+ console.error(
1731
+ chalk2.dim(
1732
+ workspaceId ? `(0 results in workspace ${workspaceId})` : "(0 results in the account's default workspace - see them all with `ft workspace list`, or scope with --workspace <id>)"
1733
+ )
1734
+ );
1735
+ }
1736
+
1737
+ // src/commands/auth.ts
1738
+ import { spawn } from "child_process";
1739
+ import chalk3 from "chalk";
1740
+ function registerAuth(program2) {
1741
+ program2.command("login").description(
1742
+ "Log in via the browser (device flow) and add the account to ~/.freeticket/config.json"
1743
+ ).option(
1744
+ "--account <name>",
1745
+ "store this login under <name> (default: the account's email); an existing one with that name is replaced"
1746
+ ).option(
1747
+ "--key <ft_live_\u2026>",
1748
+ "Skip the browser and use an API key issued in the backend (CI / automation)"
1749
+ ).option(
1750
+ "--url <url>",
1751
+ "API base URL (default: https://admin.appfreeticket.com)"
1752
+ ).option(
1753
+ "--workspace <id>",
1754
+ "pin this login to one workspace (default: every workspace the account reaches)"
1755
+ ).option("--json", "raw JSON output (confirmation goes to stderr)").action(async (opts) => {
1756
+ const apiUrl = opts.url ?? process.env.FT_API_URL ?? readConfig().apiUrl ?? DEFAULT_API_URL;
1757
+ const apiKey = opts.key ?? await deviceLogin(apiUrl);
1758
+ const workspaceId = opts.workspace;
1759
+ configureClient(workspaceId, {
1760
+ name: opts.account ?? LEGACY_ACCOUNT,
1761
+ apiUrl,
1762
+ apiKey,
1763
+ workspaceId
1764
+ });
1765
+ const me = unwrap(await getMe({})).data;
1766
+ const { name, replaces } = loginTarget(
1767
+ readConfig(),
1768
+ me.email,
1769
+ opts.account
1770
+ );
1771
+ saveAccount(
1772
+ name,
1773
+ {
1774
+ apiKey,
1775
+ ...me.email ? { email: me.email } : {},
1776
+ ...opts.url ? { apiUrl: opts.url } : {},
1777
+ ...workspaceId ? { workspaceId } : {}
1778
+ },
1779
+ replaces
1780
+ );
1781
+ console.error(
1782
+ `${chalk3.green("\u2713")} Account ${chalk3.bold(name)} saved in ${chalk3.dim(CONFIG_PATH)}`
1783
+ );
1784
+ const { activeAccount, accounts } = readConfig();
1785
+ if (activeAccount && activeAccount !== name) {
1786
+ console.error(
1787
+ chalk3.dim(
1788
+ `(account ${activeAccount} is pinned: \`ft account clear\` reads all of them, \`ft account use ${name}\` switches)`
1789
+ )
1790
+ );
1791
+ } else if (Object.keys(accounts ?? {}).length > 1) {
1792
+ console.error(
1793
+ chalk3.dim(
1794
+ "(lists now read every stored account; narrow with --account or `ft account use`)"
1795
+ )
1796
+ );
1797
+ }
1798
+ print(me, { json: opts.json });
1799
+ });
1800
+ program2.command("whoami").description(
1801
+ "Show the authenticated user and workspaces (GET /me), for every account in scope"
1802
+ ).option("--account <name>", "only this account (default: all stored)").option("--json", "raw JSON output").action(async (opts) => {
1803
+ const accounts = accountsInScope();
1804
+ if (accounts.length <= 1) {
1805
+ configureClient();
1806
+ const me = unwrap(await getMe({})).data;
1807
+ print(me, { json: opts.json });
1808
+ return;
1809
+ }
1810
+ const all = [];
1811
+ const errors = [];
1812
+ for (const account of accounts) {
1813
+ configureClient(void 0, account);
1814
+ const res = await getMe({});
1815
+ if (!res.data) {
1816
+ errors.push(`account ${account.name}: ${describeError(res)}`);
1817
+ continue;
1818
+ }
1819
+ all.push({ account: account.name, ...res.data.data });
1820
+ }
1821
+ failIfNoneAnswered(all.length, errors);
1822
+ if (opts.json) {
1823
+ print(all, { json: true });
1824
+ return;
1825
+ }
1826
+ print(
1827
+ all.map((m) => ({
1828
+ account: m.account,
1829
+ email: m.email,
1830
+ name: m.name,
1831
+ workspaces: m.workspaces.map((w) => w.slug).join(", ")
1832
+ }))
1833
+ );
1834
+ });
1835
+ program2.command("logout").description(
1836
+ "Remove a stored account (the pinned one, or the only one; --account / --all otherwise)"
1837
+ ).option("--account <name>", "remove this account").option("--all", "remove every stored account").action((opts) => {
1838
+ const { accounts = {}, activeAccount } = readConfig();
1839
+ const names = Object.keys(accounts);
1840
+ if (opts.all) {
1841
+ saveConfig({ accounts: {}, activeAccount: void 0 });
1842
+ console.log(
1843
+ `${chalk3.green("\u2713")} Logged out of every account \u2014 sessions removed from ${chalk3.dim(CONFIG_PATH)}`
1844
+ );
1845
+ return;
1846
+ }
1847
+ const name = opts.account ?? activeAccount ?? (names.length === 1 ? names[0] : void 0);
1848
+ if (names.length === 0) {
1849
+ console.log(
1850
+ `${chalk3.green("\u2713")} No stored session \u2014 nothing to remove.`
1851
+ );
1852
+ return;
1853
+ }
1854
+ if (!name) {
1855
+ fail(
1856
+ `Several accounts are stored (${names.join(", ")}): say which one to log out of.`,
1857
+ "Use `ft logout --account <name>`, or `ft logout --all`."
1858
+ );
1859
+ }
1860
+ if (!accounts[name]) {
1861
+ fail(`No account named "${name}".`, `Stored: ${names.join(", ")}`);
1862
+ }
1863
+ saveAccount(name, void 0);
1864
+ console.log(
1865
+ `${chalk3.green("\u2713")} Logged out of ${chalk3.bold(name)} \u2014 session removed from ${chalk3.dim(CONFIG_PATH)}`
1866
+ );
1867
+ });
1868
+ program2.command("config").description("Show active configuration (credentials are masked)").option("--json", "raw JSON output").action((opts) => {
1869
+ const file = readConfig();
1870
+ const cfg = loadConfig();
1871
+ print(
1872
+ {
1873
+ apiUrl: cfg.apiUrl,
1874
+ // FT_API_KEY overrides every stored account (CI).
1875
+ env: process.env.FT_API_KEY ? mask(process.env.FT_API_KEY) : null,
1876
+ activeAccount: file.activeAccount ?? null,
1877
+ accounts: Object.entries(file.accounts ?? {}).map(([name, a]) => ({
1878
+ name,
1879
+ apiUrl: a.apiUrl ?? null,
1880
+ // Same field whether it's a device-flow session or a CI API key.
1881
+ session: mask(a.apiKey),
1882
+ workspaceId: a.workspaceId ?? null
1883
+ }))
1884
+ },
1885
+ { json: opts.json }
1886
+ );
1887
+ });
1888
+ }
1889
+ function mask(secret) {
1890
+ return `${secret.slice(0, 12)}\u2026`;
1891
+ }
1892
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1893
+ function openBrowser(url) {
1894
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1895
+ try {
1896
+ spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
1897
+ } catch {
1898
+ }
1899
+ }
1900
+ async function deviceLogin(baseUrl) {
1901
+ const apiUrl = baseUrl.replace(/\/$/, "");
1902
+ client.setConfig({ baseUrl: `${apiUrl}/api/v1` });
1903
+ const start = unwrap(await postAuthDeviceCode({}));
1904
+ console.log(
1905
+ `
1906
+ Open ${chalk3.cyan(start.verification_uri)} and enter the code:
1907
+
1908
+ ${chalk3.bold(start.user_code)}
1909
+
1910
+ ${chalk3.dim("Opening your browser\u2026 (Ctrl+C to cancel)")}
1911
+ `
1912
+ );
1913
+ openBrowser(start.verification_uri_complete);
1914
+ const deadline = Date.now() + start.expires_in * 1e3;
1915
+ let interval = start.interval;
1916
+ while (Date.now() < deadline) {
1917
+ await sleep(interval * 1e3);
1918
+ const res = await postAuthDeviceToken({
1919
+ body: {
1920
+ device_code: start.device_code,
1921
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
1922
+ }
1923
+ });
1924
+ if (res.data) {
1925
+ const { access_token, workspaces } = res.data;
1926
+ if (workspaces.length > 1) {
1927
+ console.log(
1928
+ `
1929
+ ${chalk3.dim("Workspaces:")} ${workspaces.map((w) => w.slug).join(", ")} ${chalk3.dim("(all of them; narrow with --workspace or `ft workspace use`)")}`
1930
+ );
1931
+ }
1932
+ return access_token;
1933
+ }
1934
+ switch (res.error?.error) {
1935
+ case "authorization_pending":
1936
+ break;
1937
+ // keep polling at the same cadence
1938
+ case "slow_down":
1939
+ interval += 5;
1940
+ break;
1941
+ case "access_denied":
1942
+ fail("Login was denied in the browser.");
1943
+ break;
1944
+ case "expired_token":
1945
+ fail("The code expired before approval. Run `ft login` again.");
1946
+ break;
1947
+ default:
1948
+ fail(`Device login failed: ${res.error?.error ?? "unknown error"}.`);
1949
+ }
1950
+ }
1951
+ return fail("The code expired before approval. Run `ft login` again.");
1952
+ }
1953
+
1954
+ // src/commands/account.ts
1955
+ function registerAccount(program2) {
1956
+ const root = program2.command("account").alias("accounts").description("List, pin, unpin and remove stored accounts");
1957
+ root.command("list").alias("ls").description("List stored accounts (marks the pinned one)").option("--json", "raw JSON output").action((opts) => {
1958
+ const { accounts = {}, activeAccount, apiUrl } = readConfig();
1959
+ const rows = Object.entries(accounts).map(([name, a]) => ({
1960
+ active: name === activeAccount ? "*" : "",
1961
+ name,
1962
+ apiUrl: a.apiUrl ?? apiUrl ?? DEFAULT_API_URL,
1963
+ workspaceId: a.workspaceId ?? "",
1964
+ session: mask(a.apiKey)
1965
+ }));
1966
+ print(rows, {
1967
+ json: opts.json,
1968
+ columns: ["active", "name", "apiUrl", "workspaceId", "session"]
1969
+ });
1970
+ if (rows.length === 0)
1971
+ console.error(chalk4.dim("(no accounts: add one with `ft login`)"));
1972
+ else if (process.env.FT_API_KEY)
1973
+ console.error(
1974
+ chalk4.dim("(FT_API_KEY is set: it overrides every stored account)")
1975
+ );
1976
+ });
1977
+ root.command("use <name>").description(
1978
+ "Pin every command to one account (persisted in ~/.freeticket/config.json)"
1979
+ ).action((name) => {
1980
+ const names = Object.keys(readConfig().accounts ?? {});
1981
+ if (!names.includes(name)) {
1982
+ fail(
1983
+ `No account named "${name}".`,
1984
+ `Stored: ${names.join(", ") || "(none) - add one with `ft login`"}`
1985
+ );
1986
+ }
1987
+ saveConfig({ activeAccount: name });
1988
+ console.log(`${chalk4.green("\u2713")} Active account: ${chalk4.bold(name)}`);
1989
+ });
1990
+ root.command("clear").description("Unpin: go back to reading every stored account").action(() => {
1991
+ saveConfig({ activeAccount: void 0 });
1992
+ console.log(
1993
+ `${chalk4.green("\u2713")} No account pinned: lists now read all of them.`
1994
+ );
1995
+ });
1996
+ root.command("remove <name>").alias("rm").description("Remove a stored account (same as `ft logout --account`)").action((name) => {
1997
+ const names = Object.keys(readConfig().accounts ?? {});
1998
+ if (!names.includes(name)) {
1999
+ fail(`No account named "${name}".`, `Stored: ${names.join(", ")}`);
2000
+ }
2001
+ saveAccount(name, void 0);
2002
+ console.log(
2003
+ `${chalk4.green("\u2713")} Removed ${chalk4.bold(name)} from ${chalk4.dim(CONFIG_PATH)}`
2004
+ );
2005
+ });
2006
+ }
2007
+
2008
+ // src/commands/admin.ts
2009
+ import chalk5 from "chalk";
2010
+
2011
+ // src/admin-client/sdk.gen.ts
2012
+ var getMe2 = (options) => {
2013
+ return (options?.client ?? client2).get({
2014
+ security: [
2015
+ {
2016
+ in: "cookie",
2017
+ name: "better-auth.session_token",
2018
+ type: "apiKey"
2019
+ }
2020
+ ],
2021
+ url: "/me",
2022
+ ...options
2023
+ });
2024
+ };
2025
+ var getWorkspaces = (options) => {
2026
+ return (options?.client ?? client2).get({
2027
+ security: [
2028
+ {
2029
+ in: "cookie",
2030
+ name: "better-auth.session_token",
2031
+ type: "apiKey"
2032
+ }
2033
+ ],
2034
+ url: "/workspaces",
2035
+ ...options
2036
+ });
2037
+ };
2038
+ var postWorkspaces = (options) => {
2039
+ return (options.client ?? client2).post({
2040
+ security: [
2041
+ {
2042
+ in: "cookie",
2043
+ name: "better-auth.session_token",
2044
+ type: "apiKey"
2045
+ }
2046
+ ],
2047
+ url: "/workspaces",
2048
+ ...options,
2049
+ headers: {
2050
+ "Content-Type": "application/json",
2051
+ ...options?.headers
2052
+ }
2053
+ });
2054
+ };
2055
+ var getWorkspacesId = (options) => {
2056
+ return (options.client ?? client2).get({
2057
+ security: [
2058
+ {
2059
+ in: "cookie",
2060
+ name: "better-auth.session_token",
2061
+ type: "apiKey"
2062
+ }
2063
+ ],
2064
+ url: "/workspaces/{id}",
2065
+ ...options
2066
+ });
2067
+ };
2068
+ var patchWorkspacesId = (options) => {
2069
+ return (options.client ?? client2).patch({
2070
+ security: [
2071
+ {
2072
+ in: "cookie",
2073
+ name: "better-auth.session_token",
2074
+ type: "apiKey"
2075
+ }
2076
+ ],
2077
+ url: "/workspaces/{id}",
2078
+ ...options,
2079
+ headers: {
2080
+ "Content-Type": "application/json",
2081
+ ...options?.headers
2082
+ }
2083
+ });
2084
+ };
2085
+ var postWorkspacesIdPlan = (options) => {
2086
+ return (options.client ?? client2).post({
2087
+ security: [
2088
+ {
2089
+ in: "cookie",
2090
+ name: "better-auth.session_token",
2091
+ type: "apiKey"
2092
+ }
2093
+ ],
2094
+ url: "/workspaces/{id}/plan",
2095
+ ...options,
2096
+ headers: {
2097
+ "Content-Type": "application/json",
2098
+ ...options?.headers
2099
+ }
2100
+ });
2101
+ };
2102
+ var postWorkspacesIdSuspend = (options) => {
2103
+ return (options.client ?? client2).post({
2104
+ security: [
2105
+ {
2106
+ in: "cookie",
2107
+ name: "better-auth.session_token",
2108
+ type: "apiKey"
2109
+ }
2110
+ ],
2111
+ url: "/workspaces/{id}/suspend",
2112
+ ...options
2113
+ });
2114
+ };
2115
+ var postWorkspacesIdRestore = (options) => {
2116
+ return (options.client ?? client2).post({
2117
+ security: [
2118
+ {
2119
+ in: "cookie",
2120
+ name: "better-auth.session_token",
2121
+ type: "apiKey"
2122
+ }
2123
+ ],
2124
+ url: "/workspaces/{id}/restore",
2125
+ ...options
2126
+ });
2127
+ };
2128
+ var getUsers = (options) => {
2129
+ return (options?.client ?? client2).get({
2130
+ security: [
2131
+ {
2132
+ in: "cookie",
2133
+ name: "better-auth.session_token",
2134
+ type: "apiKey"
2135
+ }
2136
+ ],
2137
+ url: "/users",
2138
+ ...options
2139
+ });
2140
+ };
2141
+ var getUsersId = (options) => {
2142
+ return (options.client ?? client2).get({
2143
+ security: [
2144
+ {
2145
+ in: "cookie",
2146
+ name: "better-auth.session_token",
2147
+ type: "apiKey"
2148
+ }
2149
+ ],
2150
+ url: "/users/{id}",
2151
+ ...options
2152
+ });
2153
+ };
2154
+ var patchUsersId = (options) => {
2155
+ return (options.client ?? client2).patch({
2156
+ security: [
2157
+ {
2158
+ in: "cookie",
2159
+ name: "better-auth.session_token",
2160
+ type: "apiKey"
2161
+ }
2162
+ ],
2163
+ url: "/users/{id}",
2164
+ ...options,
2165
+ headers: {
2166
+ "Content-Type": "application/json",
2167
+ ...options?.headers
2168
+ }
2169
+ });
2170
+ };
2171
+ var postImpersonate = (options) => {
2172
+ return (options.client ?? client2).post({
2173
+ security: [
2174
+ {
2175
+ in: "cookie",
2176
+ name: "better-auth.session_token",
2177
+ type: "apiKey"
2178
+ }
2179
+ ],
2180
+ url: "/impersonate",
2181
+ ...options,
2182
+ headers: {
2183
+ "Content-Type": "application/json",
2184
+ ...options?.headers
2185
+ }
2186
+ });
2187
+ };
2188
+ var postImpersonateStop = (options) => {
2189
+ return (options?.client ?? client2).post({
2190
+ security: [
2191
+ {
2192
+ in: "cookie",
2193
+ name: "better-auth.session_token",
1047
2194
  type: "apiKey"
1048
2195
  }
1049
2196
  ],
@@ -1154,110 +2301,52 @@ var getAuditLog = (options) => {
1154
2301
  ...options
1155
2302
  });
1156
2303
  };
1157
-
1158
- // src/lib/config.ts
1159
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
1160
- import { homedir } from "os";
1161
- import { dirname, join } from "path";
1162
- var CONFIG_DIR = join(homedir(), ".freeticket");
1163
- var CONFIG_PATH = join(CONFIG_DIR, "config.json");
1164
- var DEFAULT_API_URL = "https://admin.appfreeticket.com";
1165
- function readFile() {
1166
- if (!existsSync(CONFIG_PATH)) return {};
1167
- try {
1168
- return JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
1169
- } catch {
1170
- return {};
1171
- }
1172
- }
1173
- function loadConfig() {
1174
- const file = readFile();
1175
- return {
1176
- apiUrl: process.env.FT_API_URL ?? file.apiUrl ?? DEFAULT_API_URL,
1177
- apiKey: process.env.FT_API_KEY ?? file.apiKey,
1178
- workspaceId: process.env.FT_WORKSPACE_ID ?? file.workspaceId,
1179
- adminSession: process.env.FT_ADMIN_SESSION ?? file.adminSession
1180
- };
1181
- }
1182
- function saveConfig(patch) {
1183
- const next = { ...readFile(), ...patch };
1184
- mkdirSync(dirname(CONFIG_PATH), { recursive: true });
1185
- writeFileSync(CONFIG_PATH, `${JSON.stringify(next, null, 2)}
1186
- `, {
1187
- mode: 384
1188
- });
1189
- }
1190
-
1191
- // src/lib/api.ts
1192
- function configureClient(workspaceOverride) {
1193
- const cfg = loadConfig();
1194
- if (!cfg.apiKey) {
1195
- fail(
1196
- "Not logged in. Run `ft login` to sign in through your browser.",
1197
- "CI / headless only: set FT_API_KEY (or `ft login --key`) with a backend-issued token."
1198
- );
1199
- }
1200
- const workspaceId = workspaceOverride ?? cfg.workspaceId;
1201
- client.setConfig({
1202
- baseUrl: `${cfg.apiUrl.replace(/\/$/, "")}/api/v1`,
1203
- headers: {
1204
- Authorization: `Bearer ${cfg.apiKey}`,
1205
- ...workspaceId ? { "X-Workspace-Id": workspaceId } : {}
1206
- }
1207
- });
1208
- }
1209
- function configureAdminClient() {
1210
- const cfg = loadConfig();
1211
- if (!cfg.adminSession) {
1212
- fail(
1213
- "No superadmin session. Export FT_ADMIN_SESSION with a SUPER_ADMIN better-auth session token.",
1214
- "Log in to the admin panel in your browser and copy the `better-auth.session_token` cookie."
1215
- );
1216
- }
1217
- client2.setConfig({
1218
- baseUrl: `${cfg.apiUrl.replace(/\/$/, "")}/api/admin`,
1219
- headers: {
1220
- Cookie: `better-auth.session_token=${cfg.adminSession}`
1221
- }
1222
- });
1223
- }
1224
- function unwrap(res) {
1225
- if (res.data !== void 0) return res.data;
1226
- const status = res.response?.status;
1227
- const err = res.error?.error;
1228
- if (err) {
1229
- const lines = [
1230
- `Error ${status ?? ""} [${err.code ?? "?"}]: ${err.message ?? "unknown failure"}`.trim()
1231
- ];
1232
- for (const d of err.details ?? [])
1233
- lines.push(` \xB7 ${d.path ?? ""}: ${d.message ?? ""}`.trimEnd());
1234
- fail(lines.join("\n"), hintFor(status));
1235
- }
1236
- fail(
1237
- `The API responded with ${status ?? "an error"} without a readable body.`
1238
- );
1239
- }
1240
- function hintFor(status) {
1241
- switch (status) {
1242
- case 401:
1243
- return "Your session is invalid, revoked, or expired. Run `ft login`.";
1244
- case 403:
1245
- return "Your role or workspace does not allow this action.";
1246
- case 404:
1247
- return "The resource does not exist or belongs to another workspace.";
1248
- case 501:
1249
- return "The backend has not implemented this operation yet.";
1250
- }
1251
- }
1252
- function fail(message, hint) {
1253
- console.error(message);
1254
- if (hint) console.error(`
1255
- ${hint}`);
1256
- process.exit(1);
1257
- }
2304
+ var getTokens = (options) => {
2305
+ return (options?.client ?? client2).get({
2306
+ security: [
2307
+ {
2308
+ in: "cookie",
2309
+ name: "better-auth.session_token",
2310
+ type: "apiKey"
2311
+ }
2312
+ ],
2313
+ url: "/tokens",
2314
+ ...options
2315
+ });
2316
+ };
2317
+ var postTokens = (options) => {
2318
+ return (options.client ?? client2).post({
2319
+ security: [
2320
+ {
2321
+ in: "cookie",
2322
+ name: "better-auth.session_token",
2323
+ type: "apiKey"
2324
+ }
2325
+ ],
2326
+ url: "/tokens",
2327
+ ...options,
2328
+ headers: {
2329
+ "Content-Type": "application/json",
2330
+ ...options?.headers
2331
+ }
2332
+ });
2333
+ };
2334
+ var deleteTokensId = (options) => {
2335
+ return (options.client ?? client2).delete({
2336
+ security: [
2337
+ {
2338
+ in: "cookie",
2339
+ name: "better-auth.session_token",
2340
+ type: "apiKey"
2341
+ }
2342
+ ],
2343
+ url: "/tokens/{id}",
2344
+ ...options
2345
+ });
2346
+ };
1258
2347
 
1259
2348
  // src/lib/input.ts
1260
- import { readFileSync as readFileSync2 } from "fs";
2349
+ import { readFileSync as readFileSync3 } from "fs";
1261
2350
  import * as readline from "readline";
1262
2351
  function parseData(input) {
1263
2352
  if (!input) {
@@ -1269,7 +2358,7 @@ function parseData(input) {
1269
2358
  let raw = input;
1270
2359
  if (raw.startsWith("@")) {
1271
2360
  try {
1272
- raw = readFileSync2(raw.slice(1), "utf8");
2361
+ raw = readFileSync3(raw.slice(1), "utf8");
1273
2362
  } catch {
1274
2363
  fail(`Cannot read file: ${raw.slice(1)}`);
1275
2364
  }
@@ -1280,6 +2369,16 @@ function parseData(input) {
1280
2369
  return fail("Invalid JSON in --data.");
1281
2370
  }
1282
2371
  }
2372
+ async function confirmOrExit(question, yes) {
2373
+ if (yes) return;
2374
+ if (!process.stdin.isTTY) {
2375
+ fail(
2376
+ `Refusing: ${question} \u2014 no TTY to confirm.`,
2377
+ "Pass --yes in scripts / CI."
2378
+ );
2379
+ }
2380
+ if (!await confirm(question)) fail("Aborted.");
2381
+ }
1283
2382
  function confirm(question) {
1284
2383
  if (!process.stdin.isTTY) return Promise.resolve(false);
1285
2384
  const rl = readline.createInterface({
@@ -1294,69 +2393,6 @@ function confirm(question) {
1294
2393
  });
1295
2394
  }
1296
2395
 
1297
- // src/lib/output.ts
1298
- import chalk from "chalk";
1299
- import Table from "cli-table3";
1300
- function print(data, opts = {}) {
1301
- if (opts.json) {
1302
- process.stdout.write(`${JSON.stringify(data, null, 2)}
1303
- `);
1304
- return;
1305
- }
1306
- if (Array.isArray(data) && data.every(isPlainRow)) {
1307
- if (data.length === 0) {
1308
- console.log(chalk.dim("(no results)"));
1309
- return;
1310
- }
1311
- const cols = opts.columns ?? Object.keys(data[0]);
1312
- const table = new Table({ head: cols.map((c2) => chalk.hex("#07C2BA")(c2)) });
1313
- for (const row of data) {
1314
- table.push(cols.map((c2) => fmt(row[c2])));
1315
- }
1316
- console.log(table.toString());
1317
- return;
1318
- }
1319
- process.stdout.write(`${JSON.stringify(data, null, 2)}
1320
- `);
1321
- }
1322
- function csvEsc(v) {
1323
- if (v === null || v === void 0) return "";
1324
- const s = typeof v === "object" ? JSON.stringify(v) : String(v);
1325
- return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
1326
- }
1327
- function toCsv(rows, columns) {
1328
- if (!Array.isArray(rows) || rows.length === 0) {
1329
- return columns?.length ? columns.map(csvEsc).join(",") : "";
1330
- }
1331
- const cols = columns ?? Object.keys(rows[0]);
1332
- const head = cols.map(csvEsc).join(",");
1333
- const body = rows.map(
1334
- (r) => cols.map((c2) => csvEsc(r[c2])).join(",")
1335
- );
1336
- return [head, ...body].join("\n");
1337
- }
1338
- function resolveColumns(opts, fallback) {
1339
- if (opts.full) return void 0;
1340
- if (opts.columns) {
1341
- return opts.columns.split(",").map((c2) => c2.trim()).filter(Boolean);
1342
- }
1343
- return fallback;
1344
- }
1345
- function printNextCursor(page) {
1346
- if (page?.nextCursor) {
1347
- console.error(chalk.dim(`
1348
- More results: --cursor ${page.nextCursor}`));
1349
- }
1350
- }
1351
- function isPlainRow(v) {
1352
- return v !== null && typeof v === "object" && !Array.isArray(v);
1353
- }
1354
- function fmt(v) {
1355
- if (v === null || v === void 0) return chalk.dim("\u2014");
1356
- if (typeof v === "object") return JSON.stringify(v);
1357
- return String(v);
1358
- }
1359
-
1360
2396
  // src/commands/admin.ts
1361
2397
  function registerAdmin(program2) {
1362
2398
  const admin = program2.command("admin").description("Superadmin (cross-tenant) \u2014 SUPER_ADMIN session required");
@@ -1374,14 +2410,14 @@ function registerAdmin(program2) {
1374
2410
  configureAdminClient();
1375
2411
  const me = unwrap(await getMe2({})).data;
1376
2412
  console.log(
1377
- `${chalk2.green("\u2713")} Admin session saved in ${chalk2.dim(CONFIG_PATH)}`
2413
+ `${chalk5.green("\u2713")} Admin session saved in ${chalk5.dim(CONFIG_PATH)}`
1378
2414
  );
1379
2415
  print(me, {});
1380
2416
  });
1381
2417
  admin.command("logout").description("Remove the stored superadmin session").action(() => {
1382
2418
  saveConfig({ adminSession: void 0 });
1383
2419
  console.log(
1384
- `${chalk2.green("\u2713")} Admin session removed from ${chalk2.dim(CONFIG_PATH)}`
2420
+ `${chalk5.green("\u2713")} Admin session removed from ${chalk5.dim(CONFIG_PATH)}`
1385
2421
  );
1386
2422
  });
1387
2423
  admin.command("config").description("Show admin configuration (the session is masked)").action(() => {
@@ -1399,11 +2435,14 @@ function registerAdmin(program2) {
1399
2435
  const body = unwrap(await getMe2({}));
1400
2436
  print(body.data, { json: opts.json });
1401
2437
  });
1402
- admin.command("impersonate").description(`Start impersonation (--data '{"targetUserId":"..."}')`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--json", "raw JSON output").action(async (opts) => {
2438
+ admin.command("impersonate").description(`Start impersonation (--data '{"targetUserId":"..."}')`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--yes", "skip confirmation").option("--json", "raw JSON output").action(async (opts) => {
1403
2439
  configureAdminClient();
1404
- const body = unwrap(
1405
- await postImpersonate({ body: parseData(opts.data) })
2440
+ const payload = parseData(opts.data);
2441
+ await confirmOrExit(
2442
+ `Impersonate user ${payload.targetUserId ?? "(no targetUserId in --data)"}?`,
2443
+ opts.yes
1406
2444
  );
2445
+ const body = unwrap(await postImpersonate({ body: payload }));
1407
2446
  print(body?.data ?? body, { json: opts.json });
1408
2447
  });
1409
2448
  admin.command("impersonate-stop").description("Stop the current impersonation").option("--json", "raw JSON output").action(async (opts) => {
@@ -1430,6 +2469,16 @@ function registerAdmin(program2) {
1430
2469
  name: "restore",
1431
2470
  describe: "Restore a suspended workspace",
1432
2471
  fn: postWorkspacesIdRestore
2472
+ },
2473
+ {
2474
+ // Assisted sale: activates a tier without going through Stripe
2475
+ // self-service. If the tenant had a Stripe subscription it is
2476
+ // cancelled there first; a failure there aborts with 409.
2477
+ name: "plan",
2478
+ describe: `Assign a platform plan manually (--data '{"planSlug":"spark|star|icon|legend"}')`,
2479
+ fn: postWorkspacesIdPlan,
2480
+ body: true,
2481
+ confirm: true
1433
2482
  }
1434
2483
  ],
1435
2484
  columns: ["id", "name", "type", "country", "suspended", "createdAt"],
@@ -1480,6 +2529,25 @@ function registerAdmin(program2) {
1480
2529
  columns: ["key", "enabled", "description"],
1481
2530
  noPaging: true
1482
2531
  },
2532
+ {
2533
+ // Platform service tokens (PAT): headless credential for `ft admin` in
2534
+ // CI, minted from an interactive SUPER_ADMIN session. The plaintext is
2535
+ // only ever returned by `create` — store it right away.
2536
+ name: "tokens",
2537
+ describe: "Platform service tokens (PAT)",
2538
+ list: getTokens,
2539
+ create: postTokens,
2540
+ actions: [
2541
+ {
2542
+ name: "revoke",
2543
+ describe: "Revoke a service token",
2544
+ fn: deleteTokensId,
2545
+ confirm: true
2546
+ }
2547
+ ],
2548
+ columns: ["id", "name", "lastUsedAt", "expiresAt", "createdAt"],
2549
+ noPaging: true
2550
+ },
1483
2551
  {
1484
2552
  name: "audit-log",
1485
2553
  describe: "Superadmin audit log",
@@ -1505,8 +2573,12 @@ function registerAdminResource(parent, spec) {
1505
2573
  cmd.option("--limit <n>", "results per page (1-100)", "20").option("--cursor <id>", "pagination cursor");
1506
2574
  }
1507
2575
  for (const f of spec.listFlags ?? []) cmd.option(f.flag, f.describe);
2576
+ cmd.option("--columns <list>", "comma-separated columns to display");
2577
+ cmd.option("--full", "show every field instead of the curated columns");
2578
+ cmd.option("--all", "auto-paginate: fetch every page (ignores --cursor)");
1508
2579
  cmd.option("--csv", "CSV output");
1509
2580
  cmd.option("--json", "raw JSON output");
2581
+ cmd.option("--raw", "raw JSON output including pagination metadata (page)");
1510
2582
  cmd.action(async (opts) => {
1511
2583
  configureAdminClient();
1512
2584
  const query = {};
@@ -1518,13 +2590,44 @@ function registerAdminResource(parent, spec) {
1518
2590
  const v = opts[camel(f.query)];
1519
2591
  if (v !== void 0) query[f.query] = v;
1520
2592
  }
2593
+ const columns = resolveColumns(opts, spec.columns);
2594
+ if (opts.all && !spec.noPaging) {
2595
+ const rows = [];
2596
+ let cursor;
2597
+ let page;
2598
+ do {
2599
+ const body2 = unwrap(await list({ query: { ...query, cursor } }));
2600
+ rows.push(...body2.data ?? []);
2601
+ page = body2.page;
2602
+ cursor = page?.nextCursor ?? void 0;
2603
+ } while (page?.hasMore && cursor);
2604
+ if (opts.csv) {
2605
+ process.stdout.write(`${toCsv(rows, columns)}
2606
+ `);
2607
+ return;
2608
+ }
2609
+ print(rows, {
2610
+ json: opts.json,
2611
+ columns,
2612
+ columnsExplicit: Boolean(opts.columns)
2613
+ });
2614
+ return;
2615
+ }
1521
2616
  const body = unwrap(await list({ query }));
2617
+ if (opts.raw) {
2618
+ print(body, { json: true });
2619
+ return;
2620
+ }
1522
2621
  if (opts.csv) {
1523
- process.stdout.write(`${toCsv(body.data, spec.columns)}
2622
+ process.stdout.write(`${toCsv(body.data, columns)}
1524
2623
  `);
1525
2624
  return;
1526
2625
  }
1527
- print(body.data, { json: opts.json, columns: spec.columns });
2626
+ print(body.data, {
2627
+ json: opts.json,
2628
+ columns,
2629
+ columnsExplicit: Boolean(opts.columns)
2630
+ });
1528
2631
  if (!opts.json && !spec.noPaging) printNextCursor(body.page);
1529
2632
  });
1530
2633
  }
@@ -1561,9 +2664,8 @@ function registerAdminResource(parent, spec) {
1561
2664
  cmd.option("--data <json>", "JSON body (inline or @file.json)");
1562
2665
  }
1563
2666
  cmd.action(async (value, opts) => {
1564
- if (action.confirm && !opts.yes && !await confirm(`${action.name} ${singular} ${value}?`)) {
1565
- console.error("Aborted.");
1566
- return;
2667
+ if (action.confirm) {
2668
+ await confirmOrExit(`${action.name} ${singular} ${value}?`, opts.yes);
1567
2669
  }
1568
2670
  configureAdminClient();
1569
2671
  const payload = { path: { [param]: value } };
@@ -1578,7 +2680,7 @@ function camel(s) {
1578
2680
  }
1579
2681
 
1580
2682
  // src/commands/api-keys.ts
1581
- import chalk3 from "chalk";
2683
+ import chalk6 from "chalk";
1582
2684
  var COLUMNS = [
1583
2685
  "name",
1584
2686
  "keyPrefix",
@@ -1611,185 +2713,78 @@ function registerApiKeys(program2) {
1611
2713
  }
1612
2714
  console.log(
1613
2715
  `
1614
- ${chalk3.green("\u2713")} API key "${chalk3.bold(key.name)}" created (scope: ${key.scope}).
2716
+ ${chalk6.green("\u2713")} API key "${chalk6.bold(key.name)}" created (scope: ${key.scope}).
1615
2717
  `
1616
2718
  );
1617
2719
  console.log(
1618
- chalk3.yellow(" Copy your secret now \u2014 it will NOT be shown again:\n")
1619
- );
1620
- console.log(` ${chalk3.bold.cyan(key.key)}
1621
- `);
1622
- print(
1623
- {
1624
- id: key.id,
1625
- name: key.name,
1626
- scope: key.scope,
1627
- keyPrefix: key.keyPrefix,
1628
- expiresAt: key.expiresAt,
1629
- createdAt: key.createdAt
1630
- },
1631
- {}
1632
- );
1633
- });
1634
- root.command("list").description("List your API keys (the secret is never returned)").option("--limit <n>", "results per page (1-100)", "20").option("--cursor <id>", "pagination cursor").option("--all", "auto-paginate: fetch every page (ignores --cursor)").option("--columns <list>", "comma-separated columns to display").option("--full", "show every field instead of the curated columns").option("--workspace <id>", "workspace override").option("--csv", "CSV output (for spreadsheets)").option("--json", "raw JSON output (data only)").action(async (opts) => {
1635
- configureClient(opts.workspace);
1636
- const columns = resolveColumns(opts, COLUMNS);
1637
- const query = {
1638
- limit: opts.limit,
1639
- cursor: opts.cursor
1640
- };
1641
- if (opts.all) {
1642
- const rows = [];
1643
- let cursor;
1644
- let page;
1645
- do {
1646
- const body2 = unwrap(
1647
- await getApiKeys({ query: { ...query, cursor } })
1648
- );
1649
- rows.push(...body2.data ?? []);
1650
- page = body2.page;
1651
- cursor = page?.nextCursor ?? void 0;
1652
- } while (page?.hasMore && cursor);
1653
- if (opts.csv) {
1654
- process.stdout.write(`${toCsv(rows, columns)}
1655
- `);
1656
- return;
1657
- }
1658
- print(rows, { json: opts.json, columns });
1659
- return;
1660
- }
1661
- const body = unwrap(await getApiKeys({ query }));
1662
- if (opts.csv) {
1663
- process.stdout.write(`${toCsv(body.data, columns)}
1664
- `);
1665
- return;
1666
- }
1667
- print(body.data, { json: opts.json, columns });
1668
- if (!opts.json) printNextCursor(body.page);
1669
- });
1670
- root.command("revoke <id>").description("Revoke one of your API keys").option("--yes", "skip confirmation").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (id, opts) => {
1671
- if (!opts.yes && !await confirm(`Revoke API key ${id}?`)) {
1672
- console.error("Aborted.");
1673
- return;
1674
- }
1675
- configureClient(opts.workspace);
1676
- const body = unwrap(await deleteApiKeysId({ path: { id } }));
1677
- print(body?.data ?? { revoked: id }, { json: opts.json });
1678
- });
1679
- }
1680
-
1681
- // src/commands/auth.ts
1682
- import { spawn } from "child_process";
1683
- import chalk4 from "chalk";
1684
- function registerAuth(program2) {
1685
- program2.command("login").description(
1686
- "Log in via the browser (device flow) and store the session in ~/.freeticket/config.json"
1687
- ).option(
1688
- "--key <ft_live_\u2026>",
1689
- "Skip the browser and use an API key issued in the backend (CI / automation)"
1690
- ).option(
1691
- "--url <url>",
1692
- "API base URL (default: https://admin.appfreeticket.com)"
1693
- ).option("--workspace <id>", "default active workspace").action(async (opts) => {
1694
- if (opts.url) saveConfig({ apiUrl: opts.url });
1695
- const cred = opts.key ? { apiKey: opts.key, workspaceId: void 0 } : await deviceLogin();
1696
- const workspaceId = opts.workspace ?? cred.workspaceId;
1697
- saveConfig({
1698
- apiKey: cred.apiKey,
1699
- ...workspaceId ? { workspaceId } : {}
1700
- });
1701
- configureClient(workspaceId);
1702
- const me = unwrap(await getMe({})).data;
1703
- console.log(
1704
- `${chalk4.green("\u2713")} Session saved in ${chalk4.dim(CONFIG_PATH)}`
1705
- );
1706
- print(me, {});
1707
- });
1708
- program2.command("whoami").description("Show the authenticated user and workspaces (GET /me)").option("--json", "raw JSON output").action(async (opts) => {
1709
- configureClient();
1710
- const me = unwrap(await getMe({})).data;
1711
- print(me, { json: opts.json });
1712
- });
1713
- program2.command("logout").description("Log out and remove the stored session").action(() => {
1714
- saveConfig({ apiKey: void 0 });
1715
- console.log(
1716
- `${chalk4.green("\u2713")} Logged out \u2014 session removed from ${chalk4.dim(CONFIG_PATH)}`
1717
- );
1718
- });
1719
- program2.command("config").description("Show active configuration (the credential is masked)").action(() => {
1720
- const cfg = loadConfig();
1721
- print(
1722
- {
1723
- apiUrl: cfg.apiUrl,
1724
- // Same field whether it's a device-flow session or a CI API key.
1725
- session: cfg.apiKey ? `${cfg.apiKey.slice(0, 12)}\u2026` : null,
1726
- workspaceId: cfg.workspaceId ?? null
1727
- },
1728
- {}
1729
- );
1730
- });
1731
- }
1732
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1733
- function openBrowser(url) {
1734
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1735
- try {
1736
- spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
1737
- } catch {
1738
- }
1739
- }
1740
- async function deviceLogin() {
1741
- const apiUrl = loadConfig().apiUrl.replace(/\/$/, "");
1742
- client.setConfig({ baseUrl: `${apiUrl}/api/v1` });
1743
- const start = unwrap(await postAuthDeviceCode({}));
1744
- console.log(
1745
- `
1746
- Open ${chalk4.cyan(start.verification_uri)} and enter the code:
1747
-
1748
- ${chalk4.bold(start.user_code)}
1749
-
1750
- ${chalk4.dim("Opening your browser\u2026 (Ctrl+C to cancel)")}
1751
- `
1752
- );
1753
- openBrowser(start.verification_uri_complete);
1754
- const deadline = Date.now() + start.expires_in * 1e3;
1755
- let interval = start.interval;
1756
- while (Date.now() < deadline) {
1757
- await sleep(interval * 1e3);
1758
- const res = await postAuthDeviceToken({
1759
- body: {
1760
- device_code: start.device_code,
1761
- grant_type: "urn:ietf:params:oauth:grant-type:device_code"
1762
- }
1763
- });
1764
- if (res.data) {
1765
- const { access_token, workspaces } = res.data;
1766
- const active = workspaces[0];
1767
- if (workspaces.length > 1 && active) {
1768
- console.log(
1769
- `
1770
- ${chalk4.dim("Workspaces:")} ${workspaces.map((w) => w.slug).join(", ")} ${chalk4.dim(`(using ${active.slug}; switch with --workspace)`)}`
2720
+ chalk6.yellow(" Copy your secret now \u2014 it will NOT be shown again:\n")
2721
+ );
2722
+ console.log(` ${chalk6.bold.cyan(key.key)}
2723
+ `);
2724
+ print(
2725
+ {
2726
+ id: key.id,
2727
+ name: key.name,
2728
+ scope: key.scope,
2729
+ keyPrefix: key.keyPrefix,
2730
+ expiresAt: key.expiresAt,
2731
+ createdAt: key.createdAt
2732
+ },
2733
+ {}
2734
+ );
2735
+ });
2736
+ root.command("list").description("List your API keys (the secret is never returned)").option("--limit <n>", "results per page (1-100)", "20").option("--cursor <id>", "pagination cursor").option("--all", "auto-paginate: fetch every page (ignores --cursor)").option("--columns <list>", "comma-separated columns to display").option("--full", "show every field instead of the curated columns").option("--workspace <id>", "workspace override").option("--csv", "CSV output (for spreadsheets)").option("--json", "raw JSON output (data only)").action(async (opts) => {
2737
+ configureClient(opts.workspace);
2738
+ const columns = resolveColumns(opts, COLUMNS);
2739
+ const query = {
2740
+ limit: opts.limit,
2741
+ cursor: opts.cursor
2742
+ };
2743
+ if (opts.all) {
2744
+ const rows = [];
2745
+ let cursor;
2746
+ let page;
2747
+ do {
2748
+ const body2 = unwrap(
2749
+ await getApiKeys({ query: { ...query, cursor } })
1771
2750
  );
2751
+ rows.push(...body2.data ?? []);
2752
+ page = body2.page;
2753
+ cursor = page?.nextCursor ?? void 0;
2754
+ } while (page?.hasMore && cursor);
2755
+ if (opts.csv) {
2756
+ process.stdout.write(`${toCsv(rows, columns)}
2757
+ `);
2758
+ return;
1772
2759
  }
1773
- return { apiKey: access_token, workspaceId: active?.id };
2760
+ print(rows, {
2761
+ json: opts.json,
2762
+ columns,
2763
+ columnsExplicit: Boolean(opts.columns)
2764
+ });
2765
+ if (rows.length === 0) printEmptyScope(opts.workspace);
2766
+ return;
1774
2767
  }
1775
- switch (res.error?.error) {
1776
- case "authorization_pending":
1777
- break;
1778
- // keep polling at the same cadence
1779
- case "slow_down":
1780
- interval += 5;
1781
- break;
1782
- case "access_denied":
1783
- fail("Login was denied in the browser.");
1784
- break;
1785
- case "expired_token":
1786
- fail("The code expired before approval. Run `ft login` again.");
1787
- break;
1788
- default:
1789
- fail(`Device login failed: ${res.error?.error ?? "unknown error"}.`);
2768
+ const body = unwrap(await getApiKeys({ query }));
2769
+ if (opts.csv) {
2770
+ process.stdout.write(`${toCsv(body.data, columns)}
2771
+ `);
2772
+ return;
1790
2773
  }
1791
- }
1792
- return fail("The code expired before approval. Run `ft login` again.");
2774
+ print(body.data, {
2775
+ json: opts.json,
2776
+ columns,
2777
+ columnsExplicit: Boolean(opts.columns)
2778
+ });
2779
+ if ((body.data ?? []).length === 0) printEmptyScope(opts.workspace);
2780
+ if (!opts.json) printNextCursor(body.page);
2781
+ });
2782
+ root.command("revoke <id>").description("Revoke one of your API keys").option("--yes", "skip confirmation").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (id, opts) => {
2783
+ await confirmOrExit(`Revoke API key ${id}?`, opts.yes);
2784
+ configureClient(opts.workspace);
2785
+ const body = unwrap(await deleteApiKeysId({ path: { id } }));
2786
+ print(body?.data ?? { revoked: id }, { json: opts.json });
2787
+ });
1793
2788
  }
1794
2789
 
1795
2790
  // src/commands/event-dates.ts
@@ -1824,10 +2819,7 @@ function registerEventDates(program2, spec) {
1824
2819
  print(body.data ?? body, { json: opts.json });
1825
2820
  });
1826
2821
  root.command("delete <eventId> <dateId>").description("Delete an event date").option("--yes", "skip confirmation").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (eventId, dateId, opts) => {
1827
- if (!opts.yes && !await confirm(`Delete date ${dateId}?`)) {
1828
- console.error("Aborted.");
1829
- return;
1830
- }
2822
+ await confirmOrExit(`Delete date ${dateId}?`, opts.yes);
1831
2823
  configureClient(opts.workspace);
1832
2824
  const body = unwrap(await spec.del({ path: { id: eventId, dateId } }));
1833
2825
  print(body?.data ?? { deleted: dateId }, { json: opts.json });
@@ -1835,22 +2827,49 @@ function registerEventDates(program2, spec) {
1835
2827
  }
1836
2828
 
1837
2829
  // src/commands/reports.ts
2830
+ async function reportRows(workspaceFlag, call) {
2831
+ const targets = await listTargets(workspaceFlag);
2832
+ if (!targets) {
2833
+ const res = await call();
2834
+ return unwrap(res).data;
2835
+ }
2836
+ const withAccount = spansAccounts(targets);
2837
+ const rows = [];
2838
+ for (const ws of targets) {
2839
+ configureClient(ws.id, ws.account);
2840
+ const res = await call();
2841
+ if (res.error !== void 0) {
2842
+ const where = withAccount ? `${ws.account.name} / ${ws.name}` : ws.name;
2843
+ console.error(`(${where}: ${describeError(res)})`);
2844
+ continue;
2845
+ }
2846
+ for (const row of res.data?.data ?? [])
2847
+ rows.push(tagRow(ws, row, withAccount));
2848
+ }
2849
+ return rows;
2850
+ }
1838
2851
  function registerReports(program2) {
1839
2852
  const root = program2.command("reports").description("KPIs and exports");
1840
- root.command("summary").description("Workspace KPI summary").option("--period <p>", "7d | 30d | 90d | 1y", "30d").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
2853
+ root.command("summary").description("Workspace KPI summary").option("--period <p>", "7d | 30d | 90d | 1y", "30d").option(
2854
+ "--workspace <id>",
2855
+ "read only this workspace (default: all you can access)"
2856
+ ).option("--json", "raw JSON output").action(async (opts) => {
1841
2857
  configureClient(opts.workspace);
1842
2858
  const body = unwrap(
1843
2859
  await getReportsSummary({ query: { period: opts.period } })
1844
2860
  );
1845
- print(body.data, { json: opts.json });
2861
+ printExport(body.data, opts);
1846
2862
  });
1847
2863
  root.command("reconciliation").description("CFO reconciliation: Mercado Pago vs sale vs Siigo invoice").requiredOption("--from <date>", "date_from (ISO 8601)").requiredOption("--to <date>", "date_to (ISO 8601)").option(
1848
2864
  "--match <status>",
1849
2865
  "OK | MISSING_INVOICE | MISSING_CUFE | AMOUNT_MISMATCH | MISSING_PAYMENT"
1850
- ).option("--provider <p>", "filter by payment provider").option("--page <n>", "page number").option("--page-size <n>", "rows per page").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
1851
- configureClient(opts.workspace);
1852
- const body = unwrap(
1853
- await getReportsReconciliation({
2866
+ ).option("--provider <p>", "filter by payment provider").option("--page <n>", "page number").option("--page-size <n>", "rows per page").option(
2867
+ "--workspace <id>",
2868
+ "read only this workspace (default: all you can access)"
2869
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2870
+ const rows = await reportRows(
2871
+ opts.workspace,
2872
+ () => getReportsReconciliation({
1854
2873
  query: {
1855
2874
  date_from: opts.from,
1856
2875
  date_to: opts.to,
@@ -1861,21 +2880,44 @@ function registerReports(program2) {
1861
2880
  }
1862
2881
  })
1863
2882
  );
1864
- print(body.data, { json: opts.json });
1865
- });
1866
- root.command("by-event").description("Revenue / tickets sold / availability grouped by event").option("--from <date>", "created from (ISO 8601)").option("--to <date>", "created to (ISO 8601)").option("--status <s>", "filter by sale status").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
1867
- configureClient(opts.workspace);
1868
- const body = unwrap(
1869
- await getReportsByEvent({
2883
+ printExport(rows, opts);
2884
+ });
2885
+ root.command("financials").description(
2886
+ "Per-function P&L: gross, platform fee, facial, payment fee, 4x1000, net to settle"
2887
+ ).option("--event <id>", "filter by event").option("--past", "only functions that already happened (settleable)").option(
2888
+ "--workspace <id>",
2889
+ "read only this workspace (default: all you can access)"
2890
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2891
+ const rows = await reportRows(
2892
+ opts.workspace,
2893
+ () => getReportsFinancials({
2894
+ query: {
2895
+ event: opts.event,
2896
+ past: opts.past === void 0 ? void 0 : opts.past ? "true" : "false"
2897
+ }
2898
+ })
2899
+ );
2900
+ printExport(rows, opts);
2901
+ });
2902
+ root.command("by-event").description("Revenue / tickets sold / availability grouped by event").option("--from <date>", "created from (ISO 8601)").option("--to <date>", "created to (ISO 8601)").option("--status <s>", "filter by sale status").option(
2903
+ "--workspace <id>",
2904
+ "read only this workspace (default: all you can access)"
2905
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2906
+ const rows = await reportRows(
2907
+ opts.workspace,
2908
+ () => getReportsByEvent({
1870
2909
  query: { from: opts.from, to: opts.to, status: opts.status }
1871
2910
  })
1872
2911
  );
1873
- print(body.data, { json: opts.json });
1874
- });
1875
- root.command("timeseries").description("Revenue / tickets sold bucketed over time").requiredOption("--interval <i>", "day | week | month").option("--from <date>", "created from (ISO 8601)").option("--to <date>", "created to (ISO 8601)").option("--event <id>", "filter by event").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
1876
- configureClient(opts.workspace);
1877
- const body = unwrap(
1878
- await getReportsTimeseries({
2912
+ printExport(rows, opts);
2913
+ });
2914
+ root.command("timeseries").description("Revenue / tickets sold bucketed over time").requiredOption("--interval <i>", "day | week | month").option("--from <date>", "created from (ISO 8601)").option("--to <date>", "created to (ISO 8601)").option("--event <id>", "filter by event").option(
2915
+ "--workspace <id>",
2916
+ "read only this workspace (default: all you can access)"
2917
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2918
+ const rows = await reportRows(
2919
+ opts.workspace,
2920
+ () => getReportsTimeseries({
1879
2921
  query: {
1880
2922
  interval: opts.interval,
1881
2923
  from: opts.from,
@@ -1884,15 +2926,18 @@ function registerReports(program2) {
1884
2926
  }
1885
2927
  })
1886
2928
  );
1887
- print(body.data, { json: opts.json });
1888
- });
1889
- root.command("inventory").description("Capacity / sold / reserved / available per event\xB7date\xB7type").option("--event-id <id>", "filter by event").option("--event-date-id <id>", "filter by event date").option("--from <date>", "date from (ISO 8601)").option("--to <date>", "date to (ISO 8601)").option("--include-drafts", "include draft events").option("--group-by <g>", "ticketType | date | event").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
1890
- configureClient(opts.workspace);
1891
- const body = unwrap(
1892
- await getReportsInventory({
2929
+ printExport(rows, opts);
2930
+ });
2931
+ root.command("inventory").description("Capacity / sold / reserved / available per event\xB7date\xB7type").option("--event <id>", "filter by event").option("--event-date <id>", "filter by event date").option("--event-id <id>", "alias of --event").option("--event-date-id <id>", "alias of --event-date").option("--from <date>", "date from (ISO 8601)").option("--to <date>", "date to (ISO 8601)").option("--include-drafts", "include draft events").option("--group-by <g>", "ticketType | date | event").option(
2932
+ "--workspace <id>",
2933
+ "read only this workspace (default: all you can access)"
2934
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2935
+ const rows = await reportRows(
2936
+ opts.workspace,
2937
+ () => getReportsInventory({
1893
2938
  query: {
1894
- eventId: opts.eventId,
1895
- eventDateId: opts.eventDateId,
2939
+ eventId: opts.event ?? opts.eventId,
2940
+ eventDateId: opts.eventDate ?? opts.eventDateId,
1896
2941
  from: opts.from,
1897
2942
  to: opts.to,
1898
2943
  includeDrafts: opts.includeDrafts,
@@ -1900,12 +2945,15 @@ function registerReports(program2) {
1900
2945
  }
1901
2946
  })
1902
2947
  );
1903
- print(body.data, { json: opts.json });
2948
+ printExport(rows, opts);
1904
2949
  });
1905
2950
  const exp = root.command("export").description(
1906
2951
  "Export buyers, attendees, subscribers or reconciliation (CSV)"
1907
2952
  );
1908
- exp.command("reconciliation").description("Export reconciliation (CSV) for accounting").requiredOption("--from <date>", "date_from (ISO 8601)").requiredOption("--to <date>", "date_to (ISO 8601)").option("--match <status>", "filter by match_status").option("--provider <p>", "filter by payment provider").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
2953
+ exp.command("reconciliation").description("Export reconciliation (CSV) for accounting").requiredOption("--from <date>", "date_from (ISO 8601)").requiredOption("--to <date>", "date_to (ISO 8601)").option("--match <status>", "filter by match_status").option("--provider <p>", "filter by payment provider").option(
2954
+ "--workspace <id>",
2955
+ "read only this workspace (default: all you can access)"
2956
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
1909
2957
  configureClient(opts.workspace);
1910
2958
  const body = unwrap(
1911
2959
  await getReportsExportsReconciliation({
@@ -1917,13 +2965,16 @@ function registerReports(program2) {
1917
2965
  }
1918
2966
  })
1919
2967
  );
1920
- print(body.data ?? body, { json: opts.json });
2968
+ printExport(body.data ?? body, opts);
1921
2969
  });
1922
2970
  for (const [name, fn, label] of [
1923
2971
  ["buyers", getReportsExportsBuyers, "buyers (one row per sale)"],
1924
2972
  ["attendees", getReportsExportsAttendees, "attendees (one row per ticket)"]
1925
2973
  ]) {
1926
- exp.command(name).description(`Export ${label}`).option("--event <id>", "filter by event").option("--event-date <id>", "filter by event date").option("--from <date>", "created from (ISO 8601)").option("--to <date>", "created to (ISO 8601)").option("--status <s>", "filter by sale status").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
2974
+ exp.command(name).description(`Export ${label}`).option("--event <id>", "filter by event").option("--event-date <id>", "filter by event date").option("--from <date>", "created from (ISO 8601)").option("--to <date>", "created to (ISO 8601)").option("--status <s>", "filter by sale status").option(
2975
+ "--workspace <id>",
2976
+ "read only this workspace (default: all you can access)"
2977
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
1927
2978
  configureClient(opts.workspace);
1928
2979
  const body = unwrap(
1929
2980
  await fn({
@@ -1936,27 +2987,48 @@ function registerReports(program2) {
1936
2987
  }
1937
2988
  })
1938
2989
  );
1939
- print(body.data ?? body, { json: opts.json });
2990
+ printExport(body.data ?? body, opts);
1940
2991
  });
1941
2992
  }
1942
- exp.command("subscribers").description("Export subscribers").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
2993
+ exp.command("subscribers").description("Export subscribers").option(
2994
+ "--workspace <id>",
2995
+ "read only this workspace (default: all you can access)"
2996
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
1943
2997
  configureClient(opts.workspace);
1944
2998
  const body = unwrap(await getReportsExportsSubscribers({}));
1945
- print(body.data ?? body, { json: opts.json });
2999
+ printExport(body.data ?? body, opts);
1946
3000
  });
1947
3001
  }
3002
+ function printExport(rows, opts) {
3003
+ if (typeof rows === "string") {
3004
+ process.stdout.write(rows.endsWith("\n") ? rows : `${rows}
3005
+ `);
3006
+ return;
3007
+ }
3008
+ if (opts.csv && Array.isArray(rows)) {
3009
+ process.stdout.write(`${toCsv(rows)}
3010
+ `);
3011
+ return;
3012
+ }
3013
+ print(rows, { json: opts.json });
3014
+ }
1948
3015
 
1949
3016
  // src/commands/resource.ts
3017
+ import chalk7 from "chalk";
1950
3018
  function registerResource(program2, spec) {
1951
3019
  const root = program2.command(spec.name).description(spec.describe);
1952
3020
  const singular = spec.name.replace(/s$/, "");
1953
3021
  if (spec.list) {
1954
3022
  const list = spec.list;
1955
- const cmd = root.command("list").description(`List ${spec.name} from the active workspace`).option("--limit <n>", "results per page (1-100)", "20").option("--cursor <id>", "pagination cursor").option("--all", "auto-paginate: fetch every page (ignores --cursor)").option("--columns <list>", "comma-separated columns to display").option("--full", "show every field instead of the curated columns").option("--workspace <id>", "workspace override").option("--csv", "CSV output (for spreadsheets/accounting)").option("--json", "raw JSON output (data only)").option("--raw", "raw JSON output including pagination metadata (page)");
3023
+ const cmd = root.command("list").description(
3024
+ `List ${spec.name} from every workspace you can reach (--workspace narrows it to one)`
3025
+ ).option("--limit <n>", "results per page (1-100)", "20").option("--cursor <id>", "pagination cursor").option("--all", "auto-paginate: fetch every page (ignores --cursor)").option("--columns <list>", "comma-separated columns to display").option("--full", "show every field instead of the curated columns").option(
3026
+ "--workspace <id>",
3027
+ "read only this workspace (default: all you can access)"
3028
+ ).option("--csv", "CSV output (for spreadsheets/accounting)").option("--json", "raw JSON output (data only)").option("--raw", "raw JSON output including pagination metadata (page)");
1956
3029
  for (const f of spec.listFlags ?? []) cmd.option(f.flag, f.describe);
1957
3030
  cmd.action(async (opts) => {
1958
- configureClient(opts.workspace);
1959
- const columns = resolveColumns(opts, spec.columns);
3031
+ let columns = resolveColumns(opts, spec.columns);
1960
3032
  const query = {
1961
3033
  limit: Number(opts.limit),
1962
3034
  cursor: opts.cursor
@@ -1965,6 +3037,68 @@ function registerResource(program2, spec) {
1965
3037
  const v = opts[camel2(f.query)];
1966
3038
  if (v !== void 0) query[f.query] = v;
1967
3039
  }
3040
+ const targets = await listTargets(opts.workspace);
3041
+ if (targets) {
3042
+ if (opts.cursor)
3043
+ fail(
3044
+ "--cursor needs a single workspace: a cursor from one workspace means nothing in another.",
3045
+ "Pin one with --workspace <id> (or `ft workspace use <slug>`), then paginate."
3046
+ );
3047
+ const limit = opts.all ? Number(opts.limit) : splitLimit(Number(opts.limit), targets.length);
3048
+ const withAccount = spansAccounts(targets);
3049
+ const rows = [];
3050
+ for (const ws of targets) {
3051
+ configureClient(ws.id, ws.account);
3052
+ let cursor;
3053
+ let page;
3054
+ do {
3055
+ const res = await list({ query: { ...query, limit, cursor } });
3056
+ if (res.error !== void 0) {
3057
+ console.error(
3058
+ chalk7.dim(
3059
+ `(${withAccount ? `${ws.account.name} / ` : ""}${ws.name}: ${describeError(res)})`
3060
+ )
3061
+ );
3062
+ break;
3063
+ }
3064
+ const body2 = res.data;
3065
+ for (const row of body2?.data ?? [])
3066
+ rows.push(tagRow(ws, row, withAccount));
3067
+ page = body2?.page;
3068
+ cursor = page?.nextCursor ?? void 0;
3069
+ } while (opts.all && page?.hasMore && cursor);
3070
+ }
3071
+ const max = Number(opts.limit);
3072
+ const out = !opts.all && Number.isFinite(max) && max > 0 ? rows.slice(0, max) : rows;
3073
+ if (columns && !columns.includes("workspaceName"))
3074
+ columns = ["workspaceName", ...columns];
3075
+ if (columns && withAccount && !columns.includes("account"))
3076
+ columns = ["account", ...columns];
3077
+ if (opts.raw) {
3078
+ print(
3079
+ { data: out, page: { nextCursor: null, hasMore: false } },
3080
+ { json: true }
3081
+ );
3082
+ return;
3083
+ }
3084
+ if (opts.csv) {
3085
+ process.stdout.write(`${toCsv(out, columns)}
3086
+ `);
3087
+ return;
3088
+ }
3089
+ print(out, {
3090
+ json: opts.json,
3091
+ columns,
3092
+ columnsExplicit: Boolean(opts.columns)
3093
+ });
3094
+ if (out.length === 0)
3095
+ console.error(
3096
+ chalk7.dim(
3097
+ `(0 results across ${targets.length} workspaces - check them with \`ft workspace list\`)`
3098
+ )
3099
+ );
3100
+ return;
3101
+ }
1968
3102
  if (opts.all) {
1969
3103
  const rows = [];
1970
3104
  let cursor;
@@ -1987,7 +3121,12 @@ function registerResource(program2, spec) {
1987
3121
  `);
1988
3122
  return;
1989
3123
  }
1990
- print(rows, { json: opts.json, columns });
3124
+ print(rows, {
3125
+ json: opts.json,
3126
+ columns,
3127
+ columnsExplicit: Boolean(opts.columns)
3128
+ });
3129
+ if (rows.length === 0) printEmptyScope(opts.workspace);
1991
3130
  return;
1992
3131
  }
1993
3132
  const body = unwrap(await list({ query }));
@@ -2000,13 +3139,21 @@ function registerResource(program2, spec) {
2000
3139
  `);
2001
3140
  return;
2002
3141
  }
2003
- print(body.data, { json: opts.json, columns });
3142
+ print(body.data, {
3143
+ json: opts.json,
3144
+ columns,
3145
+ columnsExplicit: Boolean(opts.columns)
3146
+ });
3147
+ if ((body.data ?? []).length === 0) printEmptyScope(opts.workspace);
2004
3148
  if (!opts.json) printNextCursor(body.page);
2005
3149
  });
2006
3150
  }
2007
3151
  if (spec.get) {
2008
3152
  const get = spec.get;
2009
- root.command("get <id>").description(`Get one ${singular} by id`).option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (id, opts) => {
3153
+ root.command("get <id>").description(`Get one ${singular} by id`).option(
3154
+ "--workspace <id>",
3155
+ "read only this workspace (default: all you can access)"
3156
+ ).option("--json", "raw JSON output").action(async (id, opts) => {
2010
3157
  configureClient(opts.workspace);
2011
3158
  const body = unwrap(await get({ path: { id } }));
2012
3159
  print(body.data, { json: opts.json });
@@ -2014,7 +3161,10 @@ function registerResource(program2, spec) {
2014
3161
  }
2015
3162
  if (spec.create) {
2016
3163
  const create = spec.create;
2017
- root.command("create").description(`Create a ${singular}`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
3164
+ root.command("create").description(`Create a ${singular}`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option(
3165
+ "--workspace <id>",
3166
+ "read only this workspace (default: all you can access)"
3167
+ ).option("--json", "raw JSON output").action(async (opts) => {
2018
3168
  configureClient(opts.workspace);
2019
3169
  const body = unwrap(await create({ body: parseData(opts.data) }));
2020
3170
  print(body.data ?? body, { json: opts.json });
@@ -2022,7 +3172,10 @@ function registerResource(program2, spec) {
2022
3172
  }
2023
3173
  if (spec.update) {
2024
3174
  const update = spec.update;
2025
- root.command("update <id>").description(`Update a ${singular} by id`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (id, opts) => {
3175
+ root.command("update <id>").description(`Update a ${singular} by id`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option(
3176
+ "--workspace <id>",
3177
+ "read only this workspace (default: all you can access)"
3178
+ ).option("--json", "raw JSON output").action(async (id, opts) => {
2026
3179
  configureClient(opts.workspace);
2027
3180
  const body = unwrap(
2028
3181
  await update({ path: { id }, body: parseData(opts.data) })
@@ -2032,18 +3185,21 @@ function registerResource(program2, spec) {
2032
3185
  }
2033
3186
  if (spec.del) {
2034
3187
  const del = spec.del;
2035
- root.command("delete <id>").description(`Delete a ${singular} by id`).option("--yes", "skip confirmation").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (id, opts) => {
2036
- if (!opts.yes && !await confirm(`Delete ${singular} ${id}?`)) {
2037
- console.error("Aborted.");
2038
- return;
2039
- }
3188
+ root.command("delete <id>").description(`Delete a ${singular} by id`).option("--yes", "skip confirmation").option(
3189
+ "--workspace <id>",
3190
+ "read only this workspace (default: all you can access)"
3191
+ ).option("--json", "raw JSON output").action(async (id, opts) => {
3192
+ await confirmOrExit(`Delete ${singular} ${id}?`, opts.yes);
2040
3193
  configureClient(opts.workspace);
2041
3194
  const body = unwrap(await del({ path: { id } }));
2042
3195
  print(body?.data ?? { deleted: id }, { json: opts.json });
2043
3196
  });
2044
3197
  }
2045
3198
  for (const action of spec.actions ?? []) {
2046
- const cmd = root.command(`${action.name} <id>`).description(action.describe).option("--workspace <id>", "workspace override").option("--json", "raw JSON output");
3199
+ const cmd = root.command(`${action.name} <id>`).description(action.describe).option(
3200
+ "--workspace <id>",
3201
+ "read only this workspace (default: all you can access)"
3202
+ ).option("--json", "raw JSON output");
2047
3203
  if (action.body) {
2048
3204
  cmd.option("--data <json>", "JSON body (inline or @file.json)");
2049
3205
  }
@@ -2055,6 +3211,7 @@ function registerResource(program2, spec) {
2055
3211
  print(body?.data ?? body ?? { ok: true, id }, { json: opts.json });
2056
3212
  });
2057
3213
  }
3214
+ spec.extend?.(root);
2058
3215
  }
2059
3216
  function camel2(s) {
2060
3217
  return s.replace(/-([a-z])/g, (_, c2) => c2.toUpperCase());
@@ -2089,145 +3246,124 @@ function registerTickets(program2) {
2089
3246
  }
2090
3247
 
2091
3248
  // src/commands/workspace.ts
2092
- import chalk5 from "chalk";
3249
+ import chalk8 from "chalk";
2093
3250
  function registerWorkspace(program2) {
2094
- const root = program2.command("workspace").description("List, switch, and show the active workspace");
2095
- root.command("list").alias("ls").description("List the workspaces you can access (marks the active one)").option("--json", "raw JSON output").action(async (opts) => {
2096
- configureClient();
2097
- const me = unwrap(await getMe({})).data;
2098
- const activeId = loadConfig().workspaceId ?? me.activeWorkspaceId;
2099
- const rows = me.workspaces.map((w) => ({
2100
- active: w.id === activeId ? "*" : "",
2101
- id: w.id,
2102
- name: w.name,
2103
- slug: w.slug
2104
- }));
3251
+ const root = program2.command("workspace").description("List, pin, unpin, and show workspaces");
3252
+ root.command("list").alias("ls").description(
3253
+ "List the workspaces you can access, across every account in scope (marks the pinned one)"
3254
+ ).option("--account <name>", "only this account (default: all stored)").option("--json", "raw JSON output").action(async (opts) => {
3255
+ const accounts = accountsInScope();
3256
+ if (accounts.length === 0) resolveAccount();
3257
+ const withAccount = accounts.length > 1;
3258
+ const rows = [];
3259
+ const errors = [];
3260
+ let answered = 0;
3261
+ for (const account of accounts) {
3262
+ configureClient(void 0, account);
3263
+ const res = await getMe({});
3264
+ if (!res.data && withAccount) {
3265
+ errors.push(`account ${account.name}: ${describeError(res)}`);
3266
+ continue;
3267
+ }
3268
+ answered++;
3269
+ const me = unwrap(res).data;
3270
+ const activeId = account.workspaceId ?? me.activeWorkspaceId;
3271
+ for (const w of me.workspaces)
3272
+ rows.push({
3273
+ ...withAccount ? { account: account.name } : {},
3274
+ active: w.id === activeId ? "*" : "",
3275
+ id: w.id,
3276
+ name: w.name,
3277
+ slug: w.slug,
3278
+ role: w.role,
3279
+ access: w.sections === null ? "full" : w.sections.length === 0 ? "revoked" : w.sections.join("|")
3280
+ });
3281
+ }
3282
+ failIfNoneAnswered(answered, errors);
2105
3283
  print(rows, {
2106
3284
  json: opts.json,
2107
- columns: ["active", "id", "name", "slug"]
3285
+ columns: [
3286
+ ...withAccount ? ["account"] : [],
3287
+ "active",
3288
+ "id",
3289
+ "name",
3290
+ "slug",
3291
+ "role",
3292
+ "access"
3293
+ ]
2108
3294
  });
2109
3295
  });
2110
3296
  root.command("use <idOrSlug>").description(
2111
- "Set the active workspace (persisted in ~/.freeticket/config.json)"
2112
- ).action(async (idOrSlug) => {
2113
- configureClient();
2114
- const me = unwrap(await getMe({})).data;
2115
- const match = me.workspaces.find(
2116
- (w) => w.id === idOrSlug || w.slug === idOrSlug
2117
- );
2118
- if (!match) {
2119
- fail(
2120
- `No workspace matches "${idOrSlug}".`,
2121
- `Available: ${me.workspaces.map((w) => w.slug).join(", ") || "(none)"}`
3297
+ "Pin every command to one workspace, and to the account that reaches it (persisted in ~/.freeticket/config.json)"
3298
+ ).option("--account <name>", "only look in this account").action(async (idOrSlug) => {
3299
+ const accounts = accountsInScope();
3300
+ if (accounts.length === 0) resolveAccount();
3301
+ const slugs = [];
3302
+ for (const account of accounts) {
3303
+ configureClient(void 0, account);
3304
+ const res = await getMe({});
3305
+ if (!res.data && accounts.length > 1) continue;
3306
+ const me = unwrap(res).data;
3307
+ const match = me.workspaces.find(
3308
+ (w) => w.id === idOrSlug || w.slug === idOrSlug
2122
3309
  );
3310
+ slugs.push(...me.workspaces.map((w) => w.slug));
3311
+ if (!match) continue;
3312
+ const stored = readConfig().accounts?.[account.name];
3313
+ if (stored)
3314
+ saveAccount(account.name, { ...stored, workspaceId: match.id });
3315
+ if (account.name !== ENV_ACCOUNT && Object.keys(readConfig().accounts ?? {}).length > 1)
3316
+ saveConfig({ activeAccount: account.name });
3317
+ console.log(
3318
+ `${chalk8.green("\u2713")} Active workspace: ${chalk8.bold(match.name)} ${chalk8.dim(`(${match.slug})`)}` + (accounts.length > 1 ? ` ${chalk8.dim(`via ${account.name}`)}` : "")
3319
+ );
3320
+ return;
3321
+ }
3322
+ fail(
3323
+ `No workspace matches "${idOrSlug}".`,
3324
+ `Available: ${slugs.join(", ") || "(none)"}`
3325
+ );
3326
+ });
3327
+ root.command("clear").description(
3328
+ "Unpin: go back to reading every workspace (and every account) you can access"
3329
+ ).option("--account <name>", "only unpin this account's workspace").action((opts) => {
3330
+ const file = readConfig();
3331
+ const names = opts.account ? [opts.account] : Object.keys(file.accounts ?? {});
3332
+ for (const name of names) {
3333
+ const stored = file.accounts?.[name];
3334
+ if (!stored) fail(`No account named "${name}".`);
3335
+ saveAccount(name, { ...stored, workspaceId: void 0 });
2123
3336
  }
2124
- saveConfig({ workspaceId: match.id });
3337
+ if (!opts.account)
3338
+ saveConfig({ activeAccount: void 0, workspaceId: void 0 });
2125
3339
  console.log(
2126
- `${chalk5.green("\u2713")} Active workspace: ${chalk5.bold(match.name)} ${chalk5.dim(`(${match.slug})`)}`
3340
+ `${chalk8.green("\u2713")} No workspace pinned: lists now read all of them.`
2127
3341
  );
2128
3342
  });
2129
- root.command("show").description("Show the active workspace").option("--json", "raw JSON output").action(async (opts) => {
2130
- configureClient();
2131
- const cfg = loadConfig();
3343
+ root.command("show").description("Show the active workspace").option(
3344
+ "--account <name>",
3345
+ "the account to ask (needed when several are stored)"
3346
+ ).option("--json", "raw JSON output").action(async (opts) => {
3347
+ const account = resolveAccount();
3348
+ configureClient(void 0, account);
2132
3349
  const me = unwrap(await getMe({})).data;
2133
- const activeId = cfg.workspaceId ?? me.activeWorkspaceId;
3350
+ const activeId = account.workspaceId ?? me.activeWorkspaceId;
2134
3351
  const active = me.workspaces.find((w) => w.id === activeId);
2135
3352
  if (!active) {
2136
3353
  fail(
2137
- "No active workspace set.",
2138
- "Pick one with `ft workspace use <slug>`."
3354
+ "No workspace pinned and the account has no default one.",
3355
+ "Pick one with `ft workspace use <slug>`, or list them with `ft workspace list`."
2139
3356
  );
2140
3357
  }
2141
3358
  print(active, { json: opts.json });
2142
3359
  });
2143
3360
  }
2144
3361
 
2145
- // src/lib/banner.ts
2146
- import { Chalk } from "chalk";
2147
- var YELLOW = "#FFD500";
2148
- var c = new Chalk({ level: 3 });
2149
- var ART = String.raw`
2150
- ___ ___ ___ ___ _____ ___ ___ _ _____ _____
2151
- | __| _ \ __| __|_ _|_ _/ __| |/ / __|_ _|
2152
- | _|| / _|| _| | | | | (__| ' <| _| | |
2153
- |_| |_|_\___|___| |_| |___\___|_|\_\___| |_|
2154
- `;
2155
- function banner() {
2156
- return [
2157
- c.hex(YELLOW)(ART),
2158
- c.hex(YELLOW)(" \u25CF ") + c.hex(YELLOW).bold("FreeTicket") + c.hex(YELLOW)(" \u2014 events, tickets, and sales from your terminal"),
2159
- ""
2160
- ].join("\n");
2161
- }
2162
-
2163
- // src/lib/update-check.ts
2164
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2165
- import { homedir as homedir2 } from "os";
2166
- import { dirname as dirname2, join as join2 } from "path";
2167
- import chalk6 from "chalk";
2168
- var CACHE_PATH = join2(homedir2(), ".freeticket", "update-check.json");
2169
- var REGISTRY = "https://registry.npmjs.org/@freeticket/cli/latest";
2170
- var ONE_DAY = 24 * 60 * 60 * 1e3;
2171
- var FETCH_TIMEOUT = 1500;
2172
- async function notifyUpdate(current) {
2173
- if (!process.stderr.isTTY || process.env.FT_NO_UPDATE_CHECK || process.env.CI) {
2174
- return;
2175
- }
2176
- try {
2177
- const latest = await getLatest();
2178
- if (latest && isNewer(latest, current)) {
2179
- process.stderr.write(
2180
- `
2181
- ${chalk6.yellow(`\u26A0 Update available: @freeticket/cli ${current} \u2192 ${latest}`)}
2182
- ${chalk6.dim(" npm i -g @freeticket/cli@latest \xB7 or use npx @freeticket/cli@latest")}
2183
-
2184
- `
2185
- );
2186
- }
2187
- } catch {
2188
- }
2189
- }
2190
- async function getLatest() {
2191
- const cached = readCache();
2192
- if (cached && Date.now() - cached.at < ONE_DAY) return cached.latest;
2193
- const res = await fetch(REGISTRY, {
2194
- signal: AbortSignal.timeout(FETCH_TIMEOUT),
2195
- headers: { Accept: "application/vnd.npm.install-v1+json" }
2196
- });
2197
- if (!res.ok) throw new Error(`registry ${res.status}`);
2198
- const latest = (await res.json()).version ?? null;
2199
- if (latest) writeCache({ at: Date.now(), latest });
2200
- return latest;
2201
- }
2202
- function readCache() {
2203
- if (!existsSync2(CACHE_PATH)) return null;
2204
- try {
2205
- return JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
2206
- } catch {
2207
- return null;
2208
- }
2209
- }
2210
- function writeCache(v) {
2211
- try {
2212
- mkdirSync2(dirname2(CACHE_PATH), { recursive: true });
2213
- writeFileSync2(CACHE_PATH, JSON.stringify(v));
2214
- } catch {
2215
- }
2216
- }
2217
- function isNewer(a, b) {
2218
- const parse = (v) => {
2219
- const [maj, min, pat] = (v.replace(/^v/, "").split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0);
2220
- return [maj ?? 0, min ?? 0, pat ?? 0];
2221
- };
2222
- const [aM, aN, aP] = parse(a);
2223
- const [bM, bN, bP] = parse(b);
2224
- return aM > bM || aM === bM && (aN > bN || aN === bN && aP > bP);
2225
- }
2226
-
2227
- // src/index.ts
3362
+ // src/program.ts
2228
3363
  var program = new Command();
2229
3364
  program.name("ft").description("Official FreeTicket CLI").version(package_default.version, "-v, --version").addHelpText("beforeAll", banner());
2230
3365
  registerAuth(program);
3366
+ registerAccount(program);
2231
3367
  registerWorkspace(program);
2232
3368
  registerResource(program, {
2233
3369
  name: "events",
@@ -2241,7 +3377,41 @@ registerResource(program, {
2241
3377
  { name: "publish", describe: "Publish an event", fn: postEventsIdPublish }
2242
3378
  ],
2243
3379
  // startsAt lives on EventDate, not Event — use createdAt for a temporal column.
2244
- columns: ["id", "name", "status", "createdAt"]
3380
+ columns: ["id", "name", "status", "createdAt"],
3381
+ listFlags: [
3382
+ { flag: "--q <text>", describe: "search by name", query: "q" },
3383
+ {
3384
+ flag: "--status <s>",
3385
+ describe: "DRAFT | PUBLISHED | SOLD_OUT | CANCELLED | COMPLETED",
3386
+ query: "status"
3387
+ },
3388
+ {
3389
+ flag: "--with-total",
3390
+ describe: "include page.total (opt-in: costs an extra count query)",
3391
+ query: "withTotal"
3392
+ }
3393
+ ]
3394
+ });
3395
+ registerResource(program, {
3396
+ name: "settlements",
3397
+ describe: "Settlements paid to the organizer",
3398
+ list: getSettlements,
3399
+ columns: ["id", "reference", "status", "amount", "currency", "createdAt"],
3400
+ listFlags: [
3401
+ { flag: "--event <id>", describe: "filter by event", query: "event" },
3402
+ {
3403
+ flag: "--status <s>",
3404
+ describe: "SENT | AWAITING_PAYMENT | PAID",
3405
+ query: "status"
3406
+ }
3407
+ ],
3408
+ extend: (root) => {
3409
+ root.command("document <id>").description("Signed download URL for the settlement PDF (5 min TTL)").option("--proof <fileName>", "download a payment proof instead").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (id, opts) => {
3410
+ configureClient(opts.workspace);
3411
+ const path = opts.proof ? `/settlements/${id}/proofs/${encodeURIComponent(opts.proof)}` : `/settlements/${id}/document`;
3412
+ print(await signedDownload(path), { json: opts.json });
3413
+ });
3414
+ }
2245
3415
  });
2246
3416
  registerEventDates(program, {
2247
3417
  list: getEventsIdDates,
@@ -2256,10 +3426,18 @@ registerResource(program, {
2256
3426
  get: getSalesId,
2257
3427
  create: postSales,
2258
3428
  actions: [
2259
- { name: "cancel", describe: "Cancel a sale", fn: postSalesIdCancel },
3429
+ {
3430
+ name: "cancel",
3431
+ describe: `Cancel a sale (--data '{"acknowledge_open_payment":true}' if the payment is still open)`,
3432
+ fn: postSalesIdCancel,
3433
+ body: true
3434
+ },
2260
3435
  {
2261
3436
  name: "refund",
2262
- describe: "Refund a sale (--data for partial amount)",
3437
+ // The contract's SaleRefundRequest only takes `acknowledge_manual` and is
3438
+ // additionalProperties:false, so there is no partial-amount field to pass.
3439
+ // The old text promised one and earned a guaranteed 422 (issue #42).
3440
+ describe: `Refund a sale (--data '{"acknowledge_manual":true}' for a manual/offline refund)`,
2263
3441
  fn: postSalesIdRefund,
2264
3442
  body: true
2265
3443
  },
@@ -2394,12 +3572,67 @@ registerResource(program, {
2394
3572
  body: true
2395
3573
  }
2396
3574
  ],
2397
- columns: ["id", "name", "email", "role"]
3575
+ columns: ["id", "name", "email", "role", "workspaceName"],
3576
+ listFlags: [
3577
+ {
3578
+ flag: "--workspace-ids <ids>",
3579
+ describe: "comma-separated workspace ids (max 25): staff of all of them in one call",
3580
+ query: "workspaceIds"
3581
+ }
3582
+ ]
3583
+ });
3584
+ registerResource(program, {
3585
+ name: "content-videos",
3586
+ describe: "Organization videos",
3587
+ list: getContentVideos,
3588
+ columns: ["id", "title", "publishedAt", "memberOnly"]
3589
+ });
3590
+ registerResource(program, {
3591
+ name: "content-posts",
3592
+ describe: "Organization posts",
3593
+ list: getContentPosts,
3594
+ columns: ["id", "title", "publishedAt", "memberOnly"]
3595
+ });
3596
+ registerResource(program, {
3597
+ name: "content-lives",
3598
+ describe: "Organization live streams",
3599
+ list: getContentLives,
3600
+ get: getContentLivesId,
3601
+ columns: ["id", "title", "status", "startsAt", "memberOnly"],
3602
+ extend: (root) => {
3603
+ root.command("playback-token").description(
3604
+ "Mint a signed playback token (30 min live / 1 h video). `memberOnly` content needs a buyer session."
3605
+ ).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
3606
+ configureClient(opts.workspace);
3607
+ const body = unwrap(
3608
+ await postContentPlaybackToken({
3609
+ body: parseData(opts.data)
3610
+ })
3611
+ );
3612
+ print(body?.data ?? body, { json: opts.json });
3613
+ });
3614
+ }
2398
3615
  });
2399
3616
  registerTickets(program);
2400
3617
  registerReports(program);
2401
3618
  registerApiKeys(program);
2402
3619
  registerAdmin(program);
3620
+ function addAccountOption(cmd) {
3621
+ if (cmd.name() === "admin") return;
3622
+ const longs = cmd.options.map((o) => o.long);
3623
+ if (longs.includes("--workspace") && !longs.includes("--account"))
3624
+ cmd.option(
3625
+ "--account <name>",
3626
+ "use only this stored account (default: all of them; see `ft account list`)"
3627
+ );
3628
+ for (const sub of cmd.commands) addAccountOption(sub);
3629
+ }
3630
+ addAccountOption(program);
3631
+ program.hook("preAction", (_program, action) => {
3632
+ setAccountFlag(action.opts().account);
3633
+ });
3634
+
3635
+ // src/index.ts
2403
3636
  if (process.argv.length <= 2) {
2404
3637
  console.log(banner());
2405
3638
  program.outputHelp();