@freeticket/cli 0.9.0 → 0.11.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 +40 -19
  2. package/dist/index.js +1602 -537
  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.9.0",
6
+ version: "0.11.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,6 +66,97 @@ 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 checkForUpdate(current, argv = process.argv) {
97
+ if (updateCheckDisabled(argv, process.env, Boolean(process.stderr.isTTY)))
98
+ return null;
99
+ try {
100
+ const latest = await getLatest();
101
+ if (latest && isNewer(latest, current)) {
102
+ return `
103
+ ${chalk.yellow(`\u26A0 Update available: @freeticket/cli ${current} \u2192 ${latest}`)}
104
+ ${chalk.dim(" npm i -g @freeticket/cli@latest \xB7 or use npx @freeticket/cli@latest")}
105
+
106
+ `;
107
+ }
108
+ } catch {
109
+ }
110
+ return null;
111
+ }
112
+ function updateCheckDisabled(argv, env, isTTY) {
113
+ if (!isTTY || env.FT_NO_UPDATE_CHECK || env.CI) return true;
114
+ return argv.some((a) => a === "--json" || a === "--raw" || a === "--csv");
115
+ }
116
+ async function getLatest() {
117
+ const cached = readCache();
118
+ const now = Date.now();
119
+ if (cached && cached.at <= now && now - cached.at < ONE_DAY)
120
+ return cached.latest;
121
+ const res = await fetch(REGISTRY, {
122
+ signal: AbortSignal.timeout(FETCH_TIMEOUT),
123
+ // Not the abbreviated `application/vnd.npm.install-v1+json`: the
124
+ // `/latest` endpoint answers that with 406, so the notice never fired.
125
+ headers: { Accept: "application/json" }
126
+ });
127
+ if (!res.ok) throw new Error(`registry ${res.status}`);
128
+ const latest = (await res.json()).version ?? null;
129
+ if (latest) writeCache({ at: Date.now(), latest });
130
+ return latest;
131
+ }
132
+ function readCache() {
133
+ if (!existsSync(CACHE_PATH)) return null;
134
+ try {
135
+ return JSON.parse(readFileSync(CACHE_PATH, "utf8"));
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+ function writeCache(v) {
141
+ try {
142
+ mkdirSync(dirname(CACHE_PATH), { recursive: true });
143
+ writeFileSync(CACHE_PATH, JSON.stringify(v));
144
+ } catch {
145
+ }
146
+ }
147
+ function isNewer(a, b) {
148
+ const parse = (v) => {
149
+ const [maj, min, pat] = (v.replace(/^v/, "").split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0);
150
+ return [maj ?? 0, min ?? 0, pat ?? 0];
151
+ };
152
+ const [aM, aN, aP] = parse(a);
153
+ const [bM, bN, bP] = parse(b);
154
+ return aM > bM || aM === bM && (aN > bN || aN === bN && aP > bP);
155
+ }
156
+
157
+ // src/program.ts
158
+ import { Command } from "commander";
159
+
72
160
  // src/client/client.gen.ts
73
161
  import { createClient, createConfig } from "@hey-api/client-fetch";
74
162
  var client = createClient(createConfig({
@@ -128,6 +216,36 @@ var postAuthDeviceToken = (options) => {
128
216
  }
129
217
  });
130
218
  };
219
+ var postAuthSignup = (options) => {
220
+ return (options.client ?? client).post({
221
+ url: "/auth/signup",
222
+ ...options,
223
+ headers: {
224
+ "Content-Type": "application/json",
225
+ ...options?.headers
226
+ }
227
+ });
228
+ };
229
+ var postWorkspaces = (options) => {
230
+ return (options.client ?? client).post({
231
+ security: [
232
+ {
233
+ name: "Authorization",
234
+ type: "apiKey"
235
+ },
236
+ {
237
+ name: "x-api-key",
238
+ type: "apiKey"
239
+ }
240
+ ],
241
+ url: "/workspaces",
242
+ ...options,
243
+ headers: {
244
+ "Content-Type": "application/json",
245
+ ...options?.headers
246
+ }
247
+ });
248
+ };
131
249
  var getMe = (options) => {
132
250
  return (options?.client ?? client).get({
133
251
  security: [
@@ -248,6 +366,22 @@ var postEventsIdPublish = (options) => {
248
366
  ...options
249
367
  });
250
368
  };
369
+ var postEventsIdCancel = (options) => {
370
+ return (options.client ?? client).post({
371
+ security: [
372
+ {
373
+ name: "Authorization",
374
+ type: "apiKey"
375
+ },
376
+ {
377
+ name: "x-api-key",
378
+ type: "apiKey"
379
+ }
380
+ ],
381
+ url: "/events/{id}/cancel",
382
+ ...options
383
+ });
384
+ };
251
385
  var deleteEventsIdDatesDateId = (options) => {
252
386
  return (options.client ?? client).delete({
253
387
  security: [
@@ -676,6 +810,38 @@ var postStaff = (options) => {
676
810
  }
677
811
  });
678
812
  };
813
+ var deleteStaffId = (options) => {
814
+ return (options.client ?? client).delete({
815
+ security: [
816
+ {
817
+ name: "Authorization",
818
+ type: "apiKey"
819
+ },
820
+ {
821
+ name: "x-api-key",
822
+ type: "apiKey"
823
+ }
824
+ ],
825
+ url: "/staff/{id}",
826
+ ...options
827
+ });
828
+ };
829
+ var getStaffId = (options) => {
830
+ return (options.client ?? client).get({
831
+ security: [
832
+ {
833
+ name: "Authorization",
834
+ type: "apiKey"
835
+ },
836
+ {
837
+ name: "x-api-key",
838
+ type: "apiKey"
839
+ }
840
+ ],
841
+ url: "/staff/{id}",
842
+ ...options
843
+ });
844
+ };
679
845
  var patchStaffIdRole = (options) => {
680
846
  return (options.client ?? client).patch({
681
847
  security: [
@@ -872,6 +1038,22 @@ var getSettlements = (options) => {
872
1038
  ...options
873
1039
  });
874
1040
  };
1041
+ var getSettlementsId = (options) => {
1042
+ return (options.client ?? client).get({
1043
+ security: [
1044
+ {
1045
+ name: "Authorization",
1046
+ type: "apiKey"
1047
+ },
1048
+ {
1049
+ name: "x-api-key",
1050
+ type: "apiKey"
1051
+ }
1052
+ ],
1053
+ url: "/settlements/{id}",
1054
+ ...options
1055
+ });
1056
+ };
875
1057
  var getDiscounts = (options) => {
876
1058
  return (options?.client ?? client).get({
877
1059
  security: [
@@ -996,6 +1178,26 @@ var deleteWebhooksId = (options) => {
996
1178
  ...options
997
1179
  });
998
1180
  };
1181
+ var patchWebhooksId = (options) => {
1182
+ return (options.client ?? client).patch({
1183
+ security: [
1184
+ {
1185
+ name: "Authorization",
1186
+ type: "apiKey"
1187
+ },
1188
+ {
1189
+ name: "x-api-key",
1190
+ type: "apiKey"
1191
+ }
1192
+ ],
1193
+ url: "/webhooks/{id}",
1194
+ ...options,
1195
+ headers: {
1196
+ "Content-Type": "application/json",
1197
+ ...options?.headers
1198
+ }
1199
+ });
1200
+ };
999
1201
  var getMembershipPlansIdSubscribers = (options) => {
1000
1202
  return (options.client ?? client).get({
1001
1203
  security: [
@@ -1044,8 +1246,8 @@ var getSalesIdTickets = (options) => {
1044
1246
  ...options
1045
1247
  });
1046
1248
  };
1047
- var postTicketsTicketCodeResend = (options) => {
1048
- return (options.client ?? client).post({
1249
+ var getSalesIdAttempts = (options) => {
1250
+ return (options.client ?? client).get({
1049
1251
  security: [
1050
1252
  {
1051
1253
  name: "Authorization",
@@ -1056,10 +1258,30 @@ var postTicketsTicketCodeResend = (options) => {
1056
1258
  type: "apiKey"
1057
1259
  }
1058
1260
  ],
1059
- url: "/tickets/{ticketCode}/resend",
1261
+ url: "/sales/{id}/attempts",
1060
1262
  ...options
1061
1263
  });
1062
1264
  };
1265
+ var patchTicketsTicketCode = (options) => {
1266
+ return (options.client ?? client).patch({
1267
+ security: [
1268
+ {
1269
+ name: "Authorization",
1270
+ type: "apiKey"
1271
+ },
1272
+ {
1273
+ name: "x-api-key",
1274
+ type: "apiKey"
1275
+ }
1276
+ ],
1277
+ url: "/tickets/{ticketCode}",
1278
+ ...options,
1279
+ headers: {
1280
+ "Content-Type": "application/json",
1281
+ ...options?.headers
1282
+ }
1283
+ });
1284
+ };
1063
1285
  var postTicketsTicketCodeCheckin = (options) => {
1064
1286
  return (options.client ?? client).post({
1065
1287
  security: [
@@ -1073,7 +1295,11 @@ var postTicketsTicketCodeCheckin = (options) => {
1073
1295
  }
1074
1296
  ],
1075
1297
  url: "/tickets/{ticketCode}/checkin",
1076
- ...options
1298
+ ...options,
1299
+ headers: {
1300
+ "Content-Type": "application/json",
1301
+ ...options?.headers
1302
+ }
1077
1303
  });
1078
1304
  };
1079
1305
  var getTicketsTicketCodeAccess = (options) => {
@@ -1144,53 +1370,51 @@ var deleteApiKeysId = (options) => {
1144
1370
  ...options
1145
1371
  });
1146
1372
  };
1147
-
1148
- // src/commands/admin.ts
1149
- import chalk2 from "chalk";
1150
-
1151
- // src/admin-client/client.gen.ts
1152
- import { createClient as createClient2, createConfig as createConfig2 } from "@hey-api/client-fetch";
1153
- var client2 = createClient2(createConfig2({
1154
- baseUrl: "https://admin.appfreeticket.com/api/admin"
1155
- }));
1156
-
1157
- // src/admin-client/sdk.gen.ts
1158
- var getMe2 = (options) => {
1159
- return (options?.client ?? client2).get({
1373
+ var getContentVideos = (options) => {
1374
+ return (options?.client ?? client).get({
1160
1375
  security: [
1161
1376
  {
1162
- in: "cookie",
1163
- name: "better-auth.session_token",
1377
+ name: "Authorization",
1378
+ type: "apiKey"
1379
+ },
1380
+ {
1381
+ name: "x-api-key",
1164
1382
  type: "apiKey"
1165
1383
  }
1166
1384
  ],
1167
- url: "/me",
1385
+ url: "/content/videos",
1168
1386
  ...options
1169
1387
  });
1170
1388
  };
1171
- var getWorkspaces = (options) => {
1172
- return (options?.client ?? client2).get({
1389
+ var getContentPosts = (options) => {
1390
+ return (options?.client ?? client).get({
1173
1391
  security: [
1174
1392
  {
1175
- in: "cookie",
1176
- name: "better-auth.session_token",
1393
+ name: "Authorization",
1394
+ type: "apiKey"
1395
+ },
1396
+ {
1397
+ name: "x-api-key",
1177
1398
  type: "apiKey"
1178
1399
  }
1179
1400
  ],
1180
- url: "/workspaces",
1401
+ url: "/content/posts",
1181
1402
  ...options
1182
1403
  });
1183
1404
  };
1184
- var postWorkspaces = (options) => {
1185
- return (options.client ?? client2).post({
1405
+ var postContentPosts = (options) => {
1406
+ return (options.client ?? client).post({
1186
1407
  security: [
1187
1408
  {
1188
- in: "cookie",
1189
- name: "better-auth.session_token",
1409
+ name: "Authorization",
1410
+ type: "apiKey"
1411
+ },
1412
+ {
1413
+ name: "x-api-key",
1190
1414
  type: "apiKey"
1191
1415
  }
1192
1416
  ],
1193
- url: "/workspaces",
1417
+ url: "/content/posts",
1194
1418
  ...options,
1195
1419
  headers: {
1196
1420
  "Content-Type": "application/json",
@@ -1198,15 +1422,863 @@ var postWorkspaces = (options) => {
1198
1422
  }
1199
1423
  });
1200
1424
  };
1201
- var getWorkspacesId = (options) => {
1202
- return (options.client ?? client2).get({
1425
+ var getContentLives = (options) => {
1426
+ return (options?.client ?? client).get({
1203
1427
  security: [
1204
1428
  {
1205
- in: "cookie",
1206
- name: "better-auth.session_token",
1429
+ name: "Authorization",
1207
1430
  type: "apiKey"
1208
- }
1209
- ],
1431
+ },
1432
+ {
1433
+ name: "x-api-key",
1434
+ type: "apiKey"
1435
+ }
1436
+ ],
1437
+ url: "/content/lives",
1438
+ ...options
1439
+ });
1440
+ };
1441
+ var getContentLivesId = (options) => {
1442
+ return (options.client ?? client).get({
1443
+ security: [
1444
+ {
1445
+ name: "Authorization",
1446
+ type: "apiKey"
1447
+ },
1448
+ {
1449
+ name: "x-api-key",
1450
+ type: "apiKey"
1451
+ }
1452
+ ],
1453
+ url: "/content/lives/{id}",
1454
+ ...options
1455
+ });
1456
+ };
1457
+ var postContentPlaybackToken = (options) => {
1458
+ return (options.client ?? client).post({
1459
+ security: [
1460
+ {
1461
+ name: "Authorization",
1462
+ type: "apiKey"
1463
+ },
1464
+ {
1465
+ name: "x-api-key",
1466
+ type: "apiKey"
1467
+ }
1468
+ ],
1469
+ url: "/content/playback-token",
1470
+ ...options,
1471
+ headers: {
1472
+ "Content-Type": "application/json",
1473
+ ...options?.headers
1474
+ }
1475
+ });
1476
+ };
1477
+ var postTicketsTicketCodeResend = (options) => {
1478
+ return (options.client ?? client).post({
1479
+ security: [
1480
+ {
1481
+ name: "Authorization",
1482
+ type: "apiKey"
1483
+ },
1484
+ {
1485
+ name: "x-api-key",
1486
+ type: "apiKey"
1487
+ }
1488
+ ],
1489
+ url: "/tickets/{ticketCode}/resend",
1490
+ ...options
1491
+ });
1492
+ };
1493
+
1494
+ // src/commands/account.ts
1495
+ import chalk4 from "chalk";
1496
+
1497
+ // src/admin-client/client.gen.ts
1498
+ import { createClient as createClient2, createConfig as createConfig2 } from "@hey-api/client-fetch";
1499
+ var client2 = createClient2(createConfig2({
1500
+ baseUrl: "https://admin.appfreeticket.com/api/admin"
1501
+ }));
1502
+
1503
+ // src/lib/config.ts
1504
+ import {
1505
+ chmodSync,
1506
+ existsSync as existsSync2,
1507
+ mkdirSync as mkdirSync2,
1508
+ readFileSync as readFileSync2,
1509
+ renameSync,
1510
+ writeFileSync as writeFileSync2
1511
+ } from "fs";
1512
+ import { homedir as homedir2 } from "os";
1513
+ import { dirname as dirname2, join as join2 } from "path";
1514
+ var CONFIG_DIR = join2(homedir2(), ".freeticket");
1515
+ var CONFIG_PATH = join2(CONFIG_DIR, "config.json");
1516
+ var DEFAULT_API_URL = "https://admin.appfreeticket.com";
1517
+ var LEGACY_ACCOUNT = "default";
1518
+ var ENV_ACCOUNT = "FT_API_KEY";
1519
+ var ConfigError = class extends Error {
1520
+ };
1521
+ function readFile() {
1522
+ if (!existsSync2(CONFIG_PATH)) return {};
1523
+ let parsed;
1524
+ try {
1525
+ parsed = JSON.parse(readFileSync2(CONFIG_PATH, "utf8"));
1526
+ } catch (err) {
1527
+ throw new ConfigError(
1528
+ `${CONFIG_PATH} is not valid JSON (${err.message}). Fix it, or move it away and run \`ft login\` again.`
1529
+ );
1530
+ }
1531
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
1532
+ throw new ConfigError(`${CONFIG_PATH} does not hold a JSON object.`);
1533
+ return migrate(parsed);
1534
+ }
1535
+ function migrate(file) {
1536
+ const { apiKey, ...rest } = file;
1537
+ if (!apiKey) return rest;
1538
+ const accounts = { ...rest.accounts };
1539
+ accounts[LEGACY_ACCOUNT] ??= {
1540
+ apiKey,
1541
+ ...rest.workspaceId ? { workspaceId: rest.workspaceId } : {}
1542
+ };
1543
+ return { ...rest, accounts };
1544
+ }
1545
+ function loginTarget(file, email, accountFlag2) {
1546
+ if (accountFlag2) return { name: accountFlag2 };
1547
+ const accounts = file.accounts ?? {};
1548
+ const same = Object.entries(accounts).find(
1549
+ ([, a]) => email !== void 0 && a.email === email
1550
+ );
1551
+ if (same) return { name: same[0] };
1552
+ const name = email ?? LEGACY_ACCOUNT;
1553
+ const names = Object.keys(accounts);
1554
+ if (names.length === 1 && names[0] === LEGACY_ACCOUNT && !accounts[LEGACY_ACCOUNT]?.email)
1555
+ return { name, replaces: LEGACY_ACCOUNT };
1556
+ return { name };
1557
+ }
1558
+ function resolveAccounts(file, env, accountFlag2) {
1559
+ const apiUrl = (a) => env.FT_API_URL ?? a?.apiUrl ?? file.apiUrl ?? DEFAULT_API_URL;
1560
+ if (env.FT_API_KEY) {
1561
+ if (accountFlag2)
1562
+ throw new Error(
1563
+ "FT_API_KEY overrides --account; unset it to use stored accounts."
1564
+ );
1565
+ return [
1566
+ {
1567
+ name: ENV_ACCOUNT,
1568
+ apiUrl: apiUrl(),
1569
+ apiKey: env.FT_API_KEY,
1570
+ // Same as before accounts existed: a workspace pinned in the file
1571
+ // still applies to the env key.
1572
+ workspaceId: env.FT_WORKSPACE_ID ?? file.workspaceId
1573
+ }
1574
+ ];
1575
+ }
1576
+ const accounts = file.accounts ?? {};
1577
+ const resolve = ([name, a]) => ({
1578
+ name,
1579
+ apiUrl: apiUrl(a),
1580
+ apiKey: a.apiKey,
1581
+ workspaceId: env.FT_WORKSPACE_ID ?? a.workspaceId
1582
+ });
1583
+ const pick2 = accountFlag2 ?? file.activeAccount;
1584
+ if (pick2 !== void 0) {
1585
+ const picked = accounts[pick2];
1586
+ if (!picked) {
1587
+ const names = Object.keys(accounts).join(", ");
1588
+ throw new Error(
1589
+ `No account named "${pick2}". Stored: ${names || "(none)"}`
1590
+ );
1591
+ }
1592
+ return [resolve([pick2, picked])];
1593
+ }
1594
+ return Object.entries(accounts).map(resolve);
1595
+ }
1596
+ function effectiveAccounts(accountFlag2) {
1597
+ return resolveAccounts(readFile(), process.env, accountFlag2);
1598
+ }
1599
+ function readConfig() {
1600
+ return readFile();
1601
+ }
1602
+ function loadConfig() {
1603
+ const file = readFile();
1604
+ let accounts = [];
1605
+ try {
1606
+ accounts = resolveAccounts(file, process.env);
1607
+ } catch {
1608
+ }
1609
+ const only = accounts.length === 1 ? accounts[0] : void 0;
1610
+ return {
1611
+ apiUrl: process.env.FT_API_URL ?? only?.apiUrl ?? file.apiUrl ?? DEFAULT_API_URL,
1612
+ apiKey: only?.apiKey,
1613
+ workspaceId: process.env.FT_WORKSPACE_ID ?? only?.workspaceId,
1614
+ adminSession: process.env.FT_ADMIN_SESSION ?? file.adminSession
1615
+ };
1616
+ }
1617
+ function saveConfig(patch) {
1618
+ const next = { ...readFile(), ...patch };
1619
+ mkdirSync2(dirname2(CONFIG_PATH), { recursive: true });
1620
+ const tmp = `${CONFIG_PATH}.${process.pid}.tmp`;
1621
+ writeFileSync2(tmp, `${JSON.stringify(next, null, 2)}
1622
+ `, { mode: 384 });
1623
+ chmodSync(tmp, 384);
1624
+ renameSync(tmp, CONFIG_PATH);
1625
+ }
1626
+ function saveAccount(name, account, replaces) {
1627
+ const file = readFile();
1628
+ const accounts = { ...file.accounts };
1629
+ if (replaces && replaces !== name) delete accounts[replaces];
1630
+ if (account) accounts[name] = account;
1631
+ else delete accounts[name];
1632
+ let activeAccount = file.activeAccount;
1633
+ if (replaces && activeAccount === replaces) activeAccount = name;
1634
+ if (!account && activeAccount === name) activeAccount = void 0;
1635
+ saveConfig({ accounts, activeAccount });
1636
+ }
1637
+
1638
+ // src/lib/api.ts
1639
+ var accountFlag;
1640
+ function setAccountFlag(name) {
1641
+ accountFlag = name;
1642
+ }
1643
+ function accountsInScope() {
1644
+ try {
1645
+ return effectiveAccounts(accountFlag);
1646
+ } catch (err) {
1647
+ const message = err.message;
1648
+ fail(
1649
+ message,
1650
+ message.startsWith("No account named") ? "See them with `ft account list`; `ft account clear` unpins." : void 0
1651
+ );
1652
+ }
1653
+ }
1654
+ function resolveAccount() {
1655
+ const accounts = accountsInScope();
1656
+ if (accounts.length === 0) {
1657
+ fail(
1658
+ "Not logged in. Run `ft login` to sign in through your browser.",
1659
+ "CI / headless only: set FT_API_KEY (or `ft login --key`) with a backend-issued token."
1660
+ );
1661
+ }
1662
+ if (accounts.length > 1) {
1663
+ fail(
1664
+ `Several accounts are stored (${accounts.map((a) => a.name).join(", ")}) and this command needs exactly one.`,
1665
+ "Pick one with --account <name>, or pin it with `ft account use <name>`."
1666
+ );
1667
+ }
1668
+ return accounts[0];
1669
+ }
1670
+ function configureClient(workspaceOverride, account = resolveAccount()) {
1671
+ const workspaceId = workspaceOverride ?? account.workspaceId;
1672
+ client.setConfig({
1673
+ baseUrl: `${account.apiUrl.replace(/\/$/, "")}/api/v1`,
1674
+ headers: {
1675
+ Authorization: `Bearer ${account.apiKey}`,
1676
+ ...workspaceId ? { "X-Workspace-Id": workspaceId } : {}
1677
+ }
1678
+ });
1679
+ }
1680
+ function configureAdminClient() {
1681
+ const cfg = loadConfig();
1682
+ if (!cfg.adminSession) {
1683
+ fail(
1684
+ "No superadmin session. Export FT_ADMIN_SESSION with a SUPER_ADMIN better-auth session token.",
1685
+ "Log in to the admin panel in your browser and copy the `better-auth.session_token` cookie."
1686
+ );
1687
+ }
1688
+ client2.setConfig({
1689
+ baseUrl: `${cfg.apiUrl.replace(/\/$/, "")}/api/admin`,
1690
+ headers: {
1691
+ Cookie: `better-auth.session_token=${cfg.adminSession}`
1692
+ }
1693
+ });
1694
+ }
1695
+ async function signedDownload(path) {
1696
+ const cfg = client.getConfig();
1697
+ const res = await fetch(`${cfg.baseUrl}${path}`, {
1698
+ redirect: "manual",
1699
+ headers: cfg.headers
1700
+ });
1701
+ const url = res.headers.get("location");
1702
+ if (!url)
1703
+ fail(
1704
+ `The API did not return a signed URL (HTTP ${res.status}).`,
1705
+ res.status === 404 ? "The settlement has no document yet, or it belongs to another workspace." : void 0
1706
+ );
1707
+ return { url, expiresInMinutes: 5 };
1708
+ }
1709
+ function unwrap(res) {
1710
+ if (res.data !== void 0) return res.data;
1711
+ const status = res.response?.status;
1712
+ const err = res.error?.error;
1713
+ if (err) {
1714
+ const lines = [
1715
+ `Error ${status ?? ""} [${err.code ?? "?"}]: ${err.message ?? "unknown failure"}`.trim()
1716
+ ];
1717
+ for (const d of err.details ?? [])
1718
+ lines.push(` \xB7 ${d.path ?? ""}: ${d.message ?? ""}`.trimEnd());
1719
+ fail(lines.join("\n"), hintFor(status));
1720
+ }
1721
+ fail(
1722
+ `The API responded with ${status ?? "an error"} without a readable body.`
1723
+ );
1724
+ }
1725
+ function describeError(res) {
1726
+ const status = res.response?.status;
1727
+ const err = res.error?.error;
1728
+ if (!err) return `HTTP ${status ?? "error"}`;
1729
+ return `${status ?? ""} ${err.code ?? "?"}: ${err.message ?? "unknown failure"}`.trim();
1730
+ }
1731
+ function hintFor(status) {
1732
+ switch (status) {
1733
+ case 401:
1734
+ return "Your session is invalid, revoked, or expired. Run `ft login`.";
1735
+ case 403:
1736
+ return "Your role or workspace does not allow this action.";
1737
+ case 404:
1738
+ return "The resource does not exist or belongs to another workspace.";
1739
+ case 422:
1740
+ return "Validation failed. Fix the fields listed above and retry.";
1741
+ case 429:
1742
+ return "Rate limit reached. Wait and retry with backoff - this one is worth retrying.";
1743
+ case 500:
1744
+ return "Server error. Retry once; if it persists, report it.";
1745
+ case 501:
1746
+ return "The backend has not implemented this operation yet.";
1747
+ case 503:
1748
+ return "The service is temporarily unavailable. Retry with backoff.";
1749
+ }
1750
+ }
1751
+ function fail(message, hint) {
1752
+ console.error(message);
1753
+ if (hint) console.error(`
1754
+ ${hint}`);
1755
+ process.exit(1);
1756
+ }
1757
+ function expandTargets(perAccount, workspaceFlag) {
1758
+ const seen = /* @__PURE__ */ new Set();
1759
+ const out = [];
1760
+ for (const { account, workspaces } of perAccount) {
1761
+ const only = workspaceFlag ?? account.workspaceId;
1762
+ for (const w of workspaces) {
1763
+ if (w.sections !== null && w.sections.length === 0) continue;
1764
+ if (only && w.id !== only) continue;
1765
+ if (seen.has(w.id)) continue;
1766
+ seen.add(w.id);
1767
+ out.push({ id: w.id, name: w.name, account });
1768
+ }
1769
+ }
1770
+ return out;
1771
+ }
1772
+ async function listTargets(override) {
1773
+ const accounts = accountsInScope();
1774
+ if (accounts.length <= 1) {
1775
+ const account = resolveAccount();
1776
+ if (!override && !account.workspaceId) {
1777
+ configureClient(void 0, account);
1778
+ const res = await getMe({});
1779
+ const targets2 = expandTargets([
1780
+ { account, workspaces: res.data?.data.workspaces ?? [] }
1781
+ ]);
1782
+ if (targets2.length > 1) return targets2;
1783
+ }
1784
+ configureClient(override, account);
1785
+ return null;
1786
+ }
1787
+ const perAccount = [];
1788
+ const errors = [];
1789
+ for (const account of accounts) {
1790
+ configureClient(void 0, account);
1791
+ const res = await getMe({});
1792
+ if (!res.data) {
1793
+ errors.push(`account ${account.name}: ${describeError(res)}`);
1794
+ continue;
1795
+ }
1796
+ perAccount.push({ account, workspaces: res.data.data.workspaces });
1797
+ }
1798
+ failIfNoneAnswered(perAccount.length, errors);
1799
+ const targets = expandTargets(perAccount, override);
1800
+ if (override && targets.length === 0) {
1801
+ fail(
1802
+ `No stored account reaches workspace ${override}.`,
1803
+ "See what each one reaches with `ft workspace list`."
1804
+ );
1805
+ }
1806
+ const [only] = targets;
1807
+ if (only && targets.length === 1) {
1808
+ configureClient(only.id, only.account);
1809
+ return null;
1810
+ }
1811
+ return targets;
1812
+ }
1813
+ function failIfNoneAnswered(answered, errors) {
1814
+ if (answered === 0 && errors.length > 0)
1815
+ fail(
1816
+ `No account could be read:
1817
+ ${errors.map((e) => ` \xB7 ${e}`).join("\n")}`,
1818
+ "Run `ft login` again for the expired ones, or remove them with `ft account remove <name>`."
1819
+ );
1820
+ for (const e of errors) console.error(`(${e})`);
1821
+ }
1822
+ function spansAccounts(targets) {
1823
+ return new Set(targets.map((t) => t.account.name)).size > 1;
1824
+ }
1825
+ function tagRow(ws, row, withAccount) {
1826
+ return {
1827
+ ...withAccount ? { account: ws.account.name } : {},
1828
+ workspaceId: ws.id,
1829
+ workspaceName: ws.name,
1830
+ ...row
1831
+ };
1832
+ }
1833
+ function splitLimit(limit, targets) {
1834
+ if (!Number.isFinite(limit) || limit <= 0 || targets <= 1) return limit;
1835
+ return Math.max(1, Math.ceil(limit / targets));
1836
+ }
1837
+
1838
+ // src/lib/output.ts
1839
+ import chalk2 from "chalk";
1840
+ import Table from "cli-table3";
1841
+ function print(data, opts = {}) {
1842
+ if (opts.json) {
1843
+ const out = opts.columnsExplicit && opts.columns && Array.isArray(data) ? data.map(
1844
+ (row) => pick(row, opts.columns)
1845
+ ) : data;
1846
+ process.stdout.write(`${JSON.stringify(out, null, 2)}
1847
+ `);
1848
+ return;
1849
+ }
1850
+ if (Array.isArray(data) && data.every(isPlainRow)) {
1851
+ if (data.length === 0) {
1852
+ console.log(chalk2.dim("(no results)"));
1853
+ return;
1854
+ }
1855
+ const cols = opts.columns ?? Object.keys(data[0]);
1856
+ const table = new Table({ head: cols.map((c2) => chalk2.hex("#07C2BA")(c2)) });
1857
+ for (const row of data) {
1858
+ table.push(cols.map((c2) => fmt(row[c2])));
1859
+ }
1860
+ console.log(table.toString());
1861
+ return;
1862
+ }
1863
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
1864
+ `);
1865
+ }
1866
+ function csvEsc(v) {
1867
+ if (v === null || v === void 0) return "";
1868
+ const s = typeof v === "object" ? JSON.stringify(v) : String(v);
1869
+ return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
1870
+ }
1871
+ function toCsv(rows, columns) {
1872
+ if (!Array.isArray(rows) || rows.length === 0) {
1873
+ return columns?.length ? columns.map(csvEsc).join(",") : "";
1874
+ }
1875
+ const cols = columns ?? Object.keys(rows[0]);
1876
+ const head = cols.map(csvEsc).join(",");
1877
+ const body = rows.map(
1878
+ (r) => cols.map((c2) => csvEsc(r[c2])).join(",")
1879
+ );
1880
+ return [head, ...body].join("\n");
1881
+ }
1882
+ function resolveColumns(opts, fallback) {
1883
+ if (opts.full) return void 0;
1884
+ if (opts.columns) {
1885
+ return opts.columns.split(",").map((c2) => c2.trim()).filter(Boolean);
1886
+ }
1887
+ return fallback;
1888
+ }
1889
+ function printNextCursor(page) {
1890
+ if (page?.nextCursor) {
1891
+ console.error(chalk2.dim(`
1892
+ More results: --cursor ${page.nextCursor}`));
1893
+ }
1894
+ }
1895
+ function isPlainRow(v) {
1896
+ return v !== null && typeof v === "object" && !Array.isArray(v);
1897
+ }
1898
+ function fmt(v) {
1899
+ if (v === null || v === void 0) return chalk2.dim("\u2014");
1900
+ if (typeof v === "object") return JSON.stringify(v);
1901
+ return String(v);
1902
+ }
1903
+ function pick(row, columns) {
1904
+ const out = {};
1905
+ for (const c2 of columns) if (c2 in row) out[c2] = row[c2];
1906
+ return out;
1907
+ }
1908
+ function printEmptyScope(workspaceFlag) {
1909
+ const workspaceId = workspaceFlag ?? loadConfig().workspaceId;
1910
+ console.error(
1911
+ chalk2.dim(
1912
+ 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>)"
1913
+ )
1914
+ );
1915
+ }
1916
+
1917
+ // src/commands/auth.ts
1918
+ import { spawn } from "child_process";
1919
+ import chalk3 from "chalk";
1920
+ function registerAuth(program2) {
1921
+ program2.command("login").description(
1922
+ "Log in via the browser (device flow) and add the account to ~/.freeticket/config.json"
1923
+ ).option(
1924
+ "--account <name>",
1925
+ "store this login under <name> (default: the account's email); an existing one with that name is replaced"
1926
+ ).option(
1927
+ "--key <ft_live_\u2026>",
1928
+ "Skip the browser and use an API key issued in the backend (CI / automation)"
1929
+ ).option(
1930
+ "--url <url>",
1931
+ "API base URL (default: https://admin.appfreeticket.com)"
1932
+ ).option(
1933
+ "--workspace <id>",
1934
+ "pin this login to one workspace (default: every workspace the account reaches)"
1935
+ ).option("--json", "raw JSON output (confirmation goes to stderr)").action(async (opts) => {
1936
+ const apiUrl = opts.url ?? process.env.FT_API_URL ?? readConfig().apiUrl ?? DEFAULT_API_URL;
1937
+ const apiKey = opts.key ?? await deviceLogin(apiUrl);
1938
+ const workspaceId = opts.workspace;
1939
+ configureClient(workspaceId, {
1940
+ name: opts.account ?? LEGACY_ACCOUNT,
1941
+ apiUrl,
1942
+ apiKey,
1943
+ workspaceId
1944
+ });
1945
+ const me = unwrap(await getMe({})).data;
1946
+ const { name, replaces } = loginTarget(
1947
+ readConfig(),
1948
+ me.email,
1949
+ opts.account
1950
+ );
1951
+ saveAccount(
1952
+ name,
1953
+ {
1954
+ apiKey,
1955
+ ...me.email ? { email: me.email } : {},
1956
+ ...opts.url ? { apiUrl: opts.url } : {},
1957
+ ...workspaceId ? { workspaceId } : {}
1958
+ },
1959
+ replaces
1960
+ );
1961
+ console.error(
1962
+ `${chalk3.green("\u2713")} Account ${chalk3.bold(name)} saved in ${chalk3.dim(CONFIG_PATH)}`
1963
+ );
1964
+ const { activeAccount, accounts } = readConfig();
1965
+ if (activeAccount && activeAccount !== name) {
1966
+ console.error(
1967
+ chalk3.dim(
1968
+ `(account ${activeAccount} is pinned: \`ft account clear\` reads all of them, \`ft account use ${name}\` switches)`
1969
+ )
1970
+ );
1971
+ } else if (Object.keys(accounts ?? {}).length > 1) {
1972
+ console.error(
1973
+ chalk3.dim(
1974
+ "(lists now read every stored account; narrow with --account or `ft account use`)"
1975
+ )
1976
+ );
1977
+ }
1978
+ print(me, { json: opts.json });
1979
+ });
1980
+ program2.command("signup").description(
1981
+ "Create a FreeTicket account (sends a verification email; then run `ft login`)"
1982
+ ).requiredOption("--email <email>", "account email").requiredOption("--name <name>", "your name").option(
1983
+ "--workspace-name <name>",
1984
+ "also create your first workspace (free Spark plan)"
1985
+ ).option(
1986
+ "--url <url>",
1987
+ "API base URL (default: https://admin.appfreeticket.com)"
1988
+ ).option("--json", "raw JSON output").action(async (opts) => {
1989
+ const apiUrl = (opts.url ?? process.env.FT_API_URL ?? readConfig().apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "");
1990
+ client.setConfig({ baseUrl: `${apiUrl}/api/v1` });
1991
+ const body = unwrap(
1992
+ await postAuthSignup({
1993
+ body: {
1994
+ email: opts.email,
1995
+ name: opts.name,
1996
+ ...opts.workspaceName ? { workspaceName: opts.workspaceName } : {}
1997
+ }
1998
+ })
1999
+ );
2000
+ console.error(
2001
+ `${chalk3.green("\u2713")} Check ${chalk3.bold(opts.email)} to verify the account and set a password, then run ${chalk3.cyan("ft login")}.`
2002
+ );
2003
+ print(body, { json: opts.json });
2004
+ });
2005
+ program2.command("whoami").description(
2006
+ "Show the authenticated user and workspaces (GET /me), for every account in scope"
2007
+ ).option("--account <name>", "only this account (default: all stored)").option("--json", "raw JSON output").action(async (opts) => {
2008
+ const accounts = accountsInScope();
2009
+ if (accounts.length <= 1) {
2010
+ configureClient();
2011
+ const me = unwrap(await getMe({})).data;
2012
+ print(me, { json: opts.json });
2013
+ return;
2014
+ }
2015
+ const all = [];
2016
+ const errors = [];
2017
+ for (const account of accounts) {
2018
+ configureClient(void 0, account);
2019
+ const res = await getMe({});
2020
+ if (!res.data) {
2021
+ errors.push(`account ${account.name}: ${describeError(res)}`);
2022
+ continue;
2023
+ }
2024
+ all.push({ account: account.name, ...res.data.data });
2025
+ }
2026
+ failIfNoneAnswered(all.length, errors);
2027
+ if (opts.json) {
2028
+ print(all, { json: true });
2029
+ return;
2030
+ }
2031
+ print(
2032
+ all.map((m) => ({
2033
+ account: m.account,
2034
+ email: m.email,
2035
+ name: m.name,
2036
+ workspaces: m.workspaces.map((w) => w.slug).join(", ")
2037
+ }))
2038
+ );
2039
+ });
2040
+ program2.command("logout").description(
2041
+ "Remove a stored account (the pinned one, or the only one; --account / --all otherwise)"
2042
+ ).option("--account <name>", "remove this account").option("--all", "remove every stored account").action((opts) => {
2043
+ const { accounts = {}, activeAccount } = readConfig();
2044
+ const names = Object.keys(accounts);
2045
+ if (opts.all) {
2046
+ saveConfig({ accounts: {}, activeAccount: void 0 });
2047
+ console.log(
2048
+ `${chalk3.green("\u2713")} Logged out of every account \u2014 sessions removed from ${chalk3.dim(CONFIG_PATH)}`
2049
+ );
2050
+ return;
2051
+ }
2052
+ const name = opts.account ?? activeAccount ?? (names.length === 1 ? names[0] : void 0);
2053
+ if (names.length === 0) {
2054
+ console.log(
2055
+ `${chalk3.green("\u2713")} No stored session \u2014 nothing to remove.`
2056
+ );
2057
+ return;
2058
+ }
2059
+ if (!name) {
2060
+ fail(
2061
+ `Several accounts are stored (${names.join(", ")}): say which one to log out of.`,
2062
+ "Use `ft logout --account <name>`, or `ft logout --all`."
2063
+ );
2064
+ }
2065
+ if (!accounts[name]) {
2066
+ fail(`No account named "${name}".`, `Stored: ${names.join(", ")}`);
2067
+ }
2068
+ saveAccount(name, void 0);
2069
+ console.log(
2070
+ `${chalk3.green("\u2713")} Logged out of ${chalk3.bold(name)} \u2014 session removed from ${chalk3.dim(CONFIG_PATH)}`
2071
+ );
2072
+ });
2073
+ program2.command("config").description("Show active configuration (credentials are masked)").option("--json", "raw JSON output").action((opts) => {
2074
+ const file = readConfig();
2075
+ const cfg = loadConfig();
2076
+ print(
2077
+ {
2078
+ apiUrl: cfg.apiUrl,
2079
+ // FT_API_KEY overrides every stored account (CI).
2080
+ env: process.env.FT_API_KEY ? mask(process.env.FT_API_KEY) : null,
2081
+ activeAccount: file.activeAccount ?? null,
2082
+ accounts: Object.entries(file.accounts ?? {}).map(([name, a]) => ({
2083
+ name,
2084
+ apiUrl: a.apiUrl ?? null,
2085
+ // Same field whether it's a device-flow session or a CI API key.
2086
+ session: mask(a.apiKey),
2087
+ workspaceId: a.workspaceId ?? null
2088
+ }))
2089
+ },
2090
+ { json: opts.json }
2091
+ );
2092
+ });
2093
+ }
2094
+ function mask(secret) {
2095
+ return `${secret.slice(0, 12)}\u2026`;
2096
+ }
2097
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2098
+ function openBrowser(url) {
2099
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
2100
+ try {
2101
+ spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
2102
+ } catch {
2103
+ }
2104
+ }
2105
+ async function deviceLogin(baseUrl) {
2106
+ const apiUrl = baseUrl.replace(/\/$/, "");
2107
+ client.setConfig({ baseUrl: `${apiUrl}/api/v1` });
2108
+ const start = unwrap(await postAuthDeviceCode({}));
2109
+ console.log(
2110
+ `
2111
+ Open ${chalk3.cyan(start.verification_uri)} and enter the code:
2112
+
2113
+ ${chalk3.bold(start.user_code)}
2114
+
2115
+ ${chalk3.dim("Opening your browser\u2026 (Ctrl+C to cancel)")}
2116
+ `
2117
+ );
2118
+ openBrowser(start.verification_uri_complete);
2119
+ const deadline = Date.now() + start.expires_in * 1e3;
2120
+ let interval = start.interval;
2121
+ while (Date.now() < deadline) {
2122
+ await sleep(interval * 1e3);
2123
+ const res = await postAuthDeviceToken({
2124
+ body: {
2125
+ device_code: start.device_code,
2126
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
2127
+ }
2128
+ });
2129
+ if (res.data) {
2130
+ const { access_token, workspaces } = res.data;
2131
+ if (workspaces.length > 1) {
2132
+ console.log(
2133
+ `
2134
+ ${chalk3.dim("Workspaces:")} ${workspaces.map((w) => w.slug).join(", ")} ${chalk3.dim("(all of them; narrow with --workspace or `ft workspace use`)")}`
2135
+ );
2136
+ }
2137
+ return access_token;
2138
+ }
2139
+ switch (res.error?.error) {
2140
+ case "authorization_pending":
2141
+ break;
2142
+ // keep polling at the same cadence
2143
+ case "slow_down":
2144
+ interval += 5;
2145
+ break;
2146
+ case "access_denied":
2147
+ fail("Login was denied in the browser.");
2148
+ break;
2149
+ case "expired_token":
2150
+ fail("The code expired before approval. Run `ft login` again.");
2151
+ break;
2152
+ default:
2153
+ fail(`Device login failed: ${res.error?.error ?? "unknown error"}.`);
2154
+ }
2155
+ }
2156
+ return fail("The code expired before approval. Run `ft login` again.");
2157
+ }
2158
+
2159
+ // src/commands/account.ts
2160
+ function registerAccount(program2) {
2161
+ const root = program2.command("account").alias("accounts").description("List, pin, unpin and remove stored accounts");
2162
+ root.command("list").alias("ls").description("List stored accounts (marks the pinned one)").option("--json", "raw JSON output").action((opts) => {
2163
+ const { accounts = {}, activeAccount, apiUrl } = readConfig();
2164
+ const rows = Object.entries(accounts).map(([name, a]) => ({
2165
+ active: name === activeAccount ? "*" : "",
2166
+ name,
2167
+ apiUrl: a.apiUrl ?? apiUrl ?? DEFAULT_API_URL,
2168
+ workspaceId: a.workspaceId ?? "",
2169
+ session: mask(a.apiKey)
2170
+ }));
2171
+ print(rows, {
2172
+ json: opts.json,
2173
+ columns: ["active", "name", "apiUrl", "workspaceId", "session"]
2174
+ });
2175
+ if (rows.length === 0)
2176
+ console.error(chalk4.dim("(no accounts: add one with `ft login`)"));
2177
+ else if (process.env.FT_API_KEY)
2178
+ console.error(
2179
+ chalk4.dim("(FT_API_KEY is set: it overrides every stored account)")
2180
+ );
2181
+ });
2182
+ root.command("use <name>").description(
2183
+ "Pin every command to one account (persisted in ~/.freeticket/config.json)"
2184
+ ).action((name) => {
2185
+ const names = Object.keys(readConfig().accounts ?? {});
2186
+ if (!names.includes(name)) {
2187
+ fail(
2188
+ `No account named "${name}".`,
2189
+ `Stored: ${names.join(", ") || "(none) - add one with `ft login`"}`
2190
+ );
2191
+ }
2192
+ saveConfig({ activeAccount: name });
2193
+ console.log(`${chalk4.green("\u2713")} Active account: ${chalk4.bold(name)}`);
2194
+ });
2195
+ root.command("clear").description("Unpin: go back to reading every stored account").action(() => {
2196
+ saveConfig({ activeAccount: void 0 });
2197
+ console.log(
2198
+ `${chalk4.green("\u2713")} No account pinned: lists now read all of them.`
2199
+ );
2200
+ });
2201
+ root.command("remove <name>").alias("rm").description("Remove a stored account (same as `ft logout --account`)").action((name) => {
2202
+ const names = Object.keys(readConfig().accounts ?? {});
2203
+ if (!names.includes(name)) {
2204
+ fail(`No account named "${name}".`, `Stored: ${names.join(", ")}`);
2205
+ }
2206
+ saveAccount(name, void 0);
2207
+ console.log(
2208
+ `${chalk4.green("\u2713")} Removed ${chalk4.bold(name)} from ${chalk4.dim(CONFIG_PATH)}`
2209
+ );
2210
+ });
2211
+ }
2212
+
2213
+ // src/commands/admin.ts
2214
+ import chalk5 from "chalk";
2215
+
2216
+ // src/admin-client/sdk.gen.ts
2217
+ var getMe2 = (options) => {
2218
+ return (options?.client ?? client2).get({
2219
+ security: [
2220
+ {
2221
+ in: "cookie",
2222
+ name: "better-auth.session_token",
2223
+ type: "apiKey"
2224
+ }
2225
+ ],
2226
+ url: "/me",
2227
+ ...options
2228
+ });
2229
+ };
2230
+ var getWorkspaces = (options) => {
2231
+ return (options?.client ?? client2).get({
2232
+ security: [
2233
+ {
2234
+ in: "cookie",
2235
+ name: "better-auth.session_token",
2236
+ type: "apiKey"
2237
+ }
2238
+ ],
2239
+ url: "/workspaces",
2240
+ ...options
2241
+ });
2242
+ };
2243
+ var postWorkspaces2 = (options) => {
2244
+ return (options.client ?? client2).post({
2245
+ security: [
2246
+ {
2247
+ in: "cookie",
2248
+ name: "better-auth.session_token",
2249
+ type: "apiKey"
2250
+ }
2251
+ ],
2252
+ url: "/workspaces",
2253
+ ...options,
2254
+ headers: {
2255
+ "Content-Type": "application/json",
2256
+ ...options?.headers
2257
+ }
2258
+ });
2259
+ };
2260
+ var deleteWorkspacesId = (options) => {
2261
+ return (options.client ?? client2).delete({
2262
+ security: [
2263
+ {
2264
+ in: "cookie",
2265
+ name: "better-auth.session_token",
2266
+ type: "apiKey"
2267
+ }
2268
+ ],
2269
+ url: "/workspaces/{id}",
2270
+ ...options
2271
+ });
2272
+ };
2273
+ var getWorkspacesId = (options) => {
2274
+ return (options.client ?? client2).get({
2275
+ security: [
2276
+ {
2277
+ in: "cookie",
2278
+ name: "better-auth.session_token",
2279
+ type: "apiKey"
2280
+ }
2281
+ ],
1210
2282
  url: "/workspaces/{id}",
1211
2283
  ...options
1212
2284
  });
@@ -1228,6 +2300,19 @@ var patchWorkspacesId = (options) => {
1228
2300
  }
1229
2301
  });
1230
2302
  };
2303
+ var getWorkspacesIdPlan = (options) => {
2304
+ return (options.client ?? client2).get({
2305
+ security: [
2306
+ {
2307
+ in: "cookie",
2308
+ name: "better-auth.session_token",
2309
+ type: "apiKey"
2310
+ }
2311
+ ],
2312
+ url: "/workspaces/{id}/plan",
2313
+ ...options
2314
+ });
2315
+ };
1231
2316
  var postWorkspacesIdPlan = (options) => {
1232
2317
  return (options.client ?? client2).post({
1233
2318
  security: [
@@ -1491,123 +2576,8 @@ var deleteTokensId = (options) => {
1491
2576
  });
1492
2577
  };
1493
2578
 
1494
- // src/lib/config.ts
1495
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
1496
- import { homedir } from "os";
1497
- import { dirname, join } from "path";
1498
- var CONFIG_DIR = join(homedir(), ".freeticket");
1499
- var CONFIG_PATH = join(CONFIG_DIR, "config.json");
1500
- var DEFAULT_API_URL = "https://admin.appfreeticket.com";
1501
- function readFile() {
1502
- if (!existsSync(CONFIG_PATH)) return {};
1503
- try {
1504
- return JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
1505
- } catch {
1506
- return {};
1507
- }
1508
- }
1509
- function loadConfig() {
1510
- const file = readFile();
1511
- return {
1512
- apiUrl: process.env.FT_API_URL ?? file.apiUrl ?? DEFAULT_API_URL,
1513
- apiKey: process.env.FT_API_KEY ?? file.apiKey,
1514
- workspaceId: process.env.FT_WORKSPACE_ID ?? file.workspaceId,
1515
- adminSession: process.env.FT_ADMIN_SESSION ?? file.adminSession
1516
- };
1517
- }
1518
- function saveConfig(patch) {
1519
- const next = { ...readFile(), ...patch };
1520
- mkdirSync(dirname(CONFIG_PATH), { recursive: true });
1521
- writeFileSync(CONFIG_PATH, `${JSON.stringify(next, null, 2)}
1522
- `, {
1523
- mode: 384
1524
- });
1525
- }
1526
-
1527
- // src/lib/api.ts
1528
- function configureClient(workspaceOverride) {
1529
- const cfg = loadConfig();
1530
- if (!cfg.apiKey) {
1531
- fail(
1532
- "Not logged in. Run `ft login` to sign in through your browser.",
1533
- "CI / headless only: set FT_API_KEY (or `ft login --key`) with a backend-issued token."
1534
- );
1535
- }
1536
- const workspaceId = workspaceOverride ?? cfg.workspaceId;
1537
- client.setConfig({
1538
- baseUrl: `${cfg.apiUrl.replace(/\/$/, "")}/api/v1`,
1539
- headers: {
1540
- Authorization: `Bearer ${cfg.apiKey}`,
1541
- ...workspaceId ? { "X-Workspace-Id": workspaceId } : {}
1542
- }
1543
- });
1544
- }
1545
- function configureAdminClient() {
1546
- const cfg = loadConfig();
1547
- if (!cfg.adminSession) {
1548
- fail(
1549
- "No superadmin session. Export FT_ADMIN_SESSION with a SUPER_ADMIN better-auth session token.",
1550
- "Log in to the admin panel in your browser and copy the `better-auth.session_token` cookie."
1551
- );
1552
- }
1553
- client2.setConfig({
1554
- baseUrl: `${cfg.apiUrl.replace(/\/$/, "")}/api/admin`,
1555
- headers: {
1556
- Cookie: `better-auth.session_token=${cfg.adminSession}`
1557
- }
1558
- });
1559
- }
1560
- async function signedDownload(path) {
1561
- const cfg = client.getConfig();
1562
- const res = await fetch(`${cfg.baseUrl}${path}`, {
1563
- redirect: "manual",
1564
- headers: cfg.headers
1565
- });
1566
- const url = res.headers.get("location");
1567
- if (!url)
1568
- fail(
1569
- `The API did not return a signed URL (HTTP ${res.status}).`,
1570
- res.status === 404 ? "The settlement has no document yet, or it belongs to another workspace." : void 0
1571
- );
1572
- return { url, expiresInMinutes: 5 };
1573
- }
1574
- function unwrap(res) {
1575
- if (res.data !== void 0) return res.data;
1576
- const status = res.response?.status;
1577
- const err = res.error?.error;
1578
- if (err) {
1579
- const lines = [
1580
- `Error ${status ?? ""} [${err.code ?? "?"}]: ${err.message ?? "unknown failure"}`.trim()
1581
- ];
1582
- for (const d of err.details ?? [])
1583
- lines.push(` \xB7 ${d.path ?? ""}: ${d.message ?? ""}`.trimEnd());
1584
- fail(lines.join("\n"), hintFor(status));
1585
- }
1586
- fail(
1587
- `The API responded with ${status ?? "an error"} without a readable body.`
1588
- );
1589
- }
1590
- function hintFor(status) {
1591
- switch (status) {
1592
- case 401:
1593
- return "Your session is invalid, revoked, or expired. Run `ft login`.";
1594
- case 403:
1595
- return "Your role or workspace does not allow this action.";
1596
- case 404:
1597
- return "The resource does not exist or belongs to another workspace.";
1598
- case 501:
1599
- return "The backend has not implemented this operation yet.";
1600
- }
1601
- }
1602
- function fail(message, hint) {
1603
- console.error(message);
1604
- if (hint) console.error(`
1605
- ${hint}`);
1606
- process.exit(1);
1607
- }
1608
-
1609
2579
  // src/lib/input.ts
1610
- import { readFileSync as readFileSync2 } from "fs";
2580
+ import { readFileSync as readFileSync3 } from "fs";
1611
2581
  import * as readline from "readline";
1612
2582
  function parseData(input) {
1613
2583
  if (!input) {
@@ -1619,7 +2589,7 @@ function parseData(input) {
1619
2589
  let raw = input;
1620
2590
  if (raw.startsWith("@")) {
1621
2591
  try {
1622
- raw = readFileSync2(raw.slice(1), "utf8");
2592
+ raw = readFileSync3(raw.slice(1), "utf8");
1623
2593
  } catch {
1624
2594
  fail(`Cannot read file: ${raw.slice(1)}`);
1625
2595
  }
@@ -1654,84 +2624,6 @@ function confirm(question) {
1654
2624
  });
1655
2625
  }
1656
2626
 
1657
- // src/lib/output.ts
1658
- import chalk from "chalk";
1659
- import Table from "cli-table3";
1660
- function print(data, opts = {}) {
1661
- if (opts.json) {
1662
- const out = opts.columnsExplicit && opts.columns && Array.isArray(data) ? data.map(
1663
- (row) => pick(row, opts.columns)
1664
- ) : data;
1665
- process.stdout.write(`${JSON.stringify(out, null, 2)}
1666
- `);
1667
- return;
1668
- }
1669
- if (Array.isArray(data) && data.every(isPlainRow)) {
1670
- if (data.length === 0) {
1671
- console.log(chalk.dim("(no results)"));
1672
- return;
1673
- }
1674
- const cols = opts.columns ?? Object.keys(data[0]);
1675
- const table = new Table({ head: cols.map((c2) => chalk.hex("#07C2BA")(c2)) });
1676
- for (const row of data) {
1677
- table.push(cols.map((c2) => fmt(row[c2])));
1678
- }
1679
- console.log(table.toString());
1680
- return;
1681
- }
1682
- process.stdout.write(`${JSON.stringify(data, null, 2)}
1683
- `);
1684
- }
1685
- function csvEsc(v) {
1686
- if (v === null || v === void 0) return "";
1687
- const s = typeof v === "object" ? JSON.stringify(v) : String(v);
1688
- return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
1689
- }
1690
- function toCsv(rows, columns) {
1691
- if (!Array.isArray(rows) || rows.length === 0) {
1692
- return columns?.length ? columns.map(csvEsc).join(",") : "";
1693
- }
1694
- const cols = columns ?? Object.keys(rows[0]);
1695
- const head = cols.map(csvEsc).join(",");
1696
- const body = rows.map(
1697
- (r) => cols.map((c2) => csvEsc(r[c2])).join(",")
1698
- );
1699
- return [head, ...body].join("\n");
1700
- }
1701
- function resolveColumns(opts, fallback) {
1702
- if (opts.full) return void 0;
1703
- if (opts.columns) {
1704
- return opts.columns.split(",").map((c2) => c2.trim()).filter(Boolean);
1705
- }
1706
- return fallback;
1707
- }
1708
- function printNextCursor(page) {
1709
- if (page?.nextCursor) {
1710
- console.error(chalk.dim(`
1711
- More results: --cursor ${page.nextCursor}`));
1712
- }
1713
- }
1714
- function isPlainRow(v) {
1715
- return v !== null && typeof v === "object" && !Array.isArray(v);
1716
- }
1717
- function fmt(v) {
1718
- if (v === null || v === void 0) return chalk.dim("\u2014");
1719
- if (typeof v === "object") return JSON.stringify(v);
1720
- return String(v);
1721
- }
1722
- function pick(row, columns) {
1723
- const out = {};
1724
- for (const c2 of columns) if (c2 in row) out[c2] = row[c2];
1725
- return out;
1726
- }
1727
- function printEmptyScope(workspaceId) {
1728
- console.error(
1729
- chalk.dim(
1730
- workspaceId ? `(0 results in workspace ${workspaceId})` : "(0 results in the session's active workspace - check it with `ft whoami`, or scope with --workspace <id>)"
1731
- )
1732
- );
1733
- }
1734
-
1735
2627
  // src/commands/admin.ts
1736
2628
  function registerAdmin(program2) {
1737
2629
  const admin = program2.command("admin").description("Superadmin (cross-tenant) \u2014 SUPER_ADMIN session required");
@@ -1749,14 +2641,14 @@ function registerAdmin(program2) {
1749
2641
  configureAdminClient();
1750
2642
  const me = unwrap(await getMe2({})).data;
1751
2643
  console.log(
1752
- `${chalk2.green("\u2713")} Admin session saved in ${chalk2.dim(CONFIG_PATH)}`
2644
+ `${chalk5.green("\u2713")} Admin session saved in ${chalk5.dim(CONFIG_PATH)}`
1753
2645
  );
1754
2646
  print(me, {});
1755
2647
  });
1756
2648
  admin.command("logout").description("Remove the stored superadmin session").action(() => {
1757
2649
  saveConfig({ adminSession: void 0 });
1758
2650
  console.log(
1759
- `${chalk2.green("\u2713")} Admin session removed from ${chalk2.dim(CONFIG_PATH)}`
2651
+ `${chalk5.green("\u2713")} Admin session removed from ${chalk5.dim(CONFIG_PATH)}`
1760
2652
  );
1761
2653
  });
1762
2654
  admin.command("config").description("Show admin configuration (the session is masked)").action(() => {
@@ -1774,11 +2666,14 @@ function registerAdmin(program2) {
1774
2666
  const body = unwrap(await getMe2({}));
1775
2667
  print(body.data, { json: opts.json });
1776
2668
  });
1777
- 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) => {
2669
+ 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) => {
1778
2670
  configureAdminClient();
1779
- const body = unwrap(
1780
- await postImpersonate({ body: parseData(opts.data) })
2671
+ const payload = parseData(opts.data);
2672
+ await confirmOrExit(
2673
+ `Impersonate user ${payload.targetUserId ?? "(no targetUserId in --data)"}?`,
2674
+ opts.yes
1781
2675
  );
2676
+ const body = unwrap(await postImpersonate({ body: payload }));
1782
2677
  print(body?.data ?? body, { json: opts.json });
1783
2678
  });
1784
2679
  admin.command("impersonate-stop").description("Stop the current impersonation").option("--json", "raw JSON output").action(async (opts) => {
@@ -1792,7 +2687,7 @@ function registerAdmin(program2) {
1792
2687
  describe: "Tenants / workspaces",
1793
2688
  list: getWorkspaces,
1794
2689
  get: getWorkspacesId,
1795
- create: postWorkspaces,
2690
+ create: postWorkspaces2,
1796
2691
  update: patchWorkspacesId,
1797
2692
  actions: [
1798
2693
  {
@@ -1815,6 +2710,23 @@ function registerAdmin(program2) {
1815
2710
  fn: postWorkspacesIdPlan,
1816
2711
  body: true,
1817
2712
  confirm: true
2713
+ },
2714
+ {
2715
+ // `plan <id>` is the POST that assigns one, so the read gets its own
2716
+ // verb. `stripeLinked: true` means `plan` will cancel that Stripe
2717
+ // subscription first.
2718
+ name: "plan-show",
2719
+ describe: "Current plan and subscription of a workspace",
2720
+ fn: getWorkspacesIdPlan
2721
+ },
2722
+ {
2723
+ // Soft delete: sets deletedAt, keeps sales/buyers/tickets. The
2724
+ // backend requires the workspace to be suspended first and to have no
2725
+ // CONFIRMED sale (409 otherwise). Does not cancel Stripe.
2726
+ name: "delete",
2727
+ describe: "Soft-delete a workspace (must be suspended first, no confirmed sales)",
2728
+ fn: deleteWorkspacesId,
2729
+ confirm: true
1818
2730
  }
1819
2731
  ],
1820
2732
  columns: ["id", "name", "type", "country", "suspended", "createdAt"],
@@ -1909,8 +2821,12 @@ function registerAdminResource(parent, spec) {
1909
2821
  cmd.option("--limit <n>", "results per page (1-100)", "20").option("--cursor <id>", "pagination cursor");
1910
2822
  }
1911
2823
  for (const f of spec.listFlags ?? []) cmd.option(f.flag, f.describe);
2824
+ cmd.option("--columns <list>", "comma-separated columns to display");
2825
+ cmd.option("--full", "show every field instead of the curated columns");
2826
+ cmd.option("--all", "auto-paginate: fetch every page (ignores --cursor)");
1912
2827
  cmd.option("--csv", "CSV output");
1913
2828
  cmd.option("--json", "raw JSON output");
2829
+ cmd.option("--raw", "raw JSON output including pagination metadata (page)");
1914
2830
  cmd.action(async (opts) => {
1915
2831
  configureAdminClient();
1916
2832
  const query = {};
@@ -1922,13 +2838,44 @@ function registerAdminResource(parent, spec) {
1922
2838
  const v = opts[camel(f.query)];
1923
2839
  if (v !== void 0) query[f.query] = v;
1924
2840
  }
2841
+ const columns = resolveColumns(opts, spec.columns);
2842
+ if (opts.all && !spec.noPaging) {
2843
+ const rows = [];
2844
+ let cursor;
2845
+ let page;
2846
+ do {
2847
+ const body2 = unwrap(await list({ query: { ...query, cursor } }));
2848
+ rows.push(...body2.data ?? []);
2849
+ page = body2.page;
2850
+ cursor = page?.nextCursor ?? void 0;
2851
+ } while (page?.hasMore && cursor);
2852
+ if (opts.csv) {
2853
+ process.stdout.write(`${toCsv(rows, columns)}
2854
+ `);
2855
+ return;
2856
+ }
2857
+ print(rows, {
2858
+ json: opts.json,
2859
+ columns,
2860
+ columnsExplicit: Boolean(opts.columns)
2861
+ });
2862
+ return;
2863
+ }
1925
2864
  const body = unwrap(await list({ query }));
2865
+ if (opts.raw) {
2866
+ print(body, { json: true });
2867
+ return;
2868
+ }
1926
2869
  if (opts.csv) {
1927
- process.stdout.write(`${toCsv(body.data, spec.columns)}
2870
+ process.stdout.write(`${toCsv(body.data, columns)}
1928
2871
  `);
1929
2872
  return;
1930
2873
  }
1931
- print(body.data, { json: opts.json, columns: spec.columns });
2874
+ print(body.data, {
2875
+ json: opts.json,
2876
+ columns,
2877
+ columnsExplicit: Boolean(opts.columns)
2878
+ });
1932
2879
  if (!opts.json && !spec.noPaging) printNextCursor(body.page);
1933
2880
  });
1934
2881
  }
@@ -1949,11 +2896,11 @@ function registerAdminResource(parent, spec) {
1949
2896
  });
1950
2897
  }
1951
2898
  if (spec.update) {
1952
- const update = spec.update;
2899
+ const update2 = spec.update;
1953
2900
  root.command("update <id>").description(`Update a ${singular} by id`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--json", "raw JSON output").action(async (id, opts) => {
1954
2901
  configureAdminClient();
1955
2902
  const body = unwrap(
1956
- await update({ path: { id }, body: parseData(opts.data) })
2903
+ await update2({ path: { id }, body: parseData(opts.data) })
1957
2904
  );
1958
2905
  print(body?.data ?? body, { json: opts.json });
1959
2906
  });
@@ -1981,7 +2928,7 @@ function camel(s) {
1981
2928
  }
1982
2929
 
1983
2930
  // src/commands/api-keys.ts
1984
- import chalk3 from "chalk";
2931
+ import chalk6 from "chalk";
1985
2932
  var COLUMNS = [
1986
2933
  "name",
1987
2934
  "keyPrefix",
@@ -2014,13 +2961,13 @@ function registerApiKeys(program2) {
2014
2961
  }
2015
2962
  console.log(
2016
2963
  `
2017
- ${chalk3.green("\u2713")} API key "${chalk3.bold(key.name)}" created (scope: ${key.scope}).
2964
+ ${chalk6.green("\u2713")} API key "${chalk6.bold(key.name)}" created (scope: ${key.scope}).
2018
2965
  `
2019
2966
  );
2020
2967
  console.log(
2021
- chalk3.yellow(" Copy your secret now \u2014 it will NOT be shown again:\n")
2968
+ chalk6.yellow(" Copy your secret now \u2014 it will NOT be shown again:\n")
2022
2969
  );
2023
- console.log(` ${chalk3.bold.cyan(key.key)}
2970
+ console.log(` ${chalk6.bold.cyan(key.key)}
2024
2971
  `);
2025
2972
  print(
2026
2973
  {
@@ -2058,7 +3005,12 @@ ${chalk3.green("\u2713")} API key "${chalk3.bold(key.name)}" created (scope: ${k
2058
3005
  `);
2059
3006
  return;
2060
3007
  }
2061
- print(rows, { json: opts.json, columns });
3008
+ print(rows, {
3009
+ json: opts.json,
3010
+ columns,
3011
+ columnsExplicit: Boolean(opts.columns)
3012
+ });
3013
+ if (rows.length === 0) printEmptyScope(opts.workspace);
2062
3014
  return;
2063
3015
  }
2064
3016
  const body = unwrap(await getApiKeys({ query }));
@@ -2067,7 +3019,12 @@ ${chalk3.green("\u2713")} API key "${chalk3.bold(key.name)}" created (scope: ${k
2067
3019
  `);
2068
3020
  return;
2069
3021
  }
2070
- print(body.data, { json: opts.json, columns });
3022
+ print(body.data, {
3023
+ json: opts.json,
3024
+ columns,
3025
+ columnsExplicit: Boolean(opts.columns)
3026
+ });
3027
+ if ((body.data ?? []).length === 0) printEmptyScope(opts.workspace);
2071
3028
  if (!opts.json) printNextCursor(body.page);
2072
3029
  });
2073
3030
  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) => {
@@ -2078,120 +3035,6 @@ ${chalk3.green("\u2713")} API key "${chalk3.bold(key.name)}" created (scope: ${k
2078
3035
  });
2079
3036
  }
2080
3037
 
2081
- // src/commands/auth.ts
2082
- import { spawn } from "child_process";
2083
- import chalk4 from "chalk";
2084
- function registerAuth(program2) {
2085
- program2.command("login").description(
2086
- "Log in via the browser (device flow) and store the session in ~/.freeticket/config.json"
2087
- ).option(
2088
- "--key <ft_live_\u2026>",
2089
- "Skip the browser and use an API key issued in the backend (CI / automation)"
2090
- ).option(
2091
- "--url <url>",
2092
- "API base URL (default: https://admin.appfreeticket.com)"
2093
- ).option("--workspace <id>", "default active workspace").option("--json", "raw JSON output (confirmation goes to stderr)").action(async (opts) => {
2094
- if (opts.url) saveConfig({ apiUrl: opts.url });
2095
- const cred = opts.key ? { apiKey: opts.key, workspaceId: void 0 } : await deviceLogin();
2096
- const workspaceId = opts.workspace ?? cred.workspaceId;
2097
- saveConfig({
2098
- apiKey: cred.apiKey,
2099
- ...workspaceId ? { workspaceId } : {}
2100
- });
2101
- configureClient(workspaceId);
2102
- const me = unwrap(await getMe({})).data;
2103
- console.error(
2104
- `${chalk4.green("\u2713")} Session saved in ${chalk4.dim(CONFIG_PATH)}`
2105
- );
2106
- print(me, { json: opts.json });
2107
- });
2108
- program2.command("whoami").description("Show the authenticated user and workspaces (GET /me)").option("--json", "raw JSON output").action(async (opts) => {
2109
- configureClient();
2110
- const me = unwrap(await getMe({})).data;
2111
- print(me, { json: opts.json });
2112
- });
2113
- program2.command("logout").description("Log out and remove the stored session").action(() => {
2114
- saveConfig({ apiKey: void 0 });
2115
- console.log(
2116
- `${chalk4.green("\u2713")} Logged out \u2014 session removed from ${chalk4.dim(CONFIG_PATH)}`
2117
- );
2118
- });
2119
- program2.command("config").description("Show active configuration (the credential is masked)").option("--json", "raw JSON output").action((opts) => {
2120
- const cfg = loadConfig();
2121
- print(
2122
- {
2123
- apiUrl: cfg.apiUrl,
2124
- // Same field whether it's a device-flow session or a CI API key.
2125
- session: cfg.apiKey ? `${cfg.apiKey.slice(0, 12)}\u2026` : null,
2126
- workspaceId: cfg.workspaceId ?? null
2127
- },
2128
- { json: opts.json }
2129
- );
2130
- });
2131
- }
2132
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2133
- function openBrowser(url) {
2134
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
2135
- try {
2136
- spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
2137
- } catch {
2138
- }
2139
- }
2140
- async function deviceLogin() {
2141
- const apiUrl = loadConfig().apiUrl.replace(/\/$/, "");
2142
- client.setConfig({ baseUrl: `${apiUrl}/api/v1` });
2143
- const start = unwrap(await postAuthDeviceCode({}));
2144
- console.log(
2145
- `
2146
- Open ${chalk4.cyan(start.verification_uri)} and enter the code:
2147
-
2148
- ${chalk4.bold(start.user_code)}
2149
-
2150
- ${chalk4.dim("Opening your browser\u2026 (Ctrl+C to cancel)")}
2151
- `
2152
- );
2153
- openBrowser(start.verification_uri_complete);
2154
- const deadline = Date.now() + start.expires_in * 1e3;
2155
- let interval = start.interval;
2156
- while (Date.now() < deadline) {
2157
- await sleep(interval * 1e3);
2158
- const res = await postAuthDeviceToken({
2159
- body: {
2160
- device_code: start.device_code,
2161
- grant_type: "urn:ietf:params:oauth:grant-type:device_code"
2162
- }
2163
- });
2164
- if (res.data) {
2165
- const { access_token, workspaces } = res.data;
2166
- const active = workspaces[0];
2167
- if (workspaces.length > 1 && active) {
2168
- console.log(
2169
- `
2170
- ${chalk4.dim("Workspaces:")} ${workspaces.map((w) => w.slug).join(", ")} ${chalk4.dim(`(using ${active.slug}; switch with --workspace)`)}`
2171
- );
2172
- }
2173
- return { apiKey: access_token, workspaceId: active?.id };
2174
- }
2175
- switch (res.error?.error) {
2176
- case "authorization_pending":
2177
- break;
2178
- // keep polling at the same cadence
2179
- case "slow_down":
2180
- interval += 5;
2181
- break;
2182
- case "access_denied":
2183
- fail("Login was denied in the browser.");
2184
- break;
2185
- case "expired_token":
2186
- fail("The code expired before approval. Run `ft login` again.");
2187
- break;
2188
- default:
2189
- fail(`Device login failed: ${res.error?.error ?? "unknown error"}.`);
2190
- }
2191
- }
2192
- return fail("The code expired before approval. Run `ft login` again.");
2193
- }
2194
-
2195
3038
  // src/commands/event-dates.ts
2196
3039
  function registerEventDates(program2, spec) {
2197
3040
  const root = program2.command("event-dates").description("Event dates (sessions of an event)");
@@ -2232,22 +3075,49 @@ function registerEventDates(program2, spec) {
2232
3075
  }
2233
3076
 
2234
3077
  // src/commands/reports.ts
3078
+ async function reportRows(workspaceFlag, call) {
3079
+ const targets = await listTargets(workspaceFlag);
3080
+ if (!targets) {
3081
+ const res = await call();
3082
+ return unwrap(res).data;
3083
+ }
3084
+ const withAccount = spansAccounts(targets);
3085
+ const rows = [];
3086
+ for (const ws of targets) {
3087
+ configureClient(ws.id, ws.account);
3088
+ const res = await call();
3089
+ if (res.error !== void 0) {
3090
+ const where = withAccount ? `${ws.account.name} / ${ws.name}` : ws.name;
3091
+ console.error(`(${where}: ${describeError(res)})`);
3092
+ continue;
3093
+ }
3094
+ for (const row of res.data?.data ?? [])
3095
+ rows.push(tagRow(ws, row, withAccount));
3096
+ }
3097
+ return rows;
3098
+ }
2235
3099
  function registerReports(program2) {
2236
3100
  const root = program2.command("reports").description("KPIs and exports");
2237
- 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) => {
3101
+ root.command("summary").description("Workspace KPI summary").option("--period <p>", "7d | 30d | 90d | 1y", "30d").option(
3102
+ "--workspace <id>",
3103
+ "read only this workspace (default: all you can access)"
3104
+ ).option("--json", "raw JSON output").action(async (opts) => {
2238
3105
  configureClient(opts.workspace);
2239
3106
  const body = unwrap(
2240
3107
  await getReportsSummary({ query: { period: opts.period } })
2241
3108
  );
2242
- print(body.data, { json: opts.json });
3109
+ printExport(body.data, opts);
2243
3110
  });
2244
3111
  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(
2245
3112
  "--match <status>",
2246
3113
  "OK | MISSING_INVOICE | MISSING_CUFE | AMOUNT_MISMATCH | MISSING_PAYMENT"
2247
- ).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) => {
2248
- configureClient(opts.workspace);
2249
- const body = unwrap(
2250
- await getReportsReconciliation({
3114
+ ).option("--provider <p>", "filter by payment provider").option("--page <n>", "page number").option("--page-size <n>", "rows per page").option(
3115
+ "--workspace <id>",
3116
+ "read only this workspace (default: all you can access)"
3117
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3118
+ const rows = await reportRows(
3119
+ opts.workspace,
3120
+ () => getReportsReconciliation({
2251
3121
  query: {
2252
3122
  date_from: opts.from,
2253
3123
  date_to: opts.to,
@@ -2258,35 +3128,44 @@ function registerReports(program2) {
2258
3128
  }
2259
3129
  })
2260
3130
  );
2261
- print(body.data, { json: opts.json });
3131
+ printExport(rows, opts);
2262
3132
  });
2263
3133
  root.command("financials").description(
2264
3134
  "Per-function P&L: gross, platform fee, facial, payment fee, 4x1000, net to settle"
2265
- ).option("--event <id>", "filter by event").option("--past", "only functions that already happened (settleable)").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2266
- configureClient(opts.workspace);
2267
- const body = unwrap(
2268
- await getReportsFinancials({
3135
+ ).option("--event <id>", "filter by event").option("--past", "only functions that already happened (settleable)").option(
3136
+ "--workspace <id>",
3137
+ "read only this workspace (default: all you can access)"
3138
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3139
+ const rows = await reportRows(
3140
+ opts.workspace,
3141
+ () => getReportsFinancials({
2269
3142
  query: {
2270
3143
  event: opts.event,
2271
3144
  past: opts.past === void 0 ? void 0 : opts.past ? "true" : "false"
2272
3145
  }
2273
3146
  })
2274
3147
  );
2275
- printExport(body.data, opts);
2276
- });
2277
- 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) => {
2278
- configureClient(opts.workspace);
2279
- const body = unwrap(
2280
- await getReportsByEvent({
3148
+ printExport(rows, opts);
3149
+ });
3150
+ 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(
3151
+ "--workspace <id>",
3152
+ "read only this workspace (default: all you can access)"
3153
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3154
+ const rows = await reportRows(
3155
+ opts.workspace,
3156
+ () => getReportsByEvent({
2281
3157
  query: { from: opts.from, to: opts.to, status: opts.status }
2282
3158
  })
2283
3159
  );
2284
- print(body.data, { json: opts.json });
2285
- });
2286
- 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) => {
2287
- configureClient(opts.workspace);
2288
- const body = unwrap(
2289
- await getReportsTimeseries({
3160
+ printExport(rows, opts);
3161
+ });
3162
+ 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(
3163
+ "--workspace <id>",
3164
+ "read only this workspace (default: all you can access)"
3165
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3166
+ const rows = await reportRows(
3167
+ opts.workspace,
3168
+ () => getReportsTimeseries({
2290
3169
  query: {
2291
3170
  interval: opts.interval,
2292
3171
  from: opts.from,
@@ -2295,15 +3174,18 @@ function registerReports(program2) {
2295
3174
  }
2296
3175
  })
2297
3176
  );
2298
- print(body.data, { json: opts.json });
2299
- });
2300
- 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) => {
2301
- configureClient(opts.workspace);
2302
- const body = unwrap(
2303
- await getReportsInventory({
3177
+ printExport(rows, opts);
3178
+ });
3179
+ 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(
3180
+ "--workspace <id>",
3181
+ "read only this workspace (default: all you can access)"
3182
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3183
+ const rows = await reportRows(
3184
+ opts.workspace,
3185
+ () => getReportsInventory({
2304
3186
  query: {
2305
- eventId: opts.eventId,
2306
- eventDateId: opts.eventDateId,
3187
+ eventId: opts.event ?? opts.eventId,
3188
+ eventDateId: opts.eventDate ?? opts.eventDateId,
2307
3189
  from: opts.from,
2308
3190
  to: opts.to,
2309
3191
  includeDrafts: opts.includeDrafts,
@@ -2311,12 +3193,15 @@ function registerReports(program2) {
2311
3193
  }
2312
3194
  })
2313
3195
  );
2314
- print(body.data, { json: opts.json });
3196
+ printExport(rows, opts);
2315
3197
  });
2316
3198
  const exp = root.command("export").description(
2317
3199
  "Export buyers, attendees, subscribers or reconciliation (CSV)"
2318
3200
  );
2319
- 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").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3201
+ 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(
3202
+ "--workspace <id>",
3203
+ "read only this workspace (default: all you can access)"
3204
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2320
3205
  configureClient(opts.workspace);
2321
3206
  const body = unwrap(
2322
3207
  await getReportsExportsReconciliation({
@@ -2333,8 +3218,13 @@ function registerReports(program2) {
2333
3218
  for (const [name, fn, label] of [
2334
3219
  ["buyers", getReportsExportsBuyers, "buyers (one row per sale)"],
2335
3220
  ["attendees", getReportsExportsAttendees, "attendees (one row per ticket)"]
3221
+ // The two responses differ in row shape since the contract typed them
3222
+ // (1.19); printExport only needs rows, so they share one signature here.
2336
3223
  ]) {
2337
- 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").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3224
+ 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(
3225
+ "--workspace <id>",
3226
+ "read only this workspace (default: all you can access)"
3227
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2338
3228
  configureClient(opts.workspace);
2339
3229
  const body = unwrap(
2340
3230
  await fn({
@@ -2350,7 +3240,10 @@ function registerReports(program2) {
2350
3240
  printExport(body.data ?? body, opts);
2351
3241
  });
2352
3242
  }
2353
- exp.command("subscribers").description("Export subscribers").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
3243
+ exp.command("subscribers").description("Export subscribers").option(
3244
+ "--workspace <id>",
3245
+ "read only this workspace (default: all you can access)"
3246
+ ).option("--json", "raw JSON output").option("--csv", "CSV output (for spreadsheets/accounting)").action(async (opts) => {
2354
3247
  configureClient(opts.workspace);
2355
3248
  const body = unwrap(await getReportsExportsSubscribers({}));
2356
3249
  printExport(body.data ?? body, opts);
@@ -2371,19 +3264,21 @@ function printExport(rows, opts) {
2371
3264
  }
2372
3265
 
2373
3266
  // src/commands/resource.ts
2374
- function activeWorkspace(flag) {
2375
- return flag ?? loadConfig().workspaceId;
2376
- }
3267
+ import chalk7 from "chalk";
2377
3268
  function registerResource(program2, spec) {
2378
3269
  const root = program2.command(spec.name).description(spec.describe);
2379
3270
  const singular = spec.name.replace(/s$/, "");
2380
3271
  if (spec.list) {
2381
3272
  const list = spec.list;
2382
- 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)");
3273
+ const cmd = root.command("list").description(
3274
+ `List ${spec.name} from every workspace you can reach (--workspace narrows it to one)`
3275
+ ).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(
3276
+ "--workspace <id>",
3277
+ "read only this workspace (default: all you can access)"
3278
+ ).option("--csv", "CSV output (for spreadsheets/accounting)").option("--json", "raw JSON output (data only)").option("--raw", "raw JSON output including pagination metadata (page)");
2383
3279
  for (const f of spec.listFlags ?? []) cmd.option(f.flag, f.describe);
2384
3280
  cmd.action(async (opts) => {
2385
- configureClient(opts.workspace);
2386
- const columns = resolveColumns(opts, spec.columns);
3281
+ let columns = resolveColumns(opts, spec.columns);
2387
3282
  const query = {
2388
3283
  limit: Number(opts.limit),
2389
3284
  cursor: opts.cursor
@@ -2392,6 +3287,68 @@ function registerResource(program2, spec) {
2392
3287
  const v = opts[camel2(f.query)];
2393
3288
  if (v !== void 0) query[f.query] = v;
2394
3289
  }
3290
+ const targets = await listTargets(opts.workspace);
3291
+ if (targets) {
3292
+ if (opts.cursor)
3293
+ fail(
3294
+ "--cursor needs a single workspace: a cursor from one workspace means nothing in another.",
3295
+ "Pin one with --workspace <id> (or `ft workspace use <slug>`), then paginate."
3296
+ );
3297
+ const limit = opts.all ? Number(opts.limit) : splitLimit(Number(opts.limit), targets.length);
3298
+ const withAccount = spansAccounts(targets);
3299
+ const rows = [];
3300
+ for (const ws of targets) {
3301
+ configureClient(ws.id, ws.account);
3302
+ let cursor;
3303
+ let page;
3304
+ do {
3305
+ const res = await list({ query: { ...query, limit, cursor } });
3306
+ if (res.error !== void 0) {
3307
+ console.error(
3308
+ chalk7.dim(
3309
+ `(${withAccount ? `${ws.account.name} / ` : ""}${ws.name}: ${describeError(res)})`
3310
+ )
3311
+ );
3312
+ break;
3313
+ }
3314
+ const body2 = res.data;
3315
+ for (const row of body2?.data ?? [])
3316
+ rows.push(tagRow(ws, row, withAccount));
3317
+ page = body2?.page;
3318
+ cursor = page?.nextCursor ?? void 0;
3319
+ } while (opts.all && page?.hasMore && cursor);
3320
+ }
3321
+ const max = Number(opts.limit);
3322
+ const out = !opts.all && Number.isFinite(max) && max > 0 ? rows.slice(0, max) : rows;
3323
+ if (columns && !columns.includes("workspaceName"))
3324
+ columns = ["workspaceName", ...columns];
3325
+ if (columns && withAccount && !columns.includes("account"))
3326
+ columns = ["account", ...columns];
3327
+ if (opts.raw) {
3328
+ print(
3329
+ { data: out, page: { nextCursor: null, hasMore: false } },
3330
+ { json: true }
3331
+ );
3332
+ return;
3333
+ }
3334
+ if (opts.csv) {
3335
+ process.stdout.write(`${toCsv(out, columns)}
3336
+ `);
3337
+ return;
3338
+ }
3339
+ print(out, {
3340
+ json: opts.json,
3341
+ columns,
3342
+ columnsExplicit: Boolean(opts.columns)
3343
+ });
3344
+ if (out.length === 0)
3345
+ console.error(
3346
+ chalk7.dim(
3347
+ `(0 results across ${targets.length} workspaces - check them with \`ft workspace list\`)`
3348
+ )
3349
+ );
3350
+ return;
3351
+ }
2395
3352
  if (opts.all) {
2396
3353
  const rows = [];
2397
3354
  let cursor;
@@ -2419,7 +3376,7 @@ function registerResource(program2, spec) {
2419
3376
  columns,
2420
3377
  columnsExplicit: Boolean(opts.columns)
2421
3378
  });
2422
- if (rows.length === 0) printEmptyScope(activeWorkspace(opts.workspace));
3379
+ if (rows.length === 0) printEmptyScope(opts.workspace);
2423
3380
  return;
2424
3381
  }
2425
3382
  const body = unwrap(await list({ query }));
@@ -2437,14 +3394,16 @@ function registerResource(program2, spec) {
2437
3394
  columns,
2438
3395
  columnsExplicit: Boolean(opts.columns)
2439
3396
  });
2440
- if ((body.data ?? []).length === 0)
2441
- printEmptyScope(activeWorkspace(opts.workspace));
3397
+ if ((body.data ?? []).length === 0) printEmptyScope(opts.workspace);
2442
3398
  if (!opts.json) printNextCursor(body.page);
2443
3399
  });
2444
3400
  }
2445
3401
  if (spec.get) {
2446
3402
  const get = spec.get;
2447
- root.command("get <id>").description(`Get one ${singular} by id`).option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (id, opts) => {
3403
+ root.command("get <id>").description(`Get one ${singular} by id`).option(
3404
+ "--workspace <id>",
3405
+ "read only this workspace (default: all you can access)"
3406
+ ).option("--json", "raw JSON output").action(async (id, opts) => {
2448
3407
  configureClient(opts.workspace);
2449
3408
  const body = unwrap(await get({ path: { id } }));
2450
3409
  print(body.data, { json: opts.json });
@@ -2452,25 +3411,34 @@ function registerResource(program2, spec) {
2452
3411
  }
2453
3412
  if (spec.create) {
2454
3413
  const create = spec.create;
2455
- 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) => {
3414
+ root.command("create").description(`Create a ${singular}`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option(
3415
+ "--workspace <id>",
3416
+ "read only this workspace (default: all you can access)"
3417
+ ).option("--json", "raw JSON output").action(async (opts) => {
2456
3418
  configureClient(opts.workspace);
2457
3419
  const body = unwrap(await create({ body: parseData(opts.data) }));
2458
3420
  print(body.data ?? body, { json: opts.json });
2459
3421
  });
2460
3422
  }
2461
3423
  if (spec.update) {
2462
- const update = spec.update;
2463
- 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) => {
3424
+ const update2 = spec.update;
3425
+ root.command("update <id>").description(`Update a ${singular} by id`).requiredOption("--data <json>", "JSON body (inline or @file.json)").option(
3426
+ "--workspace <id>",
3427
+ "read only this workspace (default: all you can access)"
3428
+ ).option("--json", "raw JSON output").action(async (id, opts) => {
2464
3429
  configureClient(opts.workspace);
2465
3430
  const body = unwrap(
2466
- await update({ path: { id }, body: parseData(opts.data) })
3431
+ await update2({ path: { id }, body: parseData(opts.data) })
2467
3432
  );
2468
3433
  print(body.data ?? body, { json: opts.json });
2469
3434
  });
2470
3435
  }
2471
3436
  if (spec.del) {
2472
3437
  const del = spec.del;
2473
- 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) => {
3438
+ root.command("delete <id>").description(`Delete a ${singular} by id`).option("--yes", "skip confirmation").option(
3439
+ "--workspace <id>",
3440
+ "read only this workspace (default: all you can access)"
3441
+ ).option("--json", "raw JSON output").action(async (id, opts) => {
2474
3442
  await confirmOrExit(`Delete ${singular} ${id}?`, opts.yes);
2475
3443
  configureClient(opts.workspace);
2476
3444
  const body = unwrap(await del({ path: { id } }));
@@ -2478,11 +3446,17 @@ function registerResource(program2, spec) {
2478
3446
  });
2479
3447
  }
2480
3448
  for (const action of spec.actions ?? []) {
2481
- const cmd = root.command(`${action.name} <id>`).description(action.describe).option("--workspace <id>", "workspace override").option("--json", "raw JSON output");
3449
+ const cmd = root.command(`${action.name} <id>`).description(action.describe).option(
3450
+ "--workspace <id>",
3451
+ "read only this workspace (default: all you can access)"
3452
+ ).option("--json", "raw JSON output");
2482
3453
  if (action.body) {
2483
3454
  cmd.option("--data <json>", "JSON body (inline or @file.json)");
2484
3455
  }
3456
+ if (action.confirm) cmd.option("--yes", "skip confirmation");
2485
3457
  cmd.action(async (id, opts) => {
3458
+ if (action.confirm)
3459
+ await confirmOrExit(`${action.name} ${singular} ${id}?`, opts.yes);
2486
3460
  configureClient(opts.workspace);
2487
3461
  const payload = { path: { id } };
2488
3462
  if (action.body && opts.data) payload.body = parseData(opts.data);
@@ -2498,7 +3472,9 @@ function camel2(s) {
2498
3472
 
2499
3473
  // src/commands/tickets.ts
2500
3474
  function registerTickets(program2) {
2501
- const root = program2.command("tickets").description("Individual tickets: door check-in, access status, QR resend");
3475
+ const root = program2.command("tickets").description(
3476
+ "Individual tickets: door check-in, access status, QR resend, reassign"
3477
+ );
2502
3478
  root.command("access <code>").description("Read a ticket's access status without admitting it").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (code, opts) => {
2503
3479
  configureClient(opts.workspace);
2504
3480
  const body = unwrap(
@@ -2511,7 +3487,12 @@ function registerTickets(program2) {
2511
3487
  ).option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (code, opts) => {
2512
3488
  configureClient(opts.workspace);
2513
3489
  const body = unwrap(
2514
- await postTicketsTicketCodeCheckin({ path: { ticketCode: code } })
3490
+ // The contract marks the body required since 1.19 (optional `source`
3491
+ // of the scanned QR); the backend accepts it empty.
3492
+ await postTicketsTicketCodeCheckin({
3493
+ path: { ticketCode: code },
3494
+ body: {}
3495
+ })
2515
3496
  );
2516
3497
  print(body.data ?? body, { json: opts.json });
2517
3498
  });
@@ -2522,150 +3503,153 @@ function registerTickets(program2) {
2522
3503
  );
2523
3504
  print(body.data ?? body, { json: opts.json });
2524
3505
  });
3506
+ root.command("reassign <code>").description(
3507
+ `Move a sold ticket to another date/type (--data '{"eventDateId":"\u2026"}' and/or "ticketTypeId", "seatLabel")`
3508
+ ).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (code, opts) => {
3509
+ configureClient(opts.workspace);
3510
+ const body = unwrap(
3511
+ await patchTicketsTicketCode({
3512
+ path: { ticketCode: code },
3513
+ body: parseData(opts.data)
3514
+ })
3515
+ );
3516
+ print(body.data ?? body, { json: opts.json });
3517
+ });
2525
3518
  }
2526
3519
 
2527
3520
  // src/commands/workspace.ts
2528
- import chalk5 from "chalk";
3521
+ import chalk8 from "chalk";
2529
3522
  function registerWorkspace(program2) {
2530
- const root = program2.command("workspace").description("List, switch, and show the active workspace");
2531
- root.command("list").alias("ls").description("List the workspaces you can access (marks the active one)").option("--json", "raw JSON output").action(async (opts) => {
2532
- configureClient();
2533
- const me = unwrap(await getMe({})).data;
2534
- const activeId = loadConfig().workspaceId ?? me.activeWorkspaceId;
2535
- const rows = me.workspaces.map((w) => ({
2536
- active: w.id === activeId ? "*" : "",
2537
- id: w.id,
2538
- name: w.name,
2539
- slug: w.slug,
2540
- role: w.role,
2541
- access: w.sections === null ? "full" : w.sections.length === 0 ? "revoked" : w.sections.join("|")
2542
- }));
3523
+ const root = program2.command("workspace").description("List, pin, unpin, show, and create workspaces");
3524
+ root.command("list").alias("ls").description(
3525
+ "List the workspaces you can access, across every account in scope (marks the pinned one)"
3526
+ ).option("--account <name>", "only this account (default: all stored)").option("--json", "raw JSON output").action(async (opts) => {
3527
+ const accounts = accountsInScope();
3528
+ if (accounts.length === 0) resolveAccount();
3529
+ const withAccount = accounts.length > 1;
3530
+ const rows = [];
3531
+ const errors = [];
3532
+ let answered = 0;
3533
+ for (const account of accounts) {
3534
+ configureClient(void 0, account);
3535
+ const res = await getMe({});
3536
+ if (!res.data && withAccount) {
3537
+ errors.push(`account ${account.name}: ${describeError(res)}`);
3538
+ continue;
3539
+ }
3540
+ answered++;
3541
+ const me = unwrap(res).data;
3542
+ const activeId = account.workspaceId ?? me.activeWorkspaceId;
3543
+ for (const w of me.workspaces)
3544
+ rows.push({
3545
+ ...withAccount ? { account: account.name } : {},
3546
+ active: w.id === activeId ? "*" : "",
3547
+ id: w.id,
3548
+ name: w.name,
3549
+ slug: w.slug,
3550
+ role: w.role,
3551
+ access: w.sections === null ? "full" : w.sections.length === 0 ? "revoked" : w.sections.join("|")
3552
+ });
3553
+ }
3554
+ failIfNoneAnswered(answered, errors);
2543
3555
  print(rows, {
2544
3556
  json: opts.json,
2545
- columns: ["active", "id", "name", "slug", "role", "access"]
3557
+ columns: [
3558
+ ...withAccount ? ["account"] : [],
3559
+ "active",
3560
+ "id",
3561
+ "name",
3562
+ "slug",
3563
+ "role",
3564
+ "access"
3565
+ ]
2546
3566
  });
2547
3567
  });
2548
3568
  root.command("use <idOrSlug>").description(
2549
- "Set the active workspace (persisted in ~/.freeticket/config.json)"
2550
- ).action(async (idOrSlug) => {
2551
- configureClient();
2552
- const me = unwrap(await getMe({})).data;
2553
- const match = me.workspaces.find(
2554
- (w) => w.id === idOrSlug || w.slug === idOrSlug
2555
- );
2556
- if (!match) {
2557
- fail(
2558
- `No workspace matches "${idOrSlug}".`,
2559
- `Available: ${me.workspaces.map((w) => w.slug).join(", ") || "(none)"}`
3569
+ "Pin every command to one workspace, and to the account that reaches it (persisted in ~/.freeticket/config.json)"
3570
+ ).option("--account <name>", "only look in this account").action(async (idOrSlug) => {
3571
+ const accounts = accountsInScope();
3572
+ if (accounts.length === 0) resolveAccount();
3573
+ const slugs = [];
3574
+ for (const account of accounts) {
3575
+ configureClient(void 0, account);
3576
+ const res = await getMe({});
3577
+ if (!res.data && accounts.length > 1) continue;
3578
+ const me = unwrap(res).data;
3579
+ const match = me.workspaces.find(
3580
+ (w) => w.id === idOrSlug || w.slug === idOrSlug
2560
3581
  );
3582
+ slugs.push(...me.workspaces.map((w) => w.slug));
3583
+ if (!match) continue;
3584
+ const stored = readConfig().accounts?.[account.name];
3585
+ if (stored)
3586
+ saveAccount(account.name, { ...stored, workspaceId: match.id });
3587
+ if (account.name !== ENV_ACCOUNT && Object.keys(readConfig().accounts ?? {}).length > 1)
3588
+ saveConfig({ activeAccount: account.name });
3589
+ console.log(
3590
+ `${chalk8.green("\u2713")} Active workspace: ${chalk8.bold(match.name)} ${chalk8.dim(`(${match.slug})`)}` + (accounts.length > 1 ? ` ${chalk8.dim(`via ${account.name}`)}` : "")
3591
+ );
3592
+ return;
3593
+ }
3594
+ fail(
3595
+ `No workspace matches "${idOrSlug}".`,
3596
+ `Available: ${slugs.join(", ") || "(none)"}`
3597
+ );
3598
+ });
3599
+ root.command("clear").description(
3600
+ "Unpin: go back to reading every workspace (and every account) you can access"
3601
+ ).option("--account <name>", "only unpin this account's workspace").action((opts) => {
3602
+ const file = readConfig();
3603
+ const names = opts.account ? [opts.account] : Object.keys(file.accounts ?? {});
3604
+ for (const name of names) {
3605
+ const stored = file.accounts?.[name];
3606
+ if (!stored) fail(`No account named "${name}".`);
3607
+ saveAccount(name, { ...stored, workspaceId: void 0 });
2561
3608
  }
2562
- saveConfig({ workspaceId: match.id });
3609
+ if (!opts.account)
3610
+ saveConfig({ activeAccount: void 0, workspaceId: void 0 });
2563
3611
  console.log(
2564
- `${chalk5.green("\u2713")} Active workspace: ${chalk5.bold(match.name)} ${chalk5.dim(`(${match.slug})`)}`
3612
+ `${chalk8.green("\u2713")} No workspace pinned: lists now read all of them.`
2565
3613
  );
2566
3614
  });
2567
- root.command("show").description("Show the active workspace").option("--json", "raw JSON output").action(async (opts) => {
2568
- configureClient();
2569
- const cfg = loadConfig();
3615
+ root.command("show").description("Show the active workspace").option(
3616
+ "--account <name>",
3617
+ "the account to ask (needed when several are stored)"
3618
+ ).option("--json", "raw JSON output").action(async (opts) => {
3619
+ const account = resolveAccount();
3620
+ configureClient(void 0, account);
2570
3621
  const me = unwrap(await getMe({})).data;
2571
- const activeId = cfg.workspaceId ?? me.activeWorkspaceId;
3622
+ const activeId = account.workspaceId ?? me.activeWorkspaceId;
2572
3623
  const active = me.workspaces.find((w) => w.id === activeId);
2573
3624
  if (!active) {
2574
3625
  fail(
2575
- "No active workspace set.",
2576
- "Pick one with `ft workspace use <slug>`."
3626
+ "No workspace pinned and the account has no default one.",
3627
+ "Pick one with `ft workspace use <slug>`, or list them with `ft workspace list`."
2577
3628
  );
2578
3629
  }
2579
3630
  print(active, { json: opts.json });
2580
3631
  });
2581
- }
2582
-
2583
- // src/lib/banner.ts
2584
- import { Chalk } from "chalk";
2585
- var YELLOW = "#FFD500";
2586
- var c = new Chalk({ level: 3 });
2587
- var ART = String.raw`
2588
- ___ ___ ___ ___ _____ ___ ___ _ _____ _____
2589
- | __| _ \ __| __|_ _|_ _/ __| |/ / __|_ _|
2590
- | _|| / _|| _| | | | | (__| ' <| _| | |
2591
- |_| |_|_\___|___| |_| |___\___|_|\_\___| |_|
2592
- `;
2593
- function banner() {
2594
- return [
2595
- c.hex(YELLOW)(ART),
2596
- c.hex(YELLOW)(" \u25CF ") + c.hex(YELLOW).bold("FreeTicket") + c.hex(YELLOW)(" \u2014 events, tickets, and sales from your terminal"),
2597
- ""
2598
- ].join("\n");
2599
- }
2600
-
2601
- // src/lib/update-check.ts
2602
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2603
- import { homedir as homedir2 } from "os";
2604
- import { dirname as dirname2, join as join2 } from "path";
2605
- import chalk6 from "chalk";
2606
- var CACHE_PATH = join2(homedir2(), ".freeticket", "update-check.json");
2607
- var REGISTRY = "https://registry.npmjs.org/@freeticket/cli/latest";
2608
- var ONE_DAY = 24 * 60 * 60 * 1e3;
2609
- var FETCH_TIMEOUT = 1500;
2610
- async function notifyUpdate(current) {
2611
- if (!process.stderr.isTTY || process.env.FT_NO_UPDATE_CHECK || process.env.CI) {
2612
- return;
2613
- }
2614
- try {
2615
- const latest = await getLatest();
2616
- if (latest && isNewer(latest, current)) {
2617
- process.stderr.write(
2618
- `
2619
- ${chalk6.yellow(`\u26A0 Update available: @freeticket/cli ${current} \u2192 ${latest}`)}
2620
- ${chalk6.dim(" npm i -g @freeticket/cli@latest \xB7 or use npx @freeticket/cli@latest")}
2621
-
2622
- `
2623
- );
2624
- }
2625
- } catch {
2626
- }
2627
- }
2628
- async function getLatest() {
2629
- const cached = readCache();
2630
- if (cached && Date.now() - cached.at < ONE_DAY) return cached.latest;
2631
- const res = await fetch(REGISTRY, {
2632
- signal: AbortSignal.timeout(FETCH_TIMEOUT),
2633
- headers: { Accept: "application/vnd.npm.install-v1+json" }
3632
+ root.command("create").description("Create your own workspace (you become its ADMIN)").requiredOption("--name <name>", "workspace name").requiredOption("--slug <slug>", "URL slug (lowercase, digits, dashes)").option(
3633
+ "--account <name>",
3634
+ "the account to create it with (needed when several are stored)"
3635
+ ).option("--json", "raw JSON output").action(async (opts) => {
3636
+ const account = resolveAccount();
3637
+ configureClient(void 0, account);
3638
+ const body = unwrap(
3639
+ await postWorkspaces({ body: { name: opts.name, slug: opts.slug } })
3640
+ );
3641
+ console.error(
3642
+ `${chalk8.green("\u2713")} Workspace ${chalk8.bold(opts.name)} created. ${chalk8.dim(`Pin it with \`ft workspace use ${opts.slug}\`.`)}`
3643
+ );
3644
+ print(body?.data ?? body, { json: opts.json });
2634
3645
  });
2635
- if (!res.ok) throw new Error(`registry ${res.status}`);
2636
- const latest = (await res.json()).version ?? null;
2637
- if (latest) writeCache({ at: Date.now(), latest });
2638
- return latest;
2639
- }
2640
- function readCache() {
2641
- if (!existsSync2(CACHE_PATH)) return null;
2642
- try {
2643
- return JSON.parse(readFileSync3(CACHE_PATH, "utf8"));
2644
- } catch {
2645
- return null;
2646
- }
2647
- }
2648
- function writeCache(v) {
2649
- try {
2650
- mkdirSync2(dirname2(CACHE_PATH), { recursive: true });
2651
- writeFileSync2(CACHE_PATH, JSON.stringify(v));
2652
- } catch {
2653
- }
2654
- }
2655
- function isNewer(a, b) {
2656
- const parse = (v) => {
2657
- const [maj, min, pat] = (v.replace(/^v/, "").split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0);
2658
- return [maj ?? 0, min ?? 0, pat ?? 0];
2659
- };
2660
- const [aM, aN, aP] = parse(a);
2661
- const [bM, bN, bP] = parse(b);
2662
- return aM > bM || aM === bM && (aN > bN || aN === bN && aP > bP);
2663
3646
  }
2664
3647
 
2665
- // src/index.ts
3648
+ // src/program.ts
2666
3649
  var program = new Command();
2667
3650
  program.name("ft").description("Official FreeTicket CLI").version(package_default.version, "-v, --version").addHelpText("beforeAll", banner());
2668
3651
  registerAuth(program);
3652
+ registerAccount(program);
2669
3653
  registerWorkspace(program);
2670
3654
  registerResource(program, {
2671
3655
  name: "events",
@@ -2676,7 +3660,16 @@ registerResource(program, {
2676
3660
  update: patchEventsId,
2677
3661
  del: deleteEventsId,
2678
3662
  actions: [
2679
- { name: "publish", describe: "Publish an event", fn: postEventsIdPublish }
3663
+ { name: "publish", describe: "Publish an event", fn: postEventsIdPublish },
3664
+ {
3665
+ // Unlike delete, cancel keeps the event, its sales and tickets (every
3666
+ // date goes CANCELLED, the waiting room turns off). It refunds nothing:
3667
+ // that is `ft sales refund`. Idempotent on the backend, but still asks.
3668
+ name: "cancel",
3669
+ describe: "Cancel an event and all its dates (keeps sales/tickets; no refunds)",
3670
+ fn: postEventsIdCancel,
3671
+ confirm: true
3672
+ }
2680
3673
  ],
2681
3674
  // startsAt lives on EventDate, not Event — use createdAt for a temporal column.
2682
3675
  columns: ["id", "name", "status", "createdAt"],
@@ -2698,6 +3691,7 @@ registerResource(program, {
2698
3691
  name: "settlements",
2699
3692
  describe: "Settlements paid to the organizer",
2700
3693
  list: getSettlements,
3694
+ get: getSettlementsId,
2701
3695
  columns: ["id", "reference", "status", "amount", "currency", "createdAt"],
2702
3696
  listFlags: [
2703
3697
  { flag: "--event <id>", describe: "filter by event", query: "event" },
@@ -2736,7 +3730,10 @@ registerResource(program, {
2736
3730
  },
2737
3731
  {
2738
3732
  name: "refund",
2739
- describe: "Refund a sale (--data for partial amount)",
3733
+ // The contract's SaleRefundRequest only takes `acknowledge_manual` and is
3734
+ // additionalProperties:false, so there is no partial-amount field to pass.
3735
+ // The old text promised one and earned a guaranteed 422 (issue #42).
3736
+ describe: `Refund a sale (--data '{"acknowledge_manual":true}' for a manual/offline refund)`,
2740
3737
  fn: postSalesIdRefund,
2741
3738
  body: true
2742
3739
  },
@@ -2744,6 +3741,13 @@ registerResource(program, {
2744
3741
  name: "tickets",
2745
3742
  describe: "List the individual tickets/attendees of a sale",
2746
3743
  fn: getSalesIdTickets
3744
+ },
3745
+ {
3746
+ // Answers "why didn't this sale go through?": one row per gateway
3747
+ // movement (approved, declined, refunded), newest first (contract 1.19).
3748
+ name: "attempts",
3749
+ describe: "Payment attempt history of a sale (declines, approvals, refunds)",
3750
+ fn: getSalesIdAttempts
2747
3751
  }
2748
3752
  ],
2749
3753
  columns: ["id", "reference", "status", "total", "currency", "createdAt"],
@@ -2834,6 +3838,8 @@ registerResource(program, {
2834
3838
  describe: "Webhook endpoints (HMAC-signed event delivery)",
2835
3839
  list: getWebhooks,
2836
3840
  create: postWebhooks,
3841
+ // PATCH keeps the signingSecret; delete + create would rotate it.
3842
+ update: patchWebhooksId,
2837
3843
  del: deleteWebhooksId,
2838
3844
  columns: ["id", "url", "events", "active", "createdAt"]
2839
3845
  });
@@ -2862,7 +3868,11 @@ registerResource(program, {
2862
3868
  name: "staff",
2863
3869
  describe: "Workspace staff",
2864
3870
  list: getStaff,
3871
+ get: getStaffId,
2865
3872
  create: postStaff,
3873
+ // Revokes access to THIS workspace only; the account and its other
3874
+ // workspaces stay. An ADMIN cannot revoke another admin (403) or itself (409).
3875
+ del: deleteStaffId,
2866
3876
  actions: [
2867
3877
  {
2868
3878
  name: "set-role",
@@ -2880,16 +3890,71 @@ registerResource(program, {
2880
3890
  }
2881
3891
  ]
2882
3892
  });
3893
+ registerResource(program, {
3894
+ name: "content-videos",
3895
+ describe: "Organization videos",
3896
+ list: getContentVideos,
3897
+ columns: ["id", "title", "publishedAt", "memberOnly"]
3898
+ });
3899
+ registerResource(program, {
3900
+ name: "content-posts",
3901
+ describe: "Organization posts",
3902
+ list: getContentPosts,
3903
+ // type=ARTICLE needs title + body (Markdown); TEXT/IMAGE need content or
3904
+ // imageUrl. Minimum role ADMIN (contract 1.19).
3905
+ create: postContentPosts,
3906
+ columns: ["id", "title", "publishedAt", "memberOnly"]
3907
+ });
3908
+ registerResource(program, {
3909
+ name: "content-lives",
3910
+ describe: "Organization live streams",
3911
+ list: getContentLives,
3912
+ get: getContentLivesId,
3913
+ columns: ["id", "title", "status", "startsAt", "memberOnly"],
3914
+ extend: (root) => {
3915
+ root.command("playback-token").description(
3916
+ "Mint a signed playback token (30 min live / 1 h video). `memberOnly` content needs a buyer session."
3917
+ ).requiredOption("--data <json>", "JSON body (inline or @file.json)").option("--workspace <id>", "workspace override").option("--json", "raw JSON output").action(async (opts) => {
3918
+ configureClient(opts.workspace);
3919
+ const body = unwrap(
3920
+ await postContentPlaybackToken({
3921
+ body: parseData(opts.data)
3922
+ })
3923
+ );
3924
+ print(body?.data ?? body, { json: opts.json });
3925
+ });
3926
+ }
3927
+ });
2883
3928
  registerTickets(program);
2884
3929
  registerReports(program);
2885
3930
  registerApiKeys(program);
2886
3931
  registerAdmin(program);
3932
+ function addAccountOption(cmd) {
3933
+ if (cmd.name() === "admin") return;
3934
+ const longs = cmd.options.map((o) => o.long);
3935
+ if (longs.includes("--workspace") && !longs.includes("--account"))
3936
+ cmd.option(
3937
+ "--account <name>",
3938
+ "use only this stored account (default: all of them; see `ft account list`)"
3939
+ );
3940
+ for (const sub of cmd.commands) addAccountOption(sub);
3941
+ }
3942
+ addAccountOption(program);
3943
+ program.hook("preAction", (_program, action) => {
3944
+ setAccountFlag(action.opts().account);
3945
+ });
3946
+
3947
+ // src/index.ts
2887
3948
  if (process.argv.length <= 2) {
2888
3949
  console.log(banner());
2889
3950
  program.outputHelp();
2890
3951
  process.exit(0);
2891
3952
  }
2892
- program.parseAsync().then(() => notifyUpdate(package_default.version)).catch((err) => {
3953
+ var update = checkForUpdate(package_default.version);
3954
+ program.parseAsync().then(async () => {
3955
+ const notice = await update;
3956
+ if (notice) process.stderr.write(notice);
3957
+ }).catch((err) => {
2893
3958
  console.error(err instanceof Error ? err.message : err);
2894
3959
  process.exit(1);
2895
3960
  });